/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/@azure/communication-calling@1.33.2/dist/sdk.bundle.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Microsoft Software License Terms for the Azure Communications Services, Azure CPaaS, AZURE COMMUNICATION SERVICES VOICE AND VIDEO CALLING CLIENT LIBRARY
// See LICENSE file for license information.
!function(g,f){"object"==typeof exports&&"undefined"!=typeof module?f(exports,require("@azure/logger"),require("@azure/communication-common")):"function"==typeof define&&define.amd?define(["exports","@azure/logger","@azure/communication-common"],f):f((g="undefined"!=typeof globalThis?globalThis:g||self)["azure-communication-calling"]={},g.logger,g.communicationCommon)}(this,(function(g,f,S){"use strict";var v,C="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(g){return g&&g.__esModule&&Object.prototype.hasOwnProperty.call(g,"default")?g.default:g}function createCommonjsModule(g,f,S){return g(S={path:f,exports:{},require:function(g,f){return commonjsRequire(g,null==f?S.path:f)}},S.exports),S.exports}function getAugmentedNamespace(g){if(g.__esModule)return g;var f=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(g).forEach((function(S){var v=Object.getOwnPropertyDescriptor(g,S);Object.defineProperty(f,S,v.get?v:{enumerable:!0,get:function(){return g[S]}})})),f}function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}
/*! *****************************************************************************
	Copyright (C) Microsoft. All rights reserved.
	Licensed under the Apache License, Version 2.0 (the "License"); you may not use
	this file except in compliance with the License. You may obtain a copy of the
	License at http://www.apache.org/licenses/LICENSE-2.0

	THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
	KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
	WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
	MERCHANTABLITY OR NON-INFRINGEMENT.

	See the Apache Version 2.0 License for specific language governing permissions
	and limitations under the License.
	***************************************************************************** */!function(g){!function(f){var S="object"==typeof C?C:"object"==typeof self?self:"object"==typeof this?this:Function("return this;")(),v=makeExporter(g);function makeExporter(g,f){return function(S,v){"function"!=typeof g[S]&&Object.defineProperty(g,S,{configurable:!0,writable:!0,value:v}),f&&f(S,v)}}void 0===S.Reflect?S.Reflect=g:v=makeExporter(S.Reflect,v),f(v)}((function(g){var f=Object.prototype.hasOwnProperty,S="function"==typeof Symbol,v=S&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",C=S&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",_="function"==typeof Object.create,T={__proto__:[]}instanceof Array,I=!_&&!T,b={create:_?function(){return MakeDictionary(Object.create(null))}:T?function(){return MakeDictionary({__proto__:null})}:function(){return MakeDictionary({})},has:I?function(g,S){return f.call(g,S)}:function(g,f){return f in g},get:I?function(g,S){return f.call(g,S)?g[S]:void 0}:function(g,f){return g[f]}},A=Object.getPrototypeOf(Function),P="object"==typeof process&&process.env&&"true"===process.env.REFLECT_METADATA_USE_MAP_POLYFILL,R=P||"function"!=typeof Map||"function"!=typeof Map.prototype.entries?CreateMapPolyfill():Map,M=P||"function"!=typeof Set||"function"!=typeof Set.prototype.entries?CreateSetPolyfill():Set,w=new(P||"function"!=typeof WeakMap?CreateWeakMapPolyfill():WeakMap);function decorate(g,f,S,v){if(IsUndefined(S)){if(!IsArray(g))throw new TypeError;if(!IsConstructor(f))throw new TypeError;return DecorateConstructor(g,f)}if(!IsArray(g))throw new TypeError;if(!IsObject(f))throw new TypeError;if(!IsObject(v)&&!IsUndefined(v)&&!IsNull(v))throw new TypeError;return IsNull(v)&&(v=void 0),DecorateProperty(g,f,S=ToPropertyKey(S),v)}function metadata(g,f){function decorator(S,v){if(!IsObject(S))throw new TypeError;if(!IsUndefined(v)&&!IsPropertyKey(v))throw new TypeError;OrdinaryDefineOwnMetadata(g,f,S,v)}return decorator}function defineMetadata(g,f,S,v){if(!IsObject(S))throw new TypeError;return IsUndefined(v)||(v=ToPropertyKey(v)),OrdinaryDefineOwnMetadata(g,f,S,v)}function hasMetadata(g,f,S){if(!IsObject(f))throw new TypeError;return IsUndefined(S)||(S=ToPropertyKey(S)),OrdinaryHasMetadata(g,f,S)}function hasOwnMetadata(g,f,S){if(!IsObject(f))throw new TypeError;return IsUndefined(S)||(S=ToPropertyKey(S)),OrdinaryHasOwnMetadata(g,f,S)}function getMetadata(g,f,S){if(!IsObject(f))throw new TypeError;return IsUndefined(S)||(S=ToPropertyKey(S)),OrdinaryGetMetadata(g,f,S)}function getOwnMetadata(g,f,S){if(!IsObject(f))throw new TypeError;return IsUndefined(S)||(S=ToPropertyKey(S)),OrdinaryGetOwnMetadata(g,f,S)}function getMetadataKeys(g,f){if(!IsObject(g))throw new TypeError;return IsUndefined(f)||(f=ToPropertyKey(f)),OrdinaryMetadataKeys(g,f)}function getOwnMetadataKeys(g,f){if(!IsObject(g))throw new TypeError;return IsUndefined(f)||(f=ToPropertyKey(f)),OrdinaryOwnMetadataKeys(g,f)}function deleteMetadata(g,f,S){if(!IsObject(f))throw new TypeError;IsUndefined(S)||(S=ToPropertyKey(S));var v=GetOrCreateMetadataMap(f,S,!1);if(IsUndefined(v))return!1;if(!v.delete(g))return!1;if(v.size>0)return!0;var C=w.get(f);return C.delete(S),C.size>0||w.delete(f),!0}function DecorateConstructor(g,f){for(var S=g.length-1;S>=0;--S){var v=(0,g[S])(f);if(!IsUndefined(v)&&!IsNull(v)){if(!IsConstructor(v))throw new TypeError;f=v}}return f}function DecorateProperty(g,f,S,v){for(var C=g.length-1;C>=0;--C){var _=(0,g[C])(f,S,v);if(!IsUndefined(_)&&!IsNull(_)){if(!IsObject(_))throw new TypeError;v=_}}return v}function GetOrCreateMetadataMap(g,f,S){var v=w.get(g);if(IsUndefined(v)){if(!S)return;v=new R,w.set(g,v)}var C=v.get(f);if(IsUndefined(C)){if(!S)return;C=new R,v.set(f,C)}return C}function OrdinaryHasMetadata(g,f,S){if(OrdinaryHasOwnMetadata(g,f,S))return!0;var v=OrdinaryGetPrototypeOf(f);return!IsNull(v)&&OrdinaryHasMetadata(g,v,S)}function OrdinaryHasOwnMetadata(g,f,S){var v=GetOrCreateMetadataMap(f,S,!1);return!IsUndefined(v)&&ToBoolean(v.has(g))}function OrdinaryGetMetadata(g,f,S){if(OrdinaryHasOwnMetadata(g,f,S))return OrdinaryGetOwnMetadata(g,f,S);var v=OrdinaryGetPrototypeOf(f);return IsNull(v)?void 0:OrdinaryGetMetadata(g,v,S)}function OrdinaryGetOwnMetadata(g,f,S){var v=GetOrCreateMetadataMap(f,S,!1);if(!IsUndefined(v))return v.get(g)}function OrdinaryDefineOwnMetadata(g,f,S,v){GetOrCreateMetadataMap(S,v,!0).set(g,f)}function OrdinaryMetadataKeys(g,f){var S=OrdinaryOwnMetadataKeys(g,f),v=OrdinaryGetPrototypeOf(g);if(null===v)return S;var C=OrdinaryMetadataKeys(v,f);if(C.length<=0)return S;if(S.length<=0)return C;for(var _=new M,T=[],I=0,b=S;I<b.length;I++){var A=b[I];_.has(A)||(_.add(A),T.push(A))}for(var P=0,R=C;P<R.length;P++){A=R[P];_.has(A)||(_.add(A),T.push(A))}return T}function OrdinaryOwnMetadataKeys(g,f){var S=[],v=GetOrCreateMetadataMap(g,f,!1);if(IsUndefined(v))return S;for(var C=GetIterator(v.keys()),_=0;;){var T=IteratorStep(C);if(!T)return S.length=_,S;var I=IteratorValue(T);try{S[_]=I}catch(g){try{IteratorClose(C)}finally{throw g}}_++}}function Type(g){if(null===g)return 1;switch(typeof g){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===g?1:6;default:return 6}}function IsUndefined(g){return void 0===g}function IsNull(g){return null===g}function IsSymbol(g){return"symbol"==typeof g}function IsObject(g){return"object"==typeof g?null!==g:"function"==typeof g}function ToPrimitive(g,f){switch(Type(g)){case 0:case 1:case 2:case 3:case 4:case 5:return g}var S=3===f?"string":5===f?"number":"default",C=GetMethod(g,v);if(void 0!==C){var _=C.call(g,S);if(IsObject(_))throw new TypeError;return _}return OrdinaryToPrimitive(g,"default"===S?"number":S)}function OrdinaryToPrimitive(g,f){if("string"===f){var S=g.toString;if(IsCallable(S))if(!IsObject(C=S.call(g)))return C;if(IsCallable(v=g.valueOf))if(!IsObject(C=v.call(g)))return C}else{var v;if(IsCallable(v=g.valueOf))if(!IsObject(C=v.call(g)))return C;var C,_=g.toString;if(IsCallable(_))if(!IsObject(C=_.call(g)))return C}throw new TypeError}function ToBoolean(g){return!!g}function ToString(g){return""+g}function ToPropertyKey(g){var f=ToPrimitive(g,3);return IsSymbol(f)?f:ToString(f)}function IsArray(g){return Array.isArray?Array.isArray(g):g instanceof Object?g instanceof Array:"[object Array]"===Object.prototype.toString.call(g)}function IsCallable(g){return"function"==typeof g}function IsConstructor(g){return"function"==typeof g}function IsPropertyKey(g){switch(Type(g)){case 3:case 4:return!0;default:return!1}}function GetMethod(g,f){var S=g[f];if(null!=S){if(!IsCallable(S))throw new TypeError;return S}}function GetIterator(g){var f=GetMethod(g,C);if(!IsCallable(f))throw new TypeError;var S=f.call(g);if(!IsObject(S))throw new TypeError;return S}function IteratorValue(g){return g.value}function IteratorStep(g){var f=g.next();return!f.done&&f}function IteratorClose(g){var f=g.return;f&&f.call(g)}function OrdinaryGetPrototypeOf(g){var f=Object.getPrototypeOf(g);if("function"!=typeof g||g===A)return f;if(f!==A)return f;var S=g.prototype,v=S&&Object.getPrototypeOf(S);if(null==v||v===Object.prototype)return f;var C=v.constructor;return"function"!=typeof C||C===g?f:C}function CreateMapPolyfill(){var g={},f=[],S=function(){function MapIterator(g,f,S){this._index=0,this._keys=g,this._values=f,this._selector=S}return MapIterator.prototype["@@iterator"]=function(){return this},MapIterator.prototype[C]=function(){return this},MapIterator.prototype.next=function(){var g=this._index;if(g>=0&&g<this._keys.length){var S=this._selector(this._keys[g],this._values[g]);return g+1>=this._keys.length?(this._index=-1,this._keys=f,this._values=f):this._index++,{value:S,done:!1}}return{value:void 0,done:!0}},MapIterator.prototype.throw=function(g){throw this._index>=0&&(this._index=-1,this._keys=f,this._values=f),g},MapIterator.prototype.return=function(g){return this._index>=0&&(this._index=-1,this._keys=f,this._values=f),{value:g,done:!0}},MapIterator}();return function(){function Map(){this._keys=[],this._values=[],this._cacheKey=g,this._cacheIndex=-2}return Object.defineProperty(Map.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Map.prototype.has=function(g){return this._find(g,!1)>=0},Map.prototype.get=function(g){var f=this._find(g,!1);return f>=0?this._values[f]:void 0},Map.prototype.set=function(g,f){var S=this._find(g,!0);return this._values[S]=f,this},Map.prototype.delete=function(f){var S=this._find(f,!1);if(S>=0){for(var v=this._keys.length,C=S+1;C<v;C++)this._keys[C-1]=this._keys[C],this._values[C-1]=this._values[C];return this._keys.length--,this._values.length--,f===this._cacheKey&&(this._cacheKey=g,this._cacheIndex=-2),!0}return!1},Map.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=g,this._cacheIndex=-2},Map.prototype.keys=function(){return new S(this._keys,this._values,getKey)},Map.prototype.values=function(){return new S(this._keys,this._values,getValue)},Map.prototype.entries=function(){return new S(this._keys,this._values,getEntry)},Map.prototype["@@iterator"]=function(){return this.entries()},Map.prototype[C]=function(){return this.entries()},Map.prototype._find=function(g,f){return this._cacheKey!==g&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=g)),this._cacheIndex<0&&f&&(this._cacheIndex=this._keys.length,this._keys.push(g),this._values.push(void 0)),this._cacheIndex},Map}();function getKey(g,f){return g}function getValue(g,f){return f}function getEntry(g,f){return[g,f]}}function CreateSetPolyfill(){return function(){function Set(){this._map=new R}return Object.defineProperty(Set.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),Set.prototype.has=function(g){return this._map.has(g)},Set.prototype.add=function(g){return this._map.set(g,g),this},Set.prototype.delete=function(g){return this._map.delete(g)},Set.prototype.clear=function(){this._map.clear()},Set.prototype.keys=function(){return this._map.keys()},Set.prototype.values=function(){return this._map.values()},Set.prototype.entries=function(){return this._map.entries()},Set.prototype["@@iterator"]=function(){return this.keys()},Set.prototype[C]=function(){return this.keys()},Set}()}function CreateWeakMapPolyfill(){var g=16,S=b.create(),v=CreateUniqueKey();return function(){function WeakMap(){this._key=CreateUniqueKey()}return WeakMap.prototype.has=function(g){var f=GetOrCreateWeakMapTable(g,!1);return void 0!==f&&b.has(f,this._key)},WeakMap.prototype.get=function(g){var f=GetOrCreateWeakMapTable(g,!1);return void 0!==f?b.get(f,this._key):void 0},WeakMap.prototype.set=function(g,f){return GetOrCreateWeakMapTable(g,!0)[this._key]=f,this},WeakMap.prototype.delete=function(g){var f=GetOrCreateWeakMapTable(g,!1);return void 0!==f&&delete f[this._key]},WeakMap.prototype.clear=function(){this._key=CreateUniqueKey()},WeakMap}();function CreateUniqueKey(){var g;do{g="@@WeakMap@@"+CreateUUID()}while(b.has(S,g));return S[g]=!0,g}function GetOrCreateWeakMapTable(g,S){if(!f.call(g,v)){if(!S)return;Object.defineProperty(g,v,{value:b.create()})}return g[v]}function FillRandomBytes(g,f){for(var S=0;S<f;++S)g[S]=255*Math.random()|0;return g}function GenRandomBytes(g){return"function"==typeof Uint8Array?"undefined"!=typeof crypto?crypto.getRandomValues(new Uint8Array(g)):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(new Uint8Array(g)):FillRandomBytes(new Uint8Array(g),g):FillRandomBytes(new Array(g),g)}function CreateUUID(){var f=GenRandomBytes(g);f[6]=79&f[6]|64,f[8]=191&f[8]|128;for(var S="",v=0;v<g;++v){var C=f[v];4!==v&&6!==v&&8!==v||(S+="-"),C<16&&(S+="0"),S+=C.toString(16).toLowerCase()}return S}}function MakeDictionary(g){return g.__=void 0,delete g.__,g}g("decorate",decorate),g("metadata",metadata),g("defineMetadata",defineMetadata),g("hasMetadata",hasMetadata),g("hasOwnMetadata",hasOwnMetadata),g("getMetadata",getMetadata),g("getOwnMetadata",getOwnMetadata),g("getMetadataKeys",getMetadataKeys),g("getOwnMetadataKeys",getOwnMetadataKeys),g("deleteMetadata",deleteMetadata)}))}(v||(v={}));var _=createCommonjsModule((function(g,f){function vsprintf(g,f){var S=0;return g.replace(/%[dixs%]/g,(function(g){var v=0;if("%"!==g[v++])return"";var C=g[v++];return"%"===C?"%":"s"===C||"d"===C||"i"===C?f[S++]:"x"===C?f[S++].toString(16):g}))}function sprintf(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];return vsprintf(g,f)}
/*!
	 *  AufLog.ts
	 *  AUF
	 *
	 *  Created by Johan Blumenberg on 2016-12-29
	 *  Copyright 2016 Microsoft. All rights reserved.
	 *
	 */
Object.defineProperty(f,"__esModule",{value:!0}),function(g){g[g.Trace=10]="Trace",g[g.Debug6=16]="Debug6",g[g.Debug5=18]="Debug5",g[g.Debug4=20]="Debug4",g[g.Debug3=30]="Debug3",g[g.Debug2=40]="Debug2",g[g.Debug1=50]="Debug1",g[g.Warning=60]="Warning",g[g.Error=70]="Error",g[g.Fatal=80]="Fatal",g[g.MetaData=90]="MetaData"}(f.LogLevel||(f.LogLevel={})),function(g){g[g.UseDefault=0]="UseDefault",g[g.Compress=1]="Compress",g[g.Disabled=2]="Disabled"}(f.LogFileCompression||(f.LogFileCompression={})),function(g){g[g.Raw=0]="Raw",g[g.Base64=1]="Base64"}(f.LogFileEncoding||(f.LogFileEncoding={})),function(g){g[g.Unencrypted=0]="Unencrypted",g[g.Encrypted=1]="Encrypted"}(f.LogFileEncryption||(f.LogFileEncryption={})),function(g){g[g.PEM=0]="PEM",g[g.DER=1]="DER",g[g.BER=2]="BER"}(f.CertStoreFormat||(f.CertStoreFormat={})),function(g){g[g.InsertFront=8]="InsertFront"}(f.AppenderFlags||(f.AppenderFlags={})),f.vsprintf=vsprintf,f.sprintf=sprintf})),T=createCommonjsModule((function(g,f){
/*!
	 *  LogFactory.ts
	 *  AUF
	 *
	 *  Created by Johan Blumenberg on 2016-12-29
	 *  Copyright 2016 Microsoft. All rights reserved.
	 *
	 */
var S,v,T=C&&C.__extends||(S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f.hasOwnProperty(S)&&(g[S]=f[S])},function(g,f){function __(){this.constructor=g}S(g,f),g.prototype=null===f?Object.create(f):(__.prototype=f.prototype,new __)});function hash(g){if(null===g)return-1;for(var f=0,S=g.length-1;S>=0;S--)f=37*f+g.charCodeAt(S)|0;var v="__auf_literal:";for(S=v.length-1;S>=0;S--)f=37*f+v.charCodeAt(S)|0;return f}Object.defineProperty(f,"__esModule",{value:!0}),function(g){g[g.Unsafe=0]="Unsafe",g[g.Safe=1]="Safe",g[g.Inherited_Unsafe=2]="Inherited_Unsafe",g[g.Inherited_Safe=3]="Inherited_Safe",g[g.Blacklisted_Unsafe=4]="Blacklisted_Unsafe"}(v||(v={}));var I,b=function(){function LogComponentImpl(g,f){this._level=_.LogLevel.Debug4,this._threshold=255,this._safe=v.Inherited_Unsafe,this._name=g,f&&(this._level=f.level(),this._safe=f.safe()?v.Inherited_Safe:v.Inherited_Unsafe,this._extendedInfo=f.extendedInfo())}return LogComponentImpl.prototype.name=function(){return this._name},LogComponentImpl.prototype.safe=function(){return this._safe===v.Safe||this._safe===v.Inherited_Safe},LogComponentImpl.prototype.safety=function(){return this._safe},LogComponentImpl.prototype.setSafety=function(g){this._safe=g},LogComponentImpl.prototype.description=function(){return this._desc},LogComponentImpl.prototype.setDescription=function(g){this._desc=g},LogComponentImpl.prototype.level=function(){return this._level},LogComponentImpl.prototype.setLevel=function(g){I.setLevel(this,g)},LogComponentImpl.prototype._setLevel=function(g){this._level=g},LogComponentImpl.prototype._setThreshold=function(g){this._threshold=g},LogComponentImpl.prototype.isEnabled=function(g){return this._threshold<=g},LogComponentImpl.prototype.setExtendedInfo=function(g){this._extendedInfo=g},LogComponentImpl.prototype.extendedInfo=function(){return this._extendedInfo},LogComponentImpl.prototype.trace=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Trace,hash(g),g].concat(f))},LogComponentImpl.prototype.debug6=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Debug6,hash(g),g].concat(f))},LogComponentImpl.prototype.debug5=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Debug5,hash(g),g].concat(f))},LogComponentImpl.prototype.debug4=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Debug4,hash(g),g].concat(f))},LogComponentImpl.prototype.debug3=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Debug3,hash(g),g].concat(f))},LogComponentImpl.prototype.debug2=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Debug2,hash(g),g].concat(f))},LogComponentImpl.prototype.debug1=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Debug1,hash(g),g].concat(f))},LogComponentImpl.prototype.warn=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Warning,hash(g),g].concat(f))},LogComponentImpl.prototype.error=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Error,hash(g),g].concat(f))},LogComponentImpl.prototype.fatal=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.Fatal,hash(g),g].concat(f))},LogComponentImpl.prototype.meta=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];I.log.apply(I,[this,_.LogLevel.MetaData,hash(g),g].concat(f))},LogComponentImpl}(),A=function(){function LogFactory(){}return LogFactory.instance=function(){return I},LogFactory.levelToString=function(g){return g<=_.LogLevel.Trace?"TRACE":g<=_.LogLevel.Debug6?"DEBUG6":g<=_.LogLevel.Debug5?"DEBUG5":g<=_.LogLevel.Debug4?"DEBUG4":g<=_.LogLevel.Debug3?"DEBUG3":g<=_.LogLevel.Debug2?"DEBUG2":g<=_.LogLevel.Debug1?"DEBUG1":g<=_.LogLevel.Warning?"WARN":g<=_.LogLevel.Error?"ERROR":g<=_.LogLevel.Fatal?"FATAL":(_.LogLevel.MetaData,"META")},LogFactory.levelFromString=function(g){return this._levelFromString[g]||parseInt(g,10)},LogFactory}();function findLevel(g,f){for(var S=f.name();S.length>0;){if(g[S])return g[S];var v=S.lastIndexOf(".");S=v<0?"":S.substr(0,v)}return g[""]?g[""]:_.LogLevel.Debug4}function findThreshold(g,f){var S=255;return f.forEach((function(f){var v=255;f.appender.levels()?v=Math.min(v,findLevel(f.appender.levels(),g)):f.appender.receiveAll()||(v=Math.min(v,g.level())),S=Math.min(S,v)})),S}function appenderMatches(g,f,S){return!!g.appender.receiveAll()||(g.appender.levels()?S>=findLevel(g.appender.levels(),f):S>=f.level())}A._levelFromString={TRACE:_.LogLevel.Trace,DEBUG6:_.LogLevel.Debug6,DEBUG5:_.LogLevel.Debug5,DEBUG4:_.LogLevel.Debug4,DEBUG3:_.LogLevel.Debug3,DEBUG2:_.LogLevel.Debug2,DEBUG1:_.LogLevel.Debug1,WARN:_.LogLevel.Warning,ERROR:_.LogLevel.Error,FATAL:_.LogLevel.Fatal,META:_.LogLevel.MetaData},f.LogFactory=A;var P=function(g){function LogFactoryImpl(){var f=g.call(this)||this;return f._nextId=0,f._appenders=[],f._components={},f._componentBlacklist=[],f._components[""]=new b("",null),f}return T(LogFactoryImpl,g),LogFactoryImpl.prototype.toHex=function(g){return(4294967296+g).toString(16).substr(-8)},LogFactoryImpl.prototype.addAppender=function(g,f){void 0===f&&(f=0);var S=this._nextId++;return f&_.AppenderFlags.InsertFront?this._appenders.unshift({appender:g,handle:S}):this._appenders.push({appender:g,handle:S}),this.recalcComponentThresholds(),S},LogFactoryImpl.prototype.removeAppender=function(g){for(var f=0;f<this._appenders.length;f++)if(this._appenders[f].handle===g){this._appenders.splice(f,1);break}this.recalcComponentThresholds()},LogFactoryImpl.prototype.log=function(g,f,S,v){for(var C=[],_=4;_<arguments.length;_++)C[_-4]=arguments[_];try{if(g.isEnabled(f)){var T={timestamp:(new Date).getTime(),component:g,level:f};this._appenders.forEach((function(_){appenderMatches(_,g,f)&&_.appender.log(T,S,v,C)}))}}catch(g){}},LogFactoryImpl.prototype.parent=function(g){for(;;){var f=g.lastIndexOf(".");if(g=f>=0?g.substr(0,f):"",this._components[g])return this._components[g]}},LogFactoryImpl.prototype.children=function(g){var f=[];for(var S in this._components)this.parent(S).name()===g&&f.push(this._components[S]);return f},LogFactoryImpl.prototype.component=function(g){if(this._components[g])return this._components[g];var f=new b(g,this.parent(g));this._components[g]=f;var S=findThreshold(f,this._appenders);return f._setThreshold(S),f},LogFactoryImpl.prototype.rootComponent=function(){return this.component("")},LogFactoryImpl.prototype.setSafetyRecursive=function(g,f){var S=this;this.children(g).forEach((function(g){g.safety()!==v.Inherited_Safe&&g.safety()!==v.Inherited_Unsafe||(g.setSafety(f),S.setSafetyRecursive(g.name(),f))}))},LogFactoryImpl.prototype.declareComponentSafe=function(g,f){var S=this.component(g);-1!==this._componentBlacklist.indexOf(S.name())?S.setSafety(v.Blacklisted_Unsafe):S.setSafety(f?v.Safe:v.Unsafe),this.setSafetyRecursive(g,f?v.Inherited_Safe:v.Inherited_Unsafe)},LogFactoryImpl.prototype.declareComponentDescription=function(g,f){this.component(g).setDescription(f)},LogFactoryImpl.prototype.setExtendedInfoRecursive=function(g,f){var S=this;this.children(g).forEach((function(g){void 0===g.extendedInfo()&&(g.setExtendedInfo(f),S.setExtendedInfoRecursive(g.name(),f))}))},LogFactoryImpl.prototype.declareComponentExtendedInfo=function(g,f){var S=this.component(g);S.setExtendedInfo(f),this.setExtendedInfoRecursive(S.name(),f)},LogFactoryImpl.prototype.recalcComponentThresholds=function(){for(var g in this._components){var f=this._components[g],S=findThreshold(f,this._appenders);f._setThreshold(S)}},LogFactoryImpl.prototype.setLevel=function(g,f){if(""===g.name())for(var S in this._components){(_=this._components[S])._setLevel(f);var v=findThreshold(_,this._appenders);_._setThreshold(v)}else{var C=g.name()+".";g._setLevel(f);v=findThreshold(g,this._appenders);for(var S in g._setThreshold(v),this._components){var _;if((_=this._components[S]).name().substr(0,C.length)===C){_._setLevel(f);var T=findThreshold(_,this._appenders);_._setThreshold(T)}}}},LogFactoryImpl.prototype.setComponentBlacklist=function(g){for(var f in this._componentBlacklist=g,this._components){var S=this._components[f];-1!==this._componentBlacklist.indexOf(S.name())&&S.setSafety(v.Blacklisted_Unsafe)}},LogFactoryImpl}(A);I=new P})),I=createCommonjsModule((function(g,f){function fromThenable(g){var f=Defer();return g.then((function(g){f.resolve(g)}),(function(g){f.reject(g)})),f.promise().thenAsync((function(g){return g}))}function isThenable(g){return null!=g&&"function"==typeof g.then}function isCancelable(g){return null!=g&&"function"==typeof g.cancel}function run(g,S){if(!f.config.catchExceptions)return g();try{return g()}catch(g){return S(g)}}Object.defineProperty(f,"__esModule",{value:!0}),f.config={exceptionsToConsole:!0,catchExceptions:!0,traceEnabled:!1,exceptionHandler:void 0,unhandledErrorHandler:function(g){throw g}},f.fromThenable=fromThenable;var S,v=[],C="undefined"!=typeof setImmediate;function asyncCallback(g){v.push(g),1===v.length&&(C?setImmediate(resolveAsyncCallbacks):setTimeout(resolveAsyncCallbacks,0))}function resolveAsyncCallbacks(){var g=v;v=[];for(var f=0;f<g.length;f++)g[f]()}function all(g){if(0===g.length)return Resolved([]);var f,v=Defer(),C=g.length,_=Array(g.length);v.onCancel((function(f){g.forEach((function(g){isCancelable(g)&&S.SyncTask.cancelOtherInternal(g,f)}))}));var checkFinish=function(){0==--C&&(void 0!==f?v.reject(f):v.resolve(_))};return g.forEach((function(g,S){isThenable(g)?g.then((function(g){_[S]=g,checkFinish()}),(function(g){void 0===f&&(f=void 0===g||g),checkFinish()})):(_[S]=g,checkFinish())})),v.promise()}function Defer(){return new S.SyncTask}function Resolved(g){return(new S.SyncTask).resolve(g).promise()}function Rejected(g){return(new S.SyncTask).reject(g).promise()}function race(g){var f=Defer(),v=!1;return f.onCancel((function(f){g.forEach((function(g){isCancelable(g)&&S.SyncTask.cancelOtherInternal(g,f)}))})),g.forEach((function(g){isThenable(g)?g.then((function(g){v||(v=!0,f.resolve(g))}),(function(g){v||(v=!0,f.reject(g))})):v||(v=!0,f.resolve(g))})),f.promise()}function raceTimer(g,f){var S=Defer(),v=setTimeout((function(){S.resolve({timedOut:!0})}),f);return race([g.then((function(g){return clearTimeout(v),{timedOut:!1,result:g}})),S.promise()])}f.asyncCallback=asyncCallback,function(g){var S=function(){function SyncTask(){this._completedSuccess=!1,this._completedFail=!1,this._traceEnabled=!1,this._cancelCallbacks=[],this._wasCanceled=!1,this._wasExplicitlyCanceled=!1,this._resolving=!1,this._storedCallbackSets=[],this._mustHandleError=!0}return SyncTask.prototype._addCallbackSet=function(g,f){var S=this,v=new SyncTask;return v.onCancel((function(f){g.wasCanceled=!0,g.cancelContext=f,S._cancelInternal(f)})),g.task=v,this._storedCallbackSets.push(g),f?this._mustHandleError=!1:v._mustHandleError=!1,this._resolving||(this._completedSuccess?this._resolveSuccesses():this._completedFail&&this._resolveFailures()),v.promise()},SyncTask.prototype.onCancel=function(g){return this._completedSuccess||this._completedFail||(this._wasCanceled?g(this._cancelContext):this._cancelCallbacks.push(g)),this},SyncTask.prototype.then=function(g,f){return this._addCallbackSet({successFunc:g,failFunc:f},!0)},SyncTask.prototype.thenAsync=function(g,f){return this._addCallbackSet({successFunc:g,failFunc:f,asyncCallback:!0},!0)},SyncTask.prototype.catch=function(g){return this._addCallbackSet({failFunc:g},!0)},SyncTask.prototype.always=function(g){return this._addCallbackSet({successFunc:g,failFunc:g},!0)},SyncTask.prototype.setTracingEnabled=function(g){return this._traceEnabled=g,this},SyncTask.prototype.finally=function(g){return this._addCallbackSet({successFunc:g,failFunc:g},!1),this},SyncTask.prototype.done=function(g){return this._addCallbackSet({successFunc:g},!1),this},SyncTask.prototype.fail=function(g){return this._addCallbackSet({failFunc:g},!1),this},SyncTask.prototype.resolve=function(g){return this._checkState(!0),this._completedSuccess=!0,this._storedResolution=g,this._cancelCallbacks=[],this._resolveSuccesses(),this},SyncTask.prototype.reject=function(g){return this._checkState(!1),this._completedFail=!0,this._storedErrResolution=g,this._cancelCallbacks=[],this._resolveFailures(),SyncTask._enforceErrorHandled(this),this},SyncTask.prototype._checkState=function(g){if(this._completedSuccess||this._completedFail){this._completeStack&&console.error(this._completeStack.message,this._completeStack.stack);var S="Failed to "+(g?"resolve":"reject")+": the task is already "+(this._completedSuccess?"resolved":"rejected");throw new Error(S)}(f.config.traceEnabled||this._traceEnabled)&&(this._completeStack=new Error("resolve"))},SyncTask._enforceErrorHandled=function(g){g._mustHandleError&&(SyncTask._rejectedTasks.push(g),SyncTask._enforceErrorHandledTimer||(SyncTask._enforceErrorHandledTimer=setTimeout((function(){SyncTask._enforceErrorHandledTimer=void 0;var g=SyncTask._rejectedTasks;SyncTask._rejectedTasks=[],g.forEach((function(g,S){g._mustHandleError&&f.config.unhandledErrorHandler(g._storedErrResolution)}))}),0)))},SyncTask.prototype.cancel=function(g){if(this._wasExplicitlyCanceled)throw new Error("Already Canceled");this._wasExplicitlyCanceled=!0,this._cancelInternal(g)},SyncTask.prototype._cancelInternal=function(g){var f=this;if(!this._wasCanceled){this._wasCanceled=!0,this._cancelContext=g;var S=this._cancelCallbacks;this._cancelCallbacks=[],S.length>0&&S.forEach((function(g){f._completedSuccess||f._completedFail||g(f._cancelContext)}))}},SyncTask.cancelOtherInternal=function(g,f){var S=g;S._storedCallbackSets&&S._cancelInternal?S._cancelInternal(f):g.cancel(f)},SyncTask.prototype.promise=function(){return this},SyncTask.prototype._resolveSuccesses=function(){var g=this;for(this._resolving=!0;this._storedCallbackSets.length;){var f=this._storedCallbackSets;this._storedCallbackSets=[],f.forEach((function(f){f.asyncCallback?asyncCallback((function(){return g._resolveSuccessCallback(f)})):g._resolveSuccessCallback(f)}))}this._resolving=!1},SyncTask.prototype._resolveSuccessCallback=function(g){var f=this;g.successFunc?run((function(){var S=g.successFunc(f._storedResolution);isCancelable(S)&&(g.wasCanceled?SyncTask.cancelOtherInternal(S,g.cancelContext):g.task.onCancel((function(g){return SyncTask.cancelOtherInternal(S,g)}))),isThenable(S)?S.then((function(f){g.task.resolve(f)}),(function(f){g.task.reject(f)})):g.task.resolve(S)}),(function(S){f._handleException(S,"SyncTask caught exception in success block: "+S.toString()),g.task.reject(S)})):g.task.resolve(this._storedResolution)},SyncTask.prototype._resolveFailures=function(){var g=this;for(this._resolving=!0;this._storedCallbackSets.length;){var f=this._storedCallbackSets;this._storedCallbackSets=[],f.forEach((function(f){f.asyncCallback?asyncCallback((function(){return g._resolveFailureCallback(f)})):g._resolveFailureCallback(f)}))}this._resolving=!1},SyncTask.prototype._resolveFailureCallback=function(g){var f=this;g.failFunc?run((function(){var S=g.failFunc(f._storedErrResolution);isCancelable(S)&&(g.wasCanceled?SyncTask.cancelOtherInternal(S,g.cancelContext):g.task.onCancel((function(g){return SyncTask.cancelOtherInternal(S,g)}))),isThenable(S)?S.then((function(f){g.task.resolve(f)}),(function(f){g.task.reject(f)})):g.task.resolve(S)}),(function(S){f._handleException(S,"SyncTask caught exception in failure block: "+S.toString()),g.task.reject(S)})):g.task.reject(this._storedErrResolution)},SyncTask.prototype._handleException=function(g,S){f.config.exceptionsToConsole&&console.error(S),f.config.exceptionHandler&&f.config.exceptionHandler(g)},SyncTask.prototype.toEs6Promise=function(){var g=this;return new Promise((function(f,S){return g.then(f,S)}))},SyncTask._rejectedTasks=[],SyncTask}();g.SyncTask=S}(S||(S={})),f.all=all,f.Defer=Defer,f.Resolved=Resolved,f.Rejected=Rejected,f.race=race,f.raceTimer=raceTimer})),b=createCommonjsModule((function(g,f){
/*!
	 *  Appenders.ts
	 *  AUF
	 *
	 *  Created by Johan Blumenberg on 2016-12-29
	 *  Copyright 2016 Microsoft. All rights reserved.
	 *
	 */
var S,v=C&&C.__extends||(S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f.hasOwnProperty(S)&&(g[S]=f[S])},function(g,f){function __(){this.constructor=g}S(g,f),g.prototype=null===f?Object.create(f):(__.prototype=f.prototype,new __)});Object.defineProperty(f,"__esModule",{value:!0});var I,b=function(){function AbstractLogAppender(g){this._formatter=g||new A}return AbstractLogAppender.prototype.formatter=function(){return this._formatter},AbstractLogAppender.prototype.receiveAll=function(){return!1},AbstractLogAppender.prototype.levels=function(){return null},AbstractLogAppender}();function toHex(g){return(4294967296+g).toString(16).substr(-8)}function pad(g,f){return(1e12+g).toString(10).substr(-f)}f.AbstractLogAppender=b,function(g){g[g.Timestamp=1]="Timestamp",g[g.Component=4]="Component",g[g.Level=8]="Level",g[g.FullDate=32]="FullDate",g[g.LogId=64]="LogId"}(I=f.SLF_Flags||(f.SLF_Flags={}));var A=function(){function StandardLogFormatter(g){void 0===g&&(g=4294967295),this._flags=g}return StandardLogFormatter.prototype.format=function(g,f,S,v){var C="";if(this._flags&I.FullDate)C+=new Date(g.timestamp).toISOString()+" ";else if(this._flags&I.Timestamp){var b=new Date(g.timestamp);C+=pad(b.getHours(),2)+":"+pad(b.getMinutes(),2)+":"+pad(b.getSeconds(),2)+"."+pad(b.getMilliseconds(),2)+" "}return this._flags&I.LogId&&(C+="[#"+toHex(f)+"-"+(g.component.safe()?"S":"u")+"] "),this._flags&I.Level&&(C+="["+T.LogFactory.levelToString(g.level)+"] "),this._flags&I.Component&&(C+="["+g.component.name()+"] "),S||""===S?C+_.vsprintf(S,v):C+toHex(f)+": "+v.join(" ")},StandardLogFormatter}();f.StandardLogFormatter=A;var P=console,R=console.log||function(){},M=console.info||R,w=console.warn||M,O=console.error||w,D=function(g){function ConsoleAppender(){return null!==g&&g.apply(this,arguments)||this}return v(ConsoleAppender,g),ConsoleAppender.prototype.log=function(g,f,S,v){v=v.slice(0);var C=g.level<=_.LogLevel.Debug3?R:g.level<=_.LogLevel.Debug1?M:g.level<=_.LogLevel.Warning?w:O;if(-1===f){var T=this.formatter().format(g,f,"",[]);"string"==typeof v[0]&&(T+=v.shift()),C.apply(P,[T].concat(v))}else{for(var I=void 0,b=[];I=S.match(/\s*%@\s*$/);)S=S.substr(0,S.length-I[0].length),b.unshift(v.pop());T=this.formatter().format(g,f,S,v);C.apply(P,[T].concat(b))}},ConsoleAppender}(b);f.ConsoleAppender=D;var N=function(){function ChainedLogAppender(g){this._chained=g}return ChainedLogAppender.prototype.log=function(g,f,S,v){this._chained.log(g,f,S,v)},ChainedLogAppender.prototype.receiveAll=function(){return this._chained.receiveAll()},ChainedLogAppender.prototype.levels=function(){return this._chained.levels()},ChainedLogAppender}();f.ChainedLogAppender=N;var k=function(g){function LevelWrappedAppender(f,S){var v=g.call(this,f)||this;return v._levels=S,v}return v(LevelWrappedAppender,g),LevelWrappedAppender.prototype.levels=function(){return this._levels},LevelWrappedAppender}(N);function wrapAppenderWithLogLevels(g,f){return new k(g,f)}f.wrapAppenderWithLogLevels=wrapAppenderWithLogLevels})),A=createCommonjsModule((function(g,f){
/*!
	 *  RootToolsManager.ts
	 *  AUF
	 *
	 *  Created by Johan Blumenberg on 2016-12-29
	 *  Copyright 2016 Microsoft. All rights reserved.
	 *
	 */
var S,v=C&&C.__extends||(S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f.hasOwnProperty(S)&&(g[S]=f[S])},function(g,f){function __(){this.constructor=g}S(g,f),g.prototype=null===f?Object.create(f):(__.prototype=f.prototype,new __)});Object.defineProperty(f,"__esModule",{value:!0});var A=T.LogFactory.instance().component("RootToolsManager");T.LogFactory.instance().declareComponentSafe("RootToolsManager",!0);var P,R="638b8ba2bae14e07aa5d73ddb5d5e5c5-297b8412-5df3-4a83-83c4-7b76c6c5d3f0-7104";!function(g){g[g.InternalBuild=0]="InternalBuild",g[g.PublicBuild=1]="PublicBuild"}(P=f.BuildType||(f.BuildType={}));var M=P.InternalBuild;function setBuildType(g){var f=M;return M=g,f}function toHex(g){return(4294967296+g).toString(16).substr(-8)}function map(g,f){var S=[];for(var v in g)S.push(f(v,g[v]));return S}function arrayEquals(g,f,S){if(null==g)return null==f||0===f.length;if(null==f)return null==g||0===g.length;if(g.length===f.length){for(var v=0;v<g.length;v++)if(!S(g[v],f[v]))return!1;return!0}return!1}function matcherEquals(g,f){return null==g?null==f:null==f?null==g:g.arg===f.arg&&g.op===f.op&&g.value===f.value}function conditionEquals(g,f){return null==g?null==f||0===f.logId:null==f?null==g||0===g.logId:g.logId===f.logId&&g.name===f.name&&arrayEquals(g.matchers,f.matchers,matcherEquals)}function filterEqualsToNativeFilter(g,f){return null==g?null==f:null==f?null==g:g.component===f.component&&g.parsedLevel===f.level}function filterEquals(g,f){return null==g?null==f:null==f?null==g:g.component===f.component&&g.level===f.level}function formatArgs(g){for(var f=[],S=0;S<g.length;S++)"string"==typeof g[S]||"number"==typeof g[S]?f.push(g[S]):f.push(JSON.stringify(g[S]));return f}f.setBuildType=setBuildType;var w=function(g){function Trigger(f,S,v){var C=g.call(this)||this;return C._unmetConditions=[],C._rtMan=f,C._triggerCallback=S,C._ecsConfig=v,C.resetConditions(),C}return v(Trigger,g),Trigger.prototype.config=function(){return this._ecsConfig},Trigger.prototype.configEquals=function(g){return this._ecsConfig.includeUnsafe===g.includeUnsafe&&this._ecsConfig.mutualSubmissionType===g.mutualSubmissionType&&this._ecsConfig.name===g.name&&this._ecsConfig.reenableAfterTriggering===g.reenableAfterTriggering&&this._ecsConfig.experimentTarget===g.experimentTarget&&conditionEquals(this._ecsConfig.resetCondition,g.resetCondition)&&arrayEquals(this._ecsConfig.conditions,g.conditions,conditionEquals)&&arrayEquals(this._ecsConfig.filters,g.filters,filterEquals)},Trigger.prototype.nativeConfigEquals=function(g){return this._ecsConfig.includeUnsafe===g.includeUnsafe&&this._ecsConfig.name===g.name&&this._ecsConfig.reenableAfterTriggering===g.reenableAfterTriggering&&conditionEquals(this._ecsConfig.resetCondition,g.resetCondition)&&arrayEquals(this._ecsConfig.conditions,g.conditions,conditionEquals)&&arrayEquals(this._ecsConfig.filters,g.filters,filterEqualsToNativeFilter)},Trigger.prototype.needReset=function(g){return!this.configEquals(g)},Trigger.prototype.resetConditions=function(){this._unmetConditions=[];for(var g=0;g<this._ecsConfig.conditions.length;g++)this._unmetConditions.push(g)},Trigger.prototype.matcherMatches=function(g,f){if(g.arg>=f.length)return!1;var S=f[g.arg],v="string"==typeof S?g.value:parseInt(g.value,10);return"="===g.op||"=="===g.op?S===v:"!="===g.op?S!==v:"<"===g.op?S<v:"<="===g.op?S<=v:">"===g.op?S>v:">="===g.op?S>=v:"CONTAINS"===g.op.toUpperCase()&&(""+S).indexOf(g.value)>=0},Trigger.prototype.conditionMatches=function(g,f,S){if(f!==g.logId)return!1;if(g.matchers)for(var v=0;v<g.matchers.length;v++)if(!this.matcherMatches(g.matchers[v],S))return!1;return!0},Trigger.prototype.log=function(g,f,S,v){if(0!==this._unmetConditions.length&&g.component!==A){var C=this._ecsConfig;C.resetCondition&&this.conditionMatches(C.resetCondition,f,v)&&(A.debug4("LogTrigger %s: resetCondition met",C.name),this.resetConditions());for(var _=0;_<this._unmetConditions.length;_++){var T=this._unmetConditions[_];if(this.conditionMatches(C.conditions[T],f,v)){A.debug4("LogTrigger %s: condition %s met",C.name,C.conditions[T].name),this._unmetConditions.splice(_,1);break}}0===this._unmetConditions.length&&(A.debug1("LogTrigger %s has triggered, trying to send the log",C.name),this._triggerCallback.call(this._rtMan,C),C.reenableAfterTriggering&&this.resetConditions())}},Trigger.prototype.receiveAll=function(){return!0},Trigger}(b.AbstractLogAppender),O=function(g){function CircularBuffer(f,S,v){var C=g.call(this)||this;return C._circularBuffer=[],C._circularBufferMaxSize=0,C._onBufferOverflow=null,C._circularBuffer=[],C._circularBufferMaxSize=S,C._includeUnsafe=f,C._onBufferOverflow=v||function(){return C._circularBuffer.shift()},C}return v(CircularBuffer,g),CircularBuffer.prototype.log=function(g,f,S,v){if((this._includeUnsafe||g.component.safe())&&!(this._circularBuffer.length>this._circularBufferMaxSize)){var C={md:g,logId:f,messages:formatArgs(v)};this._circularBuffer.push(C),this._circularBuffer.length>this._circularBufferMaxSize&&this._onBufferOverflow()}},CircularBuffer.prototype.visitReverseOrder=function(g){for(var f=this._circularBuffer.length-1;f>=0;f--){var S=this._circularBuffer[f];if(!g(S.md,S.logId,S.messages))return}},CircularBuffer.prototype.visitForwardOrder=function(g){for(var f=0;f<this._circularBuffer.length;f++){var S=this._circularBuffer[f];if(!g(S.md,S.logId,S.messages))return}},CircularBuffer.prototype.needReset=function(g,f){return g!==this._includeUnsafe||f!==this._circularBufferMaxSize},CircularBuffer.prototype.dumpLogBuffer=function(g,f,S){var v=this,C=new D(g.reverse),_=g.filter.map((function(g){return{component:"root"===g.component?"":g.component,parsedLevel:g.level}})),T=S||{matchedLines:0,totalLines:0};return(g.reverse?this.visitReverseOrder:this.visitForwardOrder).apply(this,[function(g,S,I){return T.totalLines++,v.filterMatches(g,S,I,_)&&(T.matchedLines++,C.log(g.component,g.timestamp,g.level,S,I)),!f||C._data.length<f}]),C.close(),C.data()},CircularBuffer.prototype.filterMatches=function(g,f,S,v){for(var C=0;C<v.length;C++)if((""===v[C].component||g.component.name()===v[C].component||g.component.name().substr(0,v[C].component.length)===v[C].component&&"."===g.component.name().charAt(v[C].component.length))&&g.level>=v[C].parsedLevel)return!0;return!1},CircularBuffer.prototype.clear=function(){this._circularBuffer=[]},CircularBuffer.prototype.size=function(){return this._circularBuffer.length},CircularBuffer.prototype.empty=function(){return 0===this.size()},CircularBuffer.prototype.capacity=function(){return this._circularBufferMaxSize},CircularBuffer}(b.AbstractLogAppender);f.CircularBuffer=O;var D=function(){function BinaryLogFormatter(g){this._reverse=g,this._first=!0,this._pending=[],this._components={},this._componentCount=0,this._lastts=0,this._base64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this._data="ULOG2"+String.fromCharCode(33)+String.fromCharCode(32),this._data+=g?String.fromCharCode(34):String.fromCharCode(32),this._data+=String.fromCharCode(32)}return BinaryLogFormatter.prototype._add8=function(g){if(this._pending.push(255&g),3===this._pending.length){var f=(this._pending[0]<<16)+(this._pending[1]<<8)+(this._pending[2]<<0),S=this._base64chars[f>>18&63]+this._base64chars[f>>12&63]+this._base64chars[f>>6&63]+this._base64chars[f>>0&63];this._data+=S,this._pending=[]}},BinaryLogFormatter.prototype._add16=function(g){this._add8(g>>8&255),this._add8(g>>0&255)},BinaryLogFormatter.prototype._add32=function(g){this._add8(g>>24&255),this._add8(g>>16&255),this._add8(g>>8&255),this._add8(g>>0&255)},BinaryLogFormatter.prototype._add64=function(g){this._add32(g/4294967296|0),this._add32(0|g)},BinaryLogFormatter.prototype._addS=function(g){for(var f=0;f<g.length;f++)this._add8(g.charCodeAt(f));this._add8(0)},BinaryLogFormatter.prototype._close=function(){for(;this._pending.length;)this._add8(0)},BinaryLogFormatter.prototype.log=function(g,f,S,v,C){var _=this._components[g.name()];_||(_=++this._componentCount,this._components[g.name()]=_,this._add8(2),this._add16(_),this._addS(g.name()),this._addS(""),this._addS(""),this._add8(g.safe()?1:0));var T=128;this._first&&(T|=2);var I=f-this._lastts;this._lastts=f,I>-128&&I<128&&(T|=1),this._add8(T),1&T?this._add8(I):this._add64(1e3*f),this._first&&(this._add32(1),this._add8(0),this._add16(0)),this._add16(_),this._add8(S),this._add32(v),this._add8(C.length);for(var b=0;b<C.length;b++)this._add8(8),this._addS(""+C[b]);this._first=!1},BinaryLogFormatter.prototype.close=function(){this._add8(7),this._close()},BinaryLogFormatter.prototype.data=function(){return this._data},BinaryLogFormatter.prototype.empty=function(){return this._first},BinaryLogFormatter}(),N=function(g){function DumperBuffer(f,S,v,C){var _=g.call(this)||this;return _._capacity=f,_._onBufferOverflow=S,_._enableThrottling=v,_._maxVerbosityLevel=C,_._outputFormatter=new D(!1),_._linesStored=0,_._throttling=!1,_._linesThrottled=0,_}return v(DumperBuffer,g),DumperBuffer.prototype.log=function(g,f,S,v){this._maxVerbosityLevel&&g.level<this._maxVerbosityLevel||(this._throttling?this._linesThrottled++:(this._linesStored++,this._outputFormatter.log(g.component,g.timestamp,g.level,f,formatArgs(v))),this._linesStored>this._capacity&&(this._enableThrottling?this._throttling||(this._throttling=!0):this._onBufferOverflow()))},DumperBuffer.prototype.dumpAndReset=function(){if(this._outputFormatter.empty())return"";this._linesThrottled>0&&this._outputFormatter.log(A,(new Date).getTime(),_.LogLevel.Fatal,-1,["RooToolsManager: Log buffer overflow! "+this._linesThrottled+" lines thrown away"]),this._outputFormatter.close();var g=this._outputFormatter.data();return this.clearBuffer(),g},DumperBuffer.prototype.empty=function(){return this._outputFormatter.empty()},DumperBuffer.prototype.clearBuffer=function(){this._outputFormatter=new D(!1),this._linesStored=0,this._linesThrottled=0,this._throttling=!1},DumperBuffer.prototype.capacity=function(){return this._capacity},DumperBuffer.prototype.throttlingEnabled=function(){return this._enableThrottling},DumperBuffer.prototype.size=function(){return this._linesStored},DumperBuffer.prototype.maxVerbosityLevel=function(){return this._maxVerbosityLevel},DumperBuffer}(b.AbstractLogAppender);function validateExperimentTarget(g){return"Native"===g||"JavaScript"===g||"Mixed"===g}f.DumperBuffer=N;var k=function(){function RootToolsManagerImpl(){this._maxUploadSize=0,this._jsToNativeBuffer=null,this._jsToNativeBufferHandle=null,this._jsToNativeFlushTimer=null,this._jsToNativeFlushInterval=0,this._triggers={},this._defaultBuffers=[{size:2097152,level:_.LogLevel.Debug4}],this._defaultKillswitch={blacklist:[],whitelist:[]},this._defaultBlacklists={component:[],logline:[]},this._localLogLevels={},this._defaultExperimentTarget="Mixed",this._BRBCallback=null}return RootToolsManagerImpl.prototype.setDelegate=function(g){this._glue=g,this.registerListeners()},RootToolsManagerImpl.prototype.isDelegateSet=function(){return null!=this._glue},RootToolsManagerImpl.prototype.setNativeFunctions=function(g){this._native&&this._native.log_config.removeLogTriggerListener(this),this._native=g,this._native&&this._native.log_config.addLogTriggerListener(this)},RootToolsManagerImpl.prototype.applyLogLevels=function(){var g={};for(var f in this._localLogLevels)g[f]=this._localLogLevels[f];g[""]=g.root||_.LogLevel.Debug4,delete g.root;var S=map(g,(function(g,f){return{component:g,level:f}}));S.sort((function(g,f){return g.component.length-f.component.length})),S.forEach((function(g){return T.LogFactory.instance().component(g.component).setLevel(g.level)})),this._native&&this._native.log_config.setLogLevelConfig(S)},RootToolsManagerImpl.prototype.setLocalLogLevelConfig=function(g){this._localLogLevels=g,this.applyLogLevels()},RootToolsManagerImpl.prototype.parseMatcher=function(g){return null==g||null==g.arg||null==g.op||null==g.value?null:{arg:g.arg,op:g.op,value:g.value}},RootToolsManagerImpl.prototype.parseCondition=function(g){if(null==g||null==g.logId)return null;if(g.matchers&&!(g.matchers instanceof Array))return null;var f={name:g.name||toHex(g.logId),logId:g.logId,matchers:[]};if(g.matchers&&g.matchers.length)for(var S=0,v=g.matchers;S<v.length;S++){var C=v[S],_=this.parseMatcher(C);_&&f.matchers.push(_)}return f},RootToolsManagerImpl.prototype.parseFilter=function(g){return null==g||null==g.component||0===g.component.length?null:{component:g.component,level:g.level,parsedLevel:T.LogFactory.levelFromString(g.level)}},RootToolsManagerImpl.prototype.parseConfig=function(g,f,S){if(null==g)return null;if(!(g.conditions instanceof Array)||0==g.conditions.length)return null;if(!(g.filters instanceof Array)||0==g.filters.length)return null;if(g.resetCondition&&!this.parseCondition(g.resetCondition))return null;for(var v={name:g.name||f+"->"+S,ecsNs:f,reenableAfterTriggering:g.reenableAfterTriggering||!1,mutualSubmissionType:g.mutualSubmissionType||"",includeUnsafe:M!==P.PublicBuild&&(g.includeUnsafe||!1),experimentTarget:validateExperimentTarget(g.experimentTarget)&&g.experimentTarget||this._defaultExperimentTarget,conditions:[],resetCondition:null==g.resetCondition?g.resetCondition:this.parseCondition(g.resetCondition),filters:[]},C=0,_=g.conditions;C<_.length;C++){var T=_[C],I=this.parseCondition(T);I&&v.conditions.push(I)}for(var b=0,A=g.filters;b<A.length;b++){var R=A[b],w=this.parseFilter(R);w&&v.filters.push(w)}return 0===v.conditions.length?null:v},RootToolsManagerImpl.prototype.isExperimentListed=function(g,f,S,v){return!!g&&(!(!v||!g.some((function(g){return"*"===g.namespace})))||g.some((function(g){return g.namespace===f&&(g.experiment===S||"*"==g.experiment)})))},RootToolsManagerImpl.prototype.isExperimentAllowed=function(g,f,S){return!this.isExperimentListed(g.blacklist,f,S,!0)||this.isExperimentListed(g.whitelist,f,S,!1)},RootToolsManagerImpl.prototype.findTrigger=function(g,f){for(var S in g)if(g[S].configEquals(f))return S;return null},RootToolsManagerImpl.prototype.findTriggerByNativeConfig=function(g,f){for(var S in g)if(g[S].nativeConfigEquals(f))return S;return null},RootToolsManagerImpl.prototype.OnEcsChange=function(){var g=this;function forEachAsync(g,f,S){return f<g.length?S(g[f]).then((function(){return forEachAsync(g,f+1,S)})):I.Resolved()}return null==this._glue?I.Resolved():this._glue.fetchEcsConfig("SkypeRootTools","ULBaseline").then((function(f){A.debug4("Reloading ULBaseline config - new config: %@",f),f||(A.warn("No ULBaseline config"),f={}),g._maxUploadSize=f.logUpload&&f.logUpload.maxSize||1024;var S=[],v=g._triggers;g._triggers={};var C=(f.logUpload&&f.logUpload.maxSize||1024)/100,I=f.circularBuffer&&f.circularBuffer.enabled,P=f.circularBuffer&&f.circularBuffer.buffers||g._defaultBuffers,R=f.circularBuffer&&f.circularBuffer.storeUnsafe;g._defaultExperimentTarget=validateExperimentTarget(f.defaultExperimentTarget)&&f.defaultExperimentTarget||"Mixed";var M=f.killswitch||g._defaultKillswitch,D=f.blacklists||g._defaultBlacklists;D.component.length>0&&T.LogFactory.instance().setComponentBlacklist(D.component);var N={};(f.componentLevels||[]).forEach((function(g){return N[g.component]=g.level})),forEachAsync(f.configPaths||[],0,(function(f){return g._glue.fetchEcsConfig(f.ns,f.key).then((function(C){var _=C instanceof Array?C:[C];A.debug4("Reloading ECS config for %s->%s - new config: %@",f.ns,f.key,_);for(var T=0,b=_;T<b.length;T++){var P=b[T];if(null!=P){var w=g.parseConfig(P,f.ns,f.key);if(null!=w)if("JavaScript"===w.experimentTarget||"Mixed"===w.experimentTarget)if(A.debug2("Parsed ECS config for %s->%s - %@",f.ns,f.key,w),g.isExperimentAllowed(M,f.ns,w.name)){A.debug2("Allowing %s->%s:%s according to killswitch",f.ns,f.key,w.name),I=!0;var O=g.findTrigger(v,w);null!=O?(A.debug2("Triggers updated, keeping trigger %s",w.name),g._triggers[O]=v[O],delete v[O]):S.push(w),w.filters&&w.filters.forEach((function(g){return N[g.component]=Math.min(N[g.component]||255,g.parsedLevel)})),w.includeUnsafe&&(R=!0)}else A.debug2("Disallowing %s->%s according to killswitch",f.ns,f.key);else A.debug4("Skipping %s->%s, targeted for %s",f.ns,f.key,w);else A.error("Failed to parse ECS config for %s->%s",f.ns,f.key)}}}))})).always((function(){for(var f in g.applyLogLevels(),v)A.debug2("Triggers updated, removing trigger %s",v[f].config().name),T.LogFactory.instance().removeAppender(+f);if(S.forEach((function(f){A.debug2("Triggers updated, adding trigger %s",f.name);var S=new w(g,g._triggered,f),v=T.LogFactory.instance().addAppender(S);g._triggers[String(v)]=S})),N[""]=N.root||_.LogLevel.Debug4,delete N.root,!g._circularBuffer||I&&!g._circularBuffer.needReset(R,C)?g._circularBuffer&&(Object.keys(v).length>0||S.length>0?(A.debug2("Buffer updated, reapplying log levels, removing log levels wrapper"),T.LogFactory.instance().removeAppender(g._circularBufferHandle),g._circularBufferHandle=null):A.debug2("Buffer updated, no change")):(A.debug2("Buffer updated, removing existing buffer"),T.LogFactory.instance().removeAppender(g._circularBufferHandle),g._circularBuffer=null,g._circularBufferHandle=null),I&&(g._circularBuffer||(A.debug2("Buffer updated, adding new buffer (storeUnsafe=%d,maxSize=%s)",R,C),g._circularBuffer=new O(R,C)),null==g._circularBufferHandle&&(A.debug2("Creating log level wrapper"),g._circularBufferHandle=T.LogFactory.instance().addAppender(b.wrapAppenderWithLogLevels(g._circularBuffer,N),_.AppenderFlags.InsertFront))),g._native){var M=map(N,(function(g,f){return{component:g,level:f}}));M.sort((function(g,f){return g.component.length-f.component.length})),g._native.log_config.setLogBufferConfig(I,{storeUnsafe:R,buffers:P},M);var D=[];for(var k in g._triggers){var L=g._triggers[k].config();D.push({name:L.name,ecsNs:L.ecsNs,conditions:L.conditions,resetCondition:L.resetCondition,includeUnsafe:L.includeUnsafe,reenableAfterTriggering:L.reenableAfterTriggering,filters:L.filters.map((function(g){return{component:g.component,level:g.parsedLevel}})),dumpFile:!1,metadata:{}})}g._native.log_config.setLogTriggerConfig(D,{})}}))}))},RootToolsManagerImpl.prototype._send=function(g,f){null!=this._glue&&(this._glue.sendTelemetry(R,{logTriggerName:g.name,logEcsNs:g.ecsNs,logdata:f}),A.debug4("LogSender::send, sent %d bytes",f.length))},RootToolsManagerImpl.prototype.triggered=function(g,f){},RootToolsManagerImpl.prototype.triggeredPartially=function(g,f,S,v,C){var _=this.findTriggerByNativeConfig(this._triggers,g);if(_){var I={level:f.level,component:T.LogFactory.instance().component(f.component),timestamp:f.timestamp};this._triggers[_].log(I,S,v,C)}},RootToolsManagerImpl.prototype.reset=function(g){var f=this.findTriggerByNativeConfig(this._triggers,g);f&&this._triggers[f].resetConditions()},RootToolsManagerImpl.prototype.dumpLogBuffer=function(g,f){if(this._circularBuffer){var S={matchedLines:0,totalLines:0},v=this._circularBuffer.dumpLogBuffer(g,this._maxUploadSize,S);if(A.debug4("dumpLogBuffer: dumped %d of %d lines, size of payload: %d",S.matchedLines,S.totalLines,null!=v?v.length:0),this._native){var C=I.Defer();return this._native.log_config.mergeAndDumpLogBuffer(v,g,f,(function(g){return C.resolve(g)})),C.promise()}return I.Resolved(v)}return A.warn("dumpLogBuffer: no log buffer enabled"),I.Rejected()},RootToolsManagerImpl.prototype._triggered=function(g){var f=this,S={compression:_.LogFileCompression.Compress,encoding:_.LogFileEncoding.Base64,encryption:_.LogFileEncryption.Encrypted,maxRotations:0,maxSize:this._maxUploadSize,reverse:!0},v={includeUnsafe:g.includeUnsafe,filter:g.filters.map((function(g){return{component:g.component,level:g.parsedLevel}})),reverse:!0};this.dumpLogBuffer(v,S).then((function(S){return f._send(g,S)}))},RootToolsManagerImpl.prototype.sendBRBEvent=function(g,f){try{if(A.debug2("sendBRBEvent %s",JSON.stringify(g)),null!=this._glue&&"function"==typeof this._glue.sendLoggingEventToNative){var S={eventType:"uploadBRB",mutualSubmissionType:"call",payload:g},v=void 0!==f?JSON.stringify({userIds:f}):"";this._glue.sendLoggingEventToNative(JSON.stringify(S),v)}}catch(g){A.error("sendBRBEvent %s: %s",g.name,g.message)}},RootToolsManagerImpl.prototype.setBRBCallback=function(g){A.debug2("setBRBCallback"),null!=this._glue?"function"==typeof this._glue.setNativeLoggingEventCallback?this._BRBCallback=g:A.warn("setBRBCallback: RootToolsManagerDelegate missing setNativeLoggingEventCallback method"):A.warn("setBRBCallback: RootToolsManagerDelegate is not set")},RootToolsManagerImpl.prototype.registerListeners=function(){var g=this;null!=this._glue&&"function"==typeof this._glue.setNativeLoggingEventCallback?this._glue.setNativeLoggingEventCallback((function(f,S){return g.handleNativeLoggingEvent(f,S)})):A.warn("registerListeners: RootToolsManagerDelegate missing setNativeLoggingEventCallback method")},RootToolsManagerImpl.prototype.handleNativeLoggingEvent=function(g,f){try{A.debug2("Native Log event message: %s aux: %s",g,f);var S=JSON.parse(g);if(S.eventType&&"uploadBRB"===S.eventType){if("function"!=typeof this._BRBCallback)return void A.warn("BRBCallback not set, ignoring native event");A.debug4("Sending BRB callback: %@",S.payload),this._BRBCallback(S.payload)}else S.eventType&&"jsLogFileConfiguration"===S.eventType&&this.handleLogFileConfigEvent(S)}catch(g){A.error("handleNativeLoggingEvent %s: %s",g.name,g.message)}},RootToolsManagerImpl.prototype.handleLogFileConfigEvent=function(g){if(g.payload){var f=g.payload;if(f.enabled){if(f.chunkSize&&f.flushInterval){var S={chunkSize:f.chunkSize,flushInterval:f.flushInterval,enableThrottling:f.enableThrottling,maxVerbosityLevel:f.maxVerbosityLevel};this.startJsToNativeLogging(S)}}else this.flushDisableJsToNativeLogging()}},RootToolsManagerImpl.prototype.logExternalForDDL=function(g,f){try{if(A.debug2("logExternalForDDL %s %s",g,f),null!=this._glue&&"function"==typeof this._glue.sendLoggingEventToNative){var S={eventType:"logInSClog",payload:{message:g,parameters:f}};this._glue.sendLoggingEventToNative(JSON.stringify(S),"")}else A.warn("ignoring logExternalForDDL, delegate misconfigured")}catch(g){A.error("logExternalForDDL %s: %s",g.name,g.message)}},RootToolsManagerImpl.prototype.startJsToNativeLogging=function(g){var f=this,S=g.chunkSize,v=g.flushInterval,C=g.enableThrottling,_=this._getVerbosityLevelFromConfig(g.maxVerbosityLevel);if(this._jsToNativeBuffer){if(this._jsToNativeBuffer.capacity()===S&&this._jsToNativeFlushInterval===v&&this._jsToNativeBuffer.throttlingEnabled()===C&&this._jsToNativeBuffer.maxVerbosityLevel()===_)return void A.debug1("Same JS2Native settings received - doing nothing");A.debug1("Reapplying js to native settings"),this.flushDisableJsToNativeLogging()}this._jsToNativeBuffer=new N(S,(function(){f.onJsToNativeBufferReady(f._jsToNativeBuffer)}),C,_),this.setJsToNativeFlushTimeout(v),this._jsToNativeFlushInterval=v,this._jsToNativeBufferHandle=T.LogFactory.instance().addAppender(this._jsToNativeBuffer)},RootToolsManagerImpl.prototype._getVerbosityLevelFromConfig=function(g){return g?T.LogFactory.levelFromString(g):null},RootToolsManagerImpl.prototype.flushDisableJsToNativeLogging=function(){this._jsToNativeBuffer&&this.onJsToNativeBufferReady(this._jsToNativeBuffer),this.plainDisableJsToNativeLogging()},RootToolsManagerImpl.prototype.plainDisableJsToNativeLogging=function(){this.clearJsToNativeFlushTimeout(),this._jsToNativeBufferHandle&&(T.LogFactory.instance().removeAppender(this._jsToNativeBufferHandle),this._jsToNativeBufferHandle=0,this._jsToNativeBuffer=null,A.debug1("Disabling forwarding JS logs to native"))},RootToolsManagerImpl.prototype.onJsToNativeBufferReady=function(g){null!=this._glue&&"function"==typeof this._glue.sendLoggingEventToNative?(this.clearJsToNativeFlushTimeout(),this.dumpJsToNativeBuffer(g),this.setJsToNativeFlushTimeout(this._jsToNativeFlushInterval)):this.plainDisableJsToNativeLogging()},RootToolsManagerImpl.prototype.dumpJsToNativeBuffer=function(g){if(!g.empty()){var f=g.dumpAndReset(),S={eventType:"writeLogData"};this._glue.sendLoggingEventToNative(JSON.stringify(S),f)}},RootToolsManagerImpl.prototype.clearJsToNativeFlushTimeout=function(){this._jsToNativeFlushTimer&&(clearTimeout(this._jsToNativeFlushTimer),this._jsToNativeFlushTimer=null)},RootToolsManagerImpl.prototype.setJsToNativeFlushTimeout=function(g){var f=this;!this._jsToNativeFlushTimer&&g&&(this._jsToNativeFlushTimer=setTimeout((function(){f._jsToNativeFlushTimer=null,f.onJsToNativeBufferReady(f._jsToNativeBuffer)}),g))},RootToolsManagerImpl.prototype.stopAsyncOperations=function(){this.flushDisableJsToNativeLogging()},RootToolsManagerImpl}();f.RootToolsManager=new k})),P=createCommonjsModule((function(g,f){
/*!
	 *  pii.ts
	 *  AUF
	 *
	 *  Created by Johan Blumenberg on 2017-01-16
	 *  Copyright 2017 Microsoft. All rights reserved.
	 *
	 */
Object.defineProperty(f,"__esModule",{value:!0});var DefaultTagger=function(g){return g},S=!0,v=DefaultTagger,C={},_=0;function addName(g){return C[g]="u"+ ++_}var T,I=/^([0-9][0-9]?):([^<>\*\{\}&'\"\/\\?^`|~\s]+)$/;!function(g){g[g.MSA=1]="MSA",g[g.S4B_Bridge=2]="S4B_Bridge",g[g.PSTN=4]="PSTN",g[g.SkypeId=8]="SkypeId",g[g.Thread=19]="Thread",g[g.LegacyShortCircuit=20]="LegacyShortCircuit",g[g.OneToOneTextMessage=21]="OneToOneTextMessage",g[g.GroupTextMessage=22]="GroupTextMessage",g[g.Bot=28]="Bot",g[g.InternalSkype=48]="InternalSkype"}(T||(T={}));var b=[T.Thread,T.InternalSkype];function enableAnonymization(g){S=g}function useTagger(g){v=g||DefaultTagger}f.enableAnonymization=enableAnonymization,f.useTagger=useTagger,function(g){function untaggedUserName(g){return S?g?C[g]||addName(g):null:g}function UserName(g){var f=untaggedUserName(g);return v(f)}function Mri(g){var f,S=g.match(I);if(S){var C=Number(S[1]),_=S[2];f=-1!=b.indexOf(C)?g:C+":"+untaggedUserName(_)}else f=untaggedUserName(g);return v(f)}function Omit(g){var f;return f=S?"number"==typeof g?19229:"string"==typeof g?g.charAt(0)+"...":null:g,v(f)}g.UserName=UserName,g.Mri=Mri,g.Omit=Omit}(f.pii||(f.pii={}))})),R=createCommonjsModule((function(g,f){
/*!
	 *  index.ts
	 *  AUF
	 *
	 *  Created by Johan Blumenberg on 2016-12-29
	 *  Copyright 2016 Microsoft. All rights reserved.
	 *
	 */
function __export(g){for(var S in g)f.hasOwnProperty(S)||(f[S]=g[S])}Object.defineProperty(f,"__esModule",{value:!0}),__export(_),__export(T),__export(A),__export(b),__export(P)})),M=createCommonjsModule((function(g,f){(function(){var S,v="4.17.21",_=200,T="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",I="Expected a function",b="Invalid `variable` option passed into `_.template`",A="__lodash_hash_undefined__",P=500,R="__lodash_placeholder__",M=1,w=2,O=4,D=1,N=2,k=1,L=2,F=4,x=8,U=16,V=32,B=64,H=128,$=256,j=512,G=30,q="...",W=800,z=16,K=1,J=2,Y=3,Q=1/0,X=9007199254740991,Z=17976931348623157e292,ee=NaN,te=4294967295,ie=te-1,ne=te>>>1,re=[["ary",H],["bind",k],["bindKey",L],["curry",x],["curryRight",U],["flip",j],["partial",V],["partialRight",B],["rearg",$]],se="[object Arguments]",ae="[object Array]",oe="[object AsyncFunction]",le="[object Boolean]",ce="[object Date]",de="[object DOMException]",he="[object Error]",ue="[object Function]",ge="[object GeneratorFunction]",pe="[object Map]",me="[object Number]",fe="[object Null]",Se="[object Object]",ve="[object Promise]",Ce="[object Proxy]",ye="[object RegExp]",Ee="[object Set]",_e="[object String]",Te="[object Symbol]",Ie="[object Undefined]",be="[object WeakMap]",Ae="[object WeakSet]",Pe="[object ArrayBuffer]",Re="[object DataView]",Me="[object Float32Array]",we="[object Float64Array]",Oe="[object Int8Array]",De="[object Int16Array]",Ne="[object Int32Array]",ke="[object Uint8Array]",Le="[object Uint8ClampedArray]",Fe="[object Uint16Array]",xe="[object Uint32Array]",Ue=/\b__p \+= '';/g,Ve=/\b(__p \+=) '' \+/g,Be=/(__e\(.*?\)|\b__t\)) \+\n'';/g,He=/&(?:amp|lt|gt|quot|#39);/g,$e=/[&<>"']/g,je=RegExp(He.source),Ge=RegExp($e.source),qe=/<%-([\s\S]+?)%>/g,We=/<%([\s\S]+?)%>/g,ze=/<%=([\s\S]+?)%>/g,Ke=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Je=/^\w*$/,Ye=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Qe=/[\\^$.*+?()[\]{}|]/g,Xe=RegExp(Qe.source),Ze=/^\s+/,et=/\s/,tt=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,it=/\{\n\/\* \[wrapped with (.+)\] \*/,nt=/,? & /,rt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,st=/[()=,{}\[\]\/\s]/,at=/\\(\\)?/g,ot=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,lt=/\w*$/,ct=/^[-+]0x[0-9a-f]+$/i,dt=/^0b[01]+$/i,ht=/^\[object .+?Constructor\]$/,ut=/^0o[0-7]+$/i,gt=/^(?:0|[1-9]\d*)$/,pt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,mt=/($^)/,ft=/['\n\r\u2028\u2029\\]/g,St="\\ud800-\\udfff",vt="\\u0300-\\u036f"+"\\ufe20-\\ufe2f"+"\\u20d0-\\u20ff",Ct="\\u2700-\\u27bf",yt="a-z\\xdf-\\xf6\\xf8-\\xff",Et="A-Z\\xc0-\\xd6\\xd8-\\xde",_t="\\ufe0e\\ufe0f",Tt="\\xac\\xb1\\xd7\\xf7"+"\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf"+"\\u2000-\\u206f"+" \\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",It="['’]",bt="["+St+"]",At="["+Tt+"]",Pt="["+vt+"]",Rt="\\d+",Mt="["+Ct+"]",wt="["+yt+"]",Ot="[^"+St+Tt+Rt+Ct+yt+Et+"]",Dt="\\ud83c[\\udffb-\\udfff]",Nt="[^"+St+"]",kt="(?:\\ud83c[\\udde6-\\uddff]){2}",Lt="[\\ud800-\\udbff][\\udc00-\\udfff]",Ft="["+Et+"]",xt="\\u200d",Ut="(?:"+wt+"|"+Ot+")",Vt="(?:"+Ft+"|"+Ot+")",Bt="(?:"+It+"(?:d|ll|m|re|s|t|ve))?",Ht="(?:"+It+"(?:D|LL|M|RE|S|T|VE))?",$t="(?:"+Pt+"|"+Dt+")"+"?",jt="["+_t+"]?",Gt="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",qt="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Wt=jt+$t+("(?:"+xt+"(?:"+[Nt,kt,Lt].join("|")+")"+jt+$t+")*"),zt="(?:"+[Mt,kt,Lt].join("|")+")"+Wt,Kt="(?:"+[Nt+Pt+"?",Pt,kt,Lt,bt].join("|")+")",Jt=RegExp(It,"g"),Yt=RegExp(Pt,"g"),Qt=RegExp(Dt+"(?="+Dt+")|"+Kt+Wt,"g"),Xt=RegExp([Ft+"?"+wt+"+"+Bt+"(?="+[At,Ft,"$"].join("|")+")",Vt+"+"+Ht+"(?="+[At,Ft+Ut,"$"].join("|")+")",Ft+"?"+Ut+"+"+Bt,Ft+"+"+Ht,qt,Gt,Rt,zt].join("|"),"g"),Zt=RegExp("["+xt+St+vt+_t+"]"),ei=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,ti=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],ii=-1,ni={};ni[Me]=ni[we]=ni[Oe]=ni[De]=ni[Ne]=ni[ke]=ni[Le]=ni[Fe]=ni[xe]=!0,ni[se]=ni[ae]=ni[Pe]=ni[le]=ni[Re]=ni[ce]=ni[he]=ni[ue]=ni[pe]=ni[me]=ni[Se]=ni[ye]=ni[Ee]=ni[_e]=ni[be]=!1;var ri={};ri[se]=ri[ae]=ri[Pe]=ri[Re]=ri[le]=ri[ce]=ri[Me]=ri[we]=ri[Oe]=ri[De]=ri[Ne]=ri[pe]=ri[me]=ri[Se]=ri[ye]=ri[Ee]=ri[_e]=ri[Te]=ri[ke]=ri[Le]=ri[Fe]=ri[xe]=!0,ri[he]=ri[ue]=ri[be]=!1;var si={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","Ĳ":"IJ","ĳ":"ij","Œ":"Oe","œ":"oe","ŉ":"'n","ſ":"s"},ai={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},oi={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},li={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},ci=parseFloat,di=parseInt,hi="object"==typeof C&&C&&C.Object===Object&&C,ui="object"==typeof self&&self&&self.Object===Object&&self,gi=hi||ui||Function("return this")(),pi=f&&!f.nodeType&&f,mi=pi&&g&&!g.nodeType&&g,fi=mi&&mi.exports===pi,Si=fi&&hi.process,vi=function(){try{var g=mi&&mi.require&&mi.require("util").types;return g||Si&&Si.binding&&Si.binding("util")}catch(g){}}(),Ci=vi&&vi.isArrayBuffer,yi=vi&&vi.isDate,Ei=vi&&vi.isMap,_i=vi&&vi.isRegExp,Ti=vi&&vi.isSet,Ii=vi&&vi.isTypedArray;function apply(g,f,S){switch(S.length){case 0:return g.call(f);case 1:return g.call(f,S[0]);case 2:return g.call(f,S[0],S[1]);case 3:return g.call(f,S[0],S[1],S[2])}return g.apply(f,S)}function arrayAggregator(g,f,S,v){for(var C=-1,_=null==g?0:g.length;++C<_;){var T=g[C];f(v,T,S(T),g)}return v}function arrayEach(g,f){for(var S=-1,v=null==g?0:g.length;++S<v&&!1!==f(g[S],S,g););return g}function arrayEachRight(g,f){for(var S=null==g?0:g.length;S--&&!1!==f(g[S],S,g););return g}function arrayEvery(g,f){for(var S=-1,v=null==g?0:g.length;++S<v;)if(!f(g[S],S,g))return!1;return!0}function arrayFilter(g,f){for(var S=-1,v=null==g?0:g.length,C=0,_=[];++S<v;){var T=g[S];f(T,S,g)&&(_[C++]=T)}return _}function arrayIncludes(g,f){return!!(null==g?0:g.length)&&baseIndexOf(g,f,0)>-1}function arrayIncludesWith(g,f,S){for(var v=-1,C=null==g?0:g.length;++v<C;)if(S(f,g[v]))return!0;return!1}function arrayMap(g,f){for(var S=-1,v=null==g?0:g.length,C=Array(v);++S<v;)C[S]=f(g[S],S,g);return C}function arrayPush(g,f){for(var S=-1,v=f.length,C=g.length;++S<v;)g[C+S]=f[S];return g}function arrayReduce(g,f,S,v){var C=-1,_=null==g?0:g.length;for(v&&_&&(S=g[++C]);++C<_;)S=f(S,g[C],C,g);return S}function arrayReduceRight(g,f,S,v){var C=null==g?0:g.length;for(v&&C&&(S=g[--C]);C--;)S=f(S,g[C],C,g);return S}function arraySome(g,f){for(var S=-1,v=null==g?0:g.length;++S<v;)if(f(g[S],S,g))return!0;return!1}var bi=baseProperty("length");function asciiToArray(g){return g.split("")}function asciiWords(g){return g.match(rt)||[]}function baseFindKey(g,f,S){var v;return S(g,(function(g,S,C){if(f(g,S,C))return v=S,!1})),v}function baseFindIndex(g,f,S,v){for(var C=g.length,_=S+(v?1:-1);v?_--:++_<C;)if(f(g[_],_,g))return _;return-1}function baseIndexOf(g,f,S){return f==f?strictIndexOf(g,f,S):baseFindIndex(g,baseIsNaN,S)}function baseIndexOfWith(g,f,S,v){for(var C=S-1,_=g.length;++C<_;)if(v(g[C],f))return C;return-1}function baseIsNaN(g){return g!=g}function baseMean(g,f){var S=null==g?0:g.length;return S?baseSum(g,f)/S:ee}function baseProperty(g){return function(f){return null==f?S:f[g]}}function basePropertyOf(g){return function(f){return null==g?S:g[f]}}function baseReduce(g,f,S,v,C){return C(g,(function(g,C,_){S=v?(v=!1,g):f(S,g,C,_)})),S}function baseSortBy(g,f){var S=g.length;for(g.sort(f);S--;)g[S]=g[S].value;return g}function baseSum(g,f){for(var v,C=-1,_=g.length;++C<_;){var T=f(g[C]);T!==S&&(v=v===S?T:v+T)}return v}function baseTimes(g,f){for(var S=-1,v=Array(g);++S<g;)v[S]=f(S);return v}function baseToPairs(g,f){return arrayMap(f,(function(f){return[f,g[f]]}))}function baseTrim(g){return g?g.slice(0,trimmedEndIndex(g)+1).replace(Ze,""):g}function baseUnary(g){return function(f){return g(f)}}function baseValues(g,f){return arrayMap(f,(function(f){return g[f]}))}function cacheHas(g,f){return g.has(f)}function charsStartIndex(g,f){for(var S=-1,v=g.length;++S<v&&baseIndexOf(f,g[S],0)>-1;);return S}function charsEndIndex(g,f){for(var S=g.length;S--&&baseIndexOf(f,g[S],0)>-1;);return S}function countHolders(g,f){for(var S=g.length,v=0;S--;)g[S]===f&&++v;return v}var Ai=basePropertyOf(si),Pi=basePropertyOf(ai);function escapeStringChar(g){return"\\"+li[g]}function getValue(g,f){return null==g?S:g[f]}function hasUnicode(g){return Zt.test(g)}function hasUnicodeWord(g){return ei.test(g)}function iteratorToArray(g){for(var f,S=[];!(f=g.next()).done;)S.push(f.value);return S}function mapToArray(g){var f=-1,S=Array(g.size);return g.forEach((function(g,v){S[++f]=[v,g]})),S}function overArg(g,f){return function(S){return g(f(S))}}function replaceHolders(g,f){for(var S=-1,v=g.length,C=0,_=[];++S<v;){var T=g[S];T!==f&&T!==R||(g[S]=R,_[C++]=S)}return _}function setToArray(g){var f=-1,S=Array(g.size);return g.forEach((function(g){S[++f]=g})),S}function setToPairs(g){var f=-1,S=Array(g.size);return g.forEach((function(g){S[++f]=[g,g]})),S}function strictIndexOf(g,f,S){for(var v=S-1,C=g.length;++v<C;)if(g[v]===f)return v;return-1}function strictLastIndexOf(g,f,S){for(var v=S+1;v--;)if(g[v]===f)return v;return v}function stringSize(g){return hasUnicode(g)?unicodeSize(g):bi(g)}function stringToArray(g){return hasUnicode(g)?unicodeToArray(g):asciiToArray(g)}function trimmedEndIndex(g){for(var f=g.length;f--&&et.test(g.charAt(f)););return f}var Ri=basePropertyOf(oi);function unicodeSize(g){for(var f=Qt.lastIndex=0;Qt.test(g);)++f;return f}function unicodeToArray(g){return g.match(Qt)||[]}function unicodeWords(g){return g.match(Xt)||[]}var Mi=function runInContext(g){var f,C=(g=null==g?gi:wi.defaults(gi.Object(),g,wi.pick(gi,ti))).Array,et=g.Date,rt=g.Error,St=g.Function,vt=g.Math,Ct=g.Object,yt=g.RegExp,Et=g.String,_t=g.TypeError,Tt=C.prototype,It=St.prototype,bt=Ct.prototype,At=g["__core-js_shared__"],Pt=It.toString,Rt=bt.hasOwnProperty,Mt=0,wt=(f=/[^.]+$/.exec(At&&At.keys&&At.keys.IE_PROTO||""))?"Symbol(src)_1."+f:"",Ot=bt.toString,Dt=Pt.call(Ct),Nt=gi._,kt=yt("^"+Pt.call(Rt).replace(Qe,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Lt=fi?g.Buffer:S,Ft=g.Symbol,xt=g.Uint8Array,Ut=Lt?Lt.allocUnsafe:S,Vt=overArg(Ct.getPrototypeOf,Ct),Bt=Ct.create,Ht=bt.propertyIsEnumerable,$t=Tt.splice,jt=Ft?Ft.isConcatSpreadable:S,Gt=Ft?Ft.iterator:S,qt=Ft?Ft.toStringTag:S,Wt=function(){try{var g=getNative(Ct,"defineProperty");return g({},"",{}),g}catch(g){}}(),zt=g.clearTimeout!==gi.clearTimeout&&g.clearTimeout,Kt=et&&et.now!==gi.Date.now&&et.now,Qt=g.setTimeout!==gi.setTimeout&&g.setTimeout,Xt=vt.ceil,Zt=vt.floor,ei=Ct.getOwnPropertySymbols,si=Lt?Lt.isBuffer:S,ai=g.isFinite,oi=Tt.join,li=overArg(Ct.keys,Ct),hi=vt.max,ui=vt.min,pi=et.now,mi=g.parseInt,Si=vt.random,vi=Tt.reverse,bi=getNative(g,"DataView"),Mi=getNative(g,"Map"),Oi=getNative(g,"Promise"),Di=getNative(g,"Set"),Ni=getNative(g,"WeakMap"),ki=getNative(Ct,"create"),Li=Ni&&new Ni,Fi={},xi=toSource(bi),Ui=toSource(Mi),Vi=toSource(Oi),Bi=toSource(Di),Hi=toSource(Ni),$i=Ft?Ft.prototype:S,ji=$i?$i.valueOf:S,Gi=$i?$i.toString:S;function lodash(g){if(isObjectLike(g)&&!Jn(g)&&!(g instanceof LazyWrapper)){if(g instanceof LodashWrapper)return g;if(Rt.call(g,"__wrapped__"))return wrapperClone(g)}return new LodashWrapper(g)}var qi=function(){function object(){}return function(g){if(!isObject(g))return{};if(Bt)return Bt(g);object.prototype=g;var f=new object;return object.prototype=S,f}}();function baseLodash(){}function LodashWrapper(g,f){this.__wrapped__=g,this.__actions__=[],this.__chain__=!!f,this.__index__=0,this.__values__=S}function LazyWrapper(g){this.__wrapped__=g,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=te,this.__views__=[]}function lazyClone(){var g=new LazyWrapper(this.__wrapped__);return g.__actions__=copyArray(this.__actions__),g.__dir__=this.__dir__,g.__filtered__=this.__filtered__,g.__iteratees__=copyArray(this.__iteratees__),g.__takeCount__=this.__takeCount__,g.__views__=copyArray(this.__views__),g}function lazyReverse(){if(this.__filtered__){var g=new LazyWrapper(this);g.__dir__=-1,g.__filtered__=!0}else(g=this.clone()).__dir__*=-1;return g}function lazyValue(){var g=this.__wrapped__.value(),f=this.__dir__,S=Jn(g),v=f<0,C=S?g.length:0,_=getView(0,C,this.__views__),T=_.start,I=_.end,b=I-T,A=v?I:T-1,P=this.__iteratees__,R=P.length,M=0,w=ui(b,this.__takeCount__);if(!S||!v&&C==b&&w==b)return baseWrapperValue(g,this.__actions__);var O=[];e:for(;b--&&M<w;){for(var D=-1,N=g[A+=f];++D<R;){var k=P[D],L=k.iteratee,F=k.type,x=L(N);if(F==J)N=x;else if(!x){if(F==K)continue e;break e}}O[M++]=N}return O}function Hash(g){var f=-1,S=null==g?0:g.length;for(this.clear();++f<S;){var v=g[f];this.set(v[0],v[1])}}function hashClear(){this.__data__=ki?ki(null):{},this.size=0}function hashDelete(g){var f=this.has(g)&&delete this.__data__[g];return this.size-=f?1:0,f}function hashGet(g){var f=this.__data__;if(ki){var v=f[g];return v===A?S:v}return Rt.call(f,g)?f[g]:S}function hashHas(g){var f=this.__data__;return ki?f[g]!==S:Rt.call(f,g)}function hashSet(g,f){var v=this.__data__;return this.size+=this.has(g)?0:1,v[g]=ki&&f===S?A:f,this}function ListCache(g){var f=-1,S=null==g?0:g.length;for(this.clear();++f<S;){var v=g[f];this.set(v[0],v[1])}}function listCacheClear(){this.__data__=[],this.size=0}function listCacheDelete(g){var f=this.__data__,S=assocIndexOf(f,g);return!(S<0)&&(S==f.length-1?f.pop():$t.call(f,S,1),--this.size,!0)}function listCacheGet(g){var f=this.__data__,v=assocIndexOf(f,g);return v<0?S:f[v][1]}function listCacheHas(g){return assocIndexOf(this.__data__,g)>-1}function listCacheSet(g,f){var S=this.__data__,v=assocIndexOf(S,g);return v<0?(++this.size,S.push([g,f])):S[v][1]=f,this}function MapCache(g){var f=-1,S=null==g?0:g.length;for(this.clear();++f<S;){var v=g[f];this.set(v[0],v[1])}}function mapCacheClear(){this.size=0,this.__data__={hash:new Hash,map:new(Mi||ListCache),string:new Hash}}function mapCacheDelete(g){var f=getMapData(this,g).delete(g);return this.size-=f?1:0,f}function mapCacheGet(g){return getMapData(this,g).get(g)}function mapCacheHas(g){return getMapData(this,g).has(g)}function mapCacheSet(g,f){var S=getMapData(this,g),v=S.size;return S.set(g,f),this.size+=S.size==v?0:1,this}function SetCache(g){var f=-1,S=null==g?0:g.length;for(this.__data__=new MapCache;++f<S;)this.add(g[f])}function setCacheAdd(g){return this.__data__.set(g,A),this}function setCacheHas(g){return this.__data__.has(g)}function Stack(g){var f=this.__data__=new ListCache(g);this.size=f.size}function stackClear(){this.__data__=new ListCache,this.size=0}function stackDelete(g){var f=this.__data__,S=f.delete(g);return this.size=f.size,S}function stackGet(g){return this.__data__.get(g)}function stackHas(g){return this.__data__.has(g)}function stackSet(g,f){var S=this.__data__;if(S instanceof ListCache){var v=S.__data__;if(!Mi||v.length<_-1)return v.push([g,f]),this.size=++S.size,this;S=this.__data__=new MapCache(v)}return S.set(g,f),this.size=S.size,this}function arrayLikeKeys(g,f){var S=Jn(g),v=!S&&Kn(g),C=!S&&!v&&Qn(g),_=!S&&!v&&!C&&ir(g),T=S||v||C||_,I=T?baseTimes(g.length,Et):[],b=I.length;for(var A in g)!f&&!Rt.call(g,A)||T&&("length"==A||C&&("offset"==A||"parent"==A)||_&&("buffer"==A||"byteLength"==A||"byteOffset"==A)||isIndex(A,b))||I.push(A);return I}function arraySample(g){var f=g.length;return f?g[baseRandom(0,f-1)]:S}function arraySampleSize(g,f){return shuffleSelf(copyArray(g),baseClamp(f,0,g.length))}function arrayShuffle(g){return shuffleSelf(copyArray(g))}function assignMergeValue(g,f,v){(v!==S&&!eq(g[f],v)||v===S&&!(f in g))&&baseAssignValue(g,f,v)}function assignValue(g,f,v){var C=g[f];Rt.call(g,f)&&eq(C,v)&&(v!==S||f in g)||baseAssignValue(g,f,v)}function assocIndexOf(g,f){for(var S=g.length;S--;)if(eq(g[S][0],f))return S;return-1}function baseAggregator(g,f,S,v){return Wi(g,(function(g,C,_){f(v,g,S(g),_)})),v}function baseAssign(g,f){return g&&copyObject(f,keys(f),g)}function baseAssignIn(g,f){return g&&copyObject(f,keysIn(f),g)}function baseAssignValue(g,f,S){"__proto__"==f&&Wt?Wt(g,f,{configurable:!0,enumerable:!0,value:S,writable:!0}):g[f]=S}function baseAt(g,f){for(var v=-1,_=f.length,T=C(_),I=null==g;++v<_;)T[v]=I?S:get(g,f[v]);return T}function baseClamp(g,f,v){return g==g&&(v!==S&&(g=g<=v?g:v),f!==S&&(g=g>=f?g:f)),g}function baseClone(g,f,v,C,_,T){var I,b=f&M,A=f&w,P=f&O;if(v&&(I=_?v(g,C,_,T):v(g)),I!==S)return I;if(!isObject(g))return g;var R=Jn(g);if(R){if(I=initCloneArray(g),!b)return copyArray(g,I)}else{var D=sn(g),N=D==ue||D==ge;if(Qn(g))return cloneBuffer(g,b);if(D==Se||D==se||N&&!_){if(I=A||N?{}:initCloneObject(g),!b)return A?copySymbolsIn(g,baseAssignIn(I,g)):copySymbols(g,baseAssign(I,g))}else{if(!ri[D])return _?g:{};I=initCloneByTag(g,D,b)}}T||(T=new Stack);var k=T.get(g);if(k)return k;T.set(g,I),tr(g)?g.forEach((function(S){I.add(baseClone(S,f,v,S,g,T))})):Zn(g)&&g.forEach((function(S,C){I.set(C,baseClone(S,f,v,C,g,T))}));var L=R?S:(P?A?getAllKeysIn:getAllKeys:A?keysIn:keys)(g);return arrayEach(L||g,(function(S,C){L&&(S=g[C=S]),assignValue(I,C,baseClone(S,f,v,C,g,T))})),I}function baseConforms(g){var f=keys(g);return function(S){return baseConformsTo(S,g,f)}}function baseConformsTo(g,f,v){var C=v.length;if(null==g)return!C;for(g=Ct(g);C--;){var _=v[C],T=f[_],I=g[_];if(I===S&&!(_ in g)||!T(I))return!1}return!0}function baseDelay(g,f,v){if("function"!=typeof g)throw new _t(I);return ln((function(){g.apply(S,v)}),f)}function baseDifference(g,f,S,v){var C=-1,T=arrayIncludes,I=!0,b=g.length,A=[],P=f.length;if(!b)return A;S&&(f=arrayMap(f,baseUnary(S))),v?(T=arrayIncludesWith,I=!1):f.length>=_&&(T=cacheHas,I=!1,f=new SetCache(f));e:for(;++C<b;){var R=g[C],M=null==S?R:S(R);if(R=v||0!==R?R:0,I&&M==M){for(var w=P;w--;)if(f[w]===M)continue e;A.push(R)}else T(f,M,v)||A.push(R)}return A}lodash.templateSettings={escape:qe,evaluate:We,interpolate:ze,variable:"",imports:{_:lodash}},lodash.prototype=baseLodash.prototype,lodash.prototype.constructor=lodash,LodashWrapper.prototype=qi(baseLodash.prototype),LodashWrapper.prototype.constructor=LodashWrapper,LazyWrapper.prototype=qi(baseLodash.prototype),LazyWrapper.prototype.constructor=LazyWrapper,Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var Wi=createBaseEach(baseForOwn),zi=createBaseEach(baseForOwnRight,!0);function baseEvery(g,f){var S=!0;return Wi(g,(function(g,v,C){return S=!!f(g,v,C)})),S}function baseExtremum(g,f,v){for(var C=-1,_=g.length;++C<_;){var T=g[C],I=f(T);if(null!=I&&(b===S?I==I&&!isSymbol(I):v(I,b)))var b=I,A=T}return A}function baseFill(g,f,v,C){var _=g.length;for((v=toInteger(v))<0&&(v=-v>_?0:_+v),(C=C===S||C>_?_:toInteger(C))<0&&(C+=_),C=v>C?0:toLength(C);v<C;)g[v++]=f;return g}function baseFilter(g,f){var S=[];return Wi(g,(function(g,v,C){f(g,v,C)&&S.push(g)})),S}function baseFlatten(g,f,S,v,C){var _=-1,T=g.length;for(S||(S=isFlattenable),C||(C=[]);++_<T;){var I=g[_];f>0&&S(I)?f>1?baseFlatten(I,f-1,S,v,C):arrayPush(C,I):v||(C[C.length]=I)}return C}var Ki=createBaseFor(),Ji=createBaseFor(!0);function baseForOwn(g,f){return g&&Ki(g,f,keys)}function baseForOwnRight(g,f){return g&&Ji(g,f,keys)}function baseFunctions(g,f){return arrayFilter(f,(function(f){return isFunction(g[f])}))}function baseGet(g,f){for(var v=0,C=(f=castPath(f,g)).length;null!=g&&v<C;)g=g[toKey(f[v++])];return v&&v==C?g:S}function baseGetAllKeys(g,f,S){var v=f(g);return Jn(g)?v:arrayPush(v,S(g))}function baseGetTag(g){return null==g?g===S?Ie:fe:qt&&qt in Ct(g)?getRawTag(g):objectToString(g)}function baseGt(g,f){return g>f}function baseHas(g,f){return null!=g&&Rt.call(g,f)}function baseHasIn(g,f){return null!=g&&f in Ct(g)}function baseInRange(g,f,S){return g>=ui(f,S)&&g<hi(f,S)}function baseIntersection(g,f,v){for(var _=v?arrayIncludesWith:arrayIncludes,T=g[0].length,I=g.length,b=I,A=C(I),P=1/0,R=[];b--;){var M=g[b];b&&f&&(M=arrayMap(M,baseUnary(f))),P=ui(M.length,P),A[b]=!v&&(f||T>=120&&M.length>=120)?new SetCache(b&&M):S}M=g[0];var w=-1,O=A[0];e:for(;++w<T&&R.length<P;){var D=M[w],N=f?f(D):D;if(D=v||0!==D?D:0,!(O?cacheHas(O,N):_(R,N,v))){for(b=I;--b;){var k=A[b];if(!(k?cacheHas(k,N):_(g[b],N,v)))continue e}O&&O.push(N),R.push(D)}}return R}function baseInverter(g,f,S,v){return baseForOwn(g,(function(g,C,_){f(v,S(g),C,_)})),v}function baseInvoke(g,f,v){var C=null==(g=parent(g,f=castPath(f,g)))?g:g[toKey(last(f))];return null==C?S:apply(C,g,v)}function baseIsArguments(g){return isObjectLike(g)&&baseGetTag(g)==se}function baseIsArrayBuffer(g){return isObjectLike(g)&&baseGetTag(g)==Pe}function baseIsDate(g){return isObjectLike(g)&&baseGetTag(g)==ce}function baseIsEqual(g,f,S,v,C){return g===f||(null==g||null==f||!isObjectLike(g)&&!isObjectLike(f)?g!=g&&f!=f:baseIsEqualDeep(g,f,S,v,baseIsEqual,C))}function baseIsEqualDeep(g,f,S,v,C,_){var T=Jn(g),I=Jn(f),b=T?ae:sn(g),A=I?ae:sn(f),P=(b=b==se?Se:b)==Se,R=(A=A==se?Se:A)==Se,M=b==A;if(M&&Qn(g)){if(!Qn(f))return!1;T=!0,P=!1}if(M&&!P)return _||(_=new Stack),T||ir(g)?equalArrays(g,f,S,v,C,_):equalByTag(g,f,b,S,v,C,_);if(!(S&D)){var w=P&&Rt.call(g,"__wrapped__"),O=R&&Rt.call(f,"__wrapped__");if(w||O){var N=w?g.value():g,k=O?f.value():f;return _||(_=new Stack),C(N,k,S,v,_)}}return!!M&&(_||(_=new Stack),equalObjects(g,f,S,v,C,_))}function baseIsMap(g){return isObjectLike(g)&&sn(g)==pe}function baseIsMatch(g,f,v,C){var _=v.length,T=_,I=!C;if(null==g)return!T;for(g=Ct(g);_--;){var b=v[_];if(I&&b[2]?b[1]!==g[b[0]]:!(b[0]in g))return!1}for(;++_<T;){var A=(b=v[_])[0],P=g[A],R=b[1];if(I&&b[2]){if(P===S&&!(A in g))return!1}else{var M=new Stack;if(C)var w=C(P,R,A,g,f,M);if(!(w===S?baseIsEqual(R,P,D|N,C,M):w))return!1}}return!0}function baseIsNative(g){return!(!isObject(g)||isMasked(g))&&(isFunction(g)?kt:ht).test(toSource(g))}function baseIsRegExp(g){return isObjectLike(g)&&baseGetTag(g)==ye}function baseIsSet(g){return isObjectLike(g)&&sn(g)==Ee}function baseIsTypedArray(g){return isObjectLike(g)&&isLength(g.length)&&!!ni[baseGetTag(g)]}function baseIteratee(g){return"function"==typeof g?g:null==g?identity:"object"==typeof g?Jn(g)?baseMatchesProperty(g[0],g[1]):baseMatches(g):property(g)}function baseKeys(g){if(!isPrototype(g))return li(g);var f=[];for(var S in Ct(g))Rt.call(g,S)&&"constructor"!=S&&f.push(S);return f}function baseKeysIn(g){if(!isObject(g))return nativeKeysIn(g);var f=isPrototype(g),S=[];for(var v in g)("constructor"!=v||!f&&Rt.call(g,v))&&S.push(v);return S}function baseLt(g,f){return g<f}function baseMap(g,f){var S=-1,v=isArrayLike(g)?C(g.length):[];return Wi(g,(function(g,C,_){v[++S]=f(g,C,_)})),v}function baseMatches(g){var f=getMatchData(g);return 1==f.length&&f[0][2]?matchesStrictComparable(f[0][0],f[0][1]):function(S){return S===g||baseIsMatch(S,g,f)}}function baseMatchesProperty(g,f){return isKey(g)&&isStrictComparable(f)?matchesStrictComparable(toKey(g),f):function(v){var C=get(v,g);return C===S&&C===f?hasIn(v,g):baseIsEqual(f,C,D|N)}}function baseMerge(g,f,v,C,_){g!==f&&Ki(f,(function(T,I){if(_||(_=new Stack),isObject(T))baseMergeDeep(g,f,I,v,baseMerge,C,_);else{var b=C?C(safeGet(g,I),T,I+"",g,f,_):S;b===S&&(b=T),assignMergeValue(g,I,b)}}),keysIn)}function baseMergeDeep(g,f,v,C,_,T,I){var b=safeGet(g,v),A=safeGet(f,v),P=I.get(A);if(P)assignMergeValue(g,v,P);else{var R=T?T(b,A,v+"",g,f,I):S,M=R===S;if(M){var w=Jn(A),O=!w&&Qn(A),D=!w&&!O&&ir(A);R=A,w||O||D?Jn(b)?R=b:isArrayLikeObject(b)?R=copyArray(b):O?(M=!1,R=cloneBuffer(A,!0)):D?(M=!1,R=cloneTypedArray(A,!0)):R=[]:isPlainObject(A)||Kn(A)?(R=b,Kn(b)?R=toPlainObject(b):isObject(b)&&!isFunction(b)||(R=initCloneObject(A))):M=!1}M&&(I.set(A,R),_(R,A,C,T,I),I.delete(A)),assignMergeValue(g,v,R)}}function baseNth(g,f){var v=g.length;if(v)return isIndex(f+=f<0?v:0,v)?g[f]:S}function baseOrderBy(g,f,S){f=f.length?arrayMap(f,(function(g){return Jn(g)?function(f){return baseGet(f,1===g.length?g[0]:g)}:g})):[identity];var v=-1;f=arrayMap(f,baseUnary(getIteratee()));var C=baseMap(g,(function(g,S,C){var _=arrayMap(f,(function(f){return f(g)}));return{criteria:_,index:++v,value:g}}));return baseSortBy(C,(function(g,f){return compareMultiple(g,f,S)}))}function basePick(g,f){return basePickBy(g,f,(function(f,S){return hasIn(g,S)}))}function basePickBy(g,f,S){for(var v=-1,C=f.length,_={};++v<C;){var T=f[v],I=baseGet(g,T);S(I,T)&&baseSet(_,castPath(T,g),I)}return _}function basePropertyDeep(g){return function(f){return baseGet(f,g)}}function basePullAll(g,f,S,v){var C=v?baseIndexOfWith:baseIndexOf,_=-1,T=f.length,I=g;for(g===f&&(f=copyArray(f)),S&&(I=arrayMap(g,baseUnary(S)));++_<T;)for(var b=0,A=f[_],P=S?S(A):A;(b=C(I,P,b,v))>-1;)I!==g&&$t.call(I,b,1),$t.call(g,b,1);return g}function basePullAt(g,f){for(var S=g?f.length:0,v=S-1;S--;){var C=f[S];if(S==v||C!==_){var _=C;isIndex(C)?$t.call(g,C,1):baseUnset(g,C)}}return g}function baseRandom(g,f){return g+Zt(Si()*(f-g+1))}function baseRange(g,f,S,v){for(var _=-1,T=hi(Xt((f-g)/(S||1)),0),I=C(T);T--;)I[v?T:++_]=g,g+=S;return I}function baseRepeat(g,f){var S="";if(!g||f<1||f>X)return S;do{f%2&&(S+=g),(f=Zt(f/2))&&(g+=g)}while(f);return S}function baseRest(g,f){return cn(overRest(g,f,identity),g+"")}function baseSample(g){return arraySample(values(g))}function baseSampleSize(g,f){var S=values(g);return shuffleSelf(S,baseClamp(f,0,S.length))}function baseSet(g,f,v,C){if(!isObject(g))return g;for(var _=-1,T=(f=castPath(f,g)).length,I=T-1,b=g;null!=b&&++_<T;){var A=toKey(f[_]),P=v;if("__proto__"===A||"constructor"===A||"prototype"===A)return g;if(_!=I){var R=b[A];(P=C?C(R,A,b):S)===S&&(P=isObject(R)?R:isIndex(f[_+1])?[]:{})}assignValue(b,A,P),b=b[A]}return g}var Yi=Li?function(g,f){return Li.set(g,f),g}:identity,Qi=Wt?function(g,f){return Wt(g,"toString",{configurable:!0,enumerable:!1,value:constant(f),writable:!0})}:identity;function baseShuffle(g){return shuffleSelf(values(g))}function baseSlice(g,f,S){var v=-1,_=g.length;f<0&&(f=-f>_?0:_+f),(S=S>_?_:S)<0&&(S+=_),_=f>S?0:S-f>>>0,f>>>=0;for(var T=C(_);++v<_;)T[v]=g[v+f];return T}function baseSome(g,f){var S;return Wi(g,(function(g,v,C){return!(S=f(g,v,C))})),!!S}function baseSortedIndex(g,f,S){var v=0,C=null==g?v:g.length;if("number"==typeof f&&f==f&&C<=ne){for(;v<C;){var _=v+C>>>1,T=g[_];null!==T&&!isSymbol(T)&&(S?T<=f:T<f)?v=_+1:C=_}return C}return baseSortedIndexBy(g,f,identity,S)}function baseSortedIndexBy(g,f,v,C){var _=0,T=null==g?0:g.length;if(0===T)return 0;for(var I=(f=v(f))!=f,b=null===f,A=isSymbol(f),P=f===S;_<T;){var R=Zt((_+T)/2),M=v(g[R]),w=M!==S,O=null===M,D=M==M,N=isSymbol(M);if(I)var k=C||D;else k=P?D&&(C||w):b?D&&w&&(C||!O):A?D&&w&&!O&&(C||!N):!O&&!N&&(C?M<=f:M<f);k?_=R+1:T=R}return ui(T,ie)}function baseSortedUniq(g,f){for(var S=-1,v=g.length,C=0,_=[];++S<v;){var T=g[S],I=f?f(T):T;if(!S||!eq(I,b)){var b=I;_[C++]=0===T?0:T}}return _}function baseToNumber(g){return"number"==typeof g?g:isSymbol(g)?ee:+g}function baseToString(g){if("string"==typeof g)return g;if(Jn(g))return arrayMap(g,baseToString)+"";if(isSymbol(g))return Gi?Gi.call(g):"";var f=g+"";return"0"==f&&1/g==-Q?"-0":f}function baseUniq(g,f,S){var v=-1,C=arrayIncludes,T=g.length,I=!0,b=[],A=b;if(S)I=!1,C=arrayIncludesWith;else if(T>=_){var P=f?null:en(g);if(P)return setToArray(P);I=!1,C=cacheHas,A=new SetCache}else A=f?[]:b;e:for(;++v<T;){var R=g[v],M=f?f(R):R;if(R=S||0!==R?R:0,I&&M==M){for(var w=A.length;w--;)if(A[w]===M)continue e;f&&A.push(M),b.push(R)}else C(A,M,S)||(A!==b&&A.push(M),b.push(R))}return b}function baseUnset(g,f){return null==(g=parent(g,f=castPath(f,g)))||delete g[toKey(last(f))]}function baseUpdate(g,f,S,v){return baseSet(g,f,S(baseGet(g,f)),v)}function baseWhile(g,f,S,v){for(var C=g.length,_=v?C:-1;(v?_--:++_<C)&&f(g[_],_,g););return S?baseSlice(g,v?0:_,v?_+1:C):baseSlice(g,v?_+1:0,v?C:_)}function baseWrapperValue(g,f){var S=g;return S instanceof LazyWrapper&&(S=S.value()),arrayReduce(f,(function(g,f){return f.func.apply(f.thisArg,arrayPush([g],f.args))}),S)}function baseXor(g,f,S){var v=g.length;if(v<2)return v?baseUniq(g[0]):[];for(var _=-1,T=C(v);++_<v;)for(var I=g[_],b=-1;++b<v;)b!=_&&(T[_]=baseDifference(T[_]||I,g[b],f,S));return baseUniq(baseFlatten(T,1),f,S)}function baseZipObject(g,f,v){for(var C=-1,_=g.length,T=f.length,I={};++C<_;){var b=C<T?f[C]:S;v(I,g[C],b)}return I}function castArrayLikeObject(g){return isArrayLikeObject(g)?g:[]}function castFunction(g){return"function"==typeof g?g:identity}function castPath(g,f){return Jn(g)?g:isKey(g,f)?[g]:dn(toString(g))}var Xi=baseRest;function castSlice(g,f,v){var C=g.length;return v=v===S?C:v,!f&&v>=C?g:baseSlice(g,f,v)}var Zi=zt||function(g){return gi.clearTimeout(g)};function cloneBuffer(g,f){if(f)return g.slice();var S=g.length,v=Ut?Ut(S):new g.constructor(S);return g.copy(v),v}function cloneArrayBuffer(g){var f=new g.constructor(g.byteLength);return new xt(f).set(new xt(g)),f}function cloneDataView(g,f){var S=f?cloneArrayBuffer(g.buffer):g.buffer;return new g.constructor(S,g.byteOffset,g.byteLength)}function cloneRegExp(g){var f=new g.constructor(g.source,lt.exec(g));return f.lastIndex=g.lastIndex,f}function cloneSymbol(g){return ji?Ct(ji.call(g)):{}}function cloneTypedArray(g,f){var S=f?cloneArrayBuffer(g.buffer):g.buffer;return new g.constructor(S,g.byteOffset,g.length)}function compareAscending(g,f){if(g!==f){var v=g!==S,C=null===g,_=g==g,T=isSymbol(g),I=f!==S,b=null===f,A=f==f,P=isSymbol(f);if(!b&&!P&&!T&&g>f||T&&I&&A&&!b&&!P||C&&I&&A||!v&&A||!_)return 1;if(!C&&!T&&!P&&g<f||P&&v&&_&&!C&&!T||b&&v&&_||!I&&_||!A)return-1}return 0}function compareMultiple(g,f,S){for(var v=-1,C=g.criteria,_=f.criteria,T=C.length,I=S.length;++v<T;){var b=compareAscending(C[v],_[v]);if(b)return v>=I?b:b*("desc"==S[v]?-1:1)}return g.index-f.index}function composeArgs(g,f,S,v){for(var _=-1,T=g.length,I=S.length,b=-1,A=f.length,P=hi(T-I,0),R=C(A+P),M=!v;++b<A;)R[b]=f[b];for(;++_<I;)(M||_<T)&&(R[S[_]]=g[_]);for(;P--;)R[b++]=g[_++];return R}function composeArgsRight(g,f,S,v){for(var _=-1,T=g.length,I=-1,b=S.length,A=-1,P=f.length,R=hi(T-b,0),M=C(R+P),w=!v;++_<R;)M[_]=g[_];for(var O=_;++A<P;)M[O+A]=f[A];for(;++I<b;)(w||_<T)&&(M[O+S[I]]=g[_++]);return M}function copyArray(g,f){var S=-1,v=g.length;for(f||(f=C(v));++S<v;)f[S]=g[S];return f}function copyObject(g,f,v,C){var _=!v;v||(v={});for(var T=-1,I=f.length;++T<I;){var b=f[T],A=C?C(v[b],g[b],b,v,g):S;A===S&&(A=g[b]),_?baseAssignValue(v,b,A):assignValue(v,b,A)}return v}function copySymbols(g,f){return copyObject(g,nn(g),f)}function copySymbolsIn(g,f){return copyObject(g,rn(g),f)}function createAggregator(g,f){return function(S,v){var C=Jn(S)?arrayAggregator:baseAggregator,_=f?f():{};return C(S,g,getIteratee(v,2),_)}}function createAssigner(g){return baseRest((function(f,v){var C=-1,_=v.length,T=_>1?v[_-1]:S,I=_>2?v[2]:S;for(T=g.length>3&&"function"==typeof T?(_--,T):S,I&&isIterateeCall(v[0],v[1],I)&&(T=_<3?S:T,_=1),f=Ct(f);++C<_;){var b=v[C];b&&g(f,b,C,T)}return f}))}function createBaseEach(g,f){return function(S,v){if(null==S)return S;if(!isArrayLike(S))return g(S,v);for(var C=S.length,_=f?C:-1,T=Ct(S);(f?_--:++_<C)&&!1!==v(T[_],_,T););return S}}function createBaseFor(g){return function(f,S,v){for(var C=-1,_=Ct(f),T=v(f),I=T.length;I--;){var b=T[g?I:++C];if(!1===S(_[b],b,_))break}return f}}function createBind(g,f,S){var v=f&k,C=createCtor(g);function wrapper(){return(this&&this!==gi&&this instanceof wrapper?C:g).apply(v?S:this,arguments)}return wrapper}function createCaseFirst(g){return function(f){var v=hasUnicode(f=toString(f))?stringToArray(f):S,C=v?v[0]:f.charAt(0),_=v?castSlice(v,1).join(""):f.slice(1);return C[g]()+_}}function createCompounder(g){return function(f){return arrayReduce(words(deburr(f).replace(Jt,"")),g,"")}}function createCtor(g){return function(){var f=arguments;switch(f.length){case 0:return new g;case 1:return new g(f[0]);case 2:return new g(f[0],f[1]);case 3:return new g(f[0],f[1],f[2]);case 4:return new g(f[0],f[1],f[2],f[3]);case 5:return new g(f[0],f[1],f[2],f[3],f[4]);case 6:return new g(f[0],f[1],f[2],f[3],f[4],f[5]);case 7:return new g(f[0],f[1],f[2],f[3],f[4],f[5],f[6])}var S=qi(g.prototype),v=g.apply(S,f);return isObject(v)?v:S}}function createCurry(g,f,v){var _=createCtor(g);function wrapper(){for(var T=arguments.length,I=C(T),b=T,A=getHolder(wrapper);b--;)I[b]=arguments[b];var P=T<3&&I[0]!==A&&I[T-1]!==A?[]:replaceHolders(I,A);return(T-=P.length)<v?createRecurry(g,f,createHybrid,wrapper.placeholder,S,I,P,S,S,v-T):apply(this&&this!==gi&&this instanceof wrapper?_:g,this,I)}return wrapper}function createFind(g){return function(f,v,C){var _=Ct(f);if(!isArrayLike(f)){var T=getIteratee(v,3);f=keys(f),v=function(g){return T(_[g],g,_)}}var I=g(f,v,C);return I>-1?_[T?f[I]:I]:S}}function createFlow(g){return flatRest((function(f){var v=f.length,C=v,_=LodashWrapper.prototype.thru;for(g&&f.reverse();C--;){var T=f[C];if("function"!=typeof T)throw new _t(I);if(_&&!b&&"wrapper"==getFuncName(T))var b=new LodashWrapper([],!0)}for(C=b?C:v;++C<v;){var A=getFuncName(T=f[C]),P="wrapper"==A?tn(T):S;b=P&&isLaziable(P[0])&&P[1]==(H|x|V|$)&&!P[4].length&&1==P[9]?b[getFuncName(P[0])].apply(b,P[3]):1==T.length&&isLaziable(T)?b[A]():b.thru(T)}return function(){var g=arguments,S=g[0];if(b&&1==g.length&&Jn(S))return b.plant(S).value();for(var C=0,_=v?f[C].apply(this,g):S;++C<v;)_=f[C].call(this,_);return _}}))}function createHybrid(g,f,v,_,T,I,b,A,P,R){var M=f&H,w=f&k,O=f&L,D=f&(x|U),N=f&j,F=O?S:createCtor(g);function wrapper(){for(var S=arguments.length,k=C(S),L=S;L--;)k[L]=arguments[L];if(D)var x=getHolder(wrapper),U=countHolders(k,x);if(_&&(k=composeArgs(k,_,T,D)),I&&(k=composeArgsRight(k,I,b,D)),S-=U,D&&S<R){var V=replaceHolders(k,x);return createRecurry(g,f,createHybrid,wrapper.placeholder,v,k,V,A,P,R-S)}var B=w?v:this,H=O?B[g]:g;return S=k.length,A?k=reorder(k,A):N&&S>1&&k.reverse(),M&&P<S&&(k.length=P),this&&this!==gi&&this instanceof wrapper&&(H=F||createCtor(H)),H.apply(B,k)}return wrapper}function createInverter(g,f){return function(S,v){return baseInverter(S,g,f(v),{})}}function createMathOperation(g,f){return function(v,C){var _;if(v===S&&C===S)return f;if(v!==S&&(_=v),C!==S){if(_===S)return C;"string"==typeof v||"string"==typeof C?(v=baseToString(v),C=baseToString(C)):(v=baseToNumber(v),C=baseToNumber(C)),_=g(v,C)}return _}}function createOver(g){return flatRest((function(f){return f=arrayMap(f,baseUnary(getIteratee())),baseRest((function(S){var v=this;return g(f,(function(g){return apply(g,v,S)}))}))}))}function createPadding(g,f){var v=(f=f===S?" ":baseToString(f)).length;if(v<2)return v?baseRepeat(f,g):f;var C=baseRepeat(f,Xt(g/stringSize(f)));return hasUnicode(f)?castSlice(stringToArray(C),0,g).join(""):C.slice(0,g)}function createPartial(g,f,S,v){var _=f&k,T=createCtor(g);function wrapper(){for(var f=-1,I=arguments.length,b=-1,A=v.length,P=C(A+I),R=this&&this!==gi&&this instanceof wrapper?T:g;++b<A;)P[b]=v[b];for(;I--;)P[b++]=arguments[++f];return apply(R,_?S:this,P)}return wrapper}function createRange(g){return function(f,v,C){return C&&"number"!=typeof C&&isIterateeCall(f,v,C)&&(v=C=S),f=toFinite(f),v===S?(v=f,f=0):v=toFinite(v),baseRange(f,v,C=C===S?f<v?1:-1:toFinite(C),g)}}function createRelationalOperation(g){return function(f,S){return"string"==typeof f&&"string"==typeof S||(f=toNumber(f),S=toNumber(S)),g(f,S)}}function createRecurry(g,f,v,C,_,T,I,b,A,P){var R=f&x;f|=R?V:B,(f&=~(R?B:V))&F||(f&=~(k|L));var M=[g,f,_,R?T:S,R?I:S,R?S:T,R?S:I,b,A,P],w=v.apply(S,M);return isLaziable(g)&&on(w,M),w.placeholder=C,setWrapToString(w,g,f)}function createRound(g){var f=vt[g];return function(g,S){if(g=toNumber(g),(S=null==S?0:ui(toInteger(S),292))&&ai(g)){var v=(toString(g)+"e").split("e");return+((v=(toString(f(v[0]+"e"+(+v[1]+S)))+"e").split("e"))[0]+"e"+(+v[1]-S))}return f(g)}}var en=Di&&1/setToArray(new Di([,-0]))[1]==Q?function(g){return new Di(g)}:noop;function createToPairs(g){return function(f){var S=sn(f);return S==pe?mapToArray(f):S==Ee?setToPairs(f):baseToPairs(f,g(f))}}function createWrap(g,f,v,C,_,T,b,A){var P=f&L;if(!P&&"function"!=typeof g)throw new _t(I);var R=C?C.length:0;if(R||(f&=~(V|B),C=_=S),b=b===S?b:hi(toInteger(b),0),A=A===S?A:toInteger(A),R-=_?_.length:0,f&B){var M=C,w=_;C=_=S}var O=P?S:tn(g),D=[g,f,v,C,_,M,w,T,b,A];if(O&&mergeData(D,O),g=D[0],f=D[1],v=D[2],C=D[3],_=D[4],!(A=D[9]=D[9]===S?P?0:g.length:hi(D[9]-R,0))&&f&(x|U)&&(f&=~(x|U)),f&&f!=k)N=f==x||f==U?createCurry(g,f,A):f!=V&&f!=(k|V)||_.length?createHybrid.apply(S,D):createPartial(g,f,v,C);else var N=createBind(g,f,v);return setWrapToString((O?Yi:on)(N,D),g,f)}function customDefaultsAssignIn(g,f,v,C){return g===S||eq(g,bt[v])&&!Rt.call(C,v)?f:g}function customDefaultsMerge(g,f,v,C,_,T){return isObject(g)&&isObject(f)&&(T.set(f,g),baseMerge(g,f,S,customDefaultsMerge,T),T.delete(f)),g}function customOmitClone(g){return isPlainObject(g)?S:g}function equalArrays(g,f,v,C,_,T){var I=v&D,b=g.length,A=f.length;if(b!=A&&!(I&&A>b))return!1;var P=T.get(g),R=T.get(f);if(P&&R)return P==f&&R==g;var M=-1,w=!0,O=v&N?new SetCache:S;for(T.set(g,f),T.set(f,g);++M<b;){var k=g[M],L=f[M];if(C)var F=I?C(L,k,M,f,g,T):C(k,L,M,g,f,T);if(F!==S){if(F)continue;w=!1;break}if(O){if(!arraySome(f,(function(g,f){if(!cacheHas(O,f)&&(k===g||_(k,g,v,C,T)))return O.push(f)}))){w=!1;break}}else if(k!==L&&!_(k,L,v,C,T)){w=!1;break}}return T.delete(g),T.delete(f),w}function equalByTag(g,f,S,v,C,_,T){switch(S){case Re:if(g.byteLength!=f.byteLength||g.byteOffset!=f.byteOffset)return!1;g=g.buffer,f=f.buffer;case Pe:return!(g.byteLength!=f.byteLength||!_(new xt(g),new xt(f)));case le:case ce:case me:return eq(+g,+f);case he:return g.name==f.name&&g.message==f.message;case ye:case _e:return g==f+"";case pe:var I=mapToArray;case Ee:var b=v&D;if(I||(I=setToArray),g.size!=f.size&&!b)return!1;var A=T.get(g);if(A)return A==f;v|=N,T.set(g,f);var P=equalArrays(I(g),I(f),v,C,_,T);return T.delete(g),P;case Te:if(ji)return ji.call(g)==ji.call(f)}return!1}function equalObjects(g,f,v,C,_,T){var I=v&D,b=getAllKeys(g),A=b.length;if(A!=getAllKeys(f).length&&!I)return!1;for(var P=A;P--;){var R=b[P];if(!(I?R in f:Rt.call(f,R)))return!1}var M=T.get(g),w=T.get(f);if(M&&w)return M==f&&w==g;var O=!0;T.set(g,f),T.set(f,g);for(var N=I;++P<A;){var k=g[R=b[P]],L=f[R];if(C)var F=I?C(L,k,R,f,g,T):C(k,L,R,g,f,T);if(!(F===S?k===L||_(k,L,v,C,T):F)){O=!1;break}N||(N="constructor"==R)}if(O&&!N){var x=g.constructor,U=f.constructor;x==U||!("constructor"in g)||!("constructor"in f)||"function"==typeof x&&x instanceof x&&"function"==typeof U&&U instanceof U||(O=!1)}return T.delete(g),T.delete(f),O}function flatRest(g){return cn(overRest(g,S,flatten),g+"")}function getAllKeys(g){return baseGetAllKeys(g,keys,nn)}function getAllKeysIn(g){return baseGetAllKeys(g,keysIn,rn)}var tn=Li?function(g){return Li.get(g)}:noop;function getFuncName(g){for(var f=g.name+"",S=Fi[f],v=Rt.call(Fi,f)?S.length:0;v--;){var C=S[v],_=C.func;if(null==_||_==g)return C.name}return f}function getHolder(g){return(Rt.call(lodash,"placeholder")?lodash:g).placeholder}function getIteratee(){var g=lodash.iteratee||iteratee;return g=g===iteratee?baseIteratee:g,arguments.length?g(arguments[0],arguments[1]):g}function getMapData(g,f){var S=g.__data__;return isKeyable(f)?S["string"==typeof f?"string":"hash"]:S.map}function getMatchData(g){for(var f=keys(g),S=f.length;S--;){var v=f[S],C=g[v];f[S]=[v,C,isStrictComparable(C)]}return f}function getNative(g,f){var v=getValue(g,f);return baseIsNative(v)?v:S}function getRawTag(g){var f=Rt.call(g,qt),v=g[qt];try{g[qt]=S;var C=!0}catch(g){}var _=Ot.call(g);return C&&(f?g[qt]=v:delete g[qt]),_}var nn=ei?function(g){return null==g?[]:(g=Ct(g),arrayFilter(ei(g),(function(f){return Ht.call(g,f)})))}:stubArray,rn=ei?function(g){for(var f=[];g;)arrayPush(f,nn(g)),g=Vt(g);return f}:stubArray,sn=baseGetTag;function getView(g,f,S){for(var v=-1,C=S.length;++v<C;){var _=S[v],T=_.size;switch(_.type){case"drop":g+=T;break;case"dropRight":f-=T;break;case"take":f=ui(f,g+T);break;case"takeRight":g=hi(g,f-T)}}return{start:g,end:f}}function getWrapDetails(g){var f=g.match(it);return f?f[1].split(nt):[]}function hasPath(g,f,S){for(var v=-1,C=(f=castPath(f,g)).length,_=!1;++v<C;){var T=toKey(f[v]);if(!(_=null!=g&&S(g,T)))break;g=g[T]}return _||++v!=C?_:!!(C=null==g?0:g.length)&&isLength(C)&&isIndex(T,C)&&(Jn(g)||Kn(g))}function initCloneArray(g){var f=g.length,S=new g.constructor(f);return f&&"string"==typeof g[0]&&Rt.call(g,"index")&&(S.index=g.index,S.input=g.input),S}function initCloneObject(g){return"function"!=typeof g.constructor||isPrototype(g)?{}:qi(Vt(g))}function initCloneByTag(g,f,S){var v=g.constructor;switch(f){case Pe:return cloneArrayBuffer(g);case le:case ce:return new v(+g);case Re:return cloneDataView(g,S);case Me:case we:case Oe:case De:case Ne:case ke:case Le:case Fe:case xe:return cloneTypedArray(g,S);case pe:return new v;case me:case _e:return new v(g);case ye:return cloneRegExp(g);case Ee:return new v;case Te:return cloneSymbol(g)}}function insertWrapDetails(g,f){var S=f.length;if(!S)return g;var v=S-1;return f[v]=(S>1?"& ":"")+f[v],f=f.join(S>2?", ":" "),g.replace(tt,"{\n/* [wrapped with "+f+"] */\n")}function isFlattenable(g){return Jn(g)||Kn(g)||!!(jt&&g&&g[jt])}function isIndex(g,f){var S=typeof g;return!!(f=null==f?X:f)&&("number"==S||"symbol"!=S&&gt.test(g))&&g>-1&&g%1==0&&g<f}function isIterateeCall(g,f,S){if(!isObject(S))return!1;var v=typeof f;return!!("number"==v?isArrayLike(S)&&isIndex(f,S.length):"string"==v&&f in S)&&eq(S[f],g)}function isKey(g,f){if(Jn(g))return!1;var S=typeof g;return!("number"!=S&&"symbol"!=S&&"boolean"!=S&&null!=g&&!isSymbol(g))||(Je.test(g)||!Ke.test(g)||null!=f&&g in Ct(f))}function isKeyable(g){var f=typeof g;return"string"==f||"number"==f||"symbol"==f||"boolean"==f?"__proto__"!==g:null===g}function isLaziable(g){var f=getFuncName(g),S=lodash[f];if("function"!=typeof S||!(f in LazyWrapper.prototype))return!1;if(g===S)return!0;var v=tn(S);return!!v&&g===v[0]}function isMasked(g){return!!wt&&wt in g}(bi&&sn(new bi(new ArrayBuffer(1)))!=Re||Mi&&sn(new Mi)!=pe||Oi&&sn(Oi.resolve())!=ve||Di&&sn(new Di)!=Ee||Ni&&sn(new Ni)!=be)&&(sn=function(g){var f=baseGetTag(g),v=f==Se?g.constructor:S,C=v?toSource(v):"";if(C)switch(C){case xi:return Re;case Ui:return pe;case Vi:return ve;case Bi:return Ee;case Hi:return be}return f});var an=At?isFunction:stubFalse;function isPrototype(g){var f=g&&g.constructor;return g===("function"==typeof f&&f.prototype||bt)}function isStrictComparable(g){return g==g&&!isObject(g)}function matchesStrictComparable(g,f){return function(v){return null!=v&&(v[g]===f&&(f!==S||g in Ct(v)))}}function memoizeCapped(g){var f=memoize(g,(function(g){return S.size===P&&S.clear(),g})),S=f.cache;return f}function mergeData(g,f){var S=g[1],v=f[1],C=S|v,_=C<(k|L|H),T=v==H&&S==x||v==H&&S==$&&g[7].length<=f[8]||v==(H|$)&&f[7].length<=f[8]&&S==x;if(!_&&!T)return g;v&k&&(g[2]=f[2],C|=S&k?0:F);var I=f[3];if(I){var b=g[3];g[3]=b?composeArgs(b,I,f[4]):I,g[4]=b?replaceHolders(g[3],R):f[4]}return(I=f[5])&&(b=g[5],g[5]=b?composeArgsRight(b,I,f[6]):I,g[6]=b?replaceHolders(g[5],R):f[6]),(I=f[7])&&(g[7]=I),v&H&&(g[8]=null==g[8]?f[8]:ui(g[8],f[8])),null==g[9]&&(g[9]=f[9]),g[0]=f[0],g[1]=C,g}function nativeKeysIn(g){var f=[];if(null!=g)for(var S in Ct(g))f.push(S);return f}function objectToString(g){return Ot.call(g)}function overRest(g,f,v){return f=hi(f===S?g.length-1:f,0),function(){for(var S=arguments,_=-1,T=hi(S.length-f,0),I=C(T);++_<T;)I[_]=S[f+_];_=-1;for(var b=C(f+1);++_<f;)b[_]=S[_];return b[f]=v(I),apply(g,this,b)}}function parent(g,f){return f.length<2?g:baseGet(g,baseSlice(f,0,-1))}function reorder(g,f){for(var v=g.length,C=ui(f.length,v),_=copyArray(g);C--;){var T=f[C];g[C]=isIndex(T,v)?_[T]:S}return g}function safeGet(g,f){if(("constructor"!==f||"function"!=typeof g[f])&&"__proto__"!=f)return g[f]}var on=shortOut(Yi),ln=Qt||function(g,f){return gi.setTimeout(g,f)},cn=shortOut(Qi);function setWrapToString(g,f,S){var v=f+"";return cn(g,insertWrapDetails(v,updateWrapDetails(getWrapDetails(v),S)))}function shortOut(g){var f=0,v=0;return function(){var C=pi(),_=z-(C-v);if(v=C,_>0){if(++f>=W)return arguments[0]}else f=0;return g.apply(S,arguments)}}function shuffleSelf(g,f){var v=-1,C=g.length,_=C-1;for(f=f===S?C:f;++v<f;){var T=baseRandom(v,_),I=g[T];g[T]=g[v],g[v]=I}return g.length=f,g}var dn=memoizeCapped((function(g){var f=[];return 46===g.charCodeAt(0)&&f.push(""),g.replace(Ye,(function(g,S,v,C){f.push(v?C.replace(at,"$1"):S||g)})),f}));function toKey(g){if("string"==typeof g||isSymbol(g))return g;var f=g+"";return"0"==f&&1/g==-Q?"-0":f}function toSource(g){if(null!=g){try{return Pt.call(g)}catch(g){}try{return g+""}catch(g){}}return""}function updateWrapDetails(g,f){return arrayEach(re,(function(S){var v="_."+S[0];f&S[1]&&!arrayIncludes(g,v)&&g.push(v)})),g.sort()}function wrapperClone(g){if(g instanceof LazyWrapper)return g.clone();var f=new LodashWrapper(g.__wrapped__,g.__chain__);return f.__actions__=copyArray(g.__actions__),f.__index__=g.__index__,f.__values__=g.__values__,f}function chunk(g,f,v){f=(v?isIterateeCall(g,f,v):f===S)?1:hi(toInteger(f),0);var _=null==g?0:g.length;if(!_||f<1)return[];for(var T=0,I=0,b=C(Xt(_/f));T<_;)b[I++]=baseSlice(g,T,T+=f);return b}function compact(g){for(var f=-1,S=null==g?0:g.length,v=0,C=[];++f<S;){var _=g[f];_&&(C[v++]=_)}return C}function concat(){var g=arguments.length;if(!g)return[];for(var f=C(g-1),S=arguments[0],v=g;v--;)f[v-1]=arguments[v];return arrayPush(Jn(S)?copyArray(S):[S],baseFlatten(f,1))}var hn=baseRest((function(g,f){return isArrayLikeObject(g)?baseDifference(g,baseFlatten(f,1,isArrayLikeObject,!0)):[]})),un=baseRest((function(g,f){var v=last(f);return isArrayLikeObject(v)&&(v=S),isArrayLikeObject(g)?baseDifference(g,baseFlatten(f,1,isArrayLikeObject,!0),getIteratee(v,2)):[]})),gn=baseRest((function(g,f){var v=last(f);return isArrayLikeObject(v)&&(v=S),isArrayLikeObject(g)?baseDifference(g,baseFlatten(f,1,isArrayLikeObject,!0),S,v):[]}));function drop(g,f,v){var C=null==g?0:g.length;return C?baseSlice(g,(f=v||f===S?1:toInteger(f))<0?0:f,C):[]}function dropRight(g,f,v){var C=null==g?0:g.length;return C?baseSlice(g,0,(f=C-(f=v||f===S?1:toInteger(f)))<0?0:f):[]}function dropRightWhile(g,f){return g&&g.length?baseWhile(g,getIteratee(f,3),!0,!0):[]}function dropWhile(g,f){return g&&g.length?baseWhile(g,getIteratee(f,3),!0):[]}function fill(g,f,S,v){var C=null==g?0:g.length;return C?(S&&"number"!=typeof S&&isIterateeCall(g,f,S)&&(S=0,v=C),baseFill(g,f,S,v)):[]}function findIndex(g,f,S){var v=null==g?0:g.length;if(!v)return-1;var C=null==S?0:toInteger(S);return C<0&&(C=hi(v+C,0)),baseFindIndex(g,getIteratee(f,3),C)}function findLastIndex(g,f,v){var C=null==g?0:g.length;if(!C)return-1;var _=C-1;return v!==S&&(_=toInteger(v),_=v<0?hi(C+_,0):ui(_,C-1)),baseFindIndex(g,getIteratee(f,3),_,!0)}function flatten(g){return(null==g?0:g.length)?baseFlatten(g,1):[]}function flattenDeep(g){return(null==g?0:g.length)?baseFlatten(g,Q):[]}function flattenDepth(g,f){return(null==g?0:g.length)?baseFlatten(g,f=f===S?1:toInteger(f)):[]}function fromPairs(g){for(var f=-1,S=null==g?0:g.length,v={};++f<S;){var C=g[f];v[C[0]]=C[1]}return v}function head(g){return g&&g.length?g[0]:S}function indexOf(g,f,S){var v=null==g?0:g.length;if(!v)return-1;var C=null==S?0:toInteger(S);return C<0&&(C=hi(v+C,0)),baseIndexOf(g,f,C)}function initial(g){return(null==g?0:g.length)?baseSlice(g,0,-1):[]}var pn=baseRest((function(g){var f=arrayMap(g,castArrayLikeObject);return f.length&&f[0]===g[0]?baseIntersection(f):[]})),mn=baseRest((function(g){var f=last(g),v=arrayMap(g,castArrayLikeObject);return f===last(v)?f=S:v.pop(),v.length&&v[0]===g[0]?baseIntersection(v,getIteratee(f,2)):[]})),fn=baseRest((function(g){var f=last(g),v=arrayMap(g,castArrayLikeObject);return(f="function"==typeof f?f:S)&&v.pop(),v.length&&v[0]===g[0]?baseIntersection(v,S,f):[]}));function join(g,f){return null==g?"":oi.call(g,f)}function last(g){var f=null==g?0:g.length;return f?g[f-1]:S}function lastIndexOf(g,f,v){var C=null==g?0:g.length;if(!C)return-1;var _=C;return v!==S&&(_=(_=toInteger(v))<0?hi(C+_,0):ui(_,C-1)),f==f?strictLastIndexOf(g,f,_):baseFindIndex(g,baseIsNaN,_,!0)}function nth(g,f){return g&&g.length?baseNth(g,toInteger(f)):S}var Sn=baseRest(pullAll);function pullAll(g,f){return g&&g.length&&f&&f.length?basePullAll(g,f):g}function pullAllBy(g,f,S){return g&&g.length&&f&&f.length?basePullAll(g,f,getIteratee(S,2)):g}function pullAllWith(g,f,v){return g&&g.length&&f&&f.length?basePullAll(g,f,S,v):g}var vn=flatRest((function(g,f){var S=null==g?0:g.length,v=baseAt(g,f);return basePullAt(g,arrayMap(f,(function(g){return isIndex(g,S)?+g:g})).sort(compareAscending)),v}));function remove(g,f){var S=[];if(!g||!g.length)return S;var v=-1,C=[],_=g.length;for(f=getIteratee(f,3);++v<_;){var T=g[v];f(T,v,g)&&(S.push(T),C.push(v))}return basePullAt(g,C),S}function reverse(g){return null==g?g:vi.call(g)}function slice(g,f,v){var C=null==g?0:g.length;return C?(v&&"number"!=typeof v&&isIterateeCall(g,f,v)?(f=0,v=C):(f=null==f?0:toInteger(f),v=v===S?C:toInteger(v)),baseSlice(g,f,v)):[]}function sortedIndex(g,f){return baseSortedIndex(g,f)}function sortedIndexBy(g,f,S){return baseSortedIndexBy(g,f,getIteratee(S,2))}function sortedIndexOf(g,f){var S=null==g?0:g.length;if(S){var v=baseSortedIndex(g,f);if(v<S&&eq(g[v],f))return v}return-1}function sortedLastIndex(g,f){return baseSortedIndex(g,f,!0)}function sortedLastIndexBy(g,f,S){return baseSortedIndexBy(g,f,getIteratee(S,2),!0)}function sortedLastIndexOf(g,f){if(null==g?0:g.length){var S=baseSortedIndex(g,f,!0)-1;if(eq(g[S],f))return S}return-1}function sortedUniq(g){return g&&g.length?baseSortedUniq(g):[]}function sortedUniqBy(g,f){return g&&g.length?baseSortedUniq(g,getIteratee(f,2)):[]}function tail(g){var f=null==g?0:g.length;return f?baseSlice(g,1,f):[]}function take(g,f,v){return g&&g.length?baseSlice(g,0,(f=v||f===S?1:toInteger(f))<0?0:f):[]}function takeRight(g,f,v){var C=null==g?0:g.length;return C?baseSlice(g,(f=C-(f=v||f===S?1:toInteger(f)))<0?0:f,C):[]}function takeRightWhile(g,f){return g&&g.length?baseWhile(g,getIteratee(f,3),!1,!0):[]}function takeWhile(g,f){return g&&g.length?baseWhile(g,getIteratee(f,3)):[]}var Cn=baseRest((function(g){return baseUniq(baseFlatten(g,1,isArrayLikeObject,!0))})),yn=baseRest((function(g){var f=last(g);return isArrayLikeObject(f)&&(f=S),baseUniq(baseFlatten(g,1,isArrayLikeObject,!0),getIteratee(f,2))})),En=baseRest((function(g){var f=last(g);return f="function"==typeof f?f:S,baseUniq(baseFlatten(g,1,isArrayLikeObject,!0),S,f)}));function uniq(g){return g&&g.length?baseUniq(g):[]}function uniqBy(g,f){return g&&g.length?baseUniq(g,getIteratee(f,2)):[]}function uniqWith(g,f){return f="function"==typeof f?f:S,g&&g.length?baseUniq(g,S,f):[]}function unzip(g){if(!g||!g.length)return[];var f=0;return g=arrayFilter(g,(function(g){if(isArrayLikeObject(g))return f=hi(g.length,f),!0})),baseTimes(f,(function(f){return arrayMap(g,baseProperty(f))}))}function unzipWith(g,f){if(!g||!g.length)return[];var v=unzip(g);return null==f?v:arrayMap(v,(function(g){return apply(f,S,g)}))}var _n=baseRest((function(g,f){return isArrayLikeObject(g)?baseDifference(g,f):[]})),Tn=baseRest((function(g){return baseXor(arrayFilter(g,isArrayLikeObject))})),In=baseRest((function(g){var f=last(g);return isArrayLikeObject(f)&&(f=S),baseXor(arrayFilter(g,isArrayLikeObject),getIteratee(f,2))})),bn=baseRest((function(g){var f=last(g);return f="function"==typeof f?f:S,baseXor(arrayFilter(g,isArrayLikeObject),S,f)})),An=baseRest(unzip);function zipObject(g,f){return baseZipObject(g||[],f||[],assignValue)}function zipObjectDeep(g,f){return baseZipObject(g||[],f||[],baseSet)}var Pn=baseRest((function(g){var f=g.length,v=f>1?g[f-1]:S;return v="function"==typeof v?(g.pop(),v):S,unzipWith(g,v)}));function chain(g){var f=lodash(g);return f.__chain__=!0,f}function tap(g,f){return f(g),g}function thru(g,f){return f(g)}var Rn=flatRest((function(g){var f=g.length,v=f?g[0]:0,C=this.__wrapped__,interceptor=function(f){return baseAt(f,g)};return!(f>1||this.__actions__.length)&&C instanceof LazyWrapper&&isIndex(v)?((C=C.slice(v,+v+(f?1:0))).__actions__.push({func:thru,args:[interceptor],thisArg:S}),new LodashWrapper(C,this.__chain__).thru((function(g){return f&&!g.length&&g.push(S),g}))):this.thru(interceptor)}));function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===S&&(this.__values__=toArray(this.value()));var g=this.__index__>=this.__values__.length;return{done:g,value:g?S:this.__values__[this.__index__++]}}function wrapperToIterator(){return this}function wrapperPlant(g){for(var f,v=this;v instanceof baseLodash;){var C=wrapperClone(v);C.__index__=0,C.__values__=S,f?_.__wrapped__=C:f=C;var _=C;v=v.__wrapped__}return _.__wrapped__=g,f}function wrapperReverse(){var g=this.__wrapped__;if(g instanceof LazyWrapper){var f=g;return this.__actions__.length&&(f=new LazyWrapper(this)),(f=f.reverse()).__actions__.push({func:thru,args:[reverse],thisArg:S}),new LodashWrapper(f,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}var Mn=createAggregator((function(g,f,S){Rt.call(g,S)?++g[S]:baseAssignValue(g,S,1)}));function every(g,f,v){var C=Jn(g)?arrayEvery:baseEvery;return v&&isIterateeCall(g,f,v)&&(f=S),C(g,getIteratee(f,3))}function filter(g,f){return(Jn(g)?arrayFilter:baseFilter)(g,getIteratee(f,3))}var wn=createFind(findIndex),On=createFind(findLastIndex);function flatMap(g,f){return baseFlatten(map(g,f),1)}function flatMapDeep(g,f){return baseFlatten(map(g,f),Q)}function flatMapDepth(g,f,v){return v=v===S?1:toInteger(v),baseFlatten(map(g,f),v)}function forEach(g,f){return(Jn(g)?arrayEach:Wi)(g,getIteratee(f,3))}function forEachRight(g,f){return(Jn(g)?arrayEachRight:zi)(g,getIteratee(f,3))}var Dn=createAggregator((function(g,f,S){Rt.call(g,S)?g[S].push(f):baseAssignValue(g,S,[f])}));function includes(g,f,S,v){g=isArrayLike(g)?g:values(g),S=S&&!v?toInteger(S):0;var C=g.length;return S<0&&(S=hi(C+S,0)),isString(g)?S<=C&&g.indexOf(f,S)>-1:!!C&&baseIndexOf(g,f,S)>-1}var Nn=baseRest((function(g,f,S){var v=-1,_="function"==typeof f,T=isArrayLike(g)?C(g.length):[];return Wi(g,(function(g){T[++v]=_?apply(f,g,S):baseInvoke(g,f,S)})),T})),kn=createAggregator((function(g,f,S){baseAssignValue(g,S,f)}));function map(g,f){return(Jn(g)?arrayMap:baseMap)(g,getIteratee(f,3))}function orderBy(g,f,v,C){return null==g?[]:(Jn(f)||(f=null==f?[]:[f]),Jn(v=C?S:v)||(v=null==v?[]:[v]),baseOrderBy(g,f,v))}var Ln=createAggregator((function(g,f,S){g[S?0:1].push(f)}),(function(){return[[],[]]}));function reduce(g,f,S){var v=Jn(g)?arrayReduce:baseReduce,C=arguments.length<3;return v(g,getIteratee(f,4),S,C,Wi)}function reduceRight(g,f,S){var v=Jn(g)?arrayReduceRight:baseReduce,C=arguments.length<3;return v(g,getIteratee(f,4),S,C,zi)}function reject(g,f){return(Jn(g)?arrayFilter:baseFilter)(g,negate(getIteratee(f,3)))}function sample(g){return(Jn(g)?arraySample:baseSample)(g)}function sampleSize(g,f,v){return f=(v?isIterateeCall(g,f,v):f===S)?1:toInteger(f),(Jn(g)?arraySampleSize:baseSampleSize)(g,f)}function shuffle(g){return(Jn(g)?arrayShuffle:baseShuffle)(g)}function size(g){if(null==g)return 0;if(isArrayLike(g))return isString(g)?stringSize(g):g.length;var f=sn(g);return f==pe||f==Ee?g.size:baseKeys(g).length}function some(g,f,v){var C=Jn(g)?arraySome:baseSome;return v&&isIterateeCall(g,f,v)&&(f=S),C(g,getIteratee(f,3))}var Fn=baseRest((function(g,f){if(null==g)return[];var S=f.length;return S>1&&isIterateeCall(g,f[0],f[1])?f=[]:S>2&&isIterateeCall(f[0],f[1],f[2])&&(f=[f[0]]),baseOrderBy(g,baseFlatten(f,1),[])})),xn=Kt||function(){return gi.Date.now()};function after(g,f){if("function"!=typeof f)throw new _t(I);return g=toInteger(g),function(){if(--g<1)return f.apply(this,arguments)}}function ary(g,f,v){return f=v?S:f,f=g&&null==f?g.length:f,createWrap(g,H,S,S,S,S,f)}function before(g,f){var v;if("function"!=typeof f)throw new _t(I);return g=toInteger(g),function(){return--g>0&&(v=f.apply(this,arguments)),g<=1&&(f=S),v}}var Un=baseRest((function(g,f,S){var v=k;if(S.length){var C=replaceHolders(S,getHolder(Un));v|=V}return createWrap(g,v,f,S,C)})),Vn=baseRest((function(g,f,S){var v=k|L;if(S.length){var C=replaceHolders(S,getHolder(Vn));v|=V}return createWrap(f,v,g,S,C)}));function curry(g,f,v){var C=createWrap(g,x,S,S,S,S,S,f=v?S:f);return C.placeholder=curry.placeholder,C}function curryRight(g,f,v){var C=createWrap(g,U,S,S,S,S,S,f=v?S:f);return C.placeholder=curryRight.placeholder,C}function debounce(g,f,v){var C,_,T,b,A,P,R=0,M=!1,w=!1,O=!0;if("function"!=typeof g)throw new _t(I);function invokeFunc(f){var v=C,T=_;return C=_=S,R=f,b=g.apply(T,v)}function leadingEdge(g){return R=g,A=ln(timerExpired,f),M?invokeFunc(g):b}function remainingWait(g){var S=f-(g-P);return w?ui(S,T-(g-R)):S}function shouldInvoke(g){var v=g-P;return P===S||v>=f||v<0||w&&g-R>=T}function timerExpired(){var g=xn();if(shouldInvoke(g))return trailingEdge(g);A=ln(timerExpired,remainingWait(g))}function trailingEdge(g){return A=S,O&&C?invokeFunc(g):(C=_=S,b)}function cancel(){A!==S&&Zi(A),R=0,C=P=_=A=S}function flush(){return A===S?b:trailingEdge(xn())}function debounced(){var g=xn(),v=shouldInvoke(g);if(C=arguments,_=this,P=g,v){if(A===S)return leadingEdge(P);if(w)return Zi(A),A=ln(timerExpired,f),invokeFunc(P)}return A===S&&(A=ln(timerExpired,f)),b}return f=toNumber(f)||0,isObject(v)&&(M=!!v.leading,T=(w="maxWait"in v)?hi(toNumber(v.maxWait)||0,f):T,O="trailing"in v?!!v.trailing:O),debounced.cancel=cancel,debounced.flush=flush,debounced}var Bn=baseRest((function(g,f){return baseDelay(g,1,f)})),Hn=baseRest((function(g,f,S){return baseDelay(g,toNumber(f)||0,S)}));function flip(g){return createWrap(g,j)}function memoize(g,f){if("function"!=typeof g||null!=f&&"function"!=typeof f)throw new _t(I);var memoized=function(){var S=arguments,v=f?f.apply(this,S):S[0],C=memoized.cache;if(C.has(v))return C.get(v);var _=g.apply(this,S);return memoized.cache=C.set(v,_)||C,_};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(g){if("function"!=typeof g)throw new _t(I);return function(){var f=arguments;switch(f.length){case 0:return!g.call(this);case 1:return!g.call(this,f[0]);case 2:return!g.call(this,f[0],f[1]);case 3:return!g.call(this,f[0],f[1],f[2])}return!g.apply(this,f)}}function once(g){return before(2,g)}memoize.Cache=MapCache;var $n=Xi((function(g,f){var S=(f=1==f.length&&Jn(f[0])?arrayMap(f[0],baseUnary(getIteratee())):arrayMap(baseFlatten(f,1),baseUnary(getIteratee()))).length;return baseRest((function(v){for(var C=-1,_=ui(v.length,S);++C<_;)v[C]=f[C].call(this,v[C]);return apply(g,this,v)}))})),jn=baseRest((function(g,f){var v=replaceHolders(f,getHolder(jn));return createWrap(g,V,S,f,v)})),Gn=baseRest((function(g,f){var v=replaceHolders(f,getHolder(Gn));return createWrap(g,B,S,f,v)})),qn=flatRest((function(g,f){return createWrap(g,$,S,S,S,f)}));function rest(g,f){if("function"!=typeof g)throw new _t(I);return baseRest(g,f=f===S?f:toInteger(f))}function spread(g,f){if("function"!=typeof g)throw new _t(I);return f=null==f?0:hi(toInteger(f),0),baseRest((function(S){var v=S[f],C=castSlice(S,0,f);return v&&arrayPush(C,v),apply(g,this,C)}))}function throttle(g,f,S){var v=!0,C=!0;if("function"!=typeof g)throw new _t(I);return isObject(S)&&(v="leading"in S?!!S.leading:v,C="trailing"in S?!!S.trailing:C),debounce(g,f,{leading:v,maxWait:f,trailing:C})}function unary(g){return ary(g,1)}function wrap(g,f){return jn(castFunction(f),g)}function castArray(){if(!arguments.length)return[];var g=arguments[0];return Jn(g)?g:[g]}function clone(g){return baseClone(g,O)}function cloneWith(g,f){return baseClone(g,O,f="function"==typeof f?f:S)}function cloneDeep(g){return baseClone(g,M|O)}function cloneDeepWith(g,f){return baseClone(g,M|O,f="function"==typeof f?f:S)}function conformsTo(g,f){return null==f||baseConformsTo(g,f,keys(f))}function eq(g,f){return g===f||g!=g&&f!=f}var Wn=createRelationalOperation(baseGt),zn=createRelationalOperation((function(g,f){return g>=f})),Kn=baseIsArguments(function(){return arguments}())?baseIsArguments:function(g){return isObjectLike(g)&&Rt.call(g,"callee")&&!Ht.call(g,"callee")},Jn=C.isArray,Yn=Ci?baseUnary(Ci):baseIsArrayBuffer;function isArrayLike(g){return null!=g&&isLength(g.length)&&!isFunction(g)}function isArrayLikeObject(g){return isObjectLike(g)&&isArrayLike(g)}function isBoolean(g){return!0===g||!1===g||isObjectLike(g)&&baseGetTag(g)==le}var Qn=si||stubFalse,Xn=yi?baseUnary(yi):baseIsDate;function isElement(g){return isObjectLike(g)&&1===g.nodeType&&!isPlainObject(g)}function isEmpty(g){if(null==g)return!0;if(isArrayLike(g)&&(Jn(g)||"string"==typeof g||"function"==typeof g.splice||Qn(g)||ir(g)||Kn(g)))return!g.length;var f=sn(g);if(f==pe||f==Ee)return!g.size;if(isPrototype(g))return!baseKeys(g).length;for(var S in g)if(Rt.call(g,S))return!1;return!0}function isEqual(g,f){return baseIsEqual(g,f)}function isEqualWith(g,f,v){var C=(v="function"==typeof v?v:S)?v(g,f):S;return C===S?baseIsEqual(g,f,S,v):!!C}function isError(g){if(!isObjectLike(g))return!1;var f=baseGetTag(g);return f==he||f==de||"string"==typeof g.message&&"string"==typeof g.name&&!isPlainObject(g)}function isFinite(g){return"number"==typeof g&&ai(g)}function isFunction(g){if(!isObject(g))return!1;var f=baseGetTag(g);return f==ue||f==ge||f==oe||f==Ce}function isInteger(g){return"number"==typeof g&&g==toInteger(g)}function isLength(g){return"number"==typeof g&&g>-1&&g%1==0&&g<=X}function isObject(g){var f=typeof g;return null!=g&&("object"==f||"function"==f)}function isObjectLike(g){return null!=g&&"object"==typeof g}var Zn=Ei?baseUnary(Ei):baseIsMap;function isMatch(g,f){return g===f||baseIsMatch(g,f,getMatchData(f))}function isMatchWith(g,f,v){return v="function"==typeof v?v:S,baseIsMatch(g,f,getMatchData(f),v)}function isNaN(g){return isNumber(g)&&g!=+g}function isNative(g){if(an(g))throw new rt(T);return baseIsNative(g)}function isNull(g){return null===g}function isNil(g){return null==g}function isNumber(g){return"number"==typeof g||isObjectLike(g)&&baseGetTag(g)==me}function isPlainObject(g){if(!isObjectLike(g)||baseGetTag(g)!=Se)return!1;var f=Vt(g);if(null===f)return!0;var S=Rt.call(f,"constructor")&&f.constructor;return"function"==typeof S&&S instanceof S&&Pt.call(S)==Dt}var er=_i?baseUnary(_i):baseIsRegExp;function isSafeInteger(g){return isInteger(g)&&g>=-X&&g<=X}var tr=Ti?baseUnary(Ti):baseIsSet;function isString(g){return"string"==typeof g||!Jn(g)&&isObjectLike(g)&&baseGetTag(g)==_e}function isSymbol(g){return"symbol"==typeof g||isObjectLike(g)&&baseGetTag(g)==Te}var ir=Ii?baseUnary(Ii):baseIsTypedArray;function isUndefined(g){return g===S}function isWeakMap(g){return isObjectLike(g)&&sn(g)==be}function isWeakSet(g){return isObjectLike(g)&&baseGetTag(g)==Ae}var nr=createRelationalOperation(baseLt),rr=createRelationalOperation((function(g,f){return g<=f}));function toArray(g){if(!g)return[];if(isArrayLike(g))return isString(g)?stringToArray(g):copyArray(g);if(Gt&&g[Gt])return iteratorToArray(g[Gt]());var f=sn(g);return(f==pe?mapToArray:f==Ee?setToArray:values)(g)}function toFinite(g){return g?(g=toNumber(g))===Q||g===-Q?(g<0?-1:1)*Z:g==g?g:0:0===g?g:0}function toInteger(g){var f=toFinite(g),S=f%1;return f==f?S?f-S:f:0}function toLength(g){return g?baseClamp(toInteger(g),0,te):0}function toNumber(g){if("number"==typeof g)return g;if(isSymbol(g))return ee;if(isObject(g)){var f="function"==typeof g.valueOf?g.valueOf():g;g=isObject(f)?f+"":f}if("string"!=typeof g)return 0===g?g:+g;g=baseTrim(g);var S=dt.test(g);return S||ut.test(g)?di(g.slice(2),S?2:8):ct.test(g)?ee:+g}function toPlainObject(g){return copyObject(g,keysIn(g))}function toSafeInteger(g){return g?baseClamp(toInteger(g),-X,X):0===g?g:0}function toString(g){return null==g?"":baseToString(g)}var sr=createAssigner((function(g,f){if(isPrototype(f)||isArrayLike(f))copyObject(f,keys(f),g);else for(var S in f)Rt.call(f,S)&&assignValue(g,S,f[S])})),ar=createAssigner((function(g,f){copyObject(f,keysIn(f),g)})),or=createAssigner((function(g,f,S,v){copyObject(f,keysIn(f),g,v)})),lr=createAssigner((function(g,f,S,v){copyObject(f,keys(f),g,v)})),cr=flatRest(baseAt);function create(g,f){var S=qi(g);return null==f?S:baseAssign(S,f)}var dr=baseRest((function(g,f){g=Ct(g);var v=-1,C=f.length,_=C>2?f[2]:S;for(_&&isIterateeCall(f[0],f[1],_)&&(C=1);++v<C;)for(var T=f[v],I=keysIn(T),b=-1,A=I.length;++b<A;){var P=I[b],R=g[P];(R===S||eq(R,bt[P])&&!Rt.call(g,P))&&(g[P]=T[P])}return g})),hr=baseRest((function(g){return g.push(S,customDefaultsMerge),apply(fr,S,g)}));function findKey(g,f){return baseFindKey(g,getIteratee(f,3),baseForOwn)}function findLastKey(g,f){return baseFindKey(g,getIteratee(f,3),baseForOwnRight)}function forIn(g,f){return null==g?g:Ki(g,getIteratee(f,3),keysIn)}function forInRight(g,f){return null==g?g:Ji(g,getIteratee(f,3),keysIn)}function forOwn(g,f){return g&&baseForOwn(g,getIteratee(f,3))}function forOwnRight(g,f){return g&&baseForOwnRight(g,getIteratee(f,3))}function functions(g){return null==g?[]:baseFunctions(g,keys(g))}function functionsIn(g){return null==g?[]:baseFunctions(g,keysIn(g))}function get(g,f,v){var C=null==g?S:baseGet(g,f);return C===S?v:C}function has(g,f){return null!=g&&hasPath(g,f,baseHas)}function hasIn(g,f){return null!=g&&hasPath(g,f,baseHasIn)}var ur=createInverter((function(g,f,S){null!=f&&"function"!=typeof f.toString&&(f=Ot.call(f)),g[f]=S}),constant(identity)),gr=createInverter((function(g,f,S){null!=f&&"function"!=typeof f.toString&&(f=Ot.call(f)),Rt.call(g,f)?g[f].push(S):g[f]=[S]}),getIteratee),pr=baseRest(baseInvoke);function keys(g){return isArrayLike(g)?arrayLikeKeys(g):baseKeys(g)}function keysIn(g){return isArrayLike(g)?arrayLikeKeys(g,!0):baseKeysIn(g)}function mapKeys(g,f){var S={};return f=getIteratee(f,3),baseForOwn(g,(function(g,v,C){baseAssignValue(S,f(g,v,C),g)})),S}function mapValues(g,f){var S={};return f=getIteratee(f,3),baseForOwn(g,(function(g,v,C){baseAssignValue(S,v,f(g,v,C))})),S}var mr=createAssigner((function(g,f,S){baseMerge(g,f,S)})),fr=createAssigner((function(g,f,S,v){baseMerge(g,f,S,v)})),Sr=flatRest((function(g,f){var S={};if(null==g)return S;var v=!1;f=arrayMap(f,(function(f){return f=castPath(f,g),v||(v=f.length>1),f})),copyObject(g,getAllKeysIn(g),S),v&&(S=baseClone(S,M|w|O,customOmitClone));for(var C=f.length;C--;)baseUnset(S,f[C]);return S}));function omitBy(g,f){return pickBy(g,negate(getIteratee(f)))}var vr=flatRest((function(g,f){return null==g?{}:basePick(g,f)}));function pickBy(g,f){if(null==g)return{};var S=arrayMap(getAllKeysIn(g),(function(g){return[g]}));return f=getIteratee(f),basePickBy(g,S,(function(g,S){return f(g,S[0])}))}function result(g,f,v){var C=-1,_=(f=castPath(f,g)).length;for(_||(_=1,g=S);++C<_;){var T=null==g?S:g[toKey(f[C])];T===S&&(C=_,T=v),g=isFunction(T)?T.call(g):T}return g}function set(g,f,S){return null==g?g:baseSet(g,f,S)}function setWith(g,f,v,C){return C="function"==typeof C?C:S,null==g?g:baseSet(g,f,v,C)}var Cr=createToPairs(keys),yr=createToPairs(keysIn);function transform(g,f,S){var v=Jn(g),C=v||Qn(g)||ir(g);if(f=getIteratee(f,4),null==S){var _=g&&g.constructor;S=C?v?new _:[]:isObject(g)&&isFunction(_)?qi(Vt(g)):{}}return(C?arrayEach:baseForOwn)(g,(function(g,v,C){return f(S,g,v,C)})),S}function unset(g,f){return null==g||baseUnset(g,f)}function update(g,f,S){return null==g?g:baseUpdate(g,f,castFunction(S))}function updateWith(g,f,v,C){return C="function"==typeof C?C:S,null==g?g:baseUpdate(g,f,castFunction(v),C)}function values(g){return null==g?[]:baseValues(g,keys(g))}function valuesIn(g){return null==g?[]:baseValues(g,keysIn(g))}function clamp(g,f,v){return v===S&&(v=f,f=S),v!==S&&(v=(v=toNumber(v))==v?v:0),f!==S&&(f=(f=toNumber(f))==f?f:0),baseClamp(toNumber(g),f,v)}function inRange(g,f,v){return f=toFinite(f),v===S?(v=f,f=0):v=toFinite(v),baseInRange(g=toNumber(g),f,v)}function random(g,f,v){if(v&&"boolean"!=typeof v&&isIterateeCall(g,f,v)&&(f=v=S),v===S&&("boolean"==typeof f?(v=f,f=S):"boolean"==typeof g&&(v=g,g=S)),g===S&&f===S?(g=0,f=1):(g=toFinite(g),f===S?(f=g,g=0):f=toFinite(f)),g>f){var C=g;g=f,f=C}if(v||g%1||f%1){var _=Si();return ui(g+_*(f-g+ci("1e-"+((_+"").length-1))),f)}return baseRandom(g,f)}var Er=createCompounder((function(g,f,S){return f=f.toLowerCase(),g+(S?capitalize(f):f)}));function capitalize(g){return Rr(toString(g).toLowerCase())}function deburr(g){return(g=toString(g))&&g.replace(pt,Ai).replace(Yt,"")}function endsWith(g,f,v){g=toString(g),f=baseToString(f);var C=g.length,_=v=v===S?C:baseClamp(toInteger(v),0,C);return(v-=f.length)>=0&&g.slice(v,_)==f}function escape(g){return(g=toString(g))&&Ge.test(g)?g.replace($e,Pi):g}function escapeRegExp(g){return(g=toString(g))&&Xe.test(g)?g.replace(Qe,"\\$&"):g}var _r=createCompounder((function(g,f,S){return g+(S?"-":"")+f.toLowerCase()})),Tr=createCompounder((function(g,f,S){return g+(S?" ":"")+f.toLowerCase()})),Ir=createCaseFirst("toLowerCase");function pad(g,f,S){g=toString(g);var v=(f=toInteger(f))?stringSize(g):0;if(!f||v>=f)return g;var C=(f-v)/2;return createPadding(Zt(C),S)+g+createPadding(Xt(C),S)}function padEnd(g,f,S){g=toString(g);var v=(f=toInteger(f))?stringSize(g):0;return f&&v<f?g+createPadding(f-v,S):g}function padStart(g,f,S){g=toString(g);var v=(f=toInteger(f))?stringSize(g):0;return f&&v<f?createPadding(f-v,S)+g:g}function parseInt(g,f,S){return S||null==f?f=0:f&&(f=+f),mi(toString(g).replace(Ze,""),f||0)}function repeat(g,f,v){return f=(v?isIterateeCall(g,f,v):f===S)?1:toInteger(f),baseRepeat(toString(g),f)}function replace(){var g=arguments,f=toString(g[0]);return g.length<3?f:f.replace(g[1],g[2])}var br=createCompounder((function(g,f,S){return g+(S?"_":"")+f.toLowerCase()}));function split(g,f,v){return v&&"number"!=typeof v&&isIterateeCall(g,f,v)&&(f=v=S),(v=v===S?te:v>>>0)?(g=toString(g))&&("string"==typeof f||null!=f&&!er(f))&&!(f=baseToString(f))&&hasUnicode(g)?castSlice(stringToArray(g),0,v):g.split(f,v):[]}var Ar=createCompounder((function(g,f,S){return g+(S?" ":"")+Rr(f)}));function startsWith(g,f,S){return g=toString(g),S=null==S?0:baseClamp(toInteger(S),0,g.length),f=baseToString(f),g.slice(S,S+f.length)==f}function template(g,f,v){var C=lodash.templateSettings;v&&isIterateeCall(g,f,v)&&(f=S),g=toString(g),f=or({},f,C,customDefaultsAssignIn);var _,T,I=or({},f.imports,C.imports,customDefaultsAssignIn),A=keys(I),P=baseValues(I,A),R=0,M=f.interpolate||mt,w="__p += '",O=yt((f.escape||mt).source+"|"+M.source+"|"+(M===ze?ot:mt).source+"|"+(f.evaluate||mt).source+"|$","g"),D="//# sourceURL="+(Rt.call(f,"sourceURL")?(f.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++ii+"]")+"\n";g.replace(O,(function(f,S,v,C,I,b){return v||(v=C),w+=g.slice(R,b).replace(ft,escapeStringChar),S&&(_=!0,w+="' +\n__e("+S+") +\n'"),I&&(T=!0,w+="';\n"+I+";\n__p += '"),v&&(w+="' +\n((__t = ("+v+")) == null ? '' : __t) +\n'"),R=b+f.length,f})),w+="';\n";var N=Rt.call(f,"variable")&&f.variable;if(N){if(st.test(N))throw new rt(b)}else w="with (obj) {\n"+w+"\n}\n";w=(T?w.replace(Ue,""):w).replace(Ve,"$1").replace(Be,"$1;"),w="function("+(N||"obj")+") {\n"+(N?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(_?", __e = _.escape":"")+(T?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+w+"return __p\n}";var k=Mr((function(){return St(A,D+"return "+w).apply(S,P)}));if(k.source=w,isError(k))throw k;return k}function toLower(g){return toString(g).toLowerCase()}function toUpper(g){return toString(g).toUpperCase()}function trim(g,f,v){if((g=toString(g))&&(v||f===S))return baseTrim(g);if(!g||!(f=baseToString(f)))return g;var C=stringToArray(g),_=stringToArray(f);return castSlice(C,charsStartIndex(C,_),charsEndIndex(C,_)+1).join("")}function trimEnd(g,f,v){if((g=toString(g))&&(v||f===S))return g.slice(0,trimmedEndIndex(g)+1);if(!g||!(f=baseToString(f)))return g;var C=stringToArray(g);return castSlice(C,0,charsEndIndex(C,stringToArray(f))+1).join("")}function trimStart(g,f,v){if((g=toString(g))&&(v||f===S))return g.replace(Ze,"");if(!g||!(f=baseToString(f)))return g;var C=stringToArray(g);return castSlice(C,charsStartIndex(C,stringToArray(f))).join("")}function truncate(g,f){var v=G,C=q;if(isObject(f)){var _="separator"in f?f.separator:_;v="length"in f?toInteger(f.length):v,C="omission"in f?baseToString(f.omission):C}var T=(g=toString(g)).length;if(hasUnicode(g)){var I=stringToArray(g);T=I.length}if(v>=T)return g;var b=v-stringSize(C);if(b<1)return C;var A=I?castSlice(I,0,b).join(""):g.slice(0,b);if(_===S)return A+C;if(I&&(b+=A.length-b),er(_)){if(g.slice(b).search(_)){var P,R=A;for(_.global||(_=yt(_.source,toString(lt.exec(_))+"g")),_.lastIndex=0;P=_.exec(R);)var M=P.index;A=A.slice(0,M===S?b:M)}}else if(g.indexOf(baseToString(_),b)!=b){var w=A.lastIndexOf(_);w>-1&&(A=A.slice(0,w))}return A+C}function unescape(g){return(g=toString(g))&&je.test(g)?g.replace(He,Ri):g}var Pr=createCompounder((function(g,f,S){return g+(S?" ":"")+f.toUpperCase()})),Rr=createCaseFirst("toUpperCase");function words(g,f,v){return g=toString(g),(f=v?S:f)===S?hasUnicodeWord(g)?unicodeWords(g):asciiWords(g):g.match(f)||[]}var Mr=baseRest((function(g,f){try{return apply(g,S,f)}catch(g){return isError(g)?g:new rt(g)}})),wr=flatRest((function(g,f){return arrayEach(f,(function(f){f=toKey(f),baseAssignValue(g,f,Un(g[f],g))})),g}));function cond(g){var f=null==g?0:g.length,S=getIteratee();return g=f?arrayMap(g,(function(g){if("function"!=typeof g[1])throw new _t(I);return[S(g[0]),g[1]]})):[],baseRest((function(S){for(var v=-1;++v<f;){var C=g[v];if(apply(C[0],this,S))return apply(C[1],this,S)}}))}function conforms(g){return baseConforms(baseClone(g,M))}function constant(g){return function(){return g}}function defaultTo(g,f){return null==g||g!=g?f:g}var Or=createFlow(),Dr=createFlow(!0);function identity(g){return g}function iteratee(g){return baseIteratee("function"==typeof g?g:baseClone(g,M))}function matches(g){return baseMatches(baseClone(g,M))}function matchesProperty(g,f){return baseMatchesProperty(g,baseClone(f,M))}var Nr=baseRest((function(g,f){return function(S){return baseInvoke(S,g,f)}})),kr=baseRest((function(g,f){return function(S){return baseInvoke(g,S,f)}}));function mixin(g,f,S){var v=keys(f),C=baseFunctions(f,v);null!=S||isObject(f)&&(C.length||!v.length)||(S=f,f=g,g=this,C=baseFunctions(f,keys(f)));var _=!(isObject(S)&&"chain"in S&&!S.chain),T=isFunction(g);return arrayEach(C,(function(S){var v=f[S];g[S]=v,T&&(g.prototype[S]=function(){var f=this.__chain__;if(_||f){var S=g(this.__wrapped__);return(S.__actions__=copyArray(this.__actions__)).push({func:v,args:arguments,thisArg:g}),S.__chain__=f,S}return v.apply(g,arrayPush([this.value()],arguments))})})),g}function noConflict(){return gi._===this&&(gi._=Nt),this}function noop(){}function nthArg(g){return g=toInteger(g),baseRest((function(f){return baseNth(f,g)}))}var Lr=createOver(arrayMap),Fr=createOver(arrayEvery),xr=createOver(arraySome);function property(g){return isKey(g)?baseProperty(toKey(g)):basePropertyDeep(g)}function propertyOf(g){return function(f){return null==g?S:baseGet(g,f)}}var Ur=createRange(),Vr=createRange(!0);function stubArray(){return[]}function stubFalse(){return!1}function stubObject(){return{}}function stubString(){return""}function stubTrue(){return!0}function times(g,f){if((g=toInteger(g))<1||g>X)return[];var S=te,v=ui(g,te);f=getIteratee(f),g-=te;for(var C=baseTimes(v,f);++S<g;)f(S);return C}function toPath(g){return Jn(g)?arrayMap(g,toKey):isSymbol(g)?[g]:copyArray(dn(toString(g)))}function uniqueId(g){var f=++Mt;return toString(g)+f}var Br=createMathOperation((function(g,f){return g+f}),0),Hr=createRound("ceil"),$r=createMathOperation((function(g,f){return g/f}),1),jr=createRound("floor");function max(g){return g&&g.length?baseExtremum(g,identity,baseGt):S}function maxBy(g,f){return g&&g.length?baseExtremum(g,getIteratee(f,2),baseGt):S}function mean(g){return baseMean(g,identity)}function meanBy(g,f){return baseMean(g,getIteratee(f,2))}function min(g){return g&&g.length?baseExtremum(g,identity,baseLt):S}function minBy(g,f){return g&&g.length?baseExtremum(g,getIteratee(f,2),baseLt):S}var Gr,qr=createMathOperation((function(g,f){return g*f}),1),Wr=createRound("round"),zr=createMathOperation((function(g,f){return g-f}),0);function sum(g){return g&&g.length?baseSum(g,identity):0}function sumBy(g,f){return g&&g.length?baseSum(g,getIteratee(f,2)):0}return lodash.after=after,lodash.ary=ary,lodash.assign=sr,lodash.assignIn=ar,lodash.assignInWith=or,lodash.assignWith=lr,lodash.at=cr,lodash.before=before,lodash.bind=Un,lodash.bindAll=wr,lodash.bindKey=Vn,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=Mn,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=dr,lodash.defaultsDeep=hr,lodash.defer=Bn,lodash.delay=Hn,lodash.difference=hn,lodash.differenceBy=un,lodash.differenceWith=gn,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=Or,lodash.flowRight=Dr,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=Dn,lodash.initial=initial,lodash.intersection=pn,lodash.intersectionBy=mn,lodash.intersectionWith=fn,lodash.invert=ur,lodash.invertBy=gr,lodash.invokeMap=Nn,lodash.iteratee=iteratee,lodash.keyBy=kn,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty,lodash.memoize=memoize,lodash.merge=mr,lodash.mergeWith=fr,lodash.method=Nr,lodash.methodOf=kr,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=Sr,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=Lr,lodash.overArgs=$n,lodash.overEvery=Fr,lodash.overSome=xr,lodash.partial=jn,lodash.partialRight=Gn,lodash.partition=Ln,lodash.pick=vr,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=Sn,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=vn,lodash.range=Ur,lodash.rangeRight=Vr,lodash.rearg=qn,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=Fn,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=Cr,lodash.toPairsIn=yr,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=Cn,lodash.unionBy=yn,lodash.unionWith=En,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=_n,lodash.words=words,lodash.wrap=wrap,lodash.xor=Tn,lodash.xorBy=In,lodash.xorWith=bn,lodash.zip=An,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=Pn,lodash.entries=Cr,lodash.entriesIn=yr,lodash.extend=ar,lodash.extendWith=or,mixin(lodash,lodash),lodash.add=Br,lodash.attempt=Mr,lodash.camelCase=Er,lodash.capitalize=capitalize,lodash.ceil=Hr,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=$r,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=wn,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=On,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=jr,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=Wn,lodash.gte=zn,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=pr,lodash.isArguments=Kn,lodash.isArray=Jn,lodash.isArrayBuffer=Yn,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=Qn,lodash.isDate=Xn,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=Zn,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=er,lodash.isSafeInteger=isSafeInteger,lodash.isSet=tr,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=ir,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=_r,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=Tr,lodash.lowerFirst=Ir,lodash.lt=nr,lodash.lte=rr,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=qr,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=xn,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=Wr,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=br,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=Ar,lodash.startsWith=startsWith,lodash.subtract=zr,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=Pr,lodash.upperFirst=Rr,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,(Gr={},baseForOwn(lodash,(function(g,f){Rt.call(lodash.prototype,f)||(Gr[f]=g)})),Gr),{chain:!1}),lodash.VERSION=v,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(g){lodash[g].placeholder=lodash})),arrayEach(["drop","take"],(function(g,f){LazyWrapper.prototype[g]=function(v){v=v===S?1:hi(toInteger(v),0);var C=this.__filtered__&&!f?new LazyWrapper(this):this.clone();return C.__filtered__?C.__takeCount__=ui(v,C.__takeCount__):C.__views__.push({size:ui(v,te),type:g+(C.__dir__<0?"Right":"")}),C},LazyWrapper.prototype[g+"Right"]=function(f){return this.reverse()[g](f).reverse()}})),arrayEach(["filter","map","takeWhile"],(function(g,f){var S=f+1,v=S==K||S==Y;LazyWrapper.prototype[g]=function(g){var f=this.clone();return f.__iteratees__.push({iteratee:getIteratee(g,3),type:S}),f.__filtered__=f.__filtered__||v,f}})),arrayEach(["head","last"],(function(g,f){var S="take"+(f?"Right":"");LazyWrapper.prototype[g]=function(){return this[S](1).value()[0]}})),arrayEach(["initial","tail"],(function(g,f){var S="drop"+(f?"":"Right");LazyWrapper.prototype[g]=function(){return this.__filtered__?new LazyWrapper(this):this[S](1)}})),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(g){return this.filter(g).head()},LazyWrapper.prototype.findLast=function(g){return this.reverse().find(g)},LazyWrapper.prototype.invokeMap=baseRest((function(g,f){return"function"==typeof g?new LazyWrapper(this):this.map((function(S){return baseInvoke(S,g,f)}))})),LazyWrapper.prototype.reject=function(g){return this.filter(negate(getIteratee(g)))},LazyWrapper.prototype.slice=function(g,f){g=toInteger(g);var v=this;return v.__filtered__&&(g>0||f<0)?new LazyWrapper(v):(g<0?v=v.takeRight(-g):g&&(v=v.drop(g)),f!==S&&(v=(f=toInteger(f))<0?v.dropRight(-f):v.take(f-g)),v)},LazyWrapper.prototype.takeRightWhile=function(g){return this.reverse().takeWhile(g).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(te)},baseForOwn(LazyWrapper.prototype,(function(g,f){var v=/^(?:filter|find|map|reject)|While$/.test(f),C=/^(?:head|last)$/.test(f),_=lodash[C?"take"+("last"==f?"Right":""):f],T=C||/^find/.test(f);_&&(lodash.prototype[f]=function(){var f=this.__wrapped__,I=C?[1]:arguments,b=f instanceof LazyWrapper,A=I[0],P=b||Jn(f),interceptor=function(g){var f=_.apply(lodash,arrayPush([g],I));return C&&R?f[0]:f};P&&v&&"function"==typeof A&&1!=A.length&&(b=P=!1);var R=this.__chain__,M=!!this.__actions__.length,w=T&&!R,O=b&&!M;if(!T&&P){f=O?f:new LazyWrapper(this);var D=g.apply(f,I);return D.__actions__.push({func:thru,args:[interceptor],thisArg:S}),new LodashWrapper(D,R)}return w&&O?g.apply(this,I):(D=this.thru(interceptor),w?C?D.value()[0]:D.value():D)})})),arrayEach(["pop","push","shift","sort","splice","unshift"],(function(g){var f=Tt[g],S=/^(?:push|sort|unshift)$/.test(g)?"tap":"thru",v=/^(?:pop|shift)$/.test(g);lodash.prototype[g]=function(){var g=arguments;if(v&&!this.__chain__){var C=this.value();return f.apply(Jn(C)?C:[],g)}return this[S]((function(S){return f.apply(Jn(S)?S:[],g)}))}})),baseForOwn(LazyWrapper.prototype,(function(g,f){var S=lodash[f];if(S){var v=S.name+"";Rt.call(Fi,v)||(Fi[v]=[]),Fi[v].push({name:f,func:S})}})),Fi[createHybrid(S,L).name]=[{name:"wrapper",func:S}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=Rn,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,Gt&&(lodash.prototype[Gt]=wrapperToIterator),lodash},wi=Mi();mi?((mi.exports=wi)._=wi,pi._=wi):gi._=wi}).call(C)})),w=createCommonjsModule((function(g,f){var S=window;!function(f,S){g.exports=S(R,M)}(0,((g,f)=>{var v={},C={exports:v},_=Object.create,T=Object.defineProperty,I=Object.getOwnPropertyDescriptor,b=Object.getOwnPropertyNames,A=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty,__commonJS=(g,f)=>function __require(){return f||(0,g[b(g)[0]])((f={exports:{}}).exports,f),f.exports},__export=(g,f)=>{for(var S in f)T(g,S,{get:f[S],enumerable:!0})},__copyProps=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let C of b(f))P.call(g,C)||C===S||T(g,C,{get:()=>f[C],enumerable:!(v=I(f,C))||v.enumerable});return g},__toESM=(g,f,S)=>(S=null!=g?_(A(g)):{},__copyProps(!f&&g&&g.__esModule?S:T(S,"default",{value:g,enumerable:!0}),g)),__toCommonJS=g=>__copyProps(T({},"__esModule",{value:!0}),g),__decorateClass=(g,f,S,v)=>{for(var C,_=v>1?void 0:v?I(f,S):f,b=g.length-1;b>=0;b--)(C=g[b])&&(_=(v?C(f,S,_):C(_))||_);return v&&_&&T(f,S,_),_},__decorateParam=(g,f)=>(S,v)=>f(S,v,g),w=__commonJS({"../node_modules/axios/lib/helpers/bind.js"(g,f){f.exports=function bind(g,f){return function wrap(){for(var S=new Array(arguments.length),v=0;v<S.length;v++)S[v]=arguments[v];return g.apply(f,S)}}}}),O=__commonJS({"../node_modules/axios/lib/utils.js"(g,f){var S=w(),v=Object.prototype.toString;function isArray4(g){return"[object Array]"===v.call(g)}function isUndefined7(g){return void 0===g}function isBuffer(g){return null!==g&&!isUndefined7(g)&&null!==g.constructor&&!isUndefined7(g.constructor)&&"function"==typeof g.constructor.isBuffer&&g.constructor.isBuffer(g)}function isArrayBuffer(g){return"[object ArrayBuffer]"===v.call(g)}function isFormData(g){return"undefined"!=typeof FormData&&g instanceof FormData}function isArrayBufferView(g){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(g):g&&g.buffer&&g.buffer instanceof ArrayBuffer}function isString3(g){return"string"==typeof g}function isNumber5(g){return"number"==typeof g}function isObject4(g){return null!==g&&"object"==typeof g}function isDate2(g){return"[object Date]"===v.call(g)}function isFile(g){return"[object File]"===v.call(g)}function isBlob(g){return"[object Blob]"===v.call(g)}function isFunction3(g){return"[object Function]"===v.call(g)}function isStream(g){return isObject4(g)&&isFunction3(g.pipe)}function isURLSearchParams(g){return"undefined"!=typeof URLSearchParams&&g instanceof URLSearchParams}function trim2(g){return g.replace(/^\s*/,"").replace(/\s*$/,"")}function isStandardBrowserEnv(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function forEach3(g,f){if(null!=g)if("object"!=typeof g&&(g=[g]),isArray4(g))for(var S=0,v=g.length;S<v;S++)f.call(null,g[S],S,g);else for(var C in g)Object.prototype.hasOwnProperty.call(g,C)&&f.call(null,g[C],C,g)}function merge4(){var g={};function assignValue(f,S){"object"==typeof g[S]&&"object"==typeof f?g[S]=merge4(g[S],f):g[S]=f}for(var f=0,S=arguments.length;f<S;f++)forEach3(arguments[f],assignValue);return g}function deepMerge(){var g={};function assignValue(f,S){"object"==typeof g[S]&&"object"==typeof f?g[S]=deepMerge(g[S],f):g[S]="object"==typeof f?deepMerge({},f):f}for(var f=0,S=arguments.length;f<S;f++)forEach3(arguments[f],assignValue);return g}function extend3(g,f,v){return forEach3(f,(function assignValue(f,C){g[C]=v&&"function"==typeof f?S(f,v):f})),g}f.exports={isArray:isArray4,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString3,isNumber:isNumber5,isObject:isObject4,isUndefined:isUndefined7,isDate:isDate2,isFile:isFile,isBlob:isBlob,isFunction:isFunction3,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach3,merge:merge4,deepMerge:deepMerge,extend:extend3,trim:trim2}}}),D=__commonJS({"../node_modules/axios/lib/helpers/buildURL.js"(g,f){var S=O();function encode(g){return encodeURIComponent(g).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}f.exports=function buildURL(g,f,v){if(!f)return g;var C;if(v)C=v(f);else if(S.isURLSearchParams(f))C=f.toString();else{var _=[];S.forEach(f,(function serialize(g,f){null!=g&&(S.isArray(g)?f+="[]":g=[g],S.forEach(g,(function parseValue(g){S.isDate(g)?g=g.toISOString():S.isObject(g)&&(g=JSON.stringify(g)),_.push(encode(f)+"="+encode(g))})))})),C=_.join("&")}if(C){var T=g.indexOf("#");-1!==T&&(g=g.slice(0,T)),g+=(-1===g.indexOf("?")?"?":"&")+C}return g}}}),N=__commonJS({"../node_modules/axios/lib/core/InterceptorManager.js"(g,f){var S=O();function InterceptorManager(){this.handlers=[]}InterceptorManager.prototype.use=function use(g,f){return this.handlers.push({fulfilled:g,rejected:f}),this.handlers.length-1},InterceptorManager.prototype.eject=function eject(g){this.handlers[g]&&(this.handlers[g]=null)},InterceptorManager.prototype.forEach=function forEach3(g){S.forEach(this.handlers,(function forEachHandler(f){null!==f&&g(f)}))},f.exports=InterceptorManager}}),k=__commonJS({"../node_modules/axios/lib/core/transformData.js"(g,f){var S=O();f.exports=function transformData(g,f,v){return S.forEach(v,(function transform(S){g=S(g,f)})),g}}}),L=__commonJS({"../node_modules/axios/lib/cancel/isCancel.js"(g,f){f.exports=function isCancel(g){return!(!g||!g.__CANCEL__)}}}),F=__commonJS({"../node_modules/axios/lib/helpers/normalizeHeaderName.js"(g,f){var S=O();f.exports=function normalizeHeaderName(g,f){S.forEach(g,(function processHeader(S,v){v!==f&&v.toUpperCase()===f.toUpperCase()&&(g[f]=S,delete g[v])}))}}}),x=__commonJS({"../node_modules/axios/lib/core/enhanceError.js"(g,f){f.exports=function enhanceError(g,f,S,v,C){return g.config=f,S&&(g.code=S),g.request=v,g.response=C,g.isAxiosError=!0,g.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:this.config,code:this.code}},g}}}),U=__commonJS({"../node_modules/axios/lib/core/createError.js"(g,f){var S=x();f.exports=function createError(g,f,v,C,_){var T=new Error(g);return S(T,f,v,C,_)}}}),V=__commonJS({"../node_modules/axios/lib/core/settle.js"(g,f){var S=U();f.exports=function settle(g,f,v){var C=v.config.validateStatus;!C||C(v.status)?g(v):f(S("Request failed with status code "+v.status,v.config,null,v.request,v))}}}),B=__commonJS({"../node_modules/axios/lib/helpers/isAbsoluteURL.js"(g,f){f.exports=function isAbsoluteURL(g){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(g)}}}),H=__commonJS({"../node_modules/axios/lib/helpers/combineURLs.js"(g,f){f.exports=function combineURLs(g,f){return f?g.replace(/\/+$/,"")+"/"+f.replace(/^\/+/,""):g}}}),$=__commonJS({"../node_modules/axios/lib/core/buildFullPath.js"(g,f){var S=B(),v=H();f.exports=function buildFullPath(g,f){return g&&!S(f)?v(g,f):f}}}),j=__commonJS({"../node_modules/axios/lib/helpers/parseHeaders.js"(g,f){var S=O(),v=["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"];f.exports=function parseHeaders(g){var f,C,_,T={};return g?(S.forEach(g.split("\n"),(function parser(g){if(_=g.indexOf(":"),f=S.trim(g.substr(0,_)).toLowerCase(),C=S.trim(g.substr(_+1)),f){if(T[f]&&v.indexOf(f)>=0)return;T[f]="set-cookie"===f?(T[f]?T[f]:[]).concat([C]):T[f]?T[f]+", "+C:C}})),T):T}}}),G=__commonJS({"../node_modules/axios/lib/helpers/isValidXss.js"(g,f){f.exports=function isValidXss(g){return/(\b)(on\w+)=|javascript|(<\s*)(\/*)script/gi.test(g)}}}),q=__commonJS({"../node_modules/axios/lib/helpers/isURLSameOrigin.js"(g,f){var S=O(),v=G();f.exports=S.isStandardBrowserEnv()?function standardBrowserEnv(){var g,f=/(msie|trident)/i.test(navigator.userAgent),C=document.createElement("a");function resolveURL(g){var S=g;if(v(g))throw new Error("URL contains XSS injection attempt");return f&&(C.setAttribute("href",S),S=C.href),C.setAttribute("href",S),{href:C.href,protocol:C.protocol?C.protocol.replace(/:$/,""):"",host:C.host,search:C.search?C.search.replace(/^\?/,""):"",hash:C.hash?C.hash.replace(/^#/,""):"",hostname:C.hostname,port:C.port,pathname:"/"===C.pathname.charAt(0)?C.pathname:"/"+C.pathname}}return g=resolveURL(window.location.href),function isURLSameOrigin(f){var v=S.isString(f)?resolveURL(f):f;return v.protocol===g.protocol&&v.host===g.host}}():function nonStandardBrowserEnv(){return function isURLSameOrigin(){return!0}}()}}),W=__commonJS({"../node_modules/axios/lib/helpers/cookies.js"(g,f){var S=O();f.exports=S.isStandardBrowserEnv()?function standardBrowserEnv(){return{write:function write5(g,f,v,C,_,T){var I=[];I.push(g+"="+encodeURIComponent(f)),S.isNumber(v)&&I.push("expires="+new Date(v).toGMTString()),S.isString(C)&&I.push("path="+C),S.isString(_)&&I.push("domain="+_),!0===T&&I.push("secure"),document.cookie=I.join("; ")},read:function read(g){var f=document.cookie.match(new RegExp("(^|;\\s*)("+g+")=([^;]*)"));return f?decodeURIComponent(f[3]):null},remove:function remove6(g){this.write(g,"",Date.now()-864e5)}}}():function nonStandardBrowserEnv(){return{write:function write5(){},read:function read(){return null},remove:function remove6(){}}}()}}),z=__commonJS({"../node_modules/axios/lib/adapters/xhr.js"(g,f){var S=O(),v=V(),C=D(),_=$(),T=j(),I=q(),b=U();f.exports=function xhrAdapter(g){return new Promise((function dispatchXhrRequest(f,A){var P=g.data,R=g.headers;S.isFormData(P)&&delete R["Content-Type"];var M=new XMLHttpRequest;if(g.auth){var w=g.auth.username||"",O=g.auth.password||"";R.Authorization="Basic "+btoa(w+":"+O)}var D=_(g.baseURL,g.url);if(M.open(g.method.toUpperCase(),C(D,g.params,g.paramsSerializer),!0),M.timeout=g.timeout,M.onreadystatechange=function handleLoad(){if(M&&4===M.readyState&&(0!==M.status||M.responseURL&&0===M.responseURL.indexOf("file:"))){var S="getAllResponseHeaders"in M?T(M.getAllResponseHeaders()):null,C={data:g.responseType&&"text"!==g.responseType?M.response:M.responseText,status:M.status,statusText:M.statusText,headers:S,config:g,request:M};v(f,A,C),M=null}},M.onabort=function handleAbort(){M&&(A(b("Request aborted",g,"ECONNABORTED",M)),M=null)},M.onerror=function handleError(){A(b("Network Error",g,null,M)),M=null},M.ontimeout=function handleTimeout(){var f="timeout of "+g.timeout+"ms exceeded";g.timeoutErrorMessage&&(f=g.timeoutErrorMessage),A(b(f,g,"ECONNABORTED",M)),M=null},S.isStandardBrowserEnv()){var N=W(),k=(g.withCredentials||I(D))&&g.xsrfCookieName?N.read(g.xsrfCookieName):void 0;k&&(R[g.xsrfHeaderName]=k)}if("setRequestHeader"in M&&S.forEach(R,(function setRequestHeader(g,f){void 0===P&&"content-type"===f.toLowerCase()?delete R[f]:M.setRequestHeader(f,g)})),S.isUndefined(g.withCredentials)||(M.withCredentials=!!g.withCredentials),g.responseType)try{M.responseType=g.responseType}catch(f){if("json"!==g.responseType)throw f}"function"==typeof g.onDownloadProgress&&M.addEventListener("progress",g.onDownloadProgress),"function"==typeof g.onUploadProgress&&M.upload&&M.upload.addEventListener("progress",g.onUploadProgress),g.cancelToken&&g.cancelToken.promise.then((function onCanceled(g){M&&(M.abort(),A(g),M=null)})),void 0===P&&(P=null),M.send(P)}))}}}),K=__commonJS({"../node_modules/axios/lib/defaults.js"(g,f){var S=O(),v=F(),C={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(g,f){!S.isUndefined(g)&&S.isUndefined(g["Content-Type"])&&(g["Content-Type"]=f)}function getDefaultAdapter(){var g;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(g=z()),g}var _={adapter:getDefaultAdapter(),transformRequest:[function transformRequest(g,f){return v(f,"Accept"),v(f,"Content-Type"),S.isFormData(g)||S.isArrayBuffer(g)||S.isBuffer(g)||S.isStream(g)||S.isFile(g)||S.isBlob(g)?g:S.isArrayBufferView(g)?g.buffer:S.isURLSearchParams(g)?(setContentTypeIfUnset(f,"application/x-www-form-urlencoded;charset=utf-8"),g.toString()):S.isObject(g)?(setContentTypeIfUnset(f,"application/json;charset=utf-8"),JSON.stringify(g)):g}],transformResponse:[function transformResponse(g){if("string"==typeof g)try{g=JSON.parse(g)}catch(g){}return g}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function validateStatus(g){return g>=200&&g<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};S.forEach(["delete","get","head"],(function forEachMethodNoData(g){_.headers[g]={}})),S.forEach(["post","put","patch"],(function forEachMethodWithData(g){_.headers[g]=S.merge(C)})),f.exports=_}}),J=__commonJS({"../node_modules/axios/lib/core/dispatchRequest.js"(g,f){var S=O(),v=k(),C=L(),_=K();function throwIfCancellationRequested(g){g.cancelToken&&g.cancelToken.throwIfRequested()}f.exports=function dispatchRequest(g){return throwIfCancellationRequested(g),g.headers=g.headers||{},g.data=v(g.data,g.headers,g.transformRequest),g.headers=S.merge(g.headers.common||{},g.headers[g.method]||{},g.headers),S.forEach(["delete","get","head","post","put","patch","common"],(function cleanHeaderConfig(f){delete g.headers[f]})),(g.adapter||_.adapter)(g).then((function onAdapterResolution(f){return throwIfCancellationRequested(g),f.data=v(f.data,f.headers,g.transformResponse),f}),(function onAdapterRejection(f){return C(f)||(throwIfCancellationRequested(g),f&&f.response&&(f.response.data=v(f.response.data,f.response.headers,g.transformResponse))),Promise.reject(f)}))}}}),Y=__commonJS({"../node_modules/axios/lib/core/mergeConfig.js"(g,f){var S=O();f.exports=function mergeConfig(g,f){f=f||{};var v={},C=["url","method","params","data"],_=["headers","auth","proxy"],T=["baseURL","url","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"];S.forEach(C,(function valueFromConfig2(g){void 0!==f[g]&&(v[g]=f[g])})),S.forEach(_,(function mergeDeepProperties(C){S.isObject(f[C])?v[C]=S.deepMerge(g[C],f[C]):void 0!==f[C]?v[C]=f[C]:S.isObject(g[C])?v[C]=S.deepMerge(g[C]):void 0!==g[C]&&(v[C]=g[C])})),S.forEach(T,(function defaultToConfig2(S){void 0!==f[S]?v[S]=f[S]:void 0!==g[S]&&(v[S]=g[S])}));var I=C.concat(_).concat(T),b=Object.keys(f).filter((function filterAxiosKeys(g){return-1===I.indexOf(g)}));return S.forEach(b,(function otherKeysDefaultToConfig2(S){void 0!==f[S]?v[S]=f[S]:void 0!==g[S]&&(v[S]=g[S])})),v}}}),Q=__commonJS({"../node_modules/axios/lib/core/Axios.js"(g,f){var S=O(),v=D(),C=N(),_=J(),T=Y();function Axios(g){this.defaults=g,this.interceptors={request:new C,response:new C}}Axios.prototype.request=function request(g){"string"==typeof g?(g=arguments[1]||{}).url=arguments[0]:g=g||{},(g=T(this.defaults,g)).method?g.method=g.method.toLowerCase():this.defaults.method?g.method=this.defaults.method.toLowerCase():g.method="get";var f=[_,void 0],S=Promise.resolve(g);for(this.interceptors.request.forEach((function unshiftRequestInterceptors(g){f.unshift(g.fulfilled,g.rejected)})),this.interceptors.response.forEach((function pushResponseInterceptors(g){f.push(g.fulfilled,g.rejected)}));f.length;)S=S.then(f.shift(),f.shift());return S},Axios.prototype.getUri=function getUri(g){return g=T(this.defaults,g),v(g.url,g.params,g.paramsSerializer).replace(/^\?/,"")},S.forEach(["delete","get","head","options"],(function forEachMethodNoData(g){Axios.prototype[g]=function(f,v){return this.request(S.merge(v||{},{method:g,url:f}))}})),S.forEach(["post","put","patch"],(function forEachMethodWithData(g){Axios.prototype[g]=function(f,v,C){return this.request(S.merge(C||{},{method:g,url:f,data:v}))}})),f.exports=Axios}}),X=__commonJS({"../node_modules/axios/lib/cancel/Cancel.js"(g,f){function Cancel(g){this.message=g}Cancel.prototype.toString=function toString(){return"Cancel"+(this.message?": "+this.message:"")},Cancel.prototype.__CANCEL__=!0,f.exports=Cancel}}),Z=__commonJS({"../node_modules/axios/lib/cancel/CancelToken.js"(g,f){var S=X();function CancelToken(g){if("function"!=typeof g)throw new TypeError("executor must be a function.");var f;this.promise=new Promise((function promiseExecutor(g){f=g}));var v=this;g((function cancel(g){v.reason||(v.reason=new S(g),f(v.reason))}))}CancelToken.prototype.throwIfRequested=function throwIfRequested(){if(this.reason)throw this.reason},CancelToken.source=function source(){var g;return{token:new CancelToken((function executor(f){g=f})),cancel:g}},f.exports=CancelToken}}),ee=__commonJS({"../node_modules/axios/lib/helpers/spread.js"(g,f){f.exports=function spread(g){return function wrap(f){return g.apply(null,f)}}}}),te=__commonJS({"../node_modules/axios/lib/axios.js"(g,f){var S=O(),v=w(),C=Q(),_=Y();function createInstance(g){var f=new C(g),_=v(C.prototype.request,f);return S.extend(_,C.prototype,f),S.extend(_,f),_}var T=createInstance(K());T.Axios=C,T.create=function create(g){return createInstance(_(T.defaults,g))},T.Cancel=X(),T.CancelToken=Z(),T.isCancel=L(),T.all=function all(g){return Promise.all(g)},T.spread=ee(),f.exports=T,f.exports.default=T}}),ie=__commonJS({"../node_modules/axios/index.js"(g,f){f.exports=te()}}),ne=__commonJS({"../node_modules/ua-parser-js/src/ua-parser.js"(g,f){!function(S,v){var C="1.0.38",_="",T="?",I="function",b="undefined",A="object",P="string",R="major",M="model",w="name",O="type",D="vendor",N="version",k="architecture",L="console",F="mobile",x="tablet",U="smarttv",V="wearable",B="embedded",H=500,$="Amazon",j="Apple",G="ASUS",q="BlackBerry",W="Browser",z="Chrome",K="Firefox",J="Google",Y="Huawei",Q="LG",X="Microsoft",Z="Motorola",ee="Opera",te="Samsung",ie="Sharp",ne="Sony",re="Xiaomi",se="Zebra",ae="Facebook",oe="Chromium OS",le="Mac OS",extend3=function(g,f){var S={};for(var v in g)f[v]&&f[v].length%2==0?S[v]=f[v].concat(g[v]):S[v]=g[v];return S},enumerize=function(g){for(var f={},S=0;S<g.length;S++)f[g[S].toUpperCase()]=g[S];return f},has2=function(g,f){return typeof g===P&&-1!==lowerize(f).indexOf(lowerize(g))},lowerize=function(g){return g.toLowerCase()},majorize=function(g){return typeof g===P?g.replace(/[^\d\.]/g,_).split(".")[0]:v},trim2=function(g,f){if(typeof g===P)return g=g.replace(/^\s\s*/,_),typeof f===b?g:g.substring(0,H)},rgxMapper=function(g,f){for(var S,C,_,T,b,P,R=0;R<f.length&&!b;){var M=f[R],w=f[R+1];for(S=C=0;S<M.length&&!b&&M[S];)if(b=M[S++].exec(g))for(_=0;_<w.length;_++)P=b[++C],typeof(T=w[_])===A&&T.length>0?2===T.length?typeof T[1]==I?this[T[0]]=T[1].call(this,P):this[T[0]]=T[1]:3===T.length?typeof T[1]!==I||T[1].exec&&T[1].test?this[T[0]]=P?P.replace(T[1],T[2]):v:this[T[0]]=P?T[1].call(this,P,T[2]):v:4===T.length&&(this[T[0]]=P?T[3].call(this,P.replace(T[1],T[2])):v):this[T]=P||v;R+=2}},strMapper=function(g,f){for(var S in f)if(typeof f[S]===A&&f[S].length>0){for(var C=0;C<f[S].length;C++)if(has2(f[S][C],g))return S===T?v:S}else if(has2(f[S],g))return S===T?v:S;return g},ce={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},de={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[N,[w,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[N,[w,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[w,N],[/opios[\/ ]+([\w\.]+)/i],[N,[w,ee+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[N,[w,ee+" GX"]],[/\bopr\/([\w\.]+)/i],[N,[w,ee]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[N,[w,"Baidu"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim)\s?(?:browser)?[\/ ]?([\w\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[w,N],[/\bddg\/([\w\.]+)/i],[N,[w,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[N,[w,"UC"+W]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[N,[w,"WeChat"]],[/konqueror\/([\w\.]+)/i],[N,[w,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[N,[w,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[N,[w,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[N,[w,"Smart Lenovo "+W]],[/(avast|avg)\/([\w\.]+)/i],[[w,/(.+)/,"$1 Secure "+W],N],[/\bfocus\/([\w\.]+)/i],[N,[w,K+" Focus"]],[/\bopt\/([\w\.]+)/i],[N,[w,ee+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[N,[w,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[N,[w,"Dolphin"]],[/coast\/([\w\.]+)/i],[N,[w,ee+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[N,[w,"MIUI "+W]],[/fxios\/([-\w\.]+)/i],[N,[w,K]],[/\bqihu|(qi?ho?o?|360)browser/i],[[w,"360 "+W]],[/(oculus|sailfish|huawei|vivo)browser\/([\w\.]+)/i],[[w,/(.+)/,"$1 "+W],N],[/samsungbrowser\/([\w\.]+)/i],[N,[w,te+" Internet"]],[/(comodo_dragon)\/([\w\.]+)/i],[[w,/_/g," "],N],[/metasr[\/ ]?([\d\.]+)/i],[N,[w,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[w,"Sogou Mobile"],N],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345Explorer)[\/ ]?([\w\.]+)/i],[w,N],[/(lbbrowser)/i,/\[(linkedin)app\]/i],[w],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[w,ae],N],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[w,N],[/\bgsa\/([\w\.]+) .*safari\//i],[N,[w,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[N,[w,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[N,[w,z+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[w,z+" WebView"],N],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[N,[w,"Android "+W]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[w,N],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[N,[w,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[N,w],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[w,[N,strMapper,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[w,N],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[w,"Netscape"],N],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[N,[w,K+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[w,N],[/(cobalt)\/([\w\.]+)/i],[w,[N,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[k,"amd64"]],[/(ia32(?=;))/i],[[k,lowerize]],[/((?:i[346]|x)86)[;\)]/i],[[k,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[k,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[k,"armhf"]],[/windows (ce|mobile); ppc;/i],[[k,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[k,/ower/,_,lowerize]],[/(sun4\w)[;\)]/i],[[k,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[k,lowerize]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[M,[D,te],[O,x]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[M,[D,te],[O,F]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[M,[D,j],[O,F]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[M,[D,j],[O,x]],[/(macintosh);/i],[M,[D,j]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[M,[D,ie],[O,F]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[M,[D,Y],[O,x]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[M,[D,Y],[O,F]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[M,/_/g," "],[D,re],[O,F]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[M,/_/g," "],[D,re],[O,x]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[M,[D,"OPPO"],[O,F]],[/\b(opd2\d{3}a?) bui/i],[M,[D,"OPPO"],[O,x]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[M,[D,"Vivo"],[O,F]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[M,[D,"Realme"],[O,F]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[M,[D,Z],[O,F]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[M,[D,Z],[O,x]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[M,[D,Q],[O,x]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[M,[D,Q],[O,F]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[M,[D,"Lenovo"],[O,x]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[M,/_/g," "],[D,"Nokia"],[O,F]],[/(pixel c)\b/i],[M,[D,J],[O,x]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[M,[D,J],[O,F]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[M,[D,ne],[O,F]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[M,"Xperia Tablet"],[D,ne],[O,x]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[M,[D,"OnePlus"],[O,F]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[M,[D,$],[O,x]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[M,/(.+)/g,"Fire Phone $1"],[D,$],[O,F]],[/(playbook);[-\w\),; ]+(rim)/i],[M,D,[O,x]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[M,[D,q],[O,F]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[M,[D,G],[O,x]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[M,[D,G],[O,F]],[/(nexus 9)/i],[M,[D,"HTC"],[O,x]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[D,[M,/_/g," "],[O,F]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[M,[D,"Acer"],[O,x]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[M,[D,"Meizu"],[O,F]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[M,[D,"Ulefone"],[O,F]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[D,M,[O,F]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[D,M,[O,x]],[/(surface duo)/i],[M,[D,X],[O,x]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[M,[D,"Fairphone"],[O,F]],[/(u304aa)/i],[M,[D,"AT&T"],[O,F]],[/\bsie-(\w*)/i],[M,[D,"Siemens"],[O,F]],[/\b(rct\w+) b/i],[M,[D,"RCA"],[O,x]],[/\b(venue[\d ]{2,7}) b/i],[M,[D,"Dell"],[O,x]],[/\b(q(?:mv|ta)\w+) b/i],[M,[D,"Verizon"],[O,x]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[M,[D,"Barnes & Noble"],[O,x]],[/\b(tm\d{3}\w+) b/i],[M,[D,"NuVision"],[O,x]],[/\b(k88) b/i],[M,[D,"ZTE"],[O,x]],[/\b(nx\d{3}j) b/i],[M,[D,"ZTE"],[O,F]],[/\b(gen\d{3}) b.+49h/i],[M,[D,"Swiss"],[O,F]],[/\b(zur\d{3}) b/i],[M,[D,"Swiss"],[O,x]],[/\b((zeki)?tb.*\b) b/i],[M,[D,"Zeki"],[O,x]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[D,"Dragon Touch"],M,[O,x]],[/\b(ns-?\w{0,9}) b/i],[M,[D,"Insignia"],[O,x]],[/\b((nxa|next)-?\w{0,9}) b/i],[M,[D,"NextBook"],[O,x]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[D,"Voice"],M,[O,F]],[/\b(lvtel\-)?(v1[12]) b/i],[[D,"LvTel"],M,[O,F]],[/\b(ph-1) /i],[M,[D,"Essential"],[O,F]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[M,[D,"Envizen"],[O,x]],[/\b(trio[-\w\. ]+) b/i],[M,[D,"MachSpeed"],[O,x]],[/\btu_(1491) b/i],[M,[D,"Rotor"],[O,x]],[/(shield[\w ]+) b/i],[M,[D,"Nvidia"],[O,x]],[/(sprint) (\w+)/i],[D,M,[O,F]],[/(kin\.[onetw]{3})/i],[[M,/\./g," "],[D,X],[O,F]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[M,[D,se],[O,x]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[M,[D,se],[O,F]],[/smart-tv.+(samsung)/i],[D,[O,U]],[/hbbtv.+maple;(\d+)/i],[[M,/^/,"SmartTV"],[D,te],[O,U]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[D,Q],[O,U]],[/(apple) ?tv/i],[D,[M,j+" TV"],[O,U]],[/crkey/i],[[M,z+"cast"],[D,J],[O,U]],[/droid.+aft(\w+)( bui|\))/i],[M,[D,$],[O,U]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[M,[D,ie],[O,U]],[/(bravia[\w ]+)( bui|\))/i],[M,[D,ne],[O,U]],[/(mitv-\w{5}) bui/i],[M,[D,re],[O,U]],[/Hbbtv.*(technisat) (.*);/i],[D,M,[O,U]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[D,trim2],[M,trim2],[O,U]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[O,U]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[D,M,[O,L]],[/droid.+; (shield) bui/i],[M,[D,"Nvidia"],[O,L]],[/(playstation [345portablevi]+)/i],[M,[D,ne],[O,L]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[M,[D,X],[O,L]],[/((pebble))app/i],[D,M,[O,V]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[M,[D,j],[O,V]],[/droid.+; (glass) \d/i],[M,[D,J],[O,V]],[/droid.+; (wt63?0{2,3})\)/i],[M,[D,se],[O,V]],[/(quest( \d| pro)?)/i],[M,[D,ae],[O,V]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[D,[O,B]],[/(aeobc)\b/i],[M,[D,$],[O,B]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[M,[O,F]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[M,[O,x]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[O,x]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[O,F]],[/(android[-\w\. ]{0,9});.+buil/i],[M,[D,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[N,[w,"Edge"+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[N,[w,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[w,N],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[N,w]],os:[[/microsoft (windows) (vista|xp)/i],[w,N],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[w,[N,strMapper,ce]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[N,strMapper,ce],[w,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[N,/_/g,"."],[w,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[w,le],[N,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[N,w],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[w,N],[/\(bb(10);/i],[N,[w,q]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[N,[w,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[N,[w,K+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[N,[w,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[N,[w,"watchOS"]],[/crkey\/([\d\.]+)/i],[N,[w,z+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[w,oe],N],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[w,N],[/(sunos) ?([\w\.\d]*)/i],[[w,"Solaris"],N],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[w,N]]},UAParser2=function(g,f){if(typeof g===A&&(f=g,g=v),!(this instanceof UAParser2))return new UAParser2(g,f).getResult();var C=typeof S!==b&&S.navigator?S.navigator:v,T=g||(C&&C.userAgent?C.userAgent:_),L=C&&C.userAgentData?C.userAgentData:v,U=f?extend3(de,f):de,V=C&&C.userAgent==T;return this.getBrowser=function(){var g={};return g[w]=v,g[N]=v,rgxMapper.call(g,T,U.browser),g[R]=majorize(g[N]),V&&C&&C.brave&&typeof C.brave.isBrave==I&&(g[w]="Brave"),g},this.getCPU=function(){var g={};return g[k]=v,rgxMapper.call(g,T,U.cpu),g},this.getDevice=function(){var g={};return g[D]=v,g[M]=v,g[O]=v,rgxMapper.call(g,T,U.device),V&&!g[O]&&L&&L.mobile&&(g[O]=F),V&&"Macintosh"==g[M]&&C&&typeof C.standalone!==b&&C.maxTouchPoints&&C.maxTouchPoints>2&&(g[M]="iPad",g[O]=x),g},this.getEngine=function(){var g={};return g[w]=v,g[N]=v,rgxMapper.call(g,T,U.engine),g},this.getOS=function(){var g={};return g[w]=v,g[N]=v,rgxMapper.call(g,T,U.os),V&&!g[w]&&L&&L.platform&&"Unknown"!=L.platform&&(g[w]=L.platform.replace(/chrome os/i,oe).replace(/macos/i,le)),g},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 T},this.setUA=function(g){return T=typeof g===P&&g.length>H?trim2(g,H):g,this},this.setUA(T),this};UAParser2.VERSION=C,UAParser2.BROWSER=enumerize([w,N,R]),UAParser2.CPU=enumerize([k]),UAParser2.DEVICE=enumerize([M,D,O,L,F,U,x,V,B]),UAParser2.ENGINE=UAParser2.OS=enumerize([w,N]),typeof g!==b?(typeof f!==b&&f.exports&&(g=f.exports=UAParser2),g.UAParser=UAParser2):typeof S!==b&&(S.UAParser=UAParser2);var he=typeof S!==b&&(S.jQuery||S.Zepto);if(he&&!he.ua){var ue=new UAParser2;he.ua=ue.getResult(),he.ua.get=function(){return ue.getUA()},he.ua.set=function(g){ue.setUA(g);var f=ue.getResult();for(var S in f)he.ua[S]=f[S]}}}("object"==typeof window?window:g)}}),re=__commonJS({"../node_modules/@skype/hydra_player_sdk/hydra_player_sdk_bundle.js"(g,f){var S,v;S=g,v=function(){return g={103:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.defer=void 0,f.defer=function(){var g,f;return{promise:new Promise((function(S,v){g=S,f=v})),resolve:g,reject:f}}},457:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.iframeConfigDefault=void 0,f.iframeConfigDefault={scriptSrcDownload:!1,allowSameOrigin:!1}},1:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.liveStreamStatisticConfigDefault=void 0,f.liveStreamStatisticConfigDefault={maxUserInitiatedEventCount:100}},318:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.logSupportedCodecsConfigDefault=void 0,f.logSupportedCodecsConfigDefault={logSupportedCodecs:!1}},508:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.webRtcIceCandidateCollectorConfigDefault=void 0,f.webRtcIceCandidateCollectorConfigDefault={WebRtcIceCandidateCollectorDelayAfterCompleteMs:2500,WebRtcIceCandidateCollectorDelayAfterErrorMs:1e3,WebRtcIceCandidateCollectorMaxRetriesMs:5,WebRtcIceCandidateCollectorRetryDelayMs:100,WebRtcIceCandidateCollectorMaxCollectionTimeMs:6e4,WebRtcIceCandidateCollectorDisableCollection:!1}},10:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.default=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(g){var f=16*Math.random()|0;return("x"===g?f:3&f|8).toString(16)}))}},171:function(g,f,S){var v=this&&this.__assign||function(){return v=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},v.apply(this,arguments)},C=this&&this.__awaiter||function(g,f,S,v){return new(S||(S=Promise))((function(C,_){function o2(g){try{l2(v.next(g))}catch(g){_(g)}}function s2(g){try{l2(v.throw(g))}catch(g){_(g)}}function l2(g){var f;g.done?C(g.value):(f=g.value,f instanceof S?f:new S((function(g){g(f)}))).then(o2,s2)}l2((v=v.apply(g,f||[])).next())}))},_=this&&this.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:s2(0),throw:s2(1),return:s2(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function s2(I){return function(b){return function(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!((C=(C=T.trys).length>0&&C[C.length-1])||6!==I[0]&&2!==I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}([I,b])}}},T=this&&this.__spreadArray||function(g,f,S){if(S||2===arguments.length)for(var v,C=0,_=f.length;C<_;C++)!v&&C in f||(v||(v=Array.prototype.slice.call(f,0,C)),v[C]=f[C]);return g.concat(v||Array.prototype.slice.call(f))};Object.defineProperty(f,"__esModule",{value:!0}),f.LiveStreamStatistic=f.PlayerScenario=void 0;var I=S(346),b=S(963),A=S(1),P=S(534),R=S(318),M=function(){function e3(g,f,S){this.name=g,this.details=f,this.failReason=S,this.timeStamp=Date.now()}return e3.prototype.getName=function(){return this.name},e3.prototype.getFailReason=function(){return this.failReason},e3.prototype.getDetails=function(){return this.details},e3.prototype.getTimeStamp=function(){return this.timeStamp},e3}();f.PlayerScenario=M;var w=function(){function e3(g,f,S,v){this.config=g,this.logFn=f,this.playerDiagnosticsLog=S,this.playerMetadata=v,this.playerEvents=[],this.playbackEvents=[],this.ecdnPluginEvents=[],this.experimentalEvents=[],this.userInitiatedSeekEvents=[],this.userInitiatedPlayEvents=[],this.userInitiatedPauseEvents=[],this.hydraInitResult=null,this.callSetupSucceeded=!1,this.callDropped=!1,this.latestErrorReason=void 0,this.clientNetworkType=void 0,this.supportedCodecs=void 0,this.maxPlayerPlaybackEventCount=g.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=g.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=g.maxPlayerMemoryTraceLogCount||100,this.maxPlayerExperimentalEvents=g.maxPlayerExperimentalEvents||100,this.maxUserInitiatedEventCount=P.getECSSetting(this.config,"maxUserInitiatedEventCount",A.liveStreamStatisticConfigDefault.maxUserInitiatedEventCount),this.config.debugLogging&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener(),P.getECSSetting(this.config,"logSupportedCodecs",R.logSupportedCodecsConfigDefault.logSupportedCodecs)&&this.populateSupportedCodecs()}return e3.prototype.getPlayerDiagnosticSnapshot=function(){return this.currentPlayerDiagnosticSnapshot},e3.prototype.setHydraInitResult=function(g){this.hydraInitResult=g},e3.prototype.registerStatsUpdated=function(g){var f=this;this.currentPlayerDiagnosticSnapshot=g,Object.keys(this.playerDiagnosticsLog).forEach((function(S){var v,C=S,_=null!==(v=f.playerDiagnosticsLog[S])&&void 0!==v?v:[];if(Array.isArray(_)){_.push(g[C]);var T="memoryLog"===C&&_.length>f.maxPlayerMemoryTraceLogCount,I="memoryLog"!==C&&_.length>f.maxPlayerDiagnosticsCount;(T||I)&&_.splice(0,1)}else f.playerDiagnosticsLog[S]=g[C]}))},e3.prototype.registerEventLoadAttempt=function(g,f){this.registerScenario(g,f)},e3.prototype.registerEventLoadFailed=function(g,f){this.completeScenario(g,f)},e3.prototype.registerEventLoadSucceeded=function(g,f){this.completeScenario(g,void 0,f),g===b.PlayerScenarioType.LoadPlayer&&(this.callSetupSucceeded=!0)},e3.prototype.registerSdnPluginLoadAttempt=function(g){this.registerScenario(b.PlayerScenarioType.SdnPluginLoad,g)},e3.prototype.registerSdnPluginLoadFailed=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginLoad,g)},e3.prototype.registerSdnPluginLoadSucceeded=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginLoad,void 0,g)},e3.prototype.registerSdnPluginInitializeAttempt=function(g){this.registerScenario(b.PlayerScenarioType.SdnPluginInitialize,g)},e3.prototype.registerSdnPluginInitializeFailed=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginInitialize,g)},e3.prototype.registerSdnPluginInitializeSucceeded=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginInitialize,void 0,g)},e3.prototype.registerSdnPluginSetSourceAttempt=function(g){this.registerScenario(b.PlayerScenarioType.SdnPluginSetSource,g)},e3.prototype.registerSdnPluginSetSourceFailed=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginSetSource,g)},e3.prototype.registerSdnPluginSetSourceSucceeded=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginSetSource,void 0,g)},e3.prototype.registerStreamConnectionAttempt=function(g){this.registerScenario(b.PlayerScenarioType.StreamConnection,{streamUrl:g})},e3.prototype.registerStreamConnectionSucceeded=function(g){this.completeScenario(b.PlayerScenarioType.StreamConnection,void 0,{result:P.stringifyObject(g)})},e3.prototype.registerStreamConnectionFailed=function(g,f){this.completeScenario(b.PlayerScenarioType.StreamConnection,g,{result:P.stringifyObject(f)})},e3.prototype.registerSetSourceAttempt=function(g,f,S){var v=g||"";S&&(v={src:g||"",isPrimary:P.stringifyObject(f),reason:S}),this.registerScenario(b.PlayerScenarioType.SetSource,v)},e3.prototype.registerSetSourceSucceeded=function(g,f,S,v,C){this.completeScenario(b.PlayerScenarioType.SetSource,void 0,{src:g,isPrimary:P.stringifyObject(f),switchingDiagnostics:P.stringifyObject(S),stepDuration:P.stringifyObject(v),initialSeekToLiveEdge:P.stringifyObject(C)})},e3.prototype.registerSetSourceFailed=function(g,f,S,v,C){this.completeScenario(b.PlayerScenarioType.SetSource,g,{src:P.stringifyObject(f),isPrimary:P.stringifyObject(S),switchingDiagnostics:P.stringifyObject(v),stepDuration:P.stringifyObject(C)})},e3.prototype.registerPlayerDestroyed=function(g){this.registerScenario(b.PlayerScenarioType.Destroyed,g),this.completeScenario(b.PlayerScenarioType.Destroyed)},e3.prototype.registerPlaybackStateChanged=function(g,f){var S,v,C,_,T,A;if(g!==I.HydraPlayerPlaybackState.CanPlayThrough||this.firstReadyStateTimestamp){if(g===I.HydraPlayerPlaybackState.Playing){if(this.firstPlayingState||(this.firstPlayingState={timestamp:Date.now()},f&&(f.edgeLatency&&(this.firstPlayingState.edgeLatency=f.edgeLatency),f.bufferLength&&(this.firstPlayingState.bufferLength=f.bufferLength))),this.userInitiatedSeekEvents.length>0){var P=this.userInitiatedSeekEvents[this.userInitiatedSeekEvents.length-1];this.modifyTelemetryEventPayload(P,{playingStatePosition:null!==(v=null===(S=this.currentPlayerDiagnosticSnapshot)||void 0===S?void 0:S.currentPlayPosition)&&void 0!==v?v:-1,playingStateTimestamp:Date.now()},!1)}if(this.userInitiatedPlayEvents.length>0){var R=this.userInitiatedPlayEvents[this.userInitiatedPlayEvents.length-1];this.modifyTelemetryEventPayload(R,{playingStatePosition:null!==(_=null===(C=this.currentPlayerDiagnosticSnapshot)||void 0===C?void 0:C.currentPlayPosition)&&void 0!==_?_:-1,playingStateTimestamp:Date.now()},!1)}}else if(g===I.HydraPlayerPlaybackState.Pause&&this.userInitiatedPauseEvents.length>0){var M=this.userInitiatedPauseEvents[this.userInitiatedPauseEvents.length-1];this.modifyTelemetryEventPayload(M,{pauseStatePosition:null!==(A=null===(T=this.currentPlayerDiagnosticSnapshot)||void 0===T?void 0:T.currentPlayPosition)&&void 0!==A?A:-1,pauseStateTimestamp:Date.now()},!1)}}else this.firstReadyStateTimestamp=Date.now();this.registerPlaybackEvent(b.TelemetryEventType.StateChanged,g)},e3.prototype.registerCapabilitiesUpdated=function(g){this.registerPlaybackEvent(b.TelemetryEventType.CapabilitiesUpdated,g)},e3.prototype.registerHydraInputStateChanged=function(g,f){this.registerPlaybackEvent(b.TelemetryEventType.HydraInputStateChanged,g,f)},e3.prototype.registerHydraOutputStateChanged=function(g,f){this.registerPlaybackEvent(b.TelemetryEventType.HydraOutputStateChanged,g,f)},e3.prototype.registerPlaybackBuffering=function(g){this.registerPlaybackEvent(b.TelemetryEventType.Buffering,g)},e3.prototype.registerSdnPluginEvent=function(g){var f=this.createTelemetryEvent(b.TelemetryEventType.EcdnPluginEvents,g);this.ecdnPluginEvents.push(f),this.ecdnPluginEvents.length>this.maxPlayerPlaybackEventCount&&this.ecdnPluginEvents.splice(0,1),this.logTelemetryEvent(f)},e3.prototype.registerPlaybackError=function(g,f,S,v){this.registerPlaybackEvent(b.TelemetryEventType.Error,{errorType:g,details:f,errorSource:S,errorReason:v}),this.latestErrorReason=v},e3.prototype.registerIgnoredPlaybackError=function(g){this.registerPlaybackEvent(b.TelemetryEventType.IgnoredError,g)},e3.prototype.registerDownloadBitrateChanged=function(g){this.registerPlaybackEvent(b.TelemetryEventType.BitrateChangedDownload,g)},e3.prototype.registerStreamOptionsConfigured=function(g,f){this.registerPlaybackEvent(b.TelemetryEventType.StreamOptionsConfigured,g,f)},e3.prototype.registerPlaybackBitrateChanged=function(g){this.registerPlaybackEvent(b.TelemetryEventType.BitrateChangedPlayback,g)},e3.prototype.registerVolumeChange=function(g){this.registerPlaybackEvent(b.TelemetryEventType.Volume,g)},e3.prototype.getSnapshotReport=function(){var g,f,S=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.buildCompleteTelemetryEvent()),C=this.playbackEvents,_={};this.currentPlayerDiagnosticSnapshot&&(_=this.filterAndPrepareTelemetry());var T=P.getECSSetting(this.config,"logSupportedCodecs",R.logSupportedCodecsConfigDefault.logSupportedCodecs);return v(v(v(v(v(v(v(v(v(v(v(v(v(v(v(v({isFullReport:!1,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(f=null===(g=this.currentPlayerDiagnosticSnapshot)||void 0===g?void 0:g.statsInterval)&&void 0!==f?f:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(S)),this.getHydraInternalReport(C)),this.getPlaybackReport(C)),this.getBitrateReport(C)),this.getStreamConnectionReport(S)),this.getSdnReport(S)),this.getSetSourceReport(S)),this.getExperimentalEvents()),this.getUserInitiatedSeekEvents()),{networkType:this.getClientNetworkType()}),T?{supportedCodecs:P.stringifyObject(this.supportedCodecs)}:{}),{callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),_)},e3.prototype.getReport=function(){var g,f,S,C,_=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.buildCompleteTelemetryEvent()),T=this.playbackEvents,I=P.getECSSetting(this.config,"logSupportedCodecs",R.logSupportedCodecsConfigDefault.logSupportedCodecs);return v(v(v(v(v(v(v(v(v(v(v(v(v(v(v(v(v({isFullReport:!0,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(f=null===(g=this.currentPlayerDiagnosticSnapshot)||void 0===g?void 0:g.statsInterval)&&void 0!==f?f:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(_)),this.getHydraInternalReport(T)),this.getPlaybackReport(T)),this.getBitrateReport(T)),this.getStreamConnectionReport(_)),this.getSdnReport(_)),this.getSetSourceReport(_)),this.getExperimentalEvents()),this.getUserInitiatedSeekEvents()),{networkType:this.getClientNetworkType()}),I?{supportedCodecs:P.stringifyObject(this.supportedCodecs)}:{}),{callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),this.getPlayerDiagnosticLog()),{eventId:(null===(S=this.currentPlayerDiagnosticSnapshot)||void 0===S?void 0:S.eventId)||"",templateId:(null===(C=this.currentPlayerDiagnosticSnapshot)||void 0===C?void 0:C.templateId)||""})},e3.prototype.buildCompleteTelemetryEvent=function(){this.playerEvents.sort((function(g,f){return g.getName()!==f.getName()?Object.keys(b.PlayerScenarioType).indexOf(g.getName())-Object.keys(b.PlayerScenarioType).indexOf(f.getName()):g.getTimeStamp()-f.getTimeStamp()}));for(var g,f,S,C,_,T=[],I=0,A=this.playerEvents;I<A.length;I++){var P=A[I],R=T[T.length-1];T.length&&P.getName()===R.name&&0===R.duration?T[T.length-1]=(g=R,S=(f=P).getFailReason()?{failReason:f.getFailReason()}:{},C=f.getDetails()?{details:f.getDetails()}:{},_={name:g.name,startTime:g.startTime,duration:f.getTimeStamp()>g.startTime?f.getTimeStamp()-g.startTime:g.duration},v(v(v({},_),S),C)):T.push({name:b.PlayerScenarioType[P.getName()],startTime:P.getTimeStamp(),duration:0})}return T},e3.prototype.getHydraLoadEvent=function(){var g,f,S,v={name:b.PlayerScenarioType.LoadHydra,startTime:(null===(g=this.hydraInitResult)||void 0===g?void 0:g.initStartTime)||-1,duration:(null===(f=this.hydraInitResult)||void 0===f?void 0:f.initDuration)||0};(null===(S=this.hydraInitResult)||void 0===S?void 0:S.errorMsg)&&(v.failReason=this.hydraInitResult.errorMsg);var C=this.getHydraRuntimeDownloadDetails();return C&&(v.details=C),v},e3.prototype.getHydraRuntimeDownloadDetails=function(){if(this.hydraInitResult){for(var g=[],f=0,S=this.hydraInitResult.runtimeDownloadResults;f<S.length;f++){var v=S[f],C={success:v.success,url:v.url,startTime:v.startTime,duration:v.duration,trackingReference:v.trackingReference,timeTakenToDownloadScript:v.timeTakenToDownloadScript};v.errorMsg&&(C.errorMsg=v.errorMsg),g.push(C)}return P.stringifyObject(g)}return null},e3.prototype.getTotalLoadEvent=function(){var g,f,S,v=this.getScenario(b.PlayerScenarioType.LoadPlayer),C=(null===(g=this.hydraInitResult)||void 0===g?void 0:g.initDuration)||0,_=v.length>0?v[v.length-1].getTimeStamp()-v[0].getTimeStamp():0,T=v.length>0?v[v.length-1].getFailReason():void 0,I={name:b.PlayerScenarioType.Load,startTime:(null===(f=this.hydraInitResult)||void 0===f?void 0:f.initStartTime)||-1,duration:C+_};return(null===(S=this.hydraInitResult)||void 0===S?void 0:S.errorMsg)?I.failReason=this.hydraInitResult.errorMsg:T&&(I.failReason=T),I},e3.prototype.getPlayerMetadataReport=function(){return{playerId:this.playerMetadata.playerId||"",traceId:this.playerMetadata.playerId?this.playerMetadata.playerId.replace(/-/g,""):"",hydraPlayerRuntimeVersion:this.playerMetadata.hydraPlayerRuntimeVersion||"",hydraPlayerSdkVersion:this.playerMetadata.hydraPlayerSdkVersion,player_playerType:this.playerMetadata.hydraPlayerType}},e3.prototype.registerPlaybackEvent=function(g,f,S){var v=this.createTelemetryEvent(g,f,S);g===b.TelemetryEventType.Error&&(null==f?void 0:f.errorType)!==I.HydraPlayerPlaybackErrorType.PlaybackRetried&&(v.fatal=!0,this.callDropped=!0),this.playbackEvents.push(v),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(v)},e3.prototype.getPlayerDiagnosticLog=function(){var g=this;if(!this.currentPlayerDiagnosticSnapshot)return{};var f=this.currentPlayerDiagnosticSnapshot,S=this.playerDiagnosticsLog,C=v(v({},f),S),_={};return Object.keys(C).forEach((function(f){_["player_".concat(f)]=g.prepareForTelemetry(C[f])})),_},e3.prototype.getHydraInitializationReport=function(){var g,f,S,v;return{hydraInit_succeeded:(null===(g=this.hydraInitResult)||void 0===g?void 0:g.initSucceeded)||!1,hydraInit_startTime:(null===(f=this.hydraInitResult)||void 0===f?void 0:f.initStartTime)||-1,hydraInit_errorMessage:(null===(S=this.hydraInitResult)||void 0===S?void 0:S.errorMsg)||"",hydraInit_duration:(null===(v=this.hydraInitResult)||void 0===v?void 0:v.initDuration)||0}},e3.prototype.getPlayerInitializationReport=function(g){var f,S=g.find((function(g){return g.name===b.PlayerScenarioType.Load})),v=this.playerEvents.find((function(g){return g.getName()===b.PlayerScenarioType.StreamConnection})),C={init_timeLoadToStreamConnectionEstablished:(S&&v?v.getTimeStamp()-S.startTime:-1)||-1,init_timeLoadToReady:(S&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-S.startTime:-1)||-1,init_timeLoadToPlaying:(S&&(null===(f=this.firstPlayingState)||void 0===f?void 0:f.timestamp)?this.firstPlayingState.timestamp-S.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(g)};return this.firstPlayingState&&(C.init_firstPlayingStateStatistics=this.prepareForTelemetry(this.firstPlayingState)),C},e3.prototype.getHydraInternalReport=function(g){var f=g.filter((function(g){return g.eventType===b.TelemetryEventType.HydraInputStateChanged})),S=g.filter((function(g){return g.eventType===b.TelemetryEventType.HydraOutputStateChanged}));return{hydra_inputStateChangeEvents:this.prepareForTelemetry(f),hydra_outputStateChangeEvents:this.prepareForTelemetry(S)}},e3.prototype.getPlaybackReport=function(g){var f=g.filter((function(g){return g.eventType===b.TelemetryEventType.StateChanged})),S=f.find((function(g){return g.payload===I.HydraPlayerPlaybackState.CanPlayThrough})),v=f.find((function(g){return g.payload===I.HydraPlayerPlaybackState.Play})),C=f.find((function(g){return g.payload===I.HydraPlayerPlaybackState.Start})),_=f.find((function(g){return g.payload===I.HydraPlayerPlaybackState.Playing})),T=null!=S&&null!=v?v.timestamp-S.timestamp:-1,A=null!=v&&null!=C?C.timestamp-v.timestamp:-1,P=null!=C&&null!=_?_.timestamp-C.timestamp:-1,R=f.filter((function(g){return g.payload===I.HydraPlayerPlaybackState.Seeked})),M=f.filter((function(g){return g.payload===I.HydraPlayerPlaybackState.Seeking})),w=f.filter((function(g){return g.payload===I.HydraPlayerPlaybackState.Pause})),O=f.filter((function(g){return g.payload===I.HydraPlayerPlaybackState.Waiting})),D=[b.TelemetryEventType.BitrateChangedDownload,b.TelemetryEventType.BitrateChangedPlayback,b.TelemetryEventType.Error,b.TelemetryEventType.Mute,b.TelemetryEventType.StateChanged,b.TelemetryEventType.Volume,b.TelemetryEventType.StreamOptionsConfigured,b.TelemetryEventType.IgnoredError],N=g.filter((function(g){return g.eventType===b.TelemetryEventType.Error})),k=g.filter((function(g){return g.eventType===b.TelemetryEventType.IgnoredError})),L=g.filter((function(g){return g.eventType===b.TelemetryEventType.Volume||g.eventType===b.TelemetryEventType.Mute})),F=g.filter((function(g){return g.eventType===b.TelemetryEventType.StreamOptionsConfigured})),x=g.filter((function(g){return!D.includes(g.eventType)}));return{playback_timeReadyToPlay:T,playback_timePlayToStart:A,playback_timeStartToPlaying:P,playback_bufferingEvents:this.prepareForTelemetry(O),playback_errorEvents:this.prepareForTelemetry(N),playback_ignoredErrorEvents:this.prepareForTelemetry(k),playback_pauseEvents:this.prepareForTelemetry(w),playback_otherEvents:this.prepareForTelemetry(x),playback_seekedEvents:this.prepareForTelemetry(R),playback_seekingEvents:this.prepareForTelemetry(M),playback_stateChangeEvents:this.prepareForTelemetry(f),playback_volumeEvents:this.prepareForTelemetry(L),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(F),playback_latestErrorReason:this.latestErrorReason||""}},e3.prototype.getBitrateReport=function(g){var f,S,C,_,T=g.filter((function(g){return g.eventType===b.TelemetryEventType.BitrateChangedDownload})),I=T.sort((function(g){return Number(g.payload)})),A=T.length>0?{bitrate_downloadChanges:this.prepareForTelemetry(T),bitrate_downloadChangeCount:T.length>0||-1,bitrate_downloadMin:(null===(f=I[0])||void 0===f?void 0:f.payload)||-1,bitrate_downloadMax:(null===(S=I[I.length-1])||void 0===S?void 0:S.payload)||-1}:{},P=g.filter((function(g){return g.eventType===b.TelemetryEventType.BitrateChangedPlayback})),R=P.sort((function(g){return Number(g.payload)})),M=P.length>0?{bitrate_playbackChanges:this.prepareForTelemetry(P),bitrate_playbackChangeCount:P.length>0||-1,bitrate_playbackMin:(null===(C=R[0])||void 0===C?void 0:C.payload)||-1,bitrate_playbackMax:(null===(_=R[R.length-1])||void 0===_?void 0:_.payload)||-1}:{};return v(v({},A),M)},e3.prototype.addNetworkTypeEventListener=function(){var g,f,S,v,C=this;(null===(f=null===(g=window.navigator)||void 0===g?void 0:g.connection)||void 0===f?void 0:f.type)&&(null===(v=null===(S=window.navigator)||void 0===S?void 0:S.connection)||void 0===v||v.addEventListener("change",(function(){C.updateClientNetworkType()})))},e3.prototype.updateClientNetworkType=function(){this.clientNetworkType=void 0,this.getClientNetworkType()},e3.prototype.getClientNetworkType=function(){var g,f,S,v;if(void 0===this.clientNetworkType){var C="Unknown";if(null===(f=null===(g=window.navigator)||void 0===g?void 0:g.connection)||void 0===f?void 0:f.type)switch(null===(v=null===(S=window.navigator)||void 0===S?void 0:S.connection)||void 0===v?void 0:v.type){case"cellular":C="WWAN";break;case"ethernet":C="Wired";break;case"wifi":C="Wireless";break;default:C="Unknown"}this.clientNetworkType=C}return this.clientNetworkType},e3.prototype.getCodecList=function(){return[{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L93",width:1920,height:1080,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L90",width:1920,height:1080,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L63",width:1280,height:720,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L60",width:1280,height:720,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L30",width:640,height:480,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.64002A",width:1920,height:1080,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.640028",width:1920,height:1080,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.640020",width:1280,height:720,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.64001E",width:1280,height:720,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.640015",width:640,height:480,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/webm; codecs=vp09.00.10.08",width:1920,height:1080,bitrate:5e6,framerate:30}},{type:"file",video:{contentType:"video/webm; codecs=vp8",width:1920,height:1080,bitrate:5e6,framerate:30}},{type:"file",video:{contentType:"video/ogg; codecs=theora, vorbis",width:640,height:480,bitrate:5e5,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.05M.08",width:1920,height:1080,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.04M.08",width:1920,height:1080,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.03M.08",width:1280,height:720,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.03M.08",width:1280,height:720,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.02M.08",width:640,height:480,bitrate:1e4,framerate:30}},{type:"file",audio:{contentType:"audio/webm; codecs=opus",channels:"2",bitrate:64e3,samplerate:48e3}},{type:"file",audio:{contentType:"audio/ogg; codecs=vorbis",channels:"2",bitrate:128e3,samplerate:44100}},{type:"file",audio:{contentType:"audio/mp4; codecs=mp4a.40.2",channels:"2",bitrate:128e3,samplerate:44100}},{type:"file",audio:{contentType:"audio/mp4; codecs=mp4a.40.5",channels:"2",bitrate:64e3,samplerate:48e3}},{type:"file",audio:{contentType:"audio/mpeg",channels:"2",bitrate:128e3,samplerate:44100}},{type:"file",audio:{contentType:"audio/flac",channels:"2",bitrate:32e4,samplerate:96e3}},{type:"file",audio:{contentType:"audio/mp4 codecs=ac-3",channels:"6",bitrate:64e4,samplerate:48e3}},{type:"file",audio:{contentType:"audio/mp4 codecs=ec-3",channels:"6",bitrate:64e4,samplerate:48e3}},{type:"file",audio:{contentType:"audio/wav; codecs=1",channels:"2",bitrate:1411200,samplerate:44100}}]},e3.prototype.getAudioVideoCodecsSupported=function(g){return C(this,void 0,void 0,(function(){var f,S,v=this;return _(this,(function(T){switch(T.label){case 0:return f=[],"mediaCapabilities"in navigator?(S=g.map((function(g){return C(v,void 0,void 0,(function(){var S,v;return _(this,(function(C){switch(C.label){case 0:S=g,C.label=1;case 1:return C.trys.push([1,3,,4]),[4,navigator.mediaCapabilities.decodingInfo(S)];case 2:return(v=C.sent()).supported&&(g.video?f.push({codec:g.video.contentType,supported:v.supported,smooth:v.smooth,powerEfficient:v.powerEfficient,resolution:g.video.height,framerate:g.video.framerate}):g.audio&&f.push({codec:g.audio.contentType,supported:v.supported,smooth:v.smooth,powerEfficient:v.powerEfficient})),[3,4];case 3:return C.sent(),[3,4];case 4:return[2]}}))}))})),[4,Promise.allSettled(S)]):[3,2];case 1:T.sent(),T.label=2;case 2:return[2,f]}}))}))},e3.prototype.populateSupportedCodecs=function(){var g=this;void 0===this.supportedCodecs&&this.getAudioVideoCodecsSupported(this.getCodecList()).then((function(f){g.supportedCodecs=f}))},e3.prototype.getSdnReport=function(g){var f,S=g.filter((function(g){return[b.PlayerScenarioType.SdnPluginLoad,b.PlayerScenarioType.SdnPluginInitialize,b.PlayerScenarioType.SdnPluginSetSource].includes(g.name)})),v=T(T([],S,!0),this.ecdnPluginEvents,!0),C=S.filter((function(g){return void 0!==g.failReason})),_=S.filter((function(g){return g.name===b.PlayerScenarioType.SdnPluginLoad})).sort((function(g,f){return f.startTime-g.startTime}))[0];return{sdn_loaded:!(null==_||void 0!==_.failReason),sdn_details:null!==(f=null==_?void 0:_.details)&&void 0!==f?f:"",sdn_error:C.length>0&&C[C.length-1].failReason||"",sdn_events:this.prepareForTelemetry(v)}},e3.prototype.getStreamConnectionReport=function(g){var f=g.filter((function(g){return g.name===b.PlayerScenarioType.StreamConnection}));return{stream_connection_events:this.prepareForTelemetry(f)}},e3.prototype.getSetSourceReport=function(g){var f=g.filter((function(g){return g.name===b.PlayerScenarioType.SetSource}));return{set_source_events:this.prepareForTelemetry(f)}},e3.prototype.registerScenario=function(g,f){this.playerEvents.push(new M(g,f))},e3.prototype.completeScenario=function(g,f,S){this.playerEvents.push(new M(g,S,f))},e3.prototype.logTelemetryEvent=function(g){this.config.debugLogging&&(this.logFn("debug","PlayerTelemetryEvent: ".concat(JSON.stringify(g))),this.logFn("debug","PlayerDiagnosticData: ".concat(JSON.stringify(this.currentPlayerDiagnosticSnapshot))))},e3.prototype.filterAndPrepareTelemetry=function(){var g=this,f=new Set;f.add("serviceLatencyCdg"),f.add("endToEndLatencyCdg"),f.add("videoEdgeLatencyCdg"),f.add("eventId"),f.add("templateId");var S={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((function(v){f.has(v)||(S["player_".concat(v)]=g.prepareForTelemetry(g.currentPlayerDiagnosticSnapshot[v]))})),S},e3.prototype.prepareForTelemetry=function(g){return"boolean"==typeof g?g:"string"==typeof g||void 0===g?g||"":"number"==typeof g?null!=g?g:-1:JSON.stringify(g)},e3.prototype.getScenario=function(g){return this.playerEvents.filter((function(f){return f.getName()===g}))},e3.prototype.createTelemetryEvent=function(g,f,S){var v,C,_={eventType:g,timestamp:Date.now(),currentPlayPosition:null!==(C=null===(v=this.currentPlayerDiagnosticSnapshot)||void 0===v?void 0:v.currentPlayPosition)&&void 0!==C?C:-1};return void 0!==f&&(_.payload=this.prepareForTelemetry(f)),_.message=S,_},e3.prototype.modifyTelemetryEventPayload=function(g,f,S){try{if(g.payload){var C=JSON.parse(g.payload);C=S?v(v({},C),f):v(v({},f),C),g.payload=this.prepareForTelemetry(C)}else g.payload=this.prepareForTelemetry(f)}catch(f){this.logFn("error","Failed to modify payload for event: ".concat(P.stringifyObject(g),", error: ").concat(f))}},e3.prototype.registerExperimentalEvent=function(g,f,S){var v=this.createTelemetryEvent(g,f,S);this.experimentalEvents.push(v),this.experimentalEvents.length>this.maxPlayerExperimentalEvents&&this.experimentalEvents.splice(0,1),this.logTelemetryEvent(v)},e3.prototype.getExperimentalEvents=function(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}},e3.prototype.registerUserInitiatedSeek=function(g){var f,S,v={newCurrentPlayPosition:g,seekForward:(null!==(S=null===(f=this.currentPlayerDiagnosticSnapshot)||void 0===f?void 0:f.currentPlayPosition)&&void 0!==S?S:-1)<g},C=this.createTelemetryEvent(b.TelemetryEventType.UserInitiatedSeek,v);this.userInitiatedSeekEvents.push(C),this.userInitiatedSeekEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedSeekEvents.splice(0,1)},e3.prototype.registerUserInitiatedPlay=function(){var g=this.createTelemetryEvent(b.TelemetryEventType.UserInitiatedPlay);this.userInitiatedPlayEvents.push(g),this.userInitiatedPlayEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedPlayEvents.splice(0,1)},e3.prototype.registerUserInitiatedPause=function(){var g=this.createTelemetryEvent(b.TelemetryEventType.UserInitiatedPause);this.userInitiatedPauseEvents.push(g),this.userInitiatedPauseEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedPauseEvents.splice(0,1)},e3.prototype.getUserInitiatedSeekEvents=function(){return{playback_userInitiatedSeekEvents:this.prepareForTelemetry(this.userInitiatedSeekEvents),playback_userInitiatedPlayEvents:this.prepareForTelemetry(this.userInitiatedPlayEvents),playback_userInitiatedPauseEvents:this.prepareForTelemetry(this.userInitiatedPauseEvents)}},e3.prototype.registerPlayBlocked=function(g){this.registerScenario(b.PlayerScenarioType.PlayAttemptBlocked,"Called video element play() but it failed with error: ".concat(g)),this.completeScenario(b.PlayerScenarioType.PlayAttemptBlocked)},e3}();f.LiveStreamStatistic=w},42:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.Spinner=void 0;var S=function(){function e3(g){this.container=g,this.spinnerId="hydra-player-spinner",this.firstSpinnerShowTimestamp=null,this.firstSpinnerHideTimestamp=null,this.spinnerInfoHistory=[],this.maxTimestampHistorySize=100;var f=this.container.ownerDocument.getElementById(this.spinnerId);if(f)return this.spinner=f,void this.show();var S=this.container.ownerDocument.createElement("style");S.textContent="\n            .ml-player-spinner-container {\n                width: 100%;\n                height: 100%;\n                display: flex;\n                justify-content: center;\n                align-items: center;\n                position: absolute;\n                pointer-events: none;\n            }\n            .ml-player-spinner {\n                width: 3.6rem;\n                height: 3.6rem;\n                display: block;\n                overflow-clip-margin: content-box;\n                overflow: hidden;\n                animation: ml-player-spinner-outer-rotate 3s linear infinite;\n            }\n            .ml-player-spinner-dark-wheel {\n                fill: none;\n                r: 45%;\n                cx: 50%;\n                cy: 50%;\n                stroke: rgb(68, 71, 145);\n                stroke-width: 8px;\n            }\n            .ml-player-spinner-light-wheel {\n                fill: none;\n                r: 45%;\n                cx: 50%;\n                cy: 50%;\n                stroke: rgb(127, 133, 245);\n                stroke-width: 8px;\n                stroke-dasharray: 283;\n                stroke-dashoffset: 280;\n                stroke-linecap: round;\n                transform-origin: 50% 50%;\n                animation: ml-player-spinner-inner-rotate 1.5s cubic-bezier(0.33, 0, 0.67, 1) infinite;\n            }\n            @keyframes ml-player-spinner-outer-rotate {\n                0% {\n                    transform: rotate(0deg);\n                }\n                100% {\n                    transform: rotate(360deg);\n                }\n            }\n            @keyframes ml-player-spinner-inner-rotate {\n                0% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(0deg);\n                }\n                25% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(0deg);\n                }\n                50% {\n                    stroke-dashoffset: 75;\n                    transform: rotate(45deg);\n                }\n                75% {\n                    stroke-dashoffset: 75;\n                    transform: rotate(45deg);\n                }\n                100% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(360deg);\n                }\n            }\n        ",this.container.ownerDocument.head.appendChild(S),this.container.style.position="relative";var v=this.container.ownerDocument.createElement("div");v.classList.add("ml-player-spinner-container"),this.container.appendChild(v),this.spinner=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","svg"),this.spinner.style.position="absolute",this.spinner.setAttribute("viewBox","0 0 100 100"),this.spinner.classList.add("ml-player-spinner"),this.spinner.id=this.spinnerId,v.appendChild(this.spinner);var C=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");C.classList.add("ml-player-spinner-dark-wheel"),this.spinner.appendChild(C);var _=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");_.classList.add("ml-player-spinner-light-wheel"),this.spinner.appendChild(_),this.show()}return Object.defineProperty(e3.prototype,"firstShowTimestamp",{get:function(){return this.firstSpinnerShowTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e3.prototype,"firstHideTimestamp",{get:function(){return this.firstSpinnerHideTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e3.prototype,"firstSpinnerDuration",{get:function(){return this.firstSpinnerShowTimestamp?this.firstSpinnerHideTimestamp?this.firstSpinnerHideTimestamp-this.firstSpinnerShowTimestamp:Date.now()-this.firstSpinnerShowTimestamp:null},enumerable:!1,configurable:!0}),Object.defineProperty(e3.prototype,"visibilityHistory",{get:function(){if(this.spinnerInfoHistory.length>0){var g=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];g.hideTimestamp||(g.displayDuration=Date.now()-g.showTimestamp)}return this.spinnerInfoHistory},enumerable:!1,configurable:!0}),e3.prototype.show=function(){var g=Date.now();this.firstSpinnerShowTimestamp||(this.firstSpinnerShowTimestamp=g),(0===this.spinnerInfoHistory.length||this.spinnerInfoHistory[this.spinnerInfoHistory.length-1].hideTimestamp)&&(this.spinnerInfoHistory.push({showTimestamp:g,displayDuration:0}),this.spinnerInfoHistory.length>this.maxTimestampHistorySize&&this.spinnerInfoHistory.splice(0,1)),this.spinner.style.display="block"},e3.prototype.hide=function(){var g=Date.now();if(this.firstSpinnerHideTimestamp||(this.firstSpinnerHideTimestamp=g),this.spinnerInfoHistory.length>0){var f=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];f.hideTimestamp||(f.hideTimestamp=g,f.displayDuration=g-f.showTimestamp)}this.spinner.style.display="none"},e3.prototype.isVisible=function(){return"none"!==this.spinner.style.display},e3}();f.Spinner=S},378:function(g,f){var S,v;Object.defineProperty(f,"__esModule",{value:!0}),f.MessageType=void 0,(v=S||(f.MessageType=S={})).Command="Command",v.CommandSuccessResult="CommandSuccessResult",v.CommandFailureResult="CommandFailureResult",v.PlayerEvent="PlayerEvent",v.InternalPlayerEvent="InternalPlayerEvent"},963:function(g,f){var S,v,C;Object.defineProperty(f,"__esModule",{value:!0}),f.PlayerScenarioType=f.TelemetryEventType=void 0,(C=S||(f.TelemetryEventType=S={})).BitrateChangedDownload="BitrateChangedDownload",C.StreamOptionsConfigured="StreamOptionsConfigured",C.BitrateChangedPlayback="BitrateChangedPlayback",C.CaptionsToggled="CaptionsToggled",C.Error="Error",C.IgnoredError="IgnoredError",C.FullscreenChanged="FullscreenChanged",C.Mute="Mute",C.PotentialMediaFreeze="PotentialMediaFreeze",C.StateChanged="StateChanged",C.HydraInputStateChanged="HydraInputStateChanged",C.HydraOutputStateChanged="HydraOutputStateChanged",C.Volume="Volume",C.Buffering="Buffering",C.Online="Online",C.Offline="Offline",C.NetworkChange="NetworkChange",C.HlsEvents="HlsEvents",C.EcdnPluginEvents="EcdnPluginEvents",C.UserInitiatedSeek="UserInitiatedSeek",C.UserInitiatedPlay="UserInitiatedPlay",C.UserInitiatedPause="UserInitiatedPause",C.CapabilitiesUpdated="CapabilitiesUpdated",function(g){g.LoadHydra="LoadHydra",g.LoadHlsScript="LoadHlsScript",g.LoadPlayer="LoadPlayer",g.Load="Load",g.LoadHlsAuthCookie="LoadHlsAuthCookie",g.HlsManifestLoad="HlsManifestLoad",g.HlsKeyLoad="HlsKeyLoad",g.LoadHlsFirstFragment="LoadHlsFirstFragment",g.SetSource="SetSource",g.SdnPluginLoad="SdnPluginLoad",g.ThaPluginLoad="ThaPluginLoad",g.HydraPipelineInitialization="HydraPipelineInitialization",g.Destroyed="Destroyed",g.Setup="Setup",g.StreamConnection="StreamConnection",g.SdnPluginInitialize="SdnPluginInitialize",g.SdnPluginSetSource="SdnPluginSetSource",g.PlayAttemptBlocked="PlayAttemptBlocked"}(v||(f.PlayerScenarioType=v={}))},176:function(g,f){var S,v,C,_,T,I,b,A;Object.defineProperty(f,"__esModule",{value:!0}),f.MobileInteractionType=f.HydraSupportedSDN=f.HydraPlayerDestroyedReason=f.HydraOutputState=f.HydraInputState=f.HydraPlayerPlaybackErrorSource=f.PlaybackMode=void 0,(A=S||(f.PlaybackMode=S={})).Live="Live",A.DVR="DVR",function(g){g.Stream="Stream",g.HydraPipeline="HydraPipeline",g.VideoPlayer="VideoPlayer"}(v||(f.HydraPlayerPlaybackErrorSource=v={})),function(g){g.Idle="Idle",g.Started="Started",g.BufferReceived="BufferReceived",g.Ended="Ended",g.Stopped="Stopped",g.Destroyed="Destroyed"}(C||(f.HydraInputState=C={})),function(g){g.Idle="Idle",g.Attached="Attached",g.Starting="Starting",g.Started="Started",g.BufferReceived="BufferReceived",g.BufferAppended="BufferAppended",g.Stopped="Stopped",g.Destroyed="Destroyed"}(_||(f.HydraOutputState=_={})),function(g){g.PlayerStopped="PlayerStopped",g.PlaybackError="PlaybackError"}(T||(f.HydraPlayerDestroyedReason=T={})),function(g){g.Hive="hive",g.Kollective="kollective",g.Ramp="ramp",g.Peer5="peer5",g.Microsoft="microsoft"}(I||(f.HydraSupportedSDN=I={})),function(g){g[g.DoublePress3Fingers=0]="DoublePress3Fingers"}(b||(f.MobileInteractionType=b={}))},346:function(g,f){var S,v,C,_,T,I,b,A,P;Object.defineProperty(f,"__esModule",{value:!0}),f.HttpFetchErrorReason=f.IframeMessages=f.HydraPlayerType=f.HydraPlayerPlaybackErrorType=f.HydraPlayerPlaybackState=f.HydraPlayerSetupErrorType=f.HydraStreamDeliveryPipeline=f.HydraStreamingEventType=void 0,(P=S||(f.HydraStreamingEventType=S={})).TLE="TLE",P.Overflow="Overflow",P.TownHallBasic="TownHall_Basic",P.TownHallPremium="TownHall_Premium",P.TownHall="TownHall",function(g){g.AMS="AMS",g.HLS="MiddleLaneHttpLiveStreaming",g.Ums="MiddleLaneUltraLowLatency"}(v||(f.HydraStreamDeliveryPipeline=v={})),function(g){g.MultiplePlayerLoad="MultiplePlayerLoad",g.PlayerInitializationFailed="PlayerInitializationFailed",g.InvalidStream="InvalidStream",g.SetSourceFailed="SetSourceFailed"}(C||(f.HydraPlayerSetupErrorType=C={})),function(g){g.LoadStart="loadstart",g.LoadedData="loadeddata",g.LoadedMetadata="loadedmetadata",g.Start="start",g.CanPlayThrough="canplaythrough",g.Play="play",g.Playing="playing",g.Pause="pause",g.Waiting="waiting",g.Seeking="seeking",g.Seeked="seeked",g.Ended="ended",g.Error="error",g.Destroyed="destroyed",g.Initialized="initialized",g.Stalled="stalled",g.VolumeChange="volumechange",g.PlaybackBitrateChanged="playbackbitratechanged",g.DownloadBitrateChanged="downloadbitratechanged",g.TimeUpdate="timeupdate",g.DurationChange="durationchange",g.HlsKeyLoading="hlsKeyLoading",g.HlsKeyLoaded="hlsKeyLoaded",g.HlsKeyLoadedFailed="hlsKeyLoadedFailed",g.HlsManifestLoading="hlsManifestLoading",g.HlsManifestLoaded="hlsManifestLoaded",g.HlsManifestLoadedFailed="hlsManifestLoadedFailed",g.HlsFirstFragmentLoading="hlsFragLoading",g.HlsFirstFragmentBuffered="hlsFragBuffered",g.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",g.HlsFragmentChanged="hlsFragmentChanged",g.Online="online",g.Offline="offline",g.NetworkChange="networkChange"}(_||(f.HydraPlayerPlaybackState=_={})),function(g){g.UnsupportedPlatform="UnsupportedPlatform",g.NetworkError="NetworkError",g.PlaybackRetried="PlaybackRetried",g.PlaybackError="PlaybackError",g.Unknown="Unknown",g.MediaTimeout="MediaTimeout",g.NoMediaFlow="NoMediaFlow"}(T||(f.HydraPlayerPlaybackErrorType=T={})),function(g){g[g.Hls=1]="Hls",g[g.Ums=2]="Ums"}(I||(f.HydraPlayerType=I={})),function(g){g.RequestIceCandidates="RequestIceCandidates"}(b||(f.IframeMessages=b={})),function(g){g.Unknown="Unknown",g.ClientNetwork="ClientNetwork",g.ClientNetworkOrUnreachableServer="ClientNetworkOrUnreachableServer",g.ServerNetwork="ServerNetwork",g.ClientAuthIssue="ClientAuthIssue",g.ServerResourceNotFound="ServerResourceNotFound"}(A||(f.HttpFetchErrorReason=A={}))},534:function(g,f,S){var v=this&&this.__awaiter||function(g,f,S,v){return new(S||(S=Promise))((function(C,_){function o2(g){try{l2(v.next(g))}catch(g){_(g)}}function s2(g){try{l2(v.throw(g))}catch(g){_(g)}}function l2(g){var f;g.done?C(g.value):(f=g.value,f instanceof S?f:new S((function(g){g(f)}))).then(o2,s2)}l2((v=v.apply(g,f||[])).next())}))},C=this&&this.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:s2(0),throw:s2(1),return:s2(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function s2(I){return function(b){return function(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!((C=(C=T.trys).length>0&&C[C.length-1])||6!==I[0]&&2!==I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}([I,b])}}};Object.defineProperty(f,"__esModule",{value:!0}),f.isPlaybackStoppingState=f.tryCallVideoElementPlay=f.sanitizeForFormatSpecifiers=f.addEvent=f.TimeRanges=f.NO_OP_BUFFERED=f.getHttpFetchErrorReason=f.createVideoPlayButton=f.createVideoElement=f.createVideoElementDiv=f.showPlayerControls=f.repeatUntilCancel=f.wait=f.stringifyError=f.stringifyObject=f.getRandomHexString=f.getPlayerSetting=f.getECSSetting=f.retry=f.createIFrame=f.getMajorFromVersion=void 0;var _=S(346),T=S(457);function s(g,f,S,_,T,I,b){return v(this,void 0,void 0,(function(){var A,P,R,M,w,O=this;return C(this,(function(D){switch(D.label){case 0:return A=100,P=Date.now(),[4,c(S,R={trackingRef:"",timeTakenToDownloadScript:-1},T,I,b).catch((function(g){return v(O,void 0,void 0,(function(){var f;return C(this,(function(v){switch(v.label){case 0:return f="Failed to get IFrame source: ".concat(p(g)),_.push({success:!1,url:S,startTime:P,duration:Date.now()-P,trackingReference:R.trackingRef,timeTakenToDownloadScript:R.timeTakenToDownloadScript,errorMsg:f}),_.length>A&&_.shift(),[4,Promise.reject(new Error(f))];case 1:return[2,v.sent()]}}))}))}))];case 1:return M=D.sent(),f.srcdoc=M,w=new Promise((function(g,v){f.onload=function(){_.push({success:!0,url:S,startTime:P,duration:Date.now()-P,trackingReference:R.trackingRef,timeTakenToDownloadScript:R.timeTakenToDownloadScript}),_.length>A&&_.shift(),g()},f.onerror=function(g){var f="Failed to load HydraPlayer IFrame: ".concat(p(g));_.push({success:!1,url:S,startTime:P,duration:Date.now()-P,trackingReference:R.trackingRef,timeTakenToDownloadScript:R.timeTakenToDownloadScript,errorMsg:f}),_.length>A&&_.shift(),v(new Error(f))}})),g.appendChild(f),[4,w];case 2:return D.sent(),[2]}}))}))}function l(g){return v(this,arguments,void 0,(function(g,f,S){var _=this;return void 0===f&&(f=5),void 0===S&&(S=200),C(this,(function(T){switch(T.label){case 0:return[4,g(f).catch((function(T){return v(_,void 0,void 0,(function(){var _=this;return C(this,(function(I){switch(I.label){case 0:return 0!=--f?[3,2]:[4,Promise.reject(new Error("[retry] retries exhausted: ".concat(y(T))))];case 1:case 3:return[2,I.sent()];case 2:return[4,new Promise((function(I){return setTimeout((function(){I(l(g,f,S).catch((function(g){return v(_,void 0,void 0,(function(){return C(this,(function(f){switch(f.label){case 0:return[4,Promise.reject(new Error("".concat(y(T)).concat(", ",y(g))))];case 1:return[2,f.sent()]}}))}))})))}),S)}))]}}))}))}))];case 1:return[2,T.sent()]}}))}))}function c(g,f,S,_,T){return v(this,void 0,void 0,(function(){var I,b,A,P=this;return C(this,(function(R){switch(R.label){case 0:return I=Date.now(),S?(b='<script src="'.concat(g,'"></script')+">",[3,3]):[3,1];case 1:return[4,d(g,f,_).catch((function(g){return v(P,void 0,void 0,(function(){return C(this,(function(f){switch(f.label){case 0:return[4,Promise.reject(g)];case 1:return[2,f.sent()]}}))}))}))];case 2:A=R.sent(),b=T?'<script nonce="'.concat(T,'">').concat(A,"</script")+">":"<script>".concat(A,"</script")+">",R.label=3;case 3:return f.timeTakenToDownloadScript=Date.now()-I,[2,"\n        <html class style='height: 100%; width: 100%; overflow: hidden'>\n        <head></head>\n        <body class style='height: 100%; width: 100%; margin: 0px'>\n            ".concat(b,"\n        </body>\n        </html>\n    ")]}}))}))}function d(g,f,S){return v(this,void 0,void 0,(function(){var _,T,I,b=this;return C(this,(function(A){switch(A.label){case 0:return _=function(g,f){var S,v;return f.includes("vz")?null!==(v=g.headers.get("uuid"))&&void 0!==v?v:"":null!==(S=g.headers.get("X-Azure-Ref"))&&void 0!==S?S:""},S?(T=new AbortController,I=setTimeout((function(){T.abort()}),S),[4,fetch(g,{signal:T.signal,cache:"no-cache"}).then((function(S){return v(b,void 0,void 0,(function(){return C(this,(function(v){switch(v.label){case 0:return clearTimeout(I),S.ok?[3,2]:[4,Promise.reject(new Error("".concat(S.status)))];case 1:return[2,v.sent()];case 2:return f.trackingRef=_(S,g),[2,S]}}))}))})).then((function(f){return v(b,void 0,void 0,(function(){var S=this;return C(this,(function(_){switch(_.label){case 0:return[4,f.text().then((function(_){return v(S,void 0,void 0,(function(){return C(this,(function(S){switch(S.label){case 0:return _?[2,_]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(f.status,", script ").concat(g," contents are null")))];case 2:return[2,S.sent()]}}))}))}))];case 1:return[2,_.sent()]}}))}))})).catch((function(g){return v(b,void 0,void 0,(function(){return C(this,(function(f){throw clearTimeout(I),g}))}))}))]):[3,2];case 1:case 3:return[2,A.sent()];case 2:return[4,fetch(g,{cache:"no-cache"}).then((function(S){return v(b,void 0,void 0,(function(){return C(this,(function(v){switch(v.label){case 0:return S.ok?[3,2]:[4,Promise.reject(new Error("".concat(S.status)))];case 1:return[2,v.sent()];case 2:return f.trackingRef=_(S,g),[2,S]}}))}))})).then((function(f){return v(b,void 0,void 0,(function(){var S=this;return C(this,(function(_){switch(_.label){case 0:return[4,f.text().then((function(_){return v(S,void 0,void 0,(function(){return C(this,(function(S){switch(S.label){case 0:return _?[2,_]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(f.status,", script ").concat(g," contents are null")))];case 2:return[2,S.sent()]}}))}))}))];case 1:return[2,_.sent()]}}))}))}))]}}))}))}function u(g,f,S){var v,C=S,_=null===(v=g.ecsSettings)||void 0===v?void 0:v[f];return typeof _==typeof C&&(C=_),C}function p(g){try{if(!g)return"".concat(g);if(g instanceof Map)return S={},g.forEach((function(g,f){S[f.toString()]=g})),JSON.stringify(S);var f=g.toString();return f.endsWith("[object Object]")?JSON.stringify(g):f}catch(g){return""}var S}function y(g){return g instanceof Error?g.message:p(g)}function h(g){return v(this,void 0,void 0,(function(){return C(this,(function(f){switch(f.label){case 0:return[4,new Promise((function(f){return setTimeout(f,g)}))];case 1:return f.sent(),[2]}}))}))}function f2(g){return g?g.replace(/%[a-zA-Z]/g,""):g}f.getMajorFromVersion=function(g){var f=g.match(/^(\d+)\.\d+\.\d+(-.*)?$/);return f?f[1]:null},f.createIFrame=function(g,f,S){return v(this,void 0,void 0,(function(){var _,I,b,A,P,R,M,w,O,D,N=this;return C(this,(function(k){switch(k.label){case 0:return _=u(S,"scriptSrcDownload",T.iframeConfigDefault.scriptSrcDownload),I=u(S,"allowSameOrigin",T.iframeConfigDefault.allowSameOrigin),b=S.maxRetryCountForLoadingResources,A=S.disableSandbox,P=S.hydraRuntimeFetchTimeout,R=[],(M=g.ownerDocument.createElement("iframe")).id="player-iframe",A||(I?null===(O=M.sandbox)||void 0===O||O.add("allow-scripts","allow-same-origin"):null===(D=M.sandbox)||void 0===D||D.add("allow-scripts")),M.allowFullscreen=!0,M.allow="camera; microphone; autoplay",M.style.height="100%",M.style.width="100%",M.style.border="none",w=function(g){return f[g%f.length]},[4,l((function(f){return v(N,void 0,void 0,(function(){var v,T,I;return C(this,(function(C){switch(C.label){case 0:return v=w(f),T=null!==(I=S.nonce)&&void 0!==I?I:"",[4,s(g,M,v,R,_,P,T)];case 1:return C.sent(),[2]}}))}))}),b).then((function(){return{iframe:M,initResult:{isSuccess:!0,runtimeDownloadResults:R}}})).catch((function(g){return v(N,void 0,void 0,(function(){var S;return C(this,(function(v){return S="Failed to load Hydra player runtime scripts, src: ",f.forEach((function(g){return S=S.concat(g,", ")})),S+="errors: ".concat(p(g)),[2,{initResult:{isSuccess:!1,runtimeDownloadResults:R,errorMsg:S}}]}))}))}))];case 1:return[2,k.sent()]}}))}))},f.retry=l,f.getECSSetting=u,f.getPlayerSetting=function(g,f){var S;return void 0!==(null===(S=g.ecsSettings)||void 0===S?void 0:S[f])?g.ecsSettings[f]:g[f]},f.getRandomHexString=function(g){return Array.from(Array(g)).map((function(){return Math.floor(16*Math.random()).toString(16)})).join("")},f.stringifyObject=p,f.stringifyError=y,f.wait=h,f.repeatUntilCancel=function(g,f,S,_){var T=!1,I=_||console.log,b=f2(g);return I("RepeatUntilCancel starting task: ".concat(b)),v(this,void 0,void 0,(function(){var g,v,_;return C(this,(function(C){switch(C.label){case 0:return T?[3,2]:(g=new Date,f(),v=(new Date).getTime()-g.getTime(),(_=S-v)<0&&(_=S+_%S,I("Skipping execution for ".concat(b,", last execution took: ").concat(v," ms, delayMs: ").concat(S),"warn")),[4,h(_)]);case 1:return C.sent(),[3,0];case 2:return[2]}}))})),function(){I("RepeatUntilCancel stopping task: ".concat(b)),T=!0}},f.showPlayerControls=function(g){return void 0!==g.allowPlayerControls?g.allowPlayerControls:g.streamingEventType===_.HydraStreamingEventType.TLE},f.createVideoElementDiv=function(g,f,S){S("createVideoElementDiv started");var v=f.ownerDocument.createElement("div");return v.id=g,v.style.position="relative",v.style.width="100%",v.style.height="100%",f.appendChild(v),S("createVideoElementDiv done"),v},f.createVideoElement=function(g,f,S,v,C){C("createVideoElement started");var _=f.ownerDocument.createElement("video");_.controls=v,_.id=g,_.setAttribute("playsinline","");var T=S.videoLang;T&&(_.setAttribute("lang",T),C("createVideoElement: language set to ".concat(T)));var I=S.videoElementStyles;if(I)for(var b=0;b<I.length;b++)_.classList.add(I[b]);return _.style.width="100%",_.style.height="100%",_.style.position="absolute",_.muted=S.muteVideo,_.addEventListener("contextmenu",(function(g){g.preventDefault()})),["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"].forEach((function(g){try{navigator.mediaSession.setActionHandler(g,(function(){}))}catch(g){}})),f.appendChild(_),C("createVideoElement done"),_},f.createVideoPlayButton=function(g,f,S,v){v("createVideoPlayButton started");var C=f.ownerDocument.createElement("style");C.innerHTML="\n    .hydra-play-button {\n        width: 70px;\n        height: 70px;\n        background-color: #373538;\n        border: none;\n        border-radius: 50%;\n        position: absolute;\n        top: 50%;\n        left: 50%;\n        transform: translate(-50%, -50%);\n        cursor: pointer;\n        display: flex;\n        align-items: center;\n        justify-content: center;\n    }\n\n    .triangle {\n        position: relative;\n        background-color: white;\n        text-align: left;\n    }\n    .triangle:before,\n    .triangle:after {\n        content: '';\n        position: absolute;\n        background-color: inherit;\n    }\n    .triangle,\n    .triangle:before,\n    .triangle:after {\n        width: 1em;\n        height: 1em;\n        border-top-right-radius: 30%;\n    }\n\n    .triangle {\n        transform: rotate(270deg) skewX(-30deg) scale(1, .866) translate(10%, -15%);\n    }\n    .triangle:before {\n        transform: rotate(-135deg) skewX(-45deg) scale(1.414, .707) translate(0, -50%);\n    }\n    .triangle:after {\n        transform: rotate(135deg) skewY(-45deg) scale(.707, 1.414) translate(50%);\n    }\n    ",f.ownerDocument.head.appendChild(C);var _=f.ownerDocument.createElement("div");_.id=g,_.className="hydra-play-button";var T=document.createElement("div");return T.className="triangle",_.appendChild(T),S||(_.style.display="none"),f.appendChild(_),v("createVideoPlayButton done"),_},f.getHttpFetchErrorReason=function(g){return void 0===g?_.HttpFetchErrorReason.Unknown:0===g?_.HttpFetchErrorReason.ClientNetworkOrUnreachableServer:401===g?_.HttpFetchErrorReason.ClientAuthIssue:404===g?_.HttpFetchErrorReason.ServerResourceNotFound:g>=400&&g<=499?_.HttpFetchErrorReason.ClientNetwork:g>=500&&g<=599?_.HttpFetchErrorReason.ServerNetwork:_.HttpFetchErrorReason.Unknown},f.NO_OP_BUFFERED={length:0,start:function(){return 0},end:function(){return 0}},f.TimeRanges={toString:function(g){for(var f="",S=g.length,v=0;v<S;v++)f+="[".concat(g.start(v).toFixed(3),"-").concat(g.end(v).toFixed(3),"]");return f},range:function(g){return g&&0!==g.length?[g.start(g.length-1),g.end(g.length-1)]:[0,0]},prevRange:function(g){if(g&&2===g.length)return[g.start(g.length-2),g.end(g.length-2)]}},f.addEvent=function(g,f){var S={};return(null==f?void 0:f.detail)&&(S={detail:f.detail}),new CustomEvent(g,S)},f.sanitizeForFormatSpecifiers=f2,f.tryCallVideoElementPlay=function(g){var f=g.play();return void 0!==f?f:new Promise((function(g){return g()}))},f.isPlaybackStoppingState=function(g){return g===_.HydraPlayerPlaybackState.Pause||g===_.HydraPlayerPlaybackState.Ended||g===_.HydraPlayerPlaybackState.Seeking||g===_.HydraPlayerPlaybackState.Waiting||g===_.HydraPlayerPlaybackState.Stalled||g===_.HydraPlayerPlaybackState.Destroyed}},564:function(g,f){var S,v,C,_,T,I,b,A,P,R;Object.defineProperty(f,"__esModule",{value:!0}),f.UmsModality=f.HttpFetchErrorReason=f.IframeMessages=f.HydraPlayerType=f.HydraPlayerPlaybackErrorType=f.HydraPlayerPlaybackState=f.HydraPlayerSetupErrorType=f.HydraStreamDeliveryPipeline=f.HydraStreamingEventType=void 0,(R=S||(f.HydraStreamingEventType=S={})).TLE="TLE",R.Overflow="Overflow",R.TownHallBasic="TownHall_Basic",R.TownHallPremium="TownHall_Premium",R.TownHall="TownHall",function(g){g.AMS="AMS",g.HLS="MiddleLaneHttpLiveStreaming",g.Ums="MiddleLaneUltraLowLatency"}(v||(f.HydraStreamDeliveryPipeline=v={})),function(g){g.MultiplePlayerLoad="MultiplePlayerLoad",g.PlayerInitializationFailed="PlayerInitializationFailed",g.InvalidStream="InvalidStream",g.SetSourceFailed="SetSourceFailed"}(C||(f.HydraPlayerSetupErrorType=C={})),function(g){g.LoadStart="loadstart",g.LoadedData="loadeddata",g.LoadedMetadata="loadedmetadata",g.Start="start",g.CanPlayThrough="canplaythrough",g.Play="play",g.Playing="playing",g.Pause="pause",g.Waiting="waiting",g.Seeking="seeking",g.Seeked="seeked",g.Ended="ended",g.Error="error",g.Destroyed="destroyed",g.Initialized="initialized",g.Stalled="stalled",g.VolumeChange="volumechange",g.PlaybackBitrateChanged="playbackbitratechanged",g.DownloadBitrateChanged="downloadbitratechanged",g.TimeUpdate="timeupdate",g.DurationChange="durationchange",g.HlsKeyLoading="hlsKeyLoading",g.HlsKeyLoaded="hlsKeyLoaded",g.HlsKeyLoadedFailed="hlsKeyLoadedFailed",g.HlsManifestLoading="hlsManifestLoading",g.HlsManifestLoaded="hlsManifestLoaded",g.HlsManifestLoadedFailed="hlsManifestLoadedFailed",g.HlsFirstFragmentLoading="hlsFragLoading",g.HlsFirstFragmentBuffered="hlsFragBuffered",g.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",g.HlsFragmentChanged="hlsFragmentChanged",g.Online="online",g.Offline="offline",g.NetworkChange="networkChange"}(_||(f.HydraPlayerPlaybackState=_={})),function(g){g.UnsupportedPlatform="UnsupportedPlatform",g.NetworkError="NetworkError",g.PlaybackRetried="PlaybackRetried",g.PlaybackError="PlaybackError",g.Unknown="Unknown",g.MediaTimeout="MediaTimeout",g.NoMediaFlow="NoMediaFlow"}(T||(f.HydraPlayerPlaybackErrorType=T={})),function(g){g[g.Hls=1]="Hls",g[g.Ums=2]="Ums"}(I||(f.HydraPlayerType=I={})),function(g){g.RequestIceCandidates="RequestIceCandidates"}(b||(f.IframeMessages=b={})),function(g){g.Unknown="Unknown",g.ClientNetwork="ClientNetwork",g.ClientNetworkOrUnreachableServer="ClientNetworkOrUnreachableServer",g.ServerNetwork="ServerNetwork",g.ClientAuthIssue="ClientAuthIssue",g.ServerResourceNotFound="ServerResourceNotFound"}(A||(f.HttpFetchErrorReason=A={})),function(g){g.audio="Audio",g.video="Video",g.text="Text"}(P||(f.UmsModality=P={}))},521:function(g,f,S){var v=this&&this.__awaiter||function(g,f,S,v){return new(S||(S=Promise))((function(C,_){function o2(g){try{l2(v.next(g))}catch(g){_(g)}}function s2(g){try{l2(v.throw(g))}catch(g){_(g)}}function l2(g){var f;g.done?C(g.value):(f=g.value,f instanceof S?f:new S((function(g){g(f)}))).then(o2,s2)}l2((v=v.apply(g,f||[])).next())}))},C=this&&this.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:s2(0),throw:s2(1),return:s2(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function s2(I){return function(b){return function(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!((C=(C=T.trys).length>0&&C[C.length-1])||6!==I[0]&&2!==I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}([I,b])}}};Object.defineProperty(f,"__esModule",{value:!0}),f.HydraPlayer=f.getSdkVersion=void 0;var _=S(346),T=S(378),I=S(715),b=S(357),A=S(534),P=S(42),R=S(103),M=S(282),w=S(10);f.getSdkVersion=function(){return"4.2521.1"};var O=function(){function e3(g,f){this.playerSettings=g,this.eventHandler=f,this.spinner=null,this.telemetryReportHandler=null,this.playerRuntimeUrls=[],this.commandResultsMap=new Map,this.iframeCommunicationHandler=null,this.MAX_COMMAND_RESULTS_MAP_SIZE=1e4,this.playerInternalEventHandler=new I.HydraPlayerInternalEventHandler}return e3.prototype.dispose=function(){var g;null===(g=this.telemetryReportHandler)||void 0===g||g.addDisposeTelemetry(),this.isIFrameCommunicationActive()&&this.callPlayerApi("disposeHydraPlayer")},e3.prototype.release=function(){var g;null===(g=this.spinner)||void 0===g||g.hide(),this.contextWindow&&this.contextWindow.removeEventListener("message",this.onMessage.bind(this)),this.iframeCommunicationHandler&&this.iframeCommunicationHandler.dispose(),this.iframe&&this.container&&this.container.hasChildNodes()&&this.container.removeChild(this.iframe)},e3.prototype.setup=function(g){return v(this,void 0,void 0,(function(){var f,S,v,T,I,b,R,M;return C(this,(function(C){switch(C.label){case 0:f=Date.now(),this.container=g,S=null,C.label=1;case 1:return C.trys.push([1,14,,15]),this.spinner=new P.Spinner(this.container),this.playerInternalEventHandler.setSpinner(this.spinner),[4,this.initializeIFrame()];case 2:if(!(S=C.sent()).isSuccess)return[3,12];v={initSucceeded:!0,initStartTime:f,initDuration:Date.now()-f,runtimeDownloadResults:S.runtimeDownloadResults||[]},C.label=3;case 3:return C.trys.push([3,5,,11]),[4,this.callPlayerApi("createHydraPlayer",this.playerSettings,v)];case 4:return C.sent(),[3,11];case 5:return T=C.sent(),this.eventHandler.log("warn","Failed to create HydraPlayer: ".concat(T)),this.playerSettings.playerType!==_.HydraPlayerType.Hls?[3,7]:[4,this.callPlayerApi("createHlsHydraPlayer",this.playerSettings,v)];case 6:return C.sent(),[3,10];case 7:return this.playerSettings.playerType!==_.HydraPlayerType.Ums?[3,9]:[4,this.callPlayerApi("createUmsHydraPlayer",this.playerSettings,v)];case 8:return C.sent(),[3,10];case 9:throw new Error("Cannot create Hydra player - Unknown player type");case 10:return[3,11];case 11:return this.onSetupCompleted(v),[2,!0];case 12:throw new Error(S.errorMsg);case 13:return[3,15];case 14:I=C.sent(),b=(0,A.stringifyObject)(I),this.eventHandler.log("error","Failed to setup HydraPlayer: ".concat(b)),R={initSucceeded:!1,initStartTime:f,initDuration:Date.now()-f,runtimeDownloadResults:(null==S?void 0:S.runtimeDownloadResults)||[],errorMsg:b};try{null===(M=this.spinner)||void 0===M||M.hide()}catch(g){this.eventHandler.log("error","Failed to hide spinner: ".concat((0,A.stringifyObject)(g)))}return this.onSetupCompleted(R),[2,!1];case 15:return[2]}}))}))},e3.prototype.onSetupCompleted=function(g){this.telemetryReportHandler=new b.TelemetryReportHandler(this.playerSettings,this.eventHandler.log.bind(this.eventHandler),g,this.spinner),this.playerInternalEventHandler.setTelemetryReportHandler(this.telemetryReportHandler)},e3.prototype.getFullTelemetryReport=function(){var g;return(null===(g=this.telemetryReportHandler)||void 0===g?void 0:g.getFullTelemetryReport())||{}},e3.prototype.getSnapshotTelemetryReport=function(){var g;return(null===(g=this.telemetryReportHandler)||void 0===g?void 0:g.getSnapshotTelemetryReport())||{}},e3.prototype.callPlayerApi=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];return v(this,void 0,void 0,(function(){var S,v,_,I,b;return C(this,(function(C){switch(C.label){case 0:return this.iframe?[3,2]:[4,Promise.reject(new Error("Hydra IFrame not initialized yet"))];case 1:case 3:return[2,C.sent()];case 2:if(S=(0,w.default)(),v={msgType:T.MessageType.Command,id:S,name:g,args:f},!this.isIFrameCommunicationActive())throw new Error("IFrame MessageAPI communication not active");if(this.commandResultsMap.size>=this.MAX_COMMAND_RESULTS_MAP_SIZE)throw new Error("Too many Hydra player API commands in progress - skipping this player API call");return _=R.defer(),I={name:g,id:S},this.commandResultsMap.set(I,_),null===(b=this.iframe.contentWindow)||void 0===b||b.postMessage(v,"*"),[4,_.promise]}}))}))},Object.defineProperty(e3.prototype,"contextWindow",{get:function(){var g;return null===(g=this.container)||void 0===g?void 0:g.ownerDocument.defaultView},enumerable:!1,configurable:!0}),e3.prototype.isIFrameCommunicationActive=function(){var g;return!!(null===(g=this.iframe)||void 0===g?void 0:g.contentWindow)&&!!this.contextWindow},e3.prototype.getRuntimeUrls=function(g){if(!Array.isArray(this.playerSettings.playerRuntimeJsUrls)){var f=(0,A.getMajorFromVersion)(g);return f&&this.playerSettings.playerRuntimeJsUrls[f]||[]}return this.playerSettings.playerRuntimeJsUrls},e3.prototype.initializeIFrame=function(){return v(this,void 0,void 0,(function(){var g;return C(this,(function(f){switch(f.label){case 0:return this.playerSettings.hydraPlayerSdkVersion="4.2521.1",this.playerRuntimeUrls=this.getRuntimeUrls(this.playerSettings.hydraPlayerSdkVersion),0!==this.playerRuntimeUrls.length&&this.container?[4,(0,A.createIFrame)(this.container,this.playerRuntimeUrls,this.playerSettings)]:[2,{isSuccess:!1,runtimeDownloadResults:[],errorMsg:"No compatible runtime URLs provided for HydraPlayer SDK version:\n                    ".concat(this.playerSettings.hydraPlayerSdkVersion,", URLs:\n                    ").concat((0,A.stringifyObject)(this.playerSettings.playerRuntimeJsUrls))}];case 1:return(g=f.sent()).initResult.isSuccess&&g.iframe&&(this.iframe=g.iframe,this.iframeCommunicationHandler=new M.IframeCommunicationHandler(this.iframe,this.playerSettings,this.eventHandler.log),this.contextWindow.addEventListener("message",this.onMessage.bind(this))),[2,g.initResult]}}))}))},e3.prototype.onMessage=function(g){switch(g.data.msgType){case T.MessageType.PlayerEvent:this.processPlayerEvent(g.data);break;case T.MessageType.InternalPlayerEvent:this.processInternalPlayerEvent(g.data);break;case T.MessageType.CommandSuccessResult:this.processCommandSuccessResult(g.data);break;case T.MessageType.CommandFailureResult:this.processCommandFailureResult(g.data)}},e3.prototype.processCommandSuccessResult=function(g){var f=this;this.eventHandler.log("debug","HydraPlayer command succeeded for ".concat(g.name," - result: ").concat((0,A.stringifyObject)(g.result))),this.getMapCommandResults(g).forEach((function(S){S[1].resolve(g.result),f.commandResultsMap.delete(S[0])}))},e3.prototype.processCommandFailureResult=function(g){var f=this;this.eventHandler.log("debug","HydraPlayer command failed for ".concat(g.name," - error: ").concat(g.error.message)),this.getMapCommandResults(g).forEach((function(S){S[1].reject(g.error),f.commandResultsMap.delete(S[0])}))},e3.prototype.getMapCommandResults=function(g){var f=Array.from(this.commandResultsMap.entries()),S=[];return g.id?S=f.filter((function(f){return f[0].id===g.id})):g.name&&(S=f.filter((function(f){return f[0].name===g.name}))),S},e3.prototype.processPlayerEvent=function(g){var f;null===(f=this.eventHandler[g.name])||void 0===f||f.apply(this.eventHandler,g.args)},e3.prototype.processInternalPlayerEvent=function(g){this.playerInternalEventHandler&&this.playerInternalEventHandler[g.name].apply(this,g.args)},e3}();f.HydraPlayer=O},282:function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.IframeCommunicationHandler=void 0;var v=S(346),C=S(735),_=function(){function e3(g,f,S){var v=this;this.iframe=g,this.playerSettings=f,this.logger=S,this.setupMessageListener(),this.candidatesCollector=new C.WebRtcIceCandidateCollector(this.playerSettings),this.candidatesCollector.startCandidatesCollection().catch((function(g){v.logger("warn","Failed to start collecting ICE candidates ".concat(g))}))}return e3.prototype.setupMessageListener=function(){var g;null===(g=this.iframe.ownerDocument.defaultView)||void 0===g||g.addEventListener("message",this.processMessage.bind(this))},e3.prototype.postMessageToIframe=function(g){var f;null===(f=this.iframe.contentWindow)||void 0===f||f.postMessage(g,"*")},e3.prototype.dispose=function(){var g;null===(g=this.iframe.ownerDocument.defaultView)||void 0===g||g.removeEventListener("message",this.processMessage.bind(this)),this.candidatesCollector&&this.candidatesCollector.destroy()},e3.prototype.processMessage=function(g){var f=this;g.data===v.IframeMessages.RequestIceCandidates&&void 0===g.data.candidates&&this.candidatesCollector.getCandidates().then((function(g){var S=JSON.stringify(g.map((function(g){return JSON.stringify(g)})));f.postMessageToIframe({topic:v.IframeMessages.RequestIceCandidates,candidates:S})})).catch((function(){f.postMessageToIframe({topic:v.IframeMessages.RequestIceCandidates,candidates:[]})}))},e3}();f.IframeCommunicationHandler=_},260:function(g,f,S){var v=this&&this.__createBinding||(Object.create?function(g,f,S,v){void 0===v&&(v=S);var C=Object.getOwnPropertyDescriptor(f,S);C&&!("get"in C?!f.__esModule:C.writable||C.configurable)||(C={enumerable:!0,get:function(){return f[S]}}),Object.defineProperty(g,v,C)}:function(g,f,S,v){void 0===v&&(v=S),g[v]=f[S]}),C=this&&this.__exportStar||function(g,f){for(var S in g)"default"===S||Object.prototype.hasOwnProperty.call(f,S)||v(f,g,S)};Object.defineProperty(f,"__esModule",{value:!0}),C(S(521),f),C(S(564),f)},715:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.HydraPlayerInternalEventHandler=void 0;var S=function(){function e3(){this.spinner=null,this.telemetryReportHandler=null}return e3.prototype.setSpinner=function(g){this.spinner=g},e3.prototype.setTelemetryReportHandler=function(g){this.telemetryReportHandler=g},e3.prototype.firstPlayerLoadAttemptDone=function(){var g;null===(g=this.spinner)||void 0===g||g.hide()},e3.prototype.fullTelemetryReportUpdated=function(g){var f;null===(f=this.telemetryReportHandler)||void 0===f||f.setFullTelemetryReport(g)},e3.prototype.snapshotTelemetryReportUpdated=function(g){var f;null===(f=this.telemetryReportHandler)||void 0===f||f.setSnapshotTelemetryReport(g)},e3}();f.HydraPlayerInternalEventHandler=S},357:function(g,f,S){var v=this&&this.__assign||function(){return v=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},v.apply(this,arguments)};Object.defineProperty(f,"__esModule",{value:!0}),f.TelemetryReportHandler=void 0;var C=S(346),_=S(176),T=S(963),I=S(171),b=S(534),A=function(){function e3(g,f,S,v){var _=this;this.logFn=f,this.spinner=v,this.initialLiveStreamStatistic=new I.LiveStreamStatistic(g,(function(g,f){_.logFn(g,f)}),{videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],statsInterval:[]},{hydraPlayerSdkVersion:g.hydraPlayerSdkVersion||"Unknown",hydraPlayerType:C.HydraPlayerType.Hls}),this.initialLiveStreamStatistic.setHydraInitResult(S),this.fullTelemetryReport=this.initialLiveStreamStatistic.getReport(),this.snapshotTelemetryReport=this.initialLiveStreamStatistic.getSnapshotReport()}return e3.prototype.getFullTelemetryReport=function(){return this.fullTelemetryReport},e3.prototype.getSnapshotTelemetryReport=function(){return this.snapshotTelemetryReport},e3.prototype.setFullTelemetryReport=function(g){var f,S,C,_,T,I,b;this.fullTelemetryReport=v(v({},g),{init_spinnerShowTimestamp:null!==(S=null===(f=this.spinner)||void 0===f?void 0:f.firstShowTimestamp)&&void 0!==S?S:-1,init_spinnerHideTimestamp:null!==(_=null===(C=this.spinner)||void 0===C?void 0:C.firstHideTimestamp)&&void 0!==_?_:-1,init_spinnerDuration:null!==(I=null===(T=this.spinner)||void 0===T?void 0:T.firstSpinnerDuration)&&void 0!==I?I:-1,init_spinnerVisible:(null===(b=this.spinner)||void 0===b?void 0:b.isVisible())||!1})},e3.prototype.setSnapshotTelemetryReport=function(g){var f,S,C,_,T,I,b;this.snapshotTelemetryReport=v(v({},g),{init_spinnerShowTimestamp:null!==(S=null===(f=this.spinner)||void 0===f?void 0:f.firstShowTimestamp)&&void 0!==S?S:-1,init_spinnerHideTimestamp:null!==(_=null===(C=this.spinner)||void 0===C?void 0:C.firstHideTimestamp)&&void 0!==_?_:-1,init_spinnerDuration:null!==(I=null===(T=this.spinner)||void 0===T?void 0:T.firstSpinnerDuration)&&void 0!==I?I:-1,init_spinnerVisible:(null===(b=this.spinner)||void 0===b?void 0:b.isVisible())||!1})},e3.prototype.addDisposeTelemetry=function(){var g=Date.now();this.updateInitEventsWithDisposeEvent(this.fullTelemetryReport,g,"full"),this.updateInitEventsWithDisposeEvent(this.snapshotTelemetryReport,g,"snapshot"),this.updateStateChangeEventsWithDisposeEvent(this.fullTelemetryReport,g,"full"),this.updateStateChangeEventsWithDisposeEvent(this.snapshotTelemetryReport,g,"snapshot")},e3.prototype.updateInitEventsWithDisposeEvent=function(g,f,S){try{var v=g.init_allEvents,C=JSON.parse(v);C[C.length-1].name!==T.PlayerScenarioType.Destroyed&&C.push({name:T.PlayerScenarioType.Destroyed,startTime:f,duration:0,details:_.HydraPlayerDestroyedReason.PlayerStopped}),g.init_allEvents=(0,b.stringifyObject)(C)}catch(g){this.logFn("warn","Failed to add player destroyed information to init_allEvents telemetry field in ".concat(S," telemetry report."))}},e3.prototype.updateStateChangeEventsWithDisposeEvent=function(g,f,S){try{var v=g.playback_stateChangeEvents,_=JSON.parse(v);_[_.length-1].name!==C.HydraPlayerPlaybackState.Destroyed&&_.push({eventType:T.TelemetryEventType.StateChanged,timestamp:f,currentPlayPosition:-1,payload:C.HydraPlayerPlaybackState.Destroyed}),g.playback_stateChangeEvents=(0,b.stringifyObject)(_)}catch(g){this.logFn("warn","Failed to add player destroyed information to playback_stateChangeEvents telemetry field in ".concat(S," telemetry report."))}},e3}();f.TelemetryReportHandler=A},735:function(g,f,S){var v=this&&this.__awaiter||function(g,f,S,v){return new(S||(S=Promise))((function(C,_){function o2(g){try{l2(v.next(g))}catch(g){_(g)}}function s2(g){try{l2(v.throw(g))}catch(g){_(g)}}function l2(g){var f;g.done?C(g.value):(f=g.value,f instanceof S?f:new S((function(g){g(f)}))).then(o2,s2)}l2((v=v.apply(g,f||[])).next())}))},C=this&&this.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:s2(0),throw:s2(1),return:s2(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function s2(I){return function(b){return function(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!((C=(C=T.trys).length>0&&C[C.length-1])||6!==I[0]&&2!==I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}([I,b])}}},_=this&&this.__spreadArray||function(g,f,S){if(S||2===arguments.length)for(var v,C=0,_=f.length;C<_;C++)!v&&C in f||(v||(v=Array.prototype.slice.call(f,0,C)),v[C]=f[C]);return g.concat(v||Array.prototype.slice.call(f))};Object.defineProperty(f,"__esModule",{value:!0}),f.WebRtcIceCandidateCollector=void 0;var T=S(103),I=S(534),b=S(508),A=function(){function e3(g){this.playerSettings=g,this.latestCandidates=[],this.newCandidates=[],this.peerConnection=null,this.timeoutId=void 0,this.candidatesCollectionDefer=null,this.delayAfterComplete=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDelayAfterCompleteMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDelayAfterCompleteMs),this.delayAfterError=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDelayAfterErrorMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDelayAfterErrorMs),this.maxRetries=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorMaxRetriesMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorMaxRetriesMs),this.retryDelay=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorRetryDelayMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorRetryDelayMs),this.maxCollectionTime=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorMaxCollectionTimeMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorMaxCollectionTimeMs),this.disabledCollection=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDisableCollection",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDisableCollection)}return e3.prototype.handleIceCandidate=function(g){g.candidate&&this.newCandidates.push(g.candidate)},e3.prototype.handleIceGatheringStateChange=function(){var g,f;"complete"===(null===(g=this.peerConnection)||void 0===g?void 0:g.iceGatheringState)&&(this.latestCandidates=_([],this.newCandidates,!0),this.newCandidates=[],null===(f=this.candidatesCollectionDefer)||void 0===f||f.resolve(),this.candidatesCollectionDefer=null,this.destroyConnection(),this.clearCollectionTimeout(),this.startCandidatesCollection(this.delayAfterComplete))},e3.prototype.setUpPeerConnection=function(){return v(this,void 0,void 0,(function(){var g,f,S,v;return C(this,(function(C){switch(C.label){case 0:return C.trys.push([0,3,,4]),this.peerConnection=new RTCPeerConnection,this.peerConnection.createDataChannel("local-ip-hydra-player-ice-candidates"),this.peerConnection.addEventListener("icecandidate",this.handleIceCandidate.bind(this)),this.peerConnection.addEventListener("icegatheringstatechange",this.handleIceGatheringStateChange.bind(this)),[4,null===(S=this.peerConnection)||void 0===S?void 0:S.createOffer()];case 1:return g=C.sent(),[4,null===(v=this.peerConnection)||void 0===v?void 0:v.setLocalDescription(g)];case 2:return C.sent(),[3,4];case 3:throw f=C.sent(),this.destroyConnection(),new Error("Failure starting collection: ".concat((0,I.stringifyError)(f)));case 4:return[2]}}))}))},e3.prototype.destroyConnection=function(){this.peerConnection&&(this.peerConnection.removeEventListener("icecandidate",this.handleIceCandidate.bind(this)),this.peerConnection.removeEventListener("icegatheringstatechange",this.handleIceGatheringStateChange.bind(this)),this.peerConnection.close(),this.peerConnection=null)},e3.prototype.clearCollectionTimeout=function(){void 0!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0)},e3.prototype.destroy=function(){this.disabledCollection=!0,this.destroyConnection(),this.clearCollectionTimeout(),this.candidatesCollectionDefer&&(this.candidatesCollectionDefer.reject(new Error("Collection aborted due to destroy")),this.candidatesCollectionDefer=null)},e3.prototype.startCandidatesCollection=function(){return v(this,arguments,void 0,(function(g){var f,S=this;return void 0===g&&(g=0),C(this,(function(_){switch(_.label){case 0:return this.candidatesCollectionDefer||this.disabledCollection?[2]:g>0?[4,new Promise((function(f){return setTimeout(f,g)}))]:[3,2];case 1:_.sent(),_.label=2;case 2:return this.candidatesCollectionDefer=(0,T.defer)(),this.candidatesCollectionDefer.promise.catch((function(){})),f=this.setUpPeerConnection.bind(this),[4,(0,I.retry)(f,this.maxRetries,this.retryDelay).then((function(){S.timeoutId=setTimeout((function(){var g;null===(g=S.candidatesCollectionDefer)||void 0===g||g.reject(new Error("Collection timed out")),S.candidatesCollectionDefer=null,S.destroyConnection(),S.startCandidatesCollection(S.delayAfterError)}),S.maxCollectionTime)})).catch((function(g){return v(S,void 0,void 0,(function(){var f,S;return C(this,(function(v){switch(v.label){case 0:return f="Failed to start collection ".concat((0,I.stringifyError)(g)),null===(S=this.candidatesCollectionDefer)||void 0===S||S.reject(new Error(f)),this.candidatesCollectionDefer=null,[4,Promise.reject(new Error(f))];case 1:return v.sent(),this.startCandidatesCollection(this.delayAfterError),[2]}}))}))}))];case 3:return _.sent(),[2]}}))}))},e3.prototype.getCandidates=function(){return v(this,void 0,void 0,(function(){return C(this,(function(g){switch(g.label){case 0:return 0===this.latestCandidates.length&&this.candidatesCollectionDefer?[4,this.candidatesCollectionDefer.promise]:[3,2];case 1:g.sent(),g.label=2;case 2:return[2,this.latestCandidates]}}))}))},e3}();f.WebRtcIceCandidateCollector=A}},f={},function n(S){var v=f[S];if(void 0!==v)return v.exports;var C=f[S]={exports:{}};return g[S].call(C.exports,C,C.exports,n),C.exports}(260);var g,f},"object"==typeof g&&"object"==typeof f?f.exports=v():"object"==typeof g?g.hydra_player_sdk=v():S.hydra_player_sdk=v()}}),se=__commonJS({"../node_modules/pako/lib/utils/common.js"(g){var f="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function _has(g,f){return Object.prototype.hasOwnProperty.call(g,f)}g.assign=function(g){for(var f=Array.prototype.slice.call(arguments,1);f.length;){var S=f.shift();if(S){if("object"!=typeof S)throw new TypeError(S+"must be non-object");for(var v in S)_has(S,v)&&(g[v]=S[v])}}return g},g.shrinkBuf=function(g,f){return g.length===f?g:g.subarray?g.subarray(0,f):(g.length=f,g)};var S={arraySet:function(g,f,S,v,C){if(f.subarray&&g.subarray)g.set(f.subarray(S,S+v),C);else for(var _=0;_<v;_++)g[C+_]=f[S+_]},flattenChunks:function(g){var f,S,v,C,_,T;for(v=0,f=0,S=g.length;f<S;f++)v+=g[f].length;for(T=new Uint8Array(v),C=0,f=0,S=g.length;f<S;f++)_=g[f],T.set(_,C),C+=_.length;return T}},v={arraySet:function(g,f,S,v,C){for(var _=0;_<v;_++)g[C+_]=f[S+_]},flattenChunks:function(g){return[].concat.apply([],g)}};g.setTyped=function(f){f?(g.Buf8=Uint8Array,g.Buf16=Uint16Array,g.Buf32=Int32Array,g.assign(g,S)):(g.Buf8=Array,g.Buf16=Array,g.Buf32=Array,g.assign(g,v))},g.setTyped(f)}}),ae=__commonJS({"../node_modules/pako/lib/zlib/trees.js"(g){var f=se(),S=4,v=0,C=1,_=2;function zero(g){for(var f=g.length;--f>=0;)g[f]=0}var T=0,I=1,b=2,A=3,P=258,R=29,M=256,w=M+1+R,O=30,D=19,N=2*w+1,k=15,L=16,F=7,x=256,U=16,V=17,B=18,H=[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],$=[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],j=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],G=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],q=512,W=new Array(2*(w+2));zero(W);var z=new Array(2*O);zero(z);var K=new Array(q);zero(K);var J=new Array(P-A+1);zero(J);var Y=new Array(R);zero(Y);var Q,X,Z,ee=new Array(O);function StaticTreeDesc(g,f,S,v,C){this.static_tree=g,this.extra_bits=f,this.extra_base=S,this.elems=v,this.max_length=C,this.has_stree=g&&g.length}function TreeDesc(g,f){this.dyn_tree=g,this.max_code=0,this.stat_desc=f}function d_code(g){return g<256?K[g]:K[256+(g>>>7)]}function put_short(g,f){g.pending_buf[g.pending++]=255&f,g.pending_buf[g.pending++]=f>>>8&255}function send_bits(g,f,S){g.bi_valid>L-S?(g.bi_buf|=f<<g.bi_valid&65535,put_short(g,g.bi_buf),g.bi_buf=f>>L-g.bi_valid,g.bi_valid+=S-L):(g.bi_buf|=f<<g.bi_valid&65535,g.bi_valid+=S)}function send_code(g,f,S){send_bits(g,S[2*f],S[2*f+1])}function bi_reverse(g,f){var S=0;do{S|=1&g,g>>>=1,S<<=1}while(--f>0);return S>>>1}function bi_flush(g){16===g.bi_valid?(put_short(g,g.bi_buf),g.bi_buf=0,g.bi_valid=0):g.bi_valid>=8&&(g.pending_buf[g.pending++]=255&g.bi_buf,g.bi_buf>>=8,g.bi_valid-=8)}function gen_bitlen(g,f){var S,v,C,_,T,I,b=f.dyn_tree,A=f.max_code,P=f.stat_desc.static_tree,R=f.stat_desc.has_stree,M=f.stat_desc.extra_bits,w=f.stat_desc.extra_base,O=f.stat_desc.max_length,D=0;for(_=0;_<=k;_++)g.bl_count[_]=0;for(b[2*g.heap[g.heap_max]+1]=0,S=g.heap_max+1;S<N;S++)(_=b[2*b[2*(v=g.heap[S])+1]+1]+1)>O&&(_=O,D++),b[2*v+1]=_,v>A||(g.bl_count[_]++,T=0,v>=w&&(T=M[v-w]),I=b[2*v],g.opt_len+=I*(_+T),R&&(g.static_len+=I*(P[2*v+1]+T)));if(0!==D){do{for(_=O-1;0===g.bl_count[_];)_--;g.bl_count[_]--,g.bl_count[_+1]+=2,g.bl_count[O]--,D-=2}while(D>0);for(_=O;0!==_;_--)for(v=g.bl_count[_];0!==v;)(C=g.heap[--S])>A||(b[2*C+1]!==_&&(g.opt_len+=(_-b[2*C+1])*b[2*C],b[2*C+1]=_),v--)}}function gen_codes(g,f,S){var v,C,_=new Array(k+1),T=0;for(v=1;v<=k;v++)_[v]=T=T+S[v-1]<<1;for(C=0;C<=f;C++){var I=g[2*C+1];0!==I&&(g[2*C]=bi_reverse(_[I]++,I))}}function tr_static_init(){var g,f,S,v,C,_=new Array(k+1);for(S=0,v=0;v<R-1;v++)for(Y[v]=S,g=0;g<1<<H[v];g++)J[S++]=v;for(J[S-1]=v,C=0,v=0;v<16;v++)for(ee[v]=C,g=0;g<1<<$[v];g++)K[C++]=v;for(C>>=7;v<O;v++)for(ee[v]=C<<7,g=0;g<1<<$[v]-7;g++)K[256+C++]=v;for(f=0;f<=k;f++)_[f]=0;for(g=0;g<=143;)W[2*g+1]=8,g++,_[8]++;for(;g<=255;)W[2*g+1]=9,g++,_[9]++;for(;g<=279;)W[2*g+1]=7,g++,_[7]++;for(;g<=287;)W[2*g+1]=8,g++,_[8]++;for(gen_codes(W,w+1,_),g=0;g<O;g++)z[2*g+1]=5,z[2*g]=bi_reverse(g,5);Q=new StaticTreeDesc(W,H,M+1,w,k),X=new StaticTreeDesc(z,$,0,O,k),Z=new StaticTreeDesc(new Array(0),j,0,D,F)}function init_block(g){var f;for(f=0;f<w;f++)g.dyn_ltree[2*f]=0;for(f=0;f<O;f++)g.dyn_dtree[2*f]=0;for(f=0;f<D;f++)g.bl_tree[2*f]=0;g.dyn_ltree[2*x]=1,g.opt_len=g.static_len=0,g.last_lit=g.matches=0}function bi_windup(g){g.bi_valid>8?put_short(g,g.bi_buf):g.bi_valid>0&&(g.pending_buf[g.pending++]=g.bi_buf),g.bi_buf=0,g.bi_valid=0}function copy_block(g,S,v,C){bi_windup(g),C&&(put_short(g,v),put_short(g,~v)),f.arraySet(g.pending_buf,g.window,S,v,g.pending),g.pending+=v}function smaller(g,f,S,v){var C=2*f,_=2*S;return g[C]<g[_]||g[C]===g[_]&&v[f]<=v[S]}function pqdownheap(g,f,S){for(var v=g.heap[S],C=S<<1;C<=g.heap_len&&(C<g.heap_len&&smaller(f,g.heap[C+1],g.heap[C],g.depth)&&C++,!smaller(f,v,g.heap[C],g.depth));)g.heap[S]=g.heap[C],S=C,C<<=1;g.heap[S]=v}function compress_block(g,f,S){var v,C,_,T,I=0;if(0!==g.last_lit)do{v=g.pending_buf[g.d_buf+2*I]<<8|g.pending_buf[g.d_buf+2*I+1],C=g.pending_buf[g.l_buf+I],I++,0===v?send_code(g,C,f):(send_code(g,(_=J[C])+M+1,f),0!==(T=H[_])&&send_bits(g,C-=Y[_],T),send_code(g,_=d_code(--v),S),0!==(T=$[_])&&send_bits(g,v-=ee[_],T))}while(I<g.last_lit);send_code(g,x,f)}function build_tree(g,f){var S,v,C,_=f.dyn_tree,T=f.stat_desc.static_tree,I=f.stat_desc.has_stree,b=f.stat_desc.elems,A=-1;for(g.heap_len=0,g.heap_max=N,S=0;S<b;S++)0!==_[2*S]?(g.heap[++g.heap_len]=A=S,g.depth[S]=0):_[2*S+1]=0;for(;g.heap_len<2;)_[2*(C=g.heap[++g.heap_len]=A<2?++A:0)]=1,g.depth[C]=0,g.opt_len--,I&&(g.static_len-=T[2*C+1]);for(f.max_code=A,S=g.heap_len>>1;S>=1;S--)pqdownheap(g,_,S);C=b;do{S=g.heap[1],g.heap[1]=g.heap[g.heap_len--],pqdownheap(g,_,1),v=g.heap[1],g.heap[--g.heap_max]=S,g.heap[--g.heap_max]=v,_[2*C]=_[2*S]+_[2*v],g.depth[C]=(g.depth[S]>=g.depth[v]?g.depth[S]:g.depth[v])+1,_[2*S+1]=_[2*v+1]=C,g.heap[1]=C++,pqdownheap(g,_,1)}while(g.heap_len>=2);g.heap[--g.heap_max]=g.heap[1],gen_bitlen(g,f),gen_codes(_,A,g.bl_count)}function scan_tree(g,f,S){var v,C,_=-1,T=f[1],I=0,b=7,A=4;for(0===T&&(b=138,A=3),f[2*(S+1)+1]=65535,v=0;v<=S;v++)C=T,T=f[2*(v+1)+1],++I<b&&C===T||(I<A?g.bl_tree[2*C]+=I:0!==C?(C!==_&&g.bl_tree[2*C]++,g.bl_tree[2*U]++):I<=10?g.bl_tree[2*V]++:g.bl_tree[2*B]++,I=0,_=C,0===T?(b=138,A=3):C===T?(b=6,A=3):(b=7,A=4))}function send_tree(g,f,S){var v,C,_=-1,T=f[1],I=0,b=7,A=4;for(0===T&&(b=138,A=3),v=0;v<=S;v++)if(C=T,T=f[2*(v+1)+1],!(++I<b&&C===T)){if(I<A)do{send_code(g,C,g.bl_tree)}while(0!=--I);else 0!==C?(C!==_&&(send_code(g,C,g.bl_tree),I--),send_code(g,U,g.bl_tree),send_bits(g,I-3,2)):I<=10?(send_code(g,V,g.bl_tree),send_bits(g,I-3,3)):(send_code(g,B,g.bl_tree),send_bits(g,I-11,7));I=0,_=C,0===T?(b=138,A=3):C===T?(b=6,A=3):(b=7,A=4)}}function build_bl_tree(g){var f;for(scan_tree(g,g.dyn_ltree,g.l_desc.max_code),scan_tree(g,g.dyn_dtree,g.d_desc.max_code),build_tree(g,g.bl_desc),f=D-1;f>=3&&0===g.bl_tree[2*G[f]+1];f--);return g.opt_len+=3*(f+1)+5+5+4,f}function send_all_trees(g,f,S,v){var C;for(send_bits(g,f-257,5),send_bits(g,S-1,5),send_bits(g,v-4,4),C=0;C<v;C++)send_bits(g,g.bl_tree[2*G[C]+1],3);send_tree(g,g.dyn_ltree,f-1),send_tree(g,g.dyn_dtree,S-1)}function detect_data_type(g){var f,S=4093624447;for(f=0;f<=31;f++,S>>>=1)if(1&S&&0!==g.dyn_ltree[2*f])return v;if(0!==g.dyn_ltree[18]||0!==g.dyn_ltree[20]||0!==g.dyn_ltree[26])return C;for(f=32;f<M;f++)if(0!==g.dyn_ltree[2*f])return C;return v}zero(ee);var te=!1;function _tr_init(g){te||(tr_static_init(),te=!0),g.l_desc=new TreeDesc(g.dyn_ltree,Q),g.d_desc=new TreeDesc(g.dyn_dtree,X),g.bl_desc=new TreeDesc(g.bl_tree,Z),g.bi_buf=0,g.bi_valid=0,init_block(g)}function _tr_stored_block(g,f,S,v){send_bits(g,(T<<1)+(v?1:0),3),copy_block(g,f,S,!0)}function _tr_align(g){send_bits(g,I<<1,3),send_code(g,x,W),bi_flush(g)}function _tr_flush_block(g,f,v,C){var T,A,P=0;g.level>0?(g.strm.data_type===_&&(g.strm.data_type=detect_data_type(g)),build_tree(g,g.l_desc),build_tree(g,g.d_desc),P=build_bl_tree(g),T=g.opt_len+3+7>>>3,(A=g.static_len+3+7>>>3)<=T&&(T=A)):T=A=v+5,v+4<=T&&-1!==f?_tr_stored_block(g,f,v,C):g.strategy===S||A===T?(send_bits(g,(I<<1)+(C?1:0),3),compress_block(g,W,z)):(send_bits(g,(b<<1)+(C?1:0),3),send_all_trees(g,g.l_desc.max_code+1,g.d_desc.max_code+1,P+1),compress_block(g,g.dyn_ltree,g.dyn_dtree)),init_block(g),C&&bi_windup(g)}function _tr_tally(g,f,S){return g.pending_buf[g.d_buf+2*g.last_lit]=f>>>8&255,g.pending_buf[g.d_buf+2*g.last_lit+1]=255&f,g.pending_buf[g.l_buf+g.last_lit]=255&S,g.last_lit++,0===f?g.dyn_ltree[2*S]++:(g.matches++,f--,g.dyn_ltree[2*(J[S]+M+1)]++,g.dyn_dtree[2*d_code(f)]++),g.last_lit===g.lit_bufsize-1}g._tr_init=_tr_init,g._tr_stored_block=_tr_stored_block,g._tr_flush_block=_tr_flush_block,g._tr_tally=_tr_tally,g._tr_align=_tr_align}}),oe=__commonJS({"../node_modules/pako/lib/zlib/adler32.js"(g,f){function adler32(g,f,S,v){for(var C=65535&g|0,_=g>>>16&65535|0,T=0;0!==S;){S-=T=S>2e3?2e3:S;do{_=_+(C=C+f[v++]|0)|0}while(--T);C%=65521,_%=65521}return C|_<<16|0}f.exports=adler32}}),le=__commonJS({"../node_modules/pako/lib/zlib/crc32.js"(g,f){function makeTable(){for(var g,f=[],S=0;S<256;S++){g=S;for(var v=0;v<8;v++)g=1&g?3988292384^g>>>1:g>>>1;f[S]=g}return f}var S=makeTable();function crc32(g,f,v,C){var _=S,T=C+v;g^=-1;for(var I=C;I<T;I++)g=g>>>8^_[255&(g^f[I])];return-1^g}f.exports=crc32}}),ce=__commonJS({"../node_modules/pako/lib/zlib/messages.js"(g,f){f.exports={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"}}}),de=__commonJS({"../node_modules/pako/lib/zlib/deflate.js"(g){var f,S=se(),v=ae(),C=oe(),_=le(),T=ce(),I=0,b=1,A=3,P=4,R=5,M=0,w=1,O=-2,D=-3,N=-5,k=-1,L=1,F=2,x=3,U=4,V=0,B=2,H=8,$=9,j=15,G=8,q=256+1+29,W=30,z=19,K=2*q+1,J=15,Y=3,Q=258,X=Q+Y+1,Z=32,ee=42,te=69,ie=73,ne=91,re=103,de=113,he=666,ue=1,ge=2,pe=3,me=4,fe=3;function err(g,f){return g.msg=T[f],f}function rank(g){return(g<<1)-(g>4?9:0)}function zero(g){for(var f=g.length;--f>=0;)g[f]=0}function flush_pending(g){var f=g.state,v=f.pending;v>g.avail_out&&(v=g.avail_out),0!==v&&(S.arraySet(g.output,f.pending_buf,f.pending_out,v,g.next_out),g.next_out+=v,f.pending_out+=v,g.total_out+=v,g.avail_out-=v,f.pending-=v,0===f.pending&&(f.pending_out=0))}function flush_block_only(g,f){v._tr_flush_block(g,g.block_start>=0?g.block_start:-1,g.strstart-g.block_start,f),g.block_start=g.strstart,flush_pending(g.strm)}function put_byte(g,f){g.pending_buf[g.pending++]=f}function putShortMSB(g,f){g.pending_buf[g.pending++]=f>>>8&255,g.pending_buf[g.pending++]=255&f}function read_buf(g,f,v,T){var I=g.avail_in;return I>T&&(I=T),0===I?0:(g.avail_in-=I,S.arraySet(f,g.input,g.next_in,I,v),1===g.state.wrap?g.adler=C(g.adler,f,I,v):2===g.state.wrap&&(g.adler=_(g.adler,f,I,v)),g.next_in+=I,g.total_in+=I,I)}function longest_match(g,f){var S,v,C=g.max_chain_length,_=g.strstart,T=g.prev_length,I=g.nice_match,b=g.strstart>g.w_size-X?g.strstart-(g.w_size-X):0,A=g.window,P=g.w_mask,R=g.prev,M=g.strstart+Q,w=A[_+T-1],O=A[_+T];g.prev_length>=g.good_match&&(C>>=2),I>g.lookahead&&(I=g.lookahead);do{if(A[(S=f)+T]===O&&A[S+T-1]===w&&A[S]===A[_]&&A[++S]===A[_+1]){_+=2,S++;do{}while(A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&_<M);if(v=Q-(M-_),_=M-Q,v>T){if(g.match_start=f,T=v,v>=I)break;w=A[_+T-1],O=A[_+T]}}}while((f=R[f&P])>b&&0!=--C);return T<=g.lookahead?T:g.lookahead}function fill_window(g){var f,v,C,_,T,I=g.w_size;do{if(_=g.window_size-g.lookahead-g.strstart,g.strstart>=I+(I-X)){S.arraySet(g.window,g.window,I,I,0),g.match_start-=I,g.strstart-=I,g.block_start-=I,f=v=g.hash_size;do{C=g.head[--f],g.head[f]=C>=I?C-I:0}while(--v);f=v=I;do{C=g.prev[--f],g.prev[f]=C>=I?C-I:0}while(--v);_+=I}if(0===g.strm.avail_in)break;if(v=read_buf(g.strm,g.window,g.strstart+g.lookahead,_),g.lookahead+=v,g.lookahead+g.insert>=Y)for(T=g.strstart-g.insert,g.ins_h=g.window[T],g.ins_h=(g.ins_h<<g.hash_shift^g.window[T+1])&g.hash_mask;g.insert&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[T+Y-1])&g.hash_mask,g.prev[T&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=T,T++,g.insert--,!(g.lookahead+g.insert<Y)););}while(g.lookahead<X&&0!==g.strm.avail_in)}function deflate_stored(g,f){var S=65535;for(S>g.pending_buf_size-5&&(S=g.pending_buf_size-5);;){if(g.lookahead<=1){if(fill_window(g),0===g.lookahead&&f===I)return ue;if(0===g.lookahead)break}g.strstart+=g.lookahead,g.lookahead=0;var v=g.block_start+S;if((0===g.strstart||g.strstart>=v)&&(g.lookahead=g.strstart-v,g.strstart=v,flush_block_only(g,!1),0===g.strm.avail_out))return ue;if(g.strstart-g.block_start>=g.w_size-X&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}return g.insert=0,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):(g.strstart>g.block_start&&(flush_block_only(g,!1),g.strm.avail_out),ue)}function deflate_fast(g,f){for(var S,C;;){if(g.lookahead<X){if(fill_window(g),g.lookahead<X&&f===I)return ue;if(0===g.lookahead)break}if(S=0,g.lookahead>=Y&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+Y-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart),0!==S&&g.strstart-S<=g.w_size-X&&(g.match_length=longest_match(g,S)),g.match_length>=Y)if(C=v._tr_tally(g,g.strstart-g.match_start,g.match_length-Y),g.lookahead-=g.match_length,g.match_length<=g.max_lazy_match&&g.lookahead>=Y){g.match_length--;do{g.strstart++,g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+Y-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart}while(0!=--g.match_length);g.strstart++}else g.strstart+=g.match_length,g.match_length=0,g.ins_h=g.window[g.strstart],g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+1])&g.hash_mask;else C=v._tr_tally(g,0,g.window[g.strstart]),g.lookahead--,g.strstart++;if(C&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}return g.insert=g.strstart<Y-1?g.strstart:Y-1,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?ue:ge}function deflate_slow(g,f){for(var S,C,_;;){if(g.lookahead<X){if(fill_window(g),g.lookahead<X&&f===I)return ue;if(0===g.lookahead)break}if(S=0,g.lookahead>=Y&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+Y-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart),g.prev_length=g.match_length,g.prev_match=g.match_start,g.match_length=Y-1,0!==S&&g.prev_length<g.max_lazy_match&&g.strstart-S<=g.w_size-X&&(g.match_length=longest_match(g,S),g.match_length<=5&&(g.strategy===L||g.match_length===Y&&g.strstart-g.match_start>4096)&&(g.match_length=Y-1)),g.prev_length>=Y&&g.match_length<=g.prev_length){_=g.strstart+g.lookahead-Y,C=v._tr_tally(g,g.strstart-1-g.prev_match,g.prev_length-Y),g.lookahead-=g.prev_length-1,g.prev_length-=2;do{++g.strstart<=_&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+Y-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart)}while(0!=--g.prev_length);if(g.match_available=0,g.match_length=Y-1,g.strstart++,C&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}else if(g.match_available){if((C=v._tr_tally(g,0,g.window[g.strstart-1]))&&flush_block_only(g,!1),g.strstart++,g.lookahead--,0===g.strm.avail_out)return ue}else g.match_available=1,g.strstart++,g.lookahead--}return g.match_available&&(C=v._tr_tally(g,0,g.window[g.strstart-1]),g.match_available=0),g.insert=g.strstart<Y-1?g.strstart:Y-1,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?ue:ge}function deflate_rle(g,f){for(var S,C,_,T,b=g.window;;){if(g.lookahead<=Q){if(fill_window(g),g.lookahead<=Q&&f===I)return ue;if(0===g.lookahead)break}if(g.match_length=0,g.lookahead>=Y&&g.strstart>0&&(C=b[_=g.strstart-1])===b[++_]&&C===b[++_]&&C===b[++_]){T=g.strstart+Q;do{}while(C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&_<T);g.match_length=Q-(T-_),g.match_length>g.lookahead&&(g.match_length=g.lookahead)}if(g.match_length>=Y?(S=v._tr_tally(g,1,g.match_length-Y),g.lookahead-=g.match_length,g.strstart+=g.match_length,g.match_length=0):(S=v._tr_tally(g,0,g.window[g.strstart]),g.lookahead--,g.strstart++),S&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}return g.insert=0,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?ue:ge}function deflate_huff(g,f){for(var S;;){if(0===g.lookahead&&(fill_window(g),0===g.lookahead)){if(f===I)return ue;break}if(g.match_length=0,S=v._tr_tally(g,0,g.window[g.strstart]),g.lookahead--,g.strstart++,S&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}return g.insert=0,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?ue:ge}function Config(g,f,S,v,C){this.good_length=g,this.max_lazy=f,this.nice_length=S,this.max_chain=v,this.func=C}function lm_init(g){g.window_size=2*g.w_size,zero(g.head),g.max_lazy_match=f[g.level].max_lazy,g.good_match=f[g.level].good_length,g.nice_match=f[g.level].nice_length,g.max_chain_length=f[g.level].max_chain,g.strstart=0,g.block_start=0,g.lookahead=0,g.insert=0,g.match_length=g.prev_length=Y-1,g.match_available=0,g.ins_h=0}function DeflateState(){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=H,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 S.Buf16(2*K),this.dyn_dtree=new S.Buf16(2*(2*W+1)),this.bl_tree=new S.Buf16(2*(2*z+1)),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new S.Buf16(J+1),this.heap=new S.Buf16(2*q+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new S.Buf16(2*q+1),zero(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(g){var f;return g&&g.state?(g.total_in=g.total_out=0,g.data_type=B,(f=g.state).pending=0,f.pending_out=0,f.wrap<0&&(f.wrap=-f.wrap),f.status=f.wrap?ee:de,g.adler=2===f.wrap?0:1,f.last_flush=I,v._tr_init(f),M):err(g,O)}function deflateReset(g){var f=deflateResetKeep(g);return f===M&&lm_init(g.state),f}function deflateSetHeader(g,f){return g&&g.state?2!==g.state.wrap?O:(g.state.gzhead=f,M):O}function deflateInit2(g,f,v,C,_,T){if(!g)return O;var I=1;if(f===k&&(f=6),C<0?(I=0,C=-C):C>15&&(I=2,C-=16),_<1||_>$||v!==H||C<8||C>15||f<0||f>9||T<0||T>U)return err(g,O);8===C&&(C=9);var b=new DeflateState;return g.state=b,b.strm=g,b.wrap=I,b.gzhead=null,b.w_bits=C,b.w_size=1<<b.w_bits,b.w_mask=b.w_size-1,b.hash_bits=_+7,b.hash_size=1<<b.hash_bits,b.hash_mask=b.hash_size-1,b.hash_shift=~~((b.hash_bits+Y-1)/Y),b.window=new S.Buf8(2*b.w_size),b.head=new S.Buf16(b.hash_size),b.prev=new S.Buf16(b.w_size),b.lit_bufsize=1<<_+6,b.pending_buf_size=4*b.lit_bufsize,b.pending_buf=new S.Buf8(b.pending_buf_size),b.d_buf=1*b.lit_bufsize,b.l_buf=3*b.lit_bufsize,b.level=f,b.strategy=T,b.method=v,deflateReset(g)}function deflateInit(g,f){return deflateInit2(g,f,H,j,G,V)}function deflate(g,S){var C,T,D,k;if(!g||!g.state||S>R||S<0)return g?err(g,O):O;if(T=g.state,!g.output||!g.input&&0!==g.avail_in||T.status===he&&S!==P)return err(g,0===g.avail_out?N:O);if(T.strm=g,C=T.last_flush,T.last_flush=S,T.status===ee)if(2===T.wrap)g.adler=0,put_byte(T,31),put_byte(T,139),put_byte(T,8),T.gzhead?(put_byte(T,(T.gzhead.text?1:0)+(T.gzhead.hcrc?2:0)+(T.gzhead.extra?4:0)+(T.gzhead.name?8:0)+(T.gzhead.comment?16:0)),put_byte(T,255&T.gzhead.time),put_byte(T,T.gzhead.time>>8&255),put_byte(T,T.gzhead.time>>16&255),put_byte(T,T.gzhead.time>>24&255),put_byte(T,9===T.level?2:T.strategy>=F||T.level<2?4:0),put_byte(T,255&T.gzhead.os),T.gzhead.extra&&T.gzhead.extra.length&&(put_byte(T,255&T.gzhead.extra.length),put_byte(T,T.gzhead.extra.length>>8&255)),T.gzhead.hcrc&&(g.adler=_(g.adler,T.pending_buf,T.pending,0)),T.gzindex=0,T.status=te):(put_byte(T,0),put_byte(T,0),put_byte(T,0),put_byte(T,0),put_byte(T,0),put_byte(T,9===T.level?2:T.strategy>=F||T.level<2?4:0),put_byte(T,fe),T.status=de);else{var L=H+(T.w_bits-8<<4)<<8;L|=(T.strategy>=F||T.level<2?0:T.level<6?1:6===T.level?2:3)<<6,0!==T.strstart&&(L|=Z),L+=31-L%31,T.status=de,putShortMSB(T,L),0!==T.strstart&&(putShortMSB(T,g.adler>>>16),putShortMSB(T,65535&g.adler)),g.adler=1}if(T.status===te)if(T.gzhead.extra){for(D=T.pending;T.gzindex<(65535&T.gzhead.extra.length)&&(T.pending!==T.pending_buf_size||(T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),flush_pending(g),D=T.pending,T.pending!==T.pending_buf_size));)put_byte(T,255&T.gzhead.extra[T.gzindex]),T.gzindex++;T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),T.gzindex===T.gzhead.extra.length&&(T.gzindex=0,T.status=ie)}else T.status=ie;if(T.status===ie)if(T.gzhead.name){D=T.pending;do{if(T.pending===T.pending_buf_size&&(T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),flush_pending(g),D=T.pending,T.pending===T.pending_buf_size)){k=1;break}k=T.gzindex<T.gzhead.name.length?255&T.gzhead.name.charCodeAt(T.gzindex++):0,put_byte(T,k)}while(0!==k);T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),0===k&&(T.gzindex=0,T.status=ne)}else T.status=ne;if(T.status===ne)if(T.gzhead.comment){D=T.pending;do{if(T.pending===T.pending_buf_size&&(T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),flush_pending(g),D=T.pending,T.pending===T.pending_buf_size)){k=1;break}k=T.gzindex<T.gzhead.comment.length?255&T.gzhead.comment.charCodeAt(T.gzindex++):0,put_byte(T,k)}while(0!==k);T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),0===k&&(T.status=re)}else T.status=re;if(T.status===re&&(T.gzhead.hcrc?(T.pending+2>T.pending_buf_size&&flush_pending(g),T.pending+2<=T.pending_buf_size&&(put_byte(T,255&g.adler),put_byte(T,g.adler>>8&255),g.adler=0,T.status=de)):T.status=de),0!==T.pending){if(flush_pending(g),0===g.avail_out)return T.last_flush=-1,M}else if(0===g.avail_in&&rank(S)<=rank(C)&&S!==P)return err(g,N);if(T.status===he&&0!==g.avail_in)return err(g,N);if(0!==g.avail_in||0!==T.lookahead||S!==I&&T.status!==he){var U=T.strategy===F?deflate_huff(T,S):T.strategy===x?deflate_rle(T,S):f[T.level].func(T,S);if(U!==pe&&U!==me||(T.status=he),U===ue||U===pe)return 0===g.avail_out&&(T.last_flush=-1),M;if(U===ge&&(S===b?v._tr_align(T):S!==R&&(v._tr_stored_block(T,0,0,!1),S===A&&(zero(T.head),0===T.lookahead&&(T.strstart=0,T.block_start=0,T.insert=0))),flush_pending(g),0===g.avail_out))return T.last_flush=-1,M}return S!==P?M:T.wrap<=0?w:(2===T.wrap?(put_byte(T,255&g.adler),put_byte(T,g.adler>>8&255),put_byte(T,g.adler>>16&255),put_byte(T,g.adler>>24&255),put_byte(T,255&g.total_in),put_byte(T,g.total_in>>8&255),put_byte(T,g.total_in>>16&255),put_byte(T,g.total_in>>24&255)):(putShortMSB(T,g.adler>>>16),putShortMSB(T,65535&g.adler)),flush_pending(g),T.wrap>0&&(T.wrap=-T.wrap),0!==T.pending?M:w)}function deflateEnd(g){var f;return g&&g.state?(f=g.state.status)!==ee&&f!==te&&f!==ie&&f!==ne&&f!==re&&f!==de&&f!==he?err(g,O):(g.state=null,f===de?err(g,D):M):O}function deflateSetDictionary(g,f){var v,_,T,I,b,A,P,R,w=f.length;if(!g||!g.state)return O;if(2===(I=(v=g.state).wrap)||1===I&&v.status!==ee||v.lookahead)return O;for(1===I&&(g.adler=C(g.adler,f,w,0)),v.wrap=0,w>=v.w_size&&(0===I&&(zero(v.head),v.strstart=0,v.block_start=0,v.insert=0),R=new S.Buf8(v.w_size),S.arraySet(R,f,w-v.w_size,v.w_size,0),f=R,w=v.w_size),b=g.avail_in,A=g.next_in,P=g.input,g.avail_in=w,g.next_in=0,g.input=f,fill_window(v);v.lookahead>=Y;){_=v.strstart,T=v.lookahead-(Y-1);do{v.ins_h=(v.ins_h<<v.hash_shift^v.window[_+Y-1])&v.hash_mask,v.prev[_&v.w_mask]=v.head[v.ins_h],v.head[v.ins_h]=_,_++}while(--T);v.strstart=_,v.lookahead=Y-1,fill_window(v)}return v.strstart+=v.lookahead,v.block_start=v.strstart,v.insert=v.lookahead,v.lookahead=0,v.match_length=v.prev_length=Y-1,v.match_available=0,g.next_in=A,g.input=P,g.avail_in=b,v.wrap=I,M}f=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],g.deflateInit=deflateInit,g.deflateInit2=deflateInit2,g.deflateReset=deflateReset,g.deflateResetKeep=deflateResetKeep,g.deflateSetHeader=deflateSetHeader,g.deflate=deflate,g.deflateEnd=deflateEnd,g.deflateSetDictionary=deflateSetDictionary,g.deflateInfo="pako deflate (from Nodeca project)"}}),he=__commonJS({"../node_modules/pako/lib/utils/strings.js"(g){var f=se(),S=!0,v=!0;try{String.fromCharCode.apply(null,[0])}catch(g){S=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(g){v=!1}var C,_=new f.Buf8(256);for(C=0;C<256;C++)_[C]=C>=252?6:C>=248?5:C>=240?4:C>=224?3:C>=192?2:1;function buf2binstring(g,C){if(C<65534&&(g.subarray&&v||!g.subarray&&S))return String.fromCharCode.apply(null,f.shrinkBuf(g,C));for(var _="",T=0;T<C;T++)_+=String.fromCharCode(g[T]);return _}_[254]=_[254]=1,g.string2buf=function(g){var S,v,C,_,T,I=g.length,b=0;for(_=0;_<I;_++)55296==(64512&(v=g.charCodeAt(_)))&&_+1<I&&56320==(64512&(C=g.charCodeAt(_+1)))&&(v=65536+(v-55296<<10)+(C-56320),_++),b+=v<128?1:v<2048?2:v<65536?3:4;for(S=new f.Buf8(b),T=0,_=0;T<b;_++)55296==(64512&(v=g.charCodeAt(_)))&&_+1<I&&56320==(64512&(C=g.charCodeAt(_+1)))&&(v=65536+(v-55296<<10)+(C-56320),_++),v<128?S[T++]=v:v<2048?(S[T++]=192|v>>>6,S[T++]=128|63&v):v<65536?(S[T++]=224|v>>>12,S[T++]=128|v>>>6&63,S[T++]=128|63&v):(S[T++]=240|v>>>18,S[T++]=128|v>>>12&63,S[T++]=128|v>>>6&63,S[T++]=128|63&v);return S},g.buf2binstring=function(g){return buf2binstring(g,g.length)},g.binstring2buf=function(g){for(var S=new f.Buf8(g.length),v=0,C=S.length;v<C;v++)S[v]=g.charCodeAt(v);return S},g.buf2string=function(g,f){var S,v,C,T,I=f||g.length,b=new Array(2*I);for(v=0,S=0;S<I;)if((C=g[S++])<128)b[v++]=C;else if((T=_[C])>4)b[v++]=65533,S+=T-1;else{for(C&=2===T?31:3===T?15:7;T>1&&S<I;)C=C<<6|63&g[S++],T--;T>1?b[v++]=65533:C<65536?b[v++]=C:(C-=65536,b[v++]=55296|C>>10&1023,b[v++]=56320|1023&C)}return buf2binstring(b,v)},g.utf8border=function(g,f){var S;for((f=f||g.length)>g.length&&(f=g.length),S=f-1;S>=0&&128==(192&g[S]);)S--;return S<0||0===S?f:S+_[g[S]]>f?S:f}}}),ue=__commonJS({"../node_modules/pako/lib/zlib/zstream.js"(g,f){function ZStream(){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}f.exports=ZStream}}),ge=__commonJS({"../node_modules/pako/lib/deflate.js"(g){var f=de(),S=se(),v=he(),C=ce(),_=ue(),T=Object.prototype.toString,I=0,b=4,A=0,P=1,R=2,M=-1,w=0,O=8;function Deflate(g){if(!(this instanceof Deflate))return new Deflate(g);this.options=S.assign({level:M,method:O,chunkSize:16384,windowBits:15,memLevel:8,strategy:w,to:""},g||{});var I=this.options;I.raw&&I.windowBits>0?I.windowBits=-I.windowBits:I.gzip&&I.windowBits>0&&I.windowBits<16&&(I.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _,this.strm.avail_out=0;var b=f.deflateInit2(this.strm,I.level,I.method,I.windowBits,I.memLevel,I.strategy);if(b!==A)throw new Error(C[b]);if(I.header&&f.deflateSetHeader(this.strm,I.header),I.dictionary){var P;if(P="string"==typeof I.dictionary?v.string2buf(I.dictionary):"[object ArrayBuffer]"===T.call(I.dictionary)?new Uint8Array(I.dictionary):I.dictionary,(b=f.deflateSetDictionary(this.strm,P))!==A)throw new Error(C[b]);this._dict_set=!0}}function deflate(g,f){var S=new Deflate(f);if(S.push(g,!0),S.err)throw S.msg||C[S.err];return S.result}function deflateRaw(g,f){return(f=f||{}).raw=!0,deflate(g,f)}function gzip(g,f){return(f=f||{}).gzip=!0,deflate(g,f)}Deflate.prototype.push=function(g,C){var _,M,w=this.strm,O=this.options.chunkSize;if(this.ended)return!1;M=C===~~C?C:!0===C?b:I,"string"==typeof g?w.input=v.string2buf(g):"[object ArrayBuffer]"===T.call(g)?w.input=new Uint8Array(g):w.input=g,w.next_in=0,w.avail_in=w.input.length;do{if(0===w.avail_out&&(w.output=new S.Buf8(O),w.next_out=0,w.avail_out=O),(_=f.deflate(w,M))!==P&&_!==A)return this.onEnd(_),this.ended=!0,!1;0!==w.avail_out&&(0!==w.avail_in||M!==b&&M!==R)||("string"===this.options.to?this.onData(v.buf2binstring(S.shrinkBuf(w.output,w.next_out))):this.onData(S.shrinkBuf(w.output,w.next_out)))}while((w.avail_in>0||0===w.avail_out)&&_!==P);return M===b?(_=f.deflateEnd(this.strm),this.onEnd(_),this.ended=!0,_===A):M!==R||(this.onEnd(A),w.avail_out=0,!0)},Deflate.prototype.onData=function(g){this.chunks.push(g)},Deflate.prototype.onEnd=function(g){g===A&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=S.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg},g.Deflate=Deflate,g.deflate=deflate,g.deflateRaw=deflateRaw,g.gzip=gzip}}),pe=__commonJS({"../node_modules/pako/lib/zlib/inffast.js"(g,f){var S=30,v=12;f.exports=function inflate_fast(g,f){var C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q;C=g.state,_=g.next_in,G=g.input,T=_+(g.avail_in-5),I=g.next_out,q=g.output,b=I-(f-g.avail_out),A=I+(g.avail_out-257),P=C.dmax,R=C.wsize,M=C.whave,w=C.wnext,O=C.window,D=C.hold,N=C.bits,k=C.lencode,L=C.distcode,F=(1<<C.lenbits)-1,x=(1<<C.distbits)-1;e:do{N<15&&(D+=G[_++]<<N,N+=8,D+=G[_++]<<N,N+=8),U=k[D&F];t:for(;;){if(D>>>=V=U>>>24,N-=V,0===(V=U>>>16&255))q[I++]=65535&U;else{if(!(16&V)){if(0==(64&V)){U=k[(65535&U)+(D&(1<<V)-1)];continue t}if(32&V){C.mode=v;break e}g.msg="invalid literal/length code",C.mode=S;break e}B=65535&U,(V&=15)&&(N<V&&(D+=G[_++]<<N,N+=8),B+=D&(1<<V)-1,D>>>=V,N-=V),N<15&&(D+=G[_++]<<N,N+=8,D+=G[_++]<<N,N+=8),U=L[D&x];i:for(;;){if(D>>>=V=U>>>24,N-=V,!(16&(V=U>>>16&255))){if(0==(64&V)){U=L[(65535&U)+(D&(1<<V)-1)];continue i}g.msg="invalid distance code",C.mode=S;break e}if(H=65535&U,N<(V&=15)&&(D+=G[_++]<<N,(N+=8)<V&&(D+=G[_++]<<N,N+=8)),(H+=D&(1<<V)-1)>P){g.msg="invalid distance too far back",C.mode=S;break e}if(D>>>=V,N-=V,H>(V=I-b)){if((V=H-V)>M&&C.sane){g.msg="invalid distance too far back",C.mode=S;break e}if($=0,j=O,0===w){if($+=R-V,V<B){B-=V;do{q[I++]=O[$++]}while(--V);$=I-H,j=q}}else if(w<V){if($+=R+w-V,(V-=w)<B){B-=V;do{q[I++]=O[$++]}while(--V);if($=0,w<B){B-=V=w;do{q[I++]=O[$++]}while(--V);$=I-H,j=q}}}else if($+=w-V,V<B){B-=V;do{q[I++]=O[$++]}while(--V);$=I-H,j=q}for(;B>2;)q[I++]=j[$++],q[I++]=j[$++],q[I++]=j[$++],B-=3;B&&(q[I++]=j[$++],B>1&&(q[I++]=j[$++]))}else{$=I-H;do{q[I++]=q[$++],q[I++]=q[$++],q[I++]=q[$++],B-=3}while(B>2);B&&(q[I++]=q[$++],B>1&&(q[I++]=q[$++]))}break}}break}}while(_<T&&I<A);_-=B=N>>3,D&=(1<<(N-=B<<3))-1,g.next_in=_,g.next_out=I,g.avail_in=_<T?T-_+5:5-(_-T),g.avail_out=I<A?A-I+257:257-(I-A),C.hold=D,C.bits=N}}}),me=__commonJS({"../node_modules/pako/lib/zlib/inftrees.js"(g,f){var S=se(),v=15,C=852,_=592,T=0,I=1,b=2,A=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],P=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],R=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],M=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];f.exports=function inflate_table(g,f,w,O,D,N,k,L){var F,x,U,V,B,H,$,j,G,q=L.bits,W=0,z=0,K=0,J=0,Y=0,Q=0,X=0,Z=0,ee=0,te=0,ie=null,ne=0,re=new S.Buf16(v+1),se=new S.Buf16(v+1),ae=null,oe=0;for(W=0;W<=v;W++)re[W]=0;for(z=0;z<O;z++)re[f[w+z]]++;for(Y=q,J=v;J>=1&&0===re[J];J--);if(Y>J&&(Y=J),0===J)return D[N++]=20971520,D[N++]=20971520,L.bits=1,0;for(K=1;K<J&&0===re[K];K++);for(Y<K&&(Y=K),Z=1,W=1;W<=v;W++)if(Z<<=1,(Z-=re[W])<0)return-1;if(Z>0&&(g===T||1!==J))return-1;for(se[1]=0,W=1;W<v;W++)se[W+1]=se[W]+re[W];for(z=0;z<O;z++)0!==f[w+z]&&(k[se[f[w+z]]++]=z);if(g===T?(ie=ae=k,H=19):g===I?(ie=A,ne-=257,ae=P,oe-=257,H=256):(ie=R,ae=M,H=-1),te=0,z=0,W=K,B=N,Q=Y,X=0,U=-1,V=(ee=1<<Y)-1,g===I&&ee>C||g===b&&ee>_)return 1;for(;;){$=W-X,k[z]<H?(j=0,G=k[z]):k[z]>H?(j=ae[oe+k[z]],G=ie[ne+k[z]]):(j=96,G=0),F=1<<W-X,K=x=1<<Q;do{D[B+(te>>X)+(x-=F)]=$<<24|j<<16|G|0}while(0!==x);for(F=1<<W-1;te&F;)F>>=1;if(0!==F?(te&=F-1,te+=F):te=0,z++,0==--re[W]){if(W===J)break;W=f[w+k[z]]}if(W>Y&&(te&V)!==U){for(0===X&&(X=Y),B+=K,Z=1<<(Q=W-X);Q+X<J&&!((Z-=re[Q+X])<=0);)Q++,Z<<=1;if(ee+=1<<Q,g===I&&ee>C||g===b&&ee>_)return 1;D[U=te&V]=Y<<24|Q<<16|B-N|0}}return 0!==te&&(D[B+te]=W-X<<24|64<<16|0),L.bits=Y,0}}}),fe=__commonJS({"../node_modules/pako/lib/zlib/inflate.js"(g){var f=se(),S=oe(),v=le(),C=pe(),_=me(),T=0,I=1,b=2,A=4,P=5,R=6,M=0,w=1,O=2,D=-2,N=-3,k=-4,L=-5,F=8,x=1,U=2,V=3,B=4,H=5,$=6,j=7,G=8,q=9,W=10,z=11,K=12,J=13,Y=14,Q=15,X=16,Z=17,ee=18,te=19,ie=20,ne=21,re=22,ae=23,ce=24,de=25,he=26,ue=27,ge=28,fe=29,Se=30,ve=31,Ce=852,ye=592,Ee=15;function zswap32(g){return(g>>>24&255)+(g>>>8&65280)+((65280&g)<<8)+((255&g)<<24)}function InflateState(){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 f.Buf16(320),this.work=new f.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(g){var S;return g&&g.state?(S=g.state,g.total_in=g.total_out=S.total=0,g.msg="",S.wrap&&(g.adler=1&S.wrap),S.mode=x,S.last=0,S.havedict=0,S.dmax=32768,S.head=null,S.hold=0,S.bits=0,S.lencode=S.lendyn=new f.Buf32(Ce),S.distcode=S.distdyn=new f.Buf32(ye),S.sane=1,S.back=-1,M):D}function inflateReset(g){var f;return g&&g.state?((f=g.state).wsize=0,f.whave=0,f.wnext=0,inflateResetKeep(g)):D}function inflateReset2(g,f){var S,v;return g&&g.state?(v=g.state,f<0?(S=0,f=-f):(S=1+(f>>4),f<48&&(f&=15)),f&&(f<8||f>15)?D:(null!==v.window&&v.wbits!==f&&(v.window=null),v.wrap=S,v.wbits=f,inflateReset(g))):D}function inflateInit2(g,f){var S,v;return g?(v=new InflateState,g.state=v,v.window=null,(S=inflateReset2(g,f))!==M&&(g.state=null),S):D}function inflateInit(g){return inflateInit2(g,Ee)}var _e,Te,Ie=!0;function fixedtables(g){if(Ie){var S;for(_e=new f.Buf32(512),Te=new f.Buf32(32),S=0;S<144;)g.lens[S++]=8;for(;S<256;)g.lens[S++]=9;for(;S<280;)g.lens[S++]=7;for(;S<288;)g.lens[S++]=8;for(_(I,g.lens,0,288,_e,0,g.work,{bits:9}),S=0;S<32;)g.lens[S++]=5;_(b,g.lens,0,32,Te,0,g.work,{bits:5}),Ie=!1}g.lencode=_e,g.lenbits=9,g.distcode=Te,g.distbits=5}function updatewindow(g,S,v,C){var _,T=g.state;return null===T.window&&(T.wsize=1<<T.wbits,T.wnext=0,T.whave=0,T.window=new f.Buf8(T.wsize)),C>=T.wsize?(f.arraySet(T.window,S,v-T.wsize,T.wsize,0),T.wnext=0,T.whave=T.wsize):((_=T.wsize-T.wnext)>C&&(_=C),f.arraySet(T.window,S,v-C,_,T.wnext),(C-=_)?(f.arraySet(T.window,S,v-C,C,0),T.wnext=C,T.whave=T.wsize):(T.wnext+=_,T.wnext===T.wsize&&(T.wnext=0),T.whave<T.wsize&&(T.whave+=_))),0}function inflate3(g,se){var oe,le,pe,me,Ce,ye,Ee,_e,Te,Ie,be,Ae,Pe,Re,Me,we,Oe,De,Ne,ke,Le,Fe,xe,Ue,Ve=0,Be=new f.Buf8(4),He=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!g||!g.state||!g.output||!g.input&&0!==g.avail_in)return D;(oe=g.state).mode===K&&(oe.mode=J),Ce=g.next_out,pe=g.output,Ee=g.avail_out,me=g.next_in,le=g.input,ye=g.avail_in,_e=oe.hold,Te=oe.bits,Ie=ye,be=Ee,Fe=M;e:for(;;)switch(oe.mode){case x:if(0===oe.wrap){oe.mode=J;break}for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(2&oe.wrap&&35615===_e){oe.check=0,Be[0]=255&_e,Be[1]=_e>>>8&255,oe.check=v(oe.check,Be,2,0),_e=0,Te=0,oe.mode=U;break}if(oe.flags=0,oe.head&&(oe.head.done=!1),!(1&oe.wrap)||(((255&_e)<<8)+(_e>>8))%31){g.msg="incorrect header check",oe.mode=Se;break}if((15&_e)!==F){g.msg="unknown compression method",oe.mode=Se;break}if(Te-=4,Le=8+(15&(_e>>>=4)),0===oe.wbits)oe.wbits=Le;else if(Le>oe.wbits){g.msg="invalid window size",oe.mode=Se;break}oe.dmax=1<<Le,g.adler=oe.check=1,oe.mode=512&_e?W:K,_e=0,Te=0;break;case U:for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(oe.flags=_e,(255&oe.flags)!==F){g.msg="unknown compression method",oe.mode=Se;break}if(57344&oe.flags){g.msg="unknown header flags set",oe.mode=Se;break}oe.head&&(oe.head.text=_e>>8&1),512&oe.flags&&(Be[0]=255&_e,Be[1]=_e>>>8&255,oe.check=v(oe.check,Be,2,0)),_e=0,Te=0,oe.mode=V;case V:for(;Te<32;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.head&&(oe.head.time=_e),512&oe.flags&&(Be[0]=255&_e,Be[1]=_e>>>8&255,Be[2]=_e>>>16&255,Be[3]=_e>>>24&255,oe.check=v(oe.check,Be,4,0)),_e=0,Te=0,oe.mode=B;case B:for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.head&&(oe.head.xflags=255&_e,oe.head.os=_e>>8),512&oe.flags&&(Be[0]=255&_e,Be[1]=_e>>>8&255,oe.check=v(oe.check,Be,2,0)),_e=0,Te=0,oe.mode=H;case H:if(1024&oe.flags){for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.length=_e,oe.head&&(oe.head.extra_len=_e),512&oe.flags&&(Be[0]=255&_e,Be[1]=_e>>>8&255,oe.check=v(oe.check,Be,2,0)),_e=0,Te=0}else oe.head&&(oe.head.extra=null);oe.mode=$;case $:if(1024&oe.flags&&((Ae=oe.length)>ye&&(Ae=ye),Ae&&(oe.head&&(Le=oe.head.extra_len-oe.length,oe.head.extra||(oe.head.extra=new Array(oe.head.extra_len)),f.arraySet(oe.head.extra,le,me,Ae,Le)),512&oe.flags&&(oe.check=v(oe.check,le,Ae,me)),ye-=Ae,me+=Ae,oe.length-=Ae),oe.length))break e;oe.length=0,oe.mode=j;case j:if(2048&oe.flags){if(0===ye)break e;Ae=0;do{Le=le[me+Ae++],oe.head&&Le&&oe.length<65536&&(oe.head.name+=String.fromCharCode(Le))}while(Le&&Ae<ye);if(512&oe.flags&&(oe.check=v(oe.check,le,Ae,me)),ye-=Ae,me+=Ae,Le)break e}else oe.head&&(oe.head.name=null);oe.length=0,oe.mode=G;case G:if(4096&oe.flags){if(0===ye)break e;Ae=0;do{Le=le[me+Ae++],oe.head&&Le&&oe.length<65536&&(oe.head.comment+=String.fromCharCode(Le))}while(Le&&Ae<ye);if(512&oe.flags&&(oe.check=v(oe.check,le,Ae,me)),ye-=Ae,me+=Ae,Le)break e}else oe.head&&(oe.head.comment=null);oe.mode=q;case q:if(512&oe.flags){for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(_e!==(65535&oe.check)){g.msg="header crc mismatch",oe.mode=Se;break}_e=0,Te=0}oe.head&&(oe.head.hcrc=oe.flags>>9&1,oe.head.done=!0),g.adler=oe.check=0,oe.mode=K;break;case W:for(;Te<32;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}g.adler=oe.check=zswap32(_e),_e=0,Te=0,oe.mode=z;case z:if(0===oe.havedict)return g.next_out=Ce,g.avail_out=Ee,g.next_in=me,g.avail_in=ye,oe.hold=_e,oe.bits=Te,O;g.adler=oe.check=1,oe.mode=K;case K:if(se===P||se===R)break e;case J:if(oe.last){_e>>>=7&Te,Te-=7&Te,oe.mode=ue;break}for(;Te<3;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}switch(oe.last=1&_e,Te-=1,3&(_e>>>=1)){case 0:oe.mode=Y;break;case 1:if(fixedtables(oe),oe.mode=ie,se===R){_e>>>=2,Te-=2;break e}break;case 2:oe.mode=Z;break;case 3:g.msg="invalid block type",oe.mode=Se}_e>>>=2,Te-=2;break;case Y:for(_e>>>=7&Te,Te-=7&Te;Te<32;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if((65535&_e)!=(_e>>>16^65535)){g.msg="invalid stored block lengths",oe.mode=Se;break}if(oe.length=65535&_e,_e=0,Te=0,oe.mode=Q,se===R)break e;case Q:oe.mode=X;case X:if(Ae=oe.length){if(Ae>ye&&(Ae=ye),Ae>Ee&&(Ae=Ee),0===Ae)break e;f.arraySet(pe,le,me,Ae,Ce),ye-=Ae,me+=Ae,Ee-=Ae,Ce+=Ae,oe.length-=Ae;break}oe.mode=K;break;case Z:for(;Te<14;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(oe.nlen=257+(31&_e),_e>>>=5,Te-=5,oe.ndist=1+(31&_e),_e>>>=5,Te-=5,oe.ncode=4+(15&_e),_e>>>=4,Te-=4,oe.nlen>286||oe.ndist>30){g.msg="too many length or distance symbols",oe.mode=Se;break}oe.have=0,oe.mode=ee;case ee:for(;oe.have<oe.ncode;){for(;Te<3;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.lens[He[oe.have++]]=7&_e,_e>>>=3,Te-=3}for(;oe.have<19;)oe.lens[He[oe.have++]]=0;if(oe.lencode=oe.lendyn,oe.lenbits=7,xe={bits:oe.lenbits},Fe=_(T,oe.lens,0,19,oe.lencode,0,oe.work,xe),oe.lenbits=xe.bits,Fe){g.msg="invalid code lengths set",oe.mode=Se;break}oe.have=0,oe.mode=te;case te:for(;oe.have<oe.nlen+oe.ndist;){for(;we=(Ve=oe.lencode[_e&(1<<oe.lenbits)-1])>>>16&255,Oe=65535&Ve,!((Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(Oe<16)_e>>>=Me,Te-=Me,oe.lens[oe.have++]=Oe;else{if(16===Oe){for(Ue=Me+2;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(_e>>>=Me,Te-=Me,0===oe.have){g.msg="invalid bit length repeat",oe.mode=Se;break}Le=oe.lens[oe.have-1],Ae=3+(3&_e),_e>>>=2,Te-=2}else if(17===Oe){for(Ue=Me+3;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}Te-=Me,Le=0,Ae=3+(7&(_e>>>=Me)),_e>>>=3,Te-=3}else{for(Ue=Me+7;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}Te-=Me,Le=0,Ae=11+(127&(_e>>>=Me)),_e>>>=7,Te-=7}if(oe.have+Ae>oe.nlen+oe.ndist){g.msg="invalid bit length repeat",oe.mode=Se;break}for(;Ae--;)oe.lens[oe.have++]=Le}}if(oe.mode===Se)break;if(0===oe.lens[256]){g.msg="invalid code -- missing end-of-block",oe.mode=Se;break}if(oe.lenbits=9,xe={bits:oe.lenbits},Fe=_(I,oe.lens,0,oe.nlen,oe.lencode,0,oe.work,xe),oe.lenbits=xe.bits,Fe){g.msg="invalid literal/lengths set",oe.mode=Se;break}if(oe.distbits=6,oe.distcode=oe.distdyn,xe={bits:oe.distbits},Fe=_(b,oe.lens,oe.nlen,oe.ndist,oe.distcode,0,oe.work,xe),oe.distbits=xe.bits,Fe){g.msg="invalid distances set",oe.mode=Se;break}if(oe.mode=ie,se===R)break e;case ie:oe.mode=ne;case ne:if(ye>=6&&Ee>=258){g.next_out=Ce,g.avail_out=Ee,g.next_in=me,g.avail_in=ye,oe.hold=_e,oe.bits=Te,C(g,be),Ce=g.next_out,pe=g.output,Ee=g.avail_out,me=g.next_in,le=g.input,ye=g.avail_in,_e=oe.hold,Te=oe.bits,oe.mode===K&&(oe.back=-1);break}for(oe.back=0;we=(Ve=oe.lencode[_e&(1<<oe.lenbits)-1])>>>16&255,Oe=65535&Ve,!((Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(we&&0==(240&we)){for(De=Me,Ne=we,ke=Oe;we=(Ve=oe.lencode[ke+((_e&(1<<De+Ne)-1)>>De)])>>>16&255,Oe=65535&Ve,!(De+(Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}_e>>>=De,Te-=De,oe.back+=De}if(_e>>>=Me,Te-=Me,oe.back+=Me,oe.length=Oe,0===we){oe.mode=he;break}if(32&we){oe.back=-1,oe.mode=K;break}if(64&we){g.msg="invalid literal/length code",oe.mode=Se;break}oe.extra=15&we,oe.mode=re;case re:if(oe.extra){for(Ue=oe.extra;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.length+=_e&(1<<oe.extra)-1,_e>>>=oe.extra,Te-=oe.extra,oe.back+=oe.extra}oe.was=oe.length,oe.mode=ae;case ae:for(;we=(Ve=oe.distcode[_e&(1<<oe.distbits)-1])>>>16&255,Oe=65535&Ve,!((Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(0==(240&we)){for(De=Me,Ne=we,ke=Oe;we=(Ve=oe.distcode[ke+((_e&(1<<De+Ne)-1)>>De)])>>>16&255,Oe=65535&Ve,!(De+(Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}_e>>>=De,Te-=De,oe.back+=De}if(_e>>>=Me,Te-=Me,oe.back+=Me,64&we){g.msg="invalid distance code",oe.mode=Se;break}oe.offset=Oe,oe.extra=15&we,oe.mode=ce;case ce:if(oe.extra){for(Ue=oe.extra;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.offset+=_e&(1<<oe.extra)-1,_e>>>=oe.extra,Te-=oe.extra,oe.back+=oe.extra}if(oe.offset>oe.dmax){g.msg="invalid distance too far back",oe.mode=Se;break}oe.mode=de;case de:if(0===Ee)break e;if(Ae=be-Ee,oe.offset>Ae){if((Ae=oe.offset-Ae)>oe.whave&&oe.sane){g.msg="invalid distance too far back",oe.mode=Se;break}Ae>oe.wnext?(Ae-=oe.wnext,Pe=oe.wsize-Ae):Pe=oe.wnext-Ae,Ae>oe.length&&(Ae=oe.length),Re=oe.window}else Re=pe,Pe=Ce-oe.offset,Ae=oe.length;Ae>Ee&&(Ae=Ee),Ee-=Ae,oe.length-=Ae;do{pe[Ce++]=Re[Pe++]}while(--Ae);0===oe.length&&(oe.mode=ne);break;case he:if(0===Ee)break e;pe[Ce++]=oe.length,Ee--,oe.mode=ne;break;case ue:if(oe.wrap){for(;Te<32;){if(0===ye)break e;ye--,_e|=le[me++]<<Te,Te+=8}if(be-=Ee,g.total_out+=be,oe.total+=be,be&&(g.adler=oe.check=oe.flags?v(oe.check,pe,be,Ce-be):S(oe.check,pe,be,Ce-be)),be=Ee,(oe.flags?_e:zswap32(_e))!==oe.check){g.msg="incorrect data check",oe.mode=Se;break}_e=0,Te=0}oe.mode=ge;case ge:if(oe.wrap&&oe.flags){for(;Te<32;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(_e!==(4294967295&oe.total)){g.msg="incorrect length check",oe.mode=Se;break}_e=0,Te=0}oe.mode=fe;case fe:Fe=w;break e;case Se:Fe=N;break e;case ve:return k;default:return D}return g.next_out=Ce,g.avail_out=Ee,g.next_in=me,g.avail_in=ye,oe.hold=_e,oe.bits=Te,(oe.wsize||be!==g.avail_out&&oe.mode<Se&&(oe.mode<ue||se!==A))&&updatewindow(g,g.output,g.next_out,be-g.avail_out),Ie-=g.avail_in,be-=g.avail_out,g.total_in+=Ie,g.total_out+=be,oe.total+=be,oe.wrap&&be&&(g.adler=oe.check=oe.flags?v(oe.check,pe,be,g.next_out-be):S(oe.check,pe,be,g.next_out-be)),g.data_type=oe.bits+(oe.last?64:0)+(oe.mode===K?128:0)+(oe.mode===ie||oe.mode===Q?256:0),(0===Ie&&0===be||se===A)&&Fe===M&&(Fe=L),Fe}function inflateEnd(g){if(!g||!g.state)return D;var f=g.state;return f.window&&(f.window=null),g.state=null,M}function inflateGetHeader(g,f){var S;return g&&g.state?0==(2&(S=g.state).wrap)?D:(S.head=f,f.done=!1,M):D}function inflateSetDictionary(g,f){var v,C=f.length;return g&&g.state?0!==(v=g.state).wrap&&v.mode!==z?D:v.mode===z&&S(1,f,C,0)!==v.check?N:updatewindow(g,f,C,C)?(v.mode=ve,k):(v.havedict=1,M):D}g.inflateReset=inflateReset,g.inflateReset2=inflateReset2,g.inflateResetKeep=inflateResetKeep,g.inflateInit=inflateInit,g.inflateInit2=inflateInit2,g.inflate=inflate3,g.inflateEnd=inflateEnd,g.inflateGetHeader=inflateGetHeader,g.inflateSetDictionary=inflateSetDictionary,g.inflateInfo="pako inflate (from Nodeca project)"}}),Se=__commonJS({"../node_modules/pako/lib/zlib/constants.js"(g,f){f.exports={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_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}}}),ve=__commonJS({"../node_modules/pako/lib/zlib/gzheader.js"(g,f){function GZheader(){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}f.exports=GZheader}}),Ce=__commonJS({"../node_modules/pako/lib/inflate.js"(g){var f=fe(),S=se(),v=he(),C=Se(),_=ce(),T=ue(),I=ve(),b=Object.prototype.toString;function Inflate(g){if(!(this instanceof Inflate))return new Inflate(g);this.options=S.assign({chunkSize:16384,windowBits:0,to:""},g||{});var A=this.options;A.raw&&A.windowBits>=0&&A.windowBits<16&&(A.windowBits=-A.windowBits,0===A.windowBits&&(A.windowBits=-15)),!(A.windowBits>=0&&A.windowBits<16)||g&&g.windowBits||(A.windowBits+=32),A.windowBits>15&&A.windowBits<48&&0==(15&A.windowBits)&&(A.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new T,this.strm.avail_out=0;var P=f.inflateInit2(this.strm,A.windowBits);if(P!==C.Z_OK)throw new Error(_[P]);if(this.header=new I,f.inflateGetHeader(this.strm,this.header),A.dictionary&&("string"==typeof A.dictionary?A.dictionary=v.string2buf(A.dictionary):"[object ArrayBuffer]"===b.call(A.dictionary)&&(A.dictionary=new Uint8Array(A.dictionary)),A.raw&&(P=f.inflateSetDictionary(this.strm,A.dictionary))!==C.Z_OK))throw new Error(_[P])}function inflate3(g,f){var S=new Inflate(f);if(S.push(g,!0),S.err)throw S.msg||_[S.err];return S.result}function inflateRaw(g,f){return(f=f||{}).raw=!0,inflate3(g,f)}Inflate.prototype.push=function(g,_){var T,I,A,P,R,M=this.strm,w=this.options.chunkSize,O=this.options.dictionary,D=!1;if(this.ended)return!1;I=_===~~_?_:!0===_?C.Z_FINISH:C.Z_NO_FLUSH,"string"==typeof g?M.input=v.binstring2buf(g):"[object ArrayBuffer]"===b.call(g)?M.input=new Uint8Array(g):M.input=g,M.next_in=0,M.avail_in=M.input.length;do{if(0===M.avail_out&&(M.output=new S.Buf8(w),M.next_out=0,M.avail_out=w),(T=f.inflate(M,C.Z_NO_FLUSH))===C.Z_NEED_DICT&&O&&(T=f.inflateSetDictionary(this.strm,O)),T===C.Z_BUF_ERROR&&!0===D&&(T=C.Z_OK,D=!1),T!==C.Z_STREAM_END&&T!==C.Z_OK)return this.onEnd(T),this.ended=!0,!1;M.next_out&&(0!==M.avail_out&&T!==C.Z_STREAM_END&&(0!==M.avail_in||I!==C.Z_FINISH&&I!==C.Z_SYNC_FLUSH)||("string"===this.options.to?(A=v.utf8border(M.output,M.next_out),P=M.next_out-A,R=v.buf2string(M.output,A),M.next_out=P,M.avail_out=w-P,P&&S.arraySet(M.output,M.output,A,P,0),this.onData(R)):this.onData(S.shrinkBuf(M.output,M.next_out)))),0===M.avail_in&&0===M.avail_out&&(D=!0)}while((M.avail_in>0||0===M.avail_out)&&T!==C.Z_STREAM_END);return T===C.Z_STREAM_END&&(I=C.Z_FINISH),I===C.Z_FINISH?(T=f.inflateEnd(this.strm),this.onEnd(T),this.ended=!0,T===C.Z_OK):I!==C.Z_SYNC_FLUSH||(this.onEnd(C.Z_OK),M.avail_out=0,!0)},Inflate.prototype.onData=function(g){this.chunks.push(g)},Inflate.prototype.onEnd=function(g){g===C.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=S.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg},g.Inflate=Inflate,g.inflate=inflate3,g.inflateRaw=inflateRaw,g.ungzip=inflate3}}),ye=__commonJS({"../node_modules/pako/index.js"(g,f){var S={};(0,se().assign)(S,ge(),Ce(),Se()),f.exports=S}}),Ee=__commonJS({"../signaling-agent/node_modules/sdp-transform/lib/grammar.js"(g,f){var S=f.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\S*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(g){return g.encoding?"rtpmap:%d %s/%s/%s":g.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(g){return null!=g.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(g){return"rtcp-fb:"+("*"===g.payload?"%s":"%d")+" x-message %s"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%d trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(g){return null!=g.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(g){return"extmap:%d"+(g.direction?"/%s":"%v")+(g["encrypt-uri"]?" %s":"%v")+" %s"+(g.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"cryptoscale",reg:/^cryptoscale:(\d*) (client|server) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","flavor","suite","config","sessionConfig"],format:function(g){return null!=g.sessionConfig?"cryptoscale:%d %s %s %s %s":"cryptoscale:%d %s %s %s"}},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(g){return null!=g.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(g){var f="candidate:%s %d %s %d %s %d typ %s";return f+=null!=g.raddr?" raddr %s rport %d":"%v%v",f+=null!=g.tcptype?" tcptype %s":"%v",null!=g.generation&&(f+=" generation %d"),f+=null!=g["network-id"]?" network-id %d":"%v",f+=null!=g["network-cost"]?" network-cost %d":"%v"}},{push:"xCandidatesIpv6",reg:/^x-candidate-ipv6:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation"],format:function(g){var f="candidate:%s %d %s %d %s %d typ %s";return f+=null!=g.raddr?" raddr %s rport %d":"%v%v",f+=null!=g.tcptype?" tcptype %s":"%v",null!=g.generation&&(f+=" generation %d"),f}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(g){var f="ssrc:%d";return null!=g.attribute&&(f+=" %s",null!=g.value&&(f+=":%s")),f}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(g){return null!=g.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(g){return g.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(g){return"imageattr:%s %s %s"+(g.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(g){return"simulcast:%s %s"+(g.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(g){return"ts-refclk:%s"+(null!=g.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(g){var f="mediaclk:";return f+=null!=g.id?"id=%s %s":"%v%s",f+=null!=g.mediaClockValue?"=%s":"",f+=null!=g.rateNumerator?" rate=%s":"",f+=null!=g.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{name:"xMediaBw",reg:/^x-mediabw:(\S*) send=(\d*);recv=(\d*)/,names:["label","sendBw","receiveBw"],format:"x-mediabw:%s send=%d;recv=%d"},{name:"xSsrcRange",reg:/^x-ssrc-range:(\d*)-(\d*)/,names:["ssrcMin","ssrcMax"],format:"x-ssrc-range:%d-%d"},{name:"xSource",reg:/^x-source:(\S*)/,format:"x-source:%s"},{name:"xSourceStreamId",reg:/^x-source-streamid:(\S*)/,format:"x-source-streamid:%s"},{name:"xCaps",reg:/^x-caps:(\d*) (\S*)/,names:["payloadType","value"],format:"x-caps:%d %s"},{name:"signalingFbXMessage",reg:/^x-signaling-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(g){return"x-signaling-fb:"+("*"===g.payload?"%s":"%d")+" x-message %s"}},{push:"xMediaSettings",reg:/^x-mediasettings:([\S| ]*)/,names:["settings"],format:"x-mediasettings:%s"},{name:"xDataProtocol",reg:/^x-data-protocol:\s?(.*)/,format:"x-data-protocol:%s"},{push:"invalid",names:["value"]}]};Object.keys(S).forEach((function(g){S[g].forEach((function(g){g.reg||(g.reg=/(.*)/),g.format||(g.format="%s")}))}))}}),_e=__commonJS({"../signaling-agent/node_modules/sdp-transform/lib/parser.js"(g){var toIntIfInt=function(g){return String(Number(g))===g?Number(g):g},attachProperties=function(g,f,S,v){if(v&&!S)f[v]=toIntIfInt(g[1]);else for(var C=0;C<S.length;C+=1)null!=g[C+1]&&(f[S[C]]=toIntIfInt(g[C+1]))},parseReg=function(g,f,S){var v=g.name&&g.names;g.push&&!f[g.push]?f[g.push]=[]:v&&!f[g.name]&&(f[g.name]={});var C=g.push?{}:v?f[g.name]:f;attachProperties(S.match(g.reg),C,g.names,g.name),g.push&&f[g.push].push(C)},f=Ee(),S=RegExp.prototype.test.bind(/^([a-z])=(.*)/);g.parse=function(g){var v={},C=[],_=v;return g.split(/(\r\n|\r|\n)/).filter(S).forEach((function(g){var S=g[0],v=g.slice(2);"m"===S&&(C.push({rtp:[],fmtp:[]}),_=C[C.length-1]);for(var T=0;T<(f[S]||[]).length;T+=1){var I=f[S][T];if(I.reg.test(v))return parseReg(I,_,v)}})),v.media=C,v};var paramReducer=function(g,f){var S=f.split(/=(.+)/,2);return 2===S.length?g[S[0]]=toIntIfInt(S[1]):1===S.length&&f.length>1&&(g[S[0]]=void 0),g};g.parseParams=function(g){return g.split(/;\s?/).reduce(paramReducer,{})},g.parseFmtpConfig=g.parseParams,g.parsePayloads=function(g){return g.toString().split(" ").map(Number)},g.parseRemoteCandidates=function(g){for(var f=[],S=g.split(" ").map(toIntIfInt),v=0;v<S.length;v+=3)f.push({component:S[v],ip:S[v+1],port:S[v+2]});return f},g.parseImageAttributes=function(g){return g.split(" ").map((function(g){return g.substring(1,g.length-1).split(",").reduce(paramReducer,{})}))},g.parseSimulcastStreamList=function(g){return g.split(";").map((function(g){return g.split(",").map((function(g){var f,S=!1;return"~"!==g[0]?f=toIntIfInt(g):(f=toIntIfInt(g.substring(1,g.length)),S=!0),{scid:f,paused:S}}))}))}}}),Te=__commonJS({"../signaling-agent/node_modules/sdp-transform/lib/writer.js"(g,f){var S=Ee(),v=/%[sdv%]/g,format=function(g){var f=1,S=arguments,C=S.length;return g.replace(v,(function(g){if(f>=C)return g;var v=S[f];switch(f+=1,g){case"%%":return"%";case"%s":return String(v);case"%d":return Number(v);case"%v":return""}}))},makeLine=function(g,f,S){var v=[g+"="+(f.format instanceof Function?f.format(f.push?S:S[f.name]):f.format)];if(f.names)for(var C=0;C<f.names.length;C+=1){var _=f.names[C];f.name?v.push(S[f.name][_]):v.push(S[f.names[C]])}else v.push(S[f.name]);return format.apply(null,v)},C=["v","o","s","i","u","e","p","c","b","t","r","z","a"],_=["i","c","b","a"];f.exports=function(g,f){f=f||{},null==g.version&&(g.version=0),null==g.name&&(g.name=" "),g.media.forEach((function(g){null==g.payloads&&(g.payloads="")}));var v=f.outerOrder||C,T=f.innerOrder||_,I=[];return v.forEach((function(f){S[f].forEach((function(S){S.name in g&&null!=g[S.name]?I.push(makeLine(f,S,g)):S.push in g&&null!=g[S.push]&&g[S.push].forEach((function(g){I.push(makeLine(f,S,g))}))}))})),g.media.forEach((function(g){I.push(makeLine("m",S.m[0],g)),T.forEach((function(f){S[f].forEach((function(S){S.name in g&&null!=g[S.name]?I.push(makeLine(f,S,g)):S.push in g&&null!=g[S.push]&&g[S.push].forEach((function(g){I.push(makeLine(f,S,g))}))}))}))})),I.join("\r\n")+"\r\n"}}}),Ie=__commonJS({"../signaling-agent/node_modules/sdp-transform/lib/index.js"(g){var f=_e(),S=Te();g.write=S,g.parse=f.parse,g.parseParams=f.parseParams,g.parseFmtpConfig=f.parseFmtpConfig,g.parsePayloads=f.parsePayloads,g.parseRemoteCandidates=f.parseRemoteCandidates,g.parseImageAttributes=f.parseImageAttributes,g.parseSimulcastStreamList=f.parseSimulcastStreamList}}),be=__commonJS({"../skype-calling-utilities/dist/skype-calling-utilities.bundle.js"(g,f){var S,v;S=g,v=(g,f)=>{var S={},v={exports:S},C=Object.defineProperty,_=Object.getOwnPropertyDescriptor,T=Object.getOwnPropertyNames,I=Object.prototype.hasOwnProperty,__copyProps2=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let b of T(f))I.call(g,b)||b===S||C(g,b,{get:()=>f[b],enumerable:!(v=_(f,b))||v.enumerable});return g},__toCommonJS2=g=>__copyProps2(C({},"__esModule",{value:!0}),g),b={};((g,f)=>{for(var S in f)C(g,S,{get:f[S],enumerable:!0})})(b,{SlimCoreElectronControlCapturer:()=>H}),v.exports=__toCommonJS2(b);var A=M;function stringifyObject2(g){if(!g)return`${g}`;if(g instanceof Map)return mapToString2(g);const f=g.toString();return f.endsWith("[object Object]")?JSON.stringify(g):f}function mapToString2(g){const f={};return g.forEach(((g,S)=>{f[S.toString()]=g})),JSON.stringify(f)}var P,R=class{constructor(g){this.eventLogger=g,this.subscriptions=[]}subscribe(g){return new w(this.subscriptions,g)}dispose(g){this.subscriptions=[]}raiseEvents(g){this.subscriptions.slice().forEach((f=>{try{void 0!==f.eventHandler&&g(f.eventHandler)}catch(g){this.eventLogger?.warn?.("Event handler exception caught!",stringifyObject2(g))}}))}},w=class{constructor(g,f){this.subscriptions=g,this.eventHandler=f,this.subscriptions.push(this)}dispose(){(0,A.remove)(this.subscriptions,(g=>g===this)),this.eventHandler=void 0}},O=class extends R{constructor(g){super(g)}changed(g,f){return this.subscribe({changed:{skipEventConfig:f,handler:g},on:void 0})}on(g,f){return this.subscribe({changed:void 0,on:{name:String(g),handler:this._toEventCallback(f)}})}once(g,f,S){let v;const onceSubscription=(...g)=>{v.dispose(S),this._toEventCallback(f)(...g)};return v=this.on(g,this._fromEventCallback(onceSubscription)),v}raiseChanged(g){this.raiseEvents((f=>{if(!f.changed)return;const{skipEventConfig:S,handler:v}=f.changed;!this.getShouldSkipChangedEvent(g,S)&&v()}))}event(g){return{raise:this._fromEventCallback(((...f)=>this._raiseEventImpl(String(g),...f)))}}_raiseEventImpl(g,...f){this.raiseEvents((S=>S.on&&S.on.name===g&&S.on.handler(...f)))}_toEventCallback(g){return g}_fromEventCallback(g){return g}getShouldSkipChangedEvent(g,f){return g?.skipDominantSpeakerUpdatesOnCall?!!f?.skipDominantSpeakerUpdatesOnCall:!!g?.skipParticipantsUpdatesOnCall&&!!f?.skipParticipantsUpdatesOnCall}async onAsync(g,f){return this.on(g,f)}async onceAsync(g,f,S){return this.once(g,f,S)}async changedAsync(g,f){return this.changed(g,f)}async disposeAsync(g){this.dispose(g)}};(g=>{const f=7,S=3;function encodeMouseEvent(g){if(!g)return new Uint8Array(0);g.buttonType||(g.buttonType=0),g.xPos||(g.xPos=0),g.yPos||(g.yPos=0),g.wheelRotation||(g.wheelRotation=0);const S=new ArrayBuffer(f),v=new DataView(S),C=(3&g.type)<<0,_=(7&g.buttonType)<<2,T=(g.buttonDown?1:0)<<5,I=(g.wheelButtonDown?1:0)<<6,b=0;return v.setUint8(0,1),v.setUint8(1,C|_|T|I|b),v.setUint16(2,g.xPos,!0),v.setUint16(4,g.yPos,!0),v.setUint8(6,g.wheelRotation),new Uint8Array(S)}function encodeKeyboardEvent(g){const f=new ArrayBuffer(S),v=new DataView(f),C=(3&g.codeType)<<0,_=0,T=(g.keyUp?1:0)<<4,I=(g.repeat?1:0)<<5,b=0,A=0;return v.setUint8(0,0),v.setUint8(1,C|_|T|I|b|A),v.setUint8(2,g.code),new Uint8Array(f)}function decodeEventType(g){return g[0]}function decodeMouseEvent(g){if(1!==g[0]||g.length!==f)return null;const S=new DataView(g.buffer),v=S.getUint8(1);return{type:3&v,buttonType:v>>2&7,buttonDown:!!(v>>5&1),wheelButtonDown:!!(v>>6&1),xPos:S.getUint16(2,!0),yPos:S.getUint16(4,!0),wheelRotation:S.getUint8(6)}}function decodeKeyboardEvent(g){if(0!==g[0]||g.length!==S)return null;const f=new DataView(g.buffer),v=f.getUint8(1);return{codeType:3&v,code:f.getUint8(2),repeat:!!(v>>5&1),keyUp:!!(v>>4&1)}}g.encodeMouseEvent=encodeMouseEvent,g.encodeKeyboardEvent=encodeKeyboardEvent,g.decodeEventType=decodeEventType,g.decodeMouseEvent=decodeMouseEvent,g.decodeKeyboardEvent=decodeKeyboardEvent})(P||(P={}));var D=65535,N=3e3,k=250,L=18,F=17,x=16,U=91,V=50,B=30,H=class extends O{constructor(g,f,S=!0,v=1){super(),this._logger=g,this._element=f,this._captureRegionPreserveAspectRatio=S,this._mouseMoveCount=0,this._mouseMoveStartTime=0,this._isMouseDown=!1,this._isMouseOnRenderer=!1,this._captureMode=0,this._pollTimerID=0,this._resizeTimerID=0,this._mouseMoveThrottlingEnabled=!1,this._handleResizeEvents=()=>{clearTimeout(this._resizeTimerID),this._resizeTimerID=window.setTimeout((()=>{this.updateCaptureRegion()}),k)},this._handleMouseLeave=g=>{!this._isOnScreenContent(g)&&this._isMouseOnRenderer&&(this._raiseCaptureEvent(2),this._logger.info("Mouse leaving render region")),this._isMouseOnRenderer=!1},this._handleMouseEnter=g=>{this._isOnScreenContent(g)&&(this._isMouseOnRenderer=!0,this._raiseCaptureEvent(1),this._logger.info("Mouse entering render region"))},this._handleLosingFocus=()=>{this._syncKeyStates(!0)},this._handleClick=g=>{this._isOnScreenContent(g)&&(this._raiseCaptureEvent(0),this._logger.info("Mouse clicked"))},this._handleMouseMove=g=>{if(!this._isOnScreenContent(g)&&this._isMouseOnRenderer)return this._raiseCaptureEvent(2),this._isMouseOnRenderer=!1,void this._logger.info("Mouse leaving render region");if(this._isOnScreenContent(g)&&!this._isMouseOnRenderer&&(this._raiseCaptureEvent(1),this._isMouseOnRenderer=!0,this._logger.info("Mouse entering render region")),2!==this._captureMode&&3!==this._captureMode)return;if(this._mouseMoveCount++,this._mouseMoveThrottlingEnabled){if(!this._isOnScreenContent(g)||!this._shouldMoveMouse())return}else if(!this._isOnScreenContent(g)||this._mouseMoveCount%2==0)return;const f={type:0};this._normalizeMousePosition(g,f),this._raiseMouseEvent(f)},this._handleMouseDown=g=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(g))return;const f={type:2,buttonType:convertButton(g.button),buttonDown:!0};this._isMouseDown=!0,this._normalizeMousePosition(g,f),this._raiseMouseEvent(f)},this._handleMouseUp=g=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(g))return;const f={type:2,buttonType:convertButton(g.button),buttonDown:!1};this._isMouseDown=!1,this._normalizeMousePosition(g,f),this._raiseMouseEvent(f)},this._handleKeyDown=g=>{this._raiseKeyboardEvent({codeType:1,code:g.keyCode,repeat:g.repeat,keyUp:!1}),g.stopPropagation(),g.preventDefault()},this._handleKeyUp=g=>{this._raiseKeyboardEvent({codeType:1,code:g.keyCode,repeat:g.repeat,keyUp:!0}),g.stopPropagation(),g.preventDefault()},this._handleWheel=g=>{this._raiseMouseEvent({type:1,wheelRotation:g.deltaY>0?-120:120})},this._handleContextMenu=g=>{g.preventDefault()},this._ensureCanReceiveKeyboardInput(),this._element.ownerDocument?.defaultView?.addEventListener("resize",this._handleResizeEvents,!1),this._captureRegion={left:0,top:0,width:this._element.clientWidth,height:this._element.clientHeight},this._videoSize={width:Math.floor(f.clientHeight*v),height:f.clientHeight},this._origElementSize={width:0,height:0},this._checkElementSize(),this._mouseMoveStartTime=new Date(0).getTime()}get captureMode(){return this._captureMode}get captureRegion(){return this._captureRegion}setMouseMoveThrottlingFeatureFlag(g){this._mouseMoveThrottlingEnabled=g}dispose(g){this._logger.info(`dispose causeId: ${g}`),window.clearTimeout(this._pollTimerID),this._element.ownerDocument?.defaultView?.removeEventListener("resize",this._handleResizeEvents,!1),super.dispose(g)}updateVideoSize(g,f){this._videoSize.width=g,this._videoSize.height=f,this.updateCaptureRegion()}updateCaptureRegion(){this._captureRegionPreserveAspectRatio?(this._captureRegion.width=this._element.clientWidth,this._captureRegion.height=this._element.clientWidth*this._videoSize.height/this._videoSize.width,this._captureRegion.height>this._element.clientHeight?(this._captureRegion.width=this._element.clientHeight*this._videoSize.width/this._videoSize.height,this._captureRegion.height=this._element.clientHeight,this._captureRegion.left=(this._element.clientWidth-this._captureRegion.width)/2,this._captureRegion.top=0):(this._captureRegion.left=0,this._captureRegion.top=(this._element.clientHeight-this._captureRegion.height)/2)):(this._captureRegion.width=this._element.clientWidth,this._captureRegion.height=this._element.clientHeight,this._captureRegion.top=0,this._captureRegion.left=0)}setCaptureMode(g){3===this._captureMode&&3!==g&&this._syncKeyStates(!0),this._captureMode=g,0!==g?("none"===this._element.style.pointerEvents&&this._logger.warn("Element pointer-events is 'none', event handlers will not work"),this._element.addEventListener("click",this._handleClick),this._element.addEventListener("pointermove",this._handleMouseMove),this._element.addEventListener("pointerdown",this._handleMouseDown),this._element.addEventListener("pointerup",this._handleMouseUp),this._element.addEventListener("pointerenter",this._handleMouseEnter),this._element.addEventListener("pointerleave",this._handleMouseLeave),3===g?(this._element.addEventListener("wheel",this._handleWheel),this._element.addEventListener("keydown",this._handleKeyDown),this._element.addEventListener("keyup",this._handleKeyUp),this._element.addEventListener("contextmenu",this._handleContextMenu),this._element.addEventListener("blur",this._handleLosingFocus)):(this._element.removeEventListener("wheel",this._handleWheel),this._element.removeEventListener("keydown",this._handleKeyDown),this._element.removeEventListener("keyup",this._handleKeyUp),this._element.removeEventListener("contextmenu",this._handleContextMenu),this._element.removeEventListener("blur",this._handleLosingFocus))):(this._element.removeEventListener("pointermove",this._handleMouseMove),this._element.removeEventListener("pointerdown",this._handleMouseDown),this._element.removeEventListener("pointerup",this._handleMouseUp),this._element.removeEventListener("pointerenter",this._handleMouseEnter),this._element.removeEventListener("pointerleave",this._handleMouseLeave),this._element.removeEventListener("click",this._handleClick),this._element.removeEventListener("wheel",this._handleWheel),this._element.removeEventListener("keydown",this._handleKeyDown),this._element.removeEventListener("keyup",this._handleKeyUp),this._element.removeEventListener("contextmenu",this._handleContextMenu),this._element.removeEventListener("blur",this._handleLosingFocus))}_ensureCanReceiveKeyboardInput(){this._element.tabIndex=this._element.tabIndex}_checkElementSize(){this._origElementSize.width===this._element.clientWidth&&this._origElementSize.height===this._element.clientHeight||(this.updateCaptureRegion(),this._origElementSize.width=this._element.clientWidth,this._origElementSize.height=this._element.clientHeight),this._pollTimerID=window.setTimeout((()=>{this._checkElementSize()}),N)}_raiseMouseEvent(g){this.event("mouseControlEvent").raise(g)}_raiseKeyboardEvent(g){this.event("keyboardControlEvent").raise(g)}_raiseCaptureEvent(g){this.event("ctrlCaptureEvent").raise(g)}_normalizeMousePosition(g,f){f.xPos=(g.offsetX-this._captureRegion.left)/this._captureRegion.width*D,f.yPos=(g.offsetY-this._captureRegion.top)/this._captureRegion.height*D}_isOnScreenContent(g){const f=this._captureRegion.left,S=this._captureRegion.left+this._captureRegion.width,v=this._captureRegion.top,C=this._captureRegion.top+this._captureRegion.height;return f<=g.offsetX&&g.offsetX<S&&v<=g.offsetY&&g.offsetY<C}_shouldMoveMouse(){if(this._mouseMoveStartTime){const g=(new Date).getTime(),f=g-this._mouseMoveStartTime;if(this._isMouseDown&&f>=B||!this._isMouseDown&&f>=V)return this._mouseMoveStartTime=g,!0}else this._mouseMoveStartTime=(new Date).getTime();return!1}_syncKeyStates(g){this._raiseKeyboardEvent({codeType:1,code:F,repeat:!1,keyUp:g}),this._raiseKeyboardEvent({codeType:1,code:x,repeat:!1,keyUp:g}),this._raiseKeyboardEvent({codeType:1,code:L,repeat:!1,keyUp:g}),this._raiseKeyboardEvent({codeType:1,code:U,repeat:!1,keyUp:g}),this._logger.info("Synced Key states.")}static formatMouseEvent(g){return P.encodeMouseEvent(g)}static formatKeyboardEvent(g){return P.encodeKeyboardEvent(g)}};function convertButton(g){switch(g){case 0:return 0;case 2:return 1;case 1:return 2;default:return}}if("object"==typeof v.exports&&"object"==typeof S){var __cp=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let C of Object.getOwnPropertyNames(f))Object.prototype.hasOwnProperty.call(g,C)||C===S||Object.defineProperty(g,C,{get:()=>f[C],enumerable:!(v=Object.getOwnPropertyDescriptor(f,C))||v.enumerable});return g};v.exports=__cp(v.exports,S)}return v.exports},"object"==typeof g&&"object"==typeof f?f.exports=v(R,M):"object"==typeof g?g["skype-calling-utilities"]=v(R,M):S["skype-calling-utilities"]=v(S["@skype/rt-js-bindings"],S.lodash)}}),Ae=__commonJS({"../node_modules/synctasks/dist/SyncTasks.js"(g){function fromThenable(g){var f=Defer();return g.then((function(g){f.resolve(g)}),(function(g){f.reject(g)})),f.promise().thenAsync((function(g){return g}))}function isThenable(g){return null!=g&&"function"==typeof g.then}function isCancelable(g){return null!=g&&"function"==typeof g.cancel}function run(f,S){if(!g.config.catchExceptions)return f();try{return f()}catch(g){return S(g)}}Object.defineProperty(g,"__esModule",{value:!0}),g.config={exceptionsToConsole:!0,catchExceptions:!0,traceEnabled:!1,exceptionHandler:void 0,unhandledErrorHandler:function(g){throw g}},g.fromThenable=fromThenable;var f,S,v,C=[],_="undefined"!=typeof setImmediate;function asyncCallback(g){C.push(g),1===C.length&&(_?setImmediate(resolveAsyncCallbacks):setTimeout(resolveAsyncCallbacks,0))}function resolveAsyncCallbacks(){var g=C;C=[];for(var f=0;f<g.length;f++)g[f]()}function all(g){if(0===g.length)return Resolved2([]);var S,v=Defer(),C=g.length,_=Array(g.length);v.onCancel((function(S){g.forEach((function(g){isCancelable(g)&&f.SyncTask.cancelOtherInternal(g,S)}))}));var checkFinish=function(){0==--C&&(void 0!==S?v.reject(S):v.resolve(_))};return g.forEach((function(g,f){isThenable(g)?g.then((function(g){_[f]=g,checkFinish()}),(function(g){void 0===S&&(S=void 0===g||g),checkFinish()})):(_[f]=g,checkFinish())})),v.promise()}function Defer(){return new f.SyncTask}function Resolved2(g){return(new f.SyncTask).resolve(g).promise()}function Rejected(g){return(new f.SyncTask).reject(g).promise()}function race(g){var S=Defer(),v=!1;return S.onCancel((function(S){g.forEach((function(g){isCancelable(g)&&f.SyncTask.cancelOtherInternal(g,S)}))})),g.forEach((function(g){isThenable(g)?g.then((function(g){v||(v=!0,S.resolve(g))}),(function(g){v||(v=!0,S.reject(g))})):v||(v=!0,S.resolve(g))})),S.promise()}function raceTimer(g,f){var S=Defer(),v=setTimeout((function(){S.resolve({timedOut:!0})}),f);return race([g.then((function(g){return clearTimeout(v),{timedOut:!1,result:g}})),S.promise()])}g.asyncCallback=asyncCallback,S=f||(f={}),v=function(){function SyncTask2(){this._completedSuccess=!1,this._completedFail=!1,this._traceEnabled=!1,this._cancelCallbacks=[],this._wasCanceled=!1,this._wasExplicitlyCanceled=!1,this._resolving=!1,this._storedCallbackSets=[],this._mustHandleError=!0}return SyncTask2.prototype._addCallbackSet=function(g,f){var S=this,v=new SyncTask2;return v.onCancel((function(f){g.wasCanceled=!0,g.cancelContext=f,S._cancelInternal(f)})),g.task=v,this._storedCallbackSets.push(g),f?this._mustHandleError=!1:v._mustHandleError=!1,this._resolving||(this._completedSuccess?this._resolveSuccesses():this._completedFail&&this._resolveFailures()),v.promise()},SyncTask2.prototype.onCancel=function(g){return this._completedSuccess||this._completedFail||(this._wasCanceled?g(this._cancelContext):this._cancelCallbacks.push(g)),this},SyncTask2.prototype.then=function(g,f){return this._addCallbackSet({successFunc:g,failFunc:f},!0)},SyncTask2.prototype.thenAsync=function(g,f){return this._addCallbackSet({successFunc:g,failFunc:f,asyncCallback:!0},!0)},SyncTask2.prototype.catch=function(g){return this._addCallbackSet({failFunc:g},!0)},SyncTask2.prototype.always=function(g){return this._addCallbackSet({successFunc:g,failFunc:g},!0)},SyncTask2.prototype.setTracingEnabled=function(g){return this._traceEnabled=g,this},SyncTask2.prototype.finally=function(g){return this._addCallbackSet({successFunc:g,failFunc:g},!1),this},SyncTask2.prototype.done=function(g){return this._addCallbackSet({successFunc:g},!1),this},SyncTask2.prototype.fail=function(g){return this._addCallbackSet({failFunc:g},!1),this},SyncTask2.prototype.resolve=function(g){return this._checkState(!0),this._completedSuccess=!0,this._storedResolution=g,this._cancelCallbacks=[],this._resolveSuccesses(),this},SyncTask2.prototype.reject=function(g){return this._checkState(!1),this._completedFail=!0,this._storedErrResolution=g,this._cancelCallbacks=[],this._resolveFailures(),SyncTask2._enforceErrorHandled(this),this},SyncTask2.prototype._checkState=function(f){if(this._completedSuccess||this._completedFail){this._completeStack&&console.error(this._completeStack.message,this._completeStack.stack);var S="Failed to "+(f?"resolve":"reject")+": the task is already "+(this._completedSuccess?"resolved":"rejected");throw new Error(S)}(g.config.traceEnabled||this._traceEnabled)&&(this._completeStack=new Error("resolve"))},SyncTask2._enforceErrorHandled=function(f){f._mustHandleError&&(SyncTask2._rejectedTasks.push(f),SyncTask2._enforceErrorHandledTimer||(SyncTask2._enforceErrorHandledTimer=setTimeout((function(){SyncTask2._enforceErrorHandledTimer=void 0;var f=SyncTask2._rejectedTasks;SyncTask2._rejectedTasks=[],f.forEach((function(f,S){f._mustHandleError&&g.config.unhandledErrorHandler(f._storedErrResolution)}))}),0)))},SyncTask2.prototype.cancel=function(g){if(this._wasExplicitlyCanceled)throw new Error("Already Canceled");this._wasExplicitlyCanceled=!0,this._cancelInternal(g)},SyncTask2.prototype._cancelInternal=function(g){var f=this;if(!this._wasCanceled){this._wasCanceled=!0,this._cancelContext=g;var S=this._cancelCallbacks;this._cancelCallbacks=[],S.length>0&&S.forEach((function(g){f._completedSuccess||f._completedFail||g(f._cancelContext)}))}},SyncTask2.cancelOtherInternal=function(g,f){var S=g;S._storedCallbackSets&&S._cancelInternal?S._cancelInternal(f):g.cancel(f)},SyncTask2.prototype.promise=function(){return this},SyncTask2.prototype._resolveSuccesses=function(){var g=this;for(this._resolving=!0;this._storedCallbackSets.length;){var f=this._storedCallbackSets;this._storedCallbackSets=[],f.forEach((function(f){f.asyncCallback?asyncCallback((function(){return g._resolveSuccessCallback(f)})):g._resolveSuccessCallback(f)}))}this._resolving=!1},SyncTask2.prototype._resolveSuccessCallback=function(g){var f=this;g.successFunc?run((function(){var S=g.successFunc(f._storedResolution);isCancelable(S)&&(g.wasCanceled?SyncTask2.cancelOtherInternal(S,g.cancelContext):g.task.onCancel((function(g){return SyncTask2.cancelOtherInternal(S,g)}))),isThenable(S)?S.then((function(f){g.task.resolve(f)}),(function(f){g.task.reject(f)})):g.task.resolve(S)}),(function(S){f._handleException(S,"SyncTask caught exception in success block: "+S.toString()),g.task.reject(S)})):g.task.resolve(this._storedResolution)},SyncTask2.prototype._resolveFailures=function(){var g=this;for(this._resolving=!0;this._storedCallbackSets.length;){var f=this._storedCallbackSets;this._storedCallbackSets=[],f.forEach((function(f){f.asyncCallback?asyncCallback((function(){return g._resolveFailureCallback(f)})):g._resolveFailureCallback(f)}))}this._resolving=!1},SyncTask2.prototype._resolveFailureCallback=function(g){var f=this;g.failFunc?run((function(){var S=g.failFunc(f._storedErrResolution);isCancelable(S)&&(g.wasCanceled?SyncTask2.cancelOtherInternal(S,g.cancelContext):g.task.onCancel((function(g){return SyncTask2.cancelOtherInternal(S,g)}))),isThenable(S)?S.then((function(f){g.task.resolve(f)}),(function(f){g.task.reject(f)})):g.task.resolve(S)}),(function(S){f._handleException(S,"SyncTask caught exception in failure block: "+S.toString()),g.task.reject(S)})):g.task.reject(this._storedErrResolution)},SyncTask2.prototype._handleException=function(f,S){g.config.exceptionsToConsole&&console.error(S),g.config.exceptionHandler&&g.config.exceptionHandler(f)},SyncTask2.prototype.toEs6Promise=function(){var g=this;return new Promise((function(f,S){return g.then(f,S)}))},SyncTask2._rejectedTasks=[],SyncTask2}(),S.SyncTask=v,g.all=all,g.Defer=Defer,g.Resolved=Resolved2,g.Rejected=Rejected,g.race=race,g.raceTimer=raceTimer}}),Pe=__commonJS({"../node_modules/sdp-transform/lib/grammar.js"(g,f){var S=f.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\S*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(g){return g.encoding?"rtpmap:%d %s/%s/%s":g.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(g){return null!=g.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(g){return"rtcp-fb:"+("*"===g.payload?"%s":"%d")+" x-message %s"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%d trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(g){return null!=g.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(g){return"extmap:%d"+(g.direction?"/%s":"%v")+(g["encrypt-uri"]?" %s":"%v")+" %s"+(g.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"cryptoscale",reg:/^cryptoscale:(\d*) (client|server) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","flavor","suite","config","sessionConfig"],format:function(g){return null!=g.sessionConfig?"cryptoscale:%d %s %s %s %s":"cryptoscale:%d %s %s %s"}},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(g){return null!=g.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(g){var f="candidate:%s %d %s %d %s %d typ %s";return f+=null!=g.raddr?" raddr %s rport %d":"%v%v",f+=null!=g.tcptype?" tcptype %s":"%v",null!=g.generation&&(f+=" generation %d"),f+=null!=g["network-id"]?" network-id %d":"%v",f+=null!=g["network-cost"]?" network-cost %d":"%v"}},{push:"xCandidatesIpv6",reg:/^x-candidate-ipv6:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation"],format:function(g){var f="candidate:%s %d %s %d %s %d typ %s";return f+=null!=g.raddr?" raddr %s rport %d":"%v%v",f+=null!=g.tcptype?" tcptype %s":"%v",null!=g.generation&&(f+=" generation %d"),f}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(g){var f="ssrc:%d";return null!=g.attribute&&(f+=" %s",null!=g.value&&(f+=":%s")),f}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(g){return null!=g.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(g){return g.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(g){return"imageattr:%s %s %s"+(g.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(g){return"simulcast:%s %s"+(g.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(g){return"ts-refclk:%s"+(null!=g.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(g){var f="mediaclk:";return f+=null!=g.id?"id=%s %s":"%v%s",f+=null!=g.mediaClockValue?"=%s":"",f+=null!=g.rateNumerator?" rate=%s":"",f+=null!=g.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{name:"xMediaBw",reg:/^x-mediabw:(\S*) send=(\d*);recv=(\d*)/,names:["label","sendBw","receiveBw"],format:"x-mediabw:%s send=%d;recv=%d"},{name:"xSsrcRange",reg:/^x-ssrc-range:(\d*)-(\d*)/,names:["ssrcMin","ssrcMax"],format:"x-ssrc-range:%d-%d"},{name:"xSource",reg:/^x-source:(\S*)/,format:"x-source:%s"},{name:"xSourceStreamId",reg:/^x-source-streamid:(\S*)/,format:"x-source-streamid:%s"},{name:"xCaps",reg:/^x-caps:(\d*) (\S*)/,names:["payloadType","value"],format:"x-caps:%d %s"},{name:"signalingFbXMessage",reg:/^x-signaling-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(g){return"x-signaling-fb:"+("*"===g.payload?"%s":"%d")+" x-message %s"}},{push:"xMediaSettings",reg:/^x-mediasettings:([\S| ]*)/,names:["settings"],format:"x-mediasettings:%s"},{name:"xDataProtocol",reg:/^x-data-protocol:\s?(.*)/,format:"x-data-protocol:%s"},{name:"xMultiStream",reg:/^x-multi-stream:(\d*) (\d*) (\d*) (\d*)/,names:["numberOfStreams","startSsrc","ssrcRange","ssrcGroupRange"],format:"x-multi-stream:%d %d %d %d"},{push:"invalid",names:["value"]}]};Object.keys(S).forEach((function(g){S[g].forEach((function(g){g.reg||(g.reg=/(.*)/),g.format||(g.format="%s")}))}))}}),Re=__commonJS({"../node_modules/sdp-transform/lib/parser.js"(g){var toIntIfInt=function(g){return String(Number(g))===g?Number(g):g},attachProperties=function(g,f,S,v){if(v&&!S)f[v]=toIntIfInt(g[1]);else for(var C=0;C<S.length;C+=1)null!=g[C+1]&&(f[S[C]]=toIntIfInt(g[C+1]))},parseReg=function(g,f,S){var v=g.name&&g.names;g.push&&!f[g.push]?f[g.push]=[]:v&&!f[g.name]&&(f[g.name]={});var C=g.push?{}:v?f[g.name]:f;attachProperties(S.match(g.reg),C,g.names,g.name),g.push&&f[g.push].push(C)},f=Pe(),S=RegExp.prototype.test.bind(/^([a-z])=(.*)/);g.parse=function(g){var v={},C=[],_=v;return g.split(/(\r\n|\r|\n)/).filter(S).forEach((function(g){var S=g[0],v=g.slice(2);"m"===S&&(C.push({rtp:[],fmtp:[]}),_=C[C.length-1]);for(var T=0;T<(f[S]||[]).length;T+=1){var I=f[S][T];if(I.reg.test(v))return parseReg(I,_,v)}})),v.media=C,v};var paramReducer=function(g,f){var S=f.split(/=(.+)/,2);return 2===S.length?g[S[0]]=toIntIfInt(S[1]):1===S.length&&f.length>1&&(g[S[0]]=void 0),g};g.parseParams=function(g){return g.split(/;\s?/).reduce(paramReducer,{})},g.parseFmtpConfig=g.parseParams,g.parsePayloads=function(g){return g.toString().split(" ").map(Number)},g.parseRemoteCandidates=function(g){for(var f=[],S=g.split(" ").map(toIntIfInt),v=0;v<S.length;v+=3)f.push({component:S[v],ip:S[v+1],port:S[v+2]});return f},g.parseImageAttributes=function(g){return g.split(" ").map((function(g){return g.substring(1,g.length-1).split(",").reduce(paramReducer,{})}))},g.parseSimulcastStreamList=function(g){return g.split(";").map((function(g){return g.split(",").map((function(g){var f,S=!1;return"~"!==g[0]?f=toIntIfInt(g):(f=toIntIfInt(g.substring(1,g.length)),S=!0),{scid:f,paused:S}}))}))}}}),Me=__commonJS({"../node_modules/sdp-transform/lib/writer.js"(g,f){var S=Pe(),v=/%[sdv%]/g,format=function(g){var f=1,S=arguments,C=S.length;return g.replace(v,(function(g){if(f>=C)return g;var v=S[f];switch(f+=1,g){case"%%":return"%";case"%s":return String(v);case"%d":return Number(v);case"%v":return""}}))},makeLine=function(g,f,S){var v=[g+"="+(f.format instanceof Function?f.format(f.push?S:S[f.name]):f.format)];if(f.names)for(var C=0;C<f.names.length;C+=1){var _=f.names[C];f.name?v.push(S[f.name][_]):v.push(S[f.names[C]])}else v.push(S[f.name]);return format.apply(null,v)},C=["v","o","s","i","u","e","p","c","b","t","r","z","a"],_=["i","c","b","a"];f.exports=function(g,f){f=f||{},null==g.version&&(g.version=0),null==g.name&&(g.name=" "),g.media.forEach((function(g){null==g.payloads&&(g.payloads="")}));var v=f.outerOrder||C,T=f.innerOrder||_,I=[];return v.forEach((function(f){S[f].forEach((function(S){S.name in g&&null!=g[S.name]?I.push(makeLine(f,S,g)):S.push in g&&null!=g[S.push]&&g[S.push].forEach((function(g){I.push(makeLine(f,S,g))}))}))})),g.media.forEach((function(g){I.push(makeLine("m",S.m[0],g)),T.forEach((function(f){S[f].forEach((function(S){S.name in g&&null!=g[S.name]?I.push(makeLine(f,S,g)):S.push in g&&null!=g[S.push]&&g[S.push].forEach((function(g){I.push(makeLine(f,S,g))}))}))}))})),I.join("\r\n")+"\r\n"}}}),we=__commonJS({"../node_modules/sdp-transform/lib/index.js"(g){var f=Re(),S=Me();g.write=S,g.parse=f.parse,g.parseParams=f.parseParams,g.parseFmtpConfig=f.parseFmtpConfig,g.parsePayloads=f.parsePayloads,g.parseRemoteCandidates=f.parseRemoteCandidates,g.parseImageAttributes=f.parseImageAttributes,g.parseSimulcastStreamList=f.parseSimulcastStreamList}}),Oe={};__export(Oe,{HttpRequestDispatcherImplementation:()=>$e,generateCauseId:()=>generateCauseId,getOvb:()=>getOvb,getVersion:()=>getTsCallingVersion,pluginlessStackFactory:()=>gw,whiteList:()=>pw}),C.exports=__toCommonJS(Oe);var De=__toESM(ie()),Ne=8;function generateCauseId(){const g="abcdef0123456789",f=g.length;let S="";for(let v=0;v<Ne;v++)S+=g.charAt(Math.floor(Math.random()*f));return S}function validateCauseId(g){return new RegExp("^[a-f0-9]{8}$").test(g)&&g.length===Ne}var ke=R,Le=M,Fe=class _TsCallingLogger{constructor(g,f,S=""){this.ulLogComponent=g,this.ulSafeComponent=f,this._getPrefix=(0,Le.isFunction)(S)?S:()=>S,this.logComponent=ke.LogFactory.instance().component(this.ulLogComponent),ke.LogFactory.instance().declareComponentSafe(this.ulLogComponent,f)}createChild(g){const f=(0,Le.isFunction)(g)?g:()=>g;return new _TsCallingLogger(this.ulLogComponent,this.ulSafeComponent,(()=>this._getPrefix()?`${this._getPrefix()}/${f()}`:f()))}log(...g){this._apply((g=>this.logComponent.debug2(null,g)),g)}debug(...g){this._apply((g=>this.logComponent.debug4(null,g)),g)}info(...g){this._apply((g=>this.logComponent.debug1(null,g)),g)}warn(...g){this._apply((g=>this.logComponent.warn(null,g)),g)}error(...g){this._apply((g=>this.logComponent.error(null,g)),g)}_apply(g,f=[]){this._addPrefix(f);g(f.map((g=>g instanceof DOMException?g.toString():g)).map((g=>(0,Le.isObject)(g)?JSON.stringify(g):g)).join(", "))}_addPrefix(g){if(g&&g[0]){const f=`${this._getPrefix()} ${g[0]}`;g[0]=f}}},xe=R,Ue=class{constructor(g,f){this.value=g,this.piiKind=f}},Ve=["id"," orgid","username","phonenumber"];function scrubMriOrOmit(g){return"string"==typeof g?xe.pii.Mri(g):xe.pii.Omit(g)}function scrubMriOrOmitList(g){try{return g.map(scrubMriOrOmit)}catch(g){return[]}}function scrubObjectFields(g,f=["id"],S={threadId:8}){if(!g||"object"!=typeof g)return g;try{let v=createDeepCopy(g);return v=scrubObjectData(v,f,S),v}catch(g){return{error:"failed to scrub object fields"}}}function scrubMriKeys(g){try{const f={};return Object.keys(g).forEach((S=>{const v=scrubMriOrOmit(S);f[v]=g[S]})),f}catch(g){return{error:"failed to scrub mri keys"}}}function getLoggableMriKeys(g){return JSON.stringify(scrubMriKeys(g))}function mriOrId(g){return g&&xe.pii.Mri(g)}function getLoggableThreadId(g){const f=_scrubThreadId(g);return f&&f.substr(0,8)}function _scrubThreadId(g){const f="99:";return g&&g.substr(0,3)===f?xe.pii.Omit(g):g}function createDeepCopy(g){if(!g||"object"!=typeof g)return g;const f=new Set,S=JSON.stringify(g,((g,S)=>{if("object"==typeof S&&null!==S){if(f.has(S))return;f.add(S)}return S}));return JSON.parse(S)}function scrubObjectData(g,f,S){if(!g||"object"!=typeof g)return g;const v={...g};for(const[C,_]of Object.entries(g))Array.isArray(_)?v[C]=_.map((g=>scrubObjectData(g,f,S))):"object"==typeof _?v[C]=scrubObjectData(_,f,S):"displayname"===C.toLowerCase()?v[C]="(redacted)":_&&(f.includes(C)||Ve.includes(C.toLowerCase())?v[C]=scrubMriOrOmit(_):S[C]&&"string"==typeof _&&(v[C]=_.toString().substring(0,S[C])));return v}function getMaskingRegex(g){const f=String.raw`[\\]*['|\"]?\s*[\:|=]\s*[\\]*['|\"]?`,S=String.raw`[a-zA-Z\d#.~?!@$%^&*-_()+]+?`;return new RegExp(String.raw`(${g}${f})(${S})(\\?['\"])`,"g")}function replacement(g,f,S,v,C){const _=scrubMriOrOmit(v);return String.raw`${f}${_}${C}`}function maskUserIdentity(g){if(!g)return null;const f=getMaskingRegex("([U|u]ser[N|n]ame|[O|o]rg[I|i]d)");return g.replace(f,replacement)}function maskSensitiveData(g,f="(redacted)"){if(!g)return null;const S=getMaskingRegex("([P|p]assword|[T|t]oken|[S|s]ecret|[A|a]uthorization|[D|d]isplay[N|n]ame|[P|p]honeNumber|[A|a]ddress|IP)");return maskUserIdentity(g.replace(S,`$1${f}$4`))}var Be=__toESM(M),He=["response","responseText","responseURL","status","state","statusText","timeout","withCredentials","stack","message","name","error","piiSafe","phase","code","participantId","phrase","subCode","reason","conversationType","terminatedReason","terminatedReasonCode","terminatedReasonSubCode","errorMessage"];function getPIISafeObject(g){try{return JSON.parse(JSON.stringify(g,He,4))}catch(g){return{error:"failed to parse object"}}}var processStackTrace=g=>{try{return g.split("\n")[0]}catch(g){return"invalid stack"}};function getPrintableObject(g,f=!1){if(null==g)return"void";if(g instanceof Error)return g.toString();if(g instanceof String||g instanceof Number||g instanceof Boolean)return g.toString();try{return g.stack&&(g.stack=processStackTrace(g.stack)),(f?JSON.stringify(g):JSON.stringify(g,He,4)).replace(/(\r\n\t|\n|\r\t|\s)/gm,"")}catch(f){return`failed to get error information:${g&&"function"==typeof g.toString&&g.toString()} ${g?.response&&JSON.stringify(g.response)}`}}function safeJsonStringify(g){try{return JSON.stringify(g,null,2)}catch(f){return`failed to stringify obj ${g}`}}function truncate(g,f){try{return g.substring(0,f)}catch(f){return g}}function hasValue(g){return g||!1===g||""===g||0===g}function getPIISafeCallInitOptions(g){const f={mediaPeerType:g.mediaPeerType,threadId:getLoggableThreadId(g.threadId)};return hasValue(g.messageId)&&(f.messageId=g.messageId),hasValue(g.enableGroupCallMeetupGeneration)&&(f.enableGroupCallMeetupGeneration=g.enableGroupCallMeetupGeneration),hasValue(g.endpointMetadata)&&(f.endpointMetadata=g.endpointMetadata),hasValue(g.onBehalfOf)&&(f.onBehalfOf=scrubMriOrOmit(g.onBehalfOf)),hasValue(g.onBehalfOfUserDisplayName)&&(f.onBehalfOfUserDisplayName=g.onBehalfOfUserDisplayName),hasValue(g.emergencyContent)&&(f.emergencyContent=g.emergencyContent),hasValue(g.isEmergency)&&(f.isEmergency=g.isEmergency),hasValue(g.broadcastContext)&&(f.broadcastContext=g.broadcastContext),g.meetingInfo&&(f.meetingInfo={tenantId:g.meetingInfo.tenantId,organizerId:scrubMriOrOmit(g.meetingInfo.organizerId)},hasValue(g.meetingInfo.meetingType)&&(f.meetingInfo.meetingType=g.meetingInfo.meetingType),hasValue(g.meetingInfo.replyChainMessageId)&&(f.meetingInfo.replyChainMessageId=g.meetingInfo.replyChainMessageId)),g.transferContext&&(f.transferContext={transferorMri:scrubMriOrOmit(g.transferContext.transferorMri),targetMri:scrubMriOrOmit(g.transferContext.targetMri),context:scrubObjectFields(g.transferContext.context)},hasValue(g.transferContext.transferType)&&(f.transferContext.transferType=g.transferContext.transferType)),safeJsonStringify(f)}function getPIISafePayload(g,f){try{const S=scrubObjectFields(g);return Object.keys(g).forEach((v=>{f.includes(v)?S[v]=scrubMriOrOmit(g[v]):"conversationId"===v&&(S[v]=getLoggableThreadId(g[v]))})),safeJsonStringify(Be.omit(S,["body.gp"]))}catch(g){return{error:"failed to get safe payload"}}}function getPIISafeRequestResponse(g){try{let f=scrubObjectFields(g,["id","groupCallInitiator","organizerId"]);return scrubProperty(f,"response.roster.participants"),scrubProperty(f,"response.additionalActionResponses.0.output.roster.participants"),scrubProperty(f,"response.muteUnmuteResponse"),f=Be.omit(f,["meetingChatProperties"]),f=scrubRequestData(f),f}catch(g){return"failed to return safe response"}}function getPIISafeRequest(g){try{return scrubRequestData(scrubObjectFields(g))}catch(g){return"failed to return safe request"}}function scrubRequestData(g){if(g?.config?.data){let f=g.config.data;f=JSON.parse(f),f=scrubObjectFields(f),g.config.data=safeJsonStringify(f)}return safeJsonStringify(g)}function getPIISafeMessage(g){try{const f=scrubObjectFields(g,["id","groupCallInitiator"]);return scrubProperty(f,"body.participants"),safeJsonStringify(f)}catch(g){return"failed to return safe response"}}function getPIISafeEndpointDetails(g){try{return safeJsonStringify(scrubObjectFields(g,["originalId"]))}catch(g){return"failed to return safe endpoint details"}}function scrubProperty(g,f){g&&Be.get(g,f)&&Be.set(g,f,scrubMriKeys(Be.get(g,f)))}function getRandomizedTimeout(g){const f=Math.floor(11*Math.random())+10;return Math.floor(g*(1-f/100))}function isStringBase64(g){if(!g)return!1;try{return atob(g),!0}catch(g){return!1}}function isPromiseLike(g){return!!g&&"function"==typeof g.then}function stringifyObject(g){if(!g)return`${g}`;if(g instanceof Map)return mapToString(g);const f=g.toString();return f.endsWith("[object Object]")?JSON.stringify(g):f}function stringifyRequestResponse(g){try{if(g.status)return`status: ${g.status}, URL: ${g.responseURL}, statusText: ${g.responseText}`}catch(g){}return stringifyObject(g)}function mapToString(g){const f={};return g.forEach(((g,S)=>{f[S.toString()]=g})),JSON.stringify(f)}function stringToBuffer(g){const f=new ArrayBuffer(g.length),S=new Uint8Array(f);for(let f=0;f<g.length;f++)S[f]=g.charCodeAt(f);return S}function limitArraySize(g,f,S=0){return g&&void 0!==f&&f>-1&&g.length>f&&g.splice(S,g.length-f),g}function arrayLimitedPush(g,f,S,v=0){limitArraySize(g,0===S?0:S-1,v),0!==S&&g.push(f)}var $e=class{constructor(g){g&&"function"==typeof g.createChild?this.logger=g.createChild("RequestDispatcher"):this.logger=new Fe("JS.TsCalling.RequestDispatcher",!1)}getRequestOptions(g,f,S,v,C){return{headers:f||{},timeout:v,payload:S||null,responseType:C}}getAsync(g,f){return this.sendRequest(g,f,"GET")}postAsync(g,f){return this.sendRequest(g,f,"POST")}putAsync(g,f){return this.sendRequest(g,f,"PUT")}removeAsync(g,f){return this.sendRequest(g,f,"DELETE")}async sendRequest(g,f={headers:{}},S){return f.useFetch?this.sendFetchRequest(g,f,S):this.sendAxiosRequest(g,f,S)}async sendAxiosRequest(g,f={headers:{}},S){const v=this.logger.createChild(`[${f.causeId||generateCauseId()}][AxiosRequest]`);v.info(`sending, ${S}-${g}`);const C=Date.now();let _;handleHeaders(f);try{const T=De.default.request({url:g,method:S,headers:f.headers,timeout:"number"==typeof f.timeout?f.timeout:45e3,data:f.payload||"",responseType:f.responseType||f.dataType||"json",withCredentials:valueOrDefault(f.withCredentials,!1),cancelToken:new De.default.CancelToken((g=>{_=g}))});isPromiseLike(f.timeout)&&f.timeout.then((()=>{v.info("Aborting pending request"),_()}),(()=>{v.info("Timeout promise rejected, ignoring")}));const I=await T;return v.info(`success, status=${I.status}`),{response:I.data,request:{status:I.status,statusText:I.statusText,headers:I.headers,responseURL:I.request.responseURL,readyState:I.request.readyState,response:I.request.response,responseText:""===I.request.responseType||"text"===I.request.responseType?I.request.responseText:"",withCredentials:I.request.withCredentials},duration:Date.now()-C}}catch(g){if(v.info("failed"),De.default.isCancel(g))throw v.info(`response=${getPIISafeRequestResponse(g.message)}`),{aborted:!0};throw g.response?v.info(`response=${getPIISafeRequestResponse(g.response)}`):g.request?v.info(`no response, request=${getPIISafeRequest(g.request)}`):v.info(`request not made, error=${getPrintableObject(g)}`),g||new Error("Request failed")}}async sendFetchRequest(g,f={headers:{}},S){const v=this.logger.createChild(`[${f.causeId||generateCauseId()}][FetchRequest]`);v.info(`sending, ${S}-${g}`);const C=Date.now(),_=new AbortController;let T,I=null,b=null;const abortPendingRequest=()=>{v.info("Aborting pending request"),_.abort()};handleHeaders(f);try{if(f.fetchUseKeepAlive&&f.payload?.toString().length>65e3&&v.warn("Using fetch with keep alive with more than 64kib data"),v.info(`${JSON.stringify(f.headers)}`),I=fetch(g,{method:S,headers:f.headers,body:f.payload,credentials:f.withCredentials?"include":"same-origin",signal:_.signal,keepalive:f.fetchUseKeepAlive}),isPromiseLike(f.timeout))f.timeout.then((()=>{abortPendingRequest()}),(()=>{v.info("Timeout promise rejected, ignoring")}));else if(f.timeout){const g=setTimeout((()=>abortPendingRequest()),f.timeout);I=I.finally((()=>clearTimeout(g)))}b=await I;try{T=await b.json()}catch(g){v.info(`unable to parse response as json with error ${g}`)}const A={response:T,request:{status:b.status,statusText:b.statusText,headers:Object.fromEntries(b.headers.entries()),responseURL:b.url,response:T,withCredentials:f.withCredentials},duration:Date.now()-C};if(!b.ok)throw v.info(`failed response, status=${b.status}`),A;return v.info(`success, status=${b.status}`),A}catch(g){if(v.info(`failed error=${getPrintableObject(g)}`),"AbortError"===g.name)throw{aborted:!0};throw g||new Error("Request failed")}}};function valueOrDefault(g,f){return void 0!==g?g:f}function handleHeaders(g){g.headers=g.headers||{},g.headers["content-type"]||(g.headers["content-type"]=g.contentType||"application/json")}var je=M,Ge=class _InternalLogger{constructor(g){this._callingLogger=g,this._maybeLog=(g,...f)=>{try{this._callingLogger[g](...f)}catch(g){this._callingLogger.info("[failed to log]",getPrintableObject(g))}}}getPrefix(g,f){let S="";return f&&(S+=`[${f}]`),g&&(S+=`[${g}]`),S}createChild(g,f){return new _InternalLogger(this._callingLogger.createChild(g,f))}createFnLogger(g,f,...S){return new _InternalLogger(this._callingLogger.createChild(this.getPrefix(g,f)+S.join(""),!1))}logSuccess(g){this._maybeLog("info",`success=${g}}`)}logFailure(g){const f=getPrintableObject(g);this._maybeLog("info",`failed=${f}}`)}log(...g){this._maybeLog("log",...g)}debug(...g){this._maybeLog("debug",...g)}info(...g){this._maybeLog("info",...g)}warn(...g){this._maybeLog("warn",...g)}error(...g){this._maybeLog("error",...g)}},qe=M,We=class{constructor(g){this.eventLogger=g,this.subscriptions=[]}subscribe(g){return new ze(this.subscriptions,g)}dispose(g){this.subscriptions=[]}raiseEvents(g){this.subscriptions.slice().forEach((f=>{try{void 0!==f.eventHandler&&g(f.eventHandler)}catch(g){this.eventLogger?.warn?.("Event handler exception caught!",stringifyObject(g))}}))}},ze=class{constructor(g,f){this.subscriptions=g,this.eventHandler=f,this.subscriptions.push(this)}dispose(){(0,qe.remove)(this.subscriptions,(g=>g===this)),this.eventHandler=void 0}},Ke=class extends We{constructor(g){super(g)}changed(g,f){return this.subscribe({changed:{skipEventConfig:f,handler:g},on:void 0})}on(g,f){return this.subscribe({changed:void 0,on:{name:String(g),handler:this._toEventCallback(f)}})}once(g,f,S){let v;const onceSubscription=(...g)=>{v.dispose(S),this._toEventCallback(f)(...g)};return v=this.on(g,this._fromEventCallback(onceSubscription)),v}raiseChanged(g){this.raiseEvents((f=>{if(!f.changed)return;const{skipEventConfig:S,handler:v}=f.changed;!this.getShouldSkipChangedEvent(g,S)&&v()}))}event(g){return{raise:this._fromEventCallback(((...f)=>this._raiseEventImpl(String(g),...f)))}}_raiseEventImpl(g,...f){this.raiseEvents((S=>S.on&&S.on.name===g&&S.on.handler(...f)))}_toEventCallback(g){return g}_fromEventCallback(g){return g}getShouldSkipChangedEvent(g,f){return g?.skipDominantSpeakerUpdatesOnCall?!!f?.skipDominantSpeakerUpdatesOnCall:!!g?.skipParticipantsUpdatesOnCall&&!!f?.skipParticipantsUpdatesOnCall}async onAsync(g,f){return this.on(g,f)}async onceAsync(g,f,S){return this.once(g,f,S)}async changedAsync(g,f){return this.changed(g,f)}async disposeAsync(g){this.dispose(g)}};function getTsCallingVersion(){return"2025.03.01.41"}function getOvb(){return"cba3e05218cf5c9f3c5c1009bd560650dc7383a5"}var Je=M,Ye=__toESM(ne()),Qe={OS:{Android:"Android",iOS:"iOS",MacOS:"Mac OS"},Browsers:{Opera:"Opera",Edge:"Edge",Yandex:"Yandex",Firefox:"Firefox",Safari:"Safari",MobileSafari:"Mobile Safari",WebKit:"WebKit"},Engines:{Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",WebKit:"WebKit"}},Xe="Unknown",Ze="0.0",et=class _BrowserInfoProvider{constructor(){const g=navigator.userAgent,f=new Ye.UAParser(g).getResult();this.browserInfo={name:f.browser.name||"Unknown",engine:f.engine.name||"Unknown",version:f.browser.version||Ze,formFactor:getFormFactor(f)||"Unknown",osName:f.os.name||Xe,osVersion:f.os.version||Xe},this.modifyParserResult(f)}static get instance(){return _BrowserInfoProvider._instance||(_BrowserInfoProvider._instance=new _BrowserInfoProvider),_BrowserInfoProvider._instance}static isFormFactor(...g){return g.map((g=>g.toString())).includes(this.getBrowserInfo().formFactor)}static isEngine(...g){return g.map((g=>g.toString())).includes(this.getBrowserInfo().engine)}static isBrowser(...g){return g.map((g=>g.toString())).includes(this.getBrowserInfo().name)}static isVersionGreaterOrEqual(g){const f=this.getBrowserInfo().version,S=g.split(".").map((g=>parseInt(g,10))),v=f.split(".").map((g=>parseInt(g,10)));return v[0]>S[0]||v[0]===S[0]&&v[1]>=S[1]}static getBrowserInfo(){return this.instance.browserInfo}static isRemote(){return window.navigator.mediaDevices?.isRemote}static toString(){const g=this.getBrowserInfo();return`${g.name}/${g.version} ${g.engine} ${g.formFactor}`}modifyParserResult(g){switch(g.engine.name){case Qe.Engines.EdgeHTML:this.browserInfo.engine="Edge";break;case Qe.Engines.Blink:this.browserInfo.engine="Chromium";break;case Qe.Engines.WebKit:g.browser.name?.includes("Safari")||(this.browserInfo.engine="Chromium");break;case Qe.Engines.Gecko:this.browserInfo.engine="Firefox"}g.engine.name===Qe.Engines.Blink&&g.browser.name===Qe.Browsers.Edge&&(this.browserInfo.name="EdgeAnaheim"),g.engine.name===Qe.Engines.Blink&&g.os.name===Qe.OS.Android&&(this.browserInfo.version=g.engine.version||Ze),g.browser.name!==Qe.Browsers.Opera&&g.browser.name!==Qe.Browsers.Yandex||(this.browserInfo.version=g.engine.version||Ze,g.browser.name===Qe.Browsers.Yandex&&(this.browserInfo.name="YandexBrowser")),(g.os.name===Qe.OS.iOS||g.browser.name?.includes(Qe.Browsers.Safari))&&(this.browserInfo.engine="Safari"),g.os.name!==Qe.OS.MacOS&&g.os.name!==Qe.OS.iOS||g.browser.name!==Qe.Browsers.WebKit||(this.browserInfo.engine="Safari",this.browserInfo.name="AppleWebView"),g.os.name===Qe.OS.iOS&&(this.browserInfo.version=g.os.version||Ze),g.browser.name===Qe.Browsers.MobileSafari&&(this.browserInfo.name="Safari"),g.ua.includes("maglev")&&(this.browserInfo.name="Maglev",this.browserInfo.version=g.engine.version||Ze),_BrowserInfoProvider.isRemote()&&(this.browserInfo.engine="ChromiumAVD"),g.ua.includes("Cisco")&&(this.browserInfo.name="CiscoOS"),g.ua.includes("ZoomRoom")&&(this.browserInfo.name="ZoomRoom"),g.ua.includes("TeamsSamsungTVBrowser")&&(this.browserInfo.name="SamsungTV")}};function getFormFactor(g){const f="136";if(getOsSkuInfo()===f)return"Hololens";if(/hostAudio-Processing/i.test(g.ua))return"RoomAudioProcessing";const S=g.device.type;return"mobile"===S||"tablet"===S?"Mobile":void 0===g.browser.name?"Unknown":"Desktop"}function getOsSkuInfo(){const g="os-sku",f=window.external;return f?.getHostEnvironmentValue?JSON.parse(f.getHostEnvironmentValue(g))[g]:"-1"}var tt={src:["https://statics.teams.cdn.office.net/hashed/azuremediaplayer.min-d46c9f4.js","https://statics.teams.cdn.office.net/evergreen-assets/broadcast/player-skin.min.js"],css:["https://statics.teams.cdn.office.net/evergreen-assets/broadcast/player-skin.min.css?v=2","https://statics.teams.cdn.office.net/evergreen-assets/broadcast/video-player.css?v=3"],styles:["azuremediaplayer","amp-stream-skin","amp-big-play-centered"],lang:"en-us",disableFullscreenButton:!1,playerType:0},it={src:["https://res.cdn.office.net/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js"],css:[],styles:[],lang:"en-us",disableFullscreenButton:!1,muteVideo:!1,playerType:1,hydraPlayerWebSdkUrls:["https://res-4.public.onecdn.static.microsoft/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js","https://res.cdn.office.net/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js"]},nt={src:[],css:[],styles:[],playerType:2,hydraPlayerWebSdkUrls:["https://res.cdn.office.net/s01-ml-player/4.24352.3/hydra_player_ums_bundle.js"]},rt=class{constructor(g,f,S,v){this.configIds=S,this.logger=v,this.defaultSettings=getSettings(),this.logger.info(`client settings: ${JSON.stringify(f)}`),this.defaultSettings.debug=f?.debug||!1,this.defaultSettings.playerType=f?.playerConfig?.playerType||this.defaultSettings.playerType,f?.playerConfig&&(0===this.defaultSettings.playerType?this.defaultSettings.ampSettings.liveStreamPlayerConfiguration=f.playerConfig:1===this.defaultSettings.playerType?this.defaultSettings.hlsSettings.liveStreamPlayerConfiguration=f.playerConfig:2===this.defaultSettings.playerType&&(this.defaultSettings.umsSettings.liveStreamPlayerConfiguration=f.playerConfig)),(0,Je.mergeWith)(this.defaultSettings,g,arrayMergeCustomizer),this.logger.info(`applied settings: ${JSON.stringify(this.defaultSettings)}`)}get playerConfig(){return 0===this.defaultSettings.playerType?this.defaultSettings.ampSettings.liveStreamPlayerConfiguration:1===this.defaultSettings.playerType?this.defaultSettings.hlsSettings.liveStreamPlayerConfiguration:2===this.defaultSettings.playerType?this.defaultSettings.umsSettings.liveStreamPlayerConfiguration:null}get config(){return this.defaultSettings}},st=class{constructor(){this.defaultSettings={allowSdnPlugins:!0,capturePlayerLogs:!0,playerType:0,loadType:1,maxPlayerDiagnosticsCount:50,maxPlayerMemoryTraceLogCount:1e3,maxPlayerPlaybackEventCount:50,maxRetryCount:10,playerTelemetryTickMs:1e3,removeEmptyDefaultTextTrack:!0,sendSnapshotTelemetry:!1,sendSnapshotTelemetryEveryMs:1e4,sendInitialTelemetryAfterMs:6e4,sendTelemetry:!0,textTrackKind:"subtitles",maxRetryCountForLoadingResources:5,maxVideoTrackHistoryLogCount:100,hydraRuntimeFetchTimeout:6e3,ampSettings:{errorCodesEligibleForStreamingUrlSwitch:[4194309,2097564,2097556,2097752,2097753,5242884],liveStreamPlayerConfiguration:tt,sourceResetTimeoutInMs:1e3,streamingUrlSwitchMaxCount:2,resetStreamingUrlSwitchCount:!1,useBrowserWindowSizeForBitRate:!0,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,collectUserInitiatedSeekEventsTelemetry:!0,maxUserInitiatedSeekEventCount:100,noMediaTimeoutMs:-1},hlsSettings:{liveStreamPlayerConfiguration:it,timeoutForSwitchingUrl:9e3,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,playlistInitialSequenceNumber:1,skipNonce:!1,maxStreamConnectionResultsLogCount:100,logHlsJsEvents:!1,logHlsJsEventsEveryMs:5e3,maxPlayerExperimentalEvents:100},umsSettings:{liveStreamPlayerConfiguration:nt,timeoutForSwitchingUrl:9e3,maxStreamConnectionResultsLogCount:100,minTargetEdgeLatency:.2,latencyCompensationThreshold:.5,maxPlayerExperimentalEvents:100}}}getSettings(){return this.defaultSettings}},at=class extends st{constructor(){super(),this.settings=super.getSettings(),this.settings.loadType=0,this.settings.allowSdnPlugins=!1,this.settings.umsSettings.minTargetEdgeLatency=.6,this.settings.umsSettings.latencyCompensationThreshold=.9}getSettings(){return this.settings}};function getSettings(){return(et.isEngine("Safari")?new at:new st).getSettings()}function arrayMergeCustomizer(g,f){if((0,Je.isArray)(g))return f.slice()}function isStreamValid(g){return!!g&&!!g.url&&!!g.decryptionToken}function assert(g,f,S){if(!g&&!S)throw new Error("Assert failed"+(void 0!==f?`: ${f}`:""))}var ot=class{constructor(g,f,S){this.name=g,this.stopCrash=f,this.start(S)}complete(){assert(this.startTime,"not started",this.stopCrash),assert(void 0===this.duration,"already completed",this.stopCrash),this.duration=Date.now()-this.startTime}updateDetails(g,f){if(this.details&&"object"==typeof this.details)for(let S=0;S<g.length;S++)this.details[g[S]]=f[S]}fail(g){this.failReason=g,this.complete()}set detail(g){this.details=g}getTelemetryEvent(){assert(this.startTime,"not started",this.stopCrash);try{assert(void 0!==this.duration,"not completed",this.stopCrash)}catch(g){if("SetSource"!==this.name&&"Load"!==this.name)throw g}const g={name:this.name,startTime:this.startTime,duration:this.duration};return this.failReason&&(g.failReason=this.failReason),this.details&&(g.details=this.details),g}start(g){assert(!this.startTime,"already started",this.stopCrash),this.startTime=Date.now(),this.details=g}},lt=class{constructor(g,f,S){this.config=g,this.logger=f,this.playerDiagnosticsLog=S,this.currentScenarioMap=new Map,this.playerEvents=[],this.playbackEvents=[],this.userInitiatedSeekEvents=[],this.experimentalEvents=[],this.clientNetworkType=void 0,this.maxPlayerPlaybackEventCount=g.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=g.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=g.maxPlayerMemoryTraceLogCount||100,this.maxUserInitiatedSeekEventCount=g.ampSettings?.maxUserInitiatedSeekEventCount||100,this.stopCrash=g.stopCrash||!1,this.config.debug&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener()}getPlayerDiagnosticSnapshot(){return this.currentPlayerDiagnosticSnapshot}registerStatsUpdated(g){this.currentPlayerDiagnosticSnapshot=g,Object.keys(this.playerDiagnosticsLog).forEach((f=>{const S=f,v=this.playerDiagnosticsLog[f];if(Array.isArray(v)){v.push(g[S]);const f="memoryLog"===S&&v.length>this.maxPlayerMemoryTraceLogCount,C="memoryLog"!==S&&v.length>this.maxPlayerDiagnosticsCount;(f||C)&&v.splice(0,1)}else this.playerDiagnosticsLog[f]=g[S]}))}registerEventLoadAttempt(g,f){this.registerScenario(g,f)}registerEventLoadFailed(g,f){this.completeScenario(g,f)}registerEventLoadSucceeded(g,f){this.completeScenario(g,void 0,f)}registerPlayerLoadAttempt(){this.registerScenario("Load")}registerPlayerLoadSucceeded(g){this.completeScenario("Load",void 0,g)}registerPlayerLoadFailed(g){this.completeScenario("Load",g)}registerPlayerSetupAttempt(){this.registerScenario("Setup")}registerPlayerSetupSucceeded(){this.completeScenario("Setup")}registerPlayerSetupFailed(g){this.completeScenario("Setup",g)}registerStreamConnectionAttempt(g){this.registerScenario("StreamConnection")}registerStreamConnectionSucceeded(){this.completeScenario("StreamConnection")}registerStreamConnectionFailed(g){this.completeScenario("StreamConnection",g)}registerSetSourceAttempt(g,f){let S=g;f&&(S={src:g,reason:f}),this.registerScenario("SetSource",S)}registerSetSourceSucceeded(g){this.getScenario("SetSource").updateDetails(["src"],[g]),this.completeScenario("SetSource")}registerSetSourcedFailed(g,f){this.getScenario("SetSource").updateDetails(["src"],[f]),this.completeScenario("SetSource",g)}registerSdnPluginLoad(g,f,S){this.registerScenario("SdnPluginLoad",g);const v=f?void 0:S;this.completeScenario("SdnPluginLoad",v)}registerPlayerDestroyed(g){this.registerScenario("Destroyed",g),this.completeScenario("Destroyed")}registerPlaybackStateChanged(g,f){let S;if("Ready"!==g||this.firstReadyStateTimestamp?"Playing"!==g||this.firstPlayingStateTimestamp||(this.firstPlayingStateTimestamp=Date.now()):this.firstReadyStateTimestamp=Date.now(),f&&"Buffering"===g){f?S=f.message:this.logger.debug(`Unexpected buffering payload: ${JSON.stringify(f)}`)}this.registerPlaybackEvent("StateChanged",g,S)}registerPlaybackError(g,f){this.registerPlaybackEvent("Error",{errorType:g,details:f})}registerDownloadBitratechanged(g){this.registerPlaybackEvent("BitrateChangedDownload",g)}registerStreamOptionsConfigured(g,f){this.registerPlaybackEvent("StreamOptionsConfigured",this.generateCleanedStreamOption(g),f)}registerPlaybackBitratechanged(g){this.registerPlaybackEvent("BitrateChangedPlayback",g)}registerPotentialMediaFreeze(g){this.registerPlaybackEvent("PotentialMediaFreeze",g)}registerCaptionToggle(g,f,S){const v={isEnabled:g,culture:f,playerTime:S};this.registerPlaybackEvent("CaptionsToggled",v)}registerFullScreenChange(g){this.registerPlaybackEvent("FullscreenChanged",g)}registerMute(g){this.registerPlaybackEvent("Mute",g)}registerVolumeChange(g){this.registerPlaybackEvent("Volume",g)}getExperimentalEvents(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}}getUserInitiatedSeekEvents(){return{playback_userInitiatedSeekEvents:this.prepareForTelemetry(this.userInitiatedSeekEvents)}}getSnapshotReport(g={}){const f=this.playerEvents.map((g=>g.getTelemetryEvent())),S=this.playbackEvents;let v={};return this.currentPlayerDiagnosticSnapshot&&(v=this.filterAndPrepareTelemetry()),{isFullReport:!1,configIds:g.configIds||"",playerId:g.playerId||"",correlationId:g.correlationId||"",traceId:g.correlationId?g.correlationId.replace(/-/g,""):"",eTag:g.eTag||"",isFinal:g.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:g.disableFullscreenButton??!1,threadId:g.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:getTsCallingVersion(),...this.getInitializationReport(f,S),...this.getPlaybackReport(S),...this.getBitrateReport(S),...this.getSdnReport(f),...this.getSetSourceReport(f),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(f),callDropped:this.getCallDropped(S),...v}}getReport(g={}){const f=this.playerEvents.map((g=>g.getTelemetryEvent())),S=this.playbackEvents;return{callendReason:g.callendReason,isFullReport:!0,configIds:g.configIds||"",playerId:g.playerId||"",correlationId:g.correlationId||"",traceId:g.correlationId?g.correlationId.replace(/-/g,""):"",eTag:g.eTag||"",isFinal:g.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:g.disableFullscreenButton??!1,threadId:g.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:getTsCallingVersion(),...this.getInitializationReport(f,S),...this.getPlaybackReport(S),...this.getBitrateReport(S),...this.getSdnReport(f),...this.getSetSourceReport(f),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(f),callDropped:this.getCallDropped(S),...this.getPlayerDiagnosticLog()}}registerExperimentalEvent(g,f,S){const v=this.createTelemetryEvent(g,f,S);this.experimentalEvents.push(v),this.logTelemetryEvent(v)}registerUserInitiatedSeek(g){const f=(this.currentPlayerDiagnosticSnapshot?.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1)<g.newCurrentPlayPosition,S={...g,seekForward:f},v=this.createTelemetryEvent("UserInitiatedSeek",S);this.userInitiatedSeekEvents.push(v),this.userInitiatedSeekEvents.length>this.maxUserInitiatedSeekEventCount&&this.userInitiatedSeekEvents.splice(0,1)}createTelemetryEvent(g,f,S){const v={eventType:g,timestamp:Date.now(),currentPlayPosition:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1};return void 0!==f&&(v.payload=this.prepareForTelemetry(f)),v.message=S,v}registerPlaybackEvent(g,f,S){const v=this.createTelemetryEvent(g,f,S);"Error"===g&&"PlaybackRetried"!==f?.errorType&&(v.fatal=!0),this.playbackEvents.push(v),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(v)}getPlayerDiagnosticLog(){if(!this.currentPlayerDiagnosticSnapshot)return{};const g={...this.currentPlayerDiagnosticSnapshot,...this.playerDiagnosticsLog},f={};return Object.keys(g).forEach((S=>{f[`player_${S}`]=this.prepareForTelemetry(g[S])})),f}getCallSetupSucceeded(g){const f=g.find((g=>"Load"===g.name));return!!f&&!f.failReason}getCallDropped(g){return!!g.filter((g=>"Error"===g.eventType)).find((g=>g.fatal))}getInitializationReport(g,f){const S=g.find((g=>"Load"===g.name));return{init_timeLoadToStreamConnectionEstablished:(S&&this.initialStreamConnectionEstablishedTimestamp?this.initialStreamConnectionEstablishedTimestamp-S.startTime:-1)||-1,init_timeLoadToReady:(S&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-S.startTime:-1)||-1,init_timeLoadToPlaying:(S&&this.firstPlayingStateTimestamp?this.firstPlayingStateTimestamp-S.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(g)}}getPlaybackReport(g){const f=g.filter((g=>"StateChanged"===g.eventType)),S=f.find((g=>"Ready"===g.payload)),v=f.find((g=>"Play"===g.payload)),C=f.find((g=>"Start"===g.payload)),_=f.find((g=>"Playing"===g.payload)),T=S&&v?v.timestamp-S.timestamp:-1,I=v&&C?C.timestamp-v.timestamp:-1,b=C&&_?_.timestamp-C.timestamp:-1,A=f.filter((g=>"Seeked"===g.payload)),P=f.filter((g=>"Seeking"===g.payload)),R=f.filter((g=>"Paused"===g.payload)),M=f.filter((g=>"Resume"===g.payload)),w=f.filter((g=>"Buffering"===g.payload)),O=["BitrateChangedDownload","BitrateChangedPlayback","Error","Mute","StateChanged","Volume","StreamOptionsConfigured"],D=g.filter((g=>"Error"===g.eventType)),N=g.filter((g=>"Volume"===g.eventType||"Mute"===g.eventType)),k=g.filter((g=>"StreamOptionsConfigured"===g.eventType)),L=g.filter((g=>!O.includes(g.eventType)));return{playback_timeReadyToPlay:T,playback_timePlayToStart:I,playback_timeStartToPlaying:b,playback_bufferingEvents:this.prepareForTelemetry(w),playback_errorEvents:this.prepareForTelemetry(D),playback_pauseEvents:this.prepareForTelemetry(R),playback_resumeEvents:this.prepareForTelemetry(M),playback_otherEvents:this.prepareForTelemetry(L),playback_seekedEvents:this.prepareForTelemetry(A),playback_seekingEvents:this.prepareForTelemetry(P),playback_stateChangeEvents:this.prepareForTelemetry(f),playback_volumeEvents:this.prepareForTelemetry(N),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(k)}}generateCleanedStreamOption(g){return{...g,stream:{...g?.stream,decryptionToken:g?.stream?.decryptionToken?"valid":"empty",sdnContext:g?.stream?.sdnContext?"valid":"empty",keyAuthorizationToken:g?.stream?.keyAuthorizationToken?"valid":"empty"},altStream:g?.altStream?{...g?.altStream,decryptionToken:g?.altStream?.decryptionToken?"valid":"empty",sdnContext:g?.altStream?.sdnContext?"valid":"empty",keyAuthorizationToken:g?.stream?.keyAuthorizationToken?"valid":"empty"}:void 0}}getBitrateReport(g){const f=g.filter((g=>"BitrateChangedDownload"===g.eventType)),S=f.sort((g=>Number(g.payload))),v=f.length?{bitrate_downloadChanges:this.prepareForTelemetry(f),bitrate_downloadChangeCount:f.length||-1,bitrate_downloadMin:S[0].payload||-1,bitrate_downloadMax:S[S.length-1].payload||-1}:{},C=g.filter((g=>"BitrateChangedPlayback"===g.eventType)),_=C.sort((g=>Number(g.payload)));return{...v,...C.length?{bitrate_playbackChanges:this.prepareForTelemetry(C),bitrate_playbackChangeCount:C.length||-1,bitrate_playbackMin:_[0].payload||-1,bitrate_playbackMax:_[_.length-1].payload||-1}:{}}}addNetworkTypeEventListener(){window.navigator?.connection?.type&&window.navigator?.connection?.addEventListener("change",(()=>this.updateClientNetworkType()))}updateClientNetworkType(){this.clientNetworkType=void 0,this.getClientNetworkType()}getClientNetworkType(){if(void 0===this.clientNetworkType){let g="Unknown";if(window.navigator?.connection?.type){const f=window.navigator?.connection?.type;switch(f){case"cellular":g="WWAN";break;case"ethernet":g="Wired";break;case"wifi":g="Wireless";break;default:g="Unknown"}}this.clientNetworkType=g}return this.clientNetworkType}getSdnReport(g){const f=g.filter((g=>"SdnPluginLoad"===g.name)),S=f.length?f[f.length-1]:void 0;return{sdn_loaded:!(!S||void 0!==S.failReason),sdn_details:S&&S.details||"",sdn_error:S&&S.failReason||"",sdn_events:this.prepareForTelemetry(f)}}getSetSourceReport(g){const f=g.filter((g=>"SetSource"===g.name));return{set_source_events:this.prepareForTelemetry(f)}}registerScenario(g,f){const S=this.currentScenarioMap.get(g),v=new ot(g,this.stopCrash,f);assert(!S,`previous scenario:${stringifyObject(S)} is not completed, new scenario:${stringifyObject(v)}`,this.stopCrash),this.currentScenarioMap.set(g,v),this.playerEvents.push(v)}getScenario(g){return this.currentScenarioMap.get(g)}completeScenario(g,f,S){const v=this.currentScenarioMap.get(g);assert(v,"no scenario to complete",this.stopCrash),f?v.fail(f):("StreamConnection"!==g||this.initialStreamConnectionEstablishedTimestamp||(this.initialStreamConnectionEstablishedTimestamp=Date.now()),S&&(v.detail=S),v.complete()),this.currentScenarioMap.delete(g)}logTelemetryEvent(g){this.config.debug&&(this.logger.debug(`PlayerTelemetryEvent: ${JSON.stringify(g)}`),this.logger.debug(`PlayerDiagnosticData: ${JSON.stringify(this.currentPlayerDiagnosticSnapshot)}`))}filterAndPrepareTelemetry(){const g=new Set;g.add("serviceLatencyCdg"),g.add("endToEndLatencyCdg"),g.add("videoEdgeLatencyCdg");const f={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((S=>{g.has(S)||(f[`player_${S}`]=this.prepareForTelemetry(this.currentPlayerDiagnosticSnapshot[S]))})),f}prepareForTelemetry(g){return"boolean"==typeof g?g:"string"==typeof g||void 0===g?g||"":"number"==typeof g?g??-1:JSON.stringify(g)}},ct=M;function asap(g){return new Promise((f=>{f(g())}))}var dt=class{constructor(){this.isPendingInt=!0,this.promiseInt=new Promise(((g,f)=>{this.resolveInt=g,this.rejectInt=f}))}get resolve(){return g=>{this.isPendingInt=!1,this.resolveInt(g),this.clearTimeout()}}get reject(){return g=>{this.isPendingInt=!1,this.rejectInt(g),this.clearTimeout()}}get promise(){return this.promiseInt}get isPending(){return this.isPendingInt}setTimeout(g,f=`deferred timed out after ${g}ms`){this.isPendingInt&&(this.timeoutId=setTimeout((()=>{this.reject(f)}),g))}clearTimeout(){this.timeoutId&&clearTimeout(this.timeoutId)}};function deferWithTimeout(g,f=`deferred timed out after ${g}ms`){const S=new dt;return S.setTimeout(g,f),S}function delay(g){return new Promise((f=>setTimeout(f,g)))}var ht=class{static build(g,f){return new ut(g,f)}},ut=class{constructor(g,f){this.ontimeout=g,this.name=f}start(g){if(void 0!==this.timeoutId)throw new Error(`Timer ${this.name} already started`);return this.timeoutId=window.setTimeout((()=>this.ontimeout()),g),this}stop(){if(void 0===this.timeoutId)throw new Error(`Timer ${this.name} is not defined`);clearTimeout(this.timeoutId),this.timeoutId=void 0}};function AmpPlayerF(){const g=AmpDiagnosticProviderF(),f=CaptionsControlToggleProviderF();let S;return(S||(S={})).CaptionFunctionalityNotSupported="CaptionFunctionalityNotSupported",class{constructor(g,f){this.container=g,this.eventsHandler=f,this.videoElementEvents=[],this.playerEvents=[],this.maxMemoryTraceLogCount=1e4,this.videoSourceType="application/dash+xml",this.sdnPluginLoaded=!1,this.statsTimer=-1,this.statsInterval=1e3,this.videoSourceSetAttemptCount=0,this.totalBufferingTime=0,this.isBuffering=!1,this.totalPlayingTime=0,this.isPlaying=!1,this.videoTrackTotalDurations=[]}get contextWindow(){return this.container.ownerDocument.defaultView}configure(g,f,S){this.liveStreamOptions=g,this.playerId=S,f&&(this.configProvider=f,this.statsInterval=f.config.playerTelemetryTickMs||this.statsInterval,this.maxMemoryTraceLogCount=f.config.maxPlayerMemoryTraceLogCount||this.maxMemoryTraceLogCount)}getIceCandidates(){let g=[];try{const f=this.liveStreamOptions.stream.sdnContext||this.liveStreamOptions.altStream?.sdnContext||"",S=JSON.parse(f),v=JSON.parse(S.sdnConfig);if(!v.RTCIceCandidates)throw new Error("RTCIceCandidates not present in SDN Context");g=v.RTCIceCandidates}catch(g){this.log(`getIceCandidates failed: ${JSON.stringify(g.message)}`,"error")}return this.log(`getIceCandidates: ${JSON.stringify(g)}`,"debug"),g}loadPlayerScript(){let g=Promise.resolve("");const f=this.configProvider.playerConfig.nonce,S=this.configProvider.playerConfig.css;for(let v=0;v<S.length;v++)g=g.then((()=>this.retry((()=>this.loadCss(this.container.ownerDocument,S[v],f)))));return g=g.then((()=>this.loadAmpScript())),g}loadAmpScript(){this.log("loadPlayerScript started");let g=Promise.resolve("");const f=this.configProvider.playerConfig?.nonce,S=this.configProvider.playerConfig?.src||[],v=Math.max(2,this.configProvider.config.maxRetryCountForLoadingResources);if(0===S.length)return Promise.reject("AMP Player Src is empty");for(let C=0;C<S.length;++C)g=g.then((()=>this.loadScriptPromise(S,C,f,v)));return g}loadScriptPromise(g,f,S,v,C=""){return this.retry((()=>this.setScriptByLoad(this.container.ownerDocument,g[f],S)),v).then((S=>`${g[f]}: ${S} `.concat(C))).catch((_=>this.retry((()=>this.setScriptByBlob(this.container.ownerDocument,g[f],S)),v).then((S=>`${g[f]}: ${S}`.concat(` ${_} `,` ${C} `))).catch((T=>this.retry((()=>this.setScriptByInnerHtml(this.container.ownerDocument,g[f],S)),1).then((S=>`${g[f]}: ${S}`.concat(` ${_} `,`${T} `,` ${C} `))).catch((_=>{let I=C;return f<g.length&&(I=I.concat(`Failed to load script, nonce: ${S}, src: ${g[f]} index: ${f} `),I=I.concat(`${v} attempts LoadFailure `,`${v} attempts BlobFetchFailure: `,T,", 1 attempt InnerHtmlFailure: ",`${_} `)),Promise.reject(I)}))))))}retry(g,f=this.configProvider.config.maxRetryCountForLoadingResources,S=1,v=200){return g(f).then((g=>`${g}, succeeded on load number: ${S} `)).catch((C=>(this.log(`Error loading resource: ${C} -- ${f} retriesLeft`),0==--f?Promise.reject(`${C}`):new Promise((_=>setTimeout((()=>_(this.retry(g,f,S+1).then((g=>"string"==typeof g?`${g}, succeeded on load number: ${S}`:g)).catch((g=>Promise.reject(`${C}`.concat(", ",g)))))),v))))))}setScriptByLoad(g,f,S){const v=g.createElement("script"),C=this.getElementLoadPromise(v,f);return v.src=f,S&&(v.nonce=S),g.head.appendChild(v),C.then((()=>Promise.resolve("Success: setScriptByLoad")))}setScriptByBlob(g,f,S){return this.safeResponse(f).then((f=>f.blob().then((v=>{if(v){const f=URL.createObjectURL(v);return this.setScriptByLoad(g,f,S).then((()=>Promise.resolve("Success: setScriptByBlob")))}return Promise.reject(`${f.status}, blob is null`)}))))}setScriptByInnerHtml(g,f,S){return this.safeResponse(f).then((f=>f.text().then((v=>{if(v){const f=document.createElement("script");return f.innerHTML=v,S&&!this.configProvider.config.hlsSettings.skipNonce&&(f.nonce=S),g.head.appendChild(f),Promise.resolve("Success: setScriptByInnerHtml")}return Promise.reject(`status code:${f.status}, text is null`)}))))}safeResponse(g){return fetch(g).then((g=>g.ok?g:Promise.reject(`${g.status}`)))}tryLoadSdnPlugin(){return this.sdnPluginLoaded||!this.liveStreamOptions.sdn?Promise.resolve():this.configProvider.config.allowSdnPlugins?(this.log("tryLoadSdnPlugin started"),this.retry((()=>this.setScriptByLoad(this.container.ownerDocument,this.liveStreamOptions.sdn.url,this.configProvider.playerConfig.nonce))).then((()=>{this.log("SDN script loaded"),this.sdnPluginLoaded=!0,this.log("tryLoadSdnPlugin done")}))):(this.log("Loading SDN plugins is not allowed"),Promise.reject("Loading SDN plugins is not allowed"))}createAmp(){this.log("createAmp started"),this.createVideoElement();const S=this.getAmpOptions();if(this.playerInstance=this.contextWindow.amp(this.video.id,S),!this.playerInstance)throw this.log("createAmp failed","error"),new Error("playerInstance is null");"html5"===this.playerInstance.currentTechName()?.toLowerCase()&&this.configProvider.config.ampSettings.estimateAbsoluteTime&&this.isControlsDisabled()?(this.absoluteTimeOffsetEstimator=new pt(this.log.bind(this)),this.diagnosticProvider=new g(this.playerInstance,this.contextWindow,new Date,this.configProvider,this.absoluteTimeOffsetEstimator),this.absoluteTimeOffsetEstimator.setEstimationResultCallback(this.onAbsoluteTimeOffsetEstimation.bind(this))):this.diagnosticProvider=new g(this.playerInstance,this.contextWindow,new Date,this.configProvider);const v={controlsEnabled:!this.isControlsDisabled(),logFn:this.log.bind(this),removeEmptyDefaultTextTrack:this.configProvider.config.removeEmptyDefaultTextTrack};this.diagnosticProvider.setValue("streamingEventType",this.liveStreamOptions.streamingEventType),this.diagnosticProvider.setValue("eventId",this.liveStreamOptions?.eventId||""),this.diagnosticProvider.setValue("templateId",this.liveStreamOptions?.templateId||""),this.diagnosticProvider.setValue("playerControlsEnabled",!this.isControlsDisabled()),this.captionsControl=new f(this.playerInstance,this,v,this.diagnosticProvider),this.registerPlayerEvents(),this.log("createAmp done")}isControlsDisabled(){return void 0!==this.liveStreamOptions.allowPlayerControls?!this.liveStreamOptions.allowPlayerControls:"Overflow"===this.liveStreamOptions.streamingEventType||"TownHall_Basic"===this.liveStreamOptions.streamingEventType||"TownHall_Premium"===this.liveStreamOptions.streamingEventType||"TownHall"===this.liveStreamOptions.streamingEventType}onAbsoluteTimeOffsetEstimation(g){if(this.diagnosticProvider.appendAbsoluteTimeOffsetEstimation(g),!g.isSuccess){const g=this.addEvent("CaptionFunctionalityNotSupported",{detail:{data:{fatal:!0,details:"absolute time offset estimation failed - captions will fail"}}});this.video.dispatchEvent(g)}}addEvent(g,f){let S={};return f?.detail&&(S={detail:f.detail}),new CustomEvent(g,S)}setSource(g){if(this.log("setSource started"),!this.playerInstance)throw this.log("setSource failed: playerInstance is null","error"),new Error("playerInstance is null");this.videoSourceSetAttemptCount++,this.videoSourceSetAttemptCount>0&&this.diagnosticProvider.setValue("retryCount",this.videoSourceSetAttemptCount-1);const f={src:g.url,type:this.videoSourceType,protectionInfo:g.decryptionToken?[{type:"AES",authenticationToken:g.decryptionToken}]:null};this.configureSdnSource(f,g),this.diagnosticProvider.setValue("streamUrl",g.url),this.diagnosticProvider.setValue("streamId",this.getStreamIdFromStreamUrl(g.url)),this.diagnosticProvider.setValue("streamDeliveryPipeline",g.streamDeliveryPipeline||""),this.playerInstance.src([f],this.getTextTracks()),this.absoluteTimeOffsetEstimator&&this.absoluteTimeOffsetEstimator.setManifestFileURL(g.url+"(format=m3u8-aapl-v4)"),this.log("setSource done")}getStreamIdFromStreamUrl(g){try{const f=new URL(g).pathname;if(f){const g=f.split("/");if(g?.length>1)return g[1]}return this.log(`unable to parse stream ID from stream URL: ${g}`,"warn"),""}catch{return this.log(`cannot parse stream ID from invalid stream URL: ${g}`,"warn"),""}}setPlayTime(g){g&&(this.log(`setPlayerTime: ${g}`),this.playerInstance.currentTime(g))}dispose(){this.log("dispose started"),this.diagnosticProvider&&(this.stopStatsCollection(),this.diagnosticProvider.dispose(),this.diagnosticProvider=null),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null),this.playerInstance&&(this.removePlayerEventListeners(),this.playerInstance.getMemoryLog(!0),this.playerInstance.dispose(),this.playerInstance=null),this.eventsHandler.ampDisposed(),this.video&&(this.removeVideoEventListeners(),this.video.parentNode&&this.video.parentNode.removeChild(this.video),this.video=null),this.absoluteTimeOffsetEstimator&&(this.absoluteTimeOffsetEstimator.stopStreamAbsoluteTimeOffsetRetrieval(),this.absoluteTimeOffsetEstimator=null),this.log("dispose done"),this.eventsHandler=null}updatePlaybackDiagnostics(){this.updateTotalPlayingTimeStatistic(),this.updateBufferingRateStatistic(),this.updateVideoTrackHistoryStatistic()}handlePlaybackStopped(){this.isBuffering=!1,this.isPlaying=!1,this.currentVideoPlaybackBitrate=null}showCaptions(g){this.log(`showCaptions: ${g}`),this.captionsControl.showCaptions(g)}addCues(g){g=g.filter((g=>g.text&&0!==g.text.trim().length)),this.captionsControl.addCues(g)}clearCues(){this.captionsControl.clearCues()}captionsToggled(g,f,S){this.log(`captionsToggled: ${g} for culture ${f} at ${S}`),this.eventsHandler.message("captionsToggled").send(g,f,S)}createVideoElement(){this.log("createVideoElement started"),this.video=this.container.ownerDocument.createElement("video"),this.video.id="amp-player",this.video.setAttribute("playsinline","");const g=this.configProvider.playerConfig.lang;g&&(this.video.setAttribute("lang",g),this.log(`createVideoElement: language set to ${g}`));const f=this.configProvider.playerConfig.styles;for(let g=0;g<f.length;g++)this.video.classList.add(f[g]);this.container.appendChild(this.video),this.log("createVideoElement done")}getAmpOptions(){const g=[];this.configProvider.config.debug?g.push({target:"memory",maxMemoryTraceCount:this.maxMemoryTraceLogCount}):g.push({target:"console"});const f={TraceTargets:g,maxLogLevel:this.configProvider.config.debug?3:2},S={techOrder:["azureHtml5JS","html5"],nativeControlsForTouch:!1,autoplay:!0,preload:"auto",controls:!this.isControlsDisabled(),logo:{enabled:!1},height:"100%",width:"100%",traceConfig:f,disableFullscreenButton:this.configProvider.playerConfig?.disableFullscreenButton,staleDataTimeLimitInSec:30,heuristicProfile:this.contextWindow.amp.Player.HeuristicProfile.HighQuality,customPlayerSettings:{customHeuristicSettings:{bandwidthTestWithTimeThresholdDuringLive:!1,windowSizeHeuristics:this.configProvider.config.ampSettings.useBrowserWindowSizeForBitRate,useBrowserWindowForWindowSizeRule:this.configProvider.config.ampSettings.useBrowserWindowSizeForBitRate,useVariableFragmentSizeMode:!0}},plugins:{}};return this.initializePluginOptions(S),S}isStreamValid(g){return g&&!!g.url&&!!g.decryptionToken}initializePluginOptions(g){if(!this.sdnPluginLoaded||!this.liveStreamOptions.sdn)return;const f=this.isStreamValid(this.liveStreamOptions.stream)?this.liveStreamOptions.stream:this.liveStreamOptions.altStream;this.log(`initializePluginOptions, receivedSDNContext: ${JSON.stringify(f?.sdnContext)}`,"info");try{const S=this.liveStreamOptions.correlationId||this.playerId;switch(this.liveStreamOptions.sdn.name){case"hive":if(g.plugins={hive:{debugLevel:this.configProvider.config.debug?"debug":"notice",telemetryId:S}},f&&f.sdnContext)try{const S=JSON.parse(f.sdnContext);if(S.sdnConfig){const f=JSON.parse(S.sdnConfig);f.candidateTopicName="RequestIceCandidates",delete f.RTCIceCandidates,Object.assign(g.plugins.hive,f)}}catch(g){this.log(`initializePluginOptions, failed to parse Hive sdnConfig Json from sdnContext Json, error: ${g}`,"warn")}break;case"kollective":if(f&&f.sdnContext){let v=null,C=null,_=null;try{v=this.parseJson(f.sdnContext,"kollective sdn context")}catch(g){this.log(`initializePluginOptions, failed to parse Kollective sdnContext Json, error: ${g}`,"error")}if(v){try{C=this.parseJson(v.playbackinfo,"kollective sdn playback info")}catch(g){this.log(`initializePluginOptions, failed to parse Kollective sdnContext playbackinfo Json, error: ${g}`,"error")}try{_=this.parseJson(v.sdnConfig,"kollective sdn config")}catch(g){this.log(`initializePluginOptions, failed to parse Kollective sdnContext sdnConfig Json, error: ${g}`,"error")}}g.plugins={kollectiveSDN:{playbackInfo:C,sdnConfig:_,reportSessionId:S}}}break;case"ramp":f&&f.sdnContext&&(g.plugins={RampMOPlugin:this.parseJson(f.sdnContext,"ramp sdn context")},this.configProvider.config.debug&&(g.plugins.RampMOPlugin.verbose=!0));break;case"peer5":f.sdnContext&&(g.plugins={peer5:this.parseJson(f.sdnContext,"peer5 sdn context")})}}catch(g){this.log(`initializePluginOptions failed, error: ${g.message}`,"error")}this.log(`initializePluginOptions, configured plugin options: ${JSON.stringify(g.plugins)}`,"info")}getTextTracks(){const g=[];if(this.isControlsDisabled())g.push({id:"amp-player_default",kind:"captions",label:"default-text-track",src:"",srclang:"en"});else if(this.liveStreamOptions.supportedSubtitleLanguages){const f=this.liveStreamOptions.supportedSubtitleLanguages;for(let S=0;S<f.length;S++)g.push({id:`amp-player_${f[S].culture}`,kind:this.configProvider.config.textTrackKind,label:f[S].name||f[S].culture,src:"",srclang:f[S].culture.substr(0,2)})}return g}configureSdnSource(g,f){if(!this.sdnPluginLoaded||!this.liveStreamOptions.sdn)return;switch(this.liveStreamOptions.sdn.name){case"hive":if(!f.sdnContext){g.sdnList=[];break}try{const S=JSON.parse(f.sdnContext);S.playbackinfo&&(g.sdnList=[{sdnName:"hive",sdnUrl:S.playbackinfo}])}catch(S){g.sdnList=[{sdnName:"hive",sdnUrl:f.sdnContext}]}break;case"kollective":if(!f.sdnContext){g.sdnList=[];break}try{const S=this.parseJson(f.sdnContext,"kollective sdn list context"),v=this.parseJson(S.playbackinfo,"kollective sdn list playback info"),C=this.parseJson(S.sdnConfig,"kollective sdn list sdn config");g.sdnList=[{sdnName:"kollectiveSDN",playbackInfo:v,sdnConfig:C}]}catch(f){return g.sdnList=[],void this.log(`configureSdnSource failed, error: ${f}`,"error")}break;case"ramp":case"peer5":g.sdnList=[];break;default:return}this.log(`configureSdnSource, configured source context: ${JSON.stringify(g)}`,"info")}registerPlayerEvents(){this.registerPlayerEvent(this.contextWindow.amp.eventName.error,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.error)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.canplaythrough,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.canplaythrough)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.play,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.play)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.playing,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.playing)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.pause,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.pause)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.resume,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.resume)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.start,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.start)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.ended,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.ended)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.seeking,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.seeking)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.seeked,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.seeked)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.loadedmetadata,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.loadedmetadata)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.waiting,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.waiting)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.playbackbitratechanged,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.playbackbitratechanged)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.downloadbitratechanged,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.downloadbitratechanged)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.fullscreenchange,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.fullscreenchange)})),this.registerPlayerEvent("potentialMediaFreeze",(()=>{this.onAmpEvent("potentialMediaFreeze")})),this.registerPlayerEvent(this.contextWindow.amp.eventName.mute,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.mute)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.unmute,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.unmute)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.volumechange,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.volumechange)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.loadeddata,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.loadeddata)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.loadstart,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.loadstart)})),Object.values(S).forEach((g=>{this.registerVideoEvent(g,(f=>{this.handleUserExperienceErrorEvent(g,f.detail.data.details,f.detail.data.fatal)}))})),this.configProvider.config.ampSettings.collectUserInitiatedSeekEventsTelemetry&&(this.playerEvents.push("currentTimeChanging"),this.playerInstance.addEventListener("currentTimeChanging",((g,f)=>this.onAmpCurrentTimeChangingEvent(g,f))))}onAmpCurrentTimeChangingEvent(g,f){if("currentTimeChanging"!==g.type||!f.time)return;const S={newCurrentPlayPosition:f.time};this.eventsHandler.message("stateChanged").send("UserInitiatedSeek",S)}registerPlayerEvent(g,f){this.playerEvents.push(g),this.playerInstance.addEventListener(g,f)}registerVideoEvent(g,f){this.videoElementEvents.push({name:g,callback:f}),this.video.addEventListener(g,f)}removePlayerEventListeners(){this.playerEvents.forEach((g=>{this.playerInstance.removeEventListener(g)}))}removeVideoEventListeners(){this.videoElementEvents.forEach((g=>{this.video.removeEventListener(g.name,g.callback)}))}onAmpEvent(g){let f,S;switch(g){case this.contextWindow.amp.eventName.error:S=this.playerInstance.error(),f={currentTime:this.playerInstance.currentTime(),errorCode:S?S.code:0,message:S?S.message:""};break;case this.contextWindow.amp.eventName.canplaythrough:this.initializeStatsColletion();break;case this.contextWindow.amp.eventName.loadedmetadata:this.captionsControl.initialize(),this.absoluteTimeOffsetEstimator&&this.absoluteTimeOffsetEstimator.restartStreamAbsoluteTimeOffsetRetrieval();break;case this.contextWindow.amp.eventName.fullscreenchange:f={isFullscreen:this.playerInstance.isFullscreen()};break;case this.contextWindow.amp.eventName.playbackbitratechanged:f={bitrate:this.playerInstance.currentPlaybackBitrate()};break;case this.contextWindow.amp.eventName.downloadbitratechanged:f={bitrate:this.playerInstance.currentDownloadBitrate()};break;case this.contextWindow.amp.eventName.seeked:f={captionsTimestamp:this.isControlsDisabled()?this.playerInstance.currentMediaTime():this.playerInstance.currentTime()};break;case this.contextWindow.amp.eventName.volumechange:f={value:this.playerInstance.volume()}}this.updatePlaybackDiagnostics(),this.updatePlayerState(g),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(g,f)}updatePlayerState(g){this.updatePlayingState(g),this.updateBufferingState(g),this.updateCurrentVideoTrackBitrate(g),g!==this.contextWindow.amp.eventName.ended&&g!==this.contextWindow.amp.eventName.error||this.handlePlaybackStopped()}handleUserExperienceErrorEvent(g,f,S){const v={currentTime:this.video?this.video.currentTime:0,message:f,type:g,errorCode:0,fatal:S};this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(this.contextWindow.amp.eventName.error,v)}updatePlayingState(g){this.isPlaying?g!==this.contextWindow.amp.eventName.pause&&g!==this.contextWindow.amp.eventName.seeking&&g!==this.contextWindow.amp.eventName.ended&&g!==this.contextWindow.amp.eventName.error&&g!==this.contextWindow.amp.eventName.waiting||(this.isPlaying=!1):g===this.contextWindow.amp.eventName.playing&&(this.isPlaying=!0)}updateBufferingState(g){this.isBuffering?(g===this.contextWindow.amp.eventName.pause&&"html5"===this.playerInstance.currentTechName()?.toLowerCase()||g===this.contextWindow.amp.eventName.seeking||g===this.contextWindow.amp.eventName.ended||g===this.contextWindow.amp.eventName.error||g===this.contextWindow.amp.eventName.playing)&&(this.isBuffering=!1):g===this.contextWindow.amp.eventName.waiting&&(this.isBuffering=!0)}updateCurrentVideoTrackBitrate(g){g===this.contextWindow.amp.eventName.playbackbitratechanged&&this.playerInstance.currentPlaybackBitrate()!==this.currentVideoPlaybackBitrate&&(this.currentVideoPlaybackBitrate=this.playerInstance.currentPlaybackBitrate(),this.updateVideoTrackHistoryStatistic())}initializeStatsColletion(){this.diagnosticProvider.initialize(),this.statsTimer=window.setInterval((()=>{this.eventsHandler&&(this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()))}),this.statsInterval)}stopStatsCollection(){this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),-1!==this.statsTimer&&window.clearInterval(this.statsTimer),this.statsTimer=-1}updateVideoTrackHistoryStatistic(){const g=new Date;if(this.currentVideoPlaybackBitrate){const f=this.diagnosticProvider.getValue("videoTrackHistory"),S=this.diagnosticProvider.getValue("videoTrackTotalDurations");if(f.length>0&&this.currentVideoPlaybackBitrate===f[f.length-1].trackPlaybackBitrate){if(this.videoTrackHistoryUpdatedTimestamp){this.latestVideoTrackDuration+=(g.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,f[f.length-1].durationInSeconds=Number(this.latestVideoTrackDuration.toFixed(0));const v=this.videoTrackTotalDurations.find((g=>g.trackPlaybackBitrate===this.currentVideoPlaybackBitrate)),C=S.find((g=>g.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));v&&C&&(v.totalDurationInSeconds+=(g.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,C.totalDurationInSeconds=Number(v.totalDurationInSeconds.toFixed(0)))}}else{const v=this.playerInstance.videoBufferData();let C=null;v&&v.perceivedBandwidth&&(C=v.perceivedBandwidth),f.push({trackPlaybackBitrate:this.currentVideoPlaybackBitrate,trackSwitchTimestamp:g.getTime(),trackSwitchMeasuredBandwidth:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredBandwidth():null,trackSwitchMeasuredByteSize:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredVideoDownloadSize():null,trackSwitchPerceivedBandwidth:C,durationInSeconds:0}),this.latestVideoTrackDuration=0,f.length>this.configProvider.config.maxVideoTrackHistoryLogCount&&f.splice(0,1);const _=this.videoTrackTotalDurations.find((g=>g.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));if(!_){const g={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0},f={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0};this.videoTrackTotalDurations.push(g),S.push(f)}}}this.videoTrackHistoryUpdatedTimestamp=g}updateTotalPlayingTimeStatistic(){const g=new Date;this.isPlaying&&this.totalPlayingTimeUpdatedTimestamp&&(this.totalPlayingTime+=g.getTime()-this.totalPlayingTimeUpdatedTimestamp.getTime()),this.totalPlayingTimeUpdatedTimestamp=g,this.diagnosticProvider.setValue("totalPlayingTimeInSeconds",Number((this.totalPlayingTime/1e3).toFixed(0)))}updateBufferingRateStatistic(){const g=new Date;this.isBuffering&&this.bufferingRateStatUpdatedTimestamp&&(this.totalBufferingTime+=g.getTime()-this.bufferingRateStatUpdatedTimestamp.getTime()),this.bufferingRateStatUpdatedTimestamp=g;const f=this.totalPlayingTime>0||this.totalBufferingTime>0?this.totalBufferingTime/(this.totalPlayingTime+this.totalBufferingTime):0;this.diagnosticProvider.setValue("bufferingRate",Number(f.toFixed(3)))}getPlayerDiagnostics(){const g=this.diagnosticProvider.getPlayerDiagnosticSnapshot();return g.statsInterval=this.statsInterval,this.configProvider.config.debug&&(g.memoryLog=this.playerInstance.getMemoryLog(!0)),g}log(g,f="info"){const S=`${`[AmpPlayer${1===this.configProvider.config.loadType?"IFrame":""}]`}: ${g}`;this.configProvider.config.debug&&console.log(S),this.eventsHandler.message("log").send(f,S)}getElementLoadPromise(g,f){return new Promise(((S,v)=>{g.onload=()=>{S("Element Load success")},g.onerror=()=>{v(`Failed to load script: ${f}`)}}))}loadCss(g,f,S){const v=g.createElement("link"),C=this.getElementLoadPromise(v,f);return v.href=f,v.rel="stylesheet",S&&(v.nonce=S),g.head.appendChild(v),C}parseJson(g,f){try{return JSON.parse(g)}catch(g){throw this.log(`Error parsing JSON for ${f}, error: ${JSON.stringify(g)}`),g}}}}AmpPlayerF();function AmpCommunicationHandlerF(){const g=AmpPlayerF();return class{constructor(f,S){this.pipe=f,this.amp=new g(S,this)}processMessage(g){if("Command"===g.msgType){Promise.resolve().then((()=>this.amp[g.cmd].apply(this.amp,g.args))).then((f=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:g.cmd,result:JSON.stringify(f)})})).catch((f=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:g.cmd,error:f})}))}}message(g){return{send:this.fromMessage(((...f)=>{this.sendMessageImpl(g,f)}))}}ampDisposed(){this.pipe.dispose(),this.pipe=null,this.amp=null}fromMessage(g){return g}sendMessageImpl(g,f){this.pipe.sendMsg({msgType:"PlayerNotification",name:g,args:f})}}}var gt=AmpCommunicationHandlerF();function IFrameMessageHandlerF(){function isCmdResult(g){return"CommandResult"===g.msgType}function getErrorString(g){let f="unknown";try{f="string"==typeof g?g:"toString"in g&&0!==g.toString().indexOf("[object")?g.toString():JSON.stringify(g)}catch(f){console.error("Failed to stringify error",g)}return f}return class{constructor(){this.processMsg=this.processMsg.bind(this),window.addEventListener("message",this.processMsg)}sendMsg(g){try{let f=g;isCmdResult(g)&&g.error instanceof Event&&(console.debug("Stringifying error Event before trying to postMessage:",g),f={msgType:g.msgType,cmd:g.cmd,error:`Event: ${getErrorString(g.error)}`}),this.postMessage(f)}catch(f){console.error("Unexpected exception caught from postMessage.\n","message:",g,"\n","exception:",f);const S={msgType:"PlayerNotification",name:"log",args:["error",`Unexpected error with postMessage: ${getErrorString(f)}`]};throw this.postMessage(S),f}}registerObserver(g){this.observer=g}dispose(){window.removeEventListener("message",this.processMsg),this.observer=null}processMsg(g){this.observer.processMessage(g.data)}postMessage(g){window.parent.postMessage(g,"*")}}}function HlsAbsoluteTimeOffsetEstimatorF(){const g=HlsFileParserF();return class{constructor(f){this.playlistFileDownloadPromise=Promise.resolve(),this.playlistFileDownloadRetryWaitTime=250,this.playlistFileDownloadMaxRetryCount=20,this.playlistFileDownloadCancellationFlag=!1,this.logFn=(g,S)=>f(`[HlsAbsoluteTimeOffsetEstimator]: ${g}`,S),this.hlsFileParser=new g(f)}get absoluteTimeOffset(){return this.estimatedAbsoluteTimeOffset}setEstimationResultCallback(g){this.onAbsoluteTimeOffsetEstimation=g}restartStreamAbsoluteTimeOffsetRetrieval(){this.stopStreamAbsoluteTimeOffsetRetrieval().then((()=>this.startStreamAbsoluteTimeOffsetRetrieval()))}setManifestFileURL(g){this.cachedManifestUrl=g}startStreamAbsoluteTimeOffsetRetrieval(){this.playlistFileDownloadPromise=this.retryPlaylistFileDownload((()=>this.estimateStreamTimeFromPlaylist(this.currentManifestUrl))).then((()=>{this.logFn(`Succeeded in downloading playlist files to estimate\n                    absolute stream time offset as: ${this.estimatedAbsoluteTimeOffset}`)})).catch((g=>{this.logFn(`Failed to download playlist files to estimate absolute stream time offset: ${g.message}`,"error")}))}stopStreamAbsoluteTimeOffsetRetrieval(){return this.playlistFileDownloadCancellationFlag=!0,this.playlistFileDownloadPromise.then((()=>{this.playlistFileDownloadCancellationFlag=!1,this.currentManifestUrl=this.cachedManifestUrl,this.cachedManifestUrl=null}))}retryPlaylistFileDownload(g,f=0){let S=Promise.resolve();return S=g().then((()=>(this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:f,isSuccess:!0,absoluteTimeOffsetEstimation:this.absoluteTimeOffset}),Promise.resolve()))).catch((S=>(f++,this.logFn(`Error loading playlist file: ${S} -- attempt ${f}`),this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:f,isSuccess:!1,error:S.message}),f===this.playlistFileDownloadMaxRetryCount?Promise.reject(new Error(`${S} after ${f} attempts`)):this.playlistFileDownloadCancellationFlag?Promise.reject(new Error("cancelling playlist file download")):new Promise((S=>setTimeout((()=>S(this.retryPlaylistFileDownload(g,f))),this.playlistFileDownloadRetryWaitTime)))))),S}estimateStreamTimeFromPlaylist(g){return this.hlsFileParser.getStreamRenditionsUrlsFromManifest(g).then((f=>{if(0===f.audioRenditions.length&&0===f.videoRenditions.length)throw new Error(`Unable to retrieve renditions URLs from manifest: ${g}`);return Promise.all([f.videoRenditions.length>0?this.hlsFileParser.getTextFileContent(f.videoRenditions[0]):Promise.resolve(null),f.audioRenditions.length>0?this.hlsFileParser.getTextFileContent(f.audioRenditions[0]):Promise.resolve(null)])})).then((g=>{let f;for(let S=0;S<g.length;S++){const v=g[S];if(v){this.logFn("Using segment duration and sequence number to calculate absolute time offset","debug");const g=this.hlsFileParser.getHlsFieldByName("SequenceNumber",v);if(0==g.length)throw new Error("Unable to retrieve sequence number from playlist file");const S=this.hlsFileParser.getHlsFieldByName("SegmentDuration",v,10);if(0==S.length)throw new Error("Unable to retrieve segment durations from playlist file");const C=S.map(Number);C.sort(((g,f)=>g-f));const _=C[Math.floor(C.length/2)],T=Number(g[0])*Number(_);f=f?Math.max(f,T):T}}this.estimatedAbsoluteTimeOffset=f}))}}}var pt=HlsAbsoluteTimeOffsetEstimatorF();function HlsFileParserF(){return class{constructor(g){this.fieldNameRegexMap={BaseUrl:/(.*)\/.*/,AudioManifestFile:/#EXT-X-MEDIA:TYPE=AUDIO.*URI=\"(.*)\"/,SequenceNumber:/#EXT-X-MEDIA-SEQUENCE:(\d+)/,SegmentDuration:/#EXTINF:(\d+(\.\d+)?)/},this.logFn=(f,S)=>g(`[HlsFileParser]: ${f}`,S)}getHlsFieldByName(g,f,S=1){const v=[];for(let C=1;C<=S;C++){const S=this.fieldNameRegexMap[g].exec(f);if(!(S&&S.length>0))break;v.push(S[1]),f=f.substring(S.index+S[0].length)}return v}getStreamRenditionsUrlsFromManifest(g){return g?this.getTextFileContent(g).then((f=>{const S={audioRenditions:[],videoRenditions:[]},v=f.split("\n"),C=this.getHlsFieldByName("BaseUrl",g);for(let g=0;g<v.length;g++)if(v[g].includes("#EXT-X-STREAM-INF")){const f=v[g+1];f.includes("http")?S.videoRenditions.push(f):C.length>0&&S.videoRenditions.push(`${C[0]}/${f}`)}else if(v[g].includes("EXT-X-MEDIA:TYPE")){const f=this.getHlsFieldByName("AudioManifestFile",v[g]);if(f.length>0){const g=f[0];g.includes("http")?S.audioRenditions.push(g):C.length>0&&S.audioRenditions.push(`${C[0]}/${g}`)}}return S})).catch((g=>(this.logFn(`Failed to extract stream renditions from manifest, error: ${g.message}`,"error"),{audioRenditions:[],videoRenditions:[]}))):(this.logFn("No manifest URL provided to parse"),Promise.resolve({audioRenditions:[],videoRenditions:[]}))}getTextFileContent(g){const f=fetch(g).then((f=>{if(!f.ok)throw new Error(`http-error ${f.status} when downloading: ${g}`);return f.text()})).catch((g=>(this.logFn(`Error downloading resource: ${g}`,"error"),Promise.reject(g))));return f}}}function AmpDiagnosticProviderF(){return class{constructor(g,f,S,v,C){this.playerInstance=g,this.contextWindow=f,this.streamingStartedTimestamp=S,this.configProvider=v,this.absoluteTimeOffsetEstimator=C,this.currentDiagnosticSnapshot={playerType:0,currentPlayPosition:null,tech:null,perceivedBandwidth:null,playerHeight:null,playerWidth:null,mediaHeight:null,mediaWidth:null,windowHeight:null,windowWidth:null,videoStream:null,audioStream:null,totalDurationInSeconds:null,avgVideoDownloadLatency:null,avgAudioDownloadLatency:null,avgVideoDownloadBytes:null,avgAudioDownloadBytes:null,avgAudioDownloadBandwidth:null,avgVideoDownloadBandwidth:null,maxVideoDownloadBytes:null,minVideoDownloadBytes:null,videoDownloadSuccessCount:null,audioDownloadSuccessCount:null,videoDownloadFailureCount:null,audioDownloadFailureCount:null,videoBufferLength:null,videoCachedLength:null,audioBufferLength:null,audioCachedLength:null,videoEdgeLatency:null,audioEdgeLatency:null,playbackRate:null,playbackBitrate:null,downloadBitrate:null,audioDownloadBitrate:null,audioPlaybackBitrate:null,isFullscreen:null,streamType:null,playerVersion:null,isP2PSdnUsed:null,sdnName:null,livePosition:null,muted:null,volume:null,errorCode:null,currentMediaTime:null,currentAbsoluteTime:null,absoluteTimeOffsetEstimationResults:null,estimatedAbsoluteTimeOffset:null,videoDownloadFailures:null,audioDownloadFailures:null,heuristicProfile:null,encryption:null,retryFrequency:null,averageDownloadBitrate:null,totalDownloadedBytes:0,streamId:null,streamUrl:null,streamingEventType:null,playerControlsEnabled:null,streamDeliveryPipeline:null,retryCount:0,totalPlayingTimeInSeconds:0,bufferingRate:0,videoTrackHistory:[],videoTrackTotalDurations:[],memoryLog:null,statsInterval:null},this.videoDownloadLatencies=[],this.audioDownloadLatencies=[],this.audioDownloadBytes=[],this.videoDownloadBytes=[],this.audioDownloadBandwidths=[],this.videoDownloadBandwidths=[],this.videoDownloadSuccessCount=0,this.audioDownloadSuccessCount=0,this.videoDownloadFailureCount=0,this.audioDownloadFailureCount=0,this.audioDownloadFailures=[],this.videoDownloadFailures=[],this.totalDownloadedBytes=0,this.slidingWindowLengthForLatency=5,this.slidingWindowLengthForDownloadBytes=30,this.slidingWindowLengthForDownloadBandwidth=10,this.absoluteTimeOffsetEstimationResults=[],this.downloadFailuresLimit=10,this.onAudioDownloadCompleted=this.onAudioDownloadCompleted.bind(this),this.onAudioDownloadError=this.onAudioDownloadError.bind(this),this.onVideoDownloadCompleted=this.onVideoDownloadCompleted.bind(this),this.onVideoDownloadError=this.onVideoDownloadError.bind(this)}initialize(){this.playerVideoBuffer=this.playerInstance.videoBufferData(),this.playerAudioBuffer=this.playerInstance.audioBufferData(),this.registerForPlayerBufferEvents()}setValue(g,f){this.currentDiagnosticSnapshot[g]=f}getValue(g){return this.currentDiagnosticSnapshot[g]}appendAbsoluteTimeOffsetEstimation(g){this.absoluteTimeOffsetEstimationResults.push(g),this.absoluteTimeOffsetEstimationResults.length>this.configProvider.config.ampSettings.maxAbsoluteTimeOffsetEstimationResultsLogCount&&this.absoluteTimeOffsetEstimationResults.splice(0,1)}getPlayerDiagnosticSnapshot(){if(!this.playerInstance)return null;const g=window.screen,f=this.playerInstance.error(),mean5=g=>{const f=g.slice().sort();return f[Math.floor(f.length/2)]};this.currentDiagnosticSnapshot.errorCode=f&&f.code||0,this.currentDiagnosticSnapshot.currentPlayPosition=this.playerInstance.currentTime(),this.currentDiagnosticSnapshot.currentMediaTime=this.playerInstance.currentMediaTime()??this.playerInstance.currentTime(),this.currentDiagnosticSnapshot.currentAbsoluteTime=this.getCurrentAbsoluteTime(),this.currentDiagnosticSnapshot.absoluteTimeOffsetEstimationResults=this.absoluteTimeOffsetEstimationResults,this.currentDiagnosticSnapshot.estimatedAbsoluteTimeOffset=this.getCurrentAbsoluteTimeOffset(),this.currentDiagnosticSnapshot.playbackBitrate=this.playerInstance.currentPlaybackBitrate(),this.currentDiagnosticSnapshot.downloadBitrate=this.playerInstance.currentDownloadBitrate(),this.currentDiagnosticSnapshot.audioDownloadBitrate=this.lastAudioDownloadBitrate,this.currentDiagnosticSnapshot.perceivedBandwidth=this.playerVideoBuffer?this.playerVideoBuffer.perceivedBandwidth:0,this.currentDiagnosticSnapshot.tech=this.playerInstance.currentTechName(),this.currentDiagnosticSnapshot.playerVersion=this.playerInstance.getAmpVersion(),this.currentDiagnosticSnapshot.isP2PSdnUsed=this.isP2PSdnUsed(),this.currentDiagnosticSnapshot.sdnName=this.sdnName(),this.currentDiagnosticSnapshot.heuristicProfile=this.playerInstance.currentHeuristicProfile(),this.currentDiagnosticSnapshot.encryption=this.playerInstance.currentProtectionInfo()?this.playerInstance.currentProtectionInfo().type:"",this.currentDiagnosticSnapshot.streamType=this.getStreamType(this.currentDiagnosticSnapshot.streamType),this.currentDiagnosticSnapshot.totalDurationInSeconds=this.getTotalDurationInSeconds(),this.currentDiagnosticSnapshot.audioStream=this.getAudioStreamData(),this.currentDiagnosticSnapshot.videoStream=this.getVideoStreamData(),this.currentDiagnosticSnapshot.muted=this.playerInstance.muted(),this.currentDiagnosticSnapshot.volume=this.playerInstance.volume(),this.currentDiagnosticSnapshot.playbackRate=this.playerInstance.playbackRate();const S=this.getPlayerCachedLength(),v=this.getPlayerEdgeLatency();this.currentDiagnosticSnapshot.audioBufferLength=this.playerAudioBuffer?this.playerAudioBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.audioCachedLength=S,this.currentDiagnosticSnapshot.audioEdgeLatency=v,this.currentDiagnosticSnapshot.videoBufferLength=this.playerVideoBuffer?this.playerVideoBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.videoCachedLength=S,this.currentDiagnosticSnapshot.videoEdgeLatency=v,this.currentDiagnosticSnapshot.livePosition=this.getLivePosition(),this.currentDiagnosticSnapshot.mediaHeight=this.playerInstance.videoHeight(),this.currentDiagnosticSnapshot.mediaWidth=this.playerInstance.videoWidth(),this.currentDiagnosticSnapshot.playerHeight=this.playerInstance.height(),this.currentDiagnosticSnapshot.playerWidth=this.playerInstance.width(),this.currentDiagnosticSnapshot.windowHeight=g?g.height:0,this.currentDiagnosticSnapshot.windowWidth=g?g.width:0,this.currentDiagnosticSnapshot.isFullscreen=this.playerInstance.isFullscreen(),this.currentDiagnosticSnapshot.avgAudioDownloadLatency=mean5(this.audioDownloadLatencies),this.currentDiagnosticSnapshot.avgVideoDownloadLatency=mean5(this.videoDownloadLatencies),this.currentDiagnosticSnapshot.avgAudioDownloadBytes=mean5(this.audioDownloadBytes),this.currentDiagnosticSnapshot.avgVideoDownloadBytes=mean5(this.videoDownloadBytes),this.currentDiagnosticSnapshot.maxVideoDownloadBytes=Math.max.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.minVideoDownloadBytes=Math.min.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.avgAudioDownloadBandwidth=mean5(this.audioDownloadBandwidths),this.currentDiagnosticSnapshot.avgVideoDownloadBandwidth=mean5(this.videoDownloadBandwidths),this.currentDiagnosticSnapshot.audioDownloadFailureCount=this.audioDownloadFailureCount,this.currentDiagnosticSnapshot.audioDownloadSuccessCount=this.audioDownloadSuccessCount,this.currentDiagnosticSnapshot.videoDownloadFailureCount=this.videoDownloadFailureCount,this.currentDiagnosticSnapshot.videoDownloadSuccessCount=this.videoDownloadSuccessCount,this.currentDiagnosticSnapshot.audioDownloadFailures=this.audioDownloadFailures,this.currentDiagnosticSnapshot.videoDownloadFailures=this.videoDownloadFailures,this.currentDiagnosticSnapshot.totalDownloadedBytes=this.totalDownloadedBytes,this.currentDiagnosticSnapshot.retryFrequency=this.getRetryFrequency(),this.currentDiagnosticSnapshot.averageDownloadBitrate=this.getAverageDownloadBitrate();const C=this.getDiagnosticWritableField();return Object.keys(C).forEach((g=>{this.currentDiagnosticSnapshot[g]=C[g]})),this.currentDiagnosticSnapshot}getDiagnosticWritableField(){return{streamUrl:this.currentDiagnosticSnapshot.streamUrl,streamId:this.currentDiagnosticSnapshot.streamId,streamingEventType:this.currentDiagnosticSnapshot.streamingEventType,playerControlsEnabled:this.currentDiagnosticSnapshot.playerControlsEnabled,streamDeliveryPipeline:this.currentDiagnosticSnapshot.streamDeliveryPipeline,retryCount:this.currentDiagnosticSnapshot.retryCount,totalPlayingTimeInSeconds:this.currentDiagnosticSnapshot.totalPlayingTimeInSeconds,bufferingRate:this.currentDiagnosticSnapshot.bufferingRate,videoTrackHistory:this.currentDiagnosticSnapshot.videoTrackHistory,videoTrackTotalDurations:this.currentDiagnosticSnapshot.videoTrackTotalDurations,eventId:this.currentDiagnosticSnapshot.eventId||"",templateId:this.currentDiagnosticSnapshot.templateId||""}}dispose(){this.unsubscribeFromPlayerBufferEvents()}registerForPlayerBufferEvents(){this.playerVideoBuffer&&(this.playerVideoBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onVideoDownloadCompleted),this.playerVideoBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onVideoDownloadError)),this.playerAudioBuffer&&(this.playerAudioBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onAudioDownloadCompleted),this.playerAudioBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onAudioDownloadError))}unsubscribeFromPlayerBufferEvents(){this.playerVideoBuffer&&(this.playerVideoBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onVideoDownloadCompleted),this.playerVideoBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onVideoDownloadError)),this.playerAudioBuffer&&(this.playerAudioBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onAudioDownloadCompleted),this.playerAudioBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onAudioDownloadError))}isP2PSdnUsed(){return!!this.sdnName()}sdnName(){const g="options_";return this.playerInstance[g]&&this.playerInstance[g].sdn&&this.playerInstance[g].sdn.name}getStreamType(g){let f="";return this.playerInstance&&(f=this.playerInstance.isLive()?"LIVE":"DVR"),""===f||"LIVE"===g&&f!==g?g||"":f}getCurrentAbsoluteTime(){return this.absoluteTimeOffsetEstimator?this.absoluteTimeOffsetEstimator.absoluteTimeOffset?this.absoluteTimeOffsetEstimator.absoluteTimeOffset+this.playerInstance.currentTime():this.playerInstance.currentTime():this.playerInstance.currentAbsoluteTime()??this.playerInstance.currentTime()}getCurrentAbsoluteTimeOffset(){return this.getCurrentAbsoluteTime()-this.playerInstance.currentTime()}getTotalDurationInSeconds(){const g=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;return Number(g.toFixed(0))}onVideoDownloadCompleted(){this.videoDownloadSuccessCount++,this.addToList(this.videoDownloadLatencies,this.playerVideoBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForLatency),this.addToList(this.videoDownloadBytes,this.playerVideoBuffer.downloadCompleted.totalBytes,this.slidingWindowLengthForDownloadBytes),this.addToList(this.videoDownloadBandwidths,8*this.playerVideoBuffer.downloadCompleted.totalBytes*1e3/this.playerVideoBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForDownloadBandwidth),this.totalDownloadedBytes+=this.playerVideoBuffer.downloadCompleted.totalBytes}onAudioDownloadCompleted(){this.audioDownloadSuccessCount++,this.addToList(this.audioDownloadLatencies,this.playerAudioBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForLatency),this.addToList(this.audioDownloadBytes,this.playerAudioBuffer.downloadCompleted.totalBytes,this.slidingWindowLengthForDownloadBytes),this.addToList(this.audioDownloadBandwidths,8*this.playerAudioBuffer.downloadCompleted.totalBytes*1e3/this.playerAudioBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForDownloadBandwidth),this.totalDownloadedBytes+=this.playerAudioBuffer.downloadCompleted.totalBytes;const g=this.playerAudioBuffer.downloadCompleted.mediaDownload.bitrate;g!==this.lastAudioDownloadBitrate&&(this.lastAudioDownloadBitrate=g)}addToList(g,f,S){g.push(f),g.length>S&&g.shift()}onVideoDownloadError(){this.videoDownloadFailureCount++,this.addDownloadFailureInfo(this.playerVideoBuffer.downloadFailed,this.videoDownloadFailures)}onAudioDownloadError(){this.audioDownloadFailureCount++,this.addDownloadFailureInfo(this.playerAudioBuffer.downloadFailed,this.audioDownloadFailures)}addDownloadFailureInfo(g,f){const S={bitrate:g.mediaDownload.bitrate,errorCode:g.code,mediaTime:g.mediaDownload.mediaTime,message:g.message,timestamp:Date.now()};this.addToList(f,S,this.downloadFailuresLimit)}getAudioStreamData(){const g=this.playerInstance.currentAudioStreamList();if(g)try{const f=g.streams[g.enabledIndices[0]];return{bitrate:f.bitrate,codec:f.codec,enabled:f.enabled,name:f.name,language:f.language}}catch(g){return}}getVideoStreamData(){const g=this.playerInstance.currentVideoStreamList();if(g)try{const f=g.streams[g.selectedIndex],S=this.playerInstance.currentPlaybackBitrate(),mapTrackData=g=>({bitrate:g.bitrate,height:g.height,id:g.id,selectable:g.selectable,width:g.width}),v=f.tracks?f.tracks.map(mapTrackData).find((g=>g.bitrate===S)):null;return{codec:f.codec,name:f.name,currentTrack:v}}catch(g){return}}getLivePosition(){const g=this.playerInstance.buffered();if(0===g.length)return 0;let f=g.end(0);for(let S=1;S<g.length;S++)f=Math.max(f,g.end(S));return f}getAverageDownloadBitrate(){if(this.streamingStartedTimestamp&&this.totalDownloadedBytes){const g=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;if(g>0)return 8*this.totalDownloadedBytes/g}return 0}getRetryFrequency(){const g=this.currentDiagnosticSnapshot.retryCount;if(this.streamingStartedTimestamp&&g){const f=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/6e4;if(f>0)return g/f}return 0}getAverageMeasuredBandwidth(){if(0===this.videoDownloadBandwidths.length)return null;let g=0;for(let f=0;f<this.videoDownloadBandwidths.length;f++)g+=this.videoDownloadBandwidths[f];return g/this.videoDownloadBandwidths.length}getAverageMeasuredVideoDownloadSize(){if(0===this.videoDownloadBytes.length)return null;let g=0;for(let f=0;f<this.videoDownloadBytes.length;f++)g+=this.videoDownloadBytes[f];return g/this.videoDownloadBytes.length}getPlayerCachedLength(){const g=this.playerInstance.buffered();let f=0;for(let S=0;S<g.length;S++)f+=g.end(S)-g.start(S);return f}getPlayerEdgeLatency(){const g=this.playerInstance.buffered();if(0===g.length)return 0;let f=g.end(0);for(let S=1;S<g.length;S++)f=Math.max(f,g.end(S));return f-this.playerInstance.currentTime()}}}function CaptionsControlToggleProviderF(){return class{constructor(g,f,S,v){this.player=g,this.toggleListener=f,this.config=S,this.diagnosticProvider=v,this.onTextTrackChanged=this.onTextTrackChanged.bind(this),this.isHtml5Tech="html5"===this.player.currentTechName()?.toLowerCase()}dispose(){this.unsubscribeFromTrackEvents(),this.player=null,this.toggleListener=null}initialize(){const g=this.getPlayerTextTracksAsArray();if(!this.config.controlsEnabled&&g.length>0)g[0].mode="showing";else for(let f=0;f<g.length;f++)g[f].mode="disabled";this.subscribeOnTrackEvents()}addCues(g){const f=this.player.getCurrentTextTrack();if(!f)return;const S=this.getCurrentAbsoluteTime()||1,v=this.getCurrentTime(),C=this.config.controlsEnabled?S-v:Math.max(S-v,0),_=this.isHtml5Tech?window.VTTCue:window.vttjs&&window.vttjs.VTTCue||window.VTTCue;for(let S=0;S<g.length;S++){const{start:v,end:T,text:I}=g[S],b=2,A=new _(Number((v-C).toFixed(b)),Number((T-C).toFixed(b)),I);A.size=100,!this.containsCue(f,A)&&f.addCue(A)}}clearCues(){const g=this.player.getCurrentTextTrack();if(g)try{if(g.activeCues&&g.removeCue)for(;g.activeCues.length>0;)g.removeCue(g.activeCues[0]);const f="setCues_";if(g.cues[f]){g.cues_&&(g.cues_.length=0),g.cues[f]([]);const S=Object.getOwnPropertyNames(g.cues);for(let f=0;f<S.length;f++)"length"!==S[f]&&"length_"!==S[f]&&"cues_"!==S[f]&&delete g.cues[S[f]]}}catch(g){this.config.logFn(`[clearCues]: ${g}`,"warn")}}showCaptions(g){this.config.logFn(`[CaptionsControl]: showCaptions(${g})`),g?this.show():this.hide()}hide(){this.previouslyVisibleTextTrack=this.player.getCurrentTextTrack(),this.previouslyVisibleTextTrack&&(this.previouslyVisibleTextTrack.mode="disabled"),this.player.captionToggle&&this.player.captionToggle.hide&&this.player.captionToggle.hide(),this.player.MoreOptionscaptionSubtitleButton&&this.player.MoreOptionscaptionSubtitleButton.hide&&this.player.MoreOptionscaptionSubtitleButton.hide(),this.player.MoreOptionscaptionSettingsButton&&this.player.MoreOptionscaptionSettingsButton.hide&&this.player.MoreOptionscaptionSettingsButton.hide()}show(){this.previouslyVisibleTextTrack&&(this.previouslyVisibleTextTrack.mode="showing"),this.player.captionToggle&&this.player.captionToggle.show&&this.player.captionToggle.show(),this.player.MoreOptionscaptionSubtitleButton&&this.player.MoreOptionscaptionSubtitleButton.show&&this.player.MoreOptionscaptionSubtitleButton.show(),this.player.MoreOptionscaptionSettingsButton&&this.player.MoreOptionscaptionSettingsButton.show&&this.player.MoreOptionscaptionSettingsButton.show()}subscribeOnTrackEvents(){const g=this.player.textTracks(),f="addEventListener";g&&g[f]&&(this.config.controlsEnabled&&g[f]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&g[f]("addtrack",this.onAddTrack.bind(this)))}unsubscribeFromTrackEvents(){const g=this.player.textTracks(),f="removeEventListener";g&&g[f]&&(this.config.controlsEnabled&&g[f]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&g[f]("addtrack",this.onAddTrack.bind(this)))}onTextTrackChanged(){const g=this.player.getCurrentTextTrack();if(!g||!this.currentTextTrack||this.currentTextTrack.label!==g.label||this.currentTextTrack.mode!==g.mode){if(g||this.currentTextTrack){const f=!!g&&"showing"===g.mode,S=this.getCulture(g||this.currentTextTrack),v=this.getCurrentTime();this.toggleListener.captionsToggled(f,S,v),this.config.logFn(`[CaptionsControl]: track changed: culture '${S}', timestamp '${v}'`)}this.currentTextTrack=g}}onAddTrack(g){const f=g?.track;"captions"===f?.kind&&!f.label&&!f.id&&(this.player?.textTracks_?.removeTrack_(f),this.config.logFn("[CaptionsControl]: removing default empty text track"))}getCurrentTime(){return this.isHtml5Tech?this.player.currentTime():(this.config.controlsEnabled?this.player.currentTime():this.player.currentMediaTime())||1}getCurrentAbsoluteTime(){return this.diagnosticProvider.getCurrentAbsoluteTime()}getCulture(g){if(!g)return"";if(g.id){const f=g.id.split("_")[1];if(f)return f}return""}getPlayerTextTracksAsArray(){const g=this.player.textTracks();return g&&g["tracks_"]||[]}containsCue(g,f){return Array.from(g?.cues||[]).some((g=>this.areCueEquals(g,f)))}areCueEquals(g,f){function getCueField(g){return{start:g.start?g.start:g.startTime,end:g.end?g.end:g.endTime,text:g.text}}const S=getCueField(g),v=getCueField(f);return S.start===v.start&&S.end===v.end&&S.text===v.text}}}function initIFrame(){const g=IFrameMessageHandlerF(),f=AmpCommunicationHandlerF(),S=new g,v=new f(S,document.body);S.registerObserver(v)}function buildAmpEmbeddedSrc(){let g=`(${initIFrame.toString()})();`;return g+=AmpPlayerF.toString()+";",g+=IFrameMessageHandlerF.toString()+";",g+=AmpCommunicationHandlerF.toString()+";",g+=CaptionsControlToggleProviderF.toString()+";",g+=AmpDiagnosticProviderF.toString()+";",g+=HlsAbsoluteTimeOffsetEstimatorF.toString()+";",g+=HlsFileParserF.toString()+";",g+="//# sourceURL=TsCallingAmpPlayer.js",g}var mt=class{sendMsg(g){this.peer.onMsg(g)}registerObserver(g){this.observer=g}onMsg(g){this.observer&&this.observer.processMessage(g)}connect(g){this.peer=g}dispose(){this.peer=null,this.observer=null}},ft=class{constructor(g){this.container=g}get contextWindow(){return this.container.ownerDocument.defaultView}sendMsg(g){this.iframe?.contentWindow?.postMessage(g,"*")}registerObserver(g){this.observer=g}dispose(){this.contextWindow&&this.contextWindow.removeEventListener("message",this.processMsg),this.iframe&&this.container.hasChildNodes()&&this.container.removeChild(this.iframe),this.iframe=null}initializeAmpIframe(g){const f=this.initializeIframe();return this.setAmpIframeContent(g),this.finalizeIframe(f)}initializeIframe(){const g=new dt;return this.iframe=this.container.ownerDocument.createElement("iframe"),this.iframe.id="player-iframe",this.iframe.sandbox.add("allow-scripts"),this.iframe.allowFullscreen=!0,this.iframe.allow="camera; microphone; autoplay",this.iframe.style.height="100%",this.iframe.style.width="100%",this.iframe.style.border="none",this.iframe.onload=()=>{g.resolve()},this.iframe.onerror=()=>{g.reject("iframe load failed")},g}finalizeIframe(g){return this.container.appendChild(this.iframe),this.processMsg=this.processMsg.bind(this),this.contextWindow.addEventListener("message",this.processMsg),g.promise}processMsg(g){if("null"===g.origin&&g.source===this.iframe.contentWindow&&this.observer)if("RequestIceCandidates"===g.data)this.observer.processMessage({msgType:"Command",cmd:"getIceCandidates",args:[]});else this.observer.processMessage(g.data)}setAmpIframeContent(g){const f=buildAmpEmbeddedSrc(),S=`\n            <html class style='height: 100%; width: 100%; overflow: hidden'>\n            <head></head>\n            <body class style='height: 100%; width: 100%; margin: 0px'>\n                ${g?`<script nonce='${g}'> ${f}<\/script>`:`<script> ${f}<\/script>`}\n            </body>\n            </html>\n        `;this.iframe.srcdoc=S}};async function setupAmpAndBuildPipe(g,f,S){if(0===f){const f=new mt,S=new mt;return f.connect(S),S.connect(f),S.registerObserver(new gt(S,g)),f}if(1===f){const f=new ft(g);return await f.initializeAmpIframe(S),f}throw new Error(`Unsupported communication type ${f}`)}var St=class extends Ke{constructor(g){super(g),this.logger=g,this.resultsMap=new Map,this.on("log",((g,f)=>{this.logger[g](f)}))}async initialize(g,f,S,v){const C={config:S.config,playerConfig:S.playerConfig},_=S.playerConfig?.nonce||"";this.pipe=await setupAmpAndBuildPipe(g,S.config.loadType,_),this.pipe.registerObserver(this),await this.message("configure").send(f,C,v)}message(g){return{send:this.fromMessage(((...f)=>this.sendMessageImpl(g,...f)))}}dispose(){super.dispose(),this.pipe.sendMsg(this.buildMsg("dispose")),this.pipe.dispose()}processMessage(g){let f;switch(g.msgType){case"CommandResult":f=this.getDeferred(g.cmd.toString()),f&&(g.error?(f.reject(g.error),this.logger.warn(`remote command failed: ${String(g.cmd)}, ${g.error}`)):g.result?f.resolve(g.result):f.resolve(),this.processCommandResult(g),this.resultsMap.delete(g.cmd.toString()));break;case"PlayerNotification":{const f=this.event(g.name);f.raise.apply(f,g.args);break}case"Command":this.processCommand(g).catch((f=>this.logger.warn(`error while processing command: ${JSON.stringify(g)}: ${f}`)));break;default:this.logger.warn(`unexpected message received: ${JSON.stringify(g)}`)}}async processCommand(g){if("getIceCandidates"===g.cmd.toString())await this.message("getIceCandidates").send();else this.logger.warn(`unsupported command received: ${JSON.stringify(g)}`)}processCommandResult(g){if("getIceCandidates"===g.cmd.toString())this.pipe.sendMsg({topic:"RequestIceCandidates",candidates:g.result});else this.logger.debug(`ignoring command result for: ${JSON.stringify(g)}`)}fromMessage(g){return g}sendMessageImpl(g,...f){return this.pipe.sendMsg(this.buildMsg(g,f)),this.waitForCompletion(g.toString())}buildMsg(g,f){return{msgType:"Command",cmd:g,args:f}}getDeferred(g){return this.resultsMap.get(g)}waitForCompletion(g){const f=this.getDeferred(g);f&&f.reject(new Error(`function ${g} is invoked again, before previous call is completed`));const S=new dt;return this.resultsMap.set(g,S),S.promise}},vt=class extends Ke{constructor(g,f){super(),this.player=g,this.logger=f,this.playerSubs=[],this.subscribeForPlayerEvents()}get isRendering(){return!!this.player&&this.player.isRendering()}get streamSize(){return this.player?this.player.getStreamSize():{width:0,height:0}}get rendererType(){return 0}get frameType(){return-1}seek(g){this.player.seek(g)}seekToLiveEdge(){this.player.seekToLiveEdge()}play(){this.player.play()}pause(){this.player.pause()}setVolume(g){this.player.setVolume(g)}selectVideoTrack(g){this.player.selectVideoTrack(g)}dispose(){this.stopPlayer(),super.dispose()}captions(){return this.player.getCaptionsControl()}getStats(){throw new Error("Method not implemented.")}setScalingMode(g,f){throw new Error("Method not implemented.")}captureFrame(g,f){throw new Error("Method not implemented.")}stopPlayer(){const g=this.player;this.player=null,g&&(this.logger.info("stopPlayer"),this.unsubscribeFromPlayerEvents(),g.stop())}subscribeForPlayerEvents(){this.playerSubs.push(this.player.on("fullscreenToggled",(g=>this.onFullScreenToggled(g)))),this.playerSubs.push(this.player.on("captionsToggled",((g,f,S)=>this.onCaptionsToggled(g,f,S)))),this.playerSubs.push(this.player.on("playbackTimeUpdated",(g=>this.onPlaybackTimeUpdated(g)))),this.playerSubs.push(this.player.on("videoTracksChanged",(g=>this.onVideoTracksChanged(g))))}unsubscribeFromPlayerEvents(){for(const g of this.playerSubs)g.dispose();this.playerSubs=[]}onFullScreenToggled(g){this.event("fullScreenToggled").raise(g)}onCaptionsToggled(g,f,S){this.logger.info(`Turned captions ${g?"ON":"OFF"} for culture [${f}] at player time [${S}]`),this.event("captionsToggled").raise(g,f,S)}onPlaybackTimeUpdated(g){this.event("playbackTimeUpdated").raise(g)}onVideoTracksChanged(g){this.event("videoTracksUpdated").raise(g)}},Ct=class{constructor(g,f){this.player=g,this.availableCultures=f,this.selectedCulture="",this.disposable=this.player.on("captionsToggled",((g,f,S)=>{this.selectedCulture=g?f:""}))}async addCues(g){await this.player.message("addCues").send(g)}async clearCues(){await this.player.message("clearCues").send()}async showCaptions(g){await this.player.message("showCaptions").send(g)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.disposable.dispose(),this.player=null}};function generateGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(g=>{const f=16*Math.random()|0;return("x"===g?f:3&f|8).toString(16)}))}function validateGuid(g){return new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(g)&&36===g.length}var yt=[2097152,2097552,2097556,2097557,2097564,2097652,2097654,2097655,2097656,2097752,3145728,4194305,4194306,4194307,4194308,4194309,5242880,5242881,5242882,5242884,5242885,5242886],Et=2097753,_t=class extends Ke{constructor(g,f,S){super(),this.logger=g,this.liveStreamStatistic=f,this.configProvider=S,this.playerState="Destroyed",this.retryCount=0,this.captionsTimestamp=0,this.isSwitchStreamingUrlOngoing=!1,this.streamingUrlSwitchCount=0,this.isPlaybackUnsupported=!1,this.noMediaTimeoutId=-1,this.lastPlaybackError=void 0,this.id=generateGuid(),this.logger.info(`AmpLiveStreamPlayer created: ID: ${this.id}`)}get playerId(){return this.id}async configure(g){if(!isStreamValid(g.stream)&&!isStreamValid(g.altStream))return void this.logger.error("Invalid Live Stream configuration provided: no valid primary or alternative stream");this.logger.info("Live Stream configuration provided"),this.liveStreamOptions=g;const f=isStreamValid(g.stream)?g.stream:g.altStream;if(this.playerInstance&&!this.isPlaybackUnsupported){try{await this.playerInstance.message("configure").send(g)}catch(g){const f=stringifyObject(g);this.logger.error(`configure failed: ${f}`)}await this.handleStreamInfoUpdate(f)}else this.selectedStreamDetails=f}async loadPlayer(g){if(this.playerInstance)return this.logger.error("playerLoadFailed: cannot load a player while current one is still active"),{setupSucceeded:!1,playerSetupError:{errorType:"MultiplePlayerLoad",errorMessage:"cannot load a player while current one is still active"}};if(!this.liveStreamOptions||!this.selectedStreamDetails||!isStreamValid(this.selectedStreamDetails))return this.logger.error("playerLoadFailed: empty/invalid primary and alternate stream info configured"),{setupSucceeded:!1,playerSetupError:{errorType:"InvalidStream",errorMessage:"empty/invalid primary and alternate stream info configured"}};this.playerInstance=new St(this.logger.createChild("AmpPlayerWrapper")),this.playerInstance.on("stateChanged",((g,f)=>this.ampStateChanged(g,f))),this.playerInstance.on("captionsToggled",((g,f,S)=>this.captionsToggled(g,f,S))),this.playerInstance.on("statsUpdated",(g=>this.liveStreamStatistic.registerStatsUpdated(g)));const f=this.configProvider.config.ampSettings.noMediaTimeoutMs;let S;-1!==f&&-1===this.noMediaTimeoutId&&(this.noMediaTimeoutId=self.setTimeout((()=>this.callDropDueToMediaTimeout()),f)),await this.playerInstance.initialize(g,this.liveStreamOptions,this.configProvider,this.id),this.liveStreamStatistic.registerPlayerLoadAttempt(),this.loadSucceeded=!1,this.liveStreamStatistic.registerEventLoadAttempt("LoadScript"),this.srcLoadPromise||(this.srcLoadPromise=this.playerInstance.message("loadPlayerScript").send());try{S=await this.srcLoadPromise}catch(g){const f=stringifyObject(g);return this.logger.error(`playerLoadFailed: player scripts load failed: ${f}`),this.liveStreamStatistic.registerEventLoadFailed("LoadScript",`Load Script failed: ${g}`),this.liveStreamStatistic.registerPlayerLoadFailed(`script load failed: ${S}`),this.srcLoadPromise=null,{setupSucceeded:!1,playerSetupError:{errorType:"PlayerScriptLoadFailed",errorMessage:f}}}this.liveStreamStatistic.registerEventLoadSucceeded("LoadScript"),await this.tryLoadSdnPlugin(),this.liveStreamStatistic.registerEventLoadAttempt("CreateAmp");try{await this.playerInstance.message("createAmp").send()}catch(g){const f=stringifyObject(g);return this.logger.error(`playerLoadFailed: createAmp failed: ${f}`),this.liveStreamStatistic.registerEventLoadFailed("CreateAmp",`createAmp failed: ${g}`),this.liveStreamStatistic.registerPlayerLoadFailed(`create amp failed ${f}, script load: ${S}`),{setupSucceeded:!1,playerSetupError:{errorType:"PlayerInitializationFailed",errorMessage:f}}}this.liveStreamStatistic.registerEventLoadSucceeded("CreateAmp");try{return await this.setPlayerSource(this.selectedStreamDetails),this.loadSucceeded=!0,this.logger.info(`loadPlayer succeeded: ${this.loadSucceeded}`),this.liveStreamStatistic.registerPlayerLoadSucceeded(S),this.playerState="Initialized",{setupSucceeded:this.loadSucceeded}}catch(g){const f=stringifyObject(g);return this.loadSucceeded=!1,this.logger.error(`loadPlayer succeeded: ${this.loadSucceeded}: setSource failed: ${f}`),this.liveStreamStatistic.registerPlayerLoadFailed(`setPlayerSource failed; script load: ${S}`),{setupSucceeded:this.loadSucceeded,playerSetupError:{errorType:"SetSourceFailed",errorMessage:f}}}}getRenderer(){return!this.renderer&&this.playerInstance&&(this.renderer=new vt(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}seek(g){throw new Error(`Method not implemented - cannot perform video seek operation with args: [timestamp: ${g}]`)}seekToLiveEdge(){throw new Error("Method not implemented - cannot perform video seek to live edge operation")}play(){throw new Error("Method not implemented - cannot perform video play operation")}pause(){throw new Error("Method not implemented - cannot perform video pause operation")}setVolume(g){throw new Error(`Method not implemented - cannot set video volume with args: [volume: ${g}]`)}selectVideoTrack(g){throw new Error(`Method not implemented - cannot select video track with args: [track: ${g}]`)}stop(){this.destroy("PlayerStopped")}getPlaybackState(){return this.playerState}getCaptionsTimestamp(){return this.captionsTimestamp}getCaptionsControl(){if(!this.captionsControl&&this.playerInstance){const g=this.liveStreamOptions.supportedSubtitleLanguages?this.liveStreamOptions.supportedSubtitleLanguages.map((g=>g.culture)):[];this.captionsControl=new Ct(this.playerInstance,g)}return this.captionsControl}getStreamSize(){const g=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return g?{width:g.mediaWidth,height:g.mediaHeight}:{width:0,height:0}}isRendering(){const g=this.getStreamSize();return g.width>0&&g.height>0}ampStateChanged(g,f){switch(g){case"error":return this.handlePlaybackError(f);case"canplaythrough":return this.onCanplaythrough();case"play":return this.onPlay();case"playing":return this.onPlaying();case"pause":return this.onPause();case"resume":return this.onResume();case"start":return this.onStart();case"ended":return this.onEnded();case"seeking":return this.onSeeking();case"seeked":return this.onSeeked(f);case"loadedmetadata":return this.onMetadataLoaded();case"waiting":return this.onWaiting();case"playbackbitratechanged":return this.onPlaybackBitrateChanged(f);case"downloadbitratechanged":return this.onDownloadBitrateChanged(f);case"fullscreenchange":return this.onFullscreenChange(f);case"potentialMediaFreeze":return this.onPotentialMediaFreeze();case"mute":return this.onMute();case"unmute":return this.onUnmute();case"volumechange":return this.onVolumeChange(f);case"loadstart":return this.onLoadStart();case"loadeddata":return this.onLoadedData();case"UserInitiatedSeek":return this.onUserInitiatedSeek(f);default:this.logger.warn(`Unknown amp event ${g}`)}}onUserInitiatedSeek(g){this.liveStreamStatistic.registerUserInitiatedSeek(g)}captionsToggled(g,f,S){this.event("captionsToggled").raise(g,f,S),this.liveStreamStatistic.registerCaptionToggle(g,f,S)}async tryLoadSdnPlugin(){if(this.sdnPluginLoadPromise)return void this.raiseSdnPluginSkippedEvent("SDN plugin already loaded");if(!this.liveStreamOptions.sdn)return void this.raiseSdnPluginSkippedEvent("No SDNs configured in liveStreamOptions");if(!this.configProvider.config.allowSdnPlugins)return void this.raiseSdnPluginSkippedEvent("Client configured to not allow SDN plugins");switch(this.liveStreamOptions.sdn.name){case"hive":case"kollective":case"ramp":case"peer5":break;default:return this.logger.warn(`unsupported SDN provider: ${this.liveStreamOptions.sdn.name}`),void this.liveStreamStatistic.registerSdnPluginLoad(this.liveStreamOptions.sdn.name,!1,`Unsupported SDN provider: ${this.liveStreamOptions.sdn.name}`)}let g;this.liveStreamStatistic.registerEventLoadAttempt("SdnPluginLoad");try{this.sdnPluginLoadPromise=this.playerInstance.message("tryLoadSdnPlugin").send(),await this.sdnPluginLoadPromise,this.liveStreamStatistic.registerEventLoadSucceeded("SdnPluginLoad",this.liveStreamOptions.sdn.name)}catch(f){g=stringifyObject(f),this.sdnPluginLoadPromise=void 0,this.logger.error(`loadSdnPlugin failed: ${g}`),this.liveStreamStatistic.registerEventLoadFailed("SdnPluginLoad",g),this.event("sdnPluginLoadFailed").raise(g)}}raiseSdnPluginSkippedEvent(g){this.logger.warn(`skipping SDN plugin load: ${g}`),this.event("sdnPluginLoadSkipped").raise(g)}async setPlayerSource(g){if(!g)throw this.logger.error("setPlayerSource: streamDetails is undefined"),new Error("setPlayerSource: streamDetails is undefined");if(!this.playerInstance)throw this.logger.error("setPlayerSource: playerInstance is null"),new Error("playerInstance is null");this.logger.info(`setPlayerSource: AMP source set to: [${g.url}]`),this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;try{this.logger.info("setPlayerSource: src changed"),this.selectedStreamDetails=g,this.liveStreamStatistic.registerSetSourceAttempt(g.url),await this.playerInstance.message("setSource").send(g),this.liveStreamStatistic.registerSetSourceSucceeded()}catch(g){const f=stringifyObject(g);throw this.logger.error(`setPlayerSource: failed with error [${f}]`),this.liveStreamStatistic.registerSetSourcedFailed(f),g}}async handleStreamInfoUpdate(g){this.loadSucceeded&&g.url!==this.selectedStreamDetails.url?await this.setPlayerSource(g):this.loadSucceeded&&this.playerInstance&&this.getCurrentTime()>0&&this.setPlaybackState("Start")}async switchStreamingUrl(g,f){if(this.streamingUrlSwitchCount>=this.configProvider.config.ampSettings.streamingUrlSwitchMaxCount||!(0,ct.includes)(this.configProvider.config.ampSettings.errorCodesEligibleForStreamingUrlSwitch,g)&&!f)return!1;const S=this.selectedStreamDetails.url===this.liveStreamOptions.stream?.url,v=S?this.liveStreamOptions.altStream:this.liveStreamOptions.stream;return isStreamValid(v)?(this.isSwitchStreamingUrlOngoing=!0,this.streamingUrlSwitchCount++,this.setPlayerSource(v).then((()=>!0)).catch((()=>!1))):(this.logger.error(`Stream to switch (${S?"alternative":"primary"}) is not valid`),!1)}destroy(g){this.srcLoadPromise=null,this.sdnPluginLoadPromise=null,this.renderer&&(this.renderer.dispose(),this.renderer=null),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null),this.playerInstance&&(this.liveStreamStatistic.registerPlayerDestroyed(g),this.playerInstance.dispose(),this.playerInstance=null,this.setPlaybackState("Destroyed"))}getCurrentTime(){const g=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return g&&g.currentPlayPosition||0}onCanplaythrough(){this.setPlaybackState("Ready")}onPlay(){(this.retryCount>0||this.lastKnownPlayTime)&&(this.logger.info(`Playing after retry count ${this.retryCount}, Setting current time to ${this.lastKnownPlayTime}`),this.playerInstance.message("setPlayTime").send(this.lastKnownPlayTime),this.retryCount=0,this.lastKnownPlayTime=void 0),this.setPlaybackState("Play")}onPlaying(){this.setPlaybackState("Playing")}onPause(){this.setPlaybackState("Paused")}onResume(){this.setPlaybackState("Resume")}onStart(){this.logger.info(`Playback started, retry count: ${this.retryCount}`),this.setPlaybackState("Start"),this.event("playbackStarted").raise(),self.clearTimeout(this.noMediaTimeoutId),this.isSwitchStreamingUrlOngoing&&(this.logger.info(`Playback started, switch count: ${this.streamingUrlSwitchCount}`),this.event("urlSwitched").raise(this.selectedStreamDetails===this.liveStreamOptions.altStream),this.isSwitchStreamingUrlOngoing=!1)}onEnded(){this.setPlaybackState("Ended")}onSeeking(){this.setPlaybackState("Seeking")}onSeeked(g){this.captionsTimestamp=g.captionsTimestamp,this.setPlaybackState("Seeked")}onMetadataLoaded(){this.setPlaybackState("LoadedMetadata")}onWaiting(){this.setPlaybackState("Buffering")}onLoadedData(){this.setPlaybackState("LoadedData")}onLoadStart(){this.setPlaybackState("LoadStart")}setPlaybackState(g){this.playerState=g,this.logger.debug(`playback state changed: ${g}`),this.liveStreamStatistic.registerPlaybackStateChanged(g),this.event("playbackStateChanged").raise()}onPlaybackBitrateChanged(g){this.liveStreamStatistic.registerPlaybackBitratechanged(g.bitrate)}onDownloadBitrateChanged(g){this.liveStreamStatistic.registerDownloadBitratechanged(g.bitrate)}onFullscreenChange(g){this.logger.debug(`fullscreenchange, isFullscreen=${g.isFullscreen}`),this.event("fullscreenToggled").raise(g.isFullscreen),this.liveStreamStatistic.registerFullScreenChange(g.isFullscreen)}onPotentialMediaFreeze(){this.logger.warn("Player detected a potential media freeze"),this.liveStreamStatistic.registerPotentialMediaFreeze()}onMute(){this.liveStreamStatistic.registerMute(!0)}onUnmute(){this.liveStreamStatistic.registerMute(!1)}onVolumeChange(g){this.liveStreamStatistic.registerVolumeChange(g.value)}stringifyPlayerError(g){return JSON.stringify(g,(function(g,f){return"errorCode"===g?f.toString(16):f}))}async handlePlaybackError(g){const f=4194307;this.playerState="Error",this.lastPlaybackError=g;const S=this.stringifyPlayerError(g);if(this.logger.info(`Playback error ${S}`),!g.errorCode&&null==g.fatal)return void this.logger.error("onError: error details are not available");if((g.errorCode&f)===f)return this.isPlaybackUnsupported=!0,this.raisePlaybackError("UnsupportedPlatform",S),void this.destroy("PlaybackError");this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;const v=g.errorCode,C=268435455&v;if(this.logger.error(`onError: errorCode: 0x${v.toString(16)}, errorCodeExcludingTech: 0x${C.toString(16)}, message: ${g.message}`),this.retryCount<this.configProvider.config.maxRetryCount&&(!1===g.fatal||-1!==(0,ct.indexOf)(yt,C)))setTimeout((async()=>{this.logger.info(`Retry loading stream because of error code: 0x${v.toString(16)}`),this.retryCount++,this.raisePlaybackError("PlaybackRetried",S),this.setPlayerSource(this.selectedStreamDetails)}),this.configProvider.config.ampSettings.sourceResetTimeoutInMs);else{await this.switchStreamingUrl(C,g.fatal)?this.configProvider.config.ampSettings.resetStreamingUrlSwitchCount&&(this.streamingUrlSwitchCount=0):(C===Et||g.message?.includes(Et.toString(16))?this.raisePlaybackError("NetworkError",S):this.raisePlaybackError("PlaybackError",S),this.destroy("PlaybackError"))}}raisePlaybackError(g,f){this.liveStreamStatistic.registerPlaybackError(g,f),this.event("playbackError").raise(g,f)}callDropDueToMediaTimeout(){const g={currentTime:-1,errorCode:0,message:JSON.stringify({state:this.playerState,error:this.stringifyPlayerError(this.lastPlaybackError)}),fatal:!0},f=this.stringifyPlayerError(g);this.raisePlaybackError("MediaTimeout",f),this.destroy("MediaTimeout")}},Tt=__toESM(re()),It=class extends Ke{constructor(g,f,S){super(),this.logger=g,this.telemetryLogger=S,this.playerLoaded=!1,this.playbackState="Destroyed",this.playerSubs=[],this.isFinalTelemetrySent=!1,this.captionsTimestamp=0,this.configProvider=f;const v=this.createHydraPlayerSettings();this.eventHandler=this.createEventHandler(),this.addPlayerEventSubscribers(),this.hydraPlayer=new Tt.HydraPlayer(v,this.eventHandler)}async configure(g){if(this.streamOptions=g,this.threadId=g.threadId,this.playerLoaded){const g=this.createHydraStreamOptions();await this.hydraPlayer.callPlayerApi("configureHydraPlayer",g)}}async loadPlayer(g){if(!await this.hydraPlayer.setup(g))return{setupSucceeded:!1,playerSetupError:{errorType:"HydraRuntimeLoadFailed",errorMessage:"Failed to create IFrame with Hydra runtime script"}};if(this.streamOptions){const g=this.createHydraStreamOptions();await this.hydraPlayer.callPlayerApi("configureHydraPlayer",g)}else this.logger.warn("No stream options configured before Hydra player loaded");const f=await this.hydraPlayer.callPlayerApi("loadHydraPlayer");return f.setupSucceeded&&(this.playerLoaded=!0,this.startTelemetryGathering()),this.getHydraPlayerSetupResult(f)}convertStreamDeliveryPipeline(g){switch(g){case"AMS":return Tt.HydraStreamDeliveryPipeline.AMS;case"MiddleLaneHttpLiveStreaming":return Tt.HydraStreamDeliveryPipeline.HLS;case"MiddleLaneUltraLowLatency":return Tt.HydraStreamDeliveryPipeline.Ums;default:throw new Error(`Unable to convert StreamDeliveryPipeline ${g} to HydraStreamDeliveryPipeline`)}}convertStreamingEventType(g){switch(g){case"TLE":return Tt.HydraStreamingEventType.TLE;case"Overflow":return Tt.HydraStreamingEventType.Overflow;case"TownHall_Basic":return Tt.HydraStreamingEventType.TownHallBasic;case"TownHall_Premium":return Tt.HydraStreamingEventType.TownHallPremium;case"TownHall":return Tt.HydraStreamingEventType.TownHall;default:throw new Error(`Unable to convert StreamingEventType ${g} to HydraStreamingEventType`)}}addPlayerEventSubscribers(){this.playerSubs.push(this.eventHandler.on("playbackStateChanged",(g=>{this.onPlaybackStateChanged(g)}))),this.playerSubs.push(this.eventHandler.on("playbackError",((g,f)=>{this.onPlaybackError(g,f)}))),this.playerSubs.push(this.eventHandler.on("playbackSeeked",(g=>{this.onPlaybackSeeked(g)}))),this.playerSubs.push(this.eventHandler.on("urlSwitched",(g=>{this.onUrlSwitched(g)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadSkipped",(g=>{this.onSdnPluginLoadSkipped(g)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadFailed",(g=>{this.onSdnPluginLoadFailed(g)}))),this.playerSubs.push(this.eventHandler.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.eventHandler.on("playbackTimeUpdated",(g=>{this.onPlaybackTimeUpdated(g)}))),this.playerSubs.push(this.eventHandler.on("videoTracksUpdated",(g=>{this.onVideoTracksUpdated(g)}))),this.playerSubs.push(this.eventHandler.on("statsUpdated",(g=>{this.onStatsUpdated(g)}))),this.playerSubs.push(this.eventHandler.on("log",((g,f)=>{this.onLog(g,f)}))),this.playerSubs.push(this.eventHandler.on("capabilitiesUpdated",(g=>{this.onCapabilitiesUpdated(g)})))}getTelemetryReport(){return this.hydraPlayer?.getFullTelemetryReport()}getSnapshotTelemetryReport(){return this.hydraPlayer?.getSnapshotTelemetryReport()}startTelemetryGathering(){this.statsSub=window.setTimeout((async()=>{clearTimeout(this.statsSub),this.logger.debug(`initial telemetry report after ${this.configProvider.config.sendInitialTelemetryAfterMs} ms`),this.sendTelemetry(!1)}),this.configProvider.config.sendInitialTelemetryAfterMs);let g,f;1===this.configProvider.playerConfig.playerType?(g=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,f=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs):(g=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,f=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs),g&&(this.diagSub=window.setInterval((async()=>{this.sendSnapshotTelemetry()}),f))}getHydraPlayerSetupResult(g){return{setupSucceeded:g.setupSucceeded,playerSetupError:g.playerSetupError?{errorType:this.convertHydraPlayerSetupError(g.playerSetupError.errorType),errorMessage:g.playerSetupError.errorMessage}:void 0}}convertHydraPlayerSetupError(g){switch(g){case Tt.HydraPlayerSetupErrorType.InvalidStream:return"InvalidStream";case Tt.HydraPlayerSetupErrorType.MultiplePlayerLoad:return"MultiplePlayerLoad";case Tt.HydraPlayerSetupErrorType.PlayerInitializationFailed:return"PlayerInitializationFailed";case Tt.HydraPlayerSetupErrorType.SetSourceFailed:return"SetSourceFailed";default:return}}getRenderer(){return!this.renderer&&this.hydraPlayer&&(this.renderer=new vt(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}onStatsUpdated(g){this.playerStats=g}getStats(){return this.playerStats}onLog(g,f){this.logger[g](f)}onPlaybackStateChanged(g){try{this.playbackState=this.convertHydraPlaybackState(g),this.event("playbackStateChanged").raise()}catch(g){this.logger.warn(`Not handling playback state changed event: ${stringifyObject(g)}`)}}convertHydraPlaybackState(g){switch(g){case Tt.HydraPlayerPlaybackState.LoadStart:return"LoadStart";case Tt.HydraPlayerPlaybackState.LoadedData:return"LoadedData";case Tt.HydraPlayerPlaybackState.LoadedMetadata:return"LoadedMetadata";case Tt.HydraPlayerPlaybackState.Start:return"Start";case Tt.HydraPlayerPlaybackState.CanPlayThrough:return"Ready";case Tt.HydraPlayerPlaybackState.Play:return"Play";case Tt.HydraPlayerPlaybackState.Playing:return"Playing";case Tt.HydraPlayerPlaybackState.Pause:return"Paused";case Tt.HydraPlayerPlaybackState.Waiting:return"Buffering";case Tt.HydraPlayerPlaybackState.Seeking:return"Seeking";case Tt.HydraPlayerPlaybackState.Seeked:return"Seeked";case Tt.HydraPlayerPlaybackState.Ended:return"Ended";case Tt.HydraPlayerPlaybackState.Error:return"Error";case Tt.HydraPlayerPlaybackState.Destroyed:return"Destroyed";case Tt.HydraPlayerPlaybackState.Initialized:return"Initialized";case Tt.HydraPlayerPlaybackState.Stalled:return"Stalled";default:throw new Error(`Unable to convert HydraPlayerPlaybackState ${g} to PlaybackState`)}}onPlaybackError(g,f){try{const S=this.convertHydraPlaybackErrorType(g);this.event("playbackError").raise(S,f)}catch(g){this.logger.warn(`Not handling playback error event: ${stringifyObject(g)}`)}}convertHydraPlaybackErrorType(g){switch(g){case Tt.HydraPlayerPlaybackErrorType.UnsupportedPlatform:return"UnsupportedPlatform";case Tt.HydraPlayerPlaybackErrorType.NetworkError:return"NetworkError";case Tt.HydraPlayerPlaybackErrorType.PlaybackRetried:return"PlaybackRetried";case Tt.HydraPlayerPlaybackErrorType.PlaybackError:return"PlaybackError";case Tt.HydraPlayerPlaybackErrorType.MediaTimeout:return"MediaTimeout";case Tt.HydraPlayerPlaybackErrorType.Unknown:return"Unknown";default:throw new Error(`Unable to convert HydraPlayerPlaybackErrorType ${g} to PlaybackErrorType`)}}seek(g){this.hydraPlayer.callPlayerApi("seekHydraPlayer",g)}seekToLiveEdge(){this.hydraPlayer.callPlayerApi("seekHydraPlayerToLiveEdge")}play(){this.hydraPlayer.callPlayerApi("playHydraPlayer")}pause(){this.hydraPlayer.callPlayerApi("pauseHydraPlayer")}setVolume(g){this.hydraPlayer.callPlayerApi("setHydraPlayerVolume",g)}selectVideoTrack(g){this.hydraPlayer.callPlayerApi("selectHydraPlayerVideoTrack",g)}getStreamSize(){return this.playerStats?{width:this.playerStats.mediaWidth,height:this.playerStats.mediaHeight}:{width:0,height:0}}isRendering(){const g=this.getStreamSize();return g.width>0&&g.height>0}disposePlayer(){this.hydraPlayer?.dispose()}releasePlayer(){this.hydraPlayer&&(this.hydraPlayer.release(),this.hydraPlayer=null)}stop(){this.clearPlayerEventSubscribers(),this.destroyPlayer()}destroyPlayer(){this.renderer&&(this.renderer.dispose(),this.renderer=null),this.statsSub&&(clearTimeout(this.statsSub),this.statsSub=null),this.diagSub&&(clearInterval(this.diagSub),this.diagSub=null),this.disposePlayer(),this.sendFinalTelemetry(),this.releasePlayer()}getPlaybackState(){return this.playbackState}getCaptionsTimestamp(){return this.captionsTimestamp}sendFinalTelemetry(){this.isFinalTelemetrySent||(this.isFinalTelemetrySent=!0,this.sendTelemetry(!0))}sendTelemetry(g){if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const f={...this.getTelemetryReport(),isFinal:g,threadId:this.threadId,tsCallingVersion:getTsCallingVersion(),correlationId:this.streamOptions.correlationId};this.logger.debug("generated live stream report: ",f),this.telemetryLogger.sendEvent({eventName:"live_events",props:f})}else this.logger.info("telemetry not sent")}sendSnapshotTelemetry(){if(this.telemetryLogger){const g={...this.getSnapshotTelemetryReport(),isFinal:!1,threadId:this.threadId,tsCallingVersion:getTsCallingVersion(),correlationId:this.streamOptions.correlationId};this.logger.debug("sending snapshot telemetry: ",g),this.telemetryLogger.sendEvent({eventName:"live_events",props:g})}else this.logger.error("snapshot telemetry not sent, telemetryLogger is not set")}clearPlayerEventSubscribers(){for(const g of this.playerSubs)g.dispose();this.playerSubs=[]}onPlaybackSeeked(g){this.captionsTimestamp=g}onUrlSwitched(g){this.event("urlSwitched").raise(g)}onSdnPluginLoadSkipped(g){this.event("sdnPluginLoadSkipped").raise(g)}onSdnPluginLoadFailed(g){this.event("sdnPluginLoadFailed").raise(g)}onPlaybackStarted(){this.event("playbackStarted").raise()}onPlaybackTimeUpdated(g){this.event("playbackTimeUpdated").raise(g)}onVideoTracksUpdated(g){this.event("videoTracksChanged").raise(g)}onCapabilitiesUpdated(g){this.event("capabilitiesUpdated").raise(g)}},bt=class extends Ke{constructor(){super()}playbackStateChanged(g){this.event("playbackStateChanged").raise(g)}playbackSeeked(g){this.event("playbackSeeked").raise(g)}log(g,f){this.event("log").raise(g,f)}playbackError(g,f){this.event("playbackError").raise(g,f)}urlSwitched(g){this.event("urlSwitched").raise(g)}sdnPluginLoadSkipped(g){this.event("sdnPluginLoadSkipped").raise(g)}sdnPluginLoadFailed(g){this.event("sdnPluginLoadFailed").raise(g)}statsUpdated(g){this.event("statsUpdated").raise(g)}playbackStarted(){this.event("playbackStarted").raise()}playbackTimeUpdated(g){this.event("playbackTimeUpdated").raise(g)}videoTracksUpdated(g){this.event("videoTracksUpdated").raise(g)}capabilitiesUpdated(g){this.event("capabilitiesUpdated").raise(g)}},At=__toESM(re());function GetHlsStreamPlaybackCoordinatesFromStream(g){if(g.playbackCoordinates)return g.playbackCoordinates;if(!g.url&&!g.hlsUrls)return[];const f=[];return(g.hlsUrls?g.hlsUrls:[g.url]).forEach((S=>{f.push({url:S,sdnContext:g.sdnContext})})),f}function GetUmsStreamPlaybackCoordinatesFromStream(g){return g.url?[{url:g.url,sdnContext:g.sdnContext}]:[]}var Pt=["https://res-4.public.onecdn.static.microsoft/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js","https://res.cdn.office.net/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js"],Rt=class extends It{createEventHandler(){return new wt}createHydraPlayerSettings(){return{playerType:At.HydraPlayerType.Hls,hydraRuntimeFetchTimeout:this.configProvider.config.hydraRuntimeFetchTimeout,capturePlayerLogs:this.configProvider.config.capturePlayerLogs,allowSdnPlugins:this.configProvider.config.allowSdnPlugins,debugLogging:this.configProvider.config.debug??!1,muteVideo:this.configProvider.playerConfig?.muteVideo??!1,videoLang:this.configProvider.playerConfig?.lang,videoElementStyles:this.configProvider.playerConfig?.styles,maxPlayerDiagnosticsCount:this.configProvider.config.maxPlayerDiagnosticsCount,maxPlayerMemoryTraceLogCount:this.configProvider.config.maxPlayerMemoryTraceLogCount,maxPlayerPlaybackEventCount:this.configProvider.config.maxPlayerPlaybackEventCount,maxPlayerExperimentalEvents:this.configProvider.config.hlsSettings.maxPlayerExperimentalEvents,maxRetryCount:this.configProvider.config.maxRetryCount,playerTelemetryTickMs:this.configProvider.config.playerTelemetryTickMs,removeEmptyDefaultTextTrack:this.configProvider.config.removeEmptyDefaultTextTrack,maxRetryCountForLoadingResources:this.configProvider.config.maxRetryCountForLoadingResources,maxVideoTrackHistoryLogCount:this.configProvider.config.maxVideoTrackHistoryLogCount,maxStreamConnectionResultsLogCount:this.configProvider.config.hlsSettings.maxStreamConnectionResultsLogCount,maxAbsoluteTimeOffsetEstimationResultsLogCount:this.configProvider.config.hlsSettings.maxAbsoluteTimeOffsetEstimationResultsLogCount,skipNonce:this.configProvider.config.hlsSettings.skipNonce,configIds:this.configProvider.configIds,estimateAbsoluteTime:this.configProvider.config.hlsSettings.estimateAbsoluteTime,playlistInitialSequenceNumber:this.configProvider.config.hlsSettings.playlistInitialSequenceNumber,timeoutForSwitchingUrl:this.configProvider.config.hlsSettings.timeoutForSwitchingUrl,hlsConfig:this.configProvider.config.hlsSettings.hlsConfig,logHlsJsEvents:this.configProvider.config.hlsSettings.logHlsJsEvents,logHlsJsEventsEveryMs:this.configProvider.config.hlsSettings.logHlsJsEventsEveryMs,switchingPolicy:this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.switchingPolicy,enableUuidTrace:this.configProvider.config.hlsSettings.enableUuidTrace,thaScript:this.configProvider.config.hlsSettings.thaScript,enableOffsetComputeBasedOfStreamTime:this.configProvider.config.hlsSettings.enableOffsetComputeBasedOfStreamTime,stopCrash:this.configProvider.config.stopCrash,stopTerminating:this.configProvider.config.hlsSettings.stopTerminating,stallDetectionPolicy:this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.stallDetectionPolicy,playerRuntimeJsUrls:this.configProvider.config.hydraPlayerHlsSettings?.runtimeUrls??this.configProvider.playerConfig?.hydraPlayerWebSdkUrls??Pt,disableSandbox:this.configProvider.config.hlsSettings.disableSandbox,ecsSettings:this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings,nonce:this.configProvider.playerConfig?.nonce??""}}createHydraStreamOptions(){let g=At.HydraStreamingEventType.TLE;g=this.streamOptions.streamingEventType?this.convertStreamingEventType(this.streamOptions.streamingEventType):this.streamOptions.overflow?At.HydraStreamingEventType.Overflow:At.HydraStreamingEventType.TLE;const f={stream:{playbackCoordinates:GetHlsStreamPlaybackCoordinatesFromStream(this.streamOptions.stream),urls:this.streamOptions.stream.hlsUrls?this.streamOptions.stream.hlsUrls:[this.streamOptions.stream.url],keyAuthorizationToken:this.streamOptions.stream.keyAuthorizationToken,keyDeliveryUrl:this.streamOptions.stream.keyDeliveryUrl,sdnContext:this.streamOptions.stream.sdnContext,streamDeliveryPipeline:this.streamOptions.stream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(this.streamOptions.stream.streamDeliveryPipeline):void 0},altStream:this.streamOptions.altStream?{playbackCoordinates:GetHlsStreamPlaybackCoordinatesFromStream(this.streamOptions.altStream),urls:this.streamOptions.altStream.hlsUrls?this.streamOptions.altStream.hlsUrls:[this.streamOptions.altStream.url],keyAuthorizationToken:this.streamOptions.altStream.keyAuthorizationToken,keyDeliveryUrl:this.streamOptions.altStream.keyDeliveryUrl,sdnContext:this.streamOptions.altStream.sdnContext,streamDeliveryPipeline:this.streamOptions.altStream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(this.streamOptions.altStream.streamDeliveryPipeline):void 0}:void 0,supportedSubtitleLanguages:this.streamOptions.supportedSubtitleLanguages,streamingEventType:g,allowPlayerControls:this.streamOptions.allowPlayerControls,sdn:this.streamOptions.sdn?{name:this.streamOptions.sdn.name,url:this.streamOptions.sdn.url,plugin:this.streamOptions.sdn.plugin}:void 0,thaContext:this.streamOptions.thaContext?{eventId:this.streamOptions.thaContext.eventId,organizer:{userId:this.streamOptions.thaContext.organizer?.userId,tenantId:this.streamOptions.thaContext.organizer?.tenantId},attendee:{userId:this.streamOptions.thaContext.attendee?.userId,tenantId:this.streamOptions.thaContext.attendee?.tenantId},coOrganizers:this.streamOptions.thaContext.coOrganizers}:void 0};return this.streamOptions.eventId&&(f.eventId=this.streamOptions.eventId),this.streamOptions.templateId&&(f.templateId=this.streamOptions.templateId),this.streamOptions.meetingMetadata&&(f.meetingMetadata=this.streamOptions.meetingMetadata),f}onCaptionsToggled(g,f,S){this.captionsControl&&this.captionsControl.toggleCaptions(g,f),this.event("captionsToggled").raise(g,f,S)}getCaptionsControl(){if(!this.captionsControl&&this.hydraPlayer){const g=this.streamOptions?.supportedSubtitleLanguages?this.streamOptions.supportedSubtitleLanguages.map((g=>g.culture)):["en","es"];this.captionsControl=new Mt(this.hydraPlayer,g)}return this.captionsControl}addPlayerEventSubscribers(){super.addPlayerEventSubscribers(),this.playerSubs.push(this.eventHandler.on("captionsToggled",((g,f,S)=>{this.onCaptionsToggled(g,f,S)})))}releasePlayer(){super.releasePlayer(),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null)}},Mt=class{constructor(g,f){this.hydraPlayer=g,this.availableCultures=f,this.selectedCulture=""}async addCues(g){const f=this.convertCues(g);await this.hydraPlayer.callPlayerApi("addHydraPlayerCues",f)}convertCues(g){const f=[];return g.forEach((g=>{f.push({start:g.start,end:g.end,text:g.text})})),f}async clearCues(){await this.hydraPlayer.callPlayerApi("clearHydraPlayerCues")}async showCaptions(g){await this.hydraPlayer.callPlayerApi("showHydraPlayerCaptions",g)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.hydraPlayer=null}toggleCaptions(g,f){this.selectedCulture=g?f:""}},wt=class extends bt{constructor(){super()}captionsToggled(g,f,S){this.event("captionsToggled").raise(g,f,S)}},Ot=__toESM(re()),Dt=class extends It{get tracks(){return this.trackInfo}createEventHandler(){return new kt}createHydraPlayerSettings(){return{playerType:Ot.HydraPlayerType.Ums,hydraRuntimeFetchTimeout:this.configProvider.config.hydraRuntimeFetchTimeout,allowSdnPlugins:this.configProvider.config.allowSdnPlugins,debugLogging:this.configProvider.config.debug??!1,muteVideo:this.configProvider.playerConfig?.muteVideo??!1,videoLang:this.configProvider.playerConfig?.lang,videoElementStyles:this.configProvider.playerConfig?.styles,maxPlayerDiagnosticsCount:this.configProvider.config.maxPlayerDiagnosticsCount,maxPlayerMemoryTraceLogCount:this.configProvider.config.maxPlayerMemoryTraceLogCount,maxPlayerPlaybackEventCount:this.configProvider.config.maxPlayerPlaybackEventCount,maxPlayerExperimentalEvents:this.configProvider.config.umsSettings.maxPlayerExperimentalEvents,maxRetryCount:this.configProvider.config.maxRetryCount,playerTelemetryTickMs:this.configProvider.config.playerTelemetryTickMs,maxRetryCountForLoadingResources:this.configProvider.config.maxRetryCountForLoadingResources,maxVideoTrackHistoryLogCount:this.configProvider.config.maxVideoTrackHistoryLogCount,maxStreamConnectionResultsLogCount:this.configProvider.config.umsSettings.maxStreamConnectionResultsLogCount,configIds:this.configProvider.configIds,timeoutForSwitchingUrl:this.configProvider.config.umsSettings.timeoutForSwitchingUrl,latencyCompensationThreshold:this.configProvider.config.umsSettings.latencyCompensationThreshold,switchingPolicy:this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.switchingPolicy,enableUuidTrace:this.configProvider.config.umsSettings.enableUuidTrace,thaScript:this.configProvider.config.umsSettings.thaScript,stopCrash:this.configProvider.config.stopCrash,stopTerminating:this.configProvider.config.umsSettings.stopTerminating,stallDetectionPolicy:this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.stallDetectionPolicy,playerRuntimeJsUrls:this.configProvider.config.hydraPlayerUmsSettings?.runtimeUrls??this.configProvider.playerConfig?.hydraPlayerWebSdkUrls,disableSandbox:this.configProvider.config.umsSettings.disableSandbox,ecsSettings:this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings,nonce:this.configProvider.playerConfig?.nonce??"",useLiveUmsCaptions:this.configProvider.config.umsSettings?.useLiveUmsCaptions??!1}}createHydraStreamOptions(){let g=Ot.HydraStreamingEventType.TLE;g=this.streamOptions.streamingEventType?this.convertStreamingEventType(this.streamOptions.streamingEventType):this.streamOptions.overflow?Ot.HydraStreamingEventType.Overflow:Ot.HydraStreamingEventType.TLE;const f={stream:{playbackCoordinates:GetUmsStreamPlaybackCoordinatesFromStream(this.streamOptions.stream),urls:[this.streamOptions.stream.url],decryptionKey:this.streamOptions.stream.decryptionKey,sdnContext:this.streamOptions.stream.sdnContext,streamDeliveryPipeline:this.streamOptions.stream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(this.streamOptions.stream.streamDeliveryPipeline):void 0},altStream:this.streamOptions.altStream?{playbackCoordinates:GetUmsStreamPlaybackCoordinatesFromStream(this.streamOptions.altStream),urls:[this.streamOptions.altStream.url],decryptionKey:this.streamOptions.altStream.decryptionKey,sdnContext:this.streamOptions.altStream.sdnContext,streamDeliveryPipeline:this.streamOptions.altStream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(this.streamOptions.altStream.streamDeliveryPipeline):void 0}:void 0,streamingEventType:g,allowPlayerControls:this.streamOptions.allowPlayerControls,sdn:this.streamOptions.sdn?{name:this.streamOptions.sdn.name,url:this.streamOptions.sdn.url,plugin:this.streamOptions.sdn.plugin}:void 0,thaContext:this.streamOptions.thaContext?{eventId:this.streamOptions.thaContext.eventId,organizer:{userId:this.streamOptions.thaContext.organizer?.userId,tenantId:this.streamOptions.thaContext.organizer?.tenantId},attendee:{userId:this.streamOptions.thaContext.attendee?.userId,tenantId:this.streamOptions.thaContext.attendee?.tenantId},coOrganizers:this.streamOptions.thaContext.coOrganizers}:void 0};return this.streamOptions.eventId&&(f.eventId=this.streamOptions.eventId),this.streamOptions.templateId&&(f.templateId=this.streamOptions.templateId),this.streamOptions.meetingMetadata&&(f.meetingMetadata=this.streamOptions.meetingMetadata),f}addPlayerEventSubscribers(){super.addPlayerEventSubscribers(),this.playerSubs.push(this.eventHandler.on("trackListUpdated",(g=>{this.onTrackListUpdated(g)}))),this.playerSubs.push(this.eventHandler.on("trackSelected",(g=>{this.onTrackSelected(g)})))}onTrackListUpdated(g){this.trackInfo=g;const f=stringifyObject(g);this.logger.info(`[onTrackListUpdated]: Track list updated to: ${f}`)}onTrackSelected(g){const f=stringifyObject(g);this.logger.info(`[onTrackSelected]: Track selected: ${f}`)}getCaptionsControl(){return!this.captionsControl&&this.hydraPlayer&&(this.captionsControl=new Nt(this.hydraPlayer,this.logger.createChild("CaptionsControl"))),this.captionsControl}releasePlayer(){super.releasePlayer(),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null)}},Nt=class{constructor(g,f){this.hydraPlayer=g,this.logger=f}async addCues(g){this.logger.warn("[addCues]: not implemented for UMS player")}async clearCues(){this.logger.warn("[clearCues]: not implemented for UMS player")}async showCaptions(g){await this.hydraPlayer.callPlayerApi("showHydraPlayerCaptions",g)}getSelectedCulture(){return this.logger.warn("[getSelectedCulture]: not implemented for UMS player"),""}getAvailableCultures(){return this.logger.warn("[getAvailableCultures]: not implemented for UMS player"),[]}dispose(){this.hydraPlayer=null}async selectTextTrack(g){await this.hydraPlayer.callPlayerApi("selectHydraPlayerTextTrack",g)}},kt=class extends bt{constructor(){super()}trackListUpdated(g){this.event("trackListUpdated").raise(g)}trackSelected(g){this.event("trackSelected").raise(g)}},Lt=class extends Ke{constructor(g,f,S){super(),this.configProvider=g,this.logger=f,this.getTelemetryLogger=S,this.isAvailable=!0,this._isStreaming=!1,this.playerSubs=[],this.isFinalTelemetrySent=!1,this.telemetryLogger=this.getTelemetryLogger(),1===this.configProvider.playerConfig.playerType?this.player=new Rt(this.logger.createChild("HlsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):2===this.configProvider.playerConfig.playerType?this.player=new Dt(this.logger.createChild("UmsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):(this.initializeAmpTelemetry(),this.player=new _t(this.logger.createChild("AmpLiveStreamPlayer"),this.liveStreamStatistic,this.configProvider)),this.subscribeForPlayerEvents()}get isStreaming(){return this._isStreaming}isActive(){return this.isAvailable&&this.isStreaming}async start(g,f){await this.setOptions(f),this.isFinalTelemetrySent=!1;const S=await this.player.loadPlayer(g);if(!S.setupSucceeded){this.player.stop(),this.logger.error("playerLoadFailed");const g=JSON.stringify(S.playerSetupError);throw this.sendFinalTelemetry(g),new Error(g)}return this._isStreaming=!0,this.liveStreamStatistic&&(this.statsSub=window.setTimeout((()=>{clearTimeout(this.statsSub),this.logger.debug(`initial telemetry report after ${this.configProvider.config.sendInitialTelemetryAfterMs} ms`),this.sendTelemetry(!1)}),this.configProvider.config.sendInitialTelemetryAfterMs),this.configProvider.config.sendSnapshotTelemetry&&(this.diagSub=window.setInterval((()=>{this.sendSnapshotTelemetry()}),this.configProvider.config.sendSnapshotTelemetryEveryMs))),this.player.getRenderer()}initializeAmpTelemetry(){const g={perceivedBandwidth:[],videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],currentMediaTime:[],statsInterval:[]};this.liveStreamStatistic=new lt(this.configProvider.config,this.logger.createChild("LiveStreamStatistic"),g)}async stop(){}async setOptions(g){return void 0!==g.overflow&&(g.streamingEventType||(g.streamingEventType=g.overflow?"Overflow":"TLE"),delete g.overflow),this.options=g,this.player.configure(g)}getStats(){return this.liveStreamStatistic?this.liveStreamStatistic.getPlayerDiagnosticSnapshot():this.player?.getStats?.()}dispose(){this.unsubscribeFromPlayerEvents(),this.player.stop(),this.statsSub&&(clearTimeout(this.statsSub),this.statsSub=null),this.diagSub&&(clearInterval(this.diagSub),this.diagSub=null),this.logger.debug("stopping live event"),this.sendFinalTelemetry("graceful disposed"),super.dispose()}sendFinalTelemetry(g){this.isFinalTelemetrySent||(this.isFinalTelemetrySent=!0,this.sendTelemetry(!0,g))}sendTelemetry(g,f){if(this.liveStreamStatistic)if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const S={configIds:this.configProvider.configIds,playerId:this.player.playerId,correlationId:this.options?.correlationId,eTag:this.configProvider.etag,isFinal:g,threadId:this.options?.threadId,disableFullscreenButton:this.configProvider.playerConfig.disableFullscreenButton,callendReason:f},v=this.liveStreamStatistic?.getReport(S);this.logger.debug("generated live stream report",v),this.telemetryLogger.sendEvent({eventName:"live_events",props:v})}else this.logger.info("telemetry not sent");else this.logger.info("telemetry not tracked in ILiveStream object")}sendSnapshotTelemetry(){if(this.liveStreamStatistic)if(this.telemetryLogger){const g=this.liveStreamStatistic.getSnapshotReport({configIds:this.configProvider.configIds,playerId:this.player.playerId,correlationId:this.options?.correlationId,eTag:this.configProvider.etag,isFinal:!1,threadId:this.options?.threadId,disableFullscreenButton:this.configProvider.playerConfig.disableFullscreenButton});this.logger.debug("sending snapshot telemetry: ",g),this.telemetryLogger.sendEvent({eventName:"live_events",props:g})}else this.logger.error("snapshot telemetry not sent, telemetryLogger is not set");else this.logger.info("telemetry not tracked in ILiveStream object")}subscribeForPlayerEvents(){this.playerSubs.push(this.player.on("playbackStateChanged",(()=>{this.onPlaybackStateChanged()}))),this.playerSubs.push(this.player.on("playbackError",((g,f)=>{this.onPlaybackError(g,f)}))),this.playerSubs.push(this.player.on("urlSwitched",(g=>{this.onUrlSwitched(g)}))),this.playerSubs.push(this.player.on("sdnPluginLoadSkipped",(g=>{this.onSdnPluginLoadSkipped(g)}))),this.playerSubs.push(this.player.on("sdnPluginLoadFailed",(g=>{this.onSdnPluginLoadFailed(g)}))),this.playerSubs.push(this.player.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.player.on("capabilitiesUpdated",(g=>this.onCapabilitiesUpdated(g))))}unsubscribeFromPlayerEvents(){for(const g of this.playerSubs)g.dispose();this.playerSubs=[]}onPlaybackStarted(){this.event("playbackStarted").raise()}onPlaybackStateChanged(){const g=this.player.getPlaybackState();switch(g){case"Start":this.event("playbackStarted").raise();break;case"Ended":this.event("playbackNotLive").raise(),this.sendFinalTelemetry("playback ended");break;case"Seeked":this.event("playbackSeeked").raise(this.player.getCaptionsTimestamp());break;default:this.logger.debug(`playbackStateChanged: ${g}`)}this.event("playbackStateChanged").raise(this.player.getPlaybackState())}onPlaybackError(g,f){this.event("error").raise(g,f)}onUrlSwitched(g){this.event("urlSwitched").raise(g)}onSdnPluginLoadSkipped(g){this.event("sdnPluginLoadSkipped").raise(g)}onSdnPluginLoadFailed(g){this.event("sdnPluginLoadFailed").raise(g)}onCapabilitiesUpdated(g){this.event("capabilitiesUpdated").raise(g)}},Ft=class{constructor(g,f,S){this.ecsConfig=g,this.logger=f,this.getTelemetryLogger=S}configure(g){this.configuration=g}async initialize(){const g="MDN_MIDDLELANE_TEAMS",f="liveStream",S=this.ecsConfig.getString(g,f);let v={};try{v=JSON.parse(S)}catch(S){this.logger.warn(`failed to parse ECS configuration for ${g}/${f}`)}const C=this.ecsConfig.getString("ConfigIDs",g);this._configProvider=new rt(v,this.configuration,C,this.logger.createChild("LiveStreamConfigProvider"))}createLiveStream(){return new Lt(this._configProvider,this.logger.createChild("LiveStream"),this.getTelemetryLogger)}dispose(){}},xt=class extends Ke{constructor(){super(...arguments),this.isAudioOutputSelectionSupported=!1}createAudioPlayer(){return null}createAudioRenderer(){return null}getRawDeviceMediaStream(g){return null}askDevicePermission(){return Promise.resolve({audio:!1,video:!1})}getPermissionState(g){return"granted"}enumerateDevicesAsync(){return Promise.resolve([])}getPreferredCamera(){return null}selectDevices(){}getSelectedDevices(){return{}}createPreview(){return Promise.resolve(new Ut)}createPreviewRenderer(){return Promise.resolve(new Ut)}createScreenSharingPreviewRenderer(){return Promise.resolve(new Ut)}getDeviceNameAsync(){return Promise.resolve("")}setDeviceEffectsAsync(){return Promise.resolve()}getDeviceEffectsCapabilityAsync(){return Promise.resolve(0)}setBackgroundImageAsync(){return Promise.resolve()}getImagePropertyAsync(){return Promise.resolve({width:0,height:0,uri:" "})}getMicrophoneGeometryArrayInfoAsync(g){return Promise.resolve({})}transformImageAsync(){return Promise.resolve(!1)}sendMessageDeviceVideoEffectsAsync(){return Promise.resolve({code:0})}sendMessageDeviceVideoExtensibilityAsync(){return Promise.resolve({code:0,type:"Error",response:{details:"The API has not been implemented."}})}setVideoCaptureConfigAsync(){return Promise.resolve()}captureVideoFrameWithoutEffectsAsync(){return Promise.resolve(new ImageData(0,0))}enableSignLanguageDetectionAsync(g,f){return Promise.resolve()}downloadAiModel(g,f){return Promise.resolve("")}setAudioProcessingFlags(g){}getSpeakerVolume(){return Promise.resolve(0)}getSpeakerSystemVolume(){return Promise.resolve(0)}setSpeakerVolume(g){return Promise.resolve()}setSpeakerSystemVolume(g){return Promise.resolve()}unmuteMicrophone(){return Promise.resolve()}unmuteSpeaker(){return Promise.resolve()}getNrgLevelsForDeviceTuner(g){return Promise.resolve(0)}getNrgLevelPollerForDeviceTuner(g){return Promise.resolve(new Bt)}setAudioEffectsAsync(){return Promise.resolve()}getAudioFeatureCapability(g){return Promise.resolve(0)}getMicrophoneVolume(){return Promise.resolve(0)}setMicrophoneVolume(g){return Promise.resolve()}setDeviceTelemetryData(g,f,S,v=0){return Promise.resolve()}getSpeakerDeviceDomIdAsync(g,f){return Promise.reject()}mapBrowserDevices(g,f){return Promise.reject()}getSourceFormats(g){return Promise.resolve([])}enableShellSharing(){return Promise.resolve()}disableShellSharing(){return Promise.resolve()}enableParticipantCameras(){return Promise.resolve()}registerDerivedSource(g,f){return Promise.resolve()}unregisterDerivedSource(g){return Promise.resolve()}startAudioLoopbackDevice(g){return Promise.resolve()}async dispose(g){return Promise.resolve()}},Ut=class extends Ke{constructor(){super(...arguments),this.isRendering=!1,this.streamSize={width:0,height:0},this.rendererType=-1,this.frameType=-1}captureFrame(){return Promise.resolve(new Vt)}getStats(){return Promise.resolve({framesDropped:0,framesTotal:0})}setScalingMode(){return Promise.resolve()}cameraAutoControl(g){return Promise.resolve(!1)}getCameraManualControlStates(g){return Promise.resolve([])}setCameraManualControlStates(g){return Promise.resolve([])}enumerateCameraManualControls(){return Promise.resolve([])}isCameraAdvancedControlCapable(){return Promise.resolve(!1)}dispose(){}},Vt=class extends Ke{getSize(){return{width:0,height:0}}isMirrored(){return!1}},Bt=class{getInputLevel(){return 0}getInputLevelNormalized(g,f){return 0}dispose(){}},Ht=Ke,$t="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",jt="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",Gt="http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00",qt={MEDIA_STATE:{send:"sendonly",receive:"recvonly",sendReceive:"sendrecv",inactive:"inactive"},MEDIA_DIRECTION:{SEND:"send",RECV:"recv"},MEDIA_DEVICE_KIND:{audioInput:"audioinput",audioOutput:"audiooutput",videoInput:"videoinput",compositeAudio:"compositeAudio",virtualDevice:"virtualDevice"},MEDIA_DEVICE:{camera:"camera",microphone:"microphone",speaker:"speaker",compositeAudio:"compositeAudio",defaultId:"default",communicationsId:"communications",defaultDeviceLabel:"Default",audioIngestDevice:"audioIngestDevice",virtualDevice:"virtualDevice"},MEDIA_ERROR:{constraintNotSatisfiedError:"ConstraintNotSatisfiedError",iceConnectionError:"iceConnectionError",srtpError:"srtpError",permissionDeniedError:"permissionDeniedError",internalError:"internalError",sourceUnavailableError:"SourceUnavailableError",devicesNotFoundError:"DevicesNotFoundError",noDeviceSelected:"noDeviceSelected",noNetworkError:"noNetworkError",incompatibleOffer:"IncompatibleOffer",mediaStreamRequestError:"MediaStreamRequestError",extensionNotFoundError:"ExtensionNotFoundError",sharingCancelledError:"SharingCancelledError",permissionDeniedBySystemError:"PermissionsDeniedBySystem",chromeRuntimeNotDefinedError:"ChromeRuntimeNotDefinedError",mediaStreamRequestTimedOut:"MediaStreamRequestTimedout",unsupportedStream:"UnsupportedStream",webGlRendererError:"WebGlRendererError",audioPlaybackError:"audioPlaybackError",unexpectedClose:"unexpectedClose",incompatibleOriginator:"incompatibleOriginator"},HISTOGRAM_BATCH:{seconds1to3:2,seconds3to5:4,seconds5to8:7,seconds8to15:14,seconds15to60:59,seconds60toMax:1e6},RENEGOTIATION_ERROR:{local:"local",glare:"glare",signaling:"signaling",media:"media",escalation:"escalation"},MSI:{unsubscribe:-1,subscribeAny:-2},MEDIA_LABEL:{audio:"main-audio",video:"main-video",sharing:"applicationsharing-video",data:"data"},MEDIA_TYPE:{audio:"audio",video:"video",sharing:"sharing",data:"x-data",dataChannel:"application"},MODALITY:{audio:"audio",video:"video",sharing:"sharing",data:"data"},TRACK_KIND:{audio:"audio",video:"video"},ICE_TRANSPORT_POLICY:{all:"all",relay:"relay"},RENDERER_TYPE:{video:"video",sharing:"sharing"},CONTENT_TYPE:{SDP:"application/sdp",SDP_NGC:"application/sdp-ngc-1.0"},ALLOWED_CONTENT_TYPES:{SDP_ONLY:["application/sdp"],SDP_NGC:["application/sdp","application/sdp-ngc-0.5","application/sdp-ngc-1.0"]},STREAMING_STATE:{created:"created",started:"started",active:"active",inactive:"inactive",stopped:"stopped",removed:"removed",failed:"failed"},TIME_INTERVAL:{SEC_1:1},DISPLAY_SOURCE_ID:"display",EMPTY_DEVICE_ID:"0",SYSTEM_AUDIO_SOURCE_ID:"system",MULTIPLE_RECV_STREAMS:"multipleVideoStreams",PROFILES:{udpTlsRtpSavpf:"UDP/TLS/RTP/SAVPF",rtpSavpf:"RTP/SAVPF",rtpSavp:"RTP/SAVP",udpDtlsSctp:"UDP/DTLS/SCTP"},REPORTING_PROFILE:{RT_PROFILE:"REAL_TIME",BE_PROFILE:"BEST_EFFORT",NRT_PROFILE:"NEAR_REAL_TIME"},PAYLOAD_TYPE:{DATA_CHANNEL:"webrtc-datachannel",X_DATA:"127 126",MSRTC_RED:97,MSRTC_CNFB:120},VIDEO_CAPABILITIES:{MAX_FS_PATH:"max-fs",MAX_MBPS_PATH:"max-mbps",MAX_FPS_PATH:"max-fps",MAX_BR_PATH:"max-br",SSRC_PATH:"ssrc",RID_PATH:"rid",KEYFRAME_PATH:"KeyFrame",MAX_WIDTH:"max-width",MAX_HEIGHT:"max-height",MAX_STREAMS:"max-streams",MAX_LAYERS:"max-layers",PRIORITY_LAYOUT_MIN_MBPR:"priority-layout-min-mbpr",PRIORITY_LAYOUT_MIN_BITRATE:"priority-layout-min-bitrate",VLA_DEBUG:"vla-debug",LADDER_TYPE:"ladder-type"},TRANSPORT_CC:{EXT_URI:$t,MSSDP_ENCODED_URI:$t.replace(/\//g,"\\"),ATTRIBUTE:"transport-cc"},ABS_SEND_TIME:{EXT_URI:jt,MSSDP_ENCODED_URI:jt.replace(/\//g,"\\")},VLA:{EXT_URI:Gt,EXT_URI_NON_ADV:Gt+"-non-advertised",DEFAULT_VALUE:10},MACROBLOCK_SIZE:16,MAX_FS_1080P:8160,MEDIA_EVENT_FIELDS:{Extensions:["IceConnectionState","IceConnectionStatePrevious","SignalingState","SignalingStatePrevious"],metrics:["ReconnectInProgress","IceConnectedStateTime","ErrorType","ErrorDetail","InitialNegotiationType","InitialNegotiationCompleted","TerminationReason_subCode","TerminationReason_code"]},RES_TABLE:{SEND:[{w:320,h:180,fps:15,minBr:2e4,maxBr:175e3},{w:416,h:234,fps:15,minBr:125e3,maxBr:5e5},{w:640,h:360,fps:30,minBr:4e5,maxBr:575e3},{w:960,h:540,fps:30,minBr:5e5,maxBr:1125e3},{w:1280,h:720,fps:30,minBr:1e6,maxBr:25e5},{w:1920,h:1080,fps:30,minBr:175e4,maxBr:1e8}],RECV:[{w:320,h:180,fps:15,minBr:2e4,maxBr:175e3},{w:426,h:240,fps:15,minBr:125e3,maxBr:5e5},{w:640,h:360,fps:30,minBr:4e5,maxBr:575e3},{w:960,h:540,fps:30,minBr:5e5,maxBr:1125e3},{w:1280,h:720,fps:30,minBr:1e6,maxBr:25e5},{w:1920,h:1080,fps:30,minBr:175e4,maxBr:1e8}]}};function forOwn(g,f){for(const S in g)g.hasOwnProperty(S)&&f(g[S],S)}function forOwnRec(g,f){for(const S in g)g.hasOwnProperty(S)&&("object"==typeof g[S]?forOwnRec(g[S],f):f(g[S],S,g))}function isDefined(g){return null!=g&&!Number.isNaN(g)}function getMinDefined(g,f){return isDefined(f)?isDefined(g)?Math.min(g,f):f:g}function getMaxDefined(g,f){return isDefined(f)?isDefined(g)?Math.max(g,f):f:g}function average(g){let f=0;return g.forEach((g=>f+=g)),f/=g.length,f}function remove2(g,f){let S=!1;for(let v=g.length;v-- >0;)f(g[v],v,g)&&(g.splice(v,1),S=!0);return S}function compareArraysBy(g,f,S){const v=[];return g.forEach((g=>{f.some((f=>S(g,f)))||v.push(g)})),0===v.length&&g.length===f.length}function values(g){const f=[];for(const S in g)g.hasOwnProperty(S)&&f.push(g[S]);return f}function assign(g,f){for(const S in f)f.hasOwnProperty(S)&&(g[S]=f[S])}function isEmpty(g){return!Object.keys(g).length}function keys(g){return Object.keys(g)}function shallowClone(g){const f={};return forOwn(g,((g,S)=>{f[S]=g})),f}function deepClone(g){let f;if(!g||"object"!=typeof g)return g;if(g instanceof Date)return f=new Date,f.setTime(g.getTime()),f;if(g instanceof Array){f=[];for(let S=0,v=g.length;S<v;S++)f[S]=deepClone(g[S]);return f}if(g instanceof Object)return f={},forOwn(g,(function(g,S){f[S]=deepClone(g)})),f;throw new Error("Unable to copy: "+stringifyObject(g))}function removeUndefinedFields(g){return Object.keys(g).forEach((f=>{void 0===g[f]&&delete g[f]})),g}function uniqueId(){const segment=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return segment()+segment()+segment()+"4"+segment().substring(1)+"b"+segment().substring(1)+segment()+segment()+segment()}function deepEqual(g,f){let S;const v=typeof g;if(g===f)return!0;if(v!==typeof f||"object"!==v&&"function"!==v)return!1;if(null===g||null===f)return g===f;if(g instanceof Date&&f instanceof Date)return+g==+f;if(g instanceof Map&&f instanceof Map)return compareMaps(g,f);for(S in g)if(!(S in f)||!deepEqual(g[S],f[S]))return!1;for(S in f)if(!(S in g)||!deepEqual(g[S],f[S]))return!1;return!0}function compareMaps(g,f){let S;if(g.size!==f.size)return!1;let v=!0;return g.forEach(((g,C)=>{S=f.get(C),(S!==g||void 0===S&&!f.has(C))&&(v=!1)})),v}function getMaxSubstring(g,f){return f.reduce(((f,S)=>{const v=g.includes(S)?S.length:0;return f.length<v?S:f}),"")}function assertContentTypeSupported(g,f){if(-1===f.indexOf(g))throw{detail:`${g} mediaContent.contentType is not supported`,type:qt.MEDIA_ERROR.incompatibleOffer}}function throwIfFeatureNotSupported(g,f){g.forEach((g=>{if(""!==g&&-1!==f.findIndex((f=>f===g)))throw{detail:`Required feature '${g}' is not acceptable.`,type:qt.MEDIA_ERROR.incompatibleOffer}}))}function getClosestValue(g,f,S,v=0){for(let C=1;C<g.length;C++)if(g[C-1]+v<f&&f<=g[C]+v)return S?g[C]:g[C-1];return g[0]}function isInRange(g,f,S){return f<=g&&g<=S}function getFrom(g,...f){for(const S of f)if(S.hasOwnProperty(g))return S[g]}function subtractFrom(g,f){return g.filter((g=>!f.some((f=>f===g))))}function getLongestCommonContiguousSubstring(g,f){if(g===f)return g;let S=0,v=0,C="";for(let _=0;_<g.length&&!(C.length>g.length-_);_++){let T=_;v-S>C.length&&(C=g.substring(S,v),_=v-1),S=_,v=_;for(let I=0;I<f.length;I++)T<g.length&&f[I]===g[T++]?v=T:(T=_,v-S>C.length&&(C=g.substring(S,v),_=v-1),S=_,v=_)}return C}function levenshteinDistance(g,f){const S=new Array(g.length+1);for(let v=0;v<g.length+1;v++){S[v]=new Array(f.length+1);for(let g=0;g<f.length+1;g++)S[v][g]=0}for(let f=1;f<g.length+1;f++)S[f][0]=f;for(let g=1;g<f.length+1;g++)S[0][g]=g;for(let v=1;v<g.length+1;v++)for(let C=1;C<f.length+1;C++){let _=1;g[v-1]===f[C-1]&&(_=0),S[v][C]=Math.min(S[v-1][C]+1,S[v][C-1]+1,S[v-1][C-1]+_)}return S[g.length][f.length]}function getAverage(g){return g.reduce(((g,f)=>g+f),0)/(g.length?g.length:1)}function round(g,f=3){return g&&parseFloat(g.toFixed(f))}function scrubDeviceLabelPii(g,f){if(!g)return"";if(g.length<3)return g;const S=[],v=g.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);v&&S.push(v[1]);try{if(f?.length){const v=new RegExp(`(${f.join("|")})`,"gi");let C=v.exec(g);for(;C;)S.push(C[1]),C=v.exec(g)}else S.push("no_keywords")}catch(g){S.push(`Error: ${stringifyObject(g)}`)}return 0===S.length?"unknown":S.join(" ")}function limitArraySize2(g,f,S=0){return g&&void 0!==f&&f>-1&&g.length>f&&g.splice(S,g.length-f),g}function arrayLimitedPush2(g,f,S,v=0){limitArraySize2(g,0===S?0:S-1,v),0!==S&&g.push(f)}function addGetterFields(g,f){const S={};for(const g in f)S[g]={get:f[g],configurable:!1,enumerable:!0};Object.defineProperties(g,S)}function getLast(g){return g?.length>0?g[g.length-1]:void 0}var Wt=window?.performance?.now&&window?.performance?.timeOrigin,zt=Wt?()=>window.performance.now():()=>Date.now(),Kt=Wt?window.performance.timeOrigin:0,Jt=zt,Yt=Kt;function rebaseTime(g,f,S){if(g?.length>0){const v=[];for(const C of g){const g=deepClone(C);g[f]=g[f]&&g[f]-S,v.push(g)}return v}return g}function rebaseAndLimitHistogramTimestamps(g,f,S){if(!g)return;const v={seconds1to3:[],seconds3to5:[],seconds5to8:[],seconds8to15:[],seconds15to60:[],seconds60toMax:[]};for(const[C,_]of Object.entries(g))for(const g of _)arrayLimitedPush2(v[C],g-f,S);return v}function sampleseries(g,f,S=!1){const v=g?.map(f).filter((g=>void 0!==g&&!isNaN(g)&&null!==g&&(!1===S||0!==g)));return v?.length?v.join(","):void 0}function sampleseriesArr(g,f,S){const v=g?.map(f).filter((g=>void 0!==g&&!isNaN(g)&&null!==g)).splice(-S);return v?.length?v:void 0}function clearObj(g,f){const S=[];for(const v of Object.keys(g))f.has(v)||S.push(v);for(const f of S)delete g[f]}function clearMap(g,f){const S=[];for(const v of g.keys())f.has(v)||S.push(v);for(const f of S)g.delete(f)}function convertContextProperty(g){return"object"==typeof g?stringifyObject(g):g}function getPercentilesProviderFromSampleFreqs(g){const f=Object.keys(g).map(Number).sort(((g,f)=>g-f)),S=f.reduce(((f,S)=>f+(g[S]??0)),0);return{getPercentile:v=>{const C=S*v;let _=0;for(const S of f)if(_+=g[S],_>=C)return S}}}function getHeaderValue(g,f){return g.hasOwnProperty(f)?g[f]:g.hasOwnProperty(f.toLowerCase())?g[f.toLowerCase()]:void 0}function parseServiceTokenTypes(g){const f=g.toLowerCase(),S='token_types="',v=f.indexOf(S);if(-1===v)return[];const C=f.indexOf('"',v+S.length);if(-1===C)return[];const _=f.substring(v+S.length,C).trim();if(""===_)return[];return _.split(" ")}function ceilToMacroblock(g){const f=16;return Math.ceil(g/f)*f}function limitRebaseAndStringifyEvents(g,f,S,v){return JSON.stringify(rebaseTime(limitArraySize2(g,f),S,v))}var Qt=M;function createResolutionTable(g){return g.map((g=>new Xt(g.w,g.h,g.fps,g.minBr,g.maxBr)))}var Xt=class{constructor(g,f,S=0,v=0,C=0){this.width=g,this.height=f,this.fps=S,this.minBitrate=v,this.maxBitrate=C,this.fs=Math.ceil(g/qt.MACROBLOCK_SIZE)*Math.ceil(f/qt.MACROBLOCK_SIZE)}toString(){return this.height?`${this.height}p`:`${this.fs}fs`}},Zt=class _ResolutionTable{constructor(g){g||(this.resolutions=createResolutionTable(qt.RES_TABLE.SEND)),this.resolutions=createResolutionTable(g)}static initialize(g){_ResolutionTable.Send=new _ResolutionTable(g.config.sendResolutionTableOverride),_ResolutionTable.Recv=new _ResolutionTable(g.config.recvResolutionTableOverride),g.on("configUpdated",(()=>{_ResolutionTable.Send=new _ResolutionTable(g.config.sendResolutionTableOverride),_ResolutionTable.Recv=new _ResolutionTable(g.config.recvResolutionTableOverride)}))}get initialResolution(){return this.resolutions[this.resolutions.length-1]}getResolutionByFs(g){return this.getResolutionRecord(void 0,g)}getMaxFsForHeight(g){return this.getResolutionRecord(g).fs}getResolutionForBitrate(g){let f=this.resolutions.filter((f=>f.maxBitrate&&f.maxBitrate>=g)).shift(),S=this.resolutions.filter((f=>f.minBitrate&&f.minBitrate<=g)).pop();return f=f??S,S=S??f,{lowRes:f,highRes:S}}getBitrateForResolution(g,f){const S=this.getResolutionRecord(Math.min(g,f));return{minBitrate:S.minBitrate,maxBitrate:S.maxBitrate}}getResolutionRecord(g,f){if(this===_ResolutionTable.Send){for(let S=this.resolutions.length-1;S>=0;S--){if(g&&this.resolutions[S].height<=g)return this.resolutions[S];if(f&&this.resolutions[S].fs<=f)return this.resolutions[S]}return this.resolutions[0]}for(const S of this.resolutions){if(g&&S.height>=g)return S;if(f&&S.fs>=f)return S}return this.resolutions[this.resolutions.length-1]}getNextLowerResolution(g,f){const S=Math.min(g,f),v=this.getResolutionRecord(S),C=this.resolutions.indexOf(v);return S===Math.min(v.width,v.height)||this===_ResolutionTable.Recv?this.resolutions[C-1]:this.resolutions[C]}getNextHigherResolution(g,f){const S=Math.min(g,f),v=this.getResolutionRecord(S),C=this.resolutions.indexOf(v);return S===Math.min(v.width,v.height)?this.resolutions[C+1]:this===_ResolutionTable.Recv?this.resolutions[C]:this.resolutions[C+1]}getResolutions(){return this.resolutions}};Zt.Recv=new Zt(qt.RES_TABLE.RECV),Zt.Send=new Zt(qt.RES_TABLE.SEND);var ei=Zt,convertFramesizeToResolution=g=>ei.Send.getResolutionByFs(g).height,convertResolutionToFramesize=g=>ei.Send.getMaxFsForHeight(g),ti={numVideoChannelsGvc:({current:g,constraints:f})=>getMaxIncomingStreams(g,f),specCompliantSimulcast:({current:g,constraints:f})=>getMaxSimulcastLayers(g,f),multiviewResolutionLimits:({current:g,constraints:f,logger:S})=>getMaxParticipantResolutions(g,f,S),enableVla:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getVlaEnabledStatus(g,f,S,v),allowRemoteVla:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getVlaEnabledStatus(g,f,S,v),enableNonAdvVla:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getVlaEnabledStatus(g,f,S,v),outgoingVideoLimit:({current:g,settings:f,constraints:S})=>getOutgoingVideoLimit(g,f,S),webrtcCameraOpenFs:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getMaxFsAccordingToLimit(g,f,S,v),webrtcVideoCapabilityMaxFS:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getMaxFsAccordingToLimit(g,f,S,v)},convertCallConstraintsToSettings=(g,f,S)=>({...buildSettings(g,f,S),...buildSettings(g,f,S,"1on1"),...buildSettings(g,f,S,"Multiparty")}),buildSettings=(g,f,S,v)=>{const C={};for(const _ of Object.keys(ti)){const T=`${_}${v??""}`;v&&!isDefined(f[T])||(C[T]=ti[_]({current:f[T],settings:f,constraints:S,settingsSuffix:v,logger:g}))}return C},getMaxIncomingStreams=(g,f)=>getMinDefined(g,f.maxIncomingStreams),getMaxParticipantResolutions=(g,f,S)=>{const v=f.maxParticipantResolutions;if(!v)return g;const C={more:g.more};if(Number.isInteger(v))Object.keys(g).forEach((f=>{C[f]=getMinDefined(v,g[f])}));else{const f=Object.keys(v);if(!f.length)return S.warn(`ignoring invalid value provided for maxParticipantResolutions: ${v}}`),g;f.forEach((f=>{C[f]=getMinDefined(v[f],g[f]||g.more)}))}return C},getMaxSimulcastLayers=(g,f)=>void 0!==f.maxSimulcastLayers||g.allowOverride?{...g,video:getConstrainedSimulcastConfig(g.video,f),sharing:getConstrainedSimulcastConfig(g.sharing,f)}:g,getConstrainedSimulcastConfig=(g,f)=>{const S=g?.layerScaleFactors?.filter((g=>g<=f.maxSimulcastLayers));return S?.length>1?{...g,layerScaleFactors:S}:{...g,enableLocally:!1,allowEnableRemotely:!1}},getMaxResolutionFromConstraints=g=>getMinDefined((0,Qt.isNumber)(g?.outgoingVideoLimit)?g?.outgoingVideoLimit:g?.outgoingVideoLimit?.maxResolution,g?.maxOutgoingResolution),getOutgoingVideoLimit=(g,f,S)=>{const{outgoingVideoLimit:v}=S,C=(0,Qt.isNumber)(v),_=getMaxResolutionFromConstraints(S);if(f.sendVideoCapabilityManager?.isEnabled){const fsToResolution=g=>g?convertFramesizeToResolution(g):g,resolve=(g,f,S,v)=>f?getMaxDefined(getMinDefined(f,v),S):g,_=C?void 0:v?.maxFramerate,T=C?void 0:v?.maxBitrate,I=getMaxResolutionFromConstraints(S);return{...g,maxResolution:resolve(g?.maxResolution,I,fsToResolution(f.sendVideoCapabilityManager?.minFS),fsToResolution(f.sendVideoCapabilityManager?.maxFS)),maxFramerate:resolve(g?.maxFramerate,_,f.sendVideoCapabilityManager?.minFPS,f.sendVideoCapabilityManager?.maxFPS),maxBitrate:resolve(g?.maxBitrate,T)}}let T=getMinDefined(g?.maxResolution,_);if(_>0&&f.maxCameraFsViaCallConstraints>0){const g=convertFramesizeToResolution(f.maxCameraFsViaCallConstraints);T=getMaxDefined(getMinDefined(T,g),getMinDefined(_,g))}const I=getMinDefined(g?.maxBitrate,C?void 0:v?.maxBitrate),b=getMinDefined(g?.maxFramerate,C?void 0:v?.maxFramerate);return{...g,maxResolution:T,maxBitrate:I,maxFramerate:b}},getMaxFsAccordingToLimit=(g,f,S,v)=>{if(getMaxResolutionFromConstraints(S)>0&&f.maxCameraFsViaCallConstraints>0){const C=`outgoingVideoLimit${v??""}`,{maxResolution:_}=getOutgoingVideoLimit(f[C],f,S);return getMaxDefined(g,_?convertResolutionToFramesize(_):g)}return g},getVlaEnabledStatus=(g,f,S,v)=>!((f.specCompliantSimulcast.constraintsDisableVla||f[`specCompliantSimulcast${v}`]?.constraintsDisableVla)&&S.maxSimulcastLayers<2)&&g,ii=class extends Ht{constructor(g){super(g),this.logger=g,this._constraints={},this._callConstraintsTelemetry=[]}get constraints(){return this._constraints}get callConstraintsTelemetry(){return this._callConstraintsTelemetry}addCallConstraintsTelemetryEvent(g,f){const S={timestamp:(new Date).getTime(),type:f,value:g};this._callConstraintsTelemetry.push(S)}setConstraints(g){this.logger.debug("Setting new platform call constraints",JSON.stringify(g)),this._constraints=g,this.addCallConstraintsTelemetryEvent(g,"requested"),this.raiseChanged()}getSettings(g){return convertCallConstraintsToSettings(this.logger,g,this._constraints)}},ni=M,ri='"rtcmedia"';function getRelayCredentials(g){return{expires:g.expires,username:g.username,password:g.password,realm:g.realm}}var si=class{constructor(g){this.version=g,this.reports={},this.version||(this.version=1)}watch(g){const f={time:Date.now(),duration:-1,version:this.version};return this.reports[g]&&(g=`${g}_last`),this.reports[g]=f,{end:g=>{g&&(f.error=g),f.duration=Date.now()-f.time}}}getReports(){return this.reports}};function clientToRelayConfig(g){return{Service:g.Service,Relay:g.Relay,Token:g.Token}}var ai="configFetch",oi="skypeTokenFetch",li="trapTokenFetch",ci=class{constructor(g){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new si,this.context=g,this.logger=g.logger.createChild("RM"),this.request=g.request,this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setRelayOverride(g){this.relaysOverride=g}setDefaultRelayConfig(g){this.config??(this.config=g)}async queryRelaysAsync(g={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const f=await this.updateRelaysPromise;return f?"turn"===g.relayType?f.Turn:g.isRemoteClientLync?f.Lync:f.Skype:[]}getAuthTokenStats(){}getStats(){return{config:clientToRelayConfig(this.config),stats:this.timers.getReports()}}updateRelaysFromConfigAsync(g=!1){const f=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((g=>(this.updateRelaysPromise=f,g))).catch((f=>(this.updateRelaysPromise=null,g?this.logger.warn("failed to retrieve relays",stringifyRequestResponse(f)):this.logger.error("failed to retrieve relays",stringifyRequestResponse(f)),null)));return f}refreshRelaysFromConfig(){this.request.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}updateRelaysAsync(){const g=this.config.Service.tokenUrl;let f;const fetchTrapTokenThroughProvider=async()=>(f=this.timers.watch(li),this.context.trapTokenCredentialsProvider()),fetchTrapTokenDirectly=async()=>{const S=this.timers.watch(oi);let v="";try{v=await this.context.tokenProvider(),this.logger.info("fetching skypeToken")}catch(g){throw S.end(stringifyRequestResponse(g)),g}S.end(),f=this.timers.watch(li);return(await this.request.get(g,{headers:{"X-Skypetoken":v,"api-version":2}})).response},S=this.context.trapTokenCredentialsProvider?fetchTrapTokenThroughProvider:fetchTrapTokenDirectly;return this.logger.info("Fetch TRAP token "+(this.context.trapTokenCredentialsProvider?"with provider":"directly")),S().then((g=>{f.end();let S=0;const v=this.config.Token.earlyRefreshMinutes,C=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(g),S=Math.max(g.expires-60*v,g.expires*C/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*S);const _=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:ri,T=getRelayCredentials(this.getTrapToken(_)),I={addresses:this.config.Relay.Skype.addresses,fqdns:this.config.Relay.Skype.fqdns,tcpPort:this.config.Relay.Skype.tcpPort,udpPort:this.config.Relay.Skype.udpPort,type:"msturn"},b={addresses:this.config.Relay.Lync.addresses,fqdns:this.config.Relay.Lync.fqdns,tcpPort:this.config.Relay.Lync.tcpPort,udpPort:this.config.Relay.Lync.udpPort,type:"msturn"},A={addresses:this.config.Relay.Turn.addresses,fqdns:this.config.Relay.Turn.fqdns,tcpPort:this.config.Relay.Turn.tcpPort,udpPort:this.config.Relay.Turn.udpPort,tlsPort:this.config.Relay.Turn.tlsPort,type:"turn"},P={Skype:[{...I,...T}],Lync:[{...b,...T}],Turn:[{...A,...T}]};return this.logger.info("relays from trap",[I,b,A]),P})).catch((g=>{throw f&&f.end(stringifyRequestResponse(g)),g}))}storeTrapTokens(g){if(!g?.tokens)return void this.logger.error("failed to get tokens from trap response");const f={};g.tokens.forEach((S=>{f[S.realm]={expires:g.expires,username:S.username,password:S.password,realm:S.realm}})),this.trapTokens=f}getTrapToken(g){if("string"==typeof g){const f=g.replace(/^"|"$/g,""),S=`"${f}"`,v=this.trapTokens[S]||this.trapTokens[f];if(v)return v}throw new Error(`token for relay not found, realm: ${g}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const g=this.timers.watch(ai);try{const f=await this.context.configProvider();g.end(),this.logger.info("retrieved configuration:",f),(0,ni.isEmpty)(f)||(this.config=f),this.logger.info("applied configuration:",this.config)}catch(f){this.logger.warn("failed to retrieve configuration",stringifyObject(f)),g.end(stringifyRequestResponse(f))}}};function build(g){return new ci(g)}var di=M,hi="aadTokenFetch",ui=class{constructor(g){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new si(2),this.context=g,this.authTokenFetcher=this.context.authTokenFetcher,this.logger=g.logger.createChild("RM2")}setRelayOverride(g){this.relaysOverride=g}setDefaultRelayConfig(g){this.config??(this.config=g),this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setClientSupportsGenericTokenApi(g){this.authTokenFetcher.supportsGenericTokenApi=g}async queryRelaysAsync(g={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const f=await this.updateRelaysPromise;return f?"turn"===g.relayType?f.Turn:g.isRemoteClientLync?f.Lync:f.Skype:[]}getStats(){return{config:clientToRelayConfig(this.config),stats:this.timers.getReports()}}getAuthTokenStats(){return this.context.authTokenFetcher.getStats()}updateRelaysFromConfigAsync(g=!1){const f=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((g=>(this.updateRelaysPromise=f,g))).catch((f=>(this.updateRelaysPromise=null,g?this.logger.warn("failed to retrieve relays",stringifyRequestResponse(f)):this.logger.error("failed to retrieve relays",stringifyRequestResponse(f)),null)));return f}refreshRelaysFromConfig(){this.context.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}async updateRelaysAsync(){const g=this.context.configProvider?.config.useNewTokenApi?hi:oi,f=this.timers.watch(g),S=generateCauseId();this.logger.info(`${S}[RM2] Fetch TRAP token`);try{const g=await this.context.authTokenFetcher.fetchTrapToken(S,this.config);f.end();let v=0;const C=this.config.Token.earlyRefreshMinutes,_=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(g),v=Math.max(g.expires-60*C,g.expires*_/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*v);const T=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:ri,I=getRelayCredentials(this.getTrapToken(T)),b={addresses:this.config.Relay.Skype.addresses,fqdns:this.config.Relay.Skype.fqdns,tcpPort:this.config.Relay.Skype.tcpPort,udpPort:this.config.Relay.Skype.udpPort,type:"msturn"},A={addresses:this.config.Relay.Lync.addresses,fqdns:this.config.Relay.Lync.fqdns,tcpPort:this.config.Relay.Lync.tcpPort,udpPort:this.config.Relay.Lync.udpPort,type:"msturn"},P={addresses:this.config.Relay.Turn.addresses,fqdns:this.config.Relay.Turn.fqdns,tcpPort:this.config.Relay.Turn.tcpPort,udpPort:this.config.Relay.Turn.udpPort,tlsPort:this.config.Relay.Turn.tlsPort,type:"turn"},R={Skype:[{...b,...I}],Lync:[{...A,...I}],Turn:[{...P,...I}]};return this.logger.info("relays from trap",[b,A,P]),R}catch(g){throw this.logger.info(`Fetch TRAP token failed with error ${g}`),f&&f.end(stringifyRequestResponse(g)),g}}storeTrapTokens(g){const f={};if(g?.tokens)g.tokens.forEach((S=>{f[S.realm]={expires:g.expires,username:S.username,password:S.password,realm:S.realm}}));else{if(!g.realm)return void this.logger.error("failed to get tokens from trap response");f[g.realm]=g}this.trapTokens=f}getTrapToken(g){if("string"==typeof g){const f=g.replace(/^"|"$/g,""),S=`"${f}"`,v=this.trapTokens[S]||this.trapTokens[f];if(v)return v}throw new Error(`token for relay not found, realm: ${g}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const g=this.timers.watch(ai);try{const f=await this.context.relayConfigProvider();g.end(),this.logger.info("retrieved configuration:",f),(0,di.isEmpty)(f)||(this.config=f),this.logger.info("applied configuration:",this.config)}catch(f){this.logger.warn("failed to retrieve configuration",stringifyRequestResponse(f)),g.end(stringifyRequestResponse(f))}}},gi=class{constructor(g,f,S,v,C){this.signalingAgentProvider=f,this.request=S,this.tokenProviders=v,this.configProvider=C,this.errors=[],this.clientSupportsGenericTokenAPI=!1,this.logger=g.createChild("AuthTokenFetcher")}set supportsGenericTokenApi(g){this.clientSupportsGenericTokenAPI=g}buildHeaders(g,f){const S={"api-version":2};switch(this.configProvider?.config.useTokenMigrationHeader&&(S["X-MS-Migration"]="True"),g){case 4:case 8:return S.Authorization=`Bearer ${f}`,S;case 1:return S["X-Skypetoken"]=f,S;default:throw new Error(`TokenType ${g} is not supported`)}}serviceSupportedTokenTypes(g){let f=null;if(void 0===g)f=this.clientSupportedTokenTypes();else{const S=g?.toLowerCase();f=this.constructTokenType(S)}return null===f&&this.configProvider?.config.useSkypeTokenWhenNoAuthenticateHeader&&(f|=1),f}extractWwwauthenticateHeaders(g){let f={};if(g){const S=getHeaderValue(g,"www-authenticate");S&&(f={authenticationHeaders:[S]})}return f}convertStringToTokenType(g){switch(g){case"cae":return 8;case"aad":return 4;case"skype":return 1;default:return this.logger.info("[authTokenFetcher][convertStringToTokenType]unexpected: unrecognized token type ${tokenType}"),null}}getTokenTypeFromHeaders(g,f){if(!this.clientSupportsGenericTokenAPI)return 1;let S=null;const v=f?.authenticationHeaders;if(!v&&g)this.configProvider?.config.useSkypeTokenWhenNoAuthenticateHeader?(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),S=1):(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),S=this.clientSupportedTokenTypes());else if(v||g){if(v&&g)for(const g of v){const f=parseServiceTokenTypes(g);if(this.configProvider?.config.supportMissingTokenTypesInResponse&&0===f.length)this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),S=this.clientSupportedTokenTypes();else for(const g of f){const f=this.convertStringToTokenType(g.toLowerCase());this.configProvider?.config.clientSupportsCaeToken&&8===f&&(S|=8),this.configProvider?.config.clientSupportsAadToken&&4===f&&(S|=4),this.configProvider?.config.clientSupportsSkypeToken&&1===f&&(S|=1)}}}else this.logger.info("[authTokenFetcher][getTokenTypeFromHeaders] retrying to fetch token woth client supported tokens"),S=this.clientSupportedTokenTypes();return S}constructTokenType(g){let f=null;return g.includes("aad")&&this.configProvider?.config.clientSupportsAadToken&&(f|=4),g.includes("cae")&&this.configProvider?.config.clientSupportsCaeToken&&(f|=8),g.includes("skype")&&this.configProvider?.config.clientSupportsSkypeToken&&(f|=1),f}getTokenMetadataForTrapService(g,f,S){const v={verb:"POST",path:g},C=JSON.stringify(v);let _=null;const T=this.extractWwwauthenticateHeaders(S),I=!!T?.authenticationHeaders;return _=S?this.getTokenTypeFromHeaders(I,T):this.serviceSupportedTokenTypes(f),this.logger.info(`[authTokenFetcher][getTokenMetadata] return token type=${_}, factoJson=${C}`),{tokenType:_,factorsJson:C,requestMetadataJson:T,isUnauthorized:I}}clientSupportedTokenTypes(){let g=null;return this.configProvider?.config.clientSupportsAadToken&&(g|=4),this.configProvider?.config.clientSupportsCaeToken&&(g|=8),this.configProvider?.config.clientSupportsSkypeToken&&(g|=1),g}async handleAuthTokenFailure(g,f,S,v){this.logger.info("[authTokenFetcher][handleAuthTokenFailure] failed to fetch token, retrying");try{const C=this.getTokenMetadataForTrapService(f,void 0,S);this.logger.info(`[authTokenFetcher][handleAuthTokenFailure] token request options=${C}`),C.invalidToken=v;return await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(g,!1,C)}catch(g){const f={status:g?.response?.status||g?.status,error:g,fatal:!0};this.errors.push(stringifyObject(f)),this.logger.error(`[authTokenFetcher] failed to fetch token trough new api with error: ${stringifyObject(f)}, quiting`)}}getRequestToken(g){const f=getHeaderValue(g,"X-Skypetoken");if(f)return f;const S=getHeaderValue(g,"Authorization");if(S){const g=S.split(" ");if(2===g.length)return g[1]}}async fetchTrapCredentials(g,f,S){const v=this.buildHeaders(f,g),C=await this.request.get(S,{headers:v});return C?.response}async fetchTrapTokenWithNewTokenApi(g,f,S){let v;this.logger.info(`${S}[authTokenFetcher] fetching token through fetchTrapTokenWithNewTokenApi`);const C=this.getTokenMetadataForTrapService(g,f);try{v=await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(S,!1,C),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(S);return await this.fetchTrapCredentials(v,this.tokenTypeFetched,g)}catch(f){const C={status:f?.response?.status||f?.status,error:f,fatal:!1};this.errors.push(stringifyObject(C)),this.logger.error(`${S}[authTokenFetcher] fetchTrapTokenWithNewTokenApi failed with ${stringifyObject(C)}, retrying...`);const _=f?.response?.headers;if(_){const f=this.getRequestToken(_);v=await this.handleAuthTokenFailure(S,g,_,f),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(S);return await this.fetchTrapCredentials(v,this.tokenTypeFetched,g)}throw f}}async fetchTrapTokenThroughProvider(){return this.logger.info("[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokenThroughProvider"),this.tokenProviders.trapTokenCredentialsProvider()}async fetchTrapTokensWithLegacyTokenFetcher(g,f){this.logger.info(`${f}[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokensWithLegacyTokenFetcher`);try{this.tokenTypeFetched=1;const f=await this.tokenProviders.skypeTokenProvider();return(await this.request.get(g,{headers:{"X-Skypetoken":f,"api-version":2}})).response}catch(g){throw this.errors.push(stringifyObject(g)),this.logger.error(`${f}[authTokenFetcher] fetchTrapTokensWithLegacyTokenFetcher failed with ${stringifyObject(g)}`),g}}getStats(){return{tokenType:this.tokenTypeFetched,errors:limitArraySize(this.errors,this.configProvider?.config.diagnostics.telemetryLimits.numAuthTokenErrors??100)}}async fetchTrapToken(g,f){let S;this.logger.info(`${g}[AuthTokenFetcher] Start fetching token`);const v=f.Service.tokenUrl,C=f.Service.supportedTokenTypes;return S=this.configProvider?.config.useNewTokenApi?this.fetchTrapTokenWithNewTokenApi(v,C,g):this.tokenProviders.trapTokenCredentialsProvider?this.fetchTrapTokenThroughProvider():this.fetchTrapTokensWithLegacyTokenFetcher(v,g),S}},pi=class{constructor(g,f,S,v){this.config=g,this.signalingAgentProvider=f,this.ecsProvider=S,this.logger=v}getOrCreateRelayManager(){return this.config.relayManager?this.config.relayManager:this.relayManager||this.createRelayManager()}setConfigProvider(g){this.configProvider=g}createRelayManager(){return this.relayManager??(this.relayManager=this.buildRelayManager(this.config.httpRequestDispatcher,this.config.tokenProvider,this.config.configProvider,this.config.appStateProvider,this.config.trapTokenCredentialsProvider,this.configProvider))}buildRelayManager(g,f,S,v,C,_){const T=g||new $e(this.logger),I=this.ecsProvider.getEcsConfig("SkypeCalling","enableFetchApi"),b={get:(g,f)=>T.getAsync(g,{...T.getRequestOptions("GET",f?.headers,null,f?.timeout),useFetch:I}),isOnline:v.isOnline};if(this.configProvider?.config.useNewTokenApi){const g=new gi(this.logger,this.signalingAgentProvider,b,{skypeTokenProvider:f,trapTokenCredentialsProvider:C},_);return new ui({logger:this.logger,relayConfigProvider:()=>S.getRelayConfig(),isOnline:v.isOnline,authTokenFetcher:g,configProvider:_})}return build({logger:this.logger,tokenProvider:f,trapTokenCredentialsProvider:C,configProvider:()=>S.getRelayConfig(),request:{get:(g,f)=>T.getAsync(g,{...T.getRequestOptions("GET",f?.headers,null,f?.timeout),useFetch:I}),isOnline:v.isOnline}})}},mi={CALL_SETUP_NATIVE:"skypecosi_concore_native_ts_calling_call_setup_session",CALL_IN_CALL_NATIVE:"skypecosi_concore_native_ts_calling_in_call_session",REGISTRY_WEB:"skypecosi_concore_web_ts_calling_registry",REGISTRY_NATIVE:"skypecosi_concore_native_ts_calling_registry"},fi={PARK:"*11",SHARED_LINE:"*12",SERVER_HOLD:"*13",CALL_PARK:"*14"},Si={totalParticipants:0,preheatedParticipants:0,lobbyParticipants:0,totalPresenters:0,requestingAttentionPresenters:0,totalAttendees:0,requestingAttentionAttendees:0,overflowAttendees:0},vi=R,Ci=150,yi=30,Ei=class{constructor(g,f,S,v,C){this.eventName=g,this.eventStartTime=f,this.type=S,this.causeId=v,this.status="Pending",this.eventStartTimestamp=(new Date).getTime(),this.data=[],this.causeId=v?.substring(0,8),"Event"===this.type&&delete this.status,C&&this.data.push(C)}set variant(g){this.eventVariant=g}recordSuccess(g,f){this.recordResult("Success",g,f)}recordFailure(g,f){this.recordResult("Failure",g,f)}recordTimeout(g,f){this.recordResult("Timeout",g,f)}addData(g){this.data.push(g)}isPending(){return"Pending"===this.status}getEvent(){const g={start:this.eventStartTime,duration:this.duration,status:this.status,result:this.result,causeId:this.causeId,resultCauseId:this.resultCauseId,variant:this.eventVariant,data:this.data.map((g=>this.prepareData(g,!0))).filter((g=>!!g))};return"Event"===this.type&&delete g.status,g.data.length||delete g.data,g.causeId||delete g.causeId,g.resultCauseId||delete g.resultCauseId,g.result||delete g.result,g.variant||delete g.variant,{[this.eventName]:g}}recordResult(g,f,S){this.status=g,this.result=this.prepareData(f),this.causeId!==S&&(this.resultCauseId=S),this.duration=(new Date).getTime()-this.eventStartTimestamp}prepareData(g,f=!1){if(null==g)return"";if("string"==typeof g)return scrubMriOrOmit(g);if("number"==typeof g||"boolean"==typeof g)return String(g);if("function"==typeof g)return"";if(g instanceof Error)return g.toString();try{return Object.keys(g).length?f?g:getPIISafeObject(g):""}catch(g){return"invalid"}}},_i=class{constructor(g,f,S,v){this.logger=g,this.startTime=f,this.maxEventsExceeded=S,this.perfModule=v,this.recordedEvents=[],this.ipcStats=[],this.ongoingOperations={}}recordEvent(g,f,S=generateCauseId()){this.logger.debug("Event:",g,vi.pii.Omit(f));const v=new Ei(g,this.getEventStartTime(),"Event",S,f);return this.pushToRecordedEvents(v),v}recordOperationSuccess(g,f=null,S,v,C){this.logger.info("Event success:",v,g,vi.pii.Omit(S),vi.pii.Omit(f)),this.recordOperationResult(g,f,"Success",S,v,C)}recordOperationFailure(g,f,S,v,C){this.logger.info("Event failure:",g,vi.pii.Omit(S),f),this.recordOperationResult(g,f,"Failure",S,v,C)}recordOperationTimeout(g,f,S,v,C){this.logger.info("Event timeout:",g,vi.pii.Omit(S),f),this.recordOperationResult(g,f,"Timeout",S,v,C)}maybeRecordOperationSuccess(g,f=null,S,v,C){this.hasOngoingEvent(g,S)&&this.recordOperationSuccess(g,f,S,v,C)}maybeRecordOperationFailure(g,f,S,v,C){this.hasOngoingEvent(g,S)&&this.recordOperationFailure(g,f,S,v,C)}maybeRecordOperationTimeout(g,f,S,v,C){this.hasOngoingEvent(g,S)&&this.recordOperationTimeout(g,f,S,v,C)}recordOperationResult(g,f,S,v,C,_){this.hasOngoingEvent(g,v)||this.recordOperation(g,C,v);let T=this.ongoingOperations[g];switch(v&&(T=T[v]),_&&T.addData(_),S){case"Success":T.recordSuccess(f,C);break;case"Failure":T.recordFailure(f,C);break;case"Timeout":T.recordTimeout(f,C);break;default:this.logger.error("Unknown operation record state in record operation result.")}v?delete this.ongoingOperations[g][v]:delete this.ongoingOperations[g]}recordOperation(g,f,S,v){this.logger.debug("Event create:",f,g,vi.pii.Omit(S),v);const C=new Ei(g,this.getEventStartTime(),"Operation",f,v);return this.ongoingOperations[g]||(this.ongoingOperations[g]={}),S?this.ongoingOperations[g][S]=C:this.ongoingOperations[g]=C,this.pushToRecordedEvents(C),C}setOperationVariant(g,f,S){let v;v=S?this.ongoingOperations[g][S]:this.ongoingOperations[g],v?v.variant=f:this.logger.error(`Could not find operation ${g} to set variant ${f}`)}updateOperationData(g,f,S,v){try{if(!this.ongoingOperations[g])return void this.recordEvent(g,f,S);v?this.ongoingOperations[g][v]&&this.ongoingOperations[g][v].addData(f):this.ongoingOperations[g].addData(f)}catch(f){return void this.logger.info(`Unable to update operation: ${g} data`)}}pushToRecordedEvents(g){if(this.maxEventsExceeded&&this.maxEventsExceeded()&&this.recordedEvents.shift(),this.recordedEvents.push(g),this.perfModule&&this.ipcStats.length<=yi){const g=this.perfModule.getIpcStats();g&&this.ipcStats.push({ingestionTime:this.getEventStartTime(),stats:g})}}hasOngoingEvent(g,f){return this.ongoingOperations[g]?!(f&&!this.ongoingOperations[g][f])||(this.logger.warn(`Unable to find event for name\\id ${g}\\${vi.pii.Omit(f)}`),!1):(this.logger.warn(`Unable to find event for name ${g}`),!1)}getEventStartTime(){return(new Date).getTime()-this.startTime}getEventTimestampBag(g,f){const S=f?[f.getEvent()]:this.recordedEvents.filter((f=>!g||!f.isPending())).map((g=>g.getEvent())),v=JSON.stringify({eventStart:this.startTime,events:S});return this.logger.info(`Call eventTimestampBag ${vi.pii.Omit(v)}`),v}getIPCStats(){return 0!==this.ipcStats.length?JSON.stringify(this.ipcStats):""}removeRecordedEvent(g){const f=this.recordedEvents.indexOf(g);f>-1&&this.recordedEvents.splice(f,1)}},Ti=class extends _i{constructor(g,f){super(g,f,(()=>this.recordedEvents.length>Ci)),this.getHostName=()=>{try{return"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>"}catch(g){return"unknown"}},this.tsCallingVersion=getTsCallingVersion(),this.logger=g.createChild("CallRegistryTelemetry")}setClientType(g){this.clientType=g}setEndpointId(g){this.endpointId=g}setSkypeId(g){this.skypeId=scrubMriOrOmit(g)}setApplicationType(g){this.applicationType=g}setRing(g){this.ring=g}setTenantId(g){this.tenantId=g}setUserHexCID(g){this.userHexCID=g}setAcsResourceId(g){this.acsResourceId=g}setRegion(g){this.region=g}setPartition(g){this.partition=g}getEvent(g,f){const getValue2=g=>void 0===g?"":g;return{EndpointId:getValue2(this.endpointId),SkypeId:getValue2(this.skypeId),ApplicationType:getValue2(this.applicationType),Ring:getValue2(this.ring),TenantId:getValue2(this.tenantId),userHexCID:getValue2(this.userHexCID),AcsResourceId:getValue2(this.acsResourceId),Region:getValue2(this.region),Partition:getValue2(this.partition),TsCallingVersion:getValue2(this.tsCallingVersion),HostName:this.getHostName(),EventTimestampBag:this.getEventTimestampBag(g,f),DiagnosticInfo:this.callEndDiagnosticInfo,ClientType:getValue2(this.clientType)}}removeNonPendingOperations(){this.recordedEvents=this.recordedEvents.filter((g=>g.isPending()))}},Ii=class extends _i{constructor(g,f,S){super(g,f,(()=>this.inCallMode&&this.recordedEvents.length>Ci),S),this.inCallMode=!1,this.tsCallingVersion=getTsCallingVersion(),this.logger=g.createChild("CallTelemetry")}setClientType(g){this.clientType=g}setCallId(g){this.currentCallId&&(this.previousCallId=this.currentCallId),this.currentCallId=g}setConsultativeCallId(g){this.consultativeCallId=g}setEndpointId(g){this.endpointId=g}setParticipantId(g){this.participantId=g}setDisplayName(g){this.displayName=g}setPreheatFlags(g){this.preheatFlags=g}setCallOrigin(g){this.origin=g}setGroupId(g){this.groupId=g}setThreadId(g){this.threadId=g}setBackroomThreadId(g){this.backroomThreadId=g}setStreamThreadId(g){this.streamThreadId=g}setLobbyThreadId(g){this.lobbyThreadId=g}setComplianceRecordingContentLength(g){this.complianceRecordingContentLength=g}setConversationStartTime(g){this.conversationStartTime=g}setMessageId(g){this.messageId=g}setSkypeId(g){this.skypeId=scrubMriOrOmit(g)}setApplicationType(g){this.applicationType=g}setRing(g){this.ring=g}setTenantId(g){this.tenantId=g}setUserHexCID(g){this.userHexCID=g}setAcsResourceId(g){this.acsResourceId=g}setRegion(g){this.region=g}setPartition(g){this.partition=g}setFailureType(g){this.failureType=g}setIsCast(g){this.isCast=g?"True":"False"}setIsHuddleGroupCall(g){this.isHuddleGroupCall=g?"True":"False"}setIsEmergency(g){this.isEmergency=g?"True":"False"}setRole(g){this.isAnonymous="admin"===g?"False":"True"}setCallType(g){this.callType=g}setConversationType(g){this.conversationType=g}setDirection(g){this.direction=g}setSelfParticipantRole(g){this.selfParticipantRole=g}setTerminationState(g){this.terminationState=g}setTerminationReason(g){this.terminationReason=g}setCallEndDiagnosticInfo(g){this.callEndDiagnosticInfo=g}setStackConfig(g){this.stackConfig=g}setJoinedFrom(g){this.joinedFrom=g}setMeetingCode(g){this.meetingCode=g}setMeetingUrl(g){this.meetingUrl=g}setHasMeetingRegistrationId(g){this.hasMeetingRegistrationId=g?"True":"False"}setHasParticipantPin(g){this.hasParticipantPin=g?"True":"False"}getEvent(g,f){const getValue2=g=>void 0===g?"":g;return{CorrelationId:getValue2(this.currentCallId),PreviousCorrelationId:getValue2(this.previousCallId),ConsultativeCallId:getValue2(this.consultativeCallId),EndpointId:getValue2(this.endpointId),SkypeId:getValue2(this.skypeId),ParticipantId:getValue2(this.participantId),DisplayName:new Ue(this.displayName??"",1),PreheatFlags:getValue2(this.preheatFlags),CallType:getValue2(this.callType),ConversationType:getValue2(this.conversationType),Direction:getValue2(this.direction),Origin:getValue2(this.origin),SelfParticipantRole:getValue2(this.selfParticipantRole),IsAnonymous:getValue2(this.isAnonymous),GroupId:scrubMriOrOmit(getValue2(this.groupId)),ThreadId:getLoggableThreadId(getValue2(this.threadId)),MessageId:getValue2(this.messageId),ApplicationType:getValue2(this.applicationType),Ring:getValue2(this.ring),TenantId:getValue2(this.tenantId),UserHexCID:getValue2(this.userHexCID),AcsResourceId:getValue2(this.acsResourceId),Region:getValue2(this.region),Partition:getValue2(this.partition),FailureType:getValue2(this.failureType),IsCast:getValue2(this.isCast),IsHuddleGroupCall:getValue2(this.isHuddleGroupCall),IsEmergency:getValue2(this.isEmergency),TsCallingVersion:getValue2(this.tsCallingVersion),TerminationState:getValue2(this.terminationState),TerminationReason:getValue2(this.terminationReason),StackConfig:getValue2(this.stackConfig),EventTimestampBag:this.getEventTimestampBag(g,f),HostName:this.getHostName(),DiagnosticInfo:this.callEndDiagnosticInfo,JoinedFrom:this.joinedFrom,MeetingCode:this.meetingCode,MeetingUrl:this.meetingUrl,HasMeetingRegistrationId:this.hasMeetingRegistrationId,HasParticipantPin:this.hasParticipantPin,IPCStats:this.getIPCStats(),ComplianceRecordingContentLength:getValue2(this.complianceRecordingContentLength),ConversationStartTime:getValue2(this.conversationStartTime),BackroomThreadId:getLoggableThreadId(getValue2(this.backroomThreadId)),StreamThreadId:getLoggableThreadId(getValue2(this.streamThreadId)),LobbyThreadId:getLoggableThreadId(getValue2(this.lobbyThreadId)),ClientType:getValue2(this.clientType)}}getShortEvent(){const getValue2=g=>void 0===g?"":g;return{CorrelationId:getValue2(this.currentCallId),EndpointId:getValue2(this.endpointId),ParticipantId:getValue2(this.participantId),DisplayName:new Ue(this.displayName??"",1),CallType:getValue2(this.callType),ConversationType:getValue2(this.conversationType),Direction:getValue2(this.direction),Origin:getValue2(this.origin),SelfParticipantRole:getValue2(this.selfParticipantRole),IsAnonymous:getValue2(this.isAnonymous),ThreadId:getLoggableThreadId(getValue2(this.threadId)),ApplicationType:getValue2(this.applicationType),Ring:getValue2(this.ring),TenantId:getValue2(this.tenantId),UserHexCID:getValue2(this.userHexCID),AcsResourceId:getValue2(this.acsResourceId),Region:getValue2(this.region),TsCallingVersion:getValue2(this.tsCallingVersion),DiagnosticInfo:this.callEndDiagnosticInfo,JoinedFrom:this.joinedFrom,ClientType:getValue2(this.clientType)}}switchToInCallTelemetry(){this.recordedEvents=this.recordedEvents.filter((g=>g.isPending())),this.inCallMode=!0}getHostName(){try{return location.host}catch(g){return"unknown"}}},getEndpointInformationForTelemetry=g=>Array.isArray(g)?g.map((g=>({endpointId:g.endpointId,participantId:g.participantId}))):null,calculateJoinedFromForTelemetry=(g,f,S,v,C)=>{if(g){if(g.meetingUrl)return"MeetingUrl";if(g.meetingCode)return"MeetingCode"}return f||S?"ThreadContext":v?"GroupId":C?"Awareness":""};function sanitizeMeetingCode(g,f,S){if(!g)return S.info(`sanitizeMeetingCode[${f}] empty / undefined meeting code parameter`),g;let v=g.replace(/\s/g,"");return v=v.replace(/-/g,""),S.info(`sanitizeMeetingCode[${f}] meetingCode: ${g}, sanitizedMeetingCode: ${v}`),v}function getMeetingCodeFromMeetingUrl(g,f,S){if(!g)return S.info(`getMeetingCodeFromMeetingUrl[${f}] empty / undefined meeting Url parameter`),g;const v=new URL(g);let C="";if(v&&v.pathname&&v.pathname.split("/").length>=2){const g=v.pathname.split("/");"meet"===g[g.length-2]&&(C=g[g.length-1])}return S.info(`getMeetingCodeFromMeetingUrl[${f}] meetingUrl: ${g}, meetingUrlObject: ${safeJsonStringify(v)}, meetingCode: ${C}`),C}function compareMeetingData(g,f,S,v){const C=sanitizeMeetingCode(g&&g.meetingCode||"",S,v),_=sanitizeMeetingCode(f&&f.meetingCode||"",S,v),definedAndEqual=(g,f)=>!!g&&!!f&&g===f;if(definedAndEqual(C,_))return!0;let T=getMeetingCodeFromMeetingUrl(g&&g.meetingUrl||"",S,v);T=sanitizeMeetingCode(T,S,v);let I=getMeetingCodeFromMeetingUrl(f&&f.meetingUrl||"",S,v);if(I=sanitizeMeetingCode(I,S,v),definedAndEqual(T,I))return!0;if(definedAndEqual(T,_)||definedAndEqual(I,C))return!0;if(g&&g.meetingUrl&&f&&f.meetingUrl){const S=new URL(g.meetingUrl),v=new URL(f.meetingUrl);if(S.hostname===v.hostname&&S.pathname===v.pathname)return!0}return!1}function noop(){}var bi={CODE:{SUCCESS:0,MEDIA_ERROR:410,CLIENT_ERROR_CODE:499,UNKNOWN_ERROR:497},SUB_CODE:{VDI_DISCONNECTED:3e3,ACTION_NOT_ALLOWED:3548,INVALID_DATA_TYPE:3757,ABANDONED:4990,ENDED_BY_REMOTE_ENDPOINT:5028,BEACON:4521,UNKNOWN_FAILURE:3545,SLIMCORE_CALL_SETUP_FAILURE:3546}},Ai=4294967294,Pi="_operationIdValue_",Ri="_causeIdValue_",Mi="_callStartOptionsValue_",wi="_clientReasonValue_";function callOperation(g,f,S=!1){return operationDecorator(0,g,f,S)}function participantOperation(g,f){return operationDecorator(1,g,f)}var operationId=(g,f,S)=>{if(g[f][Pi])throw new Error("can not specify more than one operation id");g[f][Pi]=S},causeId=(g,f,S)=>{if(g[f][Ri])throw new Error("can not specify more than one cause id");g[f][Ri]=S},callStartOptions=(g,f,S)=>{if(g[f][Mi])throw new Error("can not specify options more than once");g[f][Mi]=S},reason=(g,f,S)=>{if(g[f][wi])throw new Error("can not specify reason more than once");g[f][wi]=S},operationDecorator=(g,f,S,v=!1)=>(C,_,T)=>{const I=T.value,b=C[_]?.[Pi],A=C[_]?.[Ri],P=C[_]?.[Mi],R=C[_]?.[wi],M=S?.type||"Async";return T.value=function(...C){const _=this;let T=v?generateGuid():generateCauseId();void 0!==A&&(C[A]&&(validateCauseId(C[A])||validateGuid(C[A]))?T=C[A]:C[A]=T);let w,O=void 0!==b?C[b]:void 0;if(void 0!==O)if(Array.isArray(O))try{const g=O.map((g=>g.toString())).sort().concat().toString();O=getStringHash(g).toString()}catch{const g=`[${O}]${f} failed in array parsing in operationDecorator`,S={terminatedReason:32,terminatedReasonCode:bi.CODE.UNKNOWN_ERROR,terminatedReasonSubCode:bi.SUB_CODE.UNKNOWN_FAILURE,errorMessage:g};return Promise.reject(S)}else if(O&&"object"==typeof O)try{let g=JSON.stringify(O);S&&S.operationIdKey&&O.hasOwnProperty(S.operationIdKey)&&(g=O[S.operationIdKey]),O=g}catch{const g=`[${O}]${f} failed in object parsing in operationDecorator`,S={terminatedReason:32,terminatedReasonCode:bi.CODE.UNKNOWN_ERROR,terminatedReasonSubCode:bi.SUB_CODE.UNKNOWN_FAILURE,errorMessage:g};return Promise.reject(S)}void 0!==R&&C[R]&&(w=C[R]);const D=getOperationHandler(_,g);if(D.logOperation(T,f),S&&S.singular&&D.hasPendingOperation(f))return D.logOperation(T,f,"Not allowed, pending operation exists"),Promise.reject(60);if(S&&S.idempotencyLevel&&D.getRecord(f)>0)switch(D.logOperation(T,f,`Called multiple times, handling operation according to specified policy: idempotency=${S.idempotencyLevel}`),S.idempotencyLevel){case"NoOp":return Promise.resolve();case"Error":return Promise.reject(60)}try{void 0!==P&&C[P]&&_.processCallStartOptions(C[P],T)}catch{const g=`${f} failed in processCallStartOptions`,S={terminatedReason:32,terminatedReasonCode:bi.CODE.UNKNOWN_ERROR,terminatedReasonSubCode:bi.SUB_CODE.UNKNOWN_FAILURE,errorMessage:g};return Promise.reject(S)}const N=!(!S||!S.convertError),execute=()=>"Chained"===M?D.executeChained(I.bind(this,...C),f,O,T,N,w,S):"Sync"===M?D.executeSync(I.bind(this,...C),f,O,T,N,w):D.execute(I.bind(this,...C),f,O,T,N,w,S);if("StartCall"!==f&&"JoinCall"!==f||D.hasPendingOperation("_CallStartOrJoinInitiated")||D.createPendingOperation("_CallStartOrJoinInitiated").catch(noop),S&&S.triggerAttach&&(D.hasPendingOperation("_ElectronSlimcoreReady")||D.createPendingOperation("_ElectronSlimcoreReady").catch(noop)),S&&"Sync"!==S.type){const g=S&&S.waitFor;if(Array.isArray(g))return Promise.all(g.map((g=>g&&D.hasPendingOperation(g)&&D.waitForOperation(g,void 0,T)))).then(execute,execute);if(g&&D.hasPendingOperation(g))return D.waitForOperation(g,void 0,T).then(execute,execute)}return execute()},T},getOperationHandler=(g,f)=>{if(0===f)return g._callOperationHandler;if(1===f)return g._participantOperationHandler;throw new Error("Unsupported operation handler type!")};function getStringHash(g){let f=0;for(let S=0;S<g.length;S++){f=(f<<5)-f+g.charCodeAt(S),f|=0}return f}var Oi=class{constructor(g){this._disposed=!1,this._logger=g.createChild("[ASYNC]"),this._endOperationDeferred=new dt,this._endOperationDeferred.promise.catch((g=>{this._logger.info("Rejected all operations")})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._deferredOperationsWithCauseId={},this._logger=g}registerPromise(g,f){let S=!1;const always=()=>{S=!0};f.then(always,always);const v=this._endOperationDeferred.promise.catch((f=>{if(!S)throw new Error(`Operation ${g} did not complete, reason:${f}`)}));return Promise.race([v,f])}updateOperationId(g,f){this._logger.info(`updateOperationId ${g} ${f}`),Object.keys(this._deferredOperationsWithOperationId).forEach((S=>{S&&this._deferredOperationsWithOperationId[S]&&(this._logger.info(`_deferredOperationsWithOperationId ${S}`),Object.keys(this._deferredOperationsWithOperationId[S]).forEach((v=>{v&&this._deferredOperationsWithOperationId[S][v]&&(this._logger.info(`_deferredOperationsWithOperationId ${v} ${f}`),v===g&&(this._deferredOperationsWithOperationId[S][f]=this._deferredOperationsWithOperationId[S][v],delete this._deferredOperationsWithOperationId[S][v]))})))})),Object.keys(this._deferredOperationsWithCauseId).forEach((S=>{S&&this._deferredOperationsWithCauseId[S]&&(this._logger.info(`_deferredOperationsWithCauseId ${S}`),Object.keys(this._deferredOperationsWithCauseId[S]).forEach((v=>{v&&this._deferredOperationsWithCauseId[S][v]&&(this._logger.info(`_deferredOperationsWithCauseId ${v} ${f}`),v===g&&(this._deferredOperationsWithOperationId[S][f]=this._deferredOperationsWithOperationId[S][v],delete this._deferredOperationsWithOperationId[S][v]))})))}))}createPendingOperation(g,f,S=generateCauseId(),v={}){const C=new dt;C.promise.catch(noop);const _=this.getOperationInfoForLogging(S,g,f);let T;if(this._logger.info(`${_}[creating...]`),this._disposed)return this._logger.info(`${_}[create failed, call is disposed]`),Promise.reject(60);if(f){if(this._deferredOperationsWithOperationId[g]||(this._deferredOperationsWithOperationId[g]={}),this._deferredOperationsWithOperationId[g][f])return this._logger.warn(`${_} Deferred operation with given name and operation id is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${g}/${scrubMriOrOmit(f)}`));this._deferredOperationsWithOperationId[g][f]={deferred:C,causeId:S},this._deferredOperationsWithCauseId[S]||(this._deferredOperationsWithCauseId[S]={}),this._deferredOperationsWithCauseId[S][f]={deferred:C,options:v,operationName:g},T=this._endOperationDeferred.promise.catch((S=>{if(this.hasPendingOperationWithOperationId(g,f))throw new Error(`Operation ${g} ${f} did not complete, reason:${S}`)}))}else{if(this._deferredOperations[g])return this._logger.warn(`${_} Deferred operation with given name is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${g}`));this._deferredOperationsWithCauseId[S]||(this._deferredOperationsWithCauseId[S]={}),this._deferredOperationsWithCauseId[S][""]={deferred:C,options:v,operationName:g},this._deferredOperations[g]={deferred:C,causeId:S},T=this._endOperationDeferred.promise.catch((f=>{if(this.hasPendingOperation(g))throw new Error(`Operation ${g} did not complete, reason:${f}`)}))}return Promise.race([T,C.promise])}hasPendingOperation(g){return!!this._deferredOperations[g]}hasAtleastOneOfPendingOperation(g){for(const f of g)if(this.hasPendingOperation(f))return!0;return!1}hasPendingOperationWithOperationId(g,f){return!(!f||!this._deferredOperationsWithOperationId[g])&&!!this._deferredOperationsWithOperationId[g][f]}hasPendingOperationWithCauseId(g,f){const S=f||"";return this._deferredOperationsWithCauseId[g]&&!!this._deferredOperationsWithCauseId[g][S]}getPendingOperationWithCauseId(g,f){return this.hasPendingOperationWithCauseId(g,f)?this._deferredOperationsWithCauseId[g][f].deferred.promise:Promise.reject(`[${g}][${f}]: getPendingOperationWithCauseId for given causeId, operationId`)}resolveOperationWithCauseId(g,f,S){const v=f||"";if(this.hasPendingOperationWithCauseId(g,v)){const f=this._deferredOperationsWithCauseId[g][v],C=f.deferred.promise;return f.deferred.resolve(S),this._logger.info(`[${g}][${v}] resolved, result=${getPrintableObject(S)||"void"}`),delete this._deferredOperationsWithCauseId[g][v],C}return Promise.reject(`[${g}][${v}] resolveOperationWithCauseId failed, operation not found`)}rejectOperationWithCauseId(g,f,S){const v=f||"";if(this.hasPendingOperationWithCauseId(g,v)){const f=this._deferredOperationsWithCauseId[g][v],C=f.deferred.promise;return C.catch(noop),f.deferred.reject(S),this._logger.info(`[${g}][${v}] rejected, result=${getPrintableObject(S)||"void"}`),delete this._deferredOperationsWithCauseId[g][v],C}return Promise.reject(`[${g}][${v}] rejectOperationWithCauseId failed, operation not found`)}maybeResolveOperationWithCauseId(g,f,S){this.hasPendingOperationWithCauseId(g,f)?this.resolveOperationWithCauseId(g,f,S).catch((f=>{this._logger.info(`${g}maybeResolveOperationWithCauseId failed, reason=${getPrintableObject(f)}`)})):this._logger.info(`${g}maybeResolveOperationWithCauseId ignored, operation does not exist`)}maybeRejectOperationWithCauseId(g,f,S){this.hasPendingOperationWithCauseId(g,f)?this.rejectOperationWithCauseId(g,f,S).catch(noop):this._logger.info(`${g}maybeRejectOperationWithCauseId ignored, operation does not exist`)}getPendingOperation(g,f,S=generateCauseId()){return!f&&this._deferredOperations[g]?this._deferredOperations[g].deferred.promise:f&&this._deferredOperationsWithOperationId[g]&&this._deferredOperationsWithOperationId[g][f]?this._deferredOperationsWithOperationId[g][f].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(S,g,f)}: Deferred operation with given name and operation does not exist`)}waitForOperation(g,f,S=generateCauseId()){return f&&this.hasPendingOperationWithOperationId(g,f)?this._deferredOperationsWithOperationId[g][f].deferred.promise:this.hasPendingOperation(g)?this._deferredOperations[g].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(S,g,f)}failed=wait failed, operation not found`)}resolveOperation(g,f,S,v=generateCauseId(),C=!1){if(!g)return Promise.reject("Unable to resolve deferred operation with empty name");if(S&&this.hasPendingOperationWithOperationId(g,S)){const v=this._deferredOperationsWithOperationId[g][S],_=v.deferred.promise;return v.deferred.resolve(f),this._logger.info(`${this.getOperationInfoForLogging(v.causeId,g,S)}resolved, result=${getPrintableObject(f)||"void"}`),C||delete this._deferredOperationsWithOperationId[g][S],_}if(this.hasPendingOperation(g)){const v=this._deferredOperations[g],_=this._deferredOperations[g].deferred.promise;return this._deferredOperations[g].deferred.resolve(f),this._logger.info(`${this.getOperationInfoForLogging(v.causeId,g,S)}resolved, result=${getPrintableObject(f)||"void"}`),C||delete this._deferredOperations[g],_}return Promise.reject(`${this.getOperationInfoForLogging(v,g,S)}failed=resolve failed, operation not found`)}rejectOperation(g,f,S,v=generateCauseId()){if(!g)return Promise.reject("Unable to reject deferred operation with empty name");if(S&&this.hasPendingOperationWithOperationId(g,S)){const v=this._deferredOperationsWithOperationId[g][S],C=v.deferred.promise;return C.catch(noop),v.deferred.reject(f),this._logger.info(`${this.getOperationInfoForLogging(v.causeId,g,S)}rejected, reason=${getPrintableObject(f)||"void"}`),delete this._deferredOperationsWithOperationId[g][S],C}if(this.hasPendingOperation(g)){const v=this._deferredOperations[g],C=v.deferred.promise;return C.catch(noop),v.deferred.reject(f),this._logger.info(`${this.getOperationInfoForLogging(v.causeId,g,S)}rejected, reason=${getPrintableObject(f)||"void"}`),delete this._deferredOperations[g],C}return Promise.reject(`${this.getOperationInfoForLogging(v,g,S)}failed=reject failed, operation not found`)}maybeResolveOperation(g,f,S,v=generateCauseId()){const C=this.getOperationInfoForLogging(v,g,S);S&&this.hasPendingOperationWithOperationId(g,S)||this.hasPendingOperation(g)?this.resolveOperation(g,f,S,v).catch((g=>{this._logger.info(`${C}maybeResolveOperation failed, reason=${getPrintableObject(g)}`)})):this._logger.info(`${C}maybeResolveOperation ignored, operation does not exist`)}maybeResolveOperations(g,f,S,v=generateCauseId()){for(const C of g)this.maybeResolveOperation(C,f,S,v)}maybeRejectOperation(g,f,S,v=generateCauseId()){const C=this.getOperationInfoForLogging(v,g,S);S&&this.hasPendingOperationWithOperationId(g,S)||this.hasPendingOperation(g)?this.rejectOperation(g,f,S,v).catch(noop):this._logger.info(`${C}maybeRejectOperation ignored, operation does not exist`)}maybeRejectOperations(g,f,S,v=generateCauseId()){for(const C of g)this.maybeRejectOperation(C,f,S,v)}rejectPendingOperations(g,f=generateCauseId()){this._disposed=!0,this._logger.info(`[${f}]rejectPendingOperations=${JSON.stringify(g)}`),Object.keys(this._deferredOperations).forEach((S=>{this.maybeRejectOperation(S,g,void 0,f),this._deferredOperationsWithOperationId[f]&&delete this._deferredOperationsWithOperationId[f][""]})),Object.keys(this._deferredOperationsWithOperationId).forEach((S=>{Object.keys(this._deferredOperationsWithOperationId[S]).forEach((v=>{this.maybeRejectOperation(S,g,v,f),this._deferredOperationsWithOperationId[f]&&delete this._deferredOperationsWithOperationId[f][v]}))})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._endOperationDeferred.reject(g)}maybeRejectPendingOperationsWithPredicate(g,f=generateCauseId(),S){this._logger.info(`[${f}]rejectPendingOperationsWithPredicate`),Object.keys(this._deferredOperationsWithCauseId).forEach((f=>{Object.keys(this._deferredOperationsWithCauseId[f]).forEach((v=>{const C=this._deferredOperationsWithCauseId[f][v];C&&S(C.operationName,C.options)&&(this.maybeRejectOperation(C.operationName,g,v),this.maybeRejectOperationWithCauseId(f,v,g))}))}))}getOperationInfoForLogging(g,f,S=""){const v=S?`[${scrubMriOrOmit(S)}]`:"";return`[${g.substring(0,8)}][${f}]${v}`}},Di=M,Ni=class{constructor(g){this._logger=g,this._promise=Promise.resolve(void 0),this._actionQueue=[]}chainPromise(g,f,S=generateCauseId(),v=!1){const C=Date.now(),_=(("function"==typeof f?f():f)||"").toString();this._actionQueue.push(_),this._logger.info(`[${S}][${_}]enqueueing, queue=[${this._actionQueue}], reset=${v}`);const removeFromQueue=()=>{this._actionQueue=this._actionQueue.filter((g=>g!==_))};return v&&this.reset(S),this._promise=this._promise.catch(Di.noop).then((()=>{const f=Date.now()-C;return this._logger.info(`[${S}][${_}]begin, delayMs=${f}`),g()})),this._promise.then((()=>{removeFromQueue();const g=Date.now()-C;this._logger.info(`[${S}][${_}]success, durationMs=${g}`)}),(g=>{removeFromQueue();const f=Date.now()-C;this._logger.warn(`[${S}][${_}]failed=${safeJsonStringify(g)}, durationMs=${f}`)})),this._promise}reset(g){this._logger.info(`[${g}] resetting`),this._promise=Promise.resolve(void 0)}};function isSessionTerminatedReason(g){return!!g?.terminatedReasonCode}function convertFromTerminatedReasonFormat(g){return isSessionTerminatedReason(g)?{code:g.terminatedReasonCode,subCode:g.terminatedReasonSubCode,phrase:g.errorMessage}:g}function isTransactionEnd(g){return!!g?.code}function getRejectTransactionEnd(g,f){let S;return S=isTransactionEnd(g)?g:{code:499,subCode:void 0!==f?f:0,phrase:"string"==typeof g?g:getPrintableObject(g)},S}function getSuccessTransactionEnd(){return{code:0}}var ki=class{constructor(){this.msElapsed=0,this.isPaused=!1,this._startTime=(new Date).getTime(),this.pause=()=>{this.isPaused||(this.msElapsed+=(new Date).getTime()-this._startTime,this.isPaused=!0)},this.resume=()=>{this.isPaused&&(this.isPaused=!1,this._startTime=(new Date).getTime())},this.duration=()=>this.isPaused?this.msElapsed:this.msElapsed+(new Date).getTime()-this._startTime,this.durationInMinutes=()=>{const g=this.duration()/6e4;return Math.ceil(g)},this.durationInSeconds=()=>{const g=this.duration()/1e3;return Math.ceil(g)}}get startTime(){return this._startTime}};function build2(){return new ki}var Li=class extends Oi{constructor(g,f,S,v,C){super(g),this.callTelemetry=f,this._ecsConfig=S,this._publishCallback=v,this._preconditionFunction=C,this._record={},this.logSuccess=(g,f,S)=>{this._logger.info(`${g} execution succeeded, result=${f?getPrintableObject(f):"void"}, time=${S.duration()}`)},this.logFailure=(g,f,S)=>{this._logger.info(`${g} execution failed, reason=${this.stringifyForLogging(f)}, time=${S.duration()}`)},this.logTimeout=(g,f,S)=>{this._logger.info(`${g} execution timed out, reason=${this.stringifyForLogging(f)}, time=${S.duration()}`)},this.stringifyForLogging=g=>{let f;if(g instanceof Error)f=g.toString()||"Unknown Error";else try{f=JSON.stringify(g)}catch(g){f="Unable to stringify data"}return f},this.convertToTransactionEndIfErrorOrString=(g,f,S)=>{if(this._logger.info(`ecsEnableErrorConversion in operationHandler is: ${this._ecsConfig&&this._ecsConfig.enableErrorConversion}`),f&&this._ecsConfig&&this._ecsConfig.enableErrorConversion&&("string"==typeof g||g instanceof Error)){const f=getRejectTransactionEnd(g);return this._logger.info(`${S} Error converted from ${g} to ${getPrintableObject(f)}`),f}return g},this._logger=g.createChild("[Operation]"),this._chainedPromise=new Ni(this._logger.createChild("[Chained]"))}resetOperationChain(g){this._chainedPromise.reset(g)}executeSync(g,f,S,v=generateCauseId(),C,_){const T=this.getOperationInfoForLogging(v,f,S),I=build2();this._logger.info(`${T}API calledSync`);const b=this.callTelemetry.recordOperation(f,v,S,_);let A;try{this._setRecord(f),A=g(),b.recordSuccess(A,v),this.logSuccess(T,A,I)}catch(g){const f=this.convertToTransactionEndIfErrorOrString(g,C,T);b.recordFailure(f,v),this.logFailure(T,f,I)}return A}async executeChained(g,f,S,v=generateCauseId(),C,_,T){return this.checkPendingOperationAndExecute(g,!0,f,S,v,C,_,T)}async execute(g,f,S,v=generateCauseId(),C,_,T){return this.checkPendingOperationAndExecute(g,!1,f,S,v,C,_,T)}logOperation(g,f,...S){const v=S.length&&S.map((g=>this.stringifyForLogging(scrubMriOrOmit(g))));this._logger.info(`[${g.substring(0,8)}][${f}]API called, ${v?`with args=${v}`:""}`)}rejectPendingOperations(g,f=generateCauseId(),S){if(S){for(const g of Object.keys(this._deferredOperations))this.callTelemetry.maybeRecordOperationFailure(g,S,void 0,f);for(const g of Object.keys(this._deferredOperationsWithOperationId))for(const v of Object.keys(this._deferredOperationsWithOperationId[g]))this.callTelemetry.maybeRecordOperationFailure(g,S,v,f)}super.rejectPendingOperations(g,f)}maybeRejectOperations(g,f,S,v=generateCauseId(),C){if(C)for(const f of g)this.callTelemetry.maybeRecordOperationFailure(f,C,void 0,v);super.maybeRejectOperations(g,f,S,v)}checkPendingOperationAndExecute(g,f,S,v,C=generateCauseId(),_,T,I){const b=this.getOperationInfoForLogging(C,S,v);let A=null,P=null;return this.hasPendingOperationWithOperationId(S,v)||this.hasPendingOperation(S)?(this._logger.info(`${b}already pending, returning existing operation`),A=this.waitForOperation(S,v,C)):P=this.createPendingOperation(S,v,C,I),f?(this._logger.info(`${b}chained`),this._chainedPromise.chainPromise((()=>A||this.executeInternal(P,C,g,S,v,_,T,I)),S,C)):A||this.executeInternal(P,C,g,S,v,_,T,I)}_setRecord(g){this._record.hasOwnProperty(g)||(this._record[g]=0),this._record[g]+=1}getRecord(g){return this._record[g]}_recordTelemetryTimeoutAndPublish(g,f,S,v,C,_,T){const I=g||60;return window.setTimeout((()=>{if(!this._publishCallback)return void this._logger.warn(`${C} is marked to publish telemetry but no publish callback is defined.`);if(!this.hasPendingOperationWithOperationId(v,T)&&!this.hasPendingOperation(v))return;const g=new Error(`${C} execution did not complete before telemetry timeout of ${I}s.`);this.logTimeout(C,g,_),this.callTelemetry.maybeRecordOperationTimeout(v,g,T,S),this._publishCallback(f),this.callTelemetry.removeRecordedEvent(f)}),1e3*I)}_instantTelemetryPublish(g,f){this._publishCallback?(this._publishCallback(f),this.callTelemetry.removeRecordedEvent(f)):this._logger.warn(`${g} is marked to publish telemetry but no publish callback is defined.`)}parseInstantTelemetryParameters(g){let f,S=!1;return g&&(S=g.enableInstantTelemetry,f=g.telemetryTimeout),[S,f]}async executeInternal(g,f,S,v,C,_,T,I){const b=this.getOperationInfoForLogging(f,v,C);this._logger.info(`${b} executing operation...`);const A=build2(),P=this.callTelemetry.recordOperation(v,f,C,T),[R,M]=this.parseInstantTelemetryParameters(I);try{let g;this._setRecord(v),R&&(g=this._recordTelemetryTimeoutAndPublish(M,P,f,v,b,A,C)),I?.preconditionTags?.length&&this._preconditionFunction&&this._preconditionFunction(v,I.preconditionTags);const _=await S();g&&clearTimeout(g),this.callTelemetry.maybeRecordOperationSuccess(v,_,C),this.logSuccess(b,_,A),this.maybeResolveOperation(v,_,C,f)}catch(g){const S=this.convertToTransactionEndIfErrorOrString(g,_,b);this.callTelemetry.maybeRecordOperationFailure(v,convertFromTerminatedReasonFormat(S),C),this.logFailure(b,S,A),this.maybeRejectOperation(v,S,C,f)}return R&&this._instantTelemetryPublish(b,P),g}getEcsConfig(){return this._ecsConfig}},Fi={Cancel:487,Reject:603,NoNgcEndpoint:480,Forbidden:403,PreconditionFailed:412,Success:0,CallRedirected:302,BadRequest:400,NotFound:404,NotAcceptable:406,Timeout:408,Conflict:409,MediaError:410,ConfParticipantCountLimitReached:413,CallAccepted:450,CallForwarded:451,CallForwardedToVoicemail:452,P2pRejectCall:453,P2pFallbackForScreensharing:460,P2pFallbackDueToGroupCall:461,CallLegEndedOnService:470,CallDoesNotExist:481,NotAcceptableHere:488,NetworkError:490,GlareError:491,SkypeTokenError:495,LocalHttpStackError:496,UnknownError:497,LocalError:498,InternalServerError:500,CallModalityFailure:580,ServiceUnavailable:503},xi={Success:0,CallRedirectedSuccess:3020,InsufficientCapabilities:5204,PolicyRestriction:5448,UserBlocked:10005,MaxLobbyParticipantLimitReached:5807,MaxParticipantLimitReached:5808,MaxParticipantLimitReached2:5817,SharingStolenError:10029,DowngradeToStreamingClient:3099,MediaDropDuringConnect:3100,MediaDropAfterConnect:3101,MediaAnswerProcessingError:3102,MediaFinalAnswerProcessingError:3103,MediaOfferTimeout:3104,MediaFinalAnswerTimeout:3105,MediaOfferNull:3106,MediaAudioDeviceError:3107,MediaRenegotiationError:3108,MediaPermissionError:3109,MediaUnknownError:3110,MediaOfferProcessingError:3111,MediaWhiteListingIssue:3112,MediaMuteMicrophoneError:3113,MediaMuteSpeakerError:3114,MediaUnmuteMicrophoneError:3115,MediaUnmuteSpeakerError:3115,AttachActionFailed:4103,AttachFailed:4105,PreheatedCallTimedout:4113,RemovedFromConversation:5e3,DeniedInLobby:5854,RemovedFromCall:5300,TimedOutInLobby:5855,AnonymousJoinDisabledByPolicy:5723,B2bJoinDisabledByPolicy:5724,NoLobbyForBroadcastJoin:5354,NotAllowedDueToInformationBarrier:5810,TeamParkPolicyDisabled:10193,BroadcastLimitReached:800100,Suspended:58e4},Ui={[Fi.Success]:1,[Fi.Cancel]:12,[Fi.Reject]:10,[Fi.NoNgcEndpoint]:2,[Fi.Timeout]:6,[Fi.CallAccepted]:30,[Fi.CallRedirected]:75,[Fi.NotFound]:24,[Fi.CallDoesNotExist]:46,[Fi.NotAcceptable]:5,[Fi.BadRequest]:5,[Fi.MediaError]:4,[Fi.ConfParticipantCountLimitReached]:59,[Fi.CallModalityFailure]:4,[Fi.NetworkError]:3,[Fi.LocalHttpStackError]:31,[Fi.LocalError]:25,[Fi.CallForwarded]:27,[Fi.CallForwardedToVoicemail]:28,[Fi.SkypeTokenError]:29,[Fi.InternalServerError]:7,[Fi.Conflict]:7,[Fi.GlareError]:7,[Fi.CallLegEndedOnService]:7,[Fi.NotAcceptableHere]:26,[Fi.UnknownError]:32,[Fi.Forbidden]:8,[Fi.PreconditionFailed]:65},Vi={9401:33,9422:33,6102:1,6423:14,9402:14,9432:14,6519:3,9403:15,9410:36,9411:37,1e3:2,9407:17,13430:18,6009:19,10484:19,10604:19,10404:19,10420:19,10403:20,17401:20,10408:9,10486:11,10600:11,10686:11,10487:21,10500:3,10501:3,10502:3,10503:3,10504:3,10480:22,10482:22,10603:10,13406:23,13416:23},Bi={500:39,403:41,404:42,480:40},Hi={INCOMING_SKYPE_NGC_CALL:107,INCOMING_SKYPE_NGC_GVC_CALL:109,INCOMING_PSTN_NGC_CALL:111,INCOMING_SCREENSHARE_WITH_CHAT:119,INCOMING_CALLQUEUE_SUPERVISOR_CONTENT:125,INCOMING_TFL_TFW_CALL:126},$i={SHARED_LINE_CALL_RECORD:121,SHARED_LINE_V2_CALL_RECORD:123,MEETING_STARTED_NOTIFICATION:128},ji={LOG_UPLOAD_EVENT:120},Gi={Unknown:"CallEndReasonUnknown",MediaError:"CallEndReasonMediaError",MediaOfferTimeout:"CallEndReasonMediaOfferTimeout",MediaFinalAnswerTimeout:"CallEndReasonMediaFinalAnswerTimeout",MediaAnswerError:"CallEndReasonMediaAnswerError",MediaFinalAnswerError:"CallEndReasonFinalAnswerError",MediaPermissionError:"CallEndReasonMediaPermissionError",MediaRenegotiationError:"CallEndReasonRenegotiationError",MediaDropDuringConnect:"CallEndReasonMediaDropDuringConnectError",MediaDropAfterConnect:"CallEndReasonMediaDropAfterConnectError",MediaOfferProcessingError:"CallEndReasonMediaOfferProcessingError",DowngradeToStreamingClient:"DowngradeToStreamingClient",IncompatibleOffer:"CallEndReasonIncompatibleOffer",MediaWhiteListingIssue:"MediaWhitelistingIssue",AudioDeviceError:"CallEndReasonAudioDeviceError",AttachFailed:"CallEndReasonAttachFailed",BadNotificationPayload:"CallEndReasonBadNotificationPayload",RetargetNotSupported:"RetargetNotSupported",CallEndReasonLocalUserInitiated:"CallEndReasonLocalUserInitiated",EndedByRemoteEndpoint:"EndedByRemoteEndpoint",CallEndReasonRedirected:"CallEndReasonRedirected",CallEndReasonVDIdisconnect:"CallEndReasonVDIdisconnect",CallEndReasonSuspended:"CallEndReasonSuspended"},qi=(g=>(g.GetSignalingMediaTypes="GetSignalingMediaTypes",g.CallStart="CallStart",g.WaitForAnswer="WaitForAnswer",g.WaitForConnect="WaitForConnect",g.Accept="Accept",g))(qi||{}),Wi=(g=>(g.InitializeMediaSession="InitializeMediaSession",g.UpdateMediaModalities="UpdateMediaModalities",g.CreateOffer="CreateOffer",g.CreateAnswer="CreateAnswer",g.ProcessAnswer="ProcessAnswer",g.GetSignalingMediaTypes="GetSignalingMediaTypes",g.MuteUnmute="MuteUnmute",g.MuteUnmuteSpeakers="MuteUnmuteSpeakers",g.StartVideoSafe="StartVideoSafe",g.CompleteNegotiation="CompleteNegotiation",g.MuteInput="MuteInput",g.MuteOutput="MuteOutput",g.UnmuteInput="UnmuteInput",g.UnmuteOutput="UnmuteOutput",g.evaluateEndpointStatesForAccept="evaluateEndpointStatesForAccept",g.handleEndpointStatesForAccept="handleEndpointStatesForAccept",g))(Wi||{}),zi=(g=>(g.InitializeMediaSession="InitializeMediaSession",g.ProcessOffer="ProcessOffer",g.ProcessOfferedModalities="ProcessOfferedModalities",g.TrySendingProvisionalAnswer="TrySendingProvisionalAnswer",g))(zi||{}),Ki=M,Ji=__toESM(M),Yi=__toESM(M),Qi=__toESM(ye()),Xi={Success:"Success",ExpectedError:"ExpectedError",UnexpectedClientError:"UnexpectedClientError",UnexpectedServerError:"UnexpectedServerError"},Zi={INCOMING_MESSAGE_ORIGIN:{TROUTER:"Trouter",BROKER:"Broker"},INVITATION_TYPE:{NUDGE:"nudge"},KNOWN_PAYLOAD_ENCODINGS:{GZIP:!0},WEBRTC_NOTIFICATION_TYPE:{CONTROL_VIDEO_STREAMING:"ControlVideoStreaming",DOMINANT_SPEAKER_INFO:"DominantSpeakerInfo",CSRC_INFO:"CsrcInfo"},PARTICIPANT_AUDIO_STATE:{CONNECTING:"Connecting",RINGING:"Ringing",CONNECTED:"Connected",OTHER:"Other"},HEADERS:{MESSAGE_ID:"X-Microsoft-Skype-Message-ID",ORIGINAL_MESSAGE_ID:"X-Microsoft-Skype-Original-Message-ID",CONTENT_ENCODING:"X-Microsoft-Skype-Content-Encoding",CORRELATION_ID:"X-Microsoft-Skype-Chain-ID",CONTENT_SHARING_CORRELATION_ID:"X-Microsoft-Skype-ContentSharing-Chain-ID",CLIENT_USER_AGENT:"X-Microsoft-Skype-Client",SKYPE_TOKEN:"X-Skypetoken",AUTHORIZATION:"Authorization",BEARER_KEYWORD:"Bearer",AAD_KEYWORD:"Aad",CAE_KEYWORD:"Cae",SKYPE_KEYWORD:"Skype",CACHE_SKYPE_TOKEN:"X-CacheSkypeToken",AUTHENTICATE:"www-authenticate",TOKEN_MIGRATION:"X-MS-Migration",BROKER_USE_BATCHING_HEADER_NAME:"X-UseBatching",PARTICIPANT_ID:"X-Microsoft-Skype-Participant-ID",CONTENT_TYPE:"Content-Type",RING:"MS-Teams-Ring",REGION:"MS-Teams-Region",PARTITION:"MS-Teams-Partition"},KNOWN_BOTS:{VOICEMAIL_BOT_ID:"28:14524421-25b4-403a-a0f7-e62d4379cabc"},HTTP_STACK_ERROR:{NONE:0,CANNOT_CONNECT:7,REQUEST_TIMEOUT:10,ATTEMPT_TIMEOUT:30,REQUEST_ABORTED:16,ATTEMPT_ABORTED:31,ABORTED_OTHER_ATTEMPT_SUCCESSFUL:32},HTTP_STATUS_CODES:{UNKNOWN:0,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,FORBIDDEN:403,PRECONDITION_FAILED:412,UNPROCESSABLE_ENTITY:422,NETWORK_ERROR:490,SKYPE_TOKEN_ERROR:495,OFFLINE:496,TIMEOUT:498,ABORTED:498,OTHER:499,INTERNAL_SERVER_ERROR:500,CONFLICT:409,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504},CALL_END_SKYPE_TOKEN_ERROR:{code:495,subCode:4507,phrase:"CallEndReasonSkypeTokenFetchError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_TOKEN_TIMEOUT_ERROR:{code:499,subCode:3119,phrase:"CallEndReasonTokenFetchTimeout",resultCategories:[Xi.UnexpectedClientError]},CALL_END_UNSUPPORTED_TOKEN_ERROR:{code:499,subCode:3126,phrase:"CallEndReasonUnsupportedTokenError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_TOKEN_ERROR:{code:499,subCode:3127,phrase:"CallEndReasonTokenFetchError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED:{code:499,subCode:3128,phrase:"CallEndReasonTokenTimeoutInterActvityRequired",resultCategories:[Xi.UnexpectedClientError]},CALL_END_LOCAL_HTTP_STACK_ERROR:{code:496,subCode:4520,phrase:"LocalHTTPStackError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_UNKNOWN_ERROR:{code:497,subCode:3121,phrase:"CallEndReasonUnknownError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_NETWORK_ERROR:{code:490,subCode:4502,phrase:"CallEndReasonNetworkError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_DNS_HOST_NAME_RESOLVE_ERROR:{code:490,subCode:4522,phrase:"CallEndReasonDnsHostNameResolveError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_LOCAL_DECLINE:{code:486,subCode:4508,phrase:"LocalDecline",resultCategories:[Xi.Success]},RESOURCE_NOT_FOUND_ERROR:{code:404,subCode:404,phrase:"ResourceNotFound",resultCategories:[Xi.ExpectedError]},CALL_STATUS:{IDLE:"Idle",RINGING:"Ringing",CONNECTING:"Connecting",CONNECTED:"Connected",CONNECTED_FOR_ROSTER_ONLY:"ConnectedForRosterOnly",LOCAL_TERMINATED:"LocalTerminated",REMOTE_TERMINATED:"RemoteTerminated"},MEDIA_TYPES:{AUDIO:"Audio",VIDEO:"Video",SCREEN_SHARER:"ScreenSharer",SCREEN_VIEWER:"ScreenViewer"},MUTE_SCOPE:{MYSELF:"Myself",EVERYONE_ELSE:"EveryoneElse",SPECIFIED_PARTICIPANTS:"SpecifiedParticipants"},URL_BASE:{CALLAGENT:"callAgent"},LINKS:{HANGUP:"hangup",MEDIA_REJECTION:"mediaRejection",MEDIA_ANSWER:"mediaAnswer",MEDIA_RENEGOTIATION:"mediaRenegotiation",ACCEPT:"accept",ATTACH:"attach",REJECT:"reject",REDIRECT:"redirect",REPLACE:"replace",TRANSFER:"transfer",NEW_OFFER:"newOffer",TRANSFER_ACCEPTANCE:"transferAcceptance",TRANSFER_COMPLETION:"transferCompletion",CONVERSATION_CONTROLLER:"conversationController",ADD_PARTICIPANT:"addParticipant",ADD_PARTICIPANTS_AND_MODALITY:"addParticipantsAndModality",LEAVE:"leave",NOTIFICATION_LINKS:"notificationLinks",REMOVE_PARTICIPANT:"removeParticipant",KEEPALIVE:"keepAlive",ADD_MODALITY:"AddModality",REMOVE_MODALITY:"RemoveModality",CONTENT_SHARING_CONTROLLER:"contentSharingController",CONTENT_SHARING_TAKE_CONTROL:"contentSharingTakeControl",CONTENT_SHARING_UPDATE_SESSION_STATE:"contentSharingUpdateSessionState",CONTENT_SHARING_UPDATE_PARTICIPANT_STATE:"contentSharingUpdateParticipantState",CONTENT_SHARING_NOTIFICATION_LINKS:"contentSharingNotificationLinks",CONTENT_SHARING_LEAVE:"contentSharingLeave",MUTE:"mute",UNMUTE:"unmute",ADMIT:"admit",ADMIT_ALL:"admitAll",CONTROL_VIDEO_STREAMING:"controlVideoStreaming",APPLY_CHANNEL_PARAMETERS:"applyChannelParameters",UPDATE_ENDPOINT_STATE:"updateEndpointState",UPDATE_ENDPOINT_METADATA:"updateEndpointMetadata",LMC_NOTIFICATION_LINKS:"lmcNotificationLinks",UPDATE_PARTICIPANT_ROLE:"updateParticipantRole",PUBLISH_STATE:"publishState",REMOVE_STATE:"removeState",UPDATE_MEETING_SETTINGS:"updateMeetingSettings",SEARCH_PARTICIPANTS:"searchParticipants",GET_ALL_PARTICIPANTS:"getAllParticipants",PARK:"park",UNPARK:"unpark",UPDATE_MEETING_LIVE_STATE:"updateMeetingLiveState",UPDATE_MEETING_GROUPS:"updateMeetingGroups",SET_MEETING_LAYOUT:"setMeetingLayout",UPDATE_PARTICIPANT_INTERPRETATION_STATE:"updateParticipantInterpretationState",JOIN_MEETING_GROUP:"joinMeetingGroup",LEAVE_MEETING_GROUP:"leaveMeetingGroup",SEND_MESSAGE:"sendMessage",UPDATE_PARTICIPANTS_PROPERTIES:"updateParticipantsProperties",UPDATE_MEDIA_DESCRIPTIONS:"updateMediaDescriptions",UPDATE_MEETING_STATES:"updateMeetingStates",UPDATE_MONITOR_SESSION:"monitor"},CONTENT_TYPE:{JSON:"application/json",SDP:"application/sdp"},TROUTER_EVENT_TYPE:{SKYPE_SKYPE_CALL:107,LYNC_SKYPE_CALL:105},MISC:{CONVERSATION:"conversation",LOBBY_CALL_CONTROLLER:"lobby",LOBBY_PARTICIPANT_STATE:"lobby"},SIGNALING_FSM_STATE:{IDLE:"Idle",INCOMING:"Incoming",WAITING_CALL_ACCEPTANCE_ACK:"WaitingCallAcceptanceAck",OUTGOING:"Outgoing",CONNECTED:"Connected",OUTGOING_FOR_ROSTER_ONLY:"OutgoingForRosterOnly",CONNECTED_FOR_ROSTER_ONLY:"ConnectedForRosterOnly"},MEDIA_RENEGOTIATION_FSM_STATE:{IDLE:"Idle",CALL_CONNECTED:"Connected",INCOMING_RENEGOTIATION:"IncomingRenegotiation",OUTGOING_RENEGOTIATION:"OutgoingRenegotiation",RENEGOTIATION_GLARE:"RenegotiationGlare"},CONTENT_SHARING_FSM_STATE:{IDLE:"Idle",CONTENT_SHARING_START_INITIATED:"ContentSharingStartInitiated",CONTENT_SHARING_JOIN_INITIATED:"ContentSharingJoinInitiated",CONTENT_SHARING_LEAVE_INITIATED:"ContentSharingLeaveInitiated",CONTENT_SHARING_DELETE_INITIATED:"ContentSharingDeleteInitiated",CONTENT_SHARING_CONNECTED:"ContentSharingConnected"},TIMEOUT_OPERATIONS:{ADD_PARTICIPANT:"AddParticipant",NUDGE_PARTICIPANT:"NudgeParticipant",REMOVE_PARTICIPANT:"RemoveParticipant",ADMIT_PARTICIPANT:"AdmitParticipant",ADMIT:"Admit",CALL_REDIRECT:"CallRedirect",CALL_ME_BACK:"CallMeBack",INCOMING_CALL_ESTABLISHMENT:"IncomingCallEstablishment",OUTGOING_CALL_ESTABLISHMENT:"OutgoingCallEstablishment",MEDIA_ANSWER:"MediaAnswer",MEDIA_ANSWER_ACKNOWLEDGEMENT:"MediaAnswerAcknowledgement",ADD_MODALITY:"AddModality",UNMUTE:"Unmute",UPDATE_MEETING_ROLE:"UpdateMeetingRole",MAX_PREAHEATED_TIMEOUT:"MaxPreheateadTimeout",PARK_COMPLETION:"ParkCompletion",UNPARK_COMPLETION:"UnparkCompletion",UPDATE_MEETING_LIVE_STATE_COMPLETION:"UpdateMeetingLiveStateCompletion",UPDATE_MEETING_GROUPS_COMPLETION:"UpgradeMeetingGroupsCompletion",UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION:"UpdateParticipantInterpretationStateCompletion",UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION:"UpdateParticipantsPropertiesCompletion",JOIN_MEETING_GROUP_COMPLETION:"JoinMeetingGroupCompletion",LEAVE_MEETING_GROUP_COMPLETION:"LeaveMeetingGroupCompletion",SET_MEETING_LAYOUT_COMPLETION:"SetMeetingLayoutCompletion",SEND_MESSAGE_COMPLETION:"SendMessageCompletion",DISABLE_PREHEAT_ASYNC_TIMEOUT:"DisablePreheatAsyncTimeout",UPDATE_MEETING_STATES_COMPLETION:"UpdateMeetingStatesCompletion",UPDATE_MONITOR_SESSION_COMPLETION:"UpdateMonitorSessionCompletion"},TIMEOUT_VALUES_IN_SECONDS:{ADD_PARTICIPANT_TIMEOUT:130,REMOVE_PARTICIPANT_TIMEOUT:60,INCOMING_CALL_ESTABLISHMENT_TIMEOUT:75,OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:90,LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:185,MEDIA_ANSWER_TIMEOUT:35,MEDIA_ANSWER_ACKNOWLEDGEMENT_TIMEOUT:15,ADD_MODALITY_TIMEOUT:65,UNMUTE_TIMEOUT:35,ADMIT_PARTICIPANT_TIMEOUT:210,ADMIT_TIMEOUT:60,UPDATE_MEETING_ROLE_TIMEOUT:15,NUDGE_PARTICIPANT_TIMEOUT:60,CALL_ME_BACK_TIMEOUT:120,MAX_PREAHEATED_TIMEOUT:90,PARK_COMPLETION_TIMEOUT:45,UNPARK_COMPLETION_TIMEOUT:45,UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT:45,UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT:45,SET_MEETING_LAYOUT_COMPLETION_TIMEOUT:45,UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION_TIMEOUT:45,UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION_TIMEOUT:45,JOIN_MEETING_GROUP_COMPLETION_TIMEOUT:45,LEAVE_MEETING_GROUP_COMPLETION_TIMEOUT:45,CONVERSATION_KEEP_ALIVE_TIMEOUT:2700,TOKEN_REQUIRED_TIMEOUT:20,SEND_MESSAGE_COMPLETION_TIMEOUT:15,DISABLE_PREHEAT_TIMEOUT:45,UPDATE_MEETING_STATES_COMPLETION_TIMEOUT:45,UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT:45},CALL_END_CODE:{REJECT:603,SUCCESS:0,CALL_REDIRECTED:302,CANCEL:487,TIMEOUT:408,SERVICE_UNAVAILABLE:500,BAD_REQUEST:406,NO_NGC_ENDPOINT:480,P2P_FALLBACK_FOR_SCREENSHARING:460,CONFLICT:409,MEDIA_ERROR:410,CONF_PARTICIPANT_COUNT_LIMIT_REACHED:413,CALL_DOES_NOT_EXIST:481,CALL_ACCEPTED:450,CALL_FORWARDED:451,CALL_FORWARDED_TO_VOICEMAIL:452,P2P_REJECT_CALL:453,P2P_FALLBACK_DUE_TO_GROUPCALL:461,CALL_LEG_ENDED_ON_SERVICE:470,NOT_ACCEPTABLE_HERE:488,NETWORK_ERROR:490,UNKNOWN_ERROR:497,LOCAL_ERROR:498,CALL_MODALITY_FAILURE:580,ATC_CONTROLLER_FAILURE:581,CVA_CONTROLLER_FAILURE:586,GLARE_ERROR:491,NOT_FOUND:404,SKYPE_TOKEN_ERROR:495,LOCAL_HTTP_STACK_ERROR:496,HTTP_OTHER_ERROR:499,DECODING_FAILED:407,NOT_AUTHORIZED:403,BAD_SERVICE_RESPONSE:400},CALL_END_SUB_CODE:{SUCCESS:0,CALL_REDIRECTED_SUCCESS:3020,DOWNGRADE_TO_STREAMING_CLIENT:3099,MEDIA_DROP_DURING_CONNECT:3100,MEDIA_DROP_AFTER_CONNECT:3101,MEDIA_ANSWER_PROCESSING_ERROR:3102,MEDIA_FINAL_ANSWER_PROCESSING_ERROR:3103,MEDIA_OFFER_TIMEOUT:3104,MEDIA_FINAL_ANSWER_TIMEOUT:3105,MEDIA_OFFER_NULL:3106,MEDIA_AUDIO_DEVICE_ERROR:3107,MEDIA_RENEGOTIATION_ERROR:3108,MEDIA_PERMISSION_ERROR:3109,MEDIA_UNKNOWN_ERROR:3110,MEDIA_OFFER_PROCESSING_ERROR:3111,MEDIA_WHITELISTING_ISSUE:3112,MEDIA_MUTE_MICROPHONE_ERROR:3114,MEDIA_MUTE_SPEAKER_ERROR:3115,MEDIA_UNMUTE_MICROPHONE_ERROR:3116,MEDIA_UNMUTE_SPEAKER_ERROR:3117,MEDIA_GLARE_ERROR:3118,CONVERSATION_TERMINATION_UNKNOWN_ERROR:3121,CONVERSATION_NOTIFICATION_TIMEOUT:3125,CALL_NOT_ATTEMPTED:4500,CONV_URL_NOT_SET:4501,FAILED_TO_REACH_SERVICE:4502,PLACE_CALL_FAILED:4503,ATTACH_CALL_FAILED:4504,BAD_NOTIFICATION_PAYLOAD:4505,CALL_ESTABLISHMENT_TIMEOUT:4506,SKYPE_TOKEN_ERROR:4507,CONVERSATION_RESOLUTION_CONFLICT:5704,CALL_PARTICIPANT_REMOVAL_TIMEOUT:4507,UNMUTE_REQUEST_TIMEOUT:4509,UNMUTE_REQUEST_REJECTED:4510,CONFLICT_IN_NG:4090,CONFLICT_WITH_P2P:4091,CONVERSATION_END_RECEIVED_FROM_SERVICE:4100,TRANSFER_COMPLETE_TIMEOUT:4101,ATTACH_TO_NON_EXISTENT_CALL:4102,ATTACH_ACTION_FAILED:4103,ATTACH_FAILED:4105,CONVERSATION_ESTABLISHMENT_FAILED:4106,BEFORE_CONNECT:4107,AFTER_CONNECT:4108,AFTER_ACCEPT:4109,TROUTER_CONNECTION_DROPPED:4111,DUE_TO_CALL_ASSIMILATION:4112,PREHEATED_CALL_TIMEDOUT:4113,UNPARK_COMPLETION_TIMEOUT:4114,PARK_COMPLETION_TIMEOUT:4115,UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT:4116,UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT:4117,SET_MEETING_LAYOUT_COMPLETION_TIMEOUT:4118,UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT:4119,JOIN_MEETING_GROUP_TIMEOUT:4120,LEAVE_MEETING_GROUP_TIMEOUT:4121,UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT:4122,UPDATE_MEETING_STATES_COMPLETION_TIMEOUT:4123,UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT:4124,MISSING_REQUEST_URI:4511,MISC_ERROR:4512,LOCAL_HTTP_STACK_ERROR:4520,BEACON:4521,DNS_HOST_NAME_RESOLVE_ERROR:4522,CONVERSATION_ENDED_NO_NEW_OWNER_FOUND:5014,UNABLE_TO_GENERATE_MEETUP_ID:5015,UPDATE_MEETING_ROLE_REJECTED:5651,UPDATE_MEETING_ROLE_TIMEOUT:5652,PUBLISH_STATE_LINK_MISSING:5653,PUBLISH_STATE_INVALID_CONTENT:5654,PUBLISH_STATE_INVALID_SERVICE_RESPONSE:5655,REMOVE_STATE_LINK_MISSING:5656,REMOVE_STATE_MISSING_ARGUMENTS:5657,UPDATE_MEETING_SETTINGS_LINK_MISSING:5658,UPDATE_MEETING_SETTINGS_MISSING_ARGUMENTS:5659,ADMIT_ALL_LINK_MISSING:5660,ADMIT_TIMEOUT:5661,CALL_ACCEPTANCE_INVALID_SERVICE_RESPONSE:5670,ROSTER_HANDLING_INVALID_SERVICE_RESPONSE:5671,SEARCH_PARTICIPANTS_LINK_MISSING:5672,SEARCH_PARTICIPANTS_INVALID_SERVICE_RESPONSE:5673,GET_ALL_PARTICIPANTS_LINK_MISSING:5674,GET_ALL_PARTICIPANTS_INVALID_SCOPE:5675,GET_ALL_PARTICIPANTS_INVALID_SERVICE_RESPONSE:5676,PARK_UNPARK_TYPE_MISSING:5680,PARK_UNPARK_V2_DISABLED:5682,UPDATE_PARTICIPANTS_PROPERTIES_LINK_MISSING:5683,DISABLE_PREHEAT_TIMEOUT:5684,CALL_ENDED_BY_PLATFORM_AGENT:7e3,CONVERSATION_TERMINATION_INTERACTION_REQUIRED:71014},CALL_END_PHRASE:{UNKNOWN:"CallEndReasonUnknown",MEDIA_ERROR:"CallEndReasonMediaError",MEDIA_OFFER_TIMEOUT:"CallEndReasonMediaOfferTimeout",MEDIA_FINAL_ANSWER_TIMEOUT:"CallEndReasonMediaFinalAnswerTimeout",MEDIA_ANSWER_ERROR:"CallEndReasonMediaAnswerError",MEDIA_FINAL_ANSWER_ERROR:"CallEndReasonFinalAnswerError",MEDIA_PERMISSION_ERROR:"CallEndReasonMediaPermissionError",MEDIA_RENEGOTIATION_ERROR:"CallEndReasonRenegotiationError",MEDIA_DROP_DURING_CONNECT:"CallEndReasonMediaDropDuringConnectError",MEDIA_DROP_AFTER_CONNECT:"CallEndReasonMediaDropAfterConnectError",MEDIA_OFFER_PROCESSING_ERROR:"CallEndReasonMediaOfferProcessingError",MEDIA_WHITELISTING_ISSUE:"MediaWhitelistingIssue",AUDIO_ERROR:"CallEndReasonAudioDeviceError",CONVERSATION_NOTIFICATION_TIMEOUT:"ConversationNotificationTimeout",BAD_NOTIFICATION_PAYLOAD:"BadCallNotificationPayload",NETWORK_ERROR:"CallEndReasonNetworkError",LOCAL_USER_INITIATED:"CallEndReasonLocalUserInitiated",REMOTE_USER_INITIATED:"CallEndReasonRemoteUserInitiated",ESTABLISHMENT_TIMEOUT:"CallEndReasonEstablishmentTimeout",PARTICIPANT_REMOVAL_TIMEOUT:"CallParticipantRemovalTimeout",LOCAL_ERROR:"CallEndReasonLocalError",CALL_UPDATE_ERROR:"CallEndReasonCallUpdateError",CALL_REDIRECT_IS_NOT_ALLOWED:"CallRedirectisNotAllowed",P2P_FORK_CONNECTED:"CallEndReasonP2pForkConnected",P2P_FORK_FORWARDED:"CallEndReasonP2pForkForwarded",P2P_FORK_FORWARDED_TO_VOICEMAIL:"CallEndReasonP2pForkForwardedToVoiceMail",P2P_FALLBACK_FOR_SCREENSHARING:"CallEndReasonP2pFallbackForScreensharing",P2P_FALLBACK_FOR_GROUPCALL:"CallEndReasonP2pFallbackForGroupCall",P2P_FALLBACK_FOR_CALL_ASSIMILATION:"CallEndReasonP2pFallbackForCallAssimilation",P2P_FALLBACK_FOR_TRANSLATION:"CallEndReasonP2pFallbackForCallTranslation",P2P_FORK_REJECTED:"CallEndReasonP2pForkRejected",TROUTER_CONNECTION_DROPPED:"CallEndReasonTrouterConnectionDropped",REMOVED_FROM_CALL:"CallEndReasonRemovedFromCall",TRANSFER_COMPLETION_TIMEOUT:"CallEndReasonTransferCompletionTimeout",CALL_DOES_NOT_EXIST:"CallEndReasonCallDoesNotExist",ATTACH_ACTION_FAILED:"CallEndReasonAttachActionFailed",ATTACH_FAILED:"CallEndReasonAttachFailed",CONVERSATION_ESTABLISHMENT_FAILED:"CallEndReasonConversationEstablishmentFailed",CONV_END_FROM_SERVICE:"CallEndReasonConversationEndReceivedFromService",CONV_END_FROM_SERVICE_WITH_ERROR:"CallEndReasonConversationEndReceivedFromServiceWithError",SERVICE_ERROR:"CallEndReasonServiceError",CONFLICT:"CallEndReasonConflict",CALL_ALREADY_IN_P2P:"CallEndReasonCallAlreadyExistsInP2p",CONV_END_NO_MODALITY:"ConversationEndNoModalityConnected",CONV_END_FOR_ALL_INITIATED:"ConversationEndForAllInitiated",RENEGOTIATION_IN_PROGRESS:"NegotiationIsInProgress",ADD_PARTICIPANT_URL_MISSING:"AddParticipantUrlMissing",ADMIT_PARTICIPANT_URL_MISSING:"AdmitParticipantUrlMissing",ADMIT_ALL_URL_MISSING:"AdmitAllUrlMissing",UPDATE_PARTICIPANT_INTERPRETATION_STATE_URL_MISSING:"UpdateParticipantInterpretationStateUrlMissing",UPDATE_PARTICIPANTS_PROPERTIES_URL_MISSING:"UpdateParticipantsPropertiesUrlMissing",ADMIT_TIMEOUT:"AdmitTimeout",UNABLE_TO_GENERATE_MEETUP_ID:"Unable to generate GroupChat meetup id.",ENDED_BY_PMA:"Call ended by media agent.",OWNERSHIP_RESOLUTION_CONFLICT:"Conversation cannot be created due to a failure to resolve ownership.",CONVERSATION_ENDED_NO_NEW_OWNER_FOUND:"This conversation has ended since we were unable to determine a potential host for the group call.",UNMUTE_REQUEST_TIMEOUT:"UnmuteRequestTimeout",UNMUTE_REQUEST_REJECTED:"UnmuteRequestRejected",UPDATE_MEETING_ROLE_TIMEOUT:"UpdateMeetingRoleTimeout",UPDATE_MEETING_ROLE_REJECTED:"Update meeting role operation failed due to insufficient privileges.",PARK_REQUEST_FAILED:"Park Request Failed",PARK_COMPLETION_TIMEOUT:"ParkCompletionTimeout",PARK_COMPLETION_FAILED:"ParkCompletionFailed",UNPARK_REQUEST_FAILED:"UnparkFailed",UNPARK_COMPLETION_TIMEOUT:"UnparkCompletionTimeout",UNPARK_COMPLETION_FAILED:"UnparkCompletionFailed",BAD_SERVICE_RESPONSE:"BadServiceResponse",UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT:"UpdateMeetingLiveStateCompletionTimeout",UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT:"UpdateMeetingGroupsCompletionTimeout",SET_MEETING_LAYOUT_COMPLETION_TIMEOUT:"SetMeetingLayoutCompletionTimeout",UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT:"UpdateParticipantInterpretationTimeout",JOIN_MEETING_GROUP_TIMEOUT:"JoinMeetingGroupTimeout",LEAVE_MEETING_GROUP_TIMEOUT:"LeaveMeetingGroupTimeout",DOWNGRADE_TO_STREAMING_CLIENT:"DowngradeToStreamingClient",MESSAGE_STATUS_WITH_FAILURE_COUNT:"NotZeroFailureCount",UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT:"UpdateParticipantsPropertiesTimeout",DISABLE_PREHEAT_TIMEOUT:"DisablePreheatTimeout",UPDATE_MEETING_STATES_COMPLETION_TIMEOUT:"UpdateMeetingStatesCompletionTimeout",UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT:"UpdateMonitorSessionCompletionTimeout"},TRANSACTION_END_CODE:{SUCCESS:0},URL_DEFAULTS:{UPLOAD_LOG_URL:"https://api.cc.skype.com/cc/v1/uploadlog/"},SUCCESS_TRANSACTION_END:{code:0,resultCategories:[Xi.Success]},VALIDATION:{VALIDATION_FAILED:6e3,NULL_OR_EMPTY:6001}},en={REQUEST_TIMEOUT:{status:Zi.HTTP_STATUS_CODES.TIMEOUT,statusText:"Request timed out",readyState:0,response:Zi.HTTP_STACK_ERROR.REQUEST_TIMEOUT},ATTEMPT_TIMEOUT:{status:Zi.HTTP_STATUS_CODES.TIMEOUT,statusText:"Attempt timed out",readyState:0,response:Zi.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT},REQUEST_ABORTED:{status:Zi.HTTP_STATUS_CODES.ABORTED,statusText:"Request Aborted",readyState:0,response:Zi.HTTP_STACK_ERROR.REQUEST_ABORTED},ATTEMPT_ABORTED:{status:Zi.HTTP_STATUS_CODES.ABORTED,statusText:"Attempt Aborted",readyState:0,response:Zi.HTTP_STACK_ERROR.ATTEMPT_ABORTED}},tn={MEDIA_ACKNOWLEDGEMENT:"/call/mediaAcknowledgement/",MEDIA_REJECTION:"/call/rejection/",ACKNOWLEDGEMENT:"/call/acknowledgement/",MEDIA_RENEGOTIATION:"/call/mediaRenegotiation/",REPLACE:"/call/replacement/",PROGRESS:"/call/progress/",MEDIA_ANSWER:"/call/mediaAnswer/",NEW_MEDIA_OFFER:"/call/newMediaOffer/",REDIRECTION:"/call/redirection/",BALANCE_UPDATE:"/call/balanceUpdate/",ACCEPT:"/call/acceptance/",CONTROL_VIDEO_STREAMING:"/call/controlVideoStreaming/",DOMINANT_SPEAKER_INFO:"/call/dominantSpeakerInfo/",CSRC_INFO:"/call/csrcInfo/",END:"/call/end/",RETARGET_COMPLETION:"/call/retargetCompletion/",TRANSFER:"/call/transfer/",TRANSFER_ACCEPTANCE:"/call/transferAcceptance/",TRANSFER_COMPLETION:"/call/transferCompletion/",PARK_COMPLETION:"/call/holdCompletion/",UNPARK_COMPLETION:"/call/resumeCompletion/",UPDATE_MEDIA_DESCRIPTIONS:"/call/updateMediaDescriptions",MONITOR_COMPLETION:"/call/monitorCompletion/"},nn={CONV_END:"/conversation/conversationEnd/",CONV_END_SUBSCRIBE:"/subscribe/conversation/conversationEnd/",CONV_END_JOIN:"/join/conversation/conversationEnd/",CONV_UPDATE:"/conversation/conversationUpdate/",CONV_LOCAL_PARTICIPANT_UPDATE:"/conversation/localParticipantUpdate/",CONV_ROSTER_UPDATE:"/conversation/rosterUpdate/",CONV_ADD_PARTICIPANT_SUCCESS:"/conversation/addParticipantSuccess/",CONV_ADD_PARTICIPANT_FAILURE:"/conversation/addParticipantFailure/",CONV_NUDGE_PARTICIPANT_SUCCESS:"/conversation/nudgeParticipantSuccess/",CONV_NUDGE_PARTICIPANT_FAILURE:"/conversation/nudgeParticipantFailure/",CONV_ADMIT_PARTICIPANT_SUCCESS:"/conversation/admitParticipantSuccess/",CONV_ADMIT_PARTICIPANT_FAILURE:"/conversation/admitParticipantFailure/",CONV_ADMIT_ALL_STATUS:"/conversation/admitAllStatus/",CONV_REMOVE_PARTICIPANT_SUCCESS:"/conversation/removeParticipantSuccess/",CONV_REMOVE_PARTICIPANT_FAILURE:"/conversation/removeParticipantFailure/",CONV_ADD_MODALITY_SUCCESS:"/conversation/addModalitySuccess/",CONV_ADD_MODALITY_FAILURE:"/conversation/addModalityFailure/",CONV_CONTENT_SHARING_UPDATE:"/conversation/contentSharingUpdate/",CONV_CONTENT_SHARING_END:"/conversation/contentSharingEnd/",CONV_BROADCAST_UPDATE:"/conversation/broadcastUpdate/",CONV_CONFIRM_UNMUTE:"/conversation/confirmUnmute/",CONV_UNMUTE_SUCCESS:"/conversation/unmuteSuccess/",CONV_UNMUTE_FAILURE:"/conversation/unmuteFailure/",UPDATE_MEETING_LIVE_STATE_STATUS:"/conversation/updateMeetingLiveStateStatus/",UPDATE_MEETING_GROUPS_STATUS:"/conversation/updateMeetingGroupsStatus/",SET_MEETING_LAYOUT_STATUS:"/conversation/setMeetingLayoutStatus/",UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS:"/conversation/updateParticipantInterpretationStateStatus/",UPDATE_PARTICIPANT_PROPERTIES_STATUS:"/conversation/updateParticipantPropertiesStatus/",JOIN_MEETING_GROUP_STATUS:"/conversation/joinMeetingGroupStatus/",LEAVE_MEETING_GROUP_STATUS:"/conversation/leaveMeetingGroupStatus/",RECEIVE_MESSAGE:"/conversation/receiveMessage/",SEND_MESSAGE_STATUS:"/conversation/sendMessageStatus/",DISABLE_PREHEAT_ASYNC_STATUS:"/conversation/disablePreheatAsyncStatus/",UPDATE_MEETING_STATES_STATUS:"/conversation/updateMeetingStatesStatus/",MUTE_UNMUTE_ASYNC:"/conversation/muteUnmuteAsync/"},rn={...tn,...nn},sn={CALL_NOTIFICATION:"callNotification",MEDIA_ANSWER:"mediaAnswer",MEDIA_ACKNOWLEDGEMENT:"mediaAcknowledgement",CALL_ACCEPTANCE:"callAcceptance",CALL_END:"callEnd",CALL_PROGRESS:"callProgress",CALL_ACCEPTANCE_ACKNOWLEDGEMENT:"callAcceptanceAcknowledgement",MEDIA_NEGOTIATION:"mediaNegotiation",MEDIA_NEGOTIATION_FAILURE:"mediaNegotiationFailure",BALANCE_UPDATE:"balanceUpdate",RETARGET_COMPLETED:"retargetCompleted",CALL_TRANSFER:"callTransfer",TRANSFER_COMPLETION:"transferCompletion",TRANSFER_ACCEPTANCE:"transferAcceptance",PARK_COMPLETION:"holdCompletion",UNPARK_COMPLETION:"resumeCompletion",UPDATE_MEETING_LIVE_STATE_RESPONSE:"updateMeetingLiveStateResponse",UPDATE_MEETING_GROUPS_RESPONSE:"updateMeetingGroupsResponse",SET_MEETING_LAYOUT_RESPONSE:"setMeetingLayoutResponse",UPDATE_MEETING_STATES_RESPONSE:"updateMeetingStatesResponse",MONITOR_COMPLETION:"monitorCompletion"},an=Zi,on=__toESM(M),ln=class _HttpHeaderImpl{constructor(g){this.headers={},g&&Object.keys(g).forEach((f=>{this.headers[this.getLowerCaseName(f)]=g[f]}))}isEmpty(){return on.isEmpty(this.headers)}set(g,f){this.headers[this.getLowerCaseName(g)]=f}get(g,f){return f?_HttpHeaderImpl.getHeaderValue(this.headers,g)||f:_HttpHeaderImpl.getHeaderValue(this.headers,g)}delete(g){delete this.headers[g],delete this.headers[g.toLowerCase()]}hasOwnPropertyCaseInsensitive(g){return Object.keys(this.headers).filter((function(f){return f.toUpperCase()===g.toUpperCase()})).length>0}getAll(){return this.headers}getLowerCaseName(g){return _HttpHeaderImpl.useLowerCaseHeaders?g.toLowerCase():g}static getHeaderValue(g,f){return g.hasOwnProperty(f)?g[f]:g.hasOwnProperty(f.toLowerCase())?g[f.toLowerCase()]:void 0}};function get2(g,f,S=causeId2()){return assertNotNullOrEmpty(f,"trailingPath cannot be null"),assertNotNull(g,"signalingSession cannot be null"),assertNotNull(g.baseMessagingChannelUrl,"messaging channel url is not set"),`${g.baseMessagingChannelUrl}${an.URL_BASE.CALLAGENT}/${g.sessionId}/${S}${f}`}function getIdFromUrl(g){const f=g.match(new RegExp(`/${escapeRegExp(an.URL_BASE.CALLAGENT)}/+([^/]+)`,"i"));return f?f[1]:null}function clientSupportedTokenTypes(g){let f=1;return g.callingServiceSupportsAADTokens&&(f|=4),g.callingServiceSupportsCAETokens&&(f|=8),f}function parseServiceTokenTypes2(g){const f=g.toLowerCase(),S='token_types="',v=f.indexOf(S);if(-1===v)return[];const C=f.indexOf('"',v+S.length);if(-1===C)return[];const _=f.substring(v+S.length,C).trim();if(""===_)return[];return _.split(" ")}function is1to1Mri(g){return!!g.match(/^8:/)}function stripMri(g){return g.replace(/^\d+:/,"")}function causeId2(){return newGuid().substr(0,8)}function newMessageId(g){return g&&/^[a-z0-9]{8}$/.test(g)?g+newGuid().substr(8):newGuid()}function newGuid(){const g="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",f="0123456789abcdef";let S="",v=0,C=0;for(;C<36;){const _=g[C];switch(v=C%8==0?4294967295*Math.random()|0:v>>4,_){case"x":S+=f[15&v];break;case"y":S+=f[3&v|8];break;case"4":case"-":S+=_}C++}return S}function assert2(g,f){g||throwAssertTransactionEnd("Assert failed"+(void 0!==f?`:${f}`:""))}function assertNotNullOrEmpty(g,f){(!g||g instanceof String&&""===g||g instanceof Array&&0===g.length)&&throwAssertTransactionEnd("AssertNotNullOrEmpty failed. "+(void 0!==f?`: ${f}`:""))}function assertNotNull(g,f){g||throwAssertTransactionEnd("AssertNotNull failed. "+(void 0!==f?`: ${f}`:""))}function assertCallEndReason(g){assertNotNullOrEmpty(g,"callEndReason cannot be null or empty"),(void 0===g.code||void 0===g.subCode||void 0===g.phrase||g.code<0||g.subCode<0||" "===g.phrase)&&throwAssertTransactionEnd(`callEndReason must specify code, subCode and phrase. Invalid reason : ${getPrintableObject(g)}`)}function throwAssertTransactionEnd(g){throw{code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.MISC_ERROR,phrase:g,resultCategories:[Xi.ExpectedError]}}function getMediaTypes(g){assertNotNull(g,"MediaTypes passed cannot be null");const f=[],S=an.MEDIA_TYPES;for(const v of Object.keys(S))arrayContains(g,S[v])&&f.push(S[v]);return f}function getLinksPayload(g,f){const S={};for(const v of Object.values(f)){const f=v.split("/");S[f[f.length-2]]=get2(g,v)}return S}function stringEndsWith(g,f){return g.length>=f.length&&g.indexOf(f,g.length-f.length)>-1}function arrayContains(g,f){const S=f.toString().toLowerCase();return g.map((g=>g.toString().toLowerCase())).indexOf(S)>-1}function tryAddNewKeyToHashTable(g,f,S){return!g.hasOwnProperty(f)&&(g[f]=S,!0)}function tryRemoveKeyFromHashTable(g,f){return!!g.hasOwnProperty(f)&&(delete g[f],!0)}function escapeRegExp(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tryParse(g){let f=null;try{return f=JSON.parse(g),"object"==typeof f?f:null}catch(g){return null}}function getErrorForXHRFailure(g,f){if(!g)return{telemetryEndSubCode:an.CALL_END_CODE.UNKNOWN_ERROR,error:an.CALL_END_UNKNOWN_ERROR};let S;if("object"==typeof g.response)S=g.response;else try{S=JSON.parse(g.response)}catch(g){}if(g.skypeTokenError)return{telemetryEndSubCode:an.CALL_END_CODE.SKYPE_TOKEN_ERROR,error:an.CALL_END_SKYPE_TOKEN_ERROR};if(g.tokenTimeoutError&&!g.tokenInteractivityRequiredTimeout)return{telemetryEndSubCode:an.CALL_END_CODE.HTTP_OTHER_ERROR,error:an.CALL_END_TOKEN_TIMEOUT_ERROR};if(g.tokenError){const f=g.tokenErrorSubCode?{code:an.CALL_END_TOKEN_ERROR.code,subCode:g.tokenErrorSubCode,phrase:an.CALL_END_TOKEN_ERROR.phrase,resultCategories:an.CALL_END_TOKEN_ERROR.resultCategories}:an.CALL_END_TOKEN_ERROR;return{telemetryEndSubCode:an.CALL_END_CODE.HTTP_OTHER_ERROR,error:f}}if(g.tokenInteractivityRequiredTimeout)return{telemetryEndSubCode:an.CALL_END_CODE.HTTP_OTHER_ERROR,error:an.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED};if(S&&(S.operationFailure||S.broadcastOperationFailure)){const g=S.operationFailure||S.broadcastOperationFailure;return{telemetryEndSubCode:g.code,error:g}}return S&&"net::err_name_not_resolved"===S._error?.toLowerCase()?{telemetryEndSubCode:an.CALL_END_CODE.NETWORK_ERROR,error:an.CALL_END_DNS_HOST_NAME_RESOLVE_ERROR}:S?.code?{telemetryEndSubCode:S.code,error:S}:isNaN(g.status)||g.status!==an.CALL_END_CODE.NOT_FOUND?!isNaN(g.status)&&g.status?{telemetryEndSubCode:g.status,error:{code:g.status,subCode:isNaN(g.response)?0:g.response,phrase:g.statusText,resultCategories:[Xi.UnexpectedClientError]}}:!isNaN(g.response)&&g.response?{telemetryEndSubCode:0,error:{code:0,subCode:g.response,phrase:g.statusText,resultCategories:[Xi.UnexpectedClientError]}}:{telemetryEndSubCode:an.CALL_END_CODE.NETWORK_ERROR,error:an.CALL_END_NETWORK_ERROR}:{telemetryEndSubCode:an.CALL_END_CODE.NOT_FOUND,error:an.RESOURCE_NOT_FOUND_ERROR}}function isDuplicateMessage(g,f){if(g&&!g.isEmpty()&&f){const S=g.get(an.HEADERS.ORIGINAL_MESSAGE_ID),v=g.get(an.HEADERS.MESSAGE_ID);if(v&&arrayContains(f,v)||S&&arrayContains(f,S))return!0;f.length>9&&f.shift(),f.push(S||v)}return!1}function extractMessageIdFromMessage(g){const f="unknown";return g.headers?g.headers.get(an.HEADERS.ORIGINAL_MESSAGE_ID,f):f}function extractCauseIdFromMessage(g){try{return g.headers.get(an.HEADERS.ORIGINAL_MESSAGE_ID).replace("-","").substr(0,8)}catch(g){return causeId2()}}function cacheMessageResult(g,f,S){if(g&&f){const v=g.get(an.HEADERS.ORIGINAL_MESSAGE_ID)||g.get(an.HEADERS.MESSAGE_ID)||null;v&&(f[v]=S)}}function getMessageResultFromCache(g,f){if(g){return f[g.get(an.HEADERS.ORIGINAL_MESSAGE_ID)||g.get(an.HEADERS.MESSAGE_ID)||null]||null}return null}function isEncodedMessage(g){return g&&g.hasOwnPropertyCaseInsensitive(an.HEADERS.CONTENT_ENCODING)}function isMessageEncodingSupported(g){return g&&an.KNOWN_PAYLOAD_ENCODINGS.hasOwnProperty(g.get(an.HEADERS.CONTENT_ENCODING).toUpperCase())}function parseRawHttpMessage(g){const f=g.split(/\r?\n\r?\n/),S=f[0].split(/\r?\n/),v=f[1].split(/\r?\n/),C=S.shift().split(" "),_=C[0],T=C[1]||"",I=new ln;for(const g of S)try{const[f,S]=g.split(":").map((g=>Yi.trim(g)));I.set(f,S)}catch(f){throw new Error(`Malformed header: ${g+f}`)}return{url:T,headers:I,method:_,body:v.join("")}}function decodeMessage(g){const f=atob(g);return Qi.inflate(f,{to:"string"})}function defer(){let g,f,S=!0;return{isPending:()=>S,promise:new Promise(((S,v)=>{g=S,f=v})),resolve:f=>{S&&(g(f),S=!1)},reject:g=>{S&&(f(g),S=!1)}}}function isTrouterAndNavigatorConnected(g){let f=!1;try{if(f=g&&2===g.state(),navigator.onLine&&f)return 3;if(!navigator.onLine&&f)return 2;if(navigator.onLine&&!f)return 1}catch{}return 0}function isRetryable(g){return[an.HTTP_STATUS_CODES.UNKNOWN,an.HTTP_STATUS_CODES.UNAUTHORIZED,an.HTTP_STATUS_CODES.NETWORK_ERROR,an.HTTP_STATUS_CODES.OFFLINE,an.HTTP_STATUS_CODES.TIMEOUT,an.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,an.HTTP_STATUS_CODES.BAD_GATEWAY,an.HTTP_STATUS_CODES.SERVICE_UNAVAILABLE,an.HTTP_STATUS_CODES.GATEWAY_TIMEOUT].indexOf(g)>=0}function convertStringToTokenType(g,f){switch(g){case an.HEADERS.CAE_KEYWORD.toLowerCase():return 8;case an.HEADERS.AAD_KEYWORD.toLowerCase():return 4;case an.HEADERS.SKYPE_KEYWORD.toLowerCase():return 1;default:return f?.info("unexpected: unrecognized token type ${tokenType}"),null}}function getAuthHeadersTokenTypes(g,f,S,v,C){if(!f)return 1;const{callingServiceSupportsAADTokens:_,callingServiceSupportsCAETokens:T,supportMissingTokenTypesInResponse:I,useSkypeTokenWhenNoAuthenticateHeader:b}=g,A=C?.authenticationHeaders;v?.info(`[getAuthHeadersTokenTypes] UnauthorizedResponse=${S} and authHeaders=${A}`);let P=null;if(!A&&S)b?(v?.info("[getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),P=1):(v?.info("[getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),P=clientSupportedTokenTypes(g));else if(A||S){if(A&&S)for(const f of A){const S=parseServiceTokenTypes2(f);if(I&&0===S.length)v?.info("[getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),P=clientSupportedTokenTypes(g);else for(const g of S){const f=convertStringToTokenType(g.toLowerCase(),v);T&&8===f&&(P|=8),_&&4===f&&(P|=4),1===f&&(P|=1)}}}else v?.info("[getAuthHeadersTokenTypes] first time requesting token, request client supported token types"),P=clientSupportedTokenTypes(g);return P}function getRequestTypeAsString(g){switch(g){case 0:return"GET";case 1:return"POST";case 2:return"PUT";case 3:return"DELETE"}}function extractWwwauthenticateHeaders(g){let f={};if(g){const S=ln.getHeaderValue(g,an.HEADERS.AUTHENTICATE);S&&(f={authenticationHeaders:[S]})}return f}function getTokenMetadata(g,f,S,v,C=!1,_,T){T?.createChild("[utils.ts]");const I={verb:getRequestTypeAsString(S),path:v.url},b=JSON.stringify(I),A=extractWwwauthenticateHeaders(_),P=getAuthHeadersTokenTypes(g,f,C,T,A);return T?.info(`[getTokenMetadata] return token type=${P}, factoJson=${b}, headers=${A?.authenticationHeaders}`),{tokenType:P,factorsJson:b,requestMetadataJson:A,isUnauthorized:C}}function epochTimeInSecRoundedDown(){return Math.floor(Date.now()/1e3)}function millieSecondsToSeconds(g){return g/1e3}function secondsToMillieSeconds(g){return 1e3*g}function getRequestToken(g){const f=ln.getHeaderValue(g,an.HEADERS.SKYPE_TOKEN);if(f)return f;const S=ln.getHeaderValue(g,an.HEADERS.AUTHORIZATION);if(S){const g=S.split(" ");if(2===g.length)return g[1]}}function getParkTypeName(g){switch(g){case"none":return"None";case"teamPark":return"TeamPark";case"callPark":return"CallParkV2";case"serverHold":return"ServerHold";case"serverHoldV2":return"MusicOnHoldV2";case"sharedLinePark":return"SharedLinePark";case"sharedLineParkV2":return"SharedLineAppearanceV2";default:return"UnknownType"}}function getPluginlessStateTypeFromWire(g){switch(g){case"raiseHands":return"raiseHands";case"ufd":return"ufd";case"attendeeModalitiesUnrestricted":return"attendeeModalitiesUnrestricted";case"attendeeAudioRestricted":return"attendeeAudioRestricted";case"attendeeVideoRestricted":return"attendeeVideoRestricted";case"attendeeVideoUnrestricted":return"attendeeVideoUnrestricted";case"spotlight":return"spotlight";case"weatherPerson":return"weatherPerson";case"sharingLayoutType":return"sharingLayoutType";case"manageBreakoutRooms":return"manageBreakoutRooms";case"togetherMode":return"togetherMode";case"consentToRecording":return"consentToRecording";case"denyConsentToRecording":return"denyConsentToRecording";case"clientMediaUfd":return"clientMediaUfd";case"serverMediaUfd":return"serverMediaUfd";case"dhhSigner":return"dhhSigner";case"signLanguageInterpreter":return"signLanguageInterpreter";default:throw"Invalid state type when converting PublishType to PublishStateType."}}function getPluginlessStateType(g){switch(g){case"raiseHands":return"raiseHands";case"ufd":return"ufd";case"attendeeModalitiesUnrestricted":return"attendeeModalitiesUnrestricted";case"attendeeAudioRestricted":return"attendeeAudioRestricted";case"attendeeVideoRestricted":return"attendeeVideoRestricted";case"attendeeVideoUnrestricted":return"attendeeVideoUnrestricted";case"spotlight":return"spotlight";case"weatherPerson":return"weatherPerson";case"sharingLayoutType":return"sharingLayoutType";case"manageBreakoutRooms":return"manageBreakoutRooms";case"togetherMode":return"togetherMode";case"consentToRecording":return"consentToRecording";case"denyConsentToRecording":return"denyConsentToRecording";case"clientMediaUfd":return"clientMediaUfd";case"serverMediaUfd":return"serverMediaUfd";case"dhhSigner":return"dhhSigner";case"signLanguageInterpreter":return"signLanguageInterpreter";default:throw"Invalid state type when converting PublishStateType to PublishType."}}function getParticipantInvitationData(g){let f={};return g.additionalData&&g.customHeaderContext?f="object"==typeof g.additionalData?{...g.additionalData,customContext:g.customHeaderContext}:{additionalData:g.additionalData,customContext:g.customHeaderContext}:!g.additionalData&&g.customHeaderContext?f={customContext:g.customHeaderContext}:g.additionalData&&!g.customHeaderContext&&(f=g.additionalData),f}function parseDisplayNameSourceFromWire(g){if(!g)return;let f="unknown";return"substrate"===g&&(f="substrate"),f}var cn=class _Participant{static isInLobby(g,f){for(const S of g)if(S.endpointId===f&&S.isLobby)return!0;return!1}static isParticipantServerMuted(g){for(const f of g)if(f.mediaStreams&&!f.mappedTo)for(const g of f.mediaStreams)if("audio"===g.type&&!0===g.serverMuted)return!0;return!1}static fromWireParticipant(g){return assertNotNull(g,"invalid wireParticipant"),assertNotNullOrEmpty(g.id,"participant must have valid Id"),new _Participant({id:g.id,displayName:g.displayName,languageId:g.languageId,acceptedBy:g.acceptedBy})}static getPluginlessStateTypeFromWire(g){return getPluginlessStateTypeFromWire(g)}static findOrCreateTypeState(g,f){let S=f.typeStates.findIndex((f=>f.type===g));if(-1===S){const v={participantStates:[],type:g};f.typeStates.push(v),S=f.typeStates.length-1}return S}static processPublishedStates(g,f){const S={typeStates:[]};S.typeStates=[];const v=g;return Ji.forEach(v,(g=>{const v=this.findOrCreateTypeState(this.getPluginlessStateTypeFromWire(g.stateType),S),C={id:f,publishedState:{content:g.content,stateId:g.stateId,typeRank:g.typeRank}};S.typeStates[v].participantStates.push(C)})),S}static fromRosterEndpoints(g){let f=[],S=!1,v=!1,C=!1,_=!1;return f=Object.keys(g).map((f=>{let T,I,b,A=[],P=!1,R=0;if(g[f].call&&(S=!0,A=g[f].call.mediaStreams||null,R=g[f].call.serverMuteVersion||0,I=g[f].call.appliedInteractivityLevel||"unknown",b=g[f].call.negotiationTag),g[f].lobby&&(P=!0,v=!0,A=g[f].lobby.mediaStreams||null),g[f].broadcast?.sessionInformation&&(T=g[f].broadcast.sessionInformation.role||null),g[f].mappedParticipant&&(C=!0,A=g[f].mappedParticipant.mediaStreams||null),!g[f].capabilities&&g[f].endpointCapabilities){const S=g[f].endpointCapabilities;g[f].capabilities={implicitCallback:16&S?"enabled":"disabled",cloudAudioVideoConference:1&S?"enabled":"disabled",cloudScreenSharing:2&S?"enabled":"disabled",hostlessConference:4&S?"enabled":"disabled",autoJoinOnConflict:32&S?"enabled":"disabled",serverMuteUnmute:64&S?"enabled":"disabled",supportsCompressedServicePayload:128&S?"enabled":"disabled",cloudMerge:8&S?"enabled":"disabled"}}return _=_||!!g[f].streamLobby||!!g[f].stream,{endpointId:f,participantId:g[f].participantId||null,clientVersion:g[f].clientVersion||null,endpointMetadata:g[f].endpointMetadata||null,originalId:g[f].originalId||null,contentSharing:g[f].contentSharing||null,capabilities:g[f].capabilities||null,endpointType:g[f].endpointType||"default",deviceType:g[f].deviceType||void 0,clientEndpointCapabilities:g[f].clientEndpointCapabilities||void 0,mediaStreams:A,serverMuteVersion:R,broadcastMeetingRole:T,isLobby:P,endpointState:g[f].endpointState||null,publishedStates:g[f].publishedStates||null,callLinks:g[f].callLinks||null,appliedInteractivityLevel:I||"unknown",mappedTo:g[f].mappedTo||null,meetingGroupDetails:g[f].meetingGroupDetails,streamInformation:g[f].streamInformation,propertyBag:g[f].propertyBag,streamLobby:g[f].streamLobby,stream:g[f].stream,endpointMeetingRoles:g[f].endpointMeetingRoles,negotiationTag:b}})),{endpointDetails:f,participantHasCallModality:S,participantIsInLobby:v,participantHasMappedEndpoint:C,participantHasStreamEndpoint:_}}static fromRoster(g,f=!1){assertNotNull(g,`invalid rosterParticipant ${JSON.stringify(g)}`),assertNotNullOrEmpty(g.details.id,"participant must have valid Id");const S=g.endpoints||{},v=this.fromRosterEndpoints(S),C=v.endpointDetails,_=v.participantHasCallModality,T=v.participantHasMappedEndpoint,I=v.participantHasStreamEndpoint;let b=v.participantIsInLobby;return _||b||T||f||I?(_&&(b=!1),new _Participant({id:g.details.id,displayName:g.details.displayName,otpIdentity:g.details.otpIdentity,version:g.version||0,propertyBag:g.details.propertyBag||null,languageId:g.details.languageId,role:g.role||"",tenantId:g.details.tenantId||"",endpointDetails:C||[],acceptedBy:g.acceptedBy||"",isLobby:b,meetingRole:g.meetingRole,advancedMeetingRole:g.advancedMeetingRole,meetingRoles:g.meetingRoles,participantType:g.details.participantType,publishedStates:g.publishedStates||null,isIdentityMasked:g.details.isIdentityMasked,nonMaskedId:g.details.nonMaskedId||"",nonMaskedObjectId:g.details.nonMaskedObjectId||"",nonMaskedDisplayName:g.details.nonMaskedDisplayName||"",maskedIdSeqNumber:g.details.maskedIdSeqNumber||0,maskedId:g.details.maskedId||"",joinAsStreamingUser:g.joinAsStreamingUser,enableCaptcha:g.enableCaptcha})):null}static fromRosterSearchResults(g){assertNotNull(g,`invalid rosterParticipant ${JSON.stringify(g)}`),assertNotNullOrEmpty(g.details.id,"participant must have valid Id");const f=g.endpoints,{endpointDetails:S,participantHasCallModality:v,participantIsInLobby:C,participantHasMappedEndpoint:_,participantHasStreamEndpoint:T}=this.fromRosterEndpoints(f);let I=0;return v||T?I=3:C?I=10:_&&(I=3),{id:g.details.id,state:I,tenantId:g.details.tenantId||"",displayName:g.details.displayName,role:g.role||"",meetingRole:g.meetingRole,advancedMeetingRole:g.advancedMeetingRole,meetingRoles:g.meetingRoles,participantType:g.details.participantType,isServerMuted:this.isParticipantServerMuted(S),publishedStates:this.processPublishedStates(g.publishedStates,g.details.id),endpoints:S||[],isIdentityMasked:g.details.isIdentityMasked,nonMaskedId:g.details.nonMaskedId||"",nonMaskedDisplayName:g.details.nonMaskedDisplayName||"",nonMaskedObjectId:g.details.nonMaskedObjectId||"",maskedIdSeqNumber:g.details.maskedIdSeqNumber||0,maskedId:g.details.maskedId||"",joinAsStreamingUser:g.joinAsStreamingUser}}constructor(g){this.id=g.id,this.displayName=g.displayName||"",this.otpIdentity=g.otpIdentity,this.version=g.version,this.propertyBag=g.propertyBag,this.languageId=g.languageId||null,this.endpointDetails=g.endpointDetails||[],this.acceptedBy=g.acceptedBy,this.role=g.role,this.tenantId=g.tenantId,this.isLobby=g.isLobby,this.meetingRole=g.meetingRole,this.advancedMeetingRole=g.advancedMeetingRole,this.meetingRoles=g.meetingRoles,this.participantType=g.participantType,this.publishedStates=g.publishedStates,this.isIdentityMasked=g.isIdentityMasked,this.nonMaskedId=g.nonMaskedId,this.nonMaskedDisplayName=g.nonMaskedDisplayName,this.nonMaskedObjectId=g.nonMaskedObjectId,this.maskedIdSeqNumber=g.maskedIdSeqNumber,this.maskedId=g.maskedId,this.joinAsStreamingUser=g.joinAsStreamingUser,this.enableCaptcha=g.enableCaptcha}},dn={HANDLE_MEDIA_ACKNOWLEDGEMENT:"HandleMediaAcknowledgement",HANDLE_MEDIA_NEGOTIATION_FAILURE:"HandleMediaNegotiationFailure",HANDLE_MEDIA_ANSWER:"HandleMediaAnswer",HANDLE_MEDIA_ANSWER_FAILED:"HandleMediaAnswerFailed",HANDLE_MEDIA_OFFER:"HandleMediaOffer",REJECT_RENEGOTIATION:"RejectRenegotiation",HANDLE_RETARGET_COMPLETED:"HandleRetargetCompleted",HANDLE_MEDIA_ANSWER_TIMEOUT:"HandleMediaAnswerTimeout",HANDLE_MEDIA_ACKNOWLEDGEMENT_TIMEOUT:"HandleMediaAcknowledgementTimeout",ACCEPT_RENEGOTIATION:"AcceptRenegotiation",START_RENEGOTIATION:"StartRenegotiation",MEDIA_FSM_STATE_CHANGED:"MediaFsmStateChanged",ADD_MODALITY_TIMEOUT:"AddModalityTimeout",ADD_PARTICIPANT:"AddParticipant",ADD_PARTICIPANT_TIMEOUT:"AddParticipantTimeout",ADD_PARTICIPANT_WITH_REPLACES:"AddParticipantWithReplaces",ADD_PARTICIPANT_WITH_REPLACES_TIMEOUT:"AddParticipantWithReplacesTimeout",ADD_PARTICIPANTS_AND_MODALITY:"AddParticipantsAndModality",ADMIT_PARTICIPANT:"AdmitParticipant",ADMIT_PARTICIPANT_TIMEOUT:"AdmitParticipantTimeout",ADMIT:"Admit",ADMIT_TIMEOUT:"AdmitTimeout",ADMIT_FAILURE:"AdmitFailure",ADMIT_SUCCESS:"AdmitSuccess",CALL_ME_BACK:"CallMeBack",CALL_ME_BACK_TIMEOUT:"CallMeBackTimeout",REMOVE_PARTICIPANT:"RemoveParticipant",REMOVE_PARTICIPANT_OTHERS:"RemoveParticipantOthers",REMOVE_PARTICIPANT_SPECIFIED:"RemoveParticipantSpecified",REMOVE_PARTICIPANT_TIMEOUT:"RemoveParticipantTimeout",HANDLE_ADD_PARTICIPANT_SUCCESS:"HandleAddParticipantSuccess",HANDLE_ADD_PARTICIPANT_FAILURE:"HandleAddParticipantFailure",HANDLE_ADMIT_PARTICIPANT_SUCCESS:"HandleAdmitParticipantSuccess",HANDLE_ADMIT_PARTICIPANT_FAILURE:"HandleAdmitParticipantFailure",HANDLE_ADD_PARTICIPANT_MODALITY_FAILURE:"HandleAddParticipantModalityFailure",HANDLE_REMOVE_PARTICIPANT_SUCCESS:"HandleRemoveParticipantSuccess",HANDLE_REMOVE_PARTICIPANT_FAILURE:"HandleRemoveParticipantFailure",HANDLE_ROSTER_UPDATE:"HandleRosterUpdate",HANDLE_ROSTER_UPDATE_FAIL:"HandleRosterUpdateFail",HANDLE_CONVERSATION_UPDATE:"HandleConversationUpdate",HANDLE_LOCAL_PARTICIPANT_UPDATE:"HandleLocalParticipantUpdate",SET_SUBJECT:"SetSubject",SET_JOINED_FROM:"SetJoinedFrom",SET_DEVICETYPE:"SetDeviceType",GET_EMERGENCY_CONTENT:"GetEmergencyContent",SET_MULTIPARTY:"SetMultiparty",SET_GROUPID:"SetGroupId",SET_THREADID:"SetThreadId",SET_CALLOPTIONS:"SetCallOptions",SET_TRANSFER_CONTEXT:"SetTransferContext",START_CALL:"StartCall",JOIN_CALL:"JoinCall",START_OR_JOIN_CALL:"StartOrJoinCall",JOIN_CONVERSATION_WITHOUT_CALL_MODALITY:"JoinConversationWithoutCallModality",HANDLE_INCOMING_CALL:"HandleIncomingCall",END_CALL:"EndCall",END_WITH_BEACON:"EndWithBeacon",REJECT_WITH_FETCH_KEEP_ALIVE:"RejectWithFetchKeepAlive",END_WITH_FETCH_KEEP_ALIVE:"EndWithFetchKeepAlive",CONFLICTED_CALL:"ConflictedCall",SET_PROVISIONAL_ANSWER:"SetProvisionalAnswer",SET_PROVISIONAL_ANSWER_FAILED:"SetProvisionalAnswerFailed",ACCEPT_CALL:"AcceptCall",ACCEPT_CALL_FAILED:"AcceptCallFailed",HANDLE_CALL_ACCEPTANCE_ACK:"HandleCallAcceptanceAck",HANDLE_CALL_ACCEPTANCE:"HandleCallAcceptance",HANDLE_CALL_ACCEPTANCE_SYNC:"HandleCallAcceptanceSync",HANDLE_CALL_ACCEPTANCE_FAILED:"HandleCallAcceptanceFailed",HANDLE_CALL_ESTABLISHMENT_TIMEOUT:"HandleCallEstablishmentTimeout",HANDLE_CALL_END:"HandleCallEnd",HANDLE_CALL_PROGRESS:"HandleCallProgress",TROUTER_URL_CHANGED:"TrouterUrlChanged",TROUTER_STATE_CHANGED:"TrouterStateChanged",TROUTER_URL_CHANGED_TO_INVALID:"TrouterUrlChangedToInvalid",TROUTER_URL_UPDATE_FAILED:"TrouterUrlUpdateFailed",ADD_CONTENT_SHARING_MODALITY:"AddContentSharingModality",ACCEPTED_BEFORE_RINGING:"AcceptedBeforeRinging",LEAVE_CONTENT_SHARING:"LeaveContentSharing",DELETE_CONTENT_SHARING:"DeleteContentSharing",TAKE_CONTROL_CONTENT_SHARING:"TakeControlContentSharing",UPDATE_SESSION_STATE_CONTENT_SHARING:"UpdateSessionStateContentSharing",JOIN_CONTENT_SHARING:"JoinContentSharing",UPDATE_PARTICIPANT_STATE_CONTENT_SHARING:"UpdateParticipantStateContentSharing",HANDLE_CONTENT_SHARING_UPDATE:"HandleContentSharingUpdate",HANDLE_CONTENT_SHARING_END:"HandleContentSharingEnd",CONTENT_SHARING_START_FROM_ROSTER:"ContentSharingStartFromRoster",CONTENT_SHARING_END_FROM_ROSTER:"ContentSharingEndFromRoster",HANDLE_ADD_MODALITY_SUCCESS:"HandleAddModalitySuccess",HANDLE_ADD_MODALITY_FAILURE:"HandleAddModalityFailure",ADD_BROADCAST_MODALITY:"AddBroadcastModality",ADD_MODALITY:"AddModality",UPDATE_BROADCAST_DETAILS:"UpdateBroadcastDetails",WAITING_FOR_ADD_BROADCAST_MODALITY_COMPLETION:"WaitingForAddBroadcastModalityCompletion",WAITING_FOR_ADD_MODALITY_COMPLETION:"WaitingForAddModalityCompletion",MUTE:"Mute",NUDGE_PARTICIPANT_TIMEOUT:"NudgeParticipantTimeout",UNMUTE:"Unmute",UNMUTE_TIMEOUT:"UnmuteTimeout",HANDLE_UNMUTE_CONFIRM:"HandleUnmuteConfirm",HANDLE_UNMUTE_SUCCESS:"HandleUnmuteSuccess",HANDLE_UNMUTE_FAILURE:"HandleUnmuteFailure",APPROVE_UNMUTE:"ApproveUnmute",REJECT_UNMUTE:"RejectUnmute",HANDLE_CONTROL_VIDEO_STREAMING:"HandleControlVideoStreaming",HANDLE_DOMINANT_SPEAKER_CHANGED_COUNT:"HandleDominantSpeakerChangedCount",HANDLE_CSRC_INFO:"HandleCsrcInfo",SEND_WEBRTC_MEDIA_NOTIFICATION:"SendWebRtcMediaNotification",HANDLE_BALANCE_UPDATE:"HandleBalanceUpdate",TRANSFER_CALL:"TransferCall",PARK_CALL:"ParkCall",CALL_REDIRECT:"CallRedirect",CALL_REDIRECT_REQUEST_FAILED:"CallRedirectRequestFailed",TRANSFER_COMPLETION_FAILED:"TransferCompletionFailed",TRANSFER_REQUEST_RECEIVED:"TransferRequestReceived",HANDLE_PARK_REQUESTED:"HandleParkRequested",HANDLE_SERVER_HOLD:"HandleServerHold",DUPLICATE_MESSAGE_IGNORED:"DuplicateMessageIgnored",CORRELATION_ID_UPDATED:"CorrelationIdUpdated",UNKNOWN_MESSAGE_TYPE:"UnkownMessageType",FAILED_TO_HANDLE_MESSAGE:"FailedToHandleMessage",CONNECTIVITY_CHANGED:"ConnectivityChanged",TROUTER_DECODE_PAYLOAD_FAILURE:"TrouterDecodePayloadFailure",UPDATE_ENDPOINT_STATE:"UpdateEndpointState",UPDATE_ENDPOINT_STATE_SUCCESS:"UpdateEndpointStateSuccess",UPDATE_ENDPOINT_STATE_FAILURE:"UpdateEndpointStateFailure",BROKER_DECODE_PAYLOAD_FAILURE:"BrokerDecodePayloadFailure",BROKER_SUBSCRIPTION_TIMEOUT:"BrokerSubscriptionTimeout",BROKER_SUBSCRIPTION_SUCCESSFUL:"BrokerSubscriptionSuccessful",BROKER_SUBSCRIPTION_FAILED:"BrokerSubscriptionFailed",FAILED_TO_HANDLE_TROUTER_MESSAGE:"FailedToHandleTrouterMessage",FAILED_TO_HANDLE_BROKER_MESSAGE:"FailedToHandleBrokerMessage",BROKER_DISABLED_SUBSCRIBE_URL_PRESENT:"BrokerDisabledSubscribeUrlPresent",CONNECTED:"Connected",IN_LOBBY:"InLobby",STAGING:"Staging",MESSAGE_MISSING_BODY:"MessageMissingBody",BROADCAST_STATE_CHANGED:"BroadcastStateChanged",HANDLE_CALL_NOTIFICATION:"HandleCallNotification",HANDLE_INCOMING_CALL_REPLACEMENT:"HandleIncomingCallReplacement",HANDLE_PSTN_BALANCE_UPDATE:"HandlePstnBalanceUpdate",IGNORE_OLD_ROSTER:"IgnoreOldRoster",HANDLE_MEDIA_ACK:"HandleMediaAck",HANDLE_MEDIA_PROVISIONAL_ACK:"HandleMediaProvisionalAck",UPDATE_CALL_STATUS:"UpdateCallStatus",SEND_ATTACH:"SendAttach",REQUEST_NEW_OFFER:"RequestNewOffer",HANDLE_NEW_OFFER:"HandleNewOffer",UPDATE_CONVERSATION_LINKS:"UpdateConversationLinks",UPDATE_CONVERSATION_LINKS_SUCCESS:"UpdateConversationLinksSuccess",UPDATE_CONVERSATION_LINKS_FAILED:"UpdateConversationLinksFailed",PROCESS_INITIAL_OFFER:"ProcessInitialOffer",SEND_PROGRESS:"SendProgress",SEND_PROGRESS_FAILED:"SendProgressFailed",PROCESS_CALL_ACCEPTANCE:"ProcessCallAcceptance",ACCEPTANCE_USER_IN_LOBBY:"AcceptanceUserInLobby",REJECT_INCOMING_CALL:"RejectIncomingCall",SEND_KEEP_ALIVE:"SendKeepAlive",SEND_KEEP_ALIVE_FAILED:"SendKeepAliveFailed",SEND_CONVERSATION_KEEP_ALIVE_FAILED:"SendConversationKeepAliveFailed",START_AUDIO:"StartAudio",STOP_AUDIO:"StopAudio",UPDATE_MEETING_ROLE:"UpdateMeetingRole",UPDATE_MEETING_ROLE_TIMEOUT:"UpdateMeetingRoleTimeout",PREHEAT_ENABLING:"EnablingPreheat",PREHEAT_DISABLING:"DisablingPreheat",PREHEAT_DISABLED:"PreheatDisabled",TRANSFER_REQUEST_SENT:"TransferRequestSent",CALL_REDIRECT_REQUEST_SENT:"CallRedirectRequestSent",TRANSFER_REQUEST_FAILED:"TransferRequestFailed",SEND_ACCEPT_TRANSFER:"SendAcceptTransfer",SEND_ACCEPT_TRANSFER_FAIL:"SendAcceptTransferFail",WAITING_FOR_TRANSFER_COMPLETION:"WaitingForTransferCompletion",WAITING_FOR_TRANSFER_COMPLETION_FAIL:"WaitingForTransferCompletionFail",WAITING_FOR_TRANSFER_ACCEPTANCE_FAIL:"WaitingForTransferAcceptanceFail",WAITING_FOR_TRANSFER_ACCEPTANCE:"WaitingForTransferAcceptance",TRANSFER_COMPLETED:"TransferCompleted",SEND_COMPLETE_TRANSFER:"SendCompleteTransfer",SEND_COMPLETE_TRANSFER_FAILED:"SendCompleteTransferFailed",PICKUP_CODE_SET:"PickupCodeSet",ADD_PARTICIPANT_WITH_PICKUP_CODE:"AddParticipantWithPickupCode",ADD_PARTICIPANT_WITH_PICKUP_CODE_TIMEOUT:"AddParticipantWithPickupCodeTimeout",PUBLISH_STATE:"PublishState",PUBLISH_STATE_FAILURE:"PublishStateFailure",REMOVE_STATE:"RemoveState",REMOVE_STATE_FAILURE:"RemoveStateFailure",UPDATE_MEETING_SETTINGS:"UpdateMeetingSettings",UPDATE_MEETING_SETTINGS_FAILURE:"UpdateMeetingSettingsFailure",UPDATE_ENDPOINT_METADATA_SUCCESS:"UpdateEndpointMetadataSuccess",UPDATE_ENDPOINT_METADATA_FAILURE:"UpdateEndpointMetadataFailure",SEARCH_PARTICIPANTS:"SearchParticipants",GET_ALL_PARTICIPANTS:"GetAllParticipants",SEARCH_PARTICIPANTS_FAILURE:"SearchParticipantsFailure",GET_ALL_PARTICIPANTS_FAILURE:"GetAllParticipantsFailure",PARK_REQUEST:"SendParkRequest",PARK_REQUEST_FAILED:"ParkRequestFailed",WAITING_FOR_PARK_COMPLETION:"WaitingForParkCompletion",WAITING_FOR_PARK_COMPLETION_TIMEOUT:"WaitingForParkCompletionTimeout",PARK_COMPLETED:"ParkCompleted",PARK_FAILED:"ParkFailed",SEND_UNPARK_REQUEST:"SendUnparkRequest",UNPARK_REQUEST_FAILED:"UnparkRequestFailed",WAITING_FOR_UNPARK_COMPLETION:"WaitingForUnparkCompletion",WAITING_FOR_UNPARK_COMPLETION_TIMEOUT:"WaitingForUnparkCompletionTimeout",UNPARK_COMPLETED:"UnparkCompleted",UNPARK_FAILED:"UnparkFailed",UPDATE_MEETING_LIVE_STATE:"UpdateMeetingLiveState",WAITING_FOR_UPDATE_MEETING_LIVE_STATE_COMPLETION:"WaitingForUpdateMeetingLiveStateCompletion",UPDATE_MEETING_LIVE_STATE_REQUEST_FAILED:"UpdateMeetingLiveStateRequestFailed",UPDATE_MEETING_LIVE_STATE_RESPONSE_FAILURE:"UpdateMeetingLiveStateResponseFailure",UPDATE_MEETING_LIVE_STATE_RESPONSE_SUCCESS:"UpdateMeetingLiveStateResponseSuccess",UPDATE_MEETING_GROUPS:"UpdateMeetingGroups",UPDATE_PARTICIPANT_INTERPRETATION_STATE:"UpdateParticipantInterpretationState",UPDATE_PARTICIPANTS_PROPERTIES:"UpdateParticipantsProperties",JOIN_MEETING_GROUP:"JoinMeetingGroup",LEAVE_MEETING_GROUP:"LeaveMeetingGroup",INCOMING_PROXIED_MESSAGES:"incomingProxiedMessages",WAITING_FOR_UPDATE_MEETING_GROUPS_COMPLETION:"WaitingForUpdateMeetingGroupsCompletion",UPDATE_MEETING_GROUPS_REQUEST_FAILED:"UpdateMeetingGroupsRequestFailed",UPDATE_MEETING_GROUPS_REQUEST_COMPLETED:"UpdateMeetingGroupsRequestCompleted",UPDATE_MEETING_GROUPS_RESPONSE_FAILURE:"UpdateMeetingGroupsResponseFailure",UPDATE_MEETING_GROUPS_RESPONSE_SUCCESS:"UpdateMeetingGroupsResponseSuccess",SET_MEETING_LAYOUT:"SetMeetingLayout",WAITING_FOR_SET_MEETING_LAYOUT_COMPLETION:"WaitingForSetMeetingLayoutCompletion",SET_MEETING_LAYOUT_REQUEST_FAILED:"SetMeetingLayoutRequestFailed",SET_MEETING_LAYOUT_RESPONSE_FAILURE:"SetMeetingLayoutResponseFailure",SET_MEETING_LAYOUT_RESPONSE_SUCCESS:"SetMeetingLayoutResponseSuccess",WAITING_FOR_UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION:"WaitingForUpdateParticipantInterpretationStateCompletion",UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT:"UpdateParticipantInterpretationStateTimeout",UPDATE_PARTICIPANT_INTERPRETATION_STATE_REQUEST_FAILED:"UpdateParticipantInterpretationStateRequestFailed",UPDATE_PARTICIPANT_INTERPRETATION_STATE_REQUEST_COMPLETED:"UpdateParticipantInterpretationStateRequestCompleted",UPDATE_PARTICIPANT_INTERPRETATION_STATE_RESPONSE_FAILED:"UpdateParticipantInterpretationStateResponseFailed",UPDATE_PARTICIPANT_INTERPRETATION_STATE_RESPONSE_COMPLETED:"UpdateParticipantInterpretationStateResponseCompleted",WAITING_FOR_UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION:"WaitingForUpdateParticipantsPropertiesCompletion",UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT:"UpdateParticipantsPropertiesTimeout",UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED:"UpdateParticipantsPropertiesResponseFailed",UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_COMPLETED:"UpdateParticipantsPropertiesResponseCompleted",WAITING_FOR_JOIN_MEETING_GROUP_COMPLETION:"WaitingForJoinMeetingGroupCompletion",JOIN_MEETING_GROUP_REQUEST_FAILED:"JoinMeetingGroupRequestFailed",JOIN_MEETING_GROUP_REQUEST_COMPLETED:"JoinMeetingGroupRequestCompleted",JOIN_MEETING_GROUP_RESPONSE_FAILED:"JoinMeetingGroupRequestFailed",JOIN_MEETING_GROUP_RESPONSE_COMPLETED:"JoinMeetingGroupRequestCompleted",WAITING_FOR_LEAVE_MEETING_GROUP_COMPLETION:"WaitingForLeaveMeetingGroupCompletion",LEAVE_MEETING_GROUP_REQUEST_FAILED:"LeaveMeetingGroupRequestFailed",LEAVE_MEETING_GROUP_REQUEST_COMPLETED:"LeaveMeetingGroupRequestCompleted",LEAVE_MEETING_GROUP_RESPONSE_FAILED:"LeaveMeetingGroupRequestFailed",LEAVE_MEETING_GROUP_RESPONSE_COMPLETED:"LeaveMeetingGroupRequestCompleted",SUBSCRIBE_URL_FOUND:"SubscribeUrlFound",SUBSCRIBE_URL_MISSING:"SubscribeUrlMissing",SEND_MESSAGE_COMPLETION:"SendMessageCompletion",SEND_MESSAGE_TIMEOUT:"SendMessageTimeout",DISABLE_PREHEAT_SUCCEEDED:"DiablePreheatSucceeded",ASYNC_DISABLE_PREHEAT_SUCCEEDED:"AsyncDisablePreheatSucceeded",DISABLE_PREHEAT_FAILED:"DiablePreheatFailed",ASYNC_DISABLE_PREHEAT_FAILED:"AsyncDiablePreheatFailed",ASYNC_DISABLE_PREHEAT_TIMEOUT:"AsyncDiablePreheatTimeout",DISABLE_PREHEAT_RESPONSE_RECEIVED:"DisablePreheatResponseReceived",SET_STREAM_INFORMATION_RECEIVED:"StreamInformationReceived",UPDATE_MEDIA_DESCRIPTIONS:"UpdateMediaDescriptions",UPDATE_MEDIA_DESCRIPTIONS_FAILED:"UpdateMediaDescriptionsFailed",NUDGE_TO_JOIN_REALTIME:"NudgeToJoinAsRealtime",UPDATE_MEETING_STATES:"UpdateMeetingStates",WAITING_FOR_UPDATE_MEETING_STATES_COMPLETION:"WaitingForUpdateMeetingStatesCompletion",UPDATE_MEETING_STATES_RESPONSE_SUCCESS:"UpdateMeetingStatesResponseSuccess",UPDATE_MEETING_STATES_RESPONSE_FAILURE:"UpdateMeetingStatesResponseFailure",UPDATE_MONITOR_SESSION:"UpdateMonitorSession",UPDATE_MONITOR_SESSION_REQUEST_FAILED:"UpdateMonitorSessionRequestFailed",UPDATE_MONITOR_SESSION_REQUEST_COMPLETED:"UpdateMonitorSessionRequestCompleted",UPDATE_MONITOR_SESSION_RESPONSE_FAILED:"UpdateMonitorSessionResponseFailed",UPDATE_MONITOR_SESSION_RESPONSE_COMPLETED:"UpdateMonitorSessionResponseCompleted",WAITING_FOR_UPDATE_MONITOR_SESSION_COMPLETION:"WaitingForUpdateMonitorSessionCompletion"},hn={SEND_MEDIA_ANSWER:{name:"SendMediaAnswer",controller:0},START_RENEGOTIATION:{name:"StartRenegotiation",controller:0},SEND_MEDIA_ACKNOWLEDGEMENT:{name:"SendMediaAcknowledgement",controller:0},SEND_MEDIA_REJECTION:{name:"SendMediaRejection",controller:0},ADD_PARTICIPANT:{name:"AddParticipant",controller:1},ADD_PARTICIPANT_WITH_REPLACES:{name:"AddParticipantWithReplaces",controller:1},NUDGE_PARTICIPANT:{name:"NudgeParticipant",controller:1},REMOVE_PARTICIPANT_NONE:{name:"RemoveParticipant",controller:1},REMOVE_PARTICIPANT_OTHERS:{name:"RemoveParticipantOthers",controller:1},REMOVE_PARTICIPANT_SPECIFIED:{name:"RemoveParticipantSpecified",controller:1},ADMIT_PARTICIPANT:{name:"AdmitParticipant",controller:1},ADMIT:{name:"Admit",controller:1},BROKER_SUBSCRIBE:{name:"BrokerSubscribe",controller:2},CALL_ME_BACK:{name:"CallMeBack",controller:1},SEND_ACCEPTANCE:{name:"SendAcceptance",controller:0},SEND_ACCEPTANCE_ACKNOWLEDGEMENT:{name:"SendAcceptanceAcknowledgement",controller:0},END_CALL:{name:"EndCall",controller:1},CANCEL_CALL:{name:"CancelCall",controller:1},REJECT_CALL:{name:"RejectCall",controller:0},JOIN_CONVERSATION:{name:"JoinConversation",controller:1},JOIN_CONVERSATION_WITHOUT_CALL_MODALITY:{name:"JoinConversationWithoutCallModality",controller:1},LEAVE_CONVERSATION:{name:"LeaveConversation",controller:1},DELETE_CONVERSATION:{name:"DeleteConversation",controller:1},START_CALL:{name:"StartCall",controller:1},PLACE_NUDGE_CALL:{name:"PlaceNudgeCall",controller:5},UPDATE_CONVERSATION_LINKS:{name:"UpdateConversationLinks",controller:1},SEND_CONVERSATION_KEEP_ALIVE:{name:"SendConversationKeepAlive",controller:1},SEND_CALL_ATTACH:{name:"SendCallAttach",controller:0},SEND_CALL_PROGRESS:{name:"SendCallProgress",controller:0},SEND_KEEP_ALIVE:{name:"SendKeepAlive",controller:0},ADD_CONTENT_SHARING_MODALITY:{name:"AddContentSharingModality",controller:1},DELETE_CONTENT_SHARING:{name:"DeleteContentSharing",controller:3},TAKE_CONTROL_CONTENT_SHARING:{name:"TakeControlContentSharing",controller:3},UPDATE_SESSION_STATE_CONTENT_SHARING:{name:"UpdateSessionStateContentSharing",controller:3},JOIN_CONTENT_SHARING:{name:"JoinContentSharing",controller:3},UPDATE_PARTICIPANT_STATE_CONTENT_SHARING:{name:"UpdateParticipantStateContentSharing",controller:3},UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS:{name:"UpdateContentSharingNotificationLinks",controller:3},MUTE_ALL:{name:"MuteAll",controller:1},MUTE_ALL_SYNC:{name:"MuteAllSync",controller:1},MUTE_SPECIFIED:{name:"MuteSpecified",controller:1},MUTE_SPECIFIED_SYNC:{name:"MuteSpecifiedSync",controller:1},MUTE_MYSELF:{name:"MuteMyself",controller:1},UNMUTE:{name:"Unmute",controller:1},UNMUTE_SYNC:{name:"UnmuteMyselfSync",controller:1},SEND_CONTROL_VIDEO_STREAMING:{name:"SendControlVideoStreaming",controller:0},SEND_APPLY_CHANNEL_PARAMETERS:{name:"SendApplyChannelParameters",controller:0},APPROVE_UNMUTE:{name:"ApproveUnmute",controller:5},REJECT_UNMUTE:{name:"RejectUnmute",controller:5},SEND_CALL_REDIRECT_REQUEST:{name:"SendCallRedirectRequest",controller:0},SEND_TRANSFER_REQUEST:{name:"SendTransferRequest",controller:0},SEND_PARK_REQUEST:{name:"SendParkRequest",controller:0},SEND_SHARED_LINE_PARK_REQUEST:{name:"SharedLinePark",controller:0},SEND_SERVER_HOLD_REQUEST:{name:"ServerHoldRequest",controller:0},PARK_REQUEST:{name:"ParkRequest",controller:0},SEND_UNPARK_REQUEST:{name:"UnparkRequest",controller:0},TRANSFER_ACCEPTANCE:{name:"TransferAcceptance",controller:0},TRANSFER_COMPLETION:{name:"TransferCompletion",controller:0},TRANSFER_COMPLETION_FAILED:{name:"TransferCompletionFailed",controller:0},UPDATE_ENDPOINT_STATE:{name:"UpdateEndpointState",controller:1},DISABLE_PREHEAT:{name:"DisablePreheat",controller:5},REQUEST_NEW_OFFER:{name:"RequestNewOffer",controller:0},UPDATE_ENDPOINT_METADATA:{name:"UpdateEndpointMetadata",controller:1},UPDATE_MEETING_ROLE_ATTENDEE:{name:"UpdateMeetingRoleToAttendee",controller:1},UPDATE_MEETING_ROLE_PRESENTER:{name:"UpdateMeetingRoleToPresenter",controller:1},UPDATE_MEETING_ROLE_ORGANIZER:{name:"UpdateMeetingRoleToOrganizer",controller:1},ADD_PARTICIPANT_WITH_PICKUP_CODE:{name:"AddParticipantWithPickupCode",controller:1},PUBLISH_STATE:{name:"PublishState",controller:1},REMOVE_STATE:{name:"RemoveState",controller:1},UPDATE_MEETING_SETTINGS:{name:"UpdateMeetingSettings",controller:1},ADD_PARTICIPANTS_AND_MODALITY:{name:"AddParticipantsAndModality",controller:1},ADD_BROADCAST_MODALITY:{name:"AddBroadcastModality",controller:1},ADD_MODALITY:{name:"AddModality",controller:1},SEARCH_PARTICIPANTS:{name:"SearchParticipants",controller:1},GET_ALL_PARTICIPANTS:{name:"GetAllParticipants",controller:1},UPDATE_MEETING_LIVE_STATE:{name:"UpdateMeetingLiveState",controller:1},UPDATE_MEETING_GROUPS:{name:"UpdateMeetingGroups",controller:1},SET_MEETING_LAYOUT:{name:"SetMeetingLayout",controller:1},UPDATE_PARTICIPANT_INTERPRETATION_STATE:{name:"UpdateParticipantInterpretationState",controller:1},JOIN_MEETING_GROUP:{name:"JoinMeetingGroup",controller:1},LEAVE_MEETING_GROUP:{name:"LeaveMeetingGroup",controller:1},SEND_PROXIED_MESSAGE:{name:"SendProxiedMessage",controller:1},UPDATE_PARTICIPANTS_PROPERTIES:{name:"UpdateParticipantsProperties",controller:1},UPDATE_MEDIA_DESCRIPTIONS:{name:"UpdateMediaDescriptions",controller:0},UPDATE_MEETING_STATES:{name:"UpdateMeetingStates",controller:1},UPDATE_MONITOR_SESSION:{name:"UpdateMonitorSession",controller:0}},un={EVENT_SOURCE:{TROUTER:"Trouter",BROKER:"Broker",UDP:"UDP",LOCAL:"Local"},SOURCE:{NGC_SOURCE:"SkypeConcore"},EVENT_TYPE:{CONVERSATION_CALL_MODALITY:"skypecosi_concore_web_csa_conversation_callmodality",CONVERSATION_CONTENT_SHARING:"skypecosi_concore_web_csa_conversation_contentsharing",CONVERSATION_HTTP_REQUEST:"skypecosi_concore_web_csa_conversation_httprequest",CONVERSATION_TOKEN:"skypecosi_concore_web_csa_conversation_token"},EXTENSIONS:{DATA_VERSION:"DataVersion",DIRECTION:"Direction",CONTENT_SHARING_DIRECTION:"ContentSharingDirection",CONNECTED_DURATION_IN_MS:"ConnectedDurationInMsecs",PREHEATED_CALL_SETUP_DURATION_IN_S:"PreheatedCallSetupDurationInSeconds",CALL_CANCELATION_DURATION_IN_S:"CallCancelationDurationInSeconds",IS_PREHEATED:"IsPreheated",TIME_TO_RING_IN_MS:"TimeToRingInMsecs",CALL_TERMINATING_END:"CallTerminatingEnd",NETWORK_REQUESTS_PENDING:"NetworkRequestsPending",NETWORK_REQUESTS_COMPLETED:"NetworkRequestsCompleted",LOCAL_OPERATIONS_PERFORMED:"LocalOperationsPerformed",TROUTER_WAIT_OPERATIONS:"TrouterWaitOperations",CALL_START_TIME:"CallStartTime",CALL_END_TIME:"CallEndTime",IS_GROUP_CALL:"IsGroupCall",IS_HOSTLESS_CALL:"IsHostLessCall",IS_CAST_CALL:"IsCastCall",IS_HUDDLE_GROUP_CALL:"IsHuddleGroupCall",IS_MEETUP_CALL:"IsMeetupCall",IS_ON_BEHALF_OF_CALL:"IsOnBehalfOfCall",IS_SDP_IN_CALL_NOTIFICATION:"SdpInCallNotification",CALL_END_CODE:"Code",CALL_END_SUB_CODE:"SubCode",CALL_PHRASE:"Phrase",CALL_END_RESULT_CATEGORIES:"ResultCategories",CALL_END_CAUSE_ID:"CauseId",CONFLICTING_CALL_ID:"ConflictingCallId",CONTENT_SHARING_END_CODE:"ContentSharingEndReasonServiceCode",CONTENT_SHARING_END_SUB_CODE:"ContentSharingEndReasonServiceSubCode",CONVERSATION_SERVICE_URL:"ConversationServiceUrl",CONTENT_SHARING_SERVICE_URL:"ContentSharingServiceUrl",MEETING_INFO:"MeetingInfo",JOINED_FROM:"JoinedFrom",RESULT_VALUE:"ResultValue",RESULT_DETAIL:"ResultDetail",RESULT_CAUSE_ID:"ResultCauseId",RESULT_CODE:"ResultCode",LOCAL_OFFER_ANSWER_GENERATION_TIMESTAMPS:"LocalOfferAnswerGenerationTimestamps",SELF_PARTICIPANT_ROLE:"SelfParticipantRole",SCENARIO:"Scenario",CALLER_TYPE:"Caller_Type",CALLEE_TYPE:"Callee_Type",CALL_TYPE:"Call_Type",TEST_CONTEXT_ID:"Test_Context_Id",OUTGOING_MODALITIES:"Outgoing_Modalities",INCOMING_MODALITIES:"Incoming_Modalities",OFFERED_MODALITIES:"CallOfferredModalities",ANSWERED_MODALITIES:"CallAnsweredModalities",VBSS_OPERATIONS:"VBSS_Operations",CHANGING_CORRELATION_ID_NEW_ID:"ChangingCorrelationId_NewId",CHANGING_CORRELATION_ID_OLD_ID:"ChangingCorrelationId_OldId",MESSAGING_CHANNEL:"MessagingChannel",EVENT_TIMESTAMP_BAG:"EventTimestampBag",ROSTER_UPDATES_BAG:"RosterUpdatesBag",NETWORK_REQUESTS_BAG:"NetworkRequestBag",CLIENT_INFORMATION:"ClientInformation",ECS_ETAG:"EcsEtag",APPLICATION_TYPE:"ApplicationType",RING:"Ring",TENANT_ID:"TenantId",USER_HEX_CID:"UserHexCID",ACS_RESOURCE_ID:"AcsResourceId",REGION:"Region",PARTITION:"Partition",CALL_END_CLIENT_SUB_CODE:"CallEventCallEndClientSubCode",CALL_END_CLIENT_PHRASE:"CallEventCallEndClientPhrase",MEETING_CODE:"MeetingCode",MEETING_URL:"MeetingJoinUrl",BROADCAST_MEETING_ROLE:"BroadcastMeetingRole",MEETING_ROLE:"MeetingRole",ADVANCED_MEETING_ROLE:"AdvancedMeetingRole",MEETING_ROLES:"MeetingRoles",PARTICIPANT_TYPE:"ParticipantType",DISPLAY_NAME:"DisplayName",AUDIO_ONLY_WATERMARK:"ClientSupportsAudioOnlyWatermark",CLIENT_SUPPORT_WATERMARK:"ClientSupportsWatermark",TARGET_APPLICATION_TYPE:"TargetApplicationType",IS_REINVITELESS:"IsReinviteless",CLIENT_TYPE:"ClientType",CLIENT_SUPPORTS_PREVENT_SCREEN_CAPTURE:"ClientSupportsPreventScreenCapture"},MESSAGING_CHANNEL:{TROUTER:"Trouter",BROKER:"Broker"},SIGNALING_CONFIG:"JsCsaConfig",SIGNALING_CONFIG_FLAGS:{BROKER_OUTGOING_ENABLED:"BrokerOutgoingEnabled",BROKER_INCOMING_ENABLED:"BrokerIncomingEnabled",BROKER_REQUEST_BATCHING_ENABLED:"BrokerRequestBatchingEnabled",BROKER_EXCLUSIVELY_ENABLED:"BrokerExclusivelyEnabled",SUPPORTS_COMPRESSED_PAYLOAD:"SupportsCompressedPayload",SYNC_TROUTER_RESPONSE:"SyncTrouterResponse",SERVER_MUTE_UNMUTE:"serverMuteUnmute",HANDLE_OFFER_FROM_NOTIFICATION:"handleMediaOfferFromPushNotification",HANDLE_NEW_OFFER_REQUEST:"handleNewOfferRequest",SEND_PROGRESS_FROM_CC:"sendProgressFromCC",INTERNAL_HTTP_DISPATCHER:"internalHttpDispatcher",ENABLE_TOKEN_CACHE:"enableTokenCache",ENABLE_TOKEN_PREFETCH:"enableTokenPrefetch",REQUEST_HEDGING:"requestHedging",SUPPORT_MEDIA_RETARGET_WHILE_INCOMING_RENEGOTIATION:"supportMediaRetargetWhileIncomingRenegotiation",ENABLE_ERROR_CODE_IMPROVEMENTS_FOR_NETWORK_FAILURES:"enableErrorCodeImprovementsForNetworkFailures",ENABLE_CALL_ESTABLISHMENT_TIMEOUTS_FOR_START_OR_JOIN_CALL:"enableCallEstablishmentTimeoutsForStartJoinCall",ENABLE_TOKEN_CACHE_FOR_GENERIC_TOKEN_API:"enableTokenCacheForGenericTokenAPI",ENABLE_LONG_OUTGOING_1TO1_SETUP:"enableLongOutgoing1To1SetupTimeoutForWeb"},CONTEXT_ID:{CORRELATION_ID:"CorrelationId",SHARED_CORRELATION_ID:"SharedCorrelationId",SIGNALING_SESSION_ID:"SignalingSessionId",GROUP_ID:"GroupId",THREAD_ID:"ThreadId",TEAMS_MESSAGEID:"TeamsMessageId",TEAMS_MEETINGINFO:"TeamsMeetingInfo",ENDPOINT_ID:"EndpointId",PARTICIPANT_ID:"ParticipantId",DATA_VERSION:"DataVersion",CONTENT_SHARING_ID:"ContentSharingSessionId",CONTENT_SHARING_CORRELATION_ID:"ContentSharingCorrelationId"},CALL_TERMINATING_END:{LOCAL:"Local",REMOTE:"Remote"},RESULT_VALUE:{SUCCESS:"Success",FAILURE:"Failure"},DIRECTION:{INCOMING:"Incoming",OUTGOING:"Outgoing"},ROLE:{CALLER:"caller",CALLEE:"callee",JOIN:"join",JOIN_FOR_ROSTER_ONLY:"joinForRosterOnly",PREHEAT:"preheat"},VBSS_OPERATION:{START:"Start",STOP:"Stop",REJECTED:"Rejected",REMOTE_START:"RemoteStart",TIMEOUT:"Timeout",CALL_END:"CallEnd"},LOCAL_OFFER_ANSWER_OPERATIONS:{INITIAL_OFFER_GENERATION_STARTED:"InitialOfferGenerationStarted",INITIAL_OFFER_GENERATION_ENDED:"InitialOfferGenerationEnded",FINAL_ANSWER_PROCESSING_STARTED:"FinalAnswerProcessingStarted",FINAL_ANSWER_PROCESSING_ENDED:"FinalAnswerProcessingEnded",PROVISIONAL_ANSWER_PROCESSING_STARTED:"ProvisonalAnswerProcessingStarted",PROVISIONAL_ANSWER_PROCESSING_ENDED:"ProvisonalAnswerProcessingEnded",NEGOTIATION_COMPLETED:"NegotiationCompleted",INITIAL_OFFER_PROCESSING_STARTED:"InitialOfferProcessingStarted",INITIAL_OFFER_PROCESSING_ENDED:"InitialOfferProcessingEnded",FINAL_ANSWER_GENERATION_STARTED:"FinalAnswerGenerationStarted",FINAL_ANSWER_GENERATION_ENDED:"FinalAnswerGenerationEnded",PROVISIONAL_ANSWER_GENERATION_STARTED:"ProvisionalAnswerGenerationStarted",PROVISIONAL_ANSWER_GENERATION_ENDED:"ProvisionalAnswerGenerationEnded",RENEGOTIATION_OFFER_GENERATION_STARTED:"RenegotiationOfferGenerationStarted",RENEGOTIATION_OFFER_GENERATION_ENDED:"RenegotiationOfferGenerationEnded",RENEGOTIATION_ANSWER_PROCESSING_STARTED:"RenegotiationAnswerProcessingStarted",RENEGOTIATION_ANSWER_PROCESSING_ENDED:"RenegotiationAnswerProcessingEnded",RENEGOTIATION_OFFER_PROCESSING_STARTED:"RenegotiationOfferProcessingStarted",RENEGOTIATION_OFFER_PROCESSING_ENDED:"RenegotiationOfferProcessingEnded",RENEGOTIATION_ANSWER_GENERATION_STARTED:"RenegotiationAnswerGenerationStarted",RENEGOTIATION_ANSWER_GENERATION_ENDED:"RenegotiationAnswerGenerationEnded"},TROUTER_WAIT_OPERATION:{STARTED:"Started",ENDED:"Ended",FAILED:"Failed"},TOKEN_TELEMETRY_EVENT:{TOKEN_TELEMETRY:"TokenTelemetry"}};function setDefaultsForSignalingConfig(g){const f=!0,S="enabled",v=!1,C=!1,_=!0,T=!0,I=!0,b=!1,A=!1,P=!0,R=!0,M=!0,w=!0,O=!0,D=!1,N=!1,k=!1,L=!1,F=!1,x=!0,U=!0,V=!0,B=3,H=4e3,$=!1,j=!1,G=!1,q=!1,W=!1,z=!0,K={conversationKeepAliveTimeoutSec:2700,promotionUnmuteTimeoutSec:1e4},J=!1,Y=!1,Q=!1,X=!1,Z=3600,ee=86400,te=30,ie=!1,ne=!0,re=!0,se=60,ae="https://calling.teams.microsoft.com",oe=!0,le=!1,ce=!1,de=!1,he=!1,ue=!1,ge=!1,pe=0,me=0,fe=!1,Se=!1,ve=!1,Ce=!1,ye=!0,Ee=!1,_e=!1,Te=!1,Ie=!1,be=!1;g.cloudScreenSharingFlag="disabled"===g.cloudScreenSharingFlag?g.cloudScreenSharingFlag:S,g.isWebRtcEnabled="undefined"==typeof RTCIceGatherer,g.shouldServiceSendNGCUpgradeMessages=setDefault(g.shouldServiceSendNGCUpgradeMessages,_),g.isGVCOutgoingEnabled=setDefault(g.isGVCOutgoingEnabled,f),g.supportsCompressedServicePayload=setDefault(g.supportsCompressedServicePayload,T),g.supportsSynchronousTrouterResponse=setDefault(g.supportsSynchronousTrouterResponse,I),g.supportsHostlessGroupCalls=setDefault(g.supportsHostlessGroupCalls,P),g.doHostlessCalling=setDefault(g.doHostlessCalling,v),g.brokerExclusively=setDefault(g.brokerExclusively,D),g.brokerEnabledOutgoing=setDefault(g.brokerEnabledOutgoing,M),g.brokerEnabledIncoming=setDefault(g.brokerEnabledIncoming,w),g.brokerRequestBatching=setDefault(g.brokerRequestBatching,O),g.handleMediaOfferFromPushNotification=setDefault(g.handleMediaOfferFromPushNotification,x),g.handleNewOfferRequest=setDefault(g.handleNewOfferRequest,N),g.autoJoinOnConflict=setDefault(g.autoJoinOnConflict,R),g.endConflictedCall=setDefault(g.endConflictedCall,b),g.autoResolveConflictedCall=setDefault(g.autoResolveConflictedCall,A),g.shouldServiceSendCallEventMessages=setDefault(g.shouldServiceSendCallEventMessages,C),g.forceTrouterReconnectOnNetworkOnline=setDefault(g.forceTrouterReconnectOnNetworkOnline,U),g.attemptHttpRequestWithCachedSkypetoken=setDefault(g.attemptHttpRequestWithCachedSkypetoken,V),g.useInternalHttpDispatcher=setDefault(g.useInternalHttpDispatcher,k),g.enableTokenCache=setDefault(g.enableTokenCache,L),g.enableTokenPrefetch=setDefault(g.enableTokenPrefetch,F),g.hedgeDelayMs=setDefault(g.hedgeDelayMs,H),g.hedgeMaxParallelAttempts=setDefault(g.hedgeMaxParallelAttempts,B),g.useInternalHttpDispatcher&&(g.httpRequestDispatcher=new $e(g.logger)),g.enableQuickSendAcceptanceAck=setDefault(g.enableQuickSendAcceptanceAck,$),g.supportMediaRetargetWhileIncomingRenegotiation=setDefault(g.supportMediaRetargetWhileIncomingRenegotiation,j),g.callingServiceSupportsAADTokens=setDefault(g.callingServiceSupportsAADTokens,J),g.callingServiceSupportsCAETokens=setDefault(g.callingServiceSupportsCAETokens,Y),g.aadTokenExpirationTimeInSeconds=setDefault(g.aadTokenExpirationTimeInSeconds,Z),g.caeTokenExpirationTimeInSeconds=setDefault(g.caeTokenExpirationTimeInSeconds,ee),g.disableTokenMigrationHeader=setDefault(g.disableTokenMigrationHeader,Q),g.enablePublishTokenTelemetry=setDefault(g.enablePublishTokenTelemetry,X),g.forceClearExpiredTokens=setDefault(g.forceClearExpiredTokens,ie),g.enableRefreshToken=setDefault(g.enableRefreshToken,ne),g.refreshTimeBeforeTokenTimeoutInSeconds=setDefault(g.refreshTimeBeforeTokenTimeoutInSeconds,te),g.enableCallEstablishmentTimeoutsForStartJoinCall=setDefault(g.enableCallEstablishmentTimeoutsForStartJoinCall,G),g.csaTimeoutConfiguration=mergeObjects(g.csaTimeoutConfiguration,K),g.reportPreviousErrorsForTimeout=setDefault(g.reportPreviousErrorsForTimeout,de),g.callingTokenLogicalUrl=setDefault(g.callingTokenLogicalUrl,ae),g.enableAsyncDisablePreheat=setDefault(g.enableAsyncDisablePreheat,he),g.forceLowercaseHttpHeaders=setDefault(g.forceLowercaseHttpHeaders,ue),g.enableResolveScreenSharingWhenNegotiationComplete=setDefault(g.enableResolveScreenSharingWhenNegotiationComplete,ge),g.maxReinvitelessMediaForVideoForWeb=setDefault(g.maxReinvitelessMediaForVideoForWeb,pe),g.maxReinvitelessMediaForVBSSForWeb=setDefault(g.maxReinvitelessMediaForVBSSForWeb,me),g.enableRefreshTokenRetry=setDefault(g.enableRefreshTokenRetry,re),g.enableRefreshTokenRetryInSeconds=setDefault(g.enableRefreshTokenRetryInSeconds,se),g.enableConversationTypeUpdateOnCallEnd=setDefault(g.enableConversationTypeUpdateOnCallEnd,W),g.supportMissingTokenTypesInResponse=setDefault(g.supportMissingTokenTypesInResponse,oe),g.useSkypeTokenWhenNoAuthenticateHeader=setDefault(g.useSkypeTokenWhenNoAuthenticateHeader,le),g.enableAutoPromotion=setDefault(g.enableAutoPromotion,fe),g.enableBatchedSendMessageStatus=setDefault(g.enableBatchedSendMessageStatus,ve),g.enableBatchedReceiveMessage=setDefault(g.enableBatchedReceiveMessage,Se),g.enableAddParticipantEnhancements=setDefault(g.enableAddParticipantEnhancements,Ce),g.enableTokenCacheForGenericTokenAPI=setDefault(g.enableTokenCacheForGenericTokenAPI,ce),g.disableRealTimeModeFromRoster=setDefault(g.disableRealTimeModeFromRoster,ye),g.enableLongOutgoing1To1SetupTimeoutForWeb=setDefault(g.enableLongOutgoing1To1SetupTimeoutForWeb,q),g.checkAttendeeRoleInCreateContentSharing=setDefault(g.checkAttendeeRoleInCreateContentSharing,z),g.enableSpecificErrorCodesForCallEnd=setDefault(g.enableSpecificErrorCodesForCallEnd,Ee),g.enableSplitConversationEndUrl=setDefault(g.enableSplitConversationEndUrl,_e),g.enableFetchRequestWithKeepAlive=setDefault(g.enableFetchRequestWithKeepAlive,Te),g.enableFetchApi=setDefault(g.enableFetchApi,Ie),g.enableFetchApiForBeacon=setDefault(g.enableFetchApiForBeacon,be)}function setDefault(g,f){return null==g?f:g}function mergeObjects(g,f){return(f||g)&&{...f,...g}}var gn=class{constructor(){this.skypeTokenContext={},this.aadTokenContext={},this.caeTokenContext={}}getTokenContext(g){return 4===g?this.aadTokenContext:8===g?this.caeTokenContext:1===g?this.skypeTokenContext:void 0}getTokenExpiry(g,f){return 4===g?this.aadTokenContext?.expiryTime:8===g?this.caeTokenContext?.expiryTime:1===g?this.skypeTokenContext?.expiryTime:(f?.info("[getTokenExpiry] unrecognized token type, return Number.MAX_VALUE"),Number.MAX_VALUE)}getToken(g,f,S,v){return 8&g&&this.caeTokenContext?.token&&this.caeTokenContext.token!==v?{token:this.caeTokenContext.token,tokenType:8}:4&g&&this.aadTokenContext?.token&&this.aadTokenContext.token!==v?{token:this.aadTokenContext.token,tokenType:4}:1&g&&this.skypeTokenContext?.token&&this.skypeTokenContext.token!==v?{token:this.skypeTokenContext.token,tokenType:1}:(S?.info(`[getToken] no cached token found of token type: ${g}`),null)}setToken(g,f,S,v){switch(g){case 4:this.aadTokenContext.factorsJson=S,this.aadTokenContext.tokenType=g,this.aadTokenContext.token=f,this.aadTokenContext.expiryTime=v;break;case 1:this.skypeTokenContext.factorsJson=S,this.skypeTokenContext.tokenType=g,this.skypeTokenContext.token=f,this.skypeTokenContext.expiryTime=v;break;case 8:this.caeTokenContext.factorsJson=S,this.caeTokenContext.tokenType=g,this.caeTokenContext.token=f,this.caeTokenContext.expiryTime=v;break;default:throw new Error(`Invalid tokenType ${g}`)}}clearExpiredTokens(g){const f=Math.round(Date.now()/1e3);this.caeTokenContext?.expiryTime<=f&&(this.resetToken(8),g?.info("[cacheTokenManager] reset expired cae token")),this.aadTokenContext?.expiryTime<=f&&(this.resetToken(4),g?.info("[cacheTokenManager] reset expired aad token")),this.skypeTokenContext?.expiryTime<=f&&(this.resetToken(1),g?.info("[cacheTokenManager] reset expired skype token"))}resetToken(g){8===g?this.caeTokenContext={}:4===g?this.aadTokenContext={}:1===g&&(this.skypeTokenContext={})}},pn=class{constructor(g){this.timers={},this.startTimer=(g,f,S,v)=>{this.logger.info(`startTimer called for :  ${g} with timeoutInSeconds : ${S}s`);const C=window.setTimeout(f,1e3*S),_=v?`${g}${v}`:g;this.timers[_]=C},this.stopTimer=(g,f)=>{this.logger.info(`stopTimer called for : ${g}`);const S=f?`${g}${f}`:g;this.timers.hasOwnProperty(S)&&(clearTimeout(this.timers[S]),delete this.timers[S])},this.dispose=()=>{this.logger.info("timeoutManager :: dispose"),Object.keys(this.timers).forEach((g=>{this.stopTimer(g)}))},this.logger=g}},mn=3600,fn=class{constructor(g,f,S,v){this.tokenProvider=f,this.tokenCachingEnabled=!1,this.enableTokenCacheForGenericTokenAPI=!1,this.cachedToken="",this.lastTokenType=1,this.lastToken="",this.clientSupportsGenericTokenAPI=!1,this.stopTimerFlag=!1,this.tokensPromiseMap={},this.logger=g.createChild("TokenManager"),S&&this.updateTokenSettings(S),this.cacheTimers=new pn(g),this.cacheTokenManager=new gn,this.telemetryManager=v,this.nextRefreshTimePointInSeconds=Number.MAX_VALUE}deletePromisesByTriggeredByRefresh(g,f){if(this.tokensPromiseMap[g]){const S=this.tokensPromiseMap[g];for(let v=S.length-1;v>=0;v--)S[v]?.tokenRequestOptions.triggeredByRefresh===f&&this.tokensPromiseMap[g].splice(v,1)}}startTokenRefreshTimer(g){const f="startTokenRefreshTimer";if(!this.enableRefreshToken)return void this.logger.info("[startTokenRefreshTimer] token refresh is disabled");if(this.stopTimerFlag)return this.logger.info("[startTokenRefreshTimer] stopTimerFlag=true so cancel timer"),void this.cacheTimers.dispose();this.logger.info(`[startTokenRefreshTimer] starting token refresh timer timeToStartInMilliseconds=${g}`);const S=epochTimeInSecRoundedDown(),v=millieSecondsToSeconds(g),C=S+v;this.nextRefreshTimePointInSeconds===Number.MAX_VALUE||this.nextRefreshTimePointInSeconds<S||C<this.nextRefreshTimePointInSeconds?(this.logger.info("[startTokenRefreshTimer] cancelling current refresh timer to create new one with shorter time"),this.cacheTimers.stopTimer(f),this.nextRefreshTimePointInSeconds=C,this.logger.info(`[startTokenRefreshTimer] start new timer with timeout=${v} at time=${S}`),this.cacheTimers.startTimer(f,(()=>{this.nextRefreshTimePointInSeconds=Number.MAX_VALUE,this.refreshToken()}),v)):this.logger.info("[startTokenRefreshTimer] no need to set a new refresh timer")}async refreshTokenWithContext(g){const f={triggeredByRefresh:!0},S=newGuid(),v={causeId:S},C=Date.now();let _,T,I,b=2;this.logger.info(`[${S}][refreshTokenWithContext] refreshing token tokenType=${g.tokenType} factorsJson=${g.factorsJson}`);let A=null;try{const f=this.onTokenRequired({factorsJson:g.factorsJson,tokenType:g.tokenType,requestMetadataJson:v,invalidToken:void 0,isUnauthorized:void 0,triggeredByRefresh:!0}),C=await this.timeoutPromiseRace(f,this.enableRefreshTokenRetryInSeconds,"ActiveRefresh Token Timeout");_=Date.now(),I=C?.causeId,A=C?.tokenType,this.lastTokenType=A,this.lastToken=C.token,b=1,this.logger.info(`[${S}][refreshTokenWithContext] refresh token success for factorsJson ${g.factorsJson} and tokenType ${g.tokenType}`)}catch(f){T=f,I=T?.causeId,f?.timeOut?(this.logger.info(`[${S}][refreshTokenWithContext] refresh token timeout, UI did not respond with token in time ${getPrintableObject(f)}`),b=5):(this.logger.info(`[${S}][refreshTokenWithContext] failed to refresh token, UI did not respond with token ${getPrintableObject(f)}`),b=2),_=Date.now(),this.deletePromisesByTriggeredByRefresh(g.factorsJson,!0)}finally{f&&(f.requestCauseId=S,f.responseCauseId=I,f.supportTokenApi=this.clientSupportsGenericTokenAPI,f.requestTokenFactors=g.factorsJson,f.tokenRequestTime=C,f.tokenResponseTime=_,f.tokenRequestStatus=b,f.requestTokenType=g.tokenType,f.foundInCache=!1,f.responseTokenType=A,f.errorCode=T?.errorCode,f.errorSubCode=T?.errorSubCode,this.sendTokenTelemetry(f))}}refreshToken(){if(!this.clientSupportsGenericTokenAPI)return void this.logger.info("[refreshToken] refresh token is not supported due to new Token Api is not enabled");if(!this.enableTokenCacheForGenericTokenAPI)return void this.logger.info("[refreshToken] refresh token is not supported due to caching being disabled");const g=this.cacheTokenManager.getTokenContext(4),f=this.cacheTokenManager.getTokenContext(8),S=this.cacheTokenManager.getTokenContext(1);if(!g&&!f&&!S)return void this.logger.info("[refreshToken] no cached tokens available to refresh");const v=epochTimeInSecRoundedDown()+this.refreshTimeBeforeTokenTimeoutInSeconds;let C=Number.MAX_VALUE,_=!1;if(g)if(g.expiryTime>v){const f=g?.expiryTime-v;f<C&&(C=f)}else g.expiryTime<=v&&(this.refreshTokenWithContext(g),_=!0);if(f)if(f.expiryTime>v){const g=f?.expiryTime-v;g<C&&(C=g)}else f.expiryTime<=v&&(this.refreshTokenWithContext(f),_=!0);if(S)if(S.expiryTime>v){const g=S?.expiryTime-v;g<C&&(C=g)}else S.expiryTime<=v&&(this.refreshTokenWithContext(S),_=!0);_&&this.enableRefreshTokenRetry&&this.enableRefreshTokenRetryInSeconds>0&&this.enableRefreshTokenRetryInSeconds<C&&(C=this.enableRefreshTokenRetryInSeconds),C>=0&&C!==Number.MAX_VALUE&&this.startTokenRefreshTimer(secondsToMillieSeconds(C))}async getTokenWithTokenType(g,f=!1,S,v){this.logger.info(`[${g}][getTokenWithTokenType] call with factorJson=${S?.factorsJson} and request tokenType ${S?.tokenType}`);const{factorsJson:C,requestMetadataJson:_,invalidToken:T,isUnauthorized:I}=S||{},b=Date.now(),A=S?.tokenType;let P,R,M,w=2,O=null;this.clearExpiredTokens(),this.startTokenRefreshTimer(1);try{if(f)this.invalidateCachedTokenWithTokenType(A,T,C);else if(this.enableTokenCacheForGenericTokenAPI){const f=this.cacheTokenManager.getToken(A,C,this.logger,T);if(f?.token)return this.logger.info(`[${g}][getTokenWithTokenType] returning cached token for factorsJson ${C} and request tokenType ${A}, response tokenType ${f.tokenType}`),w=3,P=Date.now(),O=f.tokenType,this.lastToken=f.token,this.lastTokenType=O,f}this.logger.info(`[${g}][getTokenWithTokenType] fetching new token for factorsJson ${C} and tokenType ${A}`);const S=_||{};S.causeId=g;const v=this.onTokenRequired({factorsJson:C,tokenType:A,requestMetadataJson:S,invalidToken:T,isUnauthorized:I,triggeredByRefresh:!1}),b=await this.timeoutPromiseRace(v,an.TIMEOUT_VALUES_IN_SECONDS.TOKEN_REQUIRED_TIMEOUT,"Token not received from UI in time");return P=Date.now(),M=b?.causeId,O=b?.tokenType,this.lastToken=b?.token,this.lastTokenType=O,w=1,this.logger.info(`[${g}][getTokenWithTokenType] fetching new token success for factorsJson ${C} and tokenType ${A}`),b}catch(f){throw this.logger.info(`[${g}][getTokenWithTokenType] failed to fetch token ${getPrintableObject(f)}`),R=f,M=R?.causeId,R.timeOut&&(w=4),this.deletePromisesByTriggeredByRefresh(C,!1),f}finally{const f=!v?.tokenTelemetryData,C=f?{}:v?.tokenTelemetryData;C&&(C.requestCauseId=g,C.responseCauseId=M,C.supportTokenApi=this.clientSupportsGenericTokenAPI,C.requestTokenFactors=S?.factorsJson,C.tokenRequestTime=b,C.tokenResponseTime=P,C.tokenRequestStatus=w,C.requestTokenType=S?.tokenType,C.foundInCache=3===w,C.responseTokenType=O,C.timeToResponse=P?P-b:P,C.errorCode=R?.errorCode,C.errorSubCode=R?.errorSubCode),(!v||f&&!v.signalingSession)&&(this.logger?.info("[getTokenWithTokenType] TokenContext is not provided, sending token telemetry to Token table"),this.sendTokenTelemetry(C))}}async onTokenRequired(g){const{factorsJson:f,tokenType:S,requestMetadataJson:v,invalidToken:C,isUnauthorized:_,triggeredByRefresh:T}=g;if(this.logger.info(`[onTokenRequired] factorsJson=${f} tokenType=${S}`),!S)return this.logger.info(`[onTokenRequired] factorsJson=${f} with no token type`),Promise.reject({errorCode:an.HTTP_STATUS_CODES.UNAUTHORIZED,errorSubCode:0,causeId:v?.causeId});if(this.tokensPromiseMap[f]&&!T)for(const g of this.tokensPromiseMap[f])if(g.tokenRequestOptions.tokenType===S)return this.logger.info(`[onTokenRequired] factorsJson=${f} and tokenType ${S} has pending request`),g.defered.promise;this.tokensPromiseMap[f]||(this.tokensPromiseMap[f]=[]);const I=new dt;return this.tokensPromiseMap[f].push({tokenRequestOptions:g,defered:I}),this.tokenCallback({factorsJson:f,tokenType:S,requestMetadataJson:v,invalidToken:C,isUnauthorized:_}),I.promise}setTokenCaching(g,f){this.tokenCachingEnabled!==g&&(this.logger.info(`[authTokenManager]setTokenCaching=${g}`),this.tokenCachingEnabled=g)}setTokenCachingForGenericTokenAPI(g,f){this.enableTokenCacheForGenericTokenAPI!==g&&(this.logger.info(`[authTokenManager]setTokenCachingForGenericTokenAPI=${g}`),this.enableTokenCacheForGenericTokenAPI=g)}calculateTokenExpiry(g,f,S){const{factorsJson:v,tokenType:C}=f;let _=S-epochTimeInSecRoundedDown(),T=_,I=S;if(_&&_>0&&_>this.refreshTimeBeforeTokenTimeoutInSeconds){switch(C){case 4:_>this.aadTokenExpirationTimeInSeconds&&(_=this.aadTokenExpirationTimeInSeconds);break;case 8:_>this.caeTokenExpirationTimeInSeconds&&(_=this.caeTokenExpirationTimeInSeconds);break;default:_>mn&&(_=mn)}T=_-this.refreshTimeBeforeTokenTimeoutInSeconds,I=T+epochTimeInSecRoundedDown()}return this.logger.info(`[${g}][calculateTokenExpiry] calculate expiry to ${I} tokenType=${C} factorsJson=${v}`),I}addToCache(g,f,S,v){this.clearExpiredTokens(),this.cacheTokenManager.setToken(g,f,S,v)}clearExpiredTokens(){this.forceClearExpiredTokens&&this.cacheTokenManager.clearExpiredTokens(this.logger)}async getToken(g,f=!1,S,v){if(this.clientSupportsGenericTokenAPI){this.logger.info(`[${g}][getToken] callingTokenAPI is enabled so using new API to fetch it`);const{token:C}=await this.getTokenWithTokenType(g,f,S,v);return C}const C=Date.now();let _,T,I=2;try{if(f&&this.invalidateCachedToken(g),this.cachedToken&&this.tokenCachingEnabled)return this.logger.info(`[${g}][getToken] returning cached token`),I=3,this.lastTokenType=1,Promise.resolve(this.cachedToken);this.logger.info(`[${g}][getToken] fetching new token`);const S=await this.tokenProvider();return _=Date.now(),S?(this.tokenCachingEnabled&&(this.cachedToken=S),I=1,this.lastToken=S,this.lastTokenType=1,this.logger.info(`[${g}][getToken] fetching new token success`),S):(this.logger.info(`[${g}][getToken] received empty token`),Promise.reject("Received empty token"))}catch(f){throw this.logger.info(`[${g}][getToken] failed to fetch token=${getPrintableObject(f)}`),T=f,this.cachedToken="",f}finally{const f=v?.tokenTelemetryData;f&&(f.requestCauseId=g,f.supportTokenApi=this.clientSupportsGenericTokenAPI,f.requestTokenFactors=S?.factorsJson,f.tokenRequestTime=C,f.tokenResponseTime=_,f.tokenRequestStatus=I,f.requestTokenType=S?.tokenType,f.foundInCache=3===I,f.responseTokenType=this.lastTokenType,f.timeToResponse=_?_-C:_,f.errorCode=T?.errorCode,f.errorSubCode=T?.errorSubCode)}}invalidateCachedToken(g){this.cachedToken&&(this.logger.info(`[${g}][invalidateCachedToken]`),this.cachedToken="")}invalidateCachedTokenWithTokenType(g,f,S){8===g&&this.cacheTokenManager.getToken(8,S,this.logger)?.token===f&&(this.cacheTimers.stopTimer(S,g.toString()),this.cacheTokenManager.resetToken(8)),4===g&&this.cacheTokenManager.getToken(4,S,this.logger)?.token===f&&(this.cacheTimers.stopTimer(S,g.toString()),this.cacheTokenManager.resetToken(4)),1===g&&this.cacheTokenManager.getToken(1,S,this.logger)?.token===f&&(this.cacheTimers.stopTimer(S,g.toString()),this.cacheTokenManager.resetToken(1))}getLastToken(g){return this.logger.info(`[${g}][getLastToken]`),this.lastToken}async timeoutPromiseRace(g,f,S){let v;const C=new Promise(((g,C)=>{v=window.setTimeout((()=>{C({phrase:S,timeOut:!0})}),secondsToMillieSeconds(f))}));return Promise.race([g.then((g=>(clearTimeout(v),g))),C])}getLastTokenType(g){return this.logger.info(`[${g}][getLastTokenType] lastTokenType=${this.lastTokenType}`),this.lastTokenType}updateTokenSettings(g){const{clientSupportsGenericTokenAPI:f,aadTokenExpirationTimeInSeconds:S,caeTokenExpirationTimeInSeconds:v,refreshTimeBeforeTokenTimeoutInSeconds:C,enablePublishTokenTelemetry:_,enableRefreshToken:T,forceClearExpiredTokens:I,enableRefreshTokenRetry:b,enableRefreshTokenRetryInSeconds:A}=g;this.logger.info(`updateTokenSettings ${JSON.stringify(g)}`),this.clientSupportsGenericTokenAPI=f??this.clientSupportsGenericTokenAPI,this.aadTokenExpirationTimeInSeconds=S??this.aadTokenExpirationTimeInSeconds,this.caeTokenExpirationTimeInSeconds=v??this.caeTokenExpirationTimeInSeconds,this.refreshTimeBeforeTokenTimeoutInSeconds=C??this.refreshTimeBeforeTokenTimeoutInSeconds,this.enablePublishTokenTelemetry=_??this.enablePublishTokenTelemetry,this.forceClearExpiredTokens=I??this.forceClearExpiredTokens,this.enableRefreshToken=T??this.enableRefreshToken,this.enableRefreshTokenRetry=b??this.enableRefreshTokenRetry,this.enableRefreshTokenRetryInSeconds=A??this.enableRefreshTokenRetryInSeconds}updateToken(g,f,S,v,C){if(this.logger.info(`[${v}][updateToken] UI replies with a token with factorsJson=${g} updateMetadata=${JSON.stringify(f)} tokenExpirySecSinceEpoch?=${C}`),f.error){this.logger.info(`[${v}][updateToken] UI replies with error ${f.error} for factorsJson ${g}`);for(const S of this.tokensPromiseMap[g])S.tokenRequestOptions.requestMetadataJson.causeId===v&&S.defered.reject({phrase:f.error?.phrase,errorCode:f.error?.code,errorSubCode:f.error?.subCode,causeId:v});return}if(!S){this.logger.info(`[${v}][updateToken] received empty token`);for(const f of this.tokensPromiseMap[g])f.tokenRequestOptions.requestMetadataJson.causeId===v&&f.defered.reject({phrase:"Received empty token",causeId:v});return}if(C>epochTimeInSecRoundedDown()&&this.enableTokenCacheForGenericTokenAPI){this.logger.info(`[${v}][updateToken] caching Token with tokenType=${f.tokenType}`);const _={factorsJson:g,tokenType:f.tokenType,invalidToken:S};this.addToCache(f.tokenType,S,g,this.calculateTokenExpiry(v,_,C))}if(!this.tokensPromiseMap[g]){this.logger.warn(`[updateToken]: UI tries to update token with invalid factorsJson=${g}`);const S={responseCauseId:v,supportTokenApi:this.clientSupportsGenericTokenAPI,requestTokenFactors:g,tokenResponseTime:Date.now(),tokenRequestStatus:6,responseTokenType:f.tokenType};return void this.sendTokenTelemetry(S)}if(this.tokensPromiseMap[g]){const C=this.tokensPromiseMap[g];for(let _=C.length-1;_>=0;_--)(C[_]?.tokenRequestOptions.tokenType&f.tokenType)>0&&(C[_].defered.resolve({token:S,tokenType:f.tokenType,causeId:v}),this.tokensPromiseMap[g].splice(_,1))}if(this.logger.info(`[${v}][updateToken] resolved and upateToken with factorsJson=${g} tokenType=${f.tokenType}`),0===this.tokensPromiseMap[g].length&&delete this.tokensPromiseMap[g],4!==f.tokenType&&8!==f.tokenType&&1!==f.tokenType)return;if(Object.keys(this.tokensPromiseMap).length>0)for(const C of Object.values(this.tokensPromiseMap))for(let _=C.length-1;_>=0;_--){const T=C[_];T.tokenRequestOptions.factorsJson!==g&&(T.tokenRequestOptions.tokenType&f.tokenType)>0&&!T.tokenRequestOptions.isUnauthorized&&(T.defered.resolve({token:S,tokenType:f.tokenType,causeId:v}),C.splice(_,1))}for(const g of Object.keys(this.tokensPromiseMap))0===this.tokensPromiseMap[g].length&&delete this.tokensPromiseMap[g];const _=C-epochTimeInSecRoundedDown();this.startTokenRefreshTimer(_>=0?secondsToMillieSeconds(_):0)}setTokenRequiredCallBack(g){this.tokenCallback=g}setDisableTimerFlag(g){this.logger.info(`[setDisableTimerFlag] set disableTimerFlag to ${g}`),this.stopTimerFlag=g}sendTokenTelemetry(g){if(!this.enablePublishTokenTelemetry)return;const f={};f[un.TOKEN_TELEMETRY_EVENT.TOKEN_TELEMETRY]=JSON.stringify(g),this.telemetryManager?(this.logger.info("[sendTokenTelemetry] sending token telemetry:",f),this.telemetryManager.sendEvent(un.EVENT_TYPE.CONVERSATION_TOKEN,f)):this.logger.warn("[sendTokenTelemetry] telemetryManager is undefined, cannot send token telemetry")}dispose(){this.cacheTimers&&this.cacheTimers.dispose()}},Sn={build:(g,f,S,v)=>new fn(g,f,S,v)},vn=class{constructor(g){this.piiScrubber=this.getPiiScrubber(g)}scrubParticipantsList(g){const f=[];return Array.isArray(g)&&g.forEach((g=>f.push(this.scrubMriOrOmit(g)))),f}scrubMriOrOmit(g){return"string"==typeof g?this.piiScrubber.mri(g):this.piiScrubber.omit(g)}getPiiScrubber(g){return g&&"function"==typeof g.omit&&"function"==typeof g.mri?g:{omit:()=>"<pii:omit/>",mri:()=>"<pii:mri/>"}}},Cn=__toESM(M);function getMediaLabel(g){switch(g){case 0:return"main-audio";case 1:return"main-video";case 2:return"applicationsharing-video";case 3:return"data"}throw new Error("Invalid media type")}function mapMediaTypeStringToMediaType(g){switch(g){case"audio":return 0;case"video":return 1;case"applicationsharing-video":case"xapplicationsharing-video":return 2;case"data":return 3;default:return}}function hasParticipantLegId(g,f){return g.endpoints?.endpointDetails?.some((g=>g.participantId===f))??!1}function findSelfEndpointDetailUsingParticipantLegId(g,f){return g.endpoints?.endpointDetails.find((g=>g.participantId===f))}function findParticipantUsingParticipantLegId(g,f){return g.participants.find((g=>hasParticipantLegId(g,f)))}function hasStagingGroup(g){return!!g?.meetingGroupDetails?.groups&&Object.keys(g.meetingGroupDetails.groups).some((g=>"stagingGroup"===g))}function getSourceIdForMediaType(g,f){let S=-1;try{if(g.endpoints)e:for(const v of g.endpoints.endpointDetails)if(void 0!==v?.mediaStreams){for(const g of v.mediaStreams)if(mapMediaTypeStringToMediaType(g.type)===f){S=g.sourceId;break e}}else S=Ai}catch(g){return-1}return S}function getSourceId(g,f,S){if(!g?.endpoints)return-1;const v=g.endpoints.endpointDetails.find((g=>g?.participantId===f));if(!v?.mediaStreams)return getSourceIdForMediaType(g,S);const C=v.mediaStreams.find((({type:g})=>mapMediaTypeStringToMediaType(g)===S));return C?C.sourceId:-1}function getParticipantIdForSourceId(g,f,S){try{if(!g.endpoints)return;for(const v of g.endpoints.endpointDetails)if(v?.mediaStreams)for(const g of v.mediaStreams)if(S===g.sourceId&&mapMediaTypeStringToMediaType(g.type)===f)return v.participantId??null;return}catch(g){return}}function isScreenSharerStream(g){return"sendonly"===g.direction&&"applicationsharing-video"===g.label}function getSharingParticipantLeg(g){if(g.endpoints?.endpointDetails)return 1===g.endpoints.endpointDetails.length?g.endpoints.endpointDetails[0].participantId:g.endpoints.endpointDetails.find((g=>g?.mediaStreams?.some(isScreenSharerStream)))?.participantId}function getParticipantLegFromStreamSourceId(g,f){return g.endpoints?.endpointDetails?.find((g=>g.mediaStreams?.find((g=>g.sourceId===f))))}function processTransactionResponse(g){let f={};if(g.stateId)f.result=g.stateId;else if(g.results){const{results:S}=g;1===S.length&&S[0].stateId&&(f.result=S[0].stateId);const v={};g.results.forEach((g=>{const{result:S}=g,C=getParticipantId(g);(void 0===f.code||S.code>f.code)&&(f.code=S.code,f.subCode=S.subCode),v[C]=g})),f.result=JSON.stringify(v)}else g.result&&(f={code:g.result.code,phrase:g.result.phrase,subCode:g.result.subCode,resultCategories:g.result.resultCategories},g.additionalDetail&&(f.result=g.additionalDetail));return f}function getParticipantId(g){return g.participantId||g.participant&&g.participant.id}var yn=class{constructor(g,f){this.broadcastContext=null,this.broadcastControllerUrl="",this.broadcastCallbackUrl="",this.broadcastState=null,this.setContext=(g=null)=>{this.logger.info("BroadcastSession :: set broadcast context",g),this.broadcastContext=g},this.getContext=()=>(this.logger.info("BroadcastSession :: get broadcast context",this.broadcastContext||null),this.broadcastContext||null),this.signalingSession=g,this.signalingSessionCallback=f,this.logger=g.logger.createChild((()=>"[Broadcast]"))}handleBroadcastStateChanged(g){const f=g.body;this.broadcastState=f;const S=extractCauseIdFromMessage(g);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.BROADCAST_STATE_CHANGED,g),this.logger.info(`[${S}] broadcast state changed=${this.broadcastState}`),this.updateBroadcastMetadata(S)}updateBroadcastCallbackUrl(g){const f=get2(this.signalingSession,rn.CONV_BROADCAST_UPDATE);this.broadcastCallbackUrl!==f&&(this.broadcastCallbackUrl=f,this.logger.info(`[${g}] broadcast callback url changed=${this.broadcastCallbackUrl}`),this.updateBroadcastMetadata(g))}handleBroadcastDetailsChanged(g,f){this.signalingSession.telemetryHelper.recordEvent(dn.UPDATE_BROADCAST_DETAILS,{causeId:f}),g.activeModalities&&g.activeModalities.broadcast&&g.activeModalities.broadcast.controller!==this.broadcastControllerUrl&&(this.broadcastControllerUrl=g.activeModalities.broadcast.controller,this.broadcastAdditionalData=g.activeModalities.broadcast,this.logger.info(`[${f}] broadcast controller changed=${this.broadcastControllerUrl}`),this.signalingSessionCallback.onBroadcastMeetingConnected(an.SUCCESS_TRANSACTION_END,f),this.updateBroadcastMetadata(f)),!this.broadcastControllerUrl||g.activeModalities&&g.activeModalities.broadcast||(this.broadcastControllerUrl="",this.broadcastContext=null,this.logger.info(`[${f}] broadcast controller changed=${this.broadcastControllerUrl}`),this.updateBroadcastMetadata(f),this.signalingSessionCallback.onBroadcastMeetingEnded(an.SUCCESS_TRANSACTION_END,f))}handleAddBroadcastModalitySuccess(g,f){this.logger.info(`[${f}][handleAddBroadcastModalitySuccess]`)}handleAddBroadcastModalityFailure(g,f){this.logger.info(`[${f}][handleAddBroadcastModalityFailure]`);const S={...g.modalityFailure.broadcast};this.signalingSessionCallback.onBroadcastMeetingEnded(S,f)}updateBroadcastMetadata(g){const f={broadcastControllerUrl:this.broadcastControllerUrl,broadcastStateCallbackUrl:this.broadcastCallbackUrl,broadcastState:this.broadcastState,broadcastAdditionalData:this.broadcastAdditionalData};this.logger.info(`[${g}] update broadcast metadata=${f}`),this.signalingSessionCallback.onBroadcastMeetingUpdated&&this.signalingSessionCallback.onBroadcastMeetingUpdated(f,g)}},En="http://broker.invalid/",_n=30,Tn=5,In=1,bn=class{constructor(g){this._signalingSession=g,this.baseUrl=En,this.currentSubscriptionUrl=null,this._currentSubscriptionTimeoutInSec=_n,this._subscribers=[],this._disposed=!1,this._reportedResultCount=0,this._subscriptionRetryBackoffInSec=Tn,this._notifySubscribers=g=>{this._logger.info("_notifySubscribers"),Promise.resolve().then((()=>{g.split(",").forEach((g=>{const f=parseRawHttpMessage(decodeMessage(g));let S=f.body;isEncodedMessage(f.headers)&&isMessageEncodingSupported(f.headers)&&(S=decodeMessage(S));const v={url:f.url,body:JSON.parse(S),headers:f.headers};this._logger.info("message length=",S.length,"n. of subscribers",this._subscribers.length),this._subscribers.forEach((g=>g(v)))}))})).catch((g=>{this._logger.error("_notifySubscribers, failed to decode message",g),this._signalingSession.telemetryHelper.recordEvent(dn.BROKER_DECODE_PAYLOAD_FAILURE)}))},this._subscribeToBroker=(g,f)=>{if(this._disposed)return void this._logger.warn("_subscribeToBroker, disposed, ignore subscription");const S=causeId2();this._logger.info("_subscribeToBroker, url: ",g,",timeout in sec",f),this.currentSubscriptionUrl=g,this._currentSubscriptionTimeoutInSec=f,this._clearAllPendingTimeouts(),this._setSubscriptionTimeout(f),this._signalingSession.http.sendGetRequest({url:this.currentSubscriptionUrl,requestName:hn.BROKER_SUBSCRIBE.name,customHeaders:this._getBrokerRequestHeaders(S),payload:null,skipHttpTelemetry:!this._reportSubscriptionInTelemetry(),causeId:causeId2(),operationType:"BrokerSubscribe"}).then(this._handleSubscriptionSuccess).catch(this._handleSubscriptionFailure)},this._clearAllPendingTimeouts=()=>{this._cancelRequestTimer&&(this._cancelRequestTimer.stop(),this._cancelRequestTimer=null),this._retryRequestTimer&&(this._retryRequestTimer.stop(),this._retryRequestTimer=null)},this._abortPendingRequest=()=>{this._signalingSession.http.cancelRequestIfPending(hn.BROKER_SUBSCRIBE.name,causeId2())},this._setSubscriptionTimeout=g=>{this._cancelRequestTimer=ht.build((()=>{this._disposed||(this._signalingSession.http.hasPendingRequest(hn.BROKER_SUBSCRIBE.name)?(this._logger.warn("timeout subscription"),this._signalingSession.telemetryHelper.recordEvent(dn.BROKER_SUBSCRIPTION_TIMEOUT),this._signalingSession.http.cancelRequestIfPending(hn.BROKER_SUBSCRIBE.name,causeId2())):this._logger.error("Unable to resolve timeout deferred, it is not defined!"))}),"TIMEOUT").start(1e3*g)},this._handleSubscriptionSuccess=g=>{if(this._disposed)this._logger.warn("_handleSubscriptionSuccess, disposed, ignore subscription success");else if(this._reportSubscriptionInTelemetry(g)&&this._signalingSession.telemetryHelper.recordEvent(dn.BROKER_SUBSCRIPTION_SUCCESSFUL),g?.response){const f=g.response;this._logger.info("_handleSubscriptionSuccess, response",f),f.message&&this._notifySubscribers(f.message);const S=f.nextSubscribeUrl||this.currentSubscriptionUrl,v=f.expirationTimeInSec||this._currentSubscriptionTimeoutInSec;this._subscribeToBroker(S,v)}else this._logger.info("_handleSubscriptionSuccess, empty response")},this._handleSubscriptionFailure=g=>{if(this._disposed)return void this._logger.warn("_handleSubscriptionFailure, disposed, ignore subscription");if(g.status>=400&&g.status<500&&401!==g.status&&this.isNotNetworkErrors(g.status))return void this._logger.warn(`_handleSubscriptionFailure, received status ${g.status}, stop subscribing`);const f=getPrintableObject(g);this._logger.error("_handleSubscriptionFailure failed, re-subscribing",f),this._reportSubscriptionInTelemetry()&&this._signalingSession.telemetryHelper.recordEvent(dn.BROKER_SUBSCRIPTION_FAILED),this._retryRequestTimer=ht.build((()=>{this._subscribeToBroker(this.currentSubscriptionUrl,this._currentSubscriptionTimeoutInSec)}),"RETRY").start(1e3*this._subscriptionRetryBackoffInSec)},this._reportSubscriptionInTelemetry=g=>(this._reportedResultCount++,this._reportedResultCount<=In),this._getBrokerRequestHeaders=g=>{const f=new ln;return f.set(an.HEADERS.CONTENT_TYPE,an.CONTENT_TYPE.JSON),this._signalingSession.signalingAgentConfig.brokerRequestBatching&&f.set(an.HEADERS.BROKER_USE_BATCHING_HEADER_NAME,"1"),f},this._logger=this._signalingSession.logger.createChild("Broker"),this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration?.brokerRetryBackOffInSec&&(this._subscriptionRetryBackoffInSec=this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration.brokerRetryBackOffInSec)}subscribeToBroker(g){this._logger.info("subscribeToBroker called."),this._abortPendingRequest(),this._clearAllPendingTimeouts(),this._subscribeToBroker(g,this._currentSubscriptionTimeoutInSec)}onBrokerMessage(g){this._logger.info("onBrokerMessage callback added"),this._subscribers.push(g)}dispose(){this._disposed=!0,this._logger.info("dispose"),this._subscribers=[],this._clearAllPendingTimeouts(),this._abortPendingRequest()}isNotNetworkErrors(g){return 490!==g&&496!==g&&498!==g&&499!==g}},An=class{constructor(g){this.requests={},this.logger=g}clear(g,f){const S=f||{code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((f=>{try{const v=parseInt(f,10);Object.keys(this.requests[v]).forEach((f=>{this.rejectOperation(v,f,g,S)}))}catch(g){this.logger.warn(`CallOperations: clear error = ${g}`)}}))}hasOperation(g,f){return this.requests.hasOwnProperty(g.valueOf())&&this.requests[g.valueOf()].hasOwnProperty(f)}getAllOperations(){return this.requests}getOperation(g,f){return this.hasOperation(g,f)?this.requests[g.valueOf()][f]:null}setOperation(g,f,S){return!this.hasOperation(g,f)&&(this.hasOwnProperty(g.valueOf())||(this.requests[g.valueOf()]={}),this.requests[g.valueOf()][f]=S,!0)}rejectOperation(g,f,S,v){if(this.hasOperation(g,f)){const S=g.valueOf(),C=this.requests[S][f].promise;delete this.requests[S][f],C.reject(v)}}resolveOperation(g,f,S,v){if(this.hasOperation(g,f)){const v=g.valueOf(),C=this.requests[v][f].promise;delete this.requests[v][f],C.resolve(S)}}},Pn=class{constructor(g){this.logger=g,this.localRequests=new An(g)}dispose(g,f,S){this.logger.info(`[${S}][dispose]`),this.rejectAllPendingOperations(g,f)}hasPendingOperation(g,f,S){return this.logger.info(`[${S}][hasPendingOperation] ${g} ${scrubMriOrOmit(f)}}`),this.localRequests.hasOperation(g,f)}rejectPendingOperation(g,f,S,v,C){this.logger.info(`[${C}][rejectPendingOperation] ${g} ${f} reason: ${S} endCode: ${v}`),this.localRequests.rejectOperation(g,f,S,v)}resolvePendingOperation(g,f,S,v){this.logger.info(`[${v}][resolvePendingOperation]: ${scrubMriOrOmit(f)}`),this.localRequests.resolveOperation(g,f,S,v)}setPendingOperation(g,f,S,v){return this.logger.info(`[${v}][setPendingOperation] ${g} value: ${S}`),this.localRequests.setOperation(g,f,S)}rejectAllPendingOperations(g,f){this.logger.info("rejectLocalQueuedOperations"),this.localRequests.clear(g,f)}};function getPayload(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"content cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},to:[]},contentSharing:{identifier:f.contentIdentifier,subject:f.subject,sessionState:f.sessionState,sequenceNumber:f.sequenceNumber,links:{sessionUpdate:get2(g,rn.CONV_CONTENT_SHARING_UPDATE),sessionEnd:get2(g,rn.CONV_CONTENT_SHARING_END)}},links:{addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE)}}}}function getPayload2(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{contentSharing:{links:{sessionUpdate:get2(g,rn.CONV_CONTENT_SHARING_UPDATE),sessionEnd:get2(g,rn.CONV_CONTENT_SHARING_END)}},participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}function getPayload3(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{contentSharingTransactionEnd:f,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}function getPayload4(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}function getPayload5(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},links:{sessionUpdate:get2(g,rn.CONV_CONTENT_SHARING_UPDATE),sessionEnd:get2(g,rn.CONV_CONTENT_SHARING_END)}}}}function getPayload6(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}function getPayload7(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"sessionState cannot be null"),assertNotNull(S,"sequenceNumber cannot be null"),{payload:{sessionUpdateSequenceNumber:S,sessionState:f,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}var Rn=class{constructor(){this.msElapsed=0,this.isPaused=!1,this.startTime=(new Date).getTime(),this.pause=()=>{this.isPaused||(this.msElapsed+=(new Date).getTime()-this.startTime,this.isPaused=!0)},this.resume=()=>{this.isPaused&&(this.isPaused=!1,this.startTime=(new Date).getTime())},this.duration=()=>this.isPaused?this.msElapsed:this.msElapsed+(new Date).getTime()-this.startTime,this.durationInMinutes=()=>{const g=this.duration()/6e4;return Math.ceil(g)},this.durationInSeconds=()=>{const g=this.duration()/1e3;return Math.ceil(g)}}};function build3(){return new Rn}var Mn=class{constructor(g,f,S,v){this.signalingSession=g,this.correlationId=f,this.sessionId=null,this.fsmState=an.CONTENT_SHARING_FSM_STATE.IDLE,this.addSessionPromise=null,this.removeSessionPromise=null,this.confirmInRosterPromise=null,this.links={},this.lastUpdateSequenceNumber=-1,this.nextClientSequenceNumberToUse=1,this.disposed=!1,this.isPresenter=!1,this.FSM_STATES=an.CONTENT_SHARING_FSM_STATE,this.logger=g.logger.createChild((()=>`[${this.fsmState}][cs=${this.sessionId}][cc=${this.correlationId}]`)),S&&(this.sessionId=S),v&&(this.links=v)}start(g,f,S,v){if(this.logger.info(`[${v}][start]`),assertNotNullOrEmpty(g,"Correct addModality url is not provided"),!this.checkState("start",this.FSM_STATES.IDLE,this.addSessionPromise))return Promise.reject(null);this.addSessionPromise=S,this.confirmInRosterPromise=defer(),this.fsmState=this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.addTelemetryOperation(hn.ADD_CONTENT_SHARING_MODALITY.name,{causeId:v});const C=new ln;return C.set(an.HEADERS.CONTENT_SHARING_CORRELATION_ID,this.correlationId),this.signalingSession.http.sendPostRequest({url:g,payload:getPayload(this.signalingSession,f),requestName:hn.ADD_CONTENT_SHARING_MODALITY.name,customHeaders:C,onceTrouterReady:()=>{this.startContentSharingTimer(v)},causeId:v}).then((()=>{this.disposed||(this.presenterMri=this.signalingSession.participantManager.localParticipant.id,this.isPresenter=!0)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${v}][start] error: ${getPrintableObject(f)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise(getPrintableObject(g),f.error)),Promise.reject(null)}))}delete(g,f){this.logger.info(`[${f}][delete]`);let S=!1;if(this.fsmState===this.FSM_STATES.IDLE)return this.logger.info(`[${f}][delete] skipped because state is already ${this.fsmState}`),g.resolve(),Promise.resolve();if(this.fsmState===this.FSM_STATES.CONTENT_SHARING_START_INITIATED)S=!0,this.rejectPendingPromise("Session delete called before start was finished");else if(!this.checkState("delete",this.FSM_STATES.CONTENT_SHARING_CONNECTED,g))return Promise.reject(null);S||assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],"Correct controller url is not set"),this.removeSessionPromise=g,this.fsmState=this.FSM_STATES.CONTENT_SHARING_DELETE_INITIATED;const v=build3(),C=this.addTelemetryOperation(hn.DELETE_CONTENT_SHARING.name,{causeId:f});return(S?Promise.resolve(void 0):this.signalingSession.http.sendDeleteRequest({url:this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],requestName:hn.DELETE_CONTENT_SHARING.name,payload:getPayload3(this.signalingSession,{code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED}),causeId:f})).then((()=>{if(!this.disposed){const g={success:!0,duration:v.duration()};S&&(g.skipReason="Session delete called before start was finished"),this.updateTelemetryOperation(C,g),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${f}][delete] error: ${getPrintableObject(S)}`),!this.disposed){const g={success:!1,duration:v.duration()};this.updateTelemetryOperation(C,g),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}return Promise.reject(null)}))}join(g,f){if(this.logger.info(`[${f}][join]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],"Correct joinContentSharing url is not provided"),!this.checkState("join",this.FSM_STATES.IDLE,g))return;this.lastUpdateSequenceNumber=-1,this.nextClientSequenceNumberToUse=1,this.addSessionPromise=g,this.fsmState=this.FSM_STATES.CONTENT_SHARING_JOIN_INITIATED;const S=build3(),v=this.addTelemetryOperation(hn.JOIN_CONTENT_SHARING.name,{causeId:f});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],payload:getPayload2(this.signalingSession),requestName:hn.JOIN_CONTENT_SHARING.name,causeId:f}).then((g=>{if(!this.disposed){const f={success:!0,duration:S.duration()};this.updateTelemetryOperation(v,f),this.processStartOrJoinSuccess(g.response),this.resolvePendingPromise(g.response)}})).catch((g=>{const C=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${f}][join] error: ${getPrintableObject(C)}`),!this.disposed){const f={success:!1,duration:S.duration()};this.updateTelemetryOperation(v,f);const _=C.error;this.rejectPendingPromise(getPrintableObject(g),_)}}))}takeControl(g,f){if(this.logger.info(`[${f}][takeControl]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_TAKE_CONTROL],"correct contentSharingTakeControl url is not provided"),!this.checkState("takeControl",this.FSM_STATES.CONTENT_SHARING_CONNECTED,g))return;const S=build3(),v=this.addTelemetryOperation(hn.TAKE_CONTROL_CONTENT_SHARING.name,{causeId:f});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_TAKE_CONTROL],payload:getPayload4(this.signalingSession),requestName:hn.TAKE_CONTROL_CONTENT_SHARING.name,withoutTrouter:!0,causeId:f}).then((f=>{if(!this.disposed){const C={success:!0,duration:S.duration()};this.updateTelemetryOperation(v,C);const _={contentIdentifier:f.response.identifier,presenter:f.response.presenter.id,subject:f.response.subject||null,sessionState:f.response.sessionState||null};g.resolve(_)}})).catch((C=>{const _=getErrorForXHRFailure(C,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${f}][takeControl] error: ${getPrintableObject(_)}`),!this.disposed){const f={success:!1,duration:S.duration()};this.updateTelemetryOperation(v,f);const T=new Error(getPrintableObject(C));T.endCode=_.error,g.reject(T)}}))}updateSessionState(g,f,S){if(this.logger.info(`[${S}][updateSessionState]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],"Correct sendUpdateSessionState url is not provided"),!this.checkState("updateSessionState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,f))return;const v=build3(),C=this.addTelemetryOperation(hn.UPDATE_SESSION_STATE_CONTENT_SHARING.name,{causeId:S});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],payload:getPayload7(this.signalingSession,g,this.nextClientSequenceNumberToUse++),requestName:hn.UPDATE_SESSION_STATE_CONTENT_SHARING.name,causeId:S}).then((()=>{if(!this.disposed){const g={success:!0,duration:v.duration()};this.updateTelemetryOperation(C,g),f.resolve()}})).catch((g=>{const _=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${S}][updateSessionState] error: ${getPrintableObject(_)}`),!this.disposed){const S={success:!1,duration:v.duration()};this.updateTelemetryOperation(C,S);const T=new Error(getPrintableObject(g));T.endCode=_.error,f.reject(T)}}))}updateParticipantState(g,f){if(this.logger.info(`[${f}][updateParticipantState]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],"correct confirmContentSharingView url is not provided"),!this.checkState("updateParticipantState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,g))return;const S=build3(),v=this.addTelemetryOperation(hn.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,{causeId:f});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],payload:getPayload6(this.signalingSession),requestName:hn.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,withoutTrouter:!0,causeId:f}).then((()=>{if(!this.disposed){const f={success:!0,duration:S.duration()};this.updateTelemetryOperation(v,f),g.resolve()}})).catch((C=>{const _=getErrorForXHRFailure(C,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${f}][updateParticipantState] error: ${getPrintableObject(_)}`),!this.disposed){const f={success:!1,duration:S.duration()};this.updateTelemetryOperation(v,f);const T=new Error(getPrintableObject(C));T.endCode=_.error,g.reject(T)}}))}updateNotificationLinks(g){if(this.logger.info(`[${g}][updateNotificationLinks]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],"correct notificationLinks url is not provided"),!this.checkState("updateState",this.FSM_STATES.CONTENT_SHARING_CONNECTED))return;const f=build3(),S=this.addTelemetryOperation(hn.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,{causeId:g});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],payload:getPayload5(this.signalingSession),requestName:hn.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,withoutTrouter:!0,causeId:g}).then((()=>{if(!this.disposed){const g={success:!0,duration:f.duration()};this.updateTelemetryOperation(S,g)}})).catch((v=>{const C=getErrorForXHRFailure(v,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${g}][updateNotificationLinks] error: ${getPrintableObject(C)}`),!this.disposed){const g={success:!1,duration:f.duration()};this.updateTelemetryOperation(S,g)}}))}confirmInRoster(){this.confirmInRosterPromise&&this.confirmInRosterPromise.isPending&&(this.logger.info("Confirmed in roster"),this.confirmInRosterPromise.resolve())}handleAddModalitySuccess(g,f){return this.logger.info(`[${f}][handleAddModalitySuccess]`),this.checkState("handleAddModalitySuccess",this.FSM_STATES.CONTENT_SHARING_START_INITIATED)?g.modalitySuccess&&g.modalitySuccess.contentSharing?(this.addTelemetryOperation(dn.HANDLE_ADD_MODALITY_SUCCESS,{causeId:f}),this.processStartOrJoinSuccess(g.modalitySuccess.contentSharing),this.confirmInRosterPromise.promise.then((()=>{delete this.confirmInRosterPromise,this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY),this.resolvePendingPromise(g.modalitySuccess.contentSharing)})),!0):(this.addTelemetryOperation(dn.HANDLE_ADD_MODALITY_SUCCESS,{causeId:f,skipReason:"no content sharing blob"}),this.logger.info(`[${f}][handleAddModalitySuccess] ignored because modalitySuccess was missing or did not contain content sharing blob`),!1):(this.logger.info(`[${f}][handleAddModalitySuccess] ignored because session is not waiting to start`),!1)}handleAddModalityFailure(g,f){this.logger.info(`[${f}][handleAddModalityFailure]`);if(!this.checkState("handleAddModalityFailure",[this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.FSM_STATES.CONTENT_SHARING_CONNECTED]))return!1;if(!g.modalityFailure||!g.modalityFailure.contentSharing)return this.addTelemetryOperation(dn.HANDLE_ADD_MODALITY_FAILURE,{causeId:f,skipReason:"no content sharing blob"}),!1;const S=g.modalityFailure.contentSharing;this.addTelemetryOperation(dn.HANDLE_ADD_MODALITY_FAILURE,{reason:S,causeId:f});const v={...S};return this.sendTelemetryData(v),this.rejectPendingPromise(v.phrase,v),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY),!0}handleStartFromRoster(g,f){this.logger.info(`[${f}][handleStartFromRoster]`),this.addTelemetryOperation(dn.CONTENT_SHARING_START_FROM_ROSTER,{causeId:f})}handleStopFromRoster(g,f){this.logger.info(`[${f}][handleStopFromRoster]`),this.addTelemetryOperation(dn.CONTENT_SHARING_END_FROM_ROSTER,{causeId:f}),this.sendTelemetryData(g)}handleStop(g,f){if(this.logger.info(`[${f}][handleStop]`),this.isSelfInitiatedAction(g))return this.logger.info(`[${f}][handleStop]handleStop skipped because session was ended by self`),!1;const S={...g.contentSharingTransactionEnd};return this.addTelemetryOperation(dn.HANDLE_CONTENT_SHARING_END,{causeId:f}),this.sendTelemetryData(S),!0}handleUpdate(g,f){return this.logger.info(`[${f}][handleUpdate]`),g.sequenceNumber<=this.lastUpdateSequenceNumber?(this.logger.info(`handleUpdate skipped because of old sequence number: last received ${this.lastUpdateSequenceNumber}, update contained ${g.sequenceNumber}`),this.addTelemetryOperation(dn.HANDLE_CONTENT_SHARING_UPDATE,{causeId:f,skipReason:"old sequence number"}),!1):(this.lastUpdateSequenceNumber=g.sequenceNumber,this.isPresenter=g.presenter.id===this.signalingSession.participantManager.localParticipant.id,this.addTelemetryOperation(dn.HANDLE_CONTENT_SHARING_UPDATE,{causeId:f}),!0)}dispose(g,f){this.logger.info(`[${f}][dispose]`),this.disposed=!0,this.rejectPendingPromise("call ended",g||{code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED}),this.addTelemetryOperation(dn.HANDLE_CALL_END,{causeId:f}),this.sendTelemetryData(g)}rejectPendingPromise(g,f){this.logger.info("rejectPendingPromise");const S=new Error(g);f&&(S.endCode=f),this.removeSessionPromise&&(this.removeSessionPromise.reject(S),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.reject(S),this.addSessionPromise=null)}resolvePendingPromise(g){this.logger.info("resolvePendingPromise");let f=null;g&&(f={sessionId:g.sessionId,correlationId:g.contentSharingCorrelationId,contentIdentifier:g.identifier,presenter:g.presenter.id,subject:g.subject||null,sessionState:g.sessionState||null}),this.removeSessionPromise&&(this.removeSessionPromise.resolve(f),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.resolve(f),this.addSessionPromise=null)}processStartOrJoinSuccess(g){this.logger.info("processStartOrJoinSuccess"),this.sessionId=g.sessionId,this.fsmState=this.FSM_STATES.CONTENT_SHARING_CONNECTED,this.lastUpdateSequenceNumber=-1,this.links[an.LINKS.CONTENT_SHARING_CONTROLLER]=g.links.contentSharingController,this.links[an.LINKS.CONTENT_SHARING_TAKE_CONTROL]=g.links.takeControl,this.links[an.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE]=g.links.updateSessionState,this.links[an.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE]=g.links.sync,this.links[an.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS]=g.links.notificationLinks,this.links[an.LINKS.CONTENT_SHARING_LEAVE]=g.links.leave}checkState(g,f,S){let v;if(v="string"==typeof f?this.fsmState===f:f.indexOf(this.fsmState)>-1,v)return!0;{const v=`${g} requires state ${f}, but state is ${this.fsmState}`;return this.logger.error(v),S&&S.reject(v),!1}}isSelfInitiatedAction(g){return g.presenter.participantId===this.signalingSession.participantManager.localParticipant.participantId}startContentSharingTimer(g){this.logger.info("startContentSharingTimer"),this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY,(()=>{this.addTelemetryOperation(dn.ADD_MODALITY_TIMEOUT,{causeId:g}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise("timed out waiting for ContentSharing to start",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT})}),an.TIMEOUT_VALUES_IN_SECONDS.ADD_MODALITY_TIMEOUT)}addTelemetryOperation(g,f){return this.signalingSession.telemetryHelper.addContentSharingOperation(this.correlationId,g,f)}updateTelemetryOperation(g,f){this.signalingSession.telemetryHelper.updateContentSharingOperation(this.correlationId,g,f)}sendTelemetryData(g){this.signalingSession.telemetryHelper.sendContentSharingTelemetryData(this.correlationId,this.signalingSession.sessionId,this.isPresenter,g,this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],this.sessionId)}},wn=class{constructor(g,f){this.contentSharingToStartCallWith=null,this.contentSharingSessions={},this.DEFAULT_STOP_REASON={code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.REMOTE_USER_INITIATED},this.DEFAULT_STOP_ID="8:unknown",this.deleteContentSharingAsync=(g,f)=>{this.logger.info(`[${f}][deleteContentSharingAsync]`);const S=defer();let v=this.contentSharingSessions[g];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===g&&(v=this.pendingSessionToStart),v){const always=()=>{this.contentSharingSessions[g]&&delete this.contentSharingSessions[g]};v.delete(S,f).then(always,always)}else this.rejectBecauseOfMissingSession(g,S);return S.promise},this.signalingSession=g,this.signalingSessionCallback=f,this.logger=g.logger.createChild((()=>"[ContentSharingManager]")),this.lastProcessedSequenceNumber=-1,this.lastProcessedSequenceNumberForParticipant={}}startContentSharingAsync(g,f,S,v,C,_,T){if(this.logger.info(`startContentSharingAsync called for: ${g}`),this.pendingSessionToStart){const g="There is already a ContentSharing session start pending";return this.logger.error(g),Promise.reject(new Error(g))}const I={contentIdentifier:g,subject:S||null,sessionState:f||null,sequenceNumber:1},b=defer(),A=new Mn(this.signalingSession,T||newGuid());return this.pendingSessionToStart=A,C?(this.logger.info("Call connected, send content sharing request out immediately"),A.start(v,I,b,_)):(this.logger.info("Content sharing is to be started when startOutgoingCall is called"),A.addSessionPromise=b,A.fsmState=an.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED,this.contentSharingToStartCallWith=I),b.promise.then((()=>{this.contentSharingSessions.hasOwnProperty(A.correlationId)||(this.contentSharingSessions[A.correlationId]=A),this.pendingSessionToStart=null})).catch((()=>{this.pendingSessionToStart=null})),b.promise}joinContentSharingAsync(g,f){this.logger.info(`[${f}][joinContentSharingAsync]`);const S=defer(),v=this.contentSharingSessions[g];return v?v.join(S,f):this.rejectBecauseOfMissingSession(g,S),S.promise}updateContentSharingSessionStateAsync(g,f,S){this.logger.info(`[${S}][updateContentSharingSessionStateAsync][sessionState=${JSON.stringify(f)}]`);const v=defer(),C=this.contentSharingSessions[g];return C?C.updateSessionState(f,v,S):this.rejectBecauseOfMissingSession(g,v),v.promise}takeContentSharingControlAsync(g,f){this.logger.info(`[${f}][takeContentSharingControlAsync]`);const S=defer(),v=this.contentSharingSessions[g];return v?v.takeControl(S,f):this.rejectBecauseOfMissingSession(g,S),S.promise}updateContentSharingParticipantStateAsync(g,f){this.logger.info(`[${f}][updateContentSharingParticipantStateAsync]`);const S=defer(),v=this.contentSharingSessions[g];return v?v.updateParticipantState(S,f):this.rejectBecauseOfMissingSession(g,S),S.promise}updateContentSharingNotificationLinksAsync(g){this.logger.info(`[${g}][updateContentSharingNotificationLinksAsync]`);for(const f of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(f)){const S=this.contentSharingSessions[f];S&&S.updateNotificationLinks(g)}}getContentSharingInfoToStartSharing(){if(this.contentSharingToStartCallWith){const g=this.pendingSessionToStart,f=an.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED;g&&g.fsmState===f||(this.contentSharingToStartCallWith=null,this.pendingSessionToStart=null)}return this.contentSharingToStartCallWith}dispose(g,f){this.logger.info(`[${f}][dispose]`);for(const S of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(S)){const v=this.contentSharingSessions[S];v&&v.dispose(g,f)}}handleContentSharingUpdate(g){const f=g.body,S=extractCauseIdFromMessage(g),v=this.contentSharingSessions[f.contentSharingCorrelationId];v?v.handleUpdate(f,S)&&this.signalingSessionCallback.onContentSharingUpdated({sessionId:f.sessionId,correlationId:f.contentSharingCorrelationId,contentIdentifier:f.identifier,presenter:f.presenter.id,subject:f.subject||null,sessionState:f.sessionState||null},S):this.logger.info(`[${S}][handleContentSharingUpdate][failed][reason=no session with correlation ID ${f.correlationId}]`)}handleAddModalitySuccess(g,f){this.logger.info(`[${f}][handleAddModalitySuccess]`);const S=this.pendingSessionToStart;S?S.handleAddModalitySuccess(g,f):this.logger.info(`[${f}][handleAddModalitySuccess]Ignoring handleAddModalitySuccess because not waiting for one`)}handleAddModalityFailure(g,f){this.logger.info(`[${f}][handleAddModalityFailure]`);const S=this.pendingSessionToStart;S?S.handleAddModalityFailure(g,f):this.logger.info(`[${f}][handleAddModalityFailure]Ignoring handleAddModalityFailure because not waiting for one`)}handleIncomingContentSharingFromRoster(g,f,S){if(this.logger.info(`[${S}] handleIncomingContentSharingFromRoster: isFullRoster ${f} content ${getPrintableObject(g)}`),("MultiPartyEndpoint"===g.type||f)&&this.lastProcessedSequenceNumber>g.sequenceNumber)return void this.logger.info(`[${S}] handleIncomingContentSharingFromRoster invalid roster current sequenceNumber ${g.sequenceNumber} lastProcessedSequenceNumber ${this.lastProcessedSequenceNumber}`);const{sessionsWithPresenters:v,sessionsWithoutPresenters:C}=this.parseContentSharingSessionsFromRoster(g);this.startSessionsFromRoster(v,S),this.stopSessionsFromRoster(C,S),this.lastProcessedSequenceNumber=g.sequenceNumber}handleContentSharingEnd(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info("handleContentSharingEnd : ",getPrintableObject(f));const v=this.contentSharingSessions[f.contentSharingCorrelationId];if(!v)return void this.logger.info("Ignoring contentSharingEnd since there is no corresponding sharing ongoing");if(!v.handleStop(f,S))return;const C={...f.contentSharingTransactionEnd};this.raiseContentSharingStopped(f.contentSharingCorrelationId,S,f.presenter.id,C)}parseContentSharingSessionsFromRoster(g){const f={},S={},v=new Set;for(const S of Object.keys(g.participants)){const C=g.participants[S];if("Delta"===g.type&&this.lastProcessedSequenceNumberForParticipant.hasOwnProperty(S)&&C.version<=this.lastProcessedSequenceNumberForParticipant[S])continue;if(C.version=C.version||-1,this.lastProcessedSequenceNumberForParticipant[S]=C.version,v.add(C.details.id),!C.endpoints)continue;const _=this.signalingSession.participantManager.localParticipant.participantId;for(const g of Object.keys(C.endpoints)){const S=C.endpoints[g],v=S?.contentSharing?.sessionInformation;"presenter"===v?.role&&(f[v.contentSharingCorrelationId]={presenterId:C.details.id,sessionInfo:v,selfEndpointIsPresenter:S.participantId===_})}}for(const g of Object.keys(this.contentSharingSessions))!f[g]&&v.has(this.contentSharingSessions[g].presenterMri)&&(S[g]=this.contentSharingSessions[g]);return{sessionsWithPresenters:f,sessionsWithoutPresenters:S}}stopSessionsFromRoster(g,f){this.logger.info(`[${f}][stopSessionsFromRoster]`);for(const S of Object.keys(g))this.logger.info(`[${f}][stopSessionsFromRoster] stopping session with correlationId ${S}`),this.stopSession(g[S],f)}stopSession(g,f){this.logger.info(`[${f}][stopSession] Stopping session ${g.sessionId}`),g.handleStopFromRoster(this.DEFAULT_STOP_REASON,f),this.raiseContentSharingStopped(g.correlationId,f)}startSessionsFromRoster(g,f){this.logger.info(`[${f}][startSessionsFromRoster]`);for(const S of Object.keys(g)){this.logger.info(`[${f}][startSessionsFromRoster]`);const v=this.contentSharingSessions[S],C=g[S];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===S?this.pendingSessionToStart.confirmInRoster():v&&v.confirmInRoster(),v)v&&(this.contentSharingSessions[S].presenterMri=C.presenterId,this.logger.info(`[${f}][startSessionsFromRoster]Session ${S} is already present locally`));else{if(C.selfEndpointIsPresenter){this.logger.info(`[${f}][startSessionsFromRoster]This endpoint is presenting, dont fire callback`);continue}this.logger.info(`[${f}][startSessionsFromRoster]New sharing session found. Raising ContentSharingStarted`);this.raiseContentSharingStarted(C.presenterId,C.sessionInfo,f).handleStartFromRoster(C.presenterId,f)}}}raiseContentSharingStopped(g,f,S,v){this.logger.info(`[${f}][raiseContentSharingStopped]`),this.signalingSessionCallback.onContentSharingStopped({sessionId:this.contentSharingSessions[g].sessionId,correlationId:g,endedBy:S||this.DEFAULT_STOP_ID,reason:v||this.DEFAULT_STOP_REASON},f),delete this.contentSharingSessions[g]}raiseContentSharingStarted(g,f,S){this.logger.info(`[${S}][raiseContentSharingStarted]`);const v=new Mn(this.signalingSession,f.contentSharingCorrelationId,f.contentSharingSessionId,{[an.LINKS.CONTENT_SHARING_CONTROLLER]:f.contentSharingController});v.presenterMri=g,this.contentSharingSessions[v.correlationId]=v;const C={sessionId:f.contentSharingSessionId,correlationId:f.contentSharingCorrelationId,contentIdentifier:f.identifier,presenter:g,subject:f.subject||null,sessionState:f.sessionState||null};return this.signalingSessionCallback.onContentSharingStarted(C,S),v}rejectBecauseOfMissingSession(g,f){const S=`There is no ContentSharing session with the correlation ID ${g}`;this.logger.error(S),f&&f.reject(new Error(S))}},On={Default:{retryIntervalsMs:[200,1e3,5e3],maxRequestAttempts:4,perRequestTimeoutMs:45e3,perAttemptTimeoutMs:15e3,perRequestTimeoutWithHedgingMs:45e3,perAttemptTimeoutWithHedgingMs:3e4,hedgeDelayMs:4e3},BrokerSubscribe:{retryIntervalsMs:[100,200,500],maxRequestAttempts:4,perRequestTimeoutMs:3e4,perAttemptTimeoutMs:3e4,perRequestTimeoutWithHedgingMs:45e3,perAttemptTimeoutWithHedgingMs:3e4}},Dn={CallSetup:{requestHedgingCapability:["disabled"],hedgeDelayMs:4e3},Other:{requestHedgingCapability:["disabled"]},BrokerSubscribe:{requestHedgingCapability:["disabled"]}},Nn="HttpRequestDispatcherFactory";function reportTokenTelemetryData(g,f,S){f?.signalingSession?f.signalingSession.telemetryHelper?.addTokenTelemetry(g,f?.tokenTelemetryData):S?.info("[reportTokenTelemetryData] signaling session is not available, cannot send token telemetry")}function get3(g,f){const{signalingSession:S,operation:v,causeId:C,data:_,customHeaders:T={},forceFetchToken:I,tokenRequestOptions:b,useFetch:A,fetchUseKeepAlive:P}=g;if(S.disposed)return Promise.reject("Session already disposed");const handleFailure=g=>{const f="string"==typeof g?new Error(g):g;throw S.signalingAgent.clientSupportsGenericTokenAPI?g.timeOut?f.tokenTimeoutError=!0:(f.tokenError=!0,f.tokenErrorSubCode=g.errorSubCode):f.skypeTokenError=!0,f};let R=!1;const M={signalingSession:S,tokenTelemetryData:{}};return S.signalingAgent.authTokenManager.getToken(C,I,b,M).catch((v=>(reportTokenTelemetryData(g.requestId,M,f),!I&&isAppOnline(S)&&S.signalingAgentConfig.attemptHttpRequestWithCachedSkypetoken&&S.signalingAgent.authTokenManager.getLastToken(C)?(R=!0,f?.info(`[${C}][requestBuilder] failed to fetch token, using lastToken`),Promise.resolve(S.signalingAgent.authTokenManager.getLastToken(C))):(f?.info(`[${C}][requestBuilder] getToken failed with error ${v}`),handleFailure(v))))).then((I=>{if(S.disposed)throw new Error("token returned too late. Object is already disposed");reportTokenTelemetryData(g.requestId,M,f);const b=new ln;if(b.set(an.HEADERS.CORRELATION_ID,S.correlationId),b.set(an.HEADERS.MESSAGE_ID,newMessageId(C)),b.set(an.HEADERS.CLIENT_USER_AGENT,S.signalingAgentConfig.clientInformation),S.signalingAgent.clientSupportsGenericTokenAPI){const g=S.signalingAgent.authTokenManager.getLastTokenType(C);switch(S.signalingAgentConfig.disableTokenMigrationHeader||b.set(an.HEADERS.TOKEN_MIGRATION,"True"),g){case 8:case 4:b.set(an.HEADERS.AUTHORIZATION,`${an.HEADERS.BEARER_KEYWORD} ${I}`),b.delete(an.HEADERS.SKYPE_TOKEN);break;case 1:b.set(an.HEADERS.SKYPE_TOKEN,I),b.delete(an.HEADERS.AUTHORIZATION);break;default:throw new Error(`Error in RequestBuilder. TokenType ${g} is not supported`)}}else b.set(an.HEADERS.SKYPE_TOKEN,I);const w=S.participantManager.localParticipant;w&&(w.ring&&b.set(an.HEADERS.RING,w.ring),w.region&&b.set(an.HEADERS.REGION,w.region),w.partition&&b.set(an.HEADERS.PARTITION,w.partition));const O=_?.payload?JSON.stringify(_.payload):null,D={headers:{...b?.getAll(),...T},payload:O,usedCachedSkypetoken:R,reporting:{serviceName:v?`${Nn}-${v}`:Nn},useFetch:A,fetchUseKeepAlive:P};return S.telemetryHelper.addNetworkOperationStarted(v),D})).catch(handleFailure)}function isAppOnline(g){const f=isTrouterAndNavigatorConnected(g.signalingAgentConfig.trouterServiceProvider);return 3===f||1===f}var kn=500,Ln=1e4,Fn=4,xn=3e3,Un=3;function build4(g){return new Vn(g.causeId,g.logger,g.dispatcher,g.requestType,g.url,g.request,g.attemptFailureCallback,g.authRequiredCallback,g.settings)}var Vn=class{constructor(g,f,S,v,C,_,T,I,b){this.causeId=g,this.logger=f,this.dispatcher=S,this.requestType=v,this.url=C,this.request=_,this.onRequestFailed=T,this.authRequiredCallback=I,this.settings=b,this.requestsSent=0,this.otherAttemptSuccessful=!1,this.pendingAttempts=[],this.hedgeDelayMs=xn,this.hedgeMaxParallelAttempts=Un,this.stopStandardRetryTimer=()=>{this.standardRetryTimer&&(this.standardRetryTimer.stop(),this.standardRetryTimer=null)},this.stopHedgeTimer=()=>{this.hedgeTimer&&(this.hedgeTimer.stop(),this.hedgeTimer=null)},this.stopAttemptTimeoutTimer=g=>{try{g.timeoutTimer&&(g.timeoutTimer.stop(),this.logger.info("attempt timer stopped"))}catch(g){this.logger.info(`stopAttemptTimeoutTimer error ${g}`)}},this.stopRequestTimer=()=>{try{this.requestTimer&&(this.requestTimer.stop(),this.logger.info("Request timer stopped"))}catch(g){this.logger.info(`stopRequestTimer error ${g}`)}this.requestTimer=null},this.canScheduleNextAttempt=()=>{if(this.stackError===an.HTTP_STACK_ERROR.REQUEST_ABORTED||this.otherAttemptSuccessful||this.requestsSent>=this.settings.maxRequestAttempts)return this.logger.info(`canScheduleNextAttempt stack error ${this.stackError} otherAttemptSuccessful ${this.otherAttemptSuccessful} exceeded max attempt ${this.requestsSent>=this.settings.maxRequestAttempts}`),!1;if(this.settings.enableRequestHedging){const g=this.pendingAttempts.length<this.hedgeMaxParallelAttempts;return g||this.logger.info(`canScheduleNextAttempt enableRequestHedging attempts sent: ${this.pendingAttempts.length} max attempts: ${this.hedgeMaxParallelAttempts}`),g}{const g=this.requestsSent<this.settings.retryIntervalsMs.length;return g||this.logger.info(`canScheduleNextAttempt attempts sent: ${this.requestsSent} max attempts: ${this.settings.retryIntervalsMs.length}`),g}},this.scheduleNextRequest=g=>{this.settings.enableRequestHedging?(this.logger.info("scheduleNextRequest with hedging"),this.hedgeTimer=ht.build((()=>{this.attempt(),this.canScheduleNextAttempt()&&this.scheduleNextRequest(!1)}),"HEDGE").start(this.getNextDelay(g))):(this.logger.info("scheduleNextRequest with retry"),this.standardRetryTimer=ht.build((()=>{this.attempt()}),"RETRY").start(this.getNextDelay(g)))},this.standardizeFailedRequest=(g,f)=>{let S;const v=this.logger.createChild("[standardizeFailedRequest]");try{if(this.stackError===an.HTTP_STACK_ERROR.REQUEST_TIMEOUT)v.info("request timed out"),S=en.REQUEST_TIMEOUT;else if(this.stackError===an.HTTP_STACK_ERROR.REQUEST_ABORTED)v.info("request aborted"),S=en.REQUEST_ABORTED;else if(f&&f.status===an.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT)v.info("request attempt timed out"),S=en.ATTEMPT_TIMEOUT;else if(f&&[an.HTTP_STACK_ERROR.ATTEMPT_ABORTED,an.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL].indexOf(f.status)>-1)v.info("request attempt aborted"),S=en.ATTEMPT_ABORTED;else if(g){if(v.info(`request ${getPIISafeRequest(g)}`),g.request?.response){const f=g;S={response:{..."string"==typeof f?.request?.response?f?.response?.data:f?.request?.response,headers:f.response?.headers},status:f.request.status,statusText:f.request.statusText,readyState:f.request.readyState}}else g.status||g.statusCode||g.response?S={response:g.response,status:[void 0,null,""].indexOf(g.status)>-1?g.statusCode:g.status,statusText:g.statusText,readyState:g.readyState}:(v.info("Local http stack error"),S={response:an.CALL_END_SUB_CODE.LOCAL_HTTP_STACK_ERROR,status:an.CALL_END_CODE.LOCAL_HTTP_STACK_ERROR,statusText:"LocalHTTPStackError",readyState:g.readyState||0});this.isBrowserOffline()&&0===S.status&&4===S.readyState&&(v.info("offline"),S={response:an.HTTP_STACK_ERROR.CANNOT_CONNECT,status:an.HTTP_STATUS_CODES.OFFLINE,statusText:"offline",readyState:S.readyState}),g.response?.message&&(g.response.message.operationFailure||g.response.message.broadcastOperationFailure)?S={response:g.response.message}:!g.response&&g.body?.operationFailure&&(S={response:g.body})}else v.info("no response"),S={response:an.HTTP_STACK_ERROR.NONE,status:an.HTTP_STATUS_CODES.OTHER,statusText:"Empty Response",readyState:0}}catch(g){v.info(`Failed to handle error ${g}`),S={response:"",status:an.HTTP_STATUS_CODES.OTHER,statusText:"FailedToHandleError",readyState:0}}return S},this.hasPendingAttempts=()=>this.pendingAttempts.some((g=>g.pending)),this.getRequestFromStatus=g=>g?.request?.status||0,this.isBrowserOffline=()=>navigator&&!1===navigator.onLine,this.logger=f.createChild(`[${this.causeId}][Dispatcher]`),this.logger.info(`created request, url=${C}`),!isNaN(this.settings.hedgeDelayMs)&&this.settings.hedgeDelayMs>=kn&&this.settings.hedgeDelayMs<=Ln&&(this.hedgeDelayMs=this.settings.hedgeDelayMs),!isNaN(this.settings.hedgeMaxParallelAttempts)&&this.settings.hedgeMaxParallelAttempts>=0&&this.settings.hedgeMaxParallelAttempts<=Fn&&(this.hedgeMaxParallelAttempts=this.settings.hedgeMaxParallelAttempts),(isNaN(this.settings.perAttemptTimeoutMs)||this.settings.perAttemptTimeoutMs<=0)&&(this.settings.perAttemptTimeoutMs=15e3),(isNaN(this.settings.perRequestTimeoutMs)||this.settings.perRequestTimeoutMs<=0)&&(this.settings.perRequestTimeoutMs=45e3),(isNaN(this.settings.maxRequestAttempts)||this.settings.maxRequestAttempts<=0)&&(this.settings.maxRequestAttempts=4),(isNaN(this.settings.perRequestTimeoutWithHedgingMs)||this.settings.perRequestTimeoutWithHedgingMs<=0)&&(this.settings.perRequestTimeoutWithHedgingMs=45e3),(isNaN(this.settings.perAttemptTimeoutWithHedgingMs)||this.settings.perAttemptTimeoutWithHedgingMs<=0)&&(this.settings.perAttemptTimeoutWithHedgingMs=3e4)}sendRequest(){this.stackError=an.HTTP_STACK_ERROR.NONE;const timeoutCallback=()=>{this.stackError=an.HTTP_STACK_ERROR.REQUEST_TIMEOUT,this.cancelAllAttempts(an.HTTP_STACK_ERROR.REQUEST_TIMEOUT)};return this.logger.info("send api called"),this.requestTimer=ht.build(timeoutCallback,"REQUEST_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perRequestTimeoutWithHedgingMs:this.settings.perRequestTimeoutMs),new Promise(((g,f)=>{this.resolve=g,this.reject=f,this.scheduleNextRequest(!0)}))}cancelRequest(){this.logger.info("cancelRequest"),this.stackError=an.HTTP_STACK_ERROR.REQUEST_ABORTED,this.cancelAllAttempts(an.HTTP_STACK_ERROR.ATTEMPT_ABORTED)}cancelOtherAttempts(g){this.pendingAttempts.splice(g-1,1),this.cancelAllAttempts(an.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL)}cancelAllAttempts(g){this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.pendingAttempts.forEach((f=>{f.status=g,f.cancelDeferred.resolve(),this.stopAttemptTimeoutTimer(f)})),this.stopRequestTimer()}getRequestMethod(g){switch(g){case 0:return this.dispatcher.getAsync.bind(this.dispatcher);case 1:return this.dispatcher.postAsync.bind(this.dispatcher);case 2:return this.dispatcher.putAsync.bind(this.dispatcher);case 3:return this.dispatcher.removeAsync.bind(this.dispatcher);default:return null}}async queueAttempt(g){const f=g&&this.isNotRetryable(g);if(this.logger.info("queueAttempt"),f||!this.canScheduleNextAttempt())return this.logger.info(`unable to retry isNotRetryable ${f} ${JSON.stringify(g)}`),this.stopHedgeTimer(),this.stopRequestTimer(),void(this.hasPendingAttempts()||(this.settings.reportPreviousErrorsForTimeout&&g===en.ATTEMPT_TIMEOUT&&this.previousAttempt?this.reject(this.previousAttempt):this.reject(g)));if(this.isAuthFailedStatus(g)){this.logger.info("auth failed"),this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.stopRequestTimer();try{const f=g?.response?.headers,S=getRequestToken(this.request?.headers),v=g.response?.status===an.HTTP_STATUS_CODES.UNAUTHORIZED&&g.response?.operationFailure?.subCode===an.CALL_END_SUB_CODE.CONVERSATION_TERMINATION_INTERACTION_REQUIRED,C=await this.authRequiredCallback(f,S,{IPCAFailure:v});this.request=C}catch(f){return void this.reject(g)}}this.previousAttempt=g,this.hedgeTimer?this.logger.info("scheduleNextRequest ignored as there's already active hedge timer"):this.scheduleNextRequest(!1)}attempt(){if(this.logger.info("attempt to send request"),this.stackError===an.HTTP_STACK_ERROR.REQUEST_ABORTED||this.otherAttemptSuccessful)return;const g=(new Date).getTime();this.requestsSent++;const f=this.requestsSent,S=defer();this.request.timeout=S.promise;const v={cancelDeferred:S,status:an.HTTP_STACK_ERROR.NONE,timeoutTimer:null,pending:!0},timeoutRequest=()=>{v.status=an.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT,v.cancelDeferred.resolve()},C=ht.build(timeoutRequest,"ATTEMPT_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perAttemptTimeoutWithHedgingMs:this.settings.perAttemptTimeoutMs);v.timeoutTimer=C,this.pendingAttempts.push(v);this.getRequestMethod(this.requestType)(this.url,this.request).then((S=>{if(this.logger.info(`attempt successful, request response=${getPIISafeRequestResponse(S)} status=${this.getRequestFromStatus(S)}`),this.otherAttemptSuccessful)throw"Other attempt succesful";if(this.stackError===an.HTTP_STACK_ERROR.REQUEST_ABORTED)throw"Session disposed";if(!S)throw"Invalid response";v.pending=!1,this.otherAttemptSuccessful=!0,this.stopRequestTimer(),this.stopHedgeTimer(),this.stopAttemptTimeoutTimer(v),this.cancelOtherAttempts(f),this.resolve({success:!0,request:S.request,response:S.response,attempt:this.requestsSent,attemptStartTimestamp:g,attemptResponseTimestamp:(new Date).getTime()})})).catch((f=>{v.pending=!1,this.stopAttemptTimeoutTimer(v);const S=this.standardizeFailedRequest(f,v);this.logger.info(`attempt failed, request: ${getPIISafeRequest(f)} status=${S.status}`),this.onRequestFailed({abandoned:this.otherAttemptSuccessful,success:!1,request:S,attempt:this.requestsSent,attemptStartTimestamp:g,attemptResponseTimestamp:(new Date).getTime()}),this.queueAttempt(S)}))}getNextDelay(g){let f;if(g)f=0;else if(this.settings.enableRequestHedging)f=this.hedgeDelayMs;else{if(!(this.requestsSent<=this.settings.retryIntervalsMs.length))throw"Unable to get next delay";f=this.settings.retryIntervalsMs[this.requestsSent-1]}return this.logger.info(`next delay= ${f} ms`),f}isRequestWithStatus(g,f){return!!g&&f.indexOf(g.status)>-1}isNotRetryable(g){return!isRetryable(g?.status)}isAuthFailedStatus(g){return this.isRequestWithStatus(g,[an.HTTP_STATUS_CODES.UNAUTHORIZED])}},Bn={1:"POST",0:"GET",2:"PUT",3:"DELETE"},Hn=class{constructor(g,f){this.signalingSession=g,this.callStartTime=f,this.pendingRequests={},this.sendGetRequest=g=>this.sendRequest(0,g),this.sendPostRequest=g=>this.sendRequest(1,g),this.sendPutRequest=g=>this.sendRequest(2,g),this.sendDeleteRequest=g=>this.sendRequest(3,g),this.cancelRequestIfPending=(g,f,S,v)=>{this.logger.info(`[${f}][cancelRequestIfPending]`),this.pendingRequests[g]?S?this.hasPendingRequest(g,S)&&this.cancelRequest(g,S,f,v):Object.keys(this.pendingRequests[g]).forEach((S=>this.cancelRequest(g,S,f,v))):this.logger.info(`[${f}][cancelRequestIfPending]no pending request with name=${g}`)},this.cancelAllRequests=g=>{this.logger.info(`[${g}][cancelAllRequests]`);const f=[];return Object.keys(this.pendingRequests).forEach((S=>{Object.keys(this.pendingRequests[S]).forEach((v=>{f.push(this.cancelRequest(S,v,g))}))})),Promise.all(f).catch((()=>{}))},this.hasPendingRequest=(g,f)=>!!this.pendingRequests[g]&&Boolean(f?this.pendingRequests[g][f]:this.pendingRequests[g]),this.cancelRequest=(g,f,S,v)=>{try{return this.pendingRequests[g][f].dispatcher&&this.pendingRequests[g][f].dispatcher.cancelRequest(),this.pendingRequests[g][f].aborted=!0,this.pendingRequests[g][f].errorDetails=v,this.logger.info(`[${S}][cancelRequest]Request=${g} aborted ${v?`with errorDetails ${JSON.stringify(v)}`:""}`),this.pendingRequests[g][f].requestPromise.catch((()=>{}))}catch(v){return this.logger.warn(`[${S}][cancelRequest]Unable to cancel request=${g}, requestId=${f}`),Promise.resolve()}},this.buildRequestTelemetry=(g,f,S,v)=>({name:`${Bn[g]}-${f.requestName}`,url:f.url,eventStart:S-this.callStartTime,trouterReady:-1,requestReady:-1,status:-1,attempts:[],rtt:-1,uid:f.requestId,causeId:f.causeId,requestDispatcherConfig:v,enableRequestHedging:this.shouldEnableRequestHedging(v)}),this.addPendingRequest=g=>(this.pendingRequests[g.requestName]||(this.pendingRequests[g.requestName]={}),this.pendingRequests[g.requestName][g.requestId]={dispatcher:null,requestPromise:null,aborted:!1},this.pendingRequests[g.requestName][g.requestId]),this.sendRequest=(g,f)=>{if(!f.url){this.logger.error(f.requestName,"Link does not exist");const g={code:an.CALL_END_CODE.HTTP_OTHER_ERROR,subCode:an.CALL_END_SUB_CODE.MISSING_REQUEST_URI,phrase:`Link does not exist for requestName: ${f.requestName}.`};return Promise.reject(g)}f.requestId||(f.requestId=newGuid()),f.causeId||(f.causeId=causeId2());let S=!1,v=!1;const C=this.logger.createChild(`[${f.causeId}][${f.requestName}]`);C.info("[scheduled]");const _=this.getInternalHttpDispatcherConfig(f.requestName,f.operationType);let T;f.skipHttpTelemetry||(f.skipHttpTelemetry=!1);const I=build3(),b=(new Date).getTime(),A=[],P=this.buildRequestTelemetry(g,f,b,_),updateRequestTelemetry=()=>{this.signalingSession.disposed?this.logger.info("Unable to record telemetry, session disposed"):this.signalingSession.telemetryHelper.updateNetworkRequest(P)},deleteRequestTelemetry=()=>{this.signalingSession.telemetryHelper.deleteNetworkRequest(P)};updateRequestTelemetry();const logRequestAttempt=(g,S,_)=>{if(!g?.request)return void this.logger.warn(f.requestName,"missing request details, unable to record for telemetry!");C.info(`[finished][status=${g.request.status}][statusText=${g.request.statusText}][retryCount=${g.attempt}]`);const T=g.request.status,I=g.request.response?.operationFailure?.subCode,A={status:T,statusSubCode:I,start:g.attemptStartTimestamp-b,end:g.attemptResponseTimestamp-b,online:isTrouterAndNavigatorConnected(this.signalingSession.signalingAgentConfig.trouterServiceProvider)};g.abandoned&&(A.abandoned=!0),g.request.statusText&&(A.statusText=g.request.statusText),!S&&v||(P.status=T,P.statusSubCode=_||I),(S||!v&&T>=200&&T<400)&&(v=!0),P.attempts.push(A),updateRequestTelemetry()};if(this.hasPendingRequest(f.requestName,f.requestId))return this.logger.warn(f.requestName,f.requestId,"is already pending request!!"),this.pendingRequests[f.requestName][f.requestId].requestPromise;T=this.addPendingRequest(f);const recordTelemetryAndCleanup=(g,S,v,_)=>{if(g&&f.skipHttpTelemetry)return this.logger.info("Skipping telemetry"),void deleteRequestTelemetry();C.info(`[steps=${A}]`),this.pendingRequests[f.requestName][f.requestId].aborted&&(P.aborted=!0),this.hasPendingRequest(f.requestName,f.requestId)?(delete this.pendingRequests[S][v],Object.keys(this.pendingRequests[S]).length||delete this.pendingRequests[S]):this.logger.warn("Unable to clean up!"),this.signalingSession.disposed||(_&&(P.error=_),P.rtt=I.duration(),this.signalingSession.telemetryHelper.addNetworkOperationCompleted(f.requestName,g,I.duration()),updateRequestTelemetry(),this.signalingSession.telemetryHelper.sendHttpTelemetryData(P.uid))},checkIfNotDisposed=g=>(...S)=>{if(this.signalingSession.disposed){const g=`[${f.causeId}][${f.requestName}][failed][reason=Session disposed]`;throw C.info("[failed][reason=Session disposed]"),new Error(g)}if(this.hasPendingRequest(f.requestName,f.requestId)&&this.pendingRequests[f.requestName][f.requestId].aborted){let g;const S=`[${f.causeId}][${f.requestName}][failed][reason=request already aborted]`,v=this.pendingRequests[f.requestName][f.requestId].errorDetails;throw v?(g=v,g.phrase=S):g=S,C.info(`${S}`),new Error(JSON.stringify(g))}return g(...S)},R=checkIfNotDisposed((()=>(A.push("[waitForTrouter]"),f.withoutTrouter?Promise.resolve():this.signalingSession.ensureMessageChannelReady(f.requestName)))),M=checkIfNotDisposed((()=>(A.push("[trouterReady]"),P.trouterReady=I.duration(),f.onceTrouterReady&&f.onceTrouterReady(),updateRequestTelemetry(),Promise.resolve()))),w=checkIfNotDisposed((()=>{const S=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,v=this.signalingSession.signalingAgentConfig.enableFetchApi||f.useFetch,C=getTokenMetadata(this.signalingSession.signalingAgentConfig,S,g,f,!1,void 0,this.logger);return A.push("[buildRequest]"),get3({signalingSession:this.signalingSession,operation:f.requestName,data:f.payload,customHeaders:f.customHeaders?.getAll(),causeId:f.causeId,tokenRequestOptions:C,requestId:f.requestId,useFetch:v,fetchUseKeepAlive:f.fetchUseKeepAlive},this.logger)})),O=checkIfNotDisposed((g=>{A.push("[failedToBuildRequestOptions]");const f={request:{status:an.HTTP_STATUS_CODES.OTHER,statusText:"Local error"},attempt:1,success:!1,attemptResponseTimestamp:(new Date).getTime(),attemptStartTimestamp:(new Date).getTime()};let v;return g&&(g.skypeTokenError?(f.request={status:an.CALL_END_SKYPE_TOKEN_ERROR.code,statusText:an.CALL_END_SKYPE_TOKEN_ERROR.phrase},v=an.CALL_END_SKYPE_TOKEN_ERROR.subCode):g.tokenError?(f.request={status:an.CALL_END_TOKEN_ERROR.code,statusText:an.CALL_END_TOKEN_ERROR.phrase},v=g.errorSubCode&&g.errorSubCode>0?g.errorSubCode:an.CALL_END_TOKEN_ERROR.subCode):g.tokenTimeoutError&&(S?(f.request={status:an.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.code,statusText:an.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.phrase},v=an.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.subCode,g.tokenInteractivityRequiredTimeout=!0):(f.request={status:an.CALL_END_TOKEN_TIMEOUT_ERROR.code,statusText:an.CALL_END_TOKEN_TIMEOUT_ERROR.phrase},v=an.CALL_END_TOKEN_TIMEOUT_ERROR.subCode))),logRequestAttempt(f,!1,v),Promise.reject(g)})),D=checkIfNotDisposed((g=>(A.push("[requestBuilt]"),P.requestReady=I.duration(),g.usedCachedSkypetoken&&(P.usedCachedSkypetoken=g.usedCachedSkypetoken),updateRequestTelemetry(),Promise.resolve(g)))),authRequiredCallback=(v,C,_)=>{A.push("[authRequired]"),_?.IPCAFailure&&(S=!0);const T=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,I=getTokenMetadata(this.signalingSession.signalingAgentConfig,T,g,f,!0,v,this.logger);return I.invalidToken=C,get3({signalingSession:this.signalingSession,operation:f.requestName,data:f.payload,customHeaders:f.customHeaders?.getAll(),causeId:f.causeId,forceFetchToken:!0,tokenRequestOptions:I,requestId:f.requestId},this.logger)},N=checkIfNotDisposed((S=>{A.push("[sendRequest]");const v={..._,enableRequestHedging:this.shouldEnableRequestHedging(_),hedgeDelayMs:_.hedgeDelayMs,hedgeMaxParallelAttempts:this.signalingSession.signalingAgentConfig.hedgeMaxParallelAttempts,retryIntervalsMs:f.disableRetry||!_.retryIntervalsMs?[]:_.retryIntervalsMs,reportPreviousErrorsForTimeout:this.signalingSession.signalingAgentConfig.reportPreviousErrorsForTimeout},C=build4({logger:this.logger,causeId:f.causeId,dispatcher:this.signalingSession.signalingAgentConfig.httpRequestDispatcher,url:f.url,request:S,requestType:g,authRequiredCallback:authRequiredCallback,attemptFailureCallback:g=>{logRequestAttempt(g,!1)},settings:v});return T.dispatcher=C,updateRequestTelemetry(),C.sendRequest()})),k=checkIfNotDisposed((async g=>(logRequestAttempt(g,!0),C.info("[success]"),recordTelemetryAndCleanup(!0,f.requestName,f.requestId),g))),onFailure=g=>{const S=getPrintableObject(g);return recordTelemetryAndCleanup(!1,f.requestName,f.requestId,S),!g||g.readyState||g.status?C.info(`[failed][reason=${S}]`):C.info(`[failed][offline][reason=${S}]`),Promise.reject(g)},L=Promise.resolve().then(R).then(M).then(w).catch(O).then(D).then(N).then(k).catch(onFailure);return T.requestPromise=L,L},this.logger=this.signalingSession.logger.createChild("[HTTP]")}getInternalHttpDispatcherConfig(g,f="Other"){let S={...On.Default,...Dn[f],...On[g]};return this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap&&(S={...S,...this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap[f]}),this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap&&(S={...S,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap.Default,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap[g]}),this.logger.info(`getInternalHttpDispatcherConfig request type: ${g} config: ${safeJsonStringify(S)}`),S}shouldEnableRequestHedging(g){return!!(this.signalingSession.getMeetingInfo()&&g.requestHedgingCapability.indexOf("enabledForMeetings")>-1)||(!this.signalingSession.multiParty&&g.requestHedgingCapability.indexOf("enabledForP2PCalls")>-1||(!!(this.signalingSession.multiParty&&g.requestHedgingCapability.indexOf("enabledForGroupCalls")>-1)||g.requestHedgingCapability.indexOf("enabled")>-1))}};function getPayload8(g,f,S){assertNotNull(g,"signalingSession cannot be null");let v=[];S&&(v=getMediaTypes(S),g.telemetryHelper.addOutgoingModalities(v));const C=causeId2();return{payload:{mediaNegotiation:{callModalities:v,sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},links:{mediaAnswer:get2(g,rn.MEDIA_ANSWER,C),rejection:get2(g,rn.MEDIA_REJECTION,C)},mediaContent:f}}}}function getPayload9(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{mediaNegotiationFailure:{sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},code:f.code,subCode:f.subCode,phrase:f.phrase},debugContent:{callId:g.correlationId,endpointId:g.participantManager.localParticipant.endpointId}}}}function getPayload10(g,f,S){assertNotNull(g,"signalingSession cannot be null");let v=[];return S&&(v=getMediaTypes(S),g.telemetryHelper.addOutgoingModalities(v)),{payload:{mediaAnswer:{callModalities:v,sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},links:{mediaAcknowledgement:get2(g,rn.MEDIA_ACKNOWLEDGEMENT)},clientContentForMediaController:g.webRtcSignalingManager.getClientUrls(),mediaContent:f},debugContent:{callId:g.correlationId,endpointId:g.participantManager.localParticipant.endpointId}}}}var $n=class{constructor(g,f,S){this.telemetryHelper=S,this.vbssInitiated=!1,this.disposed=!1,this.fsmState=an.MEDIA_RENEGOTIATION_FSM_STATE.IDLE,this.fsmStateCauseId="",this.links={},this.renegotiationOffersSeenSoFar=[],this.isOutgoingRenegotiationInProgress=()=>this.fsmState===an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION||this.fsmState===an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.isIncomingRenegotiationInProgress=()=>this.fsmState===an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION||this.fsmState===an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.acceptRenegotiationAsync=(g,f,S)=>{this.logger.info(`[${S}][acceptRenegotiationAsync][mediaTypes=${f}]`),this.signalingSession.telemetryHelper.recordEvent(dn.ACCEPT_RENEGOTIATION,{mediaTypes:f,causeId:S}),assertNotNullOrEmpty(this.links[an.LINKS.MEDIA_ANSWER],"MediaAnswer link not set");const v=defer();switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,S);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,S);break;default:return this.logger.info(`[${S}][acceptRenegotiationAsync]there is no incoming media renegotiation offer to accept`),v.reject(new Error("there is no incoming media renegotiation offer to accept")),v.promise}const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT,this.handleMediaAnswerAcknowledgmentTimeout.bind(this,S),an.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_ACKNOWLEDGEMENT_TIMEOUT)};return this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.MEDIA_ANSWER],payload:getPayload10(this.signalingSession,g,f),requestName:hn.SEND_MEDIA_ANSWER.name,onceTrouterReady:onceTrouterReady,causeId:S}).then((g=>{v.resolve(g.response)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][acceptRenegotiationAsync] error: ${getPrintableObject(f)}`),this.disposed||this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),v.reject(new Error(`acceptRenegotiationAsync failed because : ${getPrintableObject(g)}`))})),v.promise},this.startRenegotiationAsync=(g,f,S,v)=>{this.logger.info(`[${v}][startRenegotiationAsync][mediaTypes=${S}]`),this.signalingSession.telemetryHelper.recordEvent(dn.START_RENEGOTIATION,{causeId:v,mediaTypes:S}),assertNotNullOrEmpty(f,"MediaRenegotiation link not set");const C=defer();switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,v);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:case an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.logger.info(`[${v}][startRenegotiationAsync][failed] can only be performed with no current outstanding renegotiations, previous negotiation causeId=${this.fsmStateCauseId}`),this.signalingSessionCallback.onMediaRenegotiationRejection(this.getGlareError(),v),Promise.resolve(null);default:return this.logger.info(`[${v}][startRenegotiationAsync][failed] can only be performed on an established call`),C.reject(new Error("media renegotiation can only be performed on an established call")),C.promise}const _=S&&arrayContains(S,an.MEDIA_TYPES.SCREEN_SHARER);_?(this.vbssInitiated=!0,this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.START)):!_&&this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.STOP));const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER,this.handleMediaAnswerTimeout.bind(this),an.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_TIMEOUT)};return this.signalingSession.http.sendPostRequest({url:f,payload:getPayload8(this.signalingSession,g,S),requestName:hn.START_RENEGOTIATION.name,onceTrouterReady:onceTrouterReady,causeId:v}).then((g=>{C.resolve(g.response)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${v}][startRenegotiationAsync] error: ${getPrintableObject(f)}`),!this.disposed){switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,v);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,v)}this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER)}C.reject(new Error(`startRenegotiationAsync failed because : ${getPrintableObject(g)}`))})),C.promise},this.handleMediaAcknowledgment=(g,f)=>{this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ACKNOWLEDGEMENT,{causeId:f}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),this.signalingSession.saveMediaControllerLinksIfAny(g),this.signalingSession.saveUpdatedCallLinksIfAny(g),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!0,f)},this.onCallConnected=g=>{this.logger.info("onCallConnected"),this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,g)},this.handleMediaNegotiationFailure=g=>{const f=extractCauseIdFromMessage(g);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_MEDIA_NEGOTIATION_FAILURE,g),this.handleMediaNegotiationFailureInternal(g.body.mediaNegotiationFailure,g.origin,f)},this.handleMediaAnswer=(g,f)=>{switch(this.logger.info(`[${f}][handleMediaAnswer]`),this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ANSWER,{causeId:f}),this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,f);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,f);break;default:return}this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER);let S=[];g.mediaAnswer.callModalities&&g.mediaAnswer.callModalities.length>0&&(S=getMediaTypes(g.mediaAnswer.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(S));const v={provisional:!1,renegotiation:!0,mediaTypes:S,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(g.mediaAnswer.mediaContent),mediaContent:g.mediaAnswer.mediaContent};this.signalingSession.http.sendPostRequest({url:g.mediaAnswer.links.mediaAcknowledgement,payload:null,requestName:hn.SEND_MEDIA_ACKNOWLEDGEMENT.name,causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);this.logger.info(`[${f}][handleMediaAnswer] error: ${getPrintableObject(S)}`),this.signalingSession.disposed||this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ANSWER_FAILED,{causeId:f})})),this.signalingSessionCallback.onAnswer(v,f)},this.handleMediaNegotiationOffer=g=>{const f=g.body,S=g.headers,v=extractCauseIdFromMessage(g);this.logger.info(`[${v}][handleMediaNegotiationOffer]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_MEDIA_OFFER,g);const C=isDuplicateMessage(S,this.renegotiationOffersSeenSoFar);switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,v),this.raiseMediaRenegotiationOffer(f,v);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,v),this.raiseMediaRenegotiationOffer(f,v);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:if(this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.supportMediaRetargetWhileIncomingRenegotiation){this.raiseMediaRenegotiationOffer(f,v);break}this.rejectAndLog(v,C,f);break;default:this.rejectAndLog(v,C,f)}},this.rejectRenegotiationAsync=(g,f)=>{this.logger.info(`[${f}][rejectRenegotiationAsync]`),this.signalingSession.telemetryHelper.recordEvent(dn.REJECT_RENEGOTIATION,{rejectionData:g,causeId:f}),assertNotNullOrEmpty(this.links[an.LINKS.MEDIA_REJECTION],"MediaRejection link not set");const S=g||{code:an.CALL_END_CODE.NOT_ACCEPTABLE_HERE,subCode:an.CALL_END_SUB_CODE.MEDIA_ANSWER_PROCESSING_ERROR,phrase:an.CALL_END_PHRASE.MEDIA_ANSWER_ERROR};switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:return this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,f),this.rejectMediaRenegotiation(this.links[an.LINKS.MEDIA_REJECTION],S,f);case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,f),this.rejectMediaRenegotiation(this.links[an.LINKS.MEDIA_REJECTION],S,f);default:return this.logger.error(`[${f}][rejectRenegotiationAsync][failed] There is no incoming media renegotiation offer to reject`),Promise.resolve(null)}},this.handleRetargetCompleted=g=>{const f=g.body.retargetCompleted,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleRetargetCompleted][details=${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_RETARGET_COMPLETED,g,getPIISafeObject(f)),0===f.code?this.signalingSessionCallback.onReTargetCompletedSuccess(S):this.signalingSessionCallback.onReTargetCompletedFailure(f,S)},this.dispose=()=>{this.logger.info("mediaRenegotiationManager :: dispose"),this.disposed=!0},this.getGlareError=()=>({code:an.CALL_END_CODE.GLARE_ERROR,subCode:an.CALL_END_SUB_CODE.MEDIA_GLARE_ERROR,phrase:an.CALL_END_PHRASE.RENEGOTIATION_IN_PROGRESS,previousNegotiationCauseId:this.fsmStateCauseId}),this.handleMediaNegotiationFailureInternal=(g,f,S)=>{switch(this.logger.info(`[${S}][handleMediaNegotiationFailureInternal][failureData=${getPIISafeObject(g)}]`),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,S);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,S);break;default:return}this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.REJECTED)),this.signalingSession.telemetryHelper.addIncomingModalities(["Rejected"]),this.signalingSessionCallback.onMediaRenegotiationRejection({code:g.code,subCode:g.subCode,phrase:g.phrase},S)},this.signalingSession=g,this.signalingSessionCallback=f,this.logger=g.logger.createChild((()=>`[RenegotiationManager][${this.fsmState}][stateCauseId=${this.fsmStateCauseId}]`))}rejectAndLog(g,f,S){this.logger.error(`[${g}][handleMediaNegotiationOffer] Cannot handle the incoming mediaRenegotiation offer in present callstate. Either call not connected or renegotiation in progress. isDuplicateOffer=${f}`),f||this.rejectMediaRenegotiation(S.mediaNegotiation.links.rejection,this.getGlareError(),g)}setFsmState(g,f){this.fsmState=g,this.fsmStateCauseId=f,this.logger.info(`[setFsmState]state=${g}`),this.telemetryHelper.recordEvent(dn.MEDIA_FSM_STATE_CHANGED,{state:g,causeId:f})}raiseMediaRenegotiationOffer(g,f){this.logger.info(`[${f}][raiseMediaRenegotiationOffer]`),this.links[an.LINKS.MEDIA_ANSWER]=g.mediaNegotiation.links.mediaAnswer,this.links[an.LINKS.MEDIA_REJECTION]=g.mediaNegotiation.links.rejection;let S=[];g.mediaNegotiation.callModalities&&g.mediaNegotiation.callModalities.length>0&&(S=getMediaTypes(g.mediaNegotiation.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(S),arrayContains(S,an.MEDIA_TYPES.SCREEN_SHARER)&&this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.REMOTE_START));const v={mediaTypes:S,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(g.mediaNegotiation.mediaContent),mediaContent:g.mediaNegotiation.mediaContent,renegotiation:!0};this.signalingSessionCallback.onOffer(v,f)}rejectMediaRenegotiation(g,f,S){this.logger.info(`[${S}][rejectMediaRenegotiation][rejectionData=${getPIISafeObject(f)}]`);const v=defer();return this.signalingSession.http.sendPostRequest({url:g,payload:getPayload9(this.signalingSession,f),requestName:hn.SEND_MEDIA_REJECTION.name,causeId:S}).then((g=>{v.resolve(g.response)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][rejectMediaRenegotiation] error: ${getPrintableObject(f)}`),v.reject(new Error(`rejectMediaRenegotiation failed because : ${getPrintableObject(g)}`))})),v.promise}handleMediaAnswerTimeout(g){this.logger.info(`[${g}][handleMediaAnswerTimeout]`),this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.TIMEOUT)),this.signalingSession.telemetryHelper.addIncomingModalities(["Timeout"]),this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ANSWER_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.handleMediaNegotiationFailureInternal({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.MEDIA_FINAL_ANSWER_TIMEOUT,phrase:an.CALL_END_PHRASE.MEDIA_FINAL_ANSWER_TIMEOUT},un.EVENT_SOURCE.LOCAL,g)}handleMediaAnswerAcknowledgmentTimeout(g){this.logger.info(`[${g}][handleMediaAnswerAcknowledgmentTimeout]`),this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ACKNOWLEDGEMENT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT);const f={reason:"timed out waiting for Media Answer Acknowledgement"};this.signalingSessionCallback.onMediaAcknowledgementFailure(!0,f,g)}},jn=class{constructor(){this.requests={}}clear(g,f){const S=f||{code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((f=>{this.rejectOperation(f,g,S)}))}hasOperation(g){return this.requests.hasOwnProperty(g)}getAllOperations(){return this.requests}getOperation(g){return this.hasOperation(g)?this.requests[g]:null}setOperation(g,f){return!this.hasOperation(g)&&(this.requests[g]=f,!0)}rejectOperation(g,f,S){const v=new Error(f);if(S&&(v.endCode=S),this.hasOperation(g)){const f=this.requests[g].promise;delete this.requests[g],f.reject(v)}}resolveOperation(g,f){if(this.hasOperation(g)){const S=this.requests[g].promise;delete this.requests[g],S.resolve(f)}}},Gn=class{constructor(g){this.logger=g,this.localAddParticipantRequests=new jn,this.localAdmitParticipantRequests=new jn,this.localCallMeBackRequests=new jn,this.localRemoveParticipantEndpointRequests=new jn,this.localRemoveParticipantRequests=new jn,this.localUpdateParticipantInterpretationStateRequest=new jn,this.participantIdMriMap=new Map}dispose(g,f,S){this.logger.info(`[${S}][dispose]`),this.rejectAllPendingOperations(g,f)}getAllPendingOperations(g,f){this.logger.info(`[${f}][getAllPendingOperations] ${g}`);const S=this.getOperationTable(g);return S?S.getAllOperations():null}getPendingOperation(g,f,S){this.logger.info(`[${S}][getPendingOperation] ${g} ${f}`);const v=this.getOperationTable(g);return v?v.getOperation(f):null}getRnlMri(g,f){this.logger.info(`[${f}][getRnlMri] ${g}`);for(const f of g)if(this.participantIdMriMap.has(f))return this.participantIdMriMap.get(f);return""}hasPendingOperation(g,f,S){this.logger.info(`[${S}][hasPendingOperation] ${g} ${scrubMriOrOmit(f)}`);const v=this.getOperationTable(g);return!!v&&v.hasOperation(f)}rejectPendingOperation(g,f,S,v,C){this.logger.info(`[${C}][rejectPendingOperation] ${g} ${scrubMriOrOmit(f)} reason: ${S}`);const _=this.getOperationTable(g);_&&_.rejectOperation(f,S,v)}resolvePendingOperation(g,f,S,v){this.logger.info(`[${v}][resolvePendingOperation]: ${scrubMriOrOmit(f)}`);const C=this.getOperationTable(g);C&&C.resolveOperation(f,S)}setPendingOperation(g,f,S,v){this.logger.info(`[${v}][setPendingOperation] ${g} ${scrubMriOrOmit(f)} value: ${S}`);const C=this.getOperationTable(g);if(!C)return!1;if(0===g){const g=S&&S.participant&&S.participant.participantId;g&&this.participantIdMriMap.set(g,f)}return C.setOperation(f,S)}setParticipantIdToMriMapping(g,f,S,v){v?(this.logger.info(`[${S}][setParticipantIdMriMap] ${mriOrId(g)}: ${scrubMriOrOmit(f)} clear mapping.`),this.participantIdMriMap.delete(g)):g&&f&&(this.logger.info(`[${S}][setParticipantIdMriMap] ${mriOrId(g)}: ${scrubMriOrOmit(f)}`),this.participantIdMriMap.set(g,f))}getOperationTable(g){switch(g){case 0:return this.localAddParticipantRequests;case 1:return this.localAdmitParticipantRequests;case 2:return this.localCallMeBackRequests;case 4:return this.localRemoveParticipantEndpointRequests;case 3:return this.localRemoveParticipantRequests;case 5:return this.localUpdateParticipantInterpretationStateRequest;default:return null}}rejectAllPendingOperations(g,f){this.logger.info("rejectLocalQueuedOperations"),this.localAddParticipantRequests.clear(g,f),this.localAdmitParticipantRequests.clear(g,f),this.localCallMeBackRequests.clear(g,f),this.localRemoveParticipantRequests.clear(g,f),this.localRemoveParticipantEndpointRequests.clear(g,f),this.localUpdateParticipantInterpretationStateRequest.clear(g,f)}};function getPayload11(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");const C=S.groupId?{id:S.groupId}:null,_=S.threadId?{threadId:S.threadId,messageId:S.messageId||null}:null;let T=[],I={};f&&f.length>0?(T=f.map((f=>({id:f.nonMaskedId?f.nonMaskedId:f.id,assertedId:f.assertedId,displayName:f.displayName,participantId:f.participantId,replacementDetails:3===S.replacementType?g.getReplacementDetailsByParticipantLegOfCall(S.callIdToReplace,f.id,f.replacementParticipantId):void 0}))),I={addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE)}):I={addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE)};const b={payload:{disableUnmute:S&&S.disableUnmute,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},to:T},participantInvitationData:getParticipantInvitationData(S),replacementDetails:3===S.replacementType?void 0:v,groupContext:C,groupChat:_,links:I}};return S&&S.alternateId&&(b.payload.participants.from.alternateId=S.alternateId),S?.callingLineIdentity&&(b.payload.participants.from.callingLineIdentity=S.callingLineIdentity),S?.clientScenario&&(b.payload.debugContent={clientScenario:S.clientScenario}),b}function getPayload12(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");const C=f.map((g=>(assertNotNull(g,"remoteParticipant cannot be null"),{id:g.id,assertedId:g.assertedId,displayName:g.displayName,participantId:g.participantId})));return{payload:{disableUnmute:S&&S.disableUnmute,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,alternateId:S?S.alternateId:null,callingLineIdentity:S?S.callingLineIdentity:null},to:C},participantInvitationData:getParticipantInvitationData(S),replacementDetails:v,links:{addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE)},debugContent:{clientScenario:S.clientScenario}}}}function getPayload13(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},to:[{id:f.id,displayName:f.displayName}]},links:{admitFailure:get2(g,rn.CONV_ADMIT_PARTICIPANT_FAILURE),admitSuccess:get2(g,rn.CONV_ADMIT_PARTICIPANT_SUCCESS)},debugContent:{causeId:S}}}}function getPayload14(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},mediaTypes:["audio"]}}}function getPayload15(g,f,S,v=!1,C=null){assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"muteScope be null"),assertNotNull(S,"participantList cannot be null");const _={from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:f,muteParticipants:S,mediaTypes:["audio"]};return v&&(_.links={clientCallback:get2(g,rn.MUTE_UNMUTE_ASYNC,C)},_.operationId=C),{payload:_}}function getPayload16(g,f,S,v,C,_){assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"participantsIds cannot be null");const T=g.groupId?{id:g.groupId}:null,I=v?{threadId:v,messageId:C||null}:null,b=[];return f.forEach((g=>{const f={id:g};b.push(f)})),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},invitationType:an.INVITATION_TYPE.NUDGE,to:b},participantInvitationData:_,groupContext:T,groupChat:I,links:{nudgeParticipantSuccess:get2(g,rn.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:get2(g,rn.CONV_NUDGE_PARTICIPANT_FAILURE)}}}}function getPayload17(g,f,S){assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"participantsIds cannot be null");const v=[];return f.forEach((g=>{const f={id:g};v.push(f)})),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},invitationType:an.INVITATION_TYPE.NUDGE,to:v},participantInvitationData:S,links:{nudgeParticipantSuccess:get2(g,rn.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:get2(g,rn.CONV_NUDGE_PARTICIPANT_FAILURE),addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE)}}}}function getPayload18(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{transactionEnd:f}}}function getPayload19(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:S,toEndpoints:[{id:f.id,endpointId:f.endpointId}]},links:{removeParticipantSuccess:get2(g,rn.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:get2(g,rn.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function getPayload20(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},to:[{id:f.id,displayName:f.displayName}]},links:{removeParticipantSuccess:get2(g,rn.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:get2(g,rn.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function getPayload21(g,f=!1,S=null){assertNotNull(g,"signalingSession cannot be null");const v={from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},mediaTypes:["audio"]};return f&&(v.links={clientCallback:get2(g,rn.MUTE_UNMUTE_ASYNC,S)},v.operationId=S),{payload:v}}function getPayload22(g,f,S,v=""){assertNotNull(S&&"specified"===S,"Only non-null non-empty scope of 'specified' is supported."),assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"participantsIds cannot be null");const C=[];return f.forEach((g=>{const f={id:g,meetingRole:v};C.push(f)})),{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:S,to:C}}}function getUpdateParticipantInterpretationStatePayload(g,f,S){assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"options cannot be null");return{payload:{from:{id:g.participantManager.localParticipant.id},to:f,links:{updateParticipantInterpretationStateStatus:get2(g,rn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS)},operationId:S}}}var qn=__toESM(M),Wn=class{constructor(g,f){this.participantManager=g,this.logger=f,this.handleRosterUpdate=(g,f,S,v)=>{if("Delta"===g.type||"MultiPartyEndpoint"===g.type){if(void 0===g.sequenceNumber&&(g.sequenceNumber=this.lastRosterUpdateSeqNumber),this.logger.info(`[${v}][handleRosterUpdate][sequenceNumber=${g.sequenceNumber}]`),this.rostersInLifetime.add(g.sequenceNumber),"Delta"===g.type)this.logger.info(`[${v}][handleRosterUpdate], RosterType: Delta, isFullRoster: ${S}`),this.handleDeltaRoster(g,S,f,v);else{if(this.logger.info(`[${v}][handleRosterUpdate], RosterType: MultiPartyEndpoint`),this.isRosterStale(g,v))return this.participantManager.signalingSession.telemetryHelper.recordEvent(dn.IGNORE_OLD_ROSTER,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,sequenceNumber:g.sequenceNumber,causeId:v}),void this.logger.info(`[${v}][handleRosterUpdate] Ignoring old roster update: received ${g.sequenceNumber}, but already handled ${this.lastRosterUpdateSeqNumber}`);for(const S of Object.keys(g.participants)){const C=cn.fromRoster(g.participants[S]);this.handleRosterParticipant(C,f,v)}this.checkForRemovedParticipants(f,g.participants,v),this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(g.participantCounts,v)}if(g.sequenceNumber>this.lastRosterUpdateSeqNumber){this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(g.participantCounts,v),this.lastRosterUpdateSeqNumber=g.sequenceNumber,this.firstRosterUpdateSeqNumber<0&&(this.firstRosterUpdateSeqNumber=this.lastRosterUpdateSeqNumber);const f=Object.keys(g.participants||0).length;this.participantCountInFirstRoster<0&&(this.participantCountInFirstRoster=f),this.maxConcurrentParticipantsDuringLeg=Math.max(this.maxConcurrentParticipantsDuringLeg,f)}this.recordTelemetry(g,S,v),this.participantManager.signalingSessionCallback.onRosterHandlingComplete()}else this.logger.warn(`[${v}][handleRosterUpdate][sequenceNumber=${g.sequenceNumber}] invalid roster type ${g.type}`)},this.isRosterStaleFromFull=(g,f)=>(this.logger.info(`[${f}][isRosterStale] ${g.sequenceNumber<this.lastFullRosterSeqNumber}`),g.sequenceNumber<this.lastFullRosterSeqNumber),this.isRosterStale=(g,f)=>(this.logger.info(`[${f}][isRosterStale] ${g.sequenceNumber<this.lastRosterUpdateSeqNumber}`),g.sequenceNumber<this.lastRosterUpdateSeqNumber),this.updateLocalParticipantFromSubscribe=(g,f)=>{this.logger.info(`[${f}][updateLocalParticipantFromSubscribe]`),this.updateLocalParticipant(g,f)},this.handleParticipantAcceptedBy=(g,f,S)=>{const v=f.hasOwnProperty(g.id),C=g.id===g.acceptedBy.id;this.logger.info(`[${S}][RosterManager::handleParticipantAcceptedBy] oldParticipantInRoster: ${v}`);this.participantManager.participantOperationHandler.setParticipantIdToMriMapping(g.participantId,g.id,S,!0),v&&!C&&this.handleRemovedDeltaRosterParticipant(new cn({id:g.id}),this.lastRosterUpdateSeqNumber,f,S)},this.lastRosterUpdateSeqNumber=-1,this.lastFullRosterSeqNumber=-1,this.firstRosterUpdateSeqNumber=-1,this.tombstoneSequence=new Map,this.latestRosterVersionForActiveParticipants=new Map,this.rostersInLifetime=new Set,this.maxConcurrentParticipantsDuringLeg=-1,this.participantCountInFirstRoster=-1}recordTelemetry(g,f,S){const v={participantCountInLastRoster:Object.keys(g.participants||0).length,participantCountInFirstRoster:this.participantCountInFirstRoster,sequenceNumberOfLastRoster:this.lastRosterUpdateSeqNumber,sequenceNumberOfLastFullRoster:this.lastFullRosterSeqNumber,sequenceNumberOfFirstRoster:this.firstRosterUpdateSeqNumber,rosterType:g.type,isFullRoster:f,maxConcurrentParticipantsDuringLeg:this.maxConcurrentParticipantsDuringLeg,totalParticipantsDuringLifetimeOfLeg:this.tombstoneSequence.size+this.latestRosterVersionForActiveParticipants.size,countOfMissingNotifications:this.getMissingNotificiations()};this.logger.info(`[recordTelemetry] data ${JSON.stringify(v,null,4)}`),this.participantManager.signalingSession.telemetryHelper.recordRosterEvent(v,dn.HANDLE_ROSTER_UPDATE,S)}getMissingNotificiations(){const g=this.lastRosterUpdateSeqNumber-this.firstRosterUpdateSeqNumber+1-this.rostersInLifetime.size;return g>0?g:0}isParticipantRosterStale(g,f){if(this.logger.info(`[isParticipantRosterStale], rosterParticipantVersion ${f}`),f){if(this.tombstoneSequence.has(g))return f<=this.tombstoneSequence.get(g);if(this.latestRosterVersionForActiveParticipants.has(g))return f<=this.latestRosterVersionForActiveParticipants.get(g)}return!1}handleDeltaRoster(g,f,S,v){if(this.logger.info(`[${v}][handleDeltaRoster] isFullRoster ${f}`),this.isRosterStaleFromFull(g,v))return this.participantManager.signalingSession.telemetryHelper.recordEvent(dn.IGNORE_OLD_ROSTER,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,lastFullRosterSeqNumber:this.lastFullRosterSeqNumber,sequenceNumber:g.sequenceNumber,causeId:v}),void this.logger.info(`[${v}][handleRosterUpdate] Ignoring old roster update: received ${g.sequenceNumber}, but already handled full roster ${this.lastFullRosterSeqNumber}`);if(f){for(const f of Object.keys(S))if(!g.participants.hasOwnProperty(f)&&!this.isParticipantRosterStale(f,g.sequenceNumber)){const C=new cn({id:f});this.logger.info(`[${v}][handleRosterUpdate] participant missing from delta, full roster`),this.handleRemovedDeltaRosterParticipant(C,g.sequenceNumber,S,v)}this.lastFullRosterSeqNumber=g.sequenceNumber}else if(!g?.participants)return void this.logger.warn(`[${v}][handleRosterUpdate] participants blob empty in delta roster`);for(const f of Object.keys(g.participants)){const C=g.participants[f];if(!this.isParticipantRosterStale(f,C.version)){let g=cn.fromRoster(C);C.state&&"active"===C.state?(this.logger.info(`[${v}][handleDeltaRoster] participant active`),this.handleRosterParticipant(g,S,v),this.tombstoneSequence.has(f)&&this.tombstoneSequence.delete(f),this.latestRosterVersionForActiveParticipants.set(f,C.version)):C.state&&"inactive"===C.state?(g=g||new cn({id:C.details.id}),this.logger.info(`[${v}][handleDeltaRoster] participant inactive`),this.handleRemovedDeltaRosterParticipant(g,C.version,S,v)):this.logger.info(`[${v}][handleDeltaRoster] unexpected participant state ${C.state}`)}}this.handleRemoveParticipantRequests(this.getActiveParticipants(g.participants),v)}getRnlMri(g,f){const S=this.participantManager.participantOperationHandler;if(g){const v=this.getRnlParticipantIdsFromRoster(g,f);return S.getRnlMri(v,f)}return""}handleRemovedDeltaRosterParticipant(g,f,S,v){const C=g.id,_=this.getRnlMri(g,v);let T="";S.hasOwnProperty(C)?T=C:S.hasOwnProperty(_)&&(T=_),T&&this.handleRemovedParticipant(S,T,v),this.tombstoneSequence.set(C,f),this.latestRosterVersionForActiveParticipants.has(C)&&this.latestRosterVersionForActiveParticipants.delete(C)}handleRemovedParticipant(g,f,S){const v=this.participantManager.signalingSessionCallback,C=this.participantManager.signalingSession;!1!==g[f]&&(tryRemoveKeyFromHashTable(this.participantManager.connectedRemoteParticipantIds,f),this.logger.info(`[${S}][handleRemovedParticipant] ${scrubMriOrOmit(f)} removed from roster`),v.onParticipantRemoved({id:f},S),C.clearParticipantCallLinks(f))}getActiveParticipants(g){const f={};for(const S of Object.keys(g))"inactive"!==g[S].state&&(f[S]=g[S]);return f}handleRosterParticipant(g,f,S){if(!g)return void this.logger.info(`[handleRosterParticipant][${S}] rosterParticipant processing skipped because null.`);if(g.id===this.participantManager.localParticipant.id){this.updateLocalParticipant(g,S);const f=this.getLocalEndpoint(),v=!(!f?.stream&&!f?.streamLobby),C=0===this.participantManager.signalingSession.callMode;return this.logger.info(`[handleRosterParticipant][${S}] isStreaming:${v} isInitialMode:${C}`),void(v&&C?this.participantManager.signalingSession.configureStreamingMode(S):v||this.participantManager.signalingSession.setRealTimeState(1,S))}const v=this.participantManager.participantOperationHandler,C=this.participantManager.signalingSession,_=this.participantManager.signalingSessionCallback,T=g.id,I=this.getRnlMri(g,S),b=this.getRnlParticipantIdsFromRoster(g,S);C.remoteCaller&&-1!==b.indexOf(C.remoteCaller.participantId)&&(g.displayName=C.remoteCaller.displayName),tryAddNewKeyToHashTable(this.participantManager.connectedRemoteParticipantIds,g.id,!0);const A=f.hasOwnProperty(g.id),P=f.hasOwnProperty(I);(A||P)&&(f[g.id]=!1),v.hasPendingOperation(0,g.id,S)&&this.isParticipantInCall(g)?(this.logger.info(`participant ${scrubMriOrOmit(g.id)} appears in roster. Resolving AddParticipant request`),C.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,g.id),v.resolvePendingOperation(0,g.id,g,S)):I&&v.hasPendingOperation(0,I,S)&&this.isParticipantInCall(g)?(this.logger.info(`RNL participant ${scrubMriOrOmit(I)} appears in roster. Resolving AddParticipant request`),C.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,I),v.resolvePendingOperation(0,I,g,S)):v.hasPendingOperation(1,g.id,S)&&this.isParticipantInCall(g)&&(this.logger.info(`participant: ${scrubMriOrOmit(g.id)} appears in roster. Resolving AdmitParticipant request`),C.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,g.id),v.resolvePendingOperation(1,g.id,g,S));for(const f of g.endpointDetails)v.hasPendingOperation(0,f.participantId,S)&&this.isParticipantInCall(g)&&(this.logger.info(`participant ${scrubMriOrOmit(g.id)} appears in roster. Resolving AddParticipant request`),C.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,f.participantId),v.resolvePendingOperation(0,f.participantId,g,S));A?(this.logger.info(`participantIds=[${b}] updated ${scrubMriOrOmit(g.id)}`),_.onParticipantUpdated(g,S),C.setParticipantCallLinks(g)):P?(this.logger.info(`RNL participant participantIds=[${b}] removed old ${scrubMriOrOmit(I)} and added new ${scrubMriOrOmit(T)}`),_.onParticipantRemoved({id:I},S,!0),C.clearParticipantCallLinks(I),_.onParticipantJoined(g,S),C.setParticipantCallLinks(g)):v.hasPendingOperation(3,g.id,S)?this.logger.info(`participantIds=[${b}] ignored ${scrubMriOrOmit(g.id)}`):(this.logger.info(`participantIds=[${b}] joined ${scrubMriOrOmit(g.id)}`),_.onParticipantJoined(g,S),C.setParticipantCallLinks(g))}getLocalEndpoint(){return qn.find(this.participantManager.localParticipant.endpointDetails,(g=>this.participantManager.localParticipant.endpointId===g.endpointId))}getRnlParticipantIdsFromRoster(g,f){const S=[];for(const f of g.endpointDetails)S.push(f.participantId);return this.logger.info(`[${f}][getRnlParticipantIdsFromRoster] ${JSON.stringify(S)}`),S}isParticipantInCall(g){return g.endpointDetails?.[0]&&!g.endpointDetails[0].isLobby}updateLocalParticipant(g,f){const S=this.participantManager.localParticipant,v=this.participantManager.signalingSession,C=this.participantManager.signalingSessionCallback;v.setParticipantCallLinks(g),this.logger.info(`[${f}][updateLocalParticipant]`);let _=!1;if(g?.endpointDetails){const T=qn.find(g.endpointDetails,(g=>S.endpointId===g.endpointId)),I=qn.find(S.endpointDetails,(g=>S.endpointId===g.endpointId));_=hasStagingGroup(T),T?.isLobby&&!I?.isLobby?v.telemetryHelper.recordEvent(dn.IN_LOBBY,{causeId:f}):!T||T.isLobby||I&&!I.isLobby||(_?v.telemetryHelper.recordEvent(dn.STAGING,{causeId:f}):v.telemetryHelper.recordEvent(dn.CONNECTED,{causeId:f})),T?.broadcastMeetingRole&&S&&S.broadcastMeetingRole!==T.broadcastMeetingRole&&(S.broadcastMeetingRole=T.broadcastMeetingRole,v.telemetryHelper.setBroadcastMeetingRole(T.broadcastMeetingRole)),C.onMeetingGroupDetailsUpdated(T?.meetingGroupDetails,f)}if(g?.meetingRole&&v.telemetryHelper.setMeetingRole(g.meetingRole),g?.advancedMeetingRole&&v.telemetryHelper.setAdvancedMeetingRole(g.advancedMeetingRole),g?.meetingRoles&&v.telemetryHelper.setMeetingRoles(g.meetingRoles),g?.participantType&&v.telemetryHelper.setParticipantType(g.participantType),g&&(S.endpointDetails=g.endpointDetails||[],S.acceptedBy=g.acceptedBy,S.role=g.role,S.meetingRole=g.meetingRole,S.advancedMeetingRole=g.advancedMeetingRole,S.meetingRoles=g.meetingRoles,S.participantType=g.participantType,S.tenantId=g.tenantId,S.isLobby=g.isLobby,S.publishedStates=g.publishedStates,S.isStaging=_,S.version=g.version,S.propertyBag=g.propertyBag,S.isIdentityMasked=g.isIdentityMasked,S.maskedIdSeqNumber=g.maskedIdSeqNumber,S.maskedId=g.maskedId,void 0!==g?.joinAsStreamingUser&&(S.joinAsStreamingUser=g.joinAsStreamingUser),void 0!==g?.enableCaptcha&&(S.enableCaptcha=g.enableCaptcha),void 0!==g?.otpIdentity&&(S.otpIdentity=g.otpIdentity),this.participantManager.localParticipant.fromRoster=!0,C.onSelfParticipantUpdated(S,f)),this.isParticipantInCall(g)){const S=this.participantManager.participantOperationHandler,C=this.getRnlMri(g,f);C&&S.hasPendingOperation(0,C,f)&&(this.logger.info(`RNL participant ${scrubMriOrOmit(C)} appears in roster. Resolving AddParticipant request`),v.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,C),S.resolvePendingOperation(0,C,g,f))}}checkForRemovedParticipants(g,f,S){const v=this.participantManager.signalingSessionCallback,C=this.participantManager.signalingSession,_=this.participantManager.participantOperationHandler;this.logger.info(`[${S}][checkForRemovedParticipants]`);for(const f of Object.keys(g))g.hasOwnProperty(f)&&!1!==g[f]&&!_.hasPendingOperation(0,f,S)&&(tryRemoveKeyFromHashTable(this.participantManager.connectedRemoteParticipantIds,f),this.logger.info(`[${S}][checkForRemovedParticipants] ${scrubMriOrOmit(f)} removed from roster`),v.onParticipantRemoved({id:f},S),C.clearParticipantCallLinks(f));this.handleRemoveParticipantRequests(f,S)}handleRemoveParticipantRequests(g,f){const S=this.participantManager.signalingSession,v=this.participantManager.participantOperationHandler;this.logger.info(`handleRemoveParticipantRequests [${f}] dynamicRosterParticipants`);const C=[];Object.keys(g).forEach((f=>{const S=cn.fromRoster(g[f]);S&&S.endpointDetails&&S.endpointDetails.forEach((g=>{g.originalId&&C.push(g.originalId)}))}));const _=v.getAllPendingOperations(3,f);for(const T of Object.keys(_))-1!==C.indexOf(T)||g.hasOwnProperty(T)||(this.logger.info(`[${f}][handleRemoveParticipantRequests] ${scrubMriOrOmit(T)} no longer appears in roster. Resolving RemoveParticipant request`),tryRemoveKeyFromHashTable(this.participantManager.connectedRemoteParticipantIds,T),S.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,T),v.resolvePendingOperation(3,T,{id:T},f))}},zn=class{constructor(g,f,S,v){this.connectedRemoteParticipantIds={},this.disposed=!1,this.unmuteApprovalLinks={},this._asyncMuteUnmuteDefers=new Map,this.muteAsyncEnabled=!1,this.unmuteAsyncEnabled=!1,this.setLocalParticipantId=(g,f)=>{g&&(this.logger.info(`[${f}][setLocalParticipantId][participantId=${g}]`),this.localParticipant.participantId=g,this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId))},this.setEnableMuteAsync=g=>{this.muteAsyncEnabled=g},this.setEnableUnmuteAsync=g=>{this.unmuteAsyncEnabled=g},this.admitParticipantAsync=(g,f,S)=>{const v=`[${S}][admitParticipantAsync]`;this.logger.info(`${v}${this.piiUtils.scrubMriOrOmit(g.id)}`);const C=defer();return this.participantOperationHandler.hasPendingOperation(1,g.id,S)?(this.logger.info(`${v}there is an existing pending request to admit the participant ${this.piiUtils.scrubMriOrOmit(g.id)}`),C.reject(new Error("there is an existing pending request to admit the participant"))):(this.participantOperationHandler.setPendingOperation(1,g.id,{participant:g,promise:C,causeId:S},S),this.sendNetworkRequestForAdmittingParticipant(g,f,S)),C.promise},this.addParticipantsAsync=(g,f,S,v,C)=>{const _=`[${C}][addParticipantsAsync]`,T=g.map((g=>this.piiUtils.scrubMriOrOmit(g.id)));this.logger.info(`${_} remoteParticipantsIds: ${T}`);const I=[],b=[];return g.forEach((g=>{const f=defer(),S=3===v.replacementType?g.participantId:g.id;this.connectedRemoteParticipantIds.hasOwnProperty(g.id)?(this.logger.info(`${_}the given participant is already connected to the call ${this.piiUtils.scrubMriOrOmit(g.id)}`),f.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(0,S,C)?(this.logger.info(`${_}there is an existing pending request to add the participant ${this.piiUtils.scrubMriOrOmit(g.id)}`),f.reject(new Error("there is an existing pending request to add the participant"))):(g.participantId||(g.participantId=newGuid(),this.logger.info(`participantId created ${g.participantId}`)),this.participantOperationHandler.setPendingOperation(0,S,{participant:g,promise:f,causeId:C},C),I.push(g)),b.push(f.promise)})),S&&this.sendNetworkRequestForAddingParticipant(I,f,v,C),b},this.nudgeParticipantsAsync=(g,f,S,v,C,_,T,I)=>(this.logger.info(`[${v}][nudgeParticipantAsync] ${this.piiUtils.scrubParticipantsList(g)}`),S?this.sendNetworkRequestForNudgingParticipants(g,f,v,C,_,T,I):Promise.reject(`[${v}][nudgeParticipantAsync] Call not started`)),this.updateMeetingRolesAsync=(g,f,S,v=causeId2())=>{const C=defer();if(!g||g.length<1){const g=`[${v}][updateMeetingRolesAsync] participantsInfo cannot be empty or null`,f=new Error(g);f.endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),C.reject(f)}else if(f)if(S){let _;"attendee"===f?_=hn.UPDATE_MEETING_ROLE_ATTENDEE.name:"presenter"===f?_=hn.UPDATE_MEETING_ROLE_PRESENTER.name:"organizer"===f?_=hn.UPDATE_MEETING_ROLE_ORGANIZER.name:C.reject(new Error(`[${v}] Invalid meetingRole value(${f})`)),this.logger.info(`[${v}][updateMeetingRolesAsync][meetingRole=${f}]`),this.signalingSession.ensureMessageChannelReady(_).then((()=>{this.sendNetworkRequestForUpdatingMeetingRoles(g,f,S,_,v,C)})).catch((g=>{const f=getPrintableObject(g);this.logger.info(`[${v}][updateMeetingRolesAsync][failed][reason=${f}]`);const S={...getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig).error};C.reject(S)}))}else{const g=`[${v}][updateMeetingRolesAsync] updateMeetingRoleUrl cannot be empty or null`,f=new Error(g);f.endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),C.reject(f)}else{const g=`[${v}][updateMeetingRolesAsync] meetingRole cannot be empty or null`,f=new Error(g);f.endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),C.reject(f)}return C.promise},this.updateParticipantInterpretationStateAsync=(g,f,S)=>{const v=`[${S}][updateParticipantInterpretationStateAsync]`,C=g.map((g=>this.piiUtils.scrubMriOrOmit(g.id)));this.logger.info(`${v} remoteParticipantsIds: ${C}`);const _=[],T=[];return g.forEach((g=>{const f=defer();this.participantOperationHandler.hasPendingOperation(5,g.id,S)?(this.logger.info(`${v}there is an existing pending request to update the participant ${this.piiUtils.scrubMriOrOmit(g.id)}`),f.reject(new Error("there is an existing pending request to update the participant"))):(this.participantOperationHandler.setPendingOperation(5,g.id,{option:g,promise:f,causeId:S},S),_.push(g)),T.push(f.promise)})),this.sendNetworkRequestToUpdateParticipantInterpretationState(_,f,g,S),T},this.callMeBackAsync=(g,f,S)=>{this.logger.info(`[${S}][callMeBackAsync] ${this.piiUtils.scrubMriOrOmit(g.id)}`);const v=defer();return this.connectedRemoteParticipantIds.hasOwnProperty(g.id)?(this.logger.info(`the given participant is already connected to the call : ${this.piiUtils.scrubMriOrOmit(g.id)}`),v.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(2,g.id,S)?(this.logger.info(`there is an existing pending request to call back the participant : ${this.piiUtils.scrubMriOrOmit(g.id)}`),v.reject(new Error("there is an existing pending request to call back the participant"))):(this.participantOperationHandler.setPendingOperation(2,g.id,{participant:g,promise:v},S),this.sendNetworkRequestForCallMeBack(g,f,S)),v.promise},this.isRosterStale=(g,f)=>this.rosterManager.isRosterStale(g,f),this.removeParticipantAsync=(g,f,S)=>{this.logger.info(`[${S}][removeParticipantAsync] ${this.piiUtils.scrubMriOrOmit(g.id)}`),assertNotNullOrEmpty(f,"correct removeParticipantUrl is not provided");const v=defer();if(this.participantOperationHandler.hasPendingOperation(3,g.id,S))this.logger.info(`there is an existing pending request to remove the participant ${this.piiUtils.scrubMriOrOmit(g.id)}`),v.reject(new Error("there is an existing pending request to remove the participant"));else{this.participantOperationHandler.setPendingOperation(3,g.id,{participant:g,promise:v},S);const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g.id),this.participantOperationHandler.rejectPendingOperation(3,g.id,"timed out waiting for participant to not show up in roster",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:an.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},S)}),an.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,g.id)};this.signalingSession.http.sendPostRequest({url:f,payload:getPayload20(this.signalingSession,g),requestName:hn.REMOVE_PARTICIPANT_NONE.name,onceTrouterReady:onceTrouterReady,causeId:S}).catch((f=>{const v=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][removeParticipantAsync][failed][reason=${getPrintableObject(v)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g.id),this.participantOperationHandler.rejectPendingOperation(3,g.id,f,v.error,S))}))}return v.promise},this.removeParticipantEndpointAsync=(g,f,S,v)=>{this.logger.info(`[${v}][removeParticipantEndpointAsync] ${truncate(g.endpointId,8)} [endPointScope] ${S}`),assertNotNullOrEmpty(f,"correct removeParticipantUrl is not provided");const C=defer();let _="";switch(S){case"all":_=hn.REMOVE_PARTICIPANT_OTHERS.name;break;case"specified":_=hn.REMOVE_PARTICIPANT_SPECIFIED.name;break;default:return Promise.reject(`invalid scope ${S} removeParticipantEndpointAsync`)}this.participantOperationHandler.setPendingOperation(4,g.endpointId,{participant:g,promise:C,scope:S},v);const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g.endpointId),this.participantOperationHandler.rejectPendingOperation(4,g.endpointId,"timed out waiting for participant endpoint sync response from service",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:an.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},v))}),an.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,g.endpointId)};return this.signalingSession.http.sendPostRequest({url:f,payload:getPayload19(this.signalingSession,g,S),requestName:_,onceTrouterReady:onceTrouterReady,causeId:v}).then((g=>{if(g.response?.code)if(-1!==[an.HTTP_STATUS_CODES.OK,an.HTTP_STATUS_CODES.CREATED].indexOf(g.response.code))this.logger.info(`[${v}][removeParticipantEndpointAsync][endPointScope] ${S} [passed][reason=${getPrintableObject(g.response)}]`),C.resolve(g.response);else{const f=new Error("invalid service response for removeParticipantEndpoint");f.endCode={code:g.response.code,subCode:g.response.subcode,phrase:g.response.reason},this.logger.info(`[${v}][removeParticipantEndpointAsync][endPointScope] ${S} [failed][reason=${getPrintableObject(g.response)}]`),C.reject(f)}C.resolve()})).catch((f=>{const C=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${v}][removeParticipantEndpointAsync][endPointScope] ${S} [failed][reason=${getPrintableObject(C)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g.endpointId),this.participantOperationHandler.rejectPendingOperation(4,g.endpointId,getPrintableObject(f),C.error,v))})),C.promise},this.getParticipantsToInitiateCallWith=()=>{this.logger.info("getParticipantsToInitiateCallWith");const g=[],f=this.participantOperationHandler.getAllPendingOperations(0,causeId2());for(const S of Object.keys(f))f.hasOwnProperty(S)&&f[S]&&g.push(f[S].participant);return g},this.initializeForIncomingCall=g=>{this.logger.info("initializeForIncomingCall"),this.participantOperationHandler.dispose("incoming calls cannot add/remove participants until call is connected",null,causeId2())},this.handleAddParticipantSuccess=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAddParticipantSuccess(${f.participantInfos?"new format":"old format"})]${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_PARTICIPANT_SUCCESS,g),this.internalHandleCallMeBackSuccess(f,S)||this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_ADD_PARTICIPANT_SUCCESS),this.signalingSession.signalingAgentConfig.enableAddParticipantEnhancements&&this.internalHandleAcceptedByParticipants(f,S)},this.handleAddParticipantFailure=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAddParticipantFailure(${f.participantInfos?"new format":"old format"})][${getPrintableObject(f)}]`),f.modalityFailure?(this.logger.info(`[${S}][handleAddParticipantFailure][modalityFailure=${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_PARTICIPANT_MODALITY_FAILURE,g)):this.internalHandleAddParticipantFailure(g,S)},this.handleAdmitParticipantSuccess=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAdmitParticipantSuccess][${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADMIT_PARTICIPANT_SUCCESS,g),f.participants&&this.internalHandleAdmitParticipantSuccess(g,S)},this.handleAdmitParticipantFailure=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAdmitParticipantFailure][${getPrintableObject(f)}]`),f.participants&&this.internalHandleAdmitParticipantFailure(g,S)},this.handleRemoveParticipantFailure=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleRemoveParticipantFailure][${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_REMOVE_PARTICIPANT_FAILURE,g);for(const g of Object.keys(f.participants))f.participants.hasOwnProperty(g)&&this.internalHandleRemoveParticipantFailure(g,f.participants[g],S)},this.handleRemoveParticipantSuccess=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleRemoveParticipantSuccess][${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_REMOVE_PARTICIPANT_SUCCESS,g)},this.handleUnmuteConfirmRequest=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleUnmuteConfirmRequest][${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_UNMUTE_CONFIRM,g),this.unmuteApprovalLinks[f.from.id]={approve:f.links.approveUnmute,reject:f.links.rejectUnmute},this.signalingSessionCallback.onUnmuteRequested(f.from.id,S)},this.approveUnmuteRequestAsync=(g,f)=>{this.logger.info(`[${f}][approveUnmuteRequestAsync]`);const S=defer();return this.unmuteApprovalLinks.hasOwnProperty(g)?(this.signalingSession.ensureMessageChannelReady(hn.APPROVE_UNMUTE.name).then((()=>{this.muteUnmute(hn.APPROVE_UNMUTE.name,getPayload14(this.signalingSession),S,this.unmuteApprovalLinks[g].approve,f)})).catch((g=>{const v=getPrintableObject(g);this.logger.info(`[${f}][approveUnmuteRequestAsync][failed][reason=${v}]`),S.reject(new Error(g))})),S.promise):(S.reject(new Error("no unmute links found for given participant")),S.promise)},this.rejectUnmuteRequestAsync=(g,f,S)=>{this.logger.info(`[${f}][rejectUnmuteRequestAsync]`);const v=defer();if(!this.unmuteApprovalLinks.hasOwnProperty(g))return v.reject(new Error("no unmute links found for given participant")),v.promise;const C=S||{code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UNMUTE_REQUEST_REJECTED,phrase:an.CALL_END_PHRASE.UNMUTE_REQUEST_REJECTED};return this.signalingSession.ensureMessageChannelReady(hn.REJECT_UNMUTE.name).then((()=>{this.muteUnmute(hn.REJECT_UNMUTE.name,getPayload18(this.signalingSession,C),v,this.unmuteApprovalLinks[g].reject,f)})).catch((g=>{const S=getPrintableObject(g);this.logger.info(`[${f}][rejectUnmuteRequestAsync][failed][reason=${S}]`),v.reject(new Error(g))})),v.promise},this.handleRosterUpdate=(g,f,S)=>{const v=this.getCurrentParticipantsInCallModality(!1);this.rosterManager.handleRosterUpdate(g,v,f,S)},this.updateLocalParticipantFromSubscribe=(g,f)=>{this.localParticipant.fromRoster||this.rosterManager.updateLocalParticipantFromSubscribe(g,f)},this.muteAsync=(g,f,S,v)=>{this.logger.info(`[${v}][muteAsync][muteScope=${f}]`);let C="specified";const _=[];let T=hn.MUTE_SPECIFIED;switch(f){case an.MUTE_SCOPE.MYSELF:T=hn.MUTE_MYSELF,_.push({id:this.localParticipant.id});break;case an.MUTE_SCOPE.EVERYONE_ELSE:T=hn.MUTE_ALL_SYNC,C="all",S.forEach((g=>{_.push({id:g})}));break;case an.MUTE_SCOPE.SPECIFIED_PARTICIPANTS:assertNotNullOrEmpty(S,`[${v}]array of participantIds must be specified for SPECIFIED_PARTICIPANTS mute scope`),T=hn.MUTE_SPECIFIED_SYNC,S.forEach((g=>{_.push({id:g})}));break;default:assert2(!1,`[${v}]muteScope is a required param. please pass in a valid value.`)}const I=defer();if(f===an.MUTE_SCOPE.SPECIFIED_PARTICIPANTS){const g=this.areParticipantsConnectedToCall(S);if(!g.result)return I.reject(new Error(`[${v}]specified participant is not connected to call yet. Id = ${g.participant}`)),I.promise}const b=this.muteAsyncEnabled&&(f===an.MUTE_SCOPE.SPECIFIED_PARTICIPANTS||f===an.MUTE_SCOPE.EVERYONE_ELSE);return this.signalingSession.ensureMessageChannelReady(T.name).then((()=>{this.muteUnmute(T.name,getPayload15(this.signalingSession,C,_,b,v),I,g,v,!1,b)})).catch((g=>{const f=getPrintableObject(g),S=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);this.logger.info(`[${v}][muteAsync][failed][reason=${f}]`),I.reject(S)})),I.promise},this.unmuteAsync=(g,f)=>{this.logger.info(`[${f}][unmuteAsync]`);const S=defer();return this.signalingSession.ensureMessageChannelReady(hn.UNMUTE_SYNC.name).then((()=>{this.muteUnmute(hn.UNMUTE_SYNC.name,getPayload21(this.signalingSession,this.unmuteAsyncEnabled,f),S,g,f,!0,this.unmuteAsyncEnabled)})).catch((g=>{const v=getPrintableObject(g);this.logger.info(`[${f}][unmuteAsync][failed][reason=${v}]`),S.reject(new Error(g))})),S.promise},this.dispose=(g,f)=>{this.logger.info(`[${f}][dispose]`),this.disposed=!0,this.participantOperationHandler.dispose("call ended",g,f),this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId),this._asyncMuteUnmuteDefers.forEach(((f,S)=>{f.reject(g)})),this._asyncMuteUnmuteDefers.clear()},this.handleMuteUnmuteAsyncResponse=g=>{const f=extractCauseIdFromMessage(g),S=this.logger.createFnLogger("handleMuteUnmuteAsyncResponse",f);if(!g.body)return void S.error("ignored. Empty message body.");const v={info:g.body.muteUnmuteResponseAsync,operationId:g.body.operationId};if(S.info(`Received async response for mute/unmute operation, operation id = ${v.operationId}.`),this.disposed)return void S.info("ignored. Call disposed.");if(!v.operationId)return void S.error("operationId is undefined.");const C=this._asyncMuteUnmuteDefers.get(v.operationId);C?(C.resolve(v),this._asyncMuteUnmuteDefers.delete(v.operationId)):S.warn(`cannot find deferred promise for operation id [${v.operationId}].`)},this.internalHandleAcceptedByParticipants=(g,f)=>{if(g?.participantInfos){const S=g.participantInfos,v=this.getCurrentParticipantsInCallModality(!1);this.logger.info(`[${f}][internalHandleAcceptedByParticipants] handling participants with acceptedBy blob.`);for(const g of S)if(g?.acceptedBy){const S=g.id;this.participantOperationHandler.hasPendingOperation(0,S,f)&&(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,S),this.logger.info(`[${f}][internalHandleAcceptedByParticipants] ${this.piiUtils.scrubMriOrOmit(S)} added using a different MRI. Resolving operation.`),this.participantOperationHandler.resolvePendingOperation(0,S,void 0,f)),this.rosterManager.handleParticipantAcceptedBy(g,v,f)}}},this.internalHandleCallMeBackSuccess=(g,f)=>{let S=!1;if(g?.participantInfos){const v=g.participantInfos;for(const g of v){const v=g.id;this.internalHandleCallMeBackSuccessHelper(v,f)&&(S=!0)}}else if(g?.participants)for(const v of g.participants)this.internalHandleCallMeBackSuccessHelper(v,f)&&(S=!0);return S},this.signalingSession=g,this.signalingSessionCallback=f,this.localParticipant=S,this.localParticipant.endpointId||(this.localParticipant.endpointId=this.signalingSession.getEndpointId());const C=truncate(this.localParticipant.endpointId,8);this.logger=v.createChild((()=>`[PM][${C}]`)),this.piiUtils=g.piiUtils,this.participantOperationHandler=new Gn(g.logger.createChild((()=>`[ParticipantOperationHandler][${C}]`))),this.rosterManager=new Wn(this,g.logger.createChild((()=>`[RosterManager][${C}]`))),this.localParticipant.participantId||(this.localParticipant.participantId=newGuid()),"string"==typeof g.signalingAgentConfig.languageCode?this.localParticipant.languageId=g.signalingAgentConfig.languageCode:"function"==typeof g.signalingAgentConfig.languageCode&&(this.localParticipant.languageId=g.signalingAgentConfig.languageCode()),g.telemetryHelper.setParticipantId(this.localParticipant.participantId),g.telemetryHelper.setEndPointId(this.localParticipant.endpointId)}handleUpdateParticipantInterpretationStateCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.operationId;if(this.disposed)return void this.logger.info(`[${S}][handleUpdateParticipantInterpretationStateCompletion] ignored. Call disposed.`);v||this.logger.warn(`[${S}][handleUpdateParticipantInterpretationStateCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleUpdateParticipantInterpretationStateCompletion] starts`);const C=g.body;if(C.participantInfos)for(const f of C.participantInfos)if(this.logger.info(f),this.participantOperationHandler.hasPendingOperation(5,f.participant.id,S))if(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,f.participant.id),f.transactionEnd.code===an.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${S}]Update participant interpretation state succeeded for: ${this.piiUtils.scrubMriOrOmit(f.participant.id)}`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_RESPONSE_COMPLETED,g),this.participantOperationHandler.resolvePendingOperation(5,f.participant.id,void 0,S);else{const v=f.transactionEnd.reason;this.logger.info(`[${S}]Update participant interpretation state failed for: ${this.piiUtils.scrubMriOrOmit(f.participant.id)} reason : ${getPrintableObject(v)}`);const C=this.getCallEndGivenParticipantFailure(v);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_RESPONSE_FAILED,g,C),this.participantOperationHandler.rejectPendingOperation(5,f.participant.id,C.phrase,C,S)}}setEnableCaptcha(g,f){this.logger.info(`[${f}][setEnableCaptcha] value:${g}`),this.localParticipant.enableCaptcha=g,this.signalingSessionCallback.onSelfParticipantUpdated(this.localParticipant,f)}areParticipantsConnectedToCall(g){this.logger.info(`areParticipantsConnectedToCall : ${getPrintableObject(g)}`);const f=this.getCurrentParticipantsInCallModality(!0);for(const S of g)if(!f.hasOwnProperty(S))return this.logger.info(`areParticipantsConnectedToCall : returning false for :${this.piiUtils.scrubMriOrOmit(S)}`),{result:!1,participant:S};return this.logger.info("areParticipantsConnectedToCall : returning true"),{result:!0}}muteUnmute(g,f,S,v,C,_,T=!1){const I=this.logger.createFnLogger("muteUnmute",C);assert2(2!==this.signalingSession.callMode,"mute/unmute operations are not allowed in streaming mode"),I.info(`operation=${g}, isAsync=${T}`),v?(_&&this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UNMUTE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent(dn.UNMUTE_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UNMUTE);const g=new Error("timed out waiting for response to request");g.endCode={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UNMUTE_REQUEST_TIMEOUT,phrase:an.CALL_END_PHRASE.UNMUTE_REQUEST_TIMEOUT},S.reject(g)}}),an.TIMEOUT_VALUES_IN_SECONDS.UNMUTE_TIMEOUT),T&&this._asyncMuteUnmuteDefers.set(C,S),this.signalingSession.http.sendPostRequest({url:v,payload:f,requestName:g,withoutTrouter:!0,causeId:C}).then((f=>{if(!this.disposed)if(T)I.info(`Inline response received for async operation, operation id: ${C}.`);else{if(f.response?.muteUnmuteResponse){const v={info:f.response.muteUnmuteResponse,operationId:f.response.operationId};switch(g){case hn.UNMUTE_SYNC.name:case hn.MUTE_ALL_SYNC.name:case hn.MUTE_SPECIFIED_SYNC.name:S.resolve(v)}}S.resolve()}})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);I.info(`operation failed, reason=${getPrintableObject(f)}`),this.disposed||(_&&this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UNMUTE),S.reject(f.error))}))):S.reject(new Error(`[${C}][muteUnmute] cannot be performed now, the link is not yet available`))}sendNetworkRequestForUpdatingMeetingRoles(g,f,S,v,C,_){if(!S){const g=`[${C}][sendNetworkRequestForUpdatingMeetingRoles] failed because correct updateMeetingRoleUrl is not provided`;new Error(g).endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),_.reject()}if(!g){const g=`[${C}][sendNetworkRequestForUpdatingMeetingRoles] failed because participants list is empty or null`,f=new Error(g);f.endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),_.reject(f)}const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent(dn.UPDATE_MEETING_ROLE,{causeId:C}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE);const g=new Error(`[${C}] Timed out waiting for response to request`);g.endCode={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MEETING_ROLE_TIMEOUT},_.reject(g)}}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_ROLE_TIMEOUT)};this.signalingSession.http.sendPostRequest({url:S,payload:getPayload22(this.signalingSession,g,"specified",f),requestName:v,onceTrouterReady:onceTrouterReady,causeId:C}).then((g=>{_.resolve(g.response)})).catch((g=>{const f=getPrintableObject(g);this.logger.info(`[${C}][sendNetworkRequestForUpdatingMeetingRoles] failed: ${f}`);const S=new Error(`[${C}][CS response] Forbidden request`),v=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);S.code=v.error.code,S.subCode=v.error.subCode,S.phrase=v.error.phrase,this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE),_.reject(S))}))}sendNetworkRequestForNudgingParticipants(g,f,S,v,C,_,T){if(f){const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(dn.NUDGE_PARTICIPANT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,g?g.join():""))}),an.TIMEOUT_VALUES_IN_SECONDS.NUDGE_PARTICIPANT_TIMEOUT,g?g.join():"")},I=_||C?getPayload16(this.signalingSession,g,C,_,T,v):getPayload17(this.signalingSession,g,v);return this.signalingSession.http.sendPostRequest({url:f,payload:I,requestName:hn.NUDGE_PARTICIPANT.name,onceTrouterReady:onceTrouterReady,causeId:S}).then((()=>{})).catch((f=>{const v=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${S}][sendNetworkRequestForNudgingParticipant][failed][reason=${getPrintableObject(v)}]`),this.disposed||this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,g?g.join():""),Promise.reject(v.error)}))}return this.logger.info(`[${S}][sendNetworkRequestForNudgingParticipant] failed because correct nudgeParticipantUrl is not provided`),Promise.reject("Missing nudgeParticipant url")}sendNetworkRequestForAddingParticipant(g,f,S,v=causeId2()){if(f){let C=hn.ADD_PARTICIPANT.name,_=dn.ADD_PARTICIPANT_TIMEOUT,T={};switch(S.replacementType){case 2:C=hn.ADD_PARTICIPANT_WITH_PICKUP_CODE.name,_=dn.ADD_PARTICIPANT_WITH_PICKUP_CODE_TIMEOUT,T.unparkContent={pickupCode:S.pickupCode};break;case 1:C=hn.ADD_PARTICIPANT_WITH_REPLACES.name,_=dn.ADD_PARTICIPANT_WITH_REPLACES_TIMEOUT,T=this.signalingSession.getCallReplacementDetailsForCall(S.callIdToReplace,v);break;case 3:C=hn.ADD_PARTICIPANT_WITH_REPLACES.name,_=dn.ADD_PARTICIPANT_WITH_REPLACES_TIMEOUT,T=this.signalingSession.getReplacementDetailsByParticipantLegOfCall(S.callIdToReplace,g[0].id,g[0].replacementParticipantId,v);break;default:C=hn.ADD_PARTICIPANT.name,_=dn.ADD_PARTICIPANT_TIMEOUT,T=null}const onceTrouterReady=()=>{g.forEach((g=>{const f=3===S.replacementType?g.participantId:g.id;this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(_,{causeId:v}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,f),this.participantOperationHandler.rejectPendingOperation(0,f,"timed out waiting for participant to show up in roster",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},v))}),an.TIMEOUT_VALUES_IN_SECONDS.ADD_PARTICIPANT_TIMEOUT,f)}))},I=S.threadId||S.groupId?getPayload11(this.signalingSession,g,S,T):getPayload12(this.signalingSession,g,S,T);this.signalingSession.http.sendPostRequest({url:f,payload:I,requestName:C,onceTrouterReady:onceTrouterReady,causeId:v}).catch((f=>{const C=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${v}][sendNetworkRequestForAddingParticipant] failed:${getPrintableObject(f)}`),this.disposed||g.forEach((g=>{const _=3===S.replacementType?g.participantId:g.id;this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,_),this.participantOperationHandler.rejectPendingOperation(0,_,f,C.error,v)}))}))}else this.logger.info(`[${v}][sendNetworkRequestForAddingParticipants] failed because correct addParticipantUrl is not provided`),g.forEach((g=>{const f=3===S.replacementType?g.participantId:g.id;this.participantOperationHandler.rejectPendingOperation(0,f,"correct addParticipantUrl is not provided",{code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:an.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},v)}))}sendNetworkRequestToUpdateParticipantInterpretationState(g,f,S,v=causeId2()){if(f){const C=hn.UPDATE_PARTICIPANT_INTERPRETATION_STATE.name,_=dn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT,onceTrouterReady=()=>{const f={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT};g.forEach((g=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.logger.info(`[${v}][sendNetworkRequestToUpdateParticipantInterpretationState] timed out`),this.signalingSession.telemetryHelper.recordEvent(_,{causeId:v}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,g.id),this.participantOperationHandler.rejectPendingOperation(5,g.id,"timed out waiting to update particiant interpretation state",f,v))}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION_TIMEOUT,g.id)}))},T=getUpdateParticipantInterpretationStatePayload(this.signalingSession,S,v);this.signalingSession.http.sendPostRequest({url:f,payload:T,requestName:C,onceTrouterReady:onceTrouterReady,causeId:v}).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${v}][sendNetworkRequestToUpdateParticipantInterpretationState] failed:${getPrintableObject(f)}`),this.disposed||g.forEach((g=>{this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,g.id),this.participantOperationHandler.rejectPendingOperation(5,g.id,f,S.error,v)}))}))}else{this.logger.info(`[${v}][sendNetworkRequestToUpdateParticipantInterpretationState] failed because correct updateParticipantUrl is not provided`);const f={code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:an.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_URL_MISSING};g.forEach((g=>{this.participantOperationHandler.rejectPendingOperation(5,g.id,"correct updateParticipantUrl is not provided",f,v)}))}}sendNetworkRequestForCallMeBack(g,f,S){if(f){const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(dn.CALL_ME_BACK_TIMEOUT,{causeId:S}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,g.id),this.participantOperationHandler.rejectPendingOperation(2,g.id,"timed out waiting for call me back success response",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},S))}),an.TIMEOUT_VALUES_IN_SECONDS.CALL_ME_BACK_TIMEOUT,g.id)},v={groupId:this.signalingSession.groupId,threadId:this.signalingSession.threadId,messageId:this.signalingSession.teamsMessageId};this.signalingSession.http.sendPostRequest({url:f,payload:getPayload11(this.signalingSession,[g],v),requestName:hn.CALL_ME_BACK.name,onceTrouterReady:onceTrouterReady,causeId:S}).catch((f=>{const v=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][sendNetworkRequestForCallMeBack] failed: ${getPrintableObject(v)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,g.id),this.participantOperationHandler.rejectPendingOperation(2,g.id,f,v.error,S))}))}else this.logger.info(`[${S}][sendNetworkRequestForCallMeBack] failed because correct addParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(2,g.id,"correct addParticipantUrl is not provided",{code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:an.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},S)}sendNetworkRequestForAdmittingParticipant(g,f,S){if(f){const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(dn.ADMIT_PARTICIPANT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,g.id),this.participantOperationHandler.rejectPendingOperation(1,g.id,"timed out waiting for participant to show up in roster",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},S))}),an.TIMEOUT_VALUES_IN_SECONDS.ADMIT_PARTICIPANT_TIMEOUT,g.id)};this.signalingSession.http.sendPostRequest({url:f,payload:getPayload13(this.signalingSession,g,S),requestName:hn.ADMIT_PARTICIPANT.name,onceTrouterReady:onceTrouterReady,causeId:S}).catch((f=>{const v=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][sendNetworkRequestForAdmittingParticipant][failed][reason=${getPrintableObject(v)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,g.id),this.participantOperationHandler.rejectPendingOperation(1,g.id,f,v.error,S))}))}else this.logger.info(`[${S}][sendNetworkRequestForAdmittingParticipant] failed because correct admitParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(1,g.id,"correct admitParticipantUrl is not provided",{code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:an.CALL_END_PHRASE.ADMIT_PARTICIPANT_URL_MISSING},S)}getCurrentParticipantsInCallModality(g){const f={},S=[an.PARTICIPANT_AUDIO_STATE.CONNECTED];return g||S.push(an.PARTICIPANT_AUDIO_STATE.CONNECTING,an.PARTICIPANT_AUDIO_STATE.RINGING),this.signalingSessionCallback.getRemoteParticipantCollection()?.forEach((g=>{S.some((f=>f===g.audioState))&&(f[g.mri]=!0)})),f}internalHandleRemoveParticipantFailure(g,f,S){if(this.participantOperationHandler.hasPendingOperation(3,g,S)){this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g),this.logger.info(`[${S}][internalHandleRemoveParticipantFailure] failed for ${this.piiUtils.scrubMriOrOmit(g)} reason ${getPrintableObject(f)}`);const v=this.getCallEndGivenParticipantFailure(f);this.participantOperationHandler.rejectPendingOperation(3,g,v.phrase,v,S)}}internalHandleCallMeBackSuccessHelper(g,f){if(this.participantOperationHandler.hasPendingOperation(2,g,f)){const S={id:g};return this.logger.info(`participant : ${this.piiUtils.scrubMriOrOmit(g)} was successfully added. Resolving CallMeBack request`),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,g),this.participantOperationHandler.resolvePendingOperation(2,S.id,S,f),!0}return!1}internalHandleAddParticipantFailure(g,f=causeId2()){const S=g.body;if(S.participantInfos){S.participantInfos.forEach((S=>{const v=[S.participant.participantId],C=this.participantOperationHandler.getRnlMri(v,f)||S.participant.id;this.rejectAddParticipantFailure(C,S.transactionEnd,g,f)}))}else if(S.participants)for(const v of Object.keys(S.participants))this.rejectAddParticipantFailure(v,S.participants[v],g,f)}rejectAddParticipantFailure(g,f,S,v){const C=this.getCallEndGivenParticipantFailure(f);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_PARTICIPANT_FAILURE,S,C),this.participantOperationHandler.hasPendingOperation(0,g,v)?(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,g),this.logger.info(`participantAdd failed for : ${this.piiUtils.scrubMriOrOmit(g)} reason : ${getPrintableObject(f)}`),this.participantOperationHandler.rejectPendingOperation(0,g,C.phrase,C,v)):this.participantOperationHandler.hasPendingOperation(2,g,v)&&(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,g),this.logger.info(`callMeBack failed for : ${this.piiUtils.scrubMriOrOmit(g)} reason : ${getPrintableObject(f)}`),this.participantOperationHandler.rejectPendingOperation(2,g,C.phrase,C,v))}internalHandleAdmitParticipantSuccess(g,f){const S=g.body;for(const g of S.participants)this.participantOperationHandler.hasPendingOperation(1,g,f)&&(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,g),this.logger.info(`Admit participant success for : ${this.piiUtils.scrubMriOrOmit(g)}`),this.participantOperationHandler.resolvePendingOperation(1,g,void 0,f))}internalHandleAdmitParticipantFailure(g,f){const S=g.body;for(const v of Object.keys(S.participants))if(this.participantOperationHandler.hasPendingOperation(1,v,f)){this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,v);const C=S.participants[v];this.logger.info(`Admit participant failed for : ${this.piiUtils.scrubMriOrOmit(v)} reason : ${getPrintableObject(C)}`);const _=this.getCallEndGivenParticipantFailure(C);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADMIT_PARTICIPANT_FAILURE,g,_),this.participantOperationHandler.rejectPendingOperation(1,v,_.phrase,_,f)}}getCallEndGivenParticipantFailure(g){let f={code:g.code,subCode:g.subCode,phrase:g.phrase,resultCategories:g.resultCategories};return g.code===an.CALL_END_CODE.CALL_MODALITY_FAILURE&&g.callControllerTransactionEnd?f={...g.callControllerTransactionEnd}:g.code===an.CALL_END_CODE.ATC_CONTROLLER_FAILURE&&g.atcControllerTransactionEnd?f={...g.atcControllerTransactionEnd}:g.code===an.CALL_END_CODE.CVA_CONTROLLER_FAILURE&&g.cvaControllerTransactionEnd&&(f={...g.cvaControllerTransactionEnd}),f}};function getPayload23(g,f){assertNotNull(g,"signalingSession cannot be null"),assertNotNullOrEmpty(f,"sendMessageOptions cannot be null or empty");const S=[];for(const v of f){const f=0===v.scope?"all":"specified",C=[];v.to&&Object.keys(v.to).forEach((g=>{v.to[g].participantLegIdMap?Object.keys(v.to[g].participantLegIdMap).forEach((f=>{C.push({id:g,level:v.to[g].level,endpointId:v.to[g].participantLegIdMap[f].endpointId,participantId:f})})):C.push({id:g,level:v.to[g].level})})),S.push({links:{sendMessageStatus:get2(g,rn.SEND_MESSAGE_STATUS)},operationId:v.operationId,payload:v.payload,scope:f,to:C,type:v.type})}return{payload:{from:{displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,id:g.participantManager.localParticipant.id,languageId:g.participantManager.localParticipant.languageId??"",participantId:g.participantManager.localParticipant.participantId},messageContent:S}}}function mapMriToResolveString(g,f){return`${g}-${f}`}function mapLegIdToResolveString(g,f){return`${g}-${f}`}function mapMriAndPropertyNameToResolveString(g,f,S){return`${g}_${f}_${S}`}var Kn=class{constructor(g){this.signalingSession=g,this.scopeAllOperations=new Map,this.mriOperations=new Map,this.legOperations=new Map,this.logger=g.logger.createChild((()=>"[ProxiedMessageNotificationManager]"))}sendProxiedMessageAsync(g,f,S){this.logger.createChild("sendProxiedMessageAsync",g).info(`Url: ${S}`);const v=[],C=[];for(const S of f)if(0!==S.scope){if(1===S.scope)for(const f in S.to)if("participant"===S.to[f].level){const _=mapMriToResolveString(f,S.operationId),T=defer();this.mriOperations.set(_,T),v.push(T.promise),C.push(_),this.startTimeout(g,"participant",_)}else if("endpoint"===S.to[f].level)for(const _ in S.to[f].participantLegIdMap){const f=mapLegIdToResolveString(_,S.operationId),T=defer();this.legOperations.set(f,T),v.push(T.promise),C.push(f),this.startTimeout(g,"endpoint",f)}}else{const f=defer();this.scopeAllOperations.set(S.operationId,f),v.push(f.promise),C.push(S.operationId),this.startTimeout(g,"all",S.operationId)}return this.sendProxiedMessageNetworkRequest(g,f,S,C),v}sendProxiedMessageNetworkRequest(g,f,S,v){const C=getPayload23(this.signalingSession,f),_=this.logger.createChild("sendProxiedMessageNetworkRequest",g);_.info(`Url: ${S}`),this.signalingSession.http.sendPostRequest({url:S,requestName:hn.SEND_PROXIED_MESSAGE.name,payload:C,causeId:g}).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);if(_.info(`failed:${getPrintableObject(f)}`),this.signalingSession.disposed)_.info("signaling session is already disposed.");else for(const f of v){this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,f);let v=null;this.scopeAllOperations.has(f)?(v=this.scopeAllOperations.get(f),this.scopeAllOperations.delete(f)):this.mriOperations.has(f)?(v=this.mriOperations.get(f),this.mriOperations.delete(f)):this.legOperations.get(f)?(v=this.legOperations.get(f),this.legOperations.delete(f)):_.warn(`could not find resolveString:${f} to reject it.`),null!==v&&v.reject({transactionEnd:S.error,causeId:g,resolveString:f})}}))}startTimeout(g,f,S){const v=this.logger.createChild("startTimeout",g);v.info(`Creating timeout for level ${f} message with resolveString ${S}`),this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,(()=>{this.signalingSession.telemetryHelper.recordEvent(dn.SEND_MESSAGE_TIMEOUT,{causeId:g,resolveString:S}),v.info(`timed out waiting for level [${f}] message with resolveString [${S}]`),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,S);const C="all"===f?this.scopeAllOperations:"participant"===f?this.mriOperations:"endpoint"===f?this.legOperations:null;null!==C?C.has(S)?(C.get(S).reject({transactionEnd:{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CONVERSATION_NOTIFICATION_TIMEOUT,phrase:an.CALL_END_PHRASE.CONVERSATION_NOTIFICATION_TIMEOUT},causeId:g,resolveString:S}),C.delete(S)):v.warn(`Could not find resolveString [${S}] on map for ${f}. Will not reject promise.`):v.warn(`Could not find a operations map for ${f}. Will not reject promise.`)}),an.TIMEOUT_VALUES_IN_SECONDS.SEND_MESSAGE_COMPLETION_TIMEOUT,S)}handleProxiedMessageNotificationItem(g,f,S){if(f.info(`Message contains ${g.participantInfos?.length} participantInfos.`),0===this.scopeAllOperations.size&&0===this.mriOperations.size&&0===this.legOperations.size)return void f.info("Received statusMessage but there is no pending operation.");const v=g.operationId;if(this.scopeAllOperations.has(v)){f.info(`Scope all resolveString:${v}`),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,v);const g={transactionEnd:{code:0,subCode:0,phrase:""},causeId:S,resolveString:v};return this.scopeAllOperations.get(v).resolve(g),this.scopeAllOperations.delete(v),void this.signalingSession.telemetryHelper.recordEvent(dn.SEND_MESSAGE_COMPLETION,{causeId:S,operationId:v,level:"all"})}for(const C of g.participantInfos){const g=0===C.transactionEnd?.code,_=mapMriToResolveString(C.participant.id,v),T=mapLegIdToResolveString(C.participant.participantId,v);if(_&&this.mriOperations.has(_)){f.info(`Scope mri resolveString:${_}`);const T={transactionEnd:C.transactionEnd,causeId:S,resolveString:_};g?this.mriOperations.get(_).resolve(T):this.mriOperations.get(_).reject(T),this.mriOperations.delete(_),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,_),this.signalingSession.telemetryHelper.recordEvent(dn.SEND_MESSAGE_COMPLETION,{causeId:S,operationId:v,level:"mri"})}else if(T&&this.legOperations.has(T)){f.info(`Scope legId resolveString:${T}`);const _={transactionEnd:C.transactionEnd,causeId:S,resolveString:T};g?this.legOperations.get(T).resolve(_):this.legOperations.get(T).reject(_),this.legOperations.delete(T),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,T),this.signalingSession.telemetryHelper.recordEvent(dn.SEND_MESSAGE_COMPLETION,{causeId:S,operationId:v,level:"leg"})}else f.warn(`Could not map this participantInfo to any pending operation operationId:${v}`)}}handleProxiedMessageNotification(g){const f=extractCauseIdFromMessage(g),S=this.logger.createChild("handleProxiedMessageNotification",f);let v;v=Array.isArray(g.body?.statuses)?g.body.statuses:[g.body],S.info(`Received ${v.length} proxied message notification(s).`);for(const g of v)this.handleProxiedMessageNotificationItem(g,S,f)}};function getPayload24(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"broadcastContext cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},broadcast:f,links:{addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE)}}}}function getPayload25(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"broadcastContext cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},groupContext:f.groupContext?{id:f.groupContext.groupId}:null,groupChat:f.groupChat?{threadId:f.groupChat.threadId,messageId:f.groupChat.messageId}:null,links:{addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE)}}}}function getPayload26(g,f){return assertNotNull(g,"signalingSession cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},links:{admitAllStatus:get2(g,rn.CONV_ADMIT_ALL_STATUS)},operationId:f,debugContent:{causeId:f}}}}function getPayload27(g,f,S=!0){assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"joinUrl cannot be null");const v={type:"Delta",rosterUpdate:get2(g,rn.CONV_ROSTER_UPDATE)},C=g.getEndpointCapabilities(),_={payload:{attach:{requireMediaContent:S,links:{end:get2(g,rn.END)},locationContent:g.getLocationContent(),networkContent:g.getNetworkContent(),areaContent:g.getAreaContent()},capabilities:null,endpointCapabilities:C,additionalActions:[{input:{capabilities:null,endpointCapabilities:C,conversationRequest:{applicationType:g.participantManager.localParticipant.applicationType,roster:v,links:{conversationEnd:get2(g,g.signalingAgentConfig.enableSplitConversationEndUrl?rn.CONV_END_JOIN:rn.CONV_END),conversationUpdate:get2(g,rn.CONV_UPDATE),localParticipantUpdate:get2(g,rn.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:get2(g,rn.RECEIVE_MESSAGE)}},endpointMetadata:g.endpointMetadata,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}},name:"join",url:f,waitForResponse:!0}]}};return g.signalingAgentConfig.ecsEtag&&(_.payload.debugContent={ecsEtag:g.signalingAgentConfig.ecsEtag}),_.payload.additionalActions.length>0&&g.deviceType&&"default"!==g.deviceType&&(_.payload.additionalActions[0].input.conversationRequest.deviceType=g.deviceType),_}function getPayload28(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{callAcceptanceAcknowledgement:{links:{mediaRenegotiation:get2(g,rn.MEDIA_RENEGOTIATION),transfer:get2(g,rn.TRANSFER),replacement:get2(g,rn.REPLACE),balanceUpdate:get2(g,rn.BALANCE_UPDATE),retargetCompletion:get2(g,rn.RETARGET_COMPLETION),controlVideoStreaming:get2(g,rn.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:get2(g,rn.UPDATE_MEDIA_DESCRIPTIONS)}}}}}function getPayload29(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");const C=getMediaTypes(S);g.telemetryHelper.addOutgoingModalities(C);const _=g.getEndpointCapabilities();return{payload:{callAcceptance:{acceptedBy:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},acceptedCallModalities:C,capabilities:null,endpointCapabilities:_,clientEndpointCapabilities:0!==v?v:null,links:{mediaRenegotiation:get2(g,rn.MEDIA_RENEGOTIATION),transfer:get2(g,rn.TRANSFER),replacement:get2(g,rn.REPLACE),balanceUpdate:get2(g,rn.BALANCE_UPDATE),retargetCompletion:get2(g,rn.RETARGET_COMPLETION),controlVideoStreaming:get2(g,rn.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:get2(g,rn.UPDATE_MEDIA_DESCRIPTIONS)},clientContentForMediaController:g.webRtcSignalingManager.getClientUrls(),mediaContent:f,pstnContent:g.pstnContent,callKeepAliveInterval:null}}}}function getPayload30(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{callProgress:{sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},status:"ringing",phrase:"ringing"}}}}function getPayload31(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");const C=g.participantManager.localParticipant;return{payload:{invitationRedirection:{target:{type:f,endpointType:v,id:S},sender:{id:C.id,endpointId:C.endpointId,participantId:C.participantId,languageId:C.languageId}}}}}function getPayload32(g,f,S){assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f);const v={payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,languageId:g.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:an.CALL_END_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:f}};return S&&f.code===an.CALL_END_CODE.CANCEL&&(v.payload.callTransactionEnd.callQualityDiagnosticsInformation=S),v}function getPayload33(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");let C=[];C=v.invitationType===an.INVITATION_TYPE.NUDGE&&Array.isArray(v.participantsToNudge)?v.participantsToNudge.map((g=>({id:g}))):g.participantManager.getParticipantsToInitiateCallWith(),g.signalingAgentConfig.doHostlessCalling||assert2(C.length>0,"remoteParticipants need to be set before a call can be made");const _={type:"Delta",rosterUpdate:get2(g,rn.CONV_ROSTER_UPDATE)},T=g.groupId?{id:g.groupId}:null,I=g.threadId?{threadId:g.threadId,messageId:g.teamsMessageId||null}:null,b=g.contentSharingManager.getContentSharingInfoToStartSharing(),A=null===b?null:{identifier:b.contentIdentifier,subject:b.subject,sessionState:b.sessionState,sessionUpdateSequenceNumber:b.sequenceNumber,links:{sessionUpdate:get2(g,rn.CONV_CONTENT_SHARING_UPDATE),sessionEnd:get2(g,rn.CONV_CONTENT_SHARING_END)}},P=g.broadcastSession?.getContext(),R=g.getEndpointCapabilities();1===C.length&&g.telemetryHelper.setCalleeType(C[0].id),g.numberOfOriginalInvitees=C.length;const M=[];C.forEach((f=>{const S={id:f.id};f.displayName&&(S.displayName=f.displayName),f.participantId&&(S.participantId=f.participantId),(v.callToVoicemail||g.transferContext&&g.transferContext.target&&"voicemail"===g.transferContext.target.endpointType)&&(S.endpointType="voicemail"),M.push(S)}));const w=g.transferContext?g.transferContext.transferor:null,O=g.transferContext?g.transferContext.transferContext:null,D={};v.callToVoicemail&&(v.voicemailResourcePath&&(D.localResourcePath=v.voicemailResourcePath),v.voicemailItemId&&(D.voicemailItemId=v.voicemailItemId));const N={payload:{conversationRequest:{conversationType:v.conversationType,subject:g.convSubject,suppressDialout:v.suppressDialout,applicationType:v.applicationType,targetApplicationType:v.targetApplicationType,roster:_,properties:{allowConversationWithoutHost:g.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:g.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:g.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:g.enableGroupCallMeetupGeneration},links:{conversationEnd:get2(g,g.signalingAgentConfig.enableSplitConversationEndUrl?v.subscribe?rn.CONV_END_SUBSCRIBE:rn.CONV_END_JOIN:rn.CONV_END),conversationUpdate:get2(g,rn.CONV_UPDATE),localParticipantUpdate:get2(g,rn.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE),addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE),confirmUnmute:get2(g,rn.CONV_CONFIRM_UNMUTE),receiveMessage:get2(g,rn.RECEIVE_MESSAGE)}},broadcast:P,contentSharing:A,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,meetingRegistrationId:v.meetingRegistrationId,participantPin:v.participantPin},to:M},capabilities:null,endpointCapabilities:R,clientEndpointCapabilities:v.clientEndpointCapabilities?v.clientEndpointCapabilities:null,endpointMetadata:g.endpointMetadata,groupContext:T,groupChat:I,meetingInfo:g.getMeetingInfo(),meetingData:v.meetingData,meetingPreferences:v.meetingPreferences,endpointState:v.endpointState}};if(v.publishedStates?.publishedStates.length>0){let f=[];f=v.publishedStates.publishedStates.map((f=>{let S={};try{S=JSON.parse(f.content)}catch(f){g.logger.warn("createConversationRequest getPayload() failed to parse state.content")}return{stateType:f.type,level:f.level,content:S,sequenceNumber:g.getPublishStateSequenceNumber()}})),N.payload.publishedStates=f}g.deviceType&&"default"!==g.deviceType&&(N.payload.conversationRequest.deviceType=g.deviceType);const k=getMediaTypes(S);if(g.telemetryHelper.addOutgoingModalities(k),N.payload.callInvitation={callModalities:k,replaces:null,transferor:w||null,clientTransferContext:O,customContext:v.customHeaderContext||null,links:{progress:get2(g,rn.PROGRESS),mediaAnswer:get2(g,rn.MEDIA_ANSWER),acceptance:get2(g,rn.ACCEPT),redirection:get2(g,rn.REDIRECTION),end:get2(g,rn.END)},clientContentForMediaController:g.webRtcSignalingManager.getClientUrls(),pstnContent:g.pstnContent,emergencyContent:g.getEmergencyContent(),mediaContent:f,voicemailSettings:D,routingFlags:v.routingFlags,invitationData:v.invitationData,locationContent:g.getLocationContent(),networkContent:g.getNetworkContent(),areaContent:g.getAreaContent()},v.pickupCode&&(N.payload.callInvitation.unparkContent={pickupCode:parseInt(v.pickupCode,10)}),v.onBehalfOf&&(N.payload.callInvitation.onBehalfOf={id:v.onBehalfOf},v.onBehalfOfUserDisplayName&&(N.payload.callInvitation.onBehalfOf.displayName=v.onBehalfOfUserDisplayName)),v.callQueueContext&&(N.payload.callInvitation.callQueueContext=v.callQueueContext),v.scenario&&(N.payload.conversationRequest.scenario=v.scenario),v.alternateId&&(N.payload.participants.from.alternateId=v.alternateId),v.callingLineIdentity&&(N.payload.participants.from.callingLineIdentity=v.callingLineIdentity),v.invitationType===an.INVITATION_TYPE.NUDGE&&(N.payload.participants.invitationType=v.invitationType),g.signalingAgentConfig.ecsEtag&&(N.payload.debugContent={ecsEtag:g.signalingAgentConfig.ecsEtag}),v.clientEndpointDebugContent){N.payload.debugContent||(N.payload.debugContent={});try{N.payload.debugContent.clientDebugContent=JSON.parse(v.clientEndpointDebugContent)}catch(g){assert2(!1,`Failed to parse ${v.clientEndpointDebugContent}`)}}if(v.captchaContentJson)try{N.payload.conversationRequest.captchaContent=JSON.parse(v.captchaContentJson)}catch(g){assert2(!1,`Failed to parse ${v.captchaContentJson}`)}return v.participationPreferences&&(N.payload.participationPreferences=v.participationPreferences),N}function getPayload34(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:an.CALL_END_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED},callTransactionEnd:f}}}function getPayload35(g,f){return{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:f}}}function getPayload36(g,f,S,v,C){assertNotNull(g,"signalingSession cannot be null");const _={type:"Delta",rosterUpdate:get2(g,rn.CONV_ROSTER_UPDATE)},T=g.getEndpointCapabilities(),I=g.groupId?{id:g.groupId}:null,b=g.threadId?{threadId:g.threadId,messageId:g.teamsMessageId||null}:null,A={payload:{conversationRequest:{conversationType:v.conversationType,subject:g.convSubject,suppressDialout:v.suppressDialout,scenario:v.scenario,applicationType:v.applicationType,roster:_,properties:{allowConversationWithoutHost:g.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:g.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:g.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:g.enableGroupCallMeetupGeneration},links:{conversationEnd:get2(g,g.signalingAgentConfig.enableSplitConversationEndUrl?v.subscribe?rn.CONV_END_SUBSCRIBE:rn.CONV_END_JOIN:rn.CONV_END),conversationUpdate:get2(g,rn.CONV_UPDATE),localParticipantUpdate:get2(g,rn.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:get2(g,rn.RECEIVE_MESSAGE)}},groupContext:I,groupChat:b,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,meetingRegistrationId:v.meetingRegistrationId,participantPin:v.participantPin}},capabilities:null,endpointCapabilities:T,clientEndpointCapabilities:v.clientEndpointCapabilities?v.clientEndpointCapabilities:null,endpointMetadata:g.endpointMetadata,meetingInfo:g.getMeetingInfo(),meetingData:v.meetingData,meetingPreferences:v.meetingPreferences,endpointState:v.endpointState}};if(v.publishedStates?.publishedStates.length>0){let f=[];f=v.publishedStates.publishedStates.map((f=>{let S={};try{S=JSON.parse(f.content)}catch(f){g.logger.warn("joinConversationRequest getPayload() failed to parse state.content")}return{stateType:f.type,level:f.level,content:S,sequenceNumber:g.getPublishStateSequenceNumber()}})),A.payload.publishedStates=f}if(v?.applyServerMute&&(A.payload.participants.from.applyServerMute=v.applyServerMute.value,v.applyServerMute.mediaTypes&&(A.payload.participants.from.mediaTypes=v.applyServerMute.mediaTypes)),g.deviceType&&"default"!==g.deviceType&&(A.payload.conversationRequest.deviceType=g.deviceType),!v.subscribe){const C=getMediaTypes(S);g.telemetryHelper.addOutgoingModalities(C),A.payload.callInvitation={callModalities:C,replaces:null,transferor:null,links:{progress:get2(g,rn.PROGRESS),mediaAnswer:get2(g,rn.MEDIA_ANSWER),acceptance:get2(g,rn.ACCEPT),redirection:get2(g,rn.REDIRECTION),end:get2(g,rn.END)},clientContentForMediaController:g.webRtcSignalingManager.getClientUrls(),mediaContent:f,pstnContent:g.pstnContent,locationContent:g.getLocationContent(),networkContent:g.getNetworkContent(),areaContent:g.getAreaContent(),sharedLineCallInvitationContent:v.sharedLineCallInvitationContent,invitationData:v.invitationData,callQueueContext:v.callQueueContext}}if(g.signalingAgentConfig.ecsEtag&&(A.payload.debugContent={ecsEtag:g.signalingAgentConfig.ecsEtag}),C&&(A.payload.debugContent||(A.payload.debugContent={}),A.payload.debugContent.causeId=C),v.clientEndpointDebugContent){A.payload.debugContent||(A.payload.debugContent={});try{A.payload.debugContent.clientDebugContent=JSON.parse(v.clientEndpointDebugContent)}catch(g){assert2(!1,`Failed to parse ${v.clientEndpointDebugContent}`)}}if(v.captchaContentJson)try{A.payload.conversationRequest.captchaContent=JSON.parse(v.captchaContentJson)}catch(g){assert2(!1,`Failed to parse ${v.captchaContentJson}`)}return v.callQueueContext&&(A.payload.conversationRequest.callQueueContext=v.callQueueContext),v.participationPreferences&&(A.payload.participationPreferences=v.participationPreferences),A}function getJoinMeetingGroupPayload(g,f,S){assertNotNull(g,"signalingSession cannot be null");return{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},..."meetingGroupId"in f&&{meetingGroup:f.meetingGroupId},..."meetingGroupLabel"in f&&{meetingGroupLabel:f.meetingGroupLabel},...f.groupPreferences&&{groupPreferences:f.groupPreferences},links:{joinMeetingGroupStatus:get2(g,rn.JOIN_MEETING_GROUP_STATUS)},operationId:S}}}function getPayload37(g,f,S,v){assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f);const C={payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:v&&"all"!==v?void 0:v},conversationTransactionEnd:{reason:"noError",code:an.CALL_END_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:f}};return S&&f.code===an.CALL_END_CODE.CANCEL&&(C.payload.callTransactionEnd.callQualityDiagnosticsInformation=S),C}function getLeaveMeetingGroupPayload(g,f,S){assertNotNull(g,"signalingSession cannot be null");const{meetingGroupId:v}=f;return{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},meetingGroup:v,links:{leaveMeetingGroupStatus:get2(g,rn.LEAVE_MEETING_GROUP_STATUS)},operationId:S}}}function getPayload38(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(S,"newOfferLink cannot be null"),{payload:{mediaOfferRequirements:{compatibleContentTypes:f,links:{offerReady:get2(g,rn.NEW_MEDIA_OFFER)}}}}}function getPayload39(g,f){return assertNotNull(f,"signalingSession cannot be null"),{payload:{callTransfer:{target:{id:f.participantManager.localParticipant.id},transferor:{details:{id:f.participantManager.localParticipant.id,endpointId:f.participantManager.localParticipant.endpointId,participantId:f.participantManager.localParticipant.participantId,languageId:f.participantManager.localParticipant.languageId},authorizationToken:null},parkType:g,links:{transferAcceptance:get2(f,rn.TRANSFER_ACCEPTANCE),transferCompletion:get2(f,rn.TRANSFER_COMPLETION)}}}}}function getPayload40(g,f,S){assertNotNull(g,"ParkRequestPayload: signalingSession cannot be null");const v={payload:{hold:{holdType:f,links:{holdCompletion:get2(g,rn.PARK_COMPLETION)}}}};return S&&(v.payload.debugContent=S),v}function getPayload41(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{callParticipantUpdate:{links:getLinksPayload(g,tn),clientContentForMediaController:g.webRtcSignalingManager.getClientUrls()}}}}function getPayload42(g,f,S,v,C,_){const T={payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},publishedState:{content:v,level:S,stateType:f,sequenceNumber:g.getPublishStateSequenceNumber()},scope:C}};if(_&&_.length>0){const g=_.map((g=>({id:g})));T.payload.to=g}return T}function getPayload43(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{callEnd:f}}}function getPayload44(g,f,S,v){const C={from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},sequenceNumber:g.getPublishStateSequenceNumber(),scope:f};return"specified"===f?C.stateIds=S:C.stateType=v,{payload:C}}function getPayload45(g,f){return{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},searchOptions:f}}}function getPayload46(g,f){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,displayName:g.participantManager.localParticipant.displayName},...f,links:{setMeetingLayoutStatus:get2(g,rn.SET_MEETING_LAYOUT_STATUS)}}}}function getPayload47(){return{payload:{transferAcceptance:{}}}}function getPayload48(g,f,S,v,C){assertNotNull(f,"signalingSession cannot be null"),assertNotNullOrEmpty(g,"transferTarget cannot be null OR empty");return{payload:{callTransfer:{target:{id:g,endpointType:"TransferTypeVoicemail"===v?"voicemail":void 0},transferor:{details:{id:f.participantManager.localParticipant.id,endpointId:f.participantManager.localParticipant.endpointId,participantId:f.participantManager.localParticipant.participantId,languageId:f.participantManager.localParticipant.languageId},authorizationToken:null},links:{transferAcceptance:get2(f,rn.TRANSFER_ACCEPTANCE),transferCompletion:get2(f,rn.TRANSFER_COMPLETION)},replacementDetails:S,disableForwardingAndUnanswered:C&&C.disableForwardingAndUnanswered,transferContext:C&&C.clientTransferContext}}}}function getPayload49(g){return{payload:{transferCompletion:g}}}function getPayload50(g,f){assertNotNull(g,"ResumePayload: signalingSession cannot be null");const S={payload:{resume:{links:{resumeCompletion:get2(g,rn.UNPARK_COMPLETION)}}}};return f&&(S.payload.debugContent=f),S}function getPayload51(g,f){return assertNotNull(f,"clientMetadataJson cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},endpointMetadata:f}}}function getPayload52(g,f,S,v,C){assertNotNull(f,"clientStateJson cannot be null");const _={payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},endpointState:f}};if(C)try{_.payload.captchaContent=JSON.parse(C)}catch(f){g.logger.warn("updateEndpointState getPayload() failed to parse captchaContentJson")}if(S?.publishedStates.length>0){let f=[];f=S.publishedStates.map((f=>{let S={};try{S=JSON.parse(f.content)}catch(f){g.logger.warn("updateEndpointState getPayload() failed to parse stateType.content")}return{stateType:f.type,level:f.level,content:S,sequenceNumber:g.getPublishStateSequenceNumber()}})),_.payload.publishedStates=f}return v&&(_.payload.links={updateEndpointStateStatus:get2(g,rn.DISABLE_PREHEAT_ASYNC_STATUS)}),_}function getMeetingGroupsPayload(g,f,S){assertNotNull(g,"signalingSession cannot be null");const{scope:v,toGroup:C,fromGroup:_,participants:T}=f;"specified"===v&&assertNotNull(T,"participantsIds cannot be null");const I={from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,displayName:g.participantManager.localParticipant.displayName},scope:v,fromGroup:_,toGroup:C,links:{updateMeetingGroupsStatus:get2(g,rn.UPDATE_MEETING_GROUPS_STATUS)},operationId:S};return T&&(I.to=T.map((g=>({id:g.mri,endpointId:g.endpointId,participantId:g.participantId})))),{payload:I}}function getPayload53(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,displayName:g.participantManager.localParticipant.displayName},meetingLiveState:f,links:{updateMeetingLiveStateStatus:get2(g,rn.UPDATE_MEETING_LIVE_STATE_STATUS)},operationId:S}}}function getPayload54(g,f){const S={};return void 0!==f.allowRaiseHands&&(S.allowRaiseHands=f.allowRaiseHands),void 0!==f.attendeeRestrictions&&(S.attendeeRestrictions=f.attendeeRestrictions),void 0!==f.lockMeeting&&(S.lockMeeting=f.lockMeeting),void 0!==f.breakoutRoomsEnabled&&(S.breakoutRoomsEnabled=f.breakoutRoomsEnabled),void 0!==f.allowPresentersToManageBreakoutRooms&&(S.allowPresentersToManageBreakoutRooms=f.allowPresentersToManageBreakoutRooms),void 0!==f.disableMdpClientAudioRecording&&(S.disableMdpClientAudioRecording=f.disableMdpClientAudioRecording),void 0!==f.refreshSettings&&(S.refreshSettings=f.refreshSettings),void 0!==f.aiInterpretationEnabled&&(S.aiInterpretationEnabled=f.aiInterpretationEnabled),void 0!==f.groupCopilotDetails&&(S.groupCopilotDetails=f.groupCopilotDetails),{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},meetingSettings:S,sequenceNumber:g.getPublishStateSequenceNumber()}}}function getPayload55(g,f,S,v){return assertNotNull(g,"signalingSession cannot be null"),{payload:{monitorContent:{sequenceId:g.getMonitorSequenceId(),monitorActionType:f,monitorData:S??{},links:{monitorCompletion:get2(g,rn.MONITOR_COMPLETION)}},debugContent:{causeId:v}}}}function getPayload56(g){assertNotNull(g,"signalingSession cannot be null");const f={type:"Delta",rosterUpdate:get2(g,nn.CONV_ROSTER_UPDATE)};return{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},roster:f,links:getLinksPayload(g,nn)}}}function getUpdateParticipantsPropertiesPayload(g,f,S){assertNotNull(g,"signalingSession cannot be null");return{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId},to:f,links:{updateParticipantPropertiesStatus:get2(g,rn.UPDATE_PARTICIPANT_PROPERTIES_STATUS)},operationId:S}}}function getPayload57(g,f){return assertNotNull(g,"signalingSession cannot be null"),{payload:{mediaAnswer:{sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},mediaContent:f,pstnContent:g.pstnContent}}}}function getPayload58(g,f){return assertNotNull(g,"signalingSession cannot be null"),{payload:{UpdateMediaDescriptions:{mediaDescriptions:f}}}}function getPayload59(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,displayName:g.participantManager.localParticipant.displayName},meetingStates:f,updateMeetingStatesStatus:get2(g,rn.UPDATE_MEETING_STATES_STATUS),operationId:S}}}var Jn=__toESM(M),Yn=__toESM(Ie()),Qn=["CorrelationId","SignalingSessionId","Region","ParticipantId","ClientInformation","ResultCode","ResultDetail","ResultValue","Direction","ClientType","MeetingRoles"],Xn=class{constructor(g,f){this.signalingSession=g,this.logger=f,this.logConversationCallModalityEvent=g=>{const f=this.createCallModalityEvent(g);this.logger.info("sending modality telemetry:",this.getStringifiedEventData(f)),f.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(un.EVENT_TYPE.CONVERSATION_CALL_MODALITY,f)},this.logConversationContentSharingEvent=g=>{g[un.CONTEXT_ID.CORRELATION_ID]=this.signalingSession.correlationId,g[un.EXTENSIONS.ECS_ETAG]=this.signalingSession.signalingAgentConfig.ecsEtag,this.logger.info("sending content sharing telemetry:",this.getStringifiedEventData(g)),g.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(un.EVENT_TYPE.CONVERSATION_CONTENT_SHARING,g)},this.logHttpTelemetryEvent=g=>{g[un.EXTENSIONS.ECS_ETAG]=this.signalingSession.signalingAgentConfig.ecsEtag,g[un.SIGNALING_CONFIG]=this.getSignalingAgentConfig(),this.logger.info("sending http telemetry:",this.getStringifiedEventData(g)),g.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(un.EVENT_TYPE.CONVERSATION_HTTP_REQUEST,g)},this.getHostDomainInfo=()=>"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>",this.getSignalingAgentConfig=()=>{const g=[],f=this.signalingSession.signalingAgentConfig;return f.supportsCompressedServicePayload&&g.push(un.SIGNALING_CONFIG_FLAGS.SUPPORTS_COMPRESSED_PAYLOAD),f.brokerEnabledOutgoing&&g.push(un.SIGNALING_CONFIG_FLAGS.BROKER_OUTGOING_ENABLED),f.brokerEnabledIncoming&&g.push(un.SIGNALING_CONFIG_FLAGS.BROKER_INCOMING_ENABLED),f.brokerRequestBatching&&g.push(un.SIGNALING_CONFIG_FLAGS.BROKER_REQUEST_BATCHING_ENABLED),f.brokerExclusively&&g.push(un.SIGNALING_CONFIG_FLAGS.BROKER_EXCLUSIVELY_ENABLED),f.supportsSynchronousTrouterResponse&&g.push(un.SIGNALING_CONFIG_FLAGS.SYNC_TROUTER_RESPONSE),f.handleMediaOfferFromPushNotification&&g.push(un.SIGNALING_CONFIG_FLAGS.HANDLE_OFFER_FROM_NOTIFICATION),f.handleNewOfferRequest&&g.push(un.SIGNALING_CONFIG_FLAGS.HANDLE_NEW_OFFER_REQUEST),f.sendProgressFromCC&&g.push(un.SIGNALING_CONFIG_FLAGS.SEND_PROGRESS_FROM_CC),f.useInternalHttpDispatcher&&g.push(un.SIGNALING_CONFIG_FLAGS.INTERNAL_HTTP_DISPATCHER),f.enableTokenCache&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_TOKEN_CACHE),f.enableTokenPrefetch&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_TOKEN_PREFETCH),f.supportMediaRetargetWhileIncomingRenegotiation&&g.push(un.SIGNALING_CONFIG_FLAGS.SUPPORT_MEDIA_RETARGET_WHILE_INCOMING_RENEGOTIATION),f.enableCallEstablishmentTimeoutsForStartJoinCall&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_CALL_ESTABLISHMENT_TIMEOUTS_FOR_START_OR_JOIN_CALL),f.enableTokenCacheForGenericTokenAPI&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_TOKEN_CACHE_FOR_GENERIC_TOKEN_API),f.enableLongOutgoing1To1SetupTimeoutForWeb&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_LONG_OUTGOING_1TO1_SETUP),g.push(un.SIGNALING_CONFIG_FLAGS.SERVER_MUTE_UNMUTE),g.join(",")},this.getStringifiedEventData=g=>{try{return JSON.stringify(g,Qn,4)}catch(g){return"invalid data"}},this.telemetryLogger=this.signalingSession.signalingAgentConfig.oneDsTelemetryLogger??this.signalingSession.signalingAgentConfig.telemetryManager}createCallModalityEvent(g){const f={};f.Type=un.SOURCE.NGC_SOURCE;const setEventProperty=(S,v=!1)=>{f[S]=v?JSON.stringify(g[S]):g[S]},setEventPropertyIfRecorded=(f,S=!1)=>{g.hasOwnProperty(f)&&setEventProperty(f,S)};if(f.ResultDetail=g[un.EXTENSIONS.RESULT_DETAIL],f.ResultValue=g[un.EXTENSIONS.RESULT_VALUE],f.ResultCode=g[un.EXTENSIONS.CALL_END_CODE],f.ResultCauseId=g[un.EXTENSIONS.RESULT_CAUSE_ID],f[un.SIGNALING_CONFIG]=this.getSignalingAgentConfig(),f[un.CONTEXT_ID.CORRELATION_ID]=this.signalingSession.correlationId,f[un.CONTEXT_ID.SIGNALING_SESSION_ID]=this.signalingSession.sessionId,setEventProperty(un.CONTEXT_ID.ENDPOINT_ID),setEventProperty(un.CONTEXT_ID.PARTICIPANT_ID),f[un.EXTENSIONS.ECS_ETAG]=this.signalingSession.signalingAgentConfig.ecsEtag,setEventProperty(un.EXTENSIONS.CONVERSATION_SERVICE_URL),setEventProperty(un.EXTENSIONS.CALL_START_TIME,!0),setEventProperty(un.EXTENSIONS.CALL_END_TIME,!0),setEventProperty(un.EXTENSIONS.MESSAGING_CHANNEL,!0),f[un.EXTENSIONS.IS_GROUP_CALL]=this.signalingSession.multiParty?"true":"false",f[un.EXTENSIONS.IS_HOSTLESS_CALL]=this.signalingSession.isHostLessCall?"true":"false",f[un.EXTENSIONS.IS_CAST_CALL]=this.signalingSession.isCastCall?"true":"false",f[un.EXTENSIONS.IS_HUDDLE_GROUP_CALL]=this.signalingSession.isHuddleGroupCall?"true":"false",f[un.EXTENSIONS.IS_ON_BEHALF_OF_CALL]=this.signalingSession.onBehalfOf?"true":"false",setEventProperty(un.EXTENSIONS.CLIENT_INFORMATION),setEventProperty(un.EXTENSIONS.IS_SDP_IN_CALL_NOTIFICATION),setEventProperty(un.EXTENSIONS.CALL_TERMINATING_END),setEventProperty(un.EXTENSIONS.CALL_END_CODE,!0),setEventProperty(un.EXTENSIONS.CALL_END_SUB_CODE,!0),setEventPropertyIfRecorded(un.CONTEXT_ID.SHARED_CORRELATION_ID),setEventPropertyIfRecorded(un.EXTENSIONS.DIRECTION),setEventPropertyIfRecorded(un.EXTENSIONS.SELF_PARTICIPANT_ROLE),setEventPropertyIfRecorded(un.EXTENSIONS.CONNECTED_DURATION_IN_MS,!0),setEventPropertyIfRecorded(un.EXTENSIONS.TIME_TO_RING_IN_MS,!0),setEventPropertyIfRecorded(un.EXTENSIONS.NETWORK_REQUESTS_COMPLETED),setEventPropertyIfRecorded(un.EXTENSIONS.NETWORK_REQUESTS_PENDING),setEventPropertyIfRecorded(un.EXTENSIONS.LOCAL_OPERATIONS_PERFORMED),setEventPropertyIfRecorded(un.EXTENSIONS.EVENT_TIMESTAMP_BAG),setEventPropertyIfRecorded(un.EXTENSIONS.ROSTER_UPDATES_BAG),setEventPropertyIfRecorded(un.EXTENSIONS.NETWORK_REQUESTS_BAG),setEventPropertyIfRecorded(un.EXTENSIONS.TROUTER_WAIT_OPERATIONS),setEventPropertyIfRecorded(un.EXTENSIONS.LOCAL_OFFER_ANSWER_GENERATION_TIMESTAMPS),setEventPropertyIfRecorded(un.EXTENSIONS.OUTGOING_MODALITIES),setEventPropertyIfRecorded(un.EXTENSIONS.INCOMING_MODALITIES),setEventPropertyIfRecorded(un.EXTENSIONS.OFFERED_MODALITIES),setEventPropertyIfRecorded(un.EXTENSIONS.ANSWERED_MODALITIES),setEventPropertyIfRecorded(un.EXTENSIONS.VBSS_OPERATIONS),setEventPropertyIfRecorded(un.EXTENSIONS.CALLER_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.CALLEE_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.SCENARIO),setEventPropertyIfRecorded(un.EXTENSIONS.PREHEATED_CALL_SETUP_DURATION_IN_S),setEventPropertyIfRecorded(un.EXTENSIONS.CALL_CANCELATION_DURATION_IN_S),setEventPropertyIfRecorded(un.EXTENSIONS.IS_PREHEATED),setEventPropertyIfRecorded(un.EXTENSIONS.ACS_RESOURCE_ID),setEventPropertyIfRecorded(un.EXTENSIONS.CALL_END_RESULT_CATEGORIES),setEventPropertyIfRecorded(un.EXTENSIONS.APPLICATION_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.RING),setEventPropertyIfRecorded(un.EXTENSIONS.REGION),setEventPropertyIfRecorded(un.EXTENSIONS.PARTITION),setEventPropertyIfRecorded(un.EXTENSIONS.JOINED_FROM),setEventPropertyIfRecorded(un.EXTENSIONS.MEETING_URL),setEventPropertyIfRecorded(un.EXTENSIONS.MEETING_CODE),setEventPropertyIfRecorded(un.EXTENSIONS.USER_HEX_CID),setEventPropertyIfRecorded(un.EXTENSIONS.BROADCAST_MEETING_ROLE),setEventPropertyIfRecorded(un.EXTENSIONS.MEETING_ROLE),setEventPropertyIfRecorded(un.EXTENSIONS.ADVANCED_MEETING_ROLE),setEventPropertyIfRecorded(un.EXTENSIONS.MEETING_ROLES,!0),setEventPropertyIfRecorded(un.EXTENSIONS.PARTICIPANT_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.DISPLAY_NAME),setEventPropertyIfRecorded(un.EXTENSIONS.AUDIO_ONLY_WATERMARK),setEventPropertyIfRecorded(un.EXTENSIONS.TARGET_APPLICATION_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.IS_REINVITELESS),setEventPropertyIfRecorded(un.EXTENSIONS.CLIENT_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.CONFLICTING_CALL_ID),this.signalingSession.callType&&(f[un.EXTENSIONS.CALL_TYPE]=this.signalingSession.callType),this.signalingSession.signalingAgentConfig.testCall&&(f[un.EXTENSIONS.TEST_CONTEXT_ID]="Test"),this.signalingSession.groupId&&(f[un.CONTEXT_ID.GROUP_ID]=scrubMriOrOmit(this.signalingSession.groupId)),this.signalingSession.threadId&&(f[un.CONTEXT_ID.THREAD_ID]=getLoggableThreadId(this.signalingSession.threadId)),this.signalingSession.teamsMessageId&&(f[un.CONTEXT_ID.TEAMS_MESSAGEID]=this.signalingSession.teamsMessageId),this.signalingSession.getMeetingInfo()){const g={...this.signalingSession.getMeetingInfo()};g.hasOwnProperty("organizerId")&&(g.organizerId=scrubMriOrOmit(g.organizerId)),f[un.CONTEXT_ID.TEAMS_MEETINGINFO]=JSON.stringify(g)}return this.signalingSession.multiParty&&0===this.signalingSession.numberOfOriginalInvitees&&g.hasOwnProperty(un.EXTENSIONS.SELF_PARTICIPANT_ROLE)&&g[un.EXTENSIONS.SELF_PARTICIPANT_ROLE]===un.ROLE.CALLER&&(f[un.EXTENSIONS.IS_MEETUP_CALL]="true"),f}};function getLogger(g,f){return new Xn(g,f)}var Zn=class{constructor(g,f,S){this.signalingSession=g,this.callStartTime=S,this.networkRequestsCompleted=[],this.networkRequestsStarted={},this.networkRequests={},this.localOperationsPerformed=[],this.recordedEvents=[],this.rosterUpdates=[],this.contentSharingOperationsPerformed={},this.outgoingModalities=[],this.incomingModalities=[],this.offeredModalities="",this.answeredModalities="",this.vbssOperations=[],this.vbssStarted=!1,this.localOfferAnswerGenerationTimestamps=[],this.trouterWaitOperations=[],this.telemetryData={},this.contentSharingBaseTelemetryData={},this.httpRequestTelemetryData={},this.connectedStopWatch=null,this.preheatedCallSetupDurationWatch=null,this.callCancelationDurationWatch=null,this.timeToRingStopWatch=null,this.isSdpInCallNotification=!1,this.isPreheated=0,this.isReinviteless=0,this.addBrokerChannel=()=>{this.setMessagingChannel(un.MESSAGING_CHANNEL.BROKER)},this.addTrouterChannel=()=>{this.setMessagingChannel(un.MESSAGING_CHANNEL.TROUTER)},this.addTrouterWaitOperation=g=>{this.trouterWaitOperations.push(this.recordOperation(g))},this.recordIncomingEvent=(g,f,S)=>{const v=extractCauseIdFromMessage(f),C={origin:f.origin,causeId:v,data:S};S||delete C.data,this.recordEvent(g,C)},this.recordIncomingEventCount=g=>{this.localOperationsPerformed.push(this.recordOperation(g));const f=this.recordedEvents.findIndex((f=>f[g]));if(-1!==f)this.recordedEvents[f][g]+=1;else{const f={};f[g]=1,this.recordedEvents.push(f)}},this.recordEvent=(g,f)=>{this.logger.debug("Event:",g,f),this.localOperationsPerformed.push(this.recordOperation(g));const S={};S[g]=this.timeSinceCallStart(),f&&(S.data=f),this.recordedEvents.push(S)},this.recordRosterEvent=(g,f,S)=>{this.localOperationsPerformed.push(this.recordOperation(f));const v={data:g,causeId:S},C={eventName:this.timeSinceCallStart(),data:v};this.rosterUpdates.push(C)},this.addOutgoingModalities=g=>{g&&this.outgoingModalities.push(g)},this.addIncomingModalities=g=>{g&&this.incomingModalities.push(g)},this.setOfferedModalities=(g,f)=>{this.offeredModalities=this.sdpTelemetryFormat(g,f)},this.setAnsweredModalities=(g,f)=>{this.answeredModalities=this.sdpTelemetryFormat(g,f)},this.setIsSdpInCallNotification=g=>{this.isSdpInCallNotification=g},this.addVbssOperations=g=>{g&&(g===un.VBSS_OPERATION.START?this.vbssStarted=!0:this.vbssStarted=!1,this.vbssOperations.push(this.recordOperation(g)))},this.addNetworkOperationStarted=g=>{tryAddNewKeyToHashTable(this.networkRequestsStarted,g,this.recordOperation(g))},this.addNetworkOperationCompleted=(g,f,S)=>{const v=f?un.RESULT_VALUE.SUCCESS:un.RESULT_VALUE.FAILURE,C=S?`${g}:${v}:${S}`:`${g}:${v}`;this.networkRequestsCompleted.push(this.recordOperation(C)),tryRemoveKeyFromHashTable(this.networkRequestsStarted,g)},this.updateNetworkRequest=g=>{this.networkRequests[g.uid]?Jn.assign(this.networkRequests[g.uid],g):this.networkRequests[g.uid]=g},this.deleteNetworkRequest=g=>{delete this.networkRequests[g.uid]},this.addContentSharingOperation=(g,f,S)=>{this.contentSharingOperationsPerformed[g]||(this.contentSharingOperationsPerformed[g]=[]);const v={[f]:this.timeSinceCallStart()};this.contentSharingOperationsPerformed[g].push(v);const C=this.contentSharingOperationsPerformed[g].length-1;return S&&this.updateContentSharingOperation(g,C,S),C},this.updateContentSharingOperation=(g,f,S)=>{if(!this.contentSharingOperationsPerformed[g])return;const v=this.contentSharingOperationsPerformed[g][f],C=[];for(const g of Object.keys(S))C.push(`${g}: ${S[g]}`);v.data=C.join(", ")},this.setDirection=g=>{this.telemetryData[un.EXTENSIONS.DIRECTION]=g},this.setEndPointId=g=>{this.telemetryData[un.CONTEXT_ID.ENDPOINT_ID]=g,this.contentSharingBaseTelemetryData[un.CONTEXT_ID.ENDPOINT_ID]=g,this.httpRequestTelemetryData[un.CONTEXT_ID.ENDPOINT_ID]=g},this.setParticipantId=g=>{this.telemetryData[un.CONTEXT_ID.PARTICIPANT_ID]=g,this.contentSharingBaseTelemetryData[un.CONTEXT_ID.PARTICIPANT_ID]=g,this.httpRequestTelemetryData[un.CONTEXT_ID.PARTICIPANT_ID]=g},this.addTokenTelemetry=(g,f)=>{g?this.networkRequests?.[g]?(this.networkRequests[g].tokenTelemetries||(this.networkRequests[g].tokenTelemetries=[]),this.networkRequests[g].tokenTelemetries.push(f)):this.logger.info(`[addTokenTelemtry] httprequest: ${g} is not found in networkRequests`):this.logger.error("[addTokenTelemetry] httprequest uid is undefined")},this.setConversationServiceUrl=g=>{this.telemetryData[un.EXTENSIONS.CONVERSATION_SERVICE_URL]=g},this.setMeetingInfo=g=>{g||(this.telemetryData[un.EXTENSIONS.MEETING_INFO]=g)},this.setJoinedFrom=g=>{this.telemetryData[un.EXTENSIONS.JOINED_FROM]=g},this.setMeetingCode=g=>{this.telemetryData[un.EXTENSIONS.MEETING_CODE]=g},this.setMeetingUrl=g=>{this.telemetryData[un.EXTENSIONS.MEETING_URL]=g},this.setBroadcastMeetingRole=g=>{this.telemetryData[un.EXTENSIONS.BROADCAST_MEETING_ROLE]=g},this.setMeetingRole=g=>{this.telemetryData[un.EXTENSIONS.MEETING_ROLE]=g},this.setAdvancedMeetingRole=g=>{this.telemetryData[un.EXTENSIONS.ADVANCED_MEETING_ROLE]=g},this.setParticipantType=g=>{this.telemetryData[un.EXTENSIONS.PARTICIPANT_TYPE]=g},this.setSelfParticipantRole=g=>{this.telemetryData[un.EXTENSIONS.SELF_PARTICIPANT_ROLE]=g},this.setDisplayName=g=>{const f=new Ue(g,1);this.telemetryData[un.EXTENSIONS.DISPLAY_NAME]=f},this.setAudioOnlyWatermark=g=>{this.telemetryData[un.EXTENSIONS.AUDIO_ONLY_WATERMARK]=g},this.setWatermarkSupport=g=>{this.telemetryData[un.EXTENSIONS.CLIENT_SUPPORT_WATERMARK]=g},this.setClientSupportsPreventScreenCapture=g=>{this.telemetryData[un.EXTENSIONS.CLIENT_SUPPORTS_PREVENT_SCREEN_CAPTURE]=g},this.setScenario=g=>{this.telemetryData[un.EXTENSIONS.SCENARIO]=g},this.setTargetApplicationType=g=>{g&&(this.telemetryData[un.EXTENSIONS.TARGET_APPLICATION_TYPE]=g)},this.setCallerType=g=>{g&&(this.telemetryData[un.EXTENSIONS.CALLER_TYPE]=g.split(":",1)[0])},this.setCalleeType=g=>{g&&(this.telemetryData[un.EXTENSIONS.CALLEE_TYPE]=g.split(":",1)[0])},this.setTerminatingData=g=>{this.telemetryData[un.EXTENSIONS.CALL_TERMINATING_END]=g.terminatingEnd,this.telemetryData[un.EXTENSIONS.CALL_END_CODE]=g.endCode||an.CALL_END_CODE.SUCCESS,this.telemetryData[un.EXTENSIONS.CALL_END_SUB_CODE]=g.endSubCode||an.CALL_END_SUB_CODE.SUCCESS,this.telemetryData[un.EXTENSIONS.CALL_PHRASE]=g.phrase||an.CALL_END_PHRASE.UNKNOWN,this.telemetryData[un.EXTENSIONS.RESULT_VALUE]=g.resultValue||un.RESULT_VALUE.SUCCESS,this.telemetryData[un.EXTENSIONS.RESULT_DETAIL]=g.resultDetail||"Call gracefully hungup",this.telemetryData[un.EXTENSIONS.RESULT_CAUSE_ID]=g.causeId||"unknown",this.telemetryData[un.EXTENSIONS.CALL_END_RESULT_CATEGORIES]=g.resultCategories||[],this.telemetryData[un.EXTENSIONS.CALL_END_CLIENT_SUB_CODE]=g.clientReasonSubCode,this.telemetryData[un.EXTENSIONS.CALL_END_CLIENT_PHRASE]=g.clientReasonPhrase},this.startCallInitializationWatch=g=>{this.timeToRingStopWatch=build3(),g&&(this.timeToRingStopWatch.msElapsed+=g)},this.startCallConnectedWatch=()=>{this.connectedStopWatch=build3()},this.setIsPreheated=()=>{this.isPreheated=1},this.startPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch=build3()},this.stopPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch.pause()},this.startCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=build3()},this.stopCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch&&this.callCancelationDurationWatch.pause()},this.getCallCancelationDuration=()=>this.callCancelationDurationWatch?this.callCancelationDurationWatch.durationInSeconds():0,this.resetCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=null},this.setOfferAnswerGenerationTimestamps=g=>{this.localOfferAnswerGenerationTimestamps.push(this.recordOperation(g))},this.setTimeToRingDuration=()=>{this.timeToRingStopWatch&&(this.telemetryData[un.EXTENSIONS.TIME_TO_RING_IN_MS]=this.timeToRingStopWatch.duration(),this.timeToRingStopWatch=null)},this.dispose=()=>{this.sendCallModalityTelemetryData()},this.setMessagingChannel=g=>{this.telemetryData[un.EXTENSIONS.MESSAGING_CHANNEL]||(this.telemetryData[un.EXTENSIONS.MESSAGING_CHANNEL]=[]);this.telemetryData[un.EXTENSIONS.MESSAGING_CHANNEL].some((f=>-1!==f.indexOf(g)))||this.telemetryData[un.EXTENSIONS.MESSAGING_CHANNEL].push(this.recordOperation(g))},this.sendHttpTelemetryData=g=>{const f={...this.httpRequestTelemetryData};f[un.CONTEXT_ID.CORRELATION_ID]=this.signalingSession.correlationId,f[un.CONTEXT_ID.SIGNALING_SESSION_ID]=this.signalingSession.sessionId,f[un.EXTENSIONS.CLIENT_INFORMATION]=this.signalingSession.signalingAgentConfig.clientInformation;const S=JSON.stringify({eventStart:this.callStartTime,events:this.networkRequests[g]});tryRemoveKeyFromHashTable(this.networkRequests,g),f[un.EXTENSIONS.NETWORK_REQUESTS_BAG]=S,this.telemetryLogger.logHttpTelemetryEvent(f)},this.sdpTelemetryFormat=(g,f)=>{if(!g)return"";const convertType=g=>{switch(g){case"main-audio":return"Audio";case"main-video":return"Video";case"applicationsharing-video":return"AppSharing";default:return}},convertDirection=g=>{switch(g){case"inactive":return"Inactive";case"sendonly":return f?"ReceiveFromPeer":"SendToPeer";case"recvonly":return f?"SendToPeer":"ReceiveFromPeer";default:return"Bidirectional"}},S={"main-audio":0,"main-video":0,"applicationsharing-video":0},v=[],C=Yn.parse(g);for(const g of C.media){const f=convertType(g.label);if(!f)continue;const C=S[g.label]++,_=convertDirection(g.direction);v.push(`${f}[${C}] = ${_}`)}return v.join(", ")},this.setReinviteless=g=>{this.isReinviteless=g?1:0},this.logger=g.logger,this.telemetryLogger=getLogger(g,this.logger),this.telemetryData[un.EXTENSIONS.CALL_START_TIME]=this.callStartTime,this.telemetryData[un.EXTENSIONS.CONVERSATION_SERVICE_URL]=g.signalingAgentConfig.conversationServiceUrl,this.fillCommonData(f,this.telemetryData),this.fillCommonData(f,this.httpRequestTelemetryData),this.fillCommonData(f,this.contentSharingBaseTelemetryData)}fillCommonData(g,f){f[un.EXTENSIONS.APPLICATION_TYPE]=g.applicationType,f[un.EXTENSIONS.RING]=g.ring,f[un.EXTENSIONS.TENANT_ID]=g.tenantId,f[un.EXTENSIONS.USER_HEX_CID]=g.userHexCID,f[un.EXTENSIONS.ACS_RESOURCE_ID]=g.acsResourceId,f[un.EXTENSIONS.REGION]=g.region,f[un.EXTENSIONS.PARTITION]=g.partition,f[un.EXTENSIONS.CLIENT_TYPE]=g.clientType}addChangingCorrelationId(g,f){this.telemetryData[un.EXTENSIONS.CHANGING_CORRELATION_ID_OLD_ID]=g,this.telemetryData[un.EXTENSIONS.CHANGING_CORRELATION_ID_NEW_ID]=f}addSharedCorrelationId(g){this.telemetryData[un.CONTEXT_ID.SHARED_CORRELATION_ID]=g}setMeetingRoles(g){this.telemetryData[un.EXTENSIONS.MEETING_ROLES]=g}setConflictingCallId(g){this.telemetryData[un.EXTENSIONS.CONFLICTING_CALL_ID]=g}sendContentSharingTelemetryData(g,f,S,v,C,_){const T={...this.contentSharingBaseTelemetryData},I=this.contentSharingOperationsPerformed[g];I&&(T[un.EXTENSIONS.EVENT_TIMESTAMP_BAG]=JSON.stringify(I)),T[un.CONTEXT_ID.CONTENT_SHARING_CORRELATION_ID]=g,T[un.CONTEXT_ID.SIGNALING_SESSION_ID]=f,T[un.CONTEXT_ID.CONTENT_SHARING_ID]=_||"",T[un.EXTENSIONS.CONTENT_SHARING_SERVICE_URL]=C,T[un.EXTENSIONS.CONTENT_SHARING_DIRECTION]=S?un.DIRECTION.OUTGOING:un.DIRECTION.INCOMING,T[un.EXTENSIONS.CALL_END_CODE]=v.code,T[un.EXTENSIONS.CALL_END_SUB_CODE]=v.subCode,T[un.EXTENSIONS.CALL_PHRASE]=v.phrase,T[un.EXTENSIONS.CALL_END_RESULT_CATEGORIES]=this.getResultCategoryString(v.resultCategories),T[un.EXTENSIONS.CALL_END_CAUSE_ID]=v.causeId,T[un.EXTENSIONS.CLIENT_INFORMATION]=this.signalingSession.signalingAgentConfig.clientInformation,delete this.contentSharingOperationsPerformed[g],this.telemetryLogger.logConversationContentSharingEvent(T)}recordOperation(g){return`${g}:${this.timeSinceCallStart()}`}timeSinceCallStart(){return(new Date).getTime()-this.callStartTime}sendCallModalityTelemetryData(){this.vbssStarted&&this.addVbssOperations(un.VBSS_OPERATION.CALL_END);const durationMsToS=g=>"number"==typeof g?g/1e3:0;if(this.telemetryData[un.EXTENSIONS.CLIENT_INFORMATION]=this.signalingSession.signalingAgentConfig.clientInformation,this.telemetryData[un.EXTENSIONS.CALL_END_TIME]=(new Date).getTime(),this.connectedStopWatch&&(this.telemetryData[un.EXTENSIONS.CONNECTED_DURATION_IN_MS]=this.connectedStopWatch.duration()),this.telemetryData[un.EXTENSIONS.IS_PREHEATED]=this.isPreheated,this.preheatedCallSetupDurationWatch&&(this.telemetryData[un.EXTENSIONS.PREHEATED_CALL_SETUP_DURATION_IN_S]=durationMsToS(this.preheatedCallSetupDurationWatch.duration())),this.callCancelationDurationWatch&&(this.telemetryData[un.EXTENSIONS.CALL_CANCELATION_DURATION_IN_S]=durationMsToS(this.callCancelationDurationWatch.duration())),this.networkRequestsCompleted.length&&(this.telemetryData[un.EXTENSIONS.NETWORK_REQUESTS_COMPLETED]=JSON.stringify(this.networkRequestsCompleted)),this.localOperationsPerformed.length&&(this.telemetryData[un.EXTENSIONS.LOCAL_OPERATIONS_PERFORMED]=JSON.stringify(this.localOperationsPerformed)),this.trouterWaitOperations.length&&(this.telemetryData[un.EXTENSIONS.TROUTER_WAIT_OPERATIONS]=JSON.stringify(this.trouterWaitOperations)),this.localOfferAnswerGenerationTimestamps.length&&(this.telemetryData[un.EXTENSIONS.LOCAL_OFFER_ANSWER_GENERATION_TIMESTAMPS]=JSON.stringify(this.localOfferAnswerGenerationTimestamps)),this.incomingModalities.length&&(this.telemetryData[un.EXTENSIONS.INCOMING_MODALITIES]=JSON.stringify(this.incomingModalities)),this.outgoingModalities.length&&(this.telemetryData[un.EXTENSIONS.OUTGOING_MODALITIES]=JSON.stringify(this.outgoingModalities)),this.offeredModalities.length&&(this.telemetryData[un.EXTENSIONS.OFFERED_MODALITIES]=this.offeredModalities),this.answeredModalities.length&&(this.telemetryData[un.EXTENSIONS.ANSWERED_MODALITIES]=this.answeredModalities),this.telemetryData[un.EXTENSIONS.CALL_END_RESULT_CATEGORIES]=this.getResultCategoryString(this.telemetryData[un.EXTENSIONS.CALL_END_RESULT_CATEGORIES]),this.telemetryData[un.EXTENSIONS.IS_SDP_IN_CALL_NOTIFICATION]=this.isSdpInCallNotification.toString(),this.vbssOperations.length&&(this.telemetryData[un.EXTENSIONS.VBSS_OPERATIONS]=JSON.stringify(this.vbssOperations)),this.recordedEvents.length){const g=JSON.stringify({eventStart:this.callStartTime,events:this.recordedEvents});this.telemetryData[un.EXTENSIONS.EVENT_TIMESTAMP_BAG]=g}if(this.rosterUpdates.length){const g=JSON.stringify({eventStart:this.callStartTime,events:this.rosterUpdates});this.telemetryData[un.EXTENSIONS.ROSTER_UPDATES_BAG]=g}const g=[];for(const f of Object.keys(this.networkRequestsStarted))g.push(this.networkRequestsStarted[f]);g.length>0&&(this.telemetryData[un.EXTENSIONS.NETWORK_REQUESTS_PENDING]=JSON.stringify(g)),this.telemetryData[un.EXTENSIONS.IS_REINVITELESS]=this.isReinviteless,this.telemetryLogger.logConversationCallModalityEvent(this.telemetryData)}getResultCategoryString(g){return g&&Array.isArray(g)?g.join(","):""}},er=class{constructor(g,f){this.disposed=!1,this.lastSeenSeqNumbers={},this.isDominantSpeakerInfoLinkEnabled=!0,this.clientUrlsGenerated=!1,this.getClientUrls=()=>{this.clientUrlsGenerated=!0;let g=null;return this.isWebRtcCall&&(g={controlVideoStreaming:get2(this.signalingSession,rn.CONTROL_VIDEO_STREAMING),csrcInfo:get2(this.signalingSession,rn.CSRC_INFO)},this.isDominantSpeakerInfoLinkEnabled&&(g.dominantSpeakerInfo=get2(this.signalingSession,rn.DOMINANT_SPEAKER_INFO))),g},this.handleDominantSpeakerInfo=g=>{const f=g.body;this.logger.debug("handleDominantSpeakerInfo : ",getPrintableObject(f)),this.signalingSession.telemetryHelper.recordIncomingEventCount(dn.HANDLE_DOMINANT_SPEAKER_CHANGED_COUNT),this.handleWebRtcNotification(an.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO,f.dominantSpeakerInformation)},this.handleControlVideoStreaming=g=>{const f=g.body;this.logger.debug("handleControlVideoStreaming: ",getPrintableObject(f)),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_CONTROL_VIDEO_STREAMING,g),this.handleWebRtcNotification(an.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING,f.controlVideoStreaming,!1)},this.handleCsrcInfo=g=>{const f=g.body;this.logger.debug("handleCsrcInfo : ",getPrintableObject(f)),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_CSRC_INFO,g),this.handleWebRtcNotification(an.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO,f.csrcInfo)},this.sendWebRtcMediaNotificationAsync=({operation:g,requestUrl:f,requestBody:S,stackRetry:v=!0},C)=>{this.logger.info("sendWebRtcMediaNotificationAsync"),assert2(this.isWebRtcCall,"this is not a webrtc call"),assertNotNullOrEmpty(f,"correct media notification requestUrl is not provided"),assertNotNullOrEmpty(S,"media notification requestBody cannot be null or empty");const _=defer(),T={url:f,payload:{payload:S},requestName:g,withoutTrouter:!0,causeId:C};return v||(T.disableRetry=!0),this.signalingSession.http.sendPostRequest(T).then((()=>{this.disposed||_.resolve()})).catch((g=>{const f=getPrintableObject(g);if(this.logger.error(`sendWebRtcMediaNotificationAsync failed because : ${f}`),!this.disposed){const f=new Error(g);f.endCode=an.CALL_END_NETWORK_ERROR,_.reject(f)}})),_.promise},this.dispose=()=>{this.logger.info("WebRtcSignalingManager :: dispose"),this.disposed=!0},this.signalingSession=g,this.signalingSessionCallback=f,this.isWebRtcCall=g.signalingAgentConfig.isWebRtcEnabled,this.logger=g.logger,this.lastSeenSeqNumbers[an.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING]=-1,this.lastSeenSeqNumbers[an.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO]=-1,this.lastSeenSeqNumbers[an.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO]=-1}areClientURLsGenerated(){return this.clientUrlsGenerated}getIsDominantSpeakerInfoLinkEnabled(){return this.isDominantSpeakerInfoLinkEnabled}setIsDominantSpeakerInfoLinkEnabled(g){this.isDominantSpeakerInfoLinkEnabled=g}handleWebRtcNotification(g,f,S=!0){assert2(this.isWebRtcCall,"ignoring message in non-webrtc call");const v=this.lastSeenSeqNumbers[g];S&&f.sequenceNumber<=v?this.logger.info(`ignoring ${g} . Last seen seq = ${v} current seq = ${f.sequenceNumber}`):(f.sequenceNumber<=v&&this.logger.info(`let listener to handle older ${g} . Last seen seq = ${v} current seq = ${f.sequenceNumber}`),this.lastSeenSeqNumbers[g]=Math.max(f.sequenceNumber,this.lastSeenSeqNumbers[g]),this.signalingSessionCallback.onWebRtcMediaNotification(g,f))}},tr=class{constructor(g,f,S,v,C,_){this.disposed=!1,this.convSubject=null,this.groupId=null,this.threadId=null,this.incomingCallCallerId=null,this.incomingCallPayload=null,this.multiParty=!0,this.isIncomingCall=!1,this.isHostLessCall=!1,this.isCastCall=!1,this.isHuddleGroupCall=!1,this.numberOfOriginalInvitees=0,this.teamsMessageId=null,this.enableGroupCallMeetupGeneration=!1,this.meetingInfo=null,this.meetingDetails=null,this.emergencyContent=null,this.transferContext=null,this.callType="default",this.callMode=0,this.transferor=null,this.onBehalfOf=null,this.onBehalfOfUserDisplayName=null,this.callQueueContext=null,this.callQueueSupervisorContent=null,this.bannerContent=null,this.callPhoneLineType=null,this.endpointMetadata={},this.sessionId=newGuid(),this.remoteCaller=null,this.acceptedElsewhereBy=null,this.parkAdditionalContextJson=null,this.serverHoldLocation=null,this.breakoutDetails=null,this.callLimits=null,this.complianceRecordingContent=null,this.backroomThreadId=null,this.streamThreadId=null,this.lobbyThreadId=null,this.conversationStartTime=null,this.realTimeState=0,this.disposing=!1,this.links={},this.provisionalMediaAnswersSeenSoFar=[],this.incomingTrouterMessagesSeenSoFar=[],this.incomingBrokerMessagesSeenSoFar=[],this.currentCallStatus=null,this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.convJoined=!1,this.keepAliveTimer=null,this.keepAliveInterval=null,this.keepAliveCount=1,this.conversationKeepAliveTimer=null,this.conversationKeepAliveInterval=null,this.conversationKeepAliveCount=1,this.remoteUser=null,this.mediaTypesToUse=null,this.lastUsedOutgoingMediaContent=null,this.lastUsedJoinCallOptions=null,this.originalRoleBeforePreheat="",this.endpointStateSequenceNumber=0,this.publishStateSequenceNumber=0,this.monitorSequenceId=0,this.requestedPublishedStatesWhileConnecting=null,this.linkUpdateRequested={conversationLinks:!1,keepAliveLinks:!1},this.incomingMessageSyncResponseCache={},this.isPreheatOnly=!1,this.callStartTime=(new Date).getTime(),this.callUsesMixer=!1,this.disablePreheatDefer=defer(),this.participantReplacementDetails={},this.meetingLiveStateSequenceNumber=0,this.meetingLayoutSequenceNumber=0,this.localParticipantUpdateSequenceNumber=0,this.isRedirectAllowed=!1,this.updateSequenceNumber=-1,this.isPromotingToRealtime=!1,this.streamInformationReceived=!1,this.startOrJoinConvResponseReceived=!1,this.updateParticipantsPromises={},this.updateEndpointState=(g,f=causeId2(),S,v)=>{this.logger.info(`[${f}][requestedEndpointState=${getPrintableObject(g,!0)}][captchaContentJson=${v}]`);const C=this.links[an.LINKS.UPDATE_ENDPOINT_STATE],_=this.getEndpointState();this.logger.info(`[${f}][currentEndpointState=${getPrintableObject(_,!0)}] startOrJoinConvResponseReceived=${this.startOrJoinConvResponseReceived}`);const T={..._,...g,endpointStateSequenceNumber:++this.endpointStateSequenceNumber};this.telemetryHelper.recordEvent(dn.UPDATE_ENDPOINT_STATE,{newEndpointState:T,causeId:f});const I=0===T?.endpointProperties?.preheatProperties&&this.isPreheatOnly;if(I&&(this.telemetryHelper.recordEvent(dn.PREHEAT_DISABLING,{causeId:f}),this.telemetryHelper.startPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallCancelationDurationWatch()),2===this.callMode&&I)return this.logger.info(`[${f}][updateEndpointState skipped as mode is streaming]`),this.handleEndpointStateUpdated(f,!0),Promise.resolve();if(!this.startOrJoinConvResponseReceived)return this.logger.info(`[${f}][updateEndpointState will be queued as we don't have a link yet]`),this.requestedEndpointStateWhileConnecting=g,this.requestedPublishedStatesWhileConnecting=S,I?this.disablePreheatDefer.promise:Promise.resolve();if(!this.shouldUpdateEndpointState(_,T)&&!this.http.hasPendingRequest(hn.UPDATE_ENDPOINT_STATE.name))return this.logger.info(`[${f}][updateEndpointState will ignore current update as there is nothing new to send]`),Promise.resolve();if(!C)return this.logger.info(`[${f}][updateEndpointState operation cannot be performed now, the link is not yet available]`),Promise.reject("No link");this.latestEndpointState=T;const b=this.signalingAgentConfig.enableAsyncDisablePreheat&&I;b&&this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT,(()=>{const g={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.DISABLE_PREHEAT_TIMEOUT,phrase:an.CALL_END_PHRASE.DISABLE_PREHEAT_TIMEOUT};this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject({response:g})}),an.TIMEOUT_VALUES_IN_SECONDS.DISABLE_PREHEAT_TIMEOUT);const A=this.http.sendPostRequest({url:C,requestName:hn.UPDATE_ENDPOINT_STATE.name,payload:getPayload52(this,T,S,b,v),causeId:f}).then((()=>(b&&(this.logger.info(`[${f}][updateEndpointState] asyncDisablePreheat: true`),this.telemetryHelper.recordEvent(dn.DISABLE_PREHEAT_RESPONSE_RECEIVED,{causeId:f})),Promise.resolve()))).catch((g=>{if(!b)throw g;this.disablePreheatDefer.reject(g)}));return(b?this.disablePreheatDefer.promise:A).then((()=>{this.logger.info(`[${f}][updateEndpointState] asyncDisablePreheat: ${b}`),this.telemetryHelper.recordEvent(b?dn.ASYNC_DISABLE_PREHEAT_SUCCEEDED:dn.DISABLE_PREHEAT_SUCCEEDED,{causeId:f}),this.disposed||this.handleEndpointStateUpdated(f,I)})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[${f}][updateEndpointState] error: ${getPrintableObject(S)}`),I&&(this.handleDisablePreheatError(S.error,b?dn.ASYNC_DISABLE_PREHEAT_FAILED:dn.DISABLE_PREHEAT_FAILED,f),this.stopCallPreheatTimer(),this.terminateEstablishedCall({code:S.error.code,subCode:S.error.subCode,phrase:S.error.phrase},{forEveryone:!1,causeId:f})),Promise.reject(S.error)}))},this.setParticipantCallLinks=g=>{g&&g.endpointDetails&&(this.participantReplacementDetails[g.id]={},g.endpointDetails.forEach((f=>{f&&f.callLinks&&(this.participantReplacementDetails[g.id][f.participantId]=f.callLinks)})))},this.clearParticipantCallLinks=g=>{this.participantReplacementDetails?.hasOwnProperty(g)&&delete this.participantReplacementDetails[g]},this.getReplacementDetailsByParticipantLeg=(g,f,S=causeId2())=>(this.logger.info(`[${S}]getReplacementDetailsByParticipantLeg: participantMri ${this.piiUtils.scrubMriOrOmit(g)} participantLegId ${f}`),this.participantReplacementDetails?.hasOwnProperty(g)&&this.participantReplacementDetails[g].hasOwnProperty(f)?{replaces:this.participantReplacementDetails[g][f].replacement,replacementTargetParticipantId:f}:(this.logger.info(`[${S}]getReplacementDetailsByParticipantLeg: unable to find replacement details for participantLegId ${f}`),{})),this.getReplacementDetailsByParticipantLegOfCall=(g,f,S,v=causeId2())=>{this.logger.info(`[${v}]getReplacementDetailsByParticipantLegOfCall: callId ${g} participantMri ${this.piiUtils.scrubMriOrOmit(f)} participantLegId ${S}`);const C=this.signalingAgent.getSignalingSession(g);return C?C.getReplacementDetailsByParticipantLeg(f,S,v):{}},this.getMriByParticipantLegOfCall=(g,f,S)=>{this.logger.info(`[${S}]getMriByParticipantLegOfCall: callId: ${g} participantLegId ${f}`);const v=this.signalingAgent.getSignalingSession(g);return v?v.getMriByParticipantLeg(f,S):""},this.getMriByParticipantLeg=(g,f)=>{this.logger.info(`getMriByParticipantLeg[${f}] participantLegId ${g}`);for(const f of Object.keys(this.participantReplacementDetails))if(f&&this.participantReplacementDetails.hasOwnProperty(f)&&this.participantReplacementDetails[f]?.hasOwnProperty(g))return f;return""},this.handleEndpointStateUpdated=(g,f)=>{this.requestedEndpointStateWhileConnecting=null,this.requestedPublishedStatesWhileConnecting=null,f&&this.handlePreheatDisabled(g)},this.handlePreheatDisabled=g=>{this.isPreheatOnly=!1,this.telemetryHelper.setSelfParticipantRole(this.originalRoleBeforePreheat),this.telemetryHelper.recordEvent(dn.PREHEAT_DISABLED,{causeId:g}),this.telemetryHelper.resetCallCancelationDurationWatch(),this.telemetryHelper.stopPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallConnectedWatch(),this.stopCallPreheatTimer(),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.resolve()},this.shouldUpdateEndpointState=(g,f)=>{if(!f)return!1;const S=f.state&&f.state.isMuted?1:0,v=f.endpointProperties&&1===f.endpointProperties.preheatProperties?1:0,C=g&&g.state&&g.state.isMuted?1:0,_=g&&g.endpointProperties&&1===g.endpointProperties.preheatProperties?1:0,T=g?.endpointProperties?.additionalEndpointProperties,I=f?.endpointProperties?.additionalEndpointProperties;return!!(S^C||v^_||I!==T)},this.setInitialTelemetry=(g,f)=>{let S,v;switch(g){case"Subscribe":this.telemetryHelper.recordEvent(dn.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY,{causeId:f.causeId,correlationId:f.correlationId}),this.telemetryHelper.setDirection(un.DIRECTION.OUTGOING),this.telemetryHelper.setSelfParticipantRole(un.ROLE.JOIN_FOR_ROSTER_ONLY),this.telemetryHelper.setConversationServiceUrl(f.conversationServiceUrl||this.signalingAgentConfig.conversationServiceUrl),this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);break;case"Acknowledge":this.telemetryHelper.recordEvent(dn.HANDLE_INCOMING_CALL,{causeId:f.causeId}),this.telemetryHelper.setDirection(un.DIRECTION.INCOMING),this.telemetryHelper.setSelfParticipantRole(un.ROLE.CALLEE),this.telemetryHelper.setCalleeType(this.participantManager.localParticipant.id);break;case"JoinCall":S=this.gatherTelemetryForStartOrJoin(f.joinCallOptions,f.causeId,f.offerGenerationTime),this.telemetryHelper.recordEvent(dn.JOIN_CALL,S),this.telemetryHelper.setDirection(un.DIRECTION.OUTGOING),this.telemetryHelper.setSelfParticipantRole(un.ROLE.JOIN);break;case"StartCall":case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":v=this.gatherTelemetryForStartOrJoin(f.callStartOptions,f.causeId,f.offerGenerationTime),this.telemetryHelper.recordEvent(dn.START_CALL,v),this.telemetryHelper.setDirection(un.DIRECTION.OUTGOING),this.telemetryHelper.setSelfParticipantRole(un.ROLE.CALLER),this.telemetryHelper.startCallInitializationWatch(f.offerGenerationTime),this.telemetryHelper.setMeetingInfo(this.getMeetingInfo())}},this.getParticipantIdForOfferAnswer=g=>{assertNotNull(g,"mediaContent should be a non null value"),this.logger.info("getParticipantIdForOfferAnswer");let f=null;return!this.remoteUser||this.groupId||this.threadId||g.newOffer||g.escalationOccurring||(f=this.remoteUser.id),f},this.getMeetingInfo=()=>this.meetingInfo,this.getEmergencyContent=()=>(this.telemetryHelper.recordEvent(dn.GET_EMERGENCY_CONTENT),this.emergencyContent),this.getEndpointId=()=>this.signalingAgent.endpointId,this.getConversationUrl=()=>this.links[an.LINKS.CONVERSATION_CONTROLLER],this.setJoinedFrom=g=>{!this.disposed&&g&&(this.telemetryHelper.recordEvent(dn.SET_JOINED_FROM),this.telemetryHelper.setJoinedFrom(g))},this.setMeetingCode=g=>{!this.disposed&&g&&this.telemetryHelper.setMeetingCode(g)},this.setMeetingUrl=g=>{!this.disposed&&g&&this.telemetryHelper.setMeetingUrl(g)},this.setSubject=g=>{this.disposed||(this.telemetryHelper.recordEvent(dn.SET_SUBJECT),assertNotNull(g,"subject should be a non null value"),this.convSubject=g)},this.setDeviceType=g=>{this.disposed||(this.telemetryHelper.recordEvent(dn.SET_DEVICETYPE),g&&(this.deviceType=g,this.logger.info("setDeviceType",this.deviceType)))},this.setOfferAnswerGenerationTimestamps=g=>{this.disposed||this.telemetryHelper.setOfferAnswerGenerationTimestamps(g)},this.setTimeToRingDuration=()=>{this.disposed||this.telemetryHelper.setTimeToRingDuration()},this.setGroupId=g=>{this.telemetryHelper.recordEvent(dn.SET_GROUPID),this.groupId!==g&&g&&(assert2(!this.groupId,"conversation groupId has already been set. It cannot be overwritten"),this.groupId=g)},this.setThreadId=g=>{this.telemetryHelper.recordEvent(dn.SET_THREADID),assertNotNull(g,"threadId should be a non null value"),this.threadId!==g&&(assert2(!this.threadId,"conversation threadId has already been set. It cannot be overwritten"),this.threadId=g)},this.setDisplayName=g=>{!this.disposed&&g&&this.telemetryHelper.setDisplayName(g)},this.setCallOptions=g=>{if(assertNotNull(g,"callOptions should be a non null value"),this.logger.info("setCallOptions",getPrintableObject(g)),this.telemetryHelper.recordEvent(dn.SET_CALLOPTIONS),g){this.teamsMessageId=g.teamsMessageId,this.meetingInfo=g.meetingInfo||null,this.emergencyContent=g.emergencyContent||null,this.enableGroupCallMeetupGeneration=g.enableGroupCallMeetupGeneration||!1,g.broadcastContext&&(this.broadcastSession=new yn(this,this.signalingSessionCallback),this.broadcastSession.setContext(g.broadcastContext));try{this.endpointMetadata=JSON.parse(g.endpointMetadata)}catch(g){this.logger.warn("Unable to parse endpoint metadata")}}},this.setTransferContext=g=>{assertNotNull(g,"transferContext should not be null"),this.logger.info("Transfer: setTransferContext",scrubObjectFields(g)),this.telemetryHelper.recordEvent(dn.SET_TRANSFER_CONTEXT),this.transferContext=g},this.muteAsync=(g,f,S=causeId2())=>(assert2(2!==this.callMode||g!==an.MUTE_SCOPE.MYSELF,"mute self operation is not allowed in streaming mode"),this.logger.info(`[${S}][muteAsync][scope=${g}]`),this.telemetryHelper.recordEvent(dn.MUTE,{causeId:S}),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,`[${S}]mute operation for all or specified only allowed in a connected call`),this.participantManager.muteAsync(this.links[an.LINKS.MUTE],g,f,S)),this.unmuteAsync=(g=causeId2())=>(assert2(2!==this.callMode,"unmute operation is not allowed in streaming mode"),this.logger.info(`[${g}][unmuteAsync]`),this.telemetryHelper.recordEvent(dn.UNMUTE,{causeId:g}),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"unmute operation only allowed in a connected call"),this.participantManager.unmuteAsync(this.links[an.LINKS.UNMUTE],g)),this.recordTelemetryForStartAudio=(g,f)=>(this.telemetryHelper.recordEvent(dn.START_AUDIO,{mediaNegotiationStatus:g,causeId:f}),Promise.resolve(null)),this.recordTelemetryForStopAudio=(g,f)=>(this.telemetryHelper.recordEvent(dn.STOP_AUDIO,{mediaNegotiationStatus:g,causeId:f}),Promise.resolve(null)),this.rejectUnmuteRequestAsync=(g,f=causeId2(),S)=>(assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"rejectUnmute operation only allowed in a connected call"),assertNotNullOrEmpty(g,"requestor must be specified"),this.logger.info(`[${f}][rejectUnmuteRequestAsync][rejectionReason=${S}]`),this.telemetryHelper.recordEvent(dn.REJECT_UNMUTE,{causeId:f,rejectionReason:S}),this.participantManager.rejectUnmuteRequestAsync(g,f,S)),this.approveUnmuteRequestAsync=(g,f=causeId2())=>(assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"approveUnmute operation only allowed in a connected call"),assertNotNullOrEmpty(g,"requestor must be specified"),this.logger.info(`[${f}][approveUnmuteRequestAsync]`),this.telemetryHelper.recordEvent(dn.APPROVE_UNMUTE,{causeId:f}),this.participantManager.approveUnmuteRequestAsync(g,f)),this.sendWebRtcMediaNotificationAsync=(g,f,S=causeId2())=>(assert2(2!==this.callMode,"sendWebRtcMediaNotification operation is not allowed in streaming mode"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"webRtc media notification can only be sent in a connected call"),this.telemetryHelper.recordEvent(dn.SEND_WEBRTC_MEDIA_NOTIFICATION,{causeId:S}),0===g?this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:hn.SEND_APPLY_CHANNEL_PARAMETERS.name,requestUrl:this.links[an.LINKS.APPLY_CHANNEL_PARAMETERS],requestBody:f,stackRetry:!1},S):this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:hn.SEND_CONTROL_VIDEO_STREAMING.name,requestUrl:this.links[an.LINKS.CONTROL_VIDEO_STREAMING],requestBody:f},S)),this.addParticipantsAsync=(g,f,S=causeId2())=>{assertNotNullOrEmpty(g,"remoteParticipants should be a non null value"),assert2(this.isCallOngoing()||this.isCallIdleOrRosterOnly(),"remoteParticipants can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${S}][addParticipantsAsync][addParticipantOptions=${getPrintableObject(f)}]\n            [remoteParticipantId=${g.map((g=>this.piiUtils.scrubMriOrOmit(g.id)))}]`);let v=dn.ADD_PARTICIPANT;switch(f.replacementType){case 2:v=dn.ADD_PARTICIPANT_WITH_PICKUP_CODE;break;case 1:case 3:v=dn.ADD_PARTICIPANT_WITH_REPLACES;break;default:v=dn.ADD_PARTICIPANT}this.telemetryHelper.recordEvent(v,{causeId:S}),f.groupId=this.groupId||f.groupId,f.threadId=this.threadId||f.threadId;const C=f.threadId||f.groupId?this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[an.LINKS.ADD_PARTICIPANT],_=this.participantManager.addParticipantsAsync(g,C,this.isCallConnectedOrConnectedForRoster(),f,S);return this.currentCallStatus||this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,S),_},this.addGroupModalityAsync=(g,f)=>{assert2(this.isCallOngoing(),"GroupModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${f}][addGroupModalityAsync][addGroupModalityOptions=${getPrintableObject(g)}]`);const S=dn.ADD_PARTICIPANTS_AND_MODALITY;this.telemetryHelper.recordEvent(S,{causeId:f});const v=getPayload11(this,null,g);return this.http.sendPostRequest({url:this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY],payload:v,requestName:hn.ADD_PARTICIPANTS_AND_MODALITY.name,causeId:f}).then((()=>{Cn.noop()})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][sendNetworkRequestForAddingParticipant] failed:${getPrintableObject(S)}`);throw S.error}))},this.addModalityAsync=(g,f)=>{assert2(this.isCallOngoing(),"GroupModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${f}][addModalityAsync][modalityContext=${getPrintableObject(g)}]`),this.telemetryHelper.recordEvent(dn.ADD_MODALITY,{causeId:f});const S=getPayload25(this,g);return this.http.sendPostRequest({url:this.links[an.LINKS.ADD_MODALITY],payload:S,requestName:hn.ADD_MODALITY.name,causeId:f}).then((g=>(this.logger.info(`[${f}][addModalityAsync] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_ADD_MODALITY_COMPLETION,{causeId:f}),an.SUCCESS_TRANSACTION_END))).catch((g=>{const S=getErrorForXHRFailure(g);return this.logger.info(`[${f}][sendNetworkRequestForAddModalityAsync] failed:${getPrintableObject(S)}`),Promise.reject(S.error)}))},this.addBroadcastModalityAsync=(g,f)=>{if(assert2(this.isCallOngoing(),"BroadcastModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${f}][addBroadcastModalityAsync][addBroadcastContext=${getPrintableObject(this.addBroadcastModalityAsync)}]`),this.telemetryHelper.recordEvent(dn.ADD_BROADCAST_MODALITY,{causeId:f}),this.broadcastSession){const g="There is already a broadcast session";return this.logger.info(g),Promise.resolve(an.SUCCESS_TRANSACTION_END)}this.broadcastSession=new yn(this,this.signalingSessionCallback),this.broadcastSession.setContext(g);const S=getPayload24(this,g);return this.http.sendPostRequest({url:this.links[an.LINKS.ADD_MODALITY],payload:S,requestName:hn.ADD_BROADCAST_MODALITY.name,causeId:f}).then((g=>(this.logger.info(`[${f}][addBroadcastModalityAsync] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_ADD_BROADCAST_MODALITY_COMPLETION,{causeId:f}),an.SUCCESS_TRANSACTION_END))).catch((g=>{const S=getErrorForXHRFailure(g);return this.logger.info(`[${f}][sendNetworkRequestForAddBroadcastModalityAsync] failed:${getPrintableObject(S)}`),this.endBroadcastMeeting(f),Promise.reject(S.error)}))},this.nudgeParticipantsAsync=g=>{if(assertNotNull(g.participantsIds,"ParticipantsIds should be a non null value"),assert2(this.isCallOngoing(),"Participants can only be nudged before starting an outgoing call or to an ongoing call"),this.logger.info(`[${g.causeId}][nudgeParticipantsAsync][participantsIds=${this.piiUtils.scrubParticipantsList(g.participantsIds)}][invitationData=${g.invitationData}]`),void 0===g.participantsIds||g.participantsIds.length<1)return Promise.reject("List of participants to nudge is empty");this.telemetryHelper.recordEvent(dn.ADD_PARTICIPANT,{withNudge:an.INVITATION_TYPE.NUDGE,causeId:g.causeId});const f=this.groupId||g.newGroupId,S=this.threadId||g.newThreadId,v=this.teamsMessageId||g.newMessageId,C=S||f?this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[an.LINKS.ADD_PARTICIPANT];return this.participantManager.nudgeParticipantsAsync(g.participantsIds,C,this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,g.causeId,g.invitationData,f,S,v)},this.callMeBackAsync=(g,f=causeId2())=>(assertNotNull(g,"remoteParticipant should be a non null value"),this.logger.info(`[${f}][callMeBackAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(g.id)}]`),this.telemetryHelper.recordEvent(dn.CALL_ME_BACK,{causeId:f}),this.hasGroupModality()||assert2(!1,"threadId/groupId must be set before using call me back"),this.participantManager.callMeBackAsync(g,this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY],f)),this.removeParticipantAsync=(g,f=causeId2(),S="none")=>{switch(assertNotNull(g,"remoteParticipant should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"participants can only be removed from an ongoing call"),this.logger.info(`[${f}][removeParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(g.id)}] [removeEndpointScope] ${S}`),S){case"all":this.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT_OTHERS,{causeId:f});break;case"specified":this.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT_SPECIFIED,{causeId:f});break;default:this.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT,{causeId:f})}return"none"!==S&&g.endpointId?this.participantManager.removeParticipantEndpointAsync(g,this.links[an.LINKS.REMOVE_PARTICIPANT],S,f):this.participantManager.removeParticipantAsync(g,this.links[an.LINKS.REMOVE_PARTICIPANT],f)},this.admitParticipantAsync=(g,f=causeId2())=>(assertNotNull(g,"remoteParticipant should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"remoteParticipants can only be admitted to an ongoing call"),this.hasGroupModality()||assert2(!1,"threadId/groupId must be set before admitting more participants to connected call"),this.logger.info(`[${f}][admitParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(g.id)}]`),this.telemetryHelper.recordEvent(dn.ADMIT_PARTICIPANT,{causeId:f}),this.participantManager.admitParticipantAsync(g,this.links[an.LINKS.ADMIT],f)),this.admitAsync=g=>{if(this.logger.info(`[${g}][admitAsync]`),this.telemetryHelper.recordEvent(dn.ADMIT,{causeId:g}),!this.links[an.LINKS.ADMIT_ALL]){const f={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.ADMIT_ALL_LINK_MISSING,phrase:an.CALL_END_PHRASE.ADMIT_ALL_URL_MISSING};return this.telemetryHelper.recordEvent(dn.ADMIT_FAILURE,{causeId:g,transactionEnd:f}),this.logger.warn(`admitAsync error ${getPrintableObject(f)}`),Promise.reject(f)}const f=defer();return this.callOperationHandler.setPendingOperation(0,g,{promise:f,causeId:g},g),this.sendNetworkRequestForAdmit(g),f.promise},this.updateMeetingRolesAsync=(g,f,S=causeId2())=>(assertNotNull(g,"participants array should be a non null value"),assertNotNull(f,"meetingRole should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"remote participant roles can only be updated in an ongoing call"),this.logger.info(`[${S}][updateMeetingRolesAsync][participants=${this.piiUtils.scrubMriOrOmit(g)}]`),this.participantManager.updateMeetingRolesAsync(g,f,this.links[an.LINKS.UPDATE_PARTICIPANT_ROLE],S)),this.startContentSharingAsync=(g,f,S,v,C=causeId2())=>(assertNotNull(g,"contentIdentifier should be a non null value"),assert2(this.isCallOngoing(),"contentSharing can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${C}][startContentSharingAsync]`),this.telemetryHelper.recordEvent(dn.ADD_CONTENT_SHARING_MODALITY,{causeId:C}),this.contentSharingManager.startContentSharingAsync(g,f,S,this.links[an.LINKS.ADD_MODALITY],this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,C,v)),this.deleteContentSharingAsync=(g,f=causeId2())=>(this.logger.info(`[${f}][deleteContentSharingAsync][correlationId=${g}]`),this.telemetryHelper.recordEvent(dn.DELETE_CONTENT_SHARING,{causeId:f,correlationId:g}),this.contentSharingManager.deleteContentSharingAsync(g,f)),this.joinContentSharingAsync=(g,f=causeId2())=>(this.logger.info(`[${f}][joinContentSharingAsync][correlationId=${g}]`),this.telemetryHelper.recordEvent(dn.JOIN_CONTENT_SHARING,{causeId:f,correlationId:g}),this.contentSharingManager.joinContentSharingAsync(g,f)),this.updateContentSharingSessionStateAsync=(g,f,S=causeId2())=>(assertNotNull(f,"sessionState should be a non null value"),this.telemetryHelper.recordEvent(dn.UPDATE_SESSION_STATE_CONTENT_SHARING,{causeId:S,correlationId:g}),this.logger.info(`[${S}][updateContentSharingSessionStateAsync][correlationId=${g}][sessionState=${f}]`),this.contentSharingManager.updateContentSharingSessionStateAsync(g,f,S)),this.takeContentSharingControlAsync=(g,f=causeId2())=>(this.telemetryHelper.recordEvent(dn.TAKE_CONTROL_CONTENT_SHARING,{causeId:f,correlationId:g}),this.logger.info(`[${f}][takeContentSharingControlAsync][correlationId=${g}]`),this.contentSharingManager.takeContentSharingControlAsync(g,f)),this.updateContentSharingParticipantStateAsync=(g,f=causeId2())=>(this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING,{causeId:f}),this.logger.info(`[${f}][updateContentSharingParticipantStateAsync][correlationId=${g}]`),this.contentSharingManager.updateContentSharingParticipantStateAsync(g,f)),this.configureEndpointStateForStartOrJoin=g=>{const f={endpointStateSequenceNumber:this.endpointStateSequenceNumber};let S=!1;if(g&&(g.muted&&(S=!0,Object.assign(f,{state:{isMuted:g.muted}})),g.isPreheatOnly||g.additionalEndpointProperties)){const v={};S=!0,g.isPreheatOnly&&(v.preheatProperties=1),g.additionalEndpointProperties&&(v.additionalEndpointProperties=g.additionalEndpointProperties),Object.assign(f,{endpointProperties:v})}if(S)return f},this.gatherTelemetryForStartOrJoin=(g,f,S)=>{const v={causeId:f};return g&&(g.invitationType===an.INVITATION_TYPE.NUDGE&&(v.withNudge=g.invitationType===an.INVITATION_TYPE.NUDGE),g.parkContext&&(v.unpark=!0,v.context=g.parkContext),g.isPreheatOnly&&(v.isPreheatOnly=!0),g.targetApplicationType&&(v.targetApplicationType=g.targetApplicationType,this.telemetryHelper.setTargetApplicationType(g.targetApplicationType))),v},this.startOutgoingCall=(g,f,S,v,C=causeId2())=>{if(assertNotNull(g,"mediaContent should be a non null value"),assertNotNull(g.blob,"outgoingSdp should be a non null value"),assert2(this.isCallIdleOrRosterOnly(),"a call is already in progress"),this.logger.info(`[${C}][startOutgoingCall][start] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${C}][startOutgoingCall][failed][reason=Session disposed]`);this.lastUsedJoinCallOptions={muted:S?S.muted:null,scenario:S?S.scenario:null,isPreheatOnly:S?S.isPreheatOnly:null,clientEndpointCapabilities:S?S.clientEndpointCapabilities:null,clientEndpointDebugContent:S?S.clientEndpointDebugContent:null},this.originalRoleBeforePreheat=un.ROLE.CALLER,S&&S.scenario&&this.telemetryHelper.setScenario(S.scenario),this.logger.info(`[${C}][startOutgoingCall]options=${getPrintableObject(this.gatherTelemetryForStartOrJoin(S,C,v))}`),this.isBrokerEnabledForOutgoingCall()&&this.setupBrokerChannel(),this.callUsesMixer=!(!S||!S.callUsesMixer),this.fsmState=an.SIGNALING_FSM_STATE.OUTGOING,this.meetingData=S?.meetingData,this.meetingPreferences=S?.meetingPreferences;const _={newCall:!0,suppressDialout:S&&S.suppressDialout||!1,conversationServiceUrl:this.signalingAgentConfig.conversationServiceUrl,onBehalfOf:S?S.onBehalfOf:null,onBehalfOfUserDisplayName:S?S.onBehalfOfUserDisplayName:null,callQueueContext:S?S.callQueueContext:null,callToVoicemail:!!S&&S.callToVoicemail,voicemailResourcePath:S?S.voicemailResourcePath:null,voicemailItemId:S?S.voicemailItemId:null,endpointState:this.configureEndpointStateForStartOrJoin(S),invitationType:S&&S.invitationType?S.invitationType:null,participantsToNudge:S&&Array.isArray(S.participantsToNudge)?S.participantsToNudge:null,routingFlags:S?S.routingFlags:null,parkContext:S?S.parkContext:null,pickupCode:S?S.pickupCode:null,scenario:S?S.scenario:null,isPreheatOnly:!!S&&S.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:S?S.clientEndpointCapabilities:0,clientEndpointDebugContent:S?S.clientEndpointDebugContent:null,invitationData:S?S.invitationData:null,conversationType:S?this.getConversationType(S.isEmergency,S.castCall,S.isHuddleGroupCall):null,meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,alternateId:S?S.alternateId:null,meetingRegistrationId:S?S.meetingRegistrationId:null,participantPin:S?S.participantPin:null,publishedStates:S?S.publishedStates:null,targetApplicationType:S?S.targetApplicationType:null,captchaContentJson:S?S.captchaContentJson:null,customHeaderContext:S?S.customHeaderContext:null,participationPreferences:S?S.participationPreferences:null};this.isCastCall=S&&S.castCall,this.isHuddleGroupCall=S&&S.isHuddleGroupCall,this.onBehalfOf=_.onBehalfOf,this.onBehalfOfUserDisplayName=_.onBehalfOfUserDisplayName,this.callQueueContext=_.callQueueContext,this.startOrJoinCall(_,hn.START_CALL.name,C,g,f)},this.joinGivenConversation=(g,f,S,v,C,_={},T=causeId2())=>{if(assertNotNull(f,"correlationId should be a non null value"),assertNotNullOrEmpty(g||this.getConversationUrl(),"conversationUrl should be a non null value"),assertNotNull(S,"mediaContent should be a non null value"),assertNotNull(S.blob,"outgoingSdp should be a non null value"),this.isPromotingToRealtime=2===this.callMode,assert2(this.isCallIdleOrRosterOnly()||this.isPromotingToRealtime,"a call is already in progress"),this.logger.info(`[${T}][joinGivenConversation][start][correlationId=${f}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${T}][joinGivenConversation][failed][reason=Session disposed]`);const I=this.gatherTelemetryForStartOrJoin(_,T,C);this.lastUsedJoinCallOptions=_,this.originalRoleBeforePreheat=un.ROLE.JOIN,this.telemetryHelper.startCallInitializationWatch(C),_&&_.scenario&&this.telemetryHelper.setScenario(_.scenario),this.logger.info(`[${T}][joinGivenConversation]options=${getPrintableObject(I)}`),this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=an.SIGNALING_FSM_STATE.OUTGOING,this.updateCorrelationId(f,T),this.meetingData=_?.meetingData,this.meetingPreferences=_?.meetingPreferences;const b={newCall:!1,suppressDialout:!0,conversationServiceUrl:g,endpointState:this.configureEndpointStateForStartOrJoin(_),scenario:_?_.scenario:null,isPreheatOnly:!!_&&_.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:_?_.clientEndpointCapabilities:0,clientEndpointDebugContent:_?_.clientEndpointDebugContent:null,conversationType:_?this.getConversationType(_.isEmergency,!1):null,meetingPreferences:this.meetingPreferences,meetingData:this.meetingData,meetingRegistrationId:_?.meetingRegistrationId,participantPin:_?.participantPin,sharedLineCallInvitationContent:_?.sharedLineCallInvitationContent,applyServerMute:_?.applyServerMute,publishedStates:_?.publishedStates,invitationData:_?.invitationData,captchaContentJson:_?.captchaContentJson,callQueueContext:_?.callQueueContext,participationPreferences:_?.participationPreferences};this.isCastCall=!1,this.startOrJoinCall(b,hn.JOIN_CONVERSATION.name,T,S,v)},this.subscribeToCall=(g,f,S=0,v,C=causeId2())=>{assertNotNull(f,"correlationId should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.IDLE,"a call is already in progress");let _=g;return _||(_=this.signalingAgentConfig.conversationServiceUrl,this.logger.info(`conversationServiceUrl passed is empty. so it is set to ${_}`)),assertNotNullOrEmpty(_,"conversationUrl should be a non null value"),this.logger.info(`[${C}][subscribeToCall][start][correlationId=${f}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed?(this.logger.warn(`[${C}][subscribeToCall][failed][reason=Session disposed]`),Promise.reject(an.CALL_END_CODE.CALL_DOES_NOT_EXIST)):(this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.lastUsedJoinCallOptions=v||{},this.lastUsedJoinCallOptions.clientEndpointCapabilities=S||this.lastUsedJoinCallOptions?.clientEndpointCapabilities,this.meetingData=v?.meetingData,this.meetingPreferences=v?.meetingPreferences,this.fsmState=an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY,this.updateCorrelationId(f,C),this.http.sendPostRequest({url:_,requestName:hn.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,operationType:"CallSetup",payload:getPayload36(this,null,null,{subscribe:!0,clientEndpointCapabilities:S,...v,applicationType:this.participantManager.localParticipant.applicationType,endpointState:this.configureEndpointStateForStartOrJoin({additionalEndpointProperties:v?.additionalEndpointProperties})},C),causeId:C}).then((g=>{this.disposed||(this.fsmState=an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,this.processConversationServiceResponseHeaders(g,C),this.processConversationServiceResponse(g.response,C,1),this.onCallStatusChanged(an.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY,C))})).catch((g=>{if(g.stack&&!this.isFatalException(g))return Promise.resolve();const f=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[${C}][subscribeToCall] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(f)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:f.telemetryEndSubCode,endSubCode:f.error.subCode,resultCategories:f.error.resultCategories,resultDetail:f.error.phrase||"SubscribeFailure",causeId:C}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,C,f.error),Promise.reject(f.error))})))},this.getCallReplacementDetailsForCall=(g,f=causeId2())=>{this.logger.info(`[${f}] getCallReplacementDetailsForCall callId ${g}`);const S=this.signalingAgent.getSignalingSession(g);return S?S.getCallReplacementDetails(f):{replaces:""}},this.getCallReplacementDetails=(g=causeId2())=>(this.logger.info(`[${g}] getCallReplacementDetails`),{replaces:this.links[an.LINKS.REPLACE]}),this.transferCallAsync=(g,f,S,v,C=causeId2())=>{this.logger.info(`[${C}] transferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(g)} transferType ${f} callTransferOptions: ${safeJsonStringify(v)}`),this.transferHelper(g,f,S,v,C)},this.redirectCall=(g,f=causeId2(),S)=>{const{id:v,endpointType:C,type:_}=g.redirectOptions;if(this.logger.info(`[${f}] redirectCall: targetId: ${this.piiUtils.scrubMriOrOmit(v)} targetEndpointType ${C}`),!this.isRedirectAllowed){const g={code:an.CALL_END_CODE.REJECT,phrase:an.CALL_END_PHRASE.CALL_REDIRECT_IS_NOT_ALLOWED};return Promise.reject(g)}this.telemetryHelper.recordEvent(dn.CALL_REDIRECT,{causeId:f});const T=getPayload31(this,_,v,C);return this.http.sendPostRequest({url:this.links[an.LINKS.REDIRECT],requestName:hn.SEND_CALL_REDIRECT_REQUEST.name,payload:T,causeId:f}).then((v=>(this.logger.info(`[${f}][redirectCall] succeeds. Leaving the call...`),this.telemetryHelper.recordEvent(dn.CALL_REDIRECT_REQUEST_SENT,{causeId:f,targetEndpointType:C}),this.terminateEstablishedCall(S,g)))).catch((g=>{const v=getErrorForXHRFailure(g);this.logger.info(`[${f}][redirectCall] error: ${getPrintableObject(v)}`);const _=v.error;return this.telemetryHelper.recordEvent(dn.CALL_REDIRECT_REQUEST_FAILED,{causeId:f,transactionEnd:_,endpointType:C}),this.disposed||(this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,endCode:S.code,endSubCode:S.subCode,clientReasonSubCode:S.clientReasonSubCode,clientReasonPhrase:S.clientReasonPhrase,resultDetail:S.phrase||"RedirectCall",resultCategories:S.resultCategories,causeId:f}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,S),this.dispose(S,f)),Promise.reject(_)}))},this.transferHelper=(g,f,S,v,C=causeId2())=>{assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet");let _=!1;this.logger.info(`[${C}][transferHelper][replacementDetails=${getPrintableObject(S)}] disableForwardingAndUnanswered=${v&&v.disableForwardingAndUnanswered}`),this.telemetryHelper.recordEvent(dn.TRANSFER_CALL,{causeId:C}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(C,_)}),an.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT),this.http.sendPostRequest({url:this.links[an.LINKS.TRANSFER],requestName:hn.SEND_TRANSFER_REQUEST.name,payload:getPayload48(g,this,S,f,v),causeId:C}).then((()=>{this.telemetryHelper.recordEvent(dn.WAITING_FOR_TRANSFER_ACCEPTANCE,{causeId:C}),_=!0})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${C}][transferCallAsync] error: ${getPrintableObject(f)}`),this.disposed||(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:an.CALL_END_CODE.NETWORK_ERROR,reason:getPrintableObject(g)}},C),this.telemetryHelper.recordEvent(dn.TRANSFER_REQUEST_FAILED,{causeId:C,...f.error}))})),this.telemetryHelper.recordEvent(dn.TRANSFER_REQUEST_SENT,{causeId:C,transferType:f})},this.consultTransferCallAsync=(g,f,S,v,C)=>{let _,T;if(this.logger.info(`[${v}] consultTransferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(f)} transferTargetParticipantLegId: ${S}`),S?(T=this.getMriByParticipantLegOfCall(g,S,v),_=this.getReplacementDetailsByParticipantLegOfCall(g,f,S,v)):(T=f,_=this.getCallReplacementDetailsForCall(g,v)),!T||!_){const C=_?"target mri corresponding not found":`unable to retrieve replacementDetails for transferTargetCallId: ${g}, transferTargetMri: ${f}, transferTargetParticipantLegId: ${S}`;return this.logger.info(`[${v}] consultTransferCallAsync: error: ${C}`),void this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:an.CALL_END_CODE.BAD_REQUEST,reason:C}},v)}this.transferHelper(T,"TransferTypeStandard",_,C,v)},this.isParkByTransfer=(g,f)=>{const S=["serverHold","sharedLinePark","teamPark"].indexOf(g)>-1;return this.logger.info(`[${f}][isParkByTransfer][context=${g}] result = ${S}`),S},this.parkCallAsync=(g,f=causeId2())=>{if(g&&"none"===g){throw{code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"}}return assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet"),this.logger.info(`[${f}][parkCallAsync][context=${g}]`),this.telemetryHelper.recordEvent(dn.PARK_CALL,{causeId:f,parkType:getParkTypeName(g)}),this.isParkByTransfer(g,f)?this.parkByTransfer(g,f):this.park(g,f)},this.unparkAsync=(g,f=causeId2())=>{if(g&&"none"===g){throw{code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"}}if(!this.links[an.LINKS.UNPARK]){throw{code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark link not available"}}this.logger.info(`[${f}][unparkAsync][context=${g}]`),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UNPARK_COMPLETION,(()=>{this.handleUnparkError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UNPARK_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UNPARK_COMPLETION_TIMEOUT},dn.WAITING_FOR_UNPARK_COMPLETION_TIMEOUT,f,g)}),an.TIMEOUT_VALUES_IN_SECONDS.UNPARK_COMPLETION_TIMEOUT);const S={causeId:f};return this.http.sendPostRequest({url:this.links[an.LINKS.UNPARK],requestName:hn.SEND_UNPARK_REQUEST.name,payload:getPayload50(this,S),causeId:f}).then((g=>(this.logger.info(`[${f}][unparkAsync] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UNPARK_COMPLETION,{causeId:f}),Promise.resolve()))).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${f}][unparkAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUnparkError(v.error,dn.UNPARK_REQUEST_FAILED,f,g),Promise.reject(v.error))}))},this.handleUpdateParticipantsPropertiesCompletion=g=>{const f=g.body,S=extractCauseIdFromMessage(g),v=this.logger.createChild(`[${S}][handleUpdateParticipantsPropertiesCompletion]`,this.correlationId),C={};if(this.disposed)v.info("ignored. Call disposed.");else{if(f.operationId||v.warn("operationId is undefined."),v.info("starts"),f.participantInfos)for(const g of f.participantInfos){if(!g.participant.id){v.warn("participant id is undefined."),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED,"participant id is undefined in response, property");continue}if(!g.participant.key){v.warn("property name (key) is undefined."),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED,"property name (key) is undefined in response");continue}const _=mapMriAndPropertyNameToResolveString(g.participant.id,f.operationId,g.participant.key),T={code:g.transactionEnd.code,subCode:g.transactionEnd.subCode,phrase:g.transactionEnd.phrase,resultCategories:g.transactionEnd.resultCategories};v.info(`Update participants properties completed for: ${this.piiUtils.scrubMriOrOmit(g.participant.id)} with transactionEnd ${getPrintableObject(T)}`),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_COMPLETED,{causeId:S,resolveId:this.piiUtils.scrubMriOrOmit(_),property:g.participant.key,result:getPrintableObject(T)}),C[_]=T,this.updateParticipantsPromises[f.operationId].delete(_)}this.checkAndCleanupPromisesForOperationId(f.operationId),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(C,f.operationId,S)}},this.getCallStatus=()=>this.currentCallStatus,this.processIncomingCallRequest=(g,f,S=causeId2())=>{assertNotNull(g,"request should be a non null value"),assertNotNullOrEmpty(g.body,"request should have a valid body"),assertNotNullOrEmpty(g.body.gp||g.body.cp,"request body should have payload"),assert2(this.isCallIdleOrRosterOnly(),"a call is already in progress");const v=this.logger.createChild(`[${S}][processIncomingCallRequest]`);if(this.callUsesMixer=g.fromMixer,v.info("[start]"),this.disposed)return void v.warn("processIncomingCallRequest canceled");this.telemetryHelper.startCallInitializationWatch(),this.isIncomingCall=!0,this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=an.SIGNALING_FSM_STATE.INCOMING,this.participantManager.initializeForIncomingCall();let C={};try{f&&(C=JSON.parse(f))}catch(g){v.warn("Unable to parse endpoint metadata")}this.endpointMetadata=C;try{let f;if(g?.body?.gp&&!isStringBase64(g.body.gp))v.info("unencoded payload, skipping decoding."),f=g.body.gp;else{const S=g.body.gp?atob(g.body.gp):decodeMessage(g.body.cp);f=JSON.parse(S)}if(!f.callNotification)throw v.info("[failed][reason=CallNotification missing]"),new Error("CallNotification is missing");v.info(`incoming call payload: ${safeJsonStringify(scrubObjectFields(f))}`),this.processIncomingCallPayload(f,S),this.incomingCallPayload=f}catch(g){this.endIncomingCallBecauseOfInvalidPayload(S)}},this.sendAttachToCall=(g=causeId2())=>(this.logger.info(`[${g}][sendAttachToCall]`),this.incomingCallPayload?(this.onCallStatusChanged(an.CALL_STATUS.IDLE,g),this.sendAttachToCallInternal(g)):(this.endIncomingCallBecauseOfInvalidPayload(g),Promise.reject(an.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD))),this.supportsNewOfferRequest=()=>this.signalingAgentConfig.handleNewOfferRequest,this.requestNewOffer=(g,f=causeId2())=>(this.telemetryHelper.recordEvent(dn.REQUEST_NEW_OFFER,{compatibleContentTypes:g,causeId:f}),this.signalingAgentConfig.handleNewOfferRequest?(assertNotNullOrEmpty(this.links[an.LINKS.NEW_OFFER],"newOffer link should be a non null value"),this.http.sendPostRequest({url:this.links[an.LINKS.NEW_OFFER],requestName:hn.REQUEST_NEW_OFFER.name,payload:getPayload38(this,g,this.links[an.LINKS.NEW_OFFER]),causeId:f}).then((g=>this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):Promise.resolve(g))).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[requestNewOffer][${f}] error ${getPrintableObject(S)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:S.telemetryEndSubCode,endSubCode:S.error.subCode,resultCategories:S.error.resultCategories,resultDetail:S.error.phrase||"RequestNewOfferFailure",causeId:f}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,S.error),this.dispose(S.error,f),Promise.reject(S.error))}))):Promise.reject("Disabled")),this.endAsync=(g,f={})=>{f.causeId=f.causeId||causeId2();const S=f.causeId;if(this.logger.info(`[${S}][endAsync][rejectionData=${g&&getPrintableObject(g)}][endCallForAll=${f.forEveryone}]`),this.disposed)return this.logger.warn(`[${S}][endAsync] canceled but session already disposed`),Promise.resolve(null);if(this.disposing=!0,this.telemetryHelper.recordEvent(dn.END_CALL,g?{code:g.code,subCode:g.subCode,causeId:S,callEndClientSubCode:g.clientReasonSubCode,callEndClientPhrase:g.clientReasonPhrase}:{causeId:S}),f.preventAllCallbacks){const g=Object.keys(this.signalingSessionCallback);for(const f of g)this.signalingSessionCallback[f]=Cn.noop}const v=this.mediaRenegotiationManager?.isIncomingRenegotiationInProgress()||this.mediaRenegotiationManager?.isOutgoingRenegotiationInProgress();if(this.telemetryHelper.stopCallCancelationDurationWatch(),this.fsmState===an.SIGNALING_FSM_STATE.INCOMING)return g.code===an.CALL_END_CODE.CALL_REDIRECTED?this.redirectCall(f,S,g):this.rejectIncomingCall(g,S);if(this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY)return this.cancelOutgoingCall(g,S);if(this.fsmState===an.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK)return this.rejectIncomingCall(g,S);if((this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED||v)&&f.forEveryone)return this.deleteConversation(g,S);if(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||v)return this.terminateEstablishedCall(g,f);{this.logger.info(`[${S}][endAsync] there is no call to cancel or end or reject in current state`);const f={code:isNaN(g?.code)?an.CALL_END_CODE.NOT_FOUND:g.code,subCode:isNaN(g?.subCode)?an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED:g.subCode,phrase:g?.phrase||an.CALL_END_PHRASE.CALL_DOES_NOT_EXIST,resultCategories:g?.resultCategories||[Xi.ExpectedError],clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase};return this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultDetail:f.phrase||"CallDoesNotExist",endCode:f.code,endSubCode:f.subCode,resultCategories:f.resultCategories,causeId:S,clientReasonSubCode:f.clientReasonSubCode,clientReasonPhrase:f.clientReasonPhrase}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,S,f),this.dispose(f,S),Promise.resolve(null)}},this.handleIncomingMsgAsync=(g,f=an.INCOMING_MESSAGE_ORIGIN.TROUTER)=>{assertNotNull(g,"incoming message should be a non null value");const S=extractMessageIdFromMessage(g),v=defer(),C=g.body,_=g.url,T={...g,origin:f},I=extractCauseIdFromMessage(T);if(this.logger.info(`[${I}][handleIncomingMsgAsync][url=${_}][messageId=${S}]`),!C)return this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(dn.MESSAGE_MISSING_BODY,{origin:f,messageId:S,causeId:I}),v.reject(new Error("received message with no body")),v.promise;if(this.disposed)return this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=call is disposed]`),v.reject(this.getCallNotFoundTransactionEnd()),v.promise;if(this.isDuplicatedIncomingMessage(T))return this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=duplicate]`),this.telemetryHelper.recordEvent(dn.DUPLICATE_MESSAGE_IGNORED,{origin:f,messageId:S,causeId:I}),v.resolve(new Error("Message was already handled")),v.promise;this.checkCorrelationIdChange(g,I);const b={[sn.CALL_NOTIFICATION]:g=>{this.handleCallNotification(g)},[sn.MEDIA_ANSWER]:g=>{this.handleMediaAnswer(g)},[sn.MEDIA_ACKNOWLEDGEMENT]:g=>{this.handleMediaAcknowledgement(g)},[sn.CALL_ACCEPTANCE]:g=>{this.handleCallAcceptance(g)},[sn.CALL_END]:g=>{this.handleCallEnd(g,!1)},[sn.CALL_PROGRESS]:g=>{this.handleCallProgress(g)},[sn.CALL_ACCEPTANCE_ACKNOWLEDGEMENT]:g=>{this.handleCallAcceptanceAck(g)},[sn.MEDIA_NEGOTIATION]:g=>{this.mediaRenegotiationManager?.handleMediaNegotiationOffer(g)},[sn.MEDIA_NEGOTIATION_FAILURE]:g=>{this.mediaRenegotiationManager?.handleMediaNegotiationFailure(g)},[sn.BALANCE_UPDATE]:g=>{this.handlePSTNBalanceUpdate(g)},[sn.RETARGET_COMPLETED]:g=>{this.mediaRenegotiationManager?.handleRetargetCompleted(g)},[sn.CALL_TRANSFER]:g=>{this.handleTransferRequested(g)},[sn.TRANSFER_COMPLETION]:g=>{this.handleTransferCompletion(g)},[sn.TRANSFER_ACCEPTANCE]:g=>{this.handleTransferAcceptance(g)},[sn.PARK_COMPLETION]:g=>{this.handleParkCompletion(g)},[sn.UNPARK_COMPLETION]:g=>{this.handleUnparkCompletion(g)},[sn.UPDATE_MEETING_LIVE_STATE_RESPONSE]:g=>{this.handleUpdateMeetingLiveStateCompletion(g)},[sn.UPDATE_MEETING_GROUPS_RESPONSE]:g=>{this.handleUpdateMeetingGroupsCompletion(g)},[sn.SET_MEETING_LAYOUT_RESPONSE]:g=>{this.handleSetMeetingLayoutCompletion(g)},[sn.UPDATE_MEETING_STATES_RESPONSE]:g=>{this.handleUpdateMeetingStatesCompletion(g)},[sn.MONITOR_COMPLETION]:g=>{this.handleUpdateMonitorSessionCompletion(g)}},A={[rn.CONTROL_VIDEO_STREAMING]:g=>{this.webRtcSignalingManager.handleControlVideoStreaming(g)},[rn.DOMINANT_SPEAKER_INFO]:g=>{this.webRtcSignalingManager.handleDominantSpeakerInfo(g)},[rn.CSRC_INFO]:g=>{this.webRtcSignalingManager.handleCsrcInfo(g)},[rn.CONV_ROSTER_UPDATE]:g=>{this.handleRosterUpdate(g,!1)},[rn.NEW_MEDIA_OFFER]:g=>{this.handleNewMediaOffer(g)},[rn.CONV_ADD_PARTICIPANT_SUCCESS]:g=>{this.participantManager.handleAddParticipantSuccess(g)},[rn.CONV_ADD_PARTICIPANT_FAILURE]:g=>{this.participantManager.handleAddParticipantFailure(g)},[rn.CONV_ADMIT_PARTICIPANT_SUCCESS]:g=>{this.participantManager.handleAdmitParticipantSuccess(g)},[rn.CONV_ADMIT_PARTICIPANT_FAILURE]:g=>{this.participantManager.handleAdmitParticipantFailure(g)},[rn.CONV_ADMIT_ALL_STATUS]:g=>{this.handleAdmitAllStatus(g)},[rn.CONV_REMOVE_PARTICIPANT_SUCCESS]:g=>{this.participantManager.handleRemoveParticipantSuccess(g)},[rn.CONV_REMOVE_PARTICIPANT_FAILURE]:g=>{this.participantManager.handleRemoveParticipantFailure(g)},[rn.CONV_CONFIRM_UNMUTE]:g=>{this.participantManager.handleUnmuteConfirmRequest(g)},[rn.CONV_UPDATE]:g=>{this.handleConversationUpdate(g)},[rn.CONV_LOCAL_PARTICIPANT_UPDATE]:g=>{this.handleLocalParticipantUpdate(g)},[rn.CONV_ADD_MODALITY_SUCCESS]:g=>{this.handleAddModalitySuccess(g)},[rn.CONV_ADD_MODALITY_FAILURE]:g=>{this.handleAddModalityFailure(g)},[rn.CONV_BROADCAST_UPDATE]:g=>{this.broadcastSession.handleBroadcastStateChanged(g)},[rn.CONV_CONTENT_SHARING_UPDATE]:g=>{this.contentSharingManager?.handleContentSharingUpdate(g)},[rn.CONV_CONTENT_SHARING_END]:g=>{this.contentSharingManager?.handleContentSharingEnd(g)},[rn.CONV_END]:g=>{this.handleCallEnd(g,!1)},[rn.CONV_END_JOIN]:g=>{this.handleCallEnd(g,!1)},[rn.CONV_END_SUBSCRIBE]:g=>{this.handleCallEnd(g,!0)},[rn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS]:g=>{this.participantManager.handleUpdateParticipantInterpretationStateCompletion(g)},[rn.UPDATE_PARTICIPANT_PROPERTIES_STATUS]:g=>{this.handleUpdateParticipantsPropertiesCompletion(g)},[rn.JOIN_MEETING_GROUP_STATUS]:g=>{this.handleJoinMeetingGroupCompletion(g)},[rn.LEAVE_MEETING_GROUP_STATUS]:g=>{this.handleLeaveMeetingGroupCompletion(g)},[rn.RECEIVE_MESSAGE]:g=>{this.handleReceiveMessage(g)},[rn.SEND_MESSAGE_STATUS]:g=>{this.proxiedMessageNotificationManager.handleProxiedMessageNotification(g)},[rn.DISABLE_PREHEAT_ASYNC_STATUS]:g=>{this.handleDisablePreheatCompletion(g)},[rn.MUTE_UNMUTE_ASYNC]:g=>{this.participantManager.handleMuteUnmuteAsyncResponse(g)}};try{const g=Object.keys(b).filter((g=>C.hasOwnProperty(g)))[0],f=this.signalingAgentConfig.enableSplitConversationEndUrl&&(stringEndsWith(T.url,rn.CONV_END_JOIN)||stringEndsWith(T.url,rn.CONV_END_SUBSCRIBE))?Object.keys(A).filter((g=>T.url&&stringEndsWith(T.url,g)))[1]:Object.keys(A).filter((g=>T.url&&stringEndsWith(T.url,g)))[0];g?b[g](T):f?A[f](T):(this.telemetryHelper.recordEvent(dn.UNKNOWN_MESSAGE_TYPE,{messageId:S}),this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=received unknown message]`)),v.resolve(!0)}catch(g){this.telemetryHelper.recordEvent(dn.FAILED_TO_HANDLE_MESSAGE,{messageId:S,error:getPrintableObject(g)}),this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=${g.message}]`),v.reject(new Error(g.message))}return v.promise},this.canHandleIncomingMsgSync=g=>{if(this.signalingAgentConfig.supportsSynchronousTrouterResponse){const f=g.body;return Boolean(f.callAcceptance)}return!1},this.handleIncomingMsgSync=g=>{const f=extractMessageIdFromMessage(g),S=g.body,v=g.url,C=an.INCOMING_MESSAGE_ORIGIN.TROUTER,_={...g,origin:C},T=extractCauseIdFromMessage(_);this.logger.info(`[${T}][handleIncomingMsgSync][url=${v}][messageId=${f}]`);const I=_.headers;let b=an.HTTP_STATUS_CODES.OK,A="";const P=new ln;if(isDuplicateMessage(I,this.incomingTrouterMessagesSeenSoFar)){this.logger.info(`[${T}][handleIncomingMsgSync][failed][reason=duplicate]`);const g=getMessageResultFromCache(I,this.incomingMessageSyncResponseCache);if(g)return this.logger.info(`[${T}][handleIncomingMsgSync][cachedResponse]`),g;this.telemetryHelper.recordEvent(dn.DUPLICATE_MESSAGE_IGNORED,{origin:C,messageId:f,causeId:T}),this.logger.info(`[${T}][handleIncomingMsgSync][failed][reason=cachedResponseNotFound]`),b=an.HTTP_STATUS_CODES.BAD_REQUEST}else if(S){if(S.callAcceptance)try{A=safeJsonStringify(this.handleCallAcceptanceSync(_))}catch(g){this.telemetryHelper.recordEvent(dn.FAILED_TO_HANDLE_MESSAGE,{messageId:f,origin:C,causeId:T,error:getPrintableObject(g)}),this.logger.info(`[${T}][handleIncomingMsgSync][failed][reason=${g?.message}]`),b=an.HTTP_STATUS_CODES.BAD_REQUEST}}else this.logger.info(`[${T}][handleIncomingMsgSync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(dn.MESSAGE_MISSING_BODY,{origin:C,messageId:f,causeId:T}),b=an.HTTP_STATUS_CODES.BAD_REQUEST;I&&(I.get(an.HEADERS.CORRELATION_ID)&&P.set(an.HEADERS.CORRELATION_ID,I.get(an.HEADERS.CORRELATION_ID)),I.get(an.HEADERS.MESSAGE_ID)&&P.set(an.HEADERS.MESSAGE_ID,I.get(an.HEADERS.MESSAGE_ID)));const R={resultCode:b,responseBody:A,responseHeaders:P.getAll()};return cacheMessageResult(I,this.incomingMessageSyncResponseCache,R),this.logger.info(`[${T}][handleIncomingMsgSync][success][resultCode=${b}]`),R},this.acceptRenegotiationAsync=(g,f,S=causeId2())=>(assertNotNull(g.blob,"finalSdp should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${S}][acceptRenegotiationAsync][mediaTypes=${f}]`),this.mediaRenegotiationManager.acceptRenegotiationAsync(g,f,S)),this.setProvisionalAnswerAsync=(g,f=causeId2())=>{assertNotNull(g.blob,"sdp should be a non null value"),this.telemetryHelper.recordEvent(dn.SET_PROVISIONAL_ANSWER,{causeId:f});const S=defer();return this.fsmState!==an.SIGNALING_FSM_STATE.INCOMING?(this.logger.info(`[setProvisionalAnswerAsync][${f}] there is no incoming call to set provisional answer on.`),S.reject(new Error("there is no incoming call to set provisional answer on.")),S.promise):(this.http.sendPostRequest({url:this.links[an.LINKS.MEDIA_ANSWER],requestName:hn.SEND_MEDIA_ANSWER.name,payload:getPayload57(this,g),causeId:f}).then((g=>{this.disposed||this.onCallStatusChanged(an.CALL_STATUS.CONNECTING,f),S.resolve(null),this.disposed||(this.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ACKNOWLEDGEMENT,{causeId:f}),this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(an.CALL_STATUS.RINGING,f),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!1,f))})).catch((g=>{const v=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[setProvisionalAnswerAsync][${f}] error: ${getPrintableObject(v)}`),this.disposed?S.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent(dn.SET_PROVISIONAL_ANSWER_FAILED,{causeId:f}),S.reject(v.error))})),S.promise)},this.startRenegotiationAsync=(g,f,S=causeId2())=>(assertNotNull(g,"mediaContent should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${S}][startRenegotiationAsync]`),this.mediaRenegotiationManager.startRenegotiationAsync(g,this.links[an.LINKS.MEDIA_RENEGOTIATION],f,S)),this.updateMediaDescriptionsAsync=(g=causeId2(),f)=>{assertNotNull(f,"mediaDescriptions should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"updateMediaDescriptions operations are only allowed when the call is connected");const S=this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS];return assertNotNull(S,"updateMediaDescriptionsUrl should be a non null value"),this.telemetryHelper.recordEvent(dn.UPDATE_MEDIA_DESCRIPTIONS,{causeId:g}),this.http.sendPostRequest({url:S,requestName:hn.UPDATE_MEDIA_DESCRIPTIONS.name,payload:getPayload58(this,f),causeId:g}).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingAgentConfig);return this.logger.info(`[updateMediaDescriptionsAsync][${g}] error: ${getPrintableObject(S)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent(dn.UPDATE_MEDIA_DESCRIPTIONS_FAILED,{causeId:g}),Promise.reject(S.error))}))},this.acceptAsync=(g,f,S,v=causeId2())=>{assertNotNull(g,"mediaContent should be a non null value"),assertNotNull(g.blob,"outgoingSdp should be a non null value"),this.logger.info(`[${v}][acceptAsync][mediaTypes=${f}]`),this.telemetryHelper.recordEvent(dn.ACCEPT_CALL,{causeId:v}),this.telemetryHelper.setAnsweredModalities(g.blob);const C=defer();return this.fsmState!==an.SIGNALING_FSM_STATE.INCOMING?(this.logger.warn("acceptAsync, there is no incoming call to accept"),C.reject(new Error("there is no incoming call to accept")),C.promise):(this.fsmState=an.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK,this.http.sendPostRequest({url:this.links[an.LINKS.ACCEPT],requestName:hn.SEND_ACCEPTANCE.name,payload:getPayload29(this,g,f,S),causeId:v}).then((g=>{this.disposed||(this.currentCallStatus===an.CALL_STATUS.IDLE&&(this.telemetryHelper.setTimeToRingDuration(),this.telemetryHelper.recordEvent(dn.ACCEPTED_BEFORE_RINGING,{causeId:v}),this.onCallStatusChanged(an.CALL_STATUS.CONNECTING,v)),g.response.callAcceptanceAcknowledgement&&(this.logger.info("acceptAsync, handling inlined callAcceptanceAcknowledgement"),this.internalHandleCallAcceptanceAck(g.response,v))),C.resolve(null)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[acceptAsync][${v}] error: ${getPrintableObject(f)}`),this.disposed?C.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=an.SIGNALING_FSM_STATE.INCOMING,this.telemetryHelper.recordEvent(dn.ACCEPT_CALL_FAILED,{causeId:v,xhrError:f}),C.reject(f.error))})),C.promise)},this.rejectRenegotiationAsync=(g,f=causeId2())=>(assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${f}][rejectRenegotiationAsync][rejectionData=${g}]`),this.mediaRenegotiationManager.rejectRenegotiationAsync(g,f)),this.saveMediaControllerLinksIfAny=g=>{g.links&&(this.links[an.LINKS.CONTROL_VIDEO_STREAMING]=g.links.controlVideoStreaming||this.links[an.LINKS.CONTROL_VIDEO_STREAMING],this.links[an.LINKS.APPLY_CHANNEL_PARAMETERS]=g.links.applyChannelParameters||this.links[an.LINKS.APPLY_CHANNEL_PARAMETERS])},this.getInitialMediaOfferFromIncomingCallPayload=(g=causeId2())=>{if(!this.signalingAgentConfig.handleMediaOfferFromPushNotification)return null;const f=this.incomingCallPayload?.callNotification?.mediaContent?this.incomingCallPayload.callNotification.mediaContent:null;return this.telemetryHelper.setIsSdpInCallNotification(!!f),f},this.updateCorrelationId=(g,f=causeId2())=>{if(this.logger.info(`[${f}][updateCorrelationId][old=${this.correlationId}][new=${g}]`),this.correlationId!==g&&!this.disposed){const S=this.correlationId;this.correlationId=g,this.telemetryHelper&&this.telemetryHelper.recordEvent&&this.telemetryHelper.recordEvent(dn.CORRELATION_ID_UPDATED,{newId:this.correlationId,oldId:S,causeId:f}),this.signalingSessionCallback&&this.signalingSessionCallback.onCorrelationIdUpdated&&this.signalingSessionCallback.onCorrelationIdUpdated(this.correlationId,f)}},this.endIncomingCallBecauseOfInvalidPayload=g=>{this.logger.info(`[${g}][endIncomingCallBecauseOfInvalidPayload]`),this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const f={code:an.CALL_END_CODE.BAD_REQUEST,subCode:an.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD,phrase:an.CALL_END_PHRASE.BAD_NOTIFICATION_PAYLOAD,resultCategories:[Xi.UnexpectedServerError]};this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:f.code,endSubCode:f.subCode,resultDetail:f.phrase||"EndIncomingCall",resultCategories:f.resultCategories,causeId:g}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,g,f),this.dispose(f,g)},this.isDuplicatedIncomingMessage=g=>g.origin===an.INCOMING_MESSAGE_ORIGIN.BROKER&&isDuplicateMessage(g.headers,this.incomingBrokerMessagesSeenSoFar)||g.origin===an.INCOMING_MESSAGE_ORIGIN.TROUTER&&isDuplicateMessage(g.headers,this.incomingTrouterMessagesSeenSoFar),this.getEndpointState=()=>{let g;return g=this.startOrJoinConvResponseReceived?{...this.latestEndpointState}:{...this.requestedEndpointStateWhileConnecting},g},this.setMultiParty=(g,f)=>{const S=!!g;this.multiParty!==S&&(this.telemetryHelper.recordEvent(dn.SET_MULTIPARTY,{isMultiparty:S,causeId:f}),this.multiParty=S)},this.setupTrouterChannel=()=>{this.logger.info(`Broker config: outgoing=${this.signalingAgentConfig.brokerEnabledOutgoing?"enabled":"disabled"}incoming=${this.signalingAgentConfig.brokerEnabledIncoming?"enabled":"disabled"}batching=${this.signalingAgentConfig.brokerRequestBatching?"enabled":"disabled"}exclusive=${this.signalingAgentConfig.brokerExclusively?"enabled":"disabled"}`);const setTrouterUrl=g=>{g&&"string"==typeof g&&g.trim()&&(this.baseMessagingChannelUrl=this.previousTrouterUrl=this.currentTrouterUrl=g.trim(),this.telemetryHelper.addTrouterChannel())};this.brokerExclusiveEnabled()||(this.signalingAgentConfig.trouterServiceProvider?(2===this.signalingAgentConfig.trouterServiceProvider.state()&&this.signalingAgentConfig.trouterServiceProvider.getTrouterUrlAsync().then(setTrouterUrl),this.signalingAgentConfig.trouterServiceProvider.onStateChanged(this.onTrouterStateChanged)):(setTrouterUrl(this.signalingAgentConfig.trouterUrlGetter.trouterUrl()),this.signalingAgentConfig.trouterUrlGetter.trouterUrl.changed(this.onTrouterUrlChanged)))},this.isTrouterDisconnected=()=>{try{return 3===this.signalingAgentConfig.trouterServiceProvider.state()}catch(g){return!1}},this.forceTrouterConnectionCheck=()=>{try{return void this.signalingAgentConfig.trouterServiceProvider.checkConnection(!1)}catch(g){return}},this.navigatorOnlineCallback=()=>{this.disposed||(this.reportConnectivityStatus(),this.isTrouterDisconnected()&&this.signalingAgentConfig.forceTrouterReconnectOnNetworkOnline&&this.forceTrouterConnectionCheck())},this.navigatorOfflineCallback=()=>{this.reportConnectivityStatus()},this.reportConnectivityStatus=()=>{if(!this.disposed){const g=isTrouterAndNavigatorConnected(this.signalingAgentConfig.trouterServiceProvider);this.logger.info(`[Connectivity] status=${g}`),this.telemetryHelper.recordEvent(dn.CONNECTIVITY_CHANGED,{status:g})}},this.onTrouterStateChanged=(g,f)=>{const S=causeId2();this.logger.info(`[${S}][onTrouterStateChanged][state=${g}]`),this.disposed?this.logger.info("onTrouterStateChanged ignored"):(this.reportConnectivityStatus(),2===g&&(this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter(dn.TROUTER_STATE_CHANGED,S)))},this.setupConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.addEventListener&&(window.addEventListener("online",this.navigatorOnlineCallback),window.addEventListener("offline",this.navigatorOfflineCallback))}catch(g){return}},this.tearDownConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.removeEventListener&&(window.removeEventListener("online",this.navigatorOnlineCallback),window.removeEventListener("offline",this.navigatorOfflineCallback))}catch(g){return}},this.getTrouterUrlAsync=()=>this.signalingAgentConfig.trouterServiceProvider?this.signalingAgentConfig.trouterServiceProvider.getTrouterUrlAsync():this.signalingAgentConfig.trouterUrlGetter.getTrouterUrlAsync(),this.brokerExclusiveEnabled=()=>this.signalingAgentConfig.brokerEnabledOutgoing&&this.signalingAgentConfig.brokerEnabledIncoming&&this.signalingAgentConfig.brokerExclusively,this.isBrokerEnabledForOutgoingCall=()=>this.signalingAgentConfig.brokerEnabledOutgoing,this.isBrokerEnabledForIncomingCall=()=>this.signalingAgentConfig.brokerEnabledIncoming,this.setupBrokerChannel=()=>{this.brokerService||(this.logger.info("setupBrokerChannel, Enable broker"),this.brokerService=new bn(this),this.brokerService.onBrokerMessage((g=>{this.logger.info("setupBrokerChannel, message from broker",getPIISafeMessage(g)),this.handleIncomingMsgAsync(g,an.INCOMING_MESSAGE_ORIGIN.BROKER).catch((g=>{this.telemetryHelper.recordEvent(dn.FAILED_TO_HANDLE_BROKER_MESSAGE),this.logger.info("setupBrokerChannel, Failed to handle message from broker",g)}))})),this.baseMessagingChannelUrl||(this.telemetryHelper.addBrokerChannel(),this.baseMessagingChannelUrl=this.brokerService.baseUrl))},this.onTrouterUrlChanged=()=>{const g=causeId2();this.logger.info(`[${g}][onTrouterUrlChanged]`),this.disposed?this.logger.info("onTrouterUrlChanged ignored"):this.getTrouterUrlAsync().then((f=>{this.telemetryHelper.recordEvent(dn.TROUTER_URL_CHANGED,{url:f}),this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter(dn.TROUTER_URL_CHANGED,g)})).catch((g=>{this.logger.info(`Failed to update links to trouter: ${g}`)}))},this.updateLinksToTrouter=(g,f)=>{this.logger.info(`[${f}][updateLinksToTrouter][tag=${g}]`),this.ensureLatestTrouterUrl(g).then((()=>{this.previousTrouterUrl!==this.currentTrouterUrl?(this.previousTrouterUrl=this.currentTrouterUrl,this.updateConversationLinks(),this.updateKeepAliveUrl(),this.contentSharingManager?.updateContentSharingNotificationLinksAsync(f),this.broadcastSession&&this.broadcastSession.updateBroadcastCallbackUrl(f)):this.logger.info(`[${f}][updateLinksToTrouter]skip updating links, url did not change`)})).catch((g=>{this.disposed||this.telemetryHelper.recordEvent(dn.TROUTER_URL_UPDATE_FAILED,{causeId:f}),this.logger.info(`[${f}][updateLinksToTrouter][failed][reason=${getPrintableObject(g)}]`)}))},this.updateLinks=(g,f)=>{this.ensureLatestTrouterUrl(dn.TROUTER_URL_CHANGED).then((()=>{g(f)})).catch((g=>{this.disposed||this.telemetryHelper.recordEvent(dn.TROUTER_URL_UPDATE_FAILED,{causeId:f}),this.logger.warn("Failed to update links")}))},this.startCallPreheatTimer=g=>{this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT,(()=>{this.handleCallEstablishmentTimeout(g,an.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,"Preheat timed out!"),this.terminateEstablishedCall({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,phrase:"Preheat timed out!"},{forEveryone:!1,causeId:g})}),an.TIMEOUT_VALUES_IN_SECONDS.MAX_PREAHEATED_TIMEOUT)},this.stopCallPreheatTimer=()=>{this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT)},this.updateKeepAliveUrl=()=>{this.logger.info("updateKeepAliveUrl"),this.links.hasOwnProperty(an.LINKS.KEEPALIVE)?(this.linkUpdateRequested.keepAliveLinks=!1,this.logger.info("updateKeepAliveUrl, sending request"),this.sendToKeepAliveUrl(getPayload41(this))):this.linkUpdateRequested.keepAliveLinks=!0},this.updateConversationLinks=(g=causeId2())=>{this.logger.info(`[${g}][updateConversationLinks]`),this.telemetryHelper.recordEvent(dn.UPDATE_CONVERSATION_LINKS,{causeId:g}),this.links.hasOwnProperty(an.LINKS.NOTIFICATION_LINKS)?(this.linkUpdateRequested.conversationLinks=!1,this.logger.info("updateConversationLinks, sending request"),this.sendToUpdateConversationLinks(!0)):this.linkUpdateRequested.conversationLinks=!0},this.sendAttachToCallInternal=(g=causeId2())=>{this.telemetryHelper.recordEvent(dn.SEND_ATTACH,{causeId:g}),this.logger.info(`[${g}][sendAttachToCallInternal]`);const f=new ln;return this.signalingAgentConfig.sendProgressFromCC&&f.set(an.HEADERS.CACHE_SKYPE_TOKEN,"1"),this.http.sendPostRequest({url:this.incomingCallPayload.callNotification.links.attach,customHeaders:f,requestName:hn.SEND_CALL_ATTACH.name,payload:getPayload27(this,this.incomingCallPayload.conversationInvitation.conversationController,!this.getInitialMediaOfferFromIncomingCallPayload()),causeId:g}).then((f=>{if(!this.disposed){this.processAttachResponse(this.incomingCallPayload,f,g);const S=f.response.additionalActionResponses;S&&S.length>0&&this.processConversationServiceResponse(S[0].output,g,0),this.onCallStatusChanged(an.CALL_STATUS.RINGING,g),this.telemetryHelper.setTimeToRingDuration(),this.handleBrokerSubscription(f.response.callInvitation,g)}})).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingAgentConfig);this.logger.info(`[${g}][sendAttachToCallInternal] error: ${getPrintableObject(f)} xhrError: ${getPrintableObject(S)}`),this.disposed||(this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:S.telemetryEndSubCode,endSubCode:S.error.subCode,resultCategories:S.error.resultCategories,resultDetail:S.error.phrase||"SendAttachtoCallFailure",causeId:g}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,g,S.error),this.dispose(S.error,g))}))},this._processCallAcceptance=(g,f)=>{if(this.logger.info(`[${f}][_processCallAcceptance]`),this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING){this.processCallAcceptance(g.body,f),this.telemetryHelper.setTimeToRingDuration();try{this.multiParty||this.callUsesMixer||this.participantManager.handleRosterUpdate(this.getFakeRoster(g.body),!0,f)}catch(S){const v={code:an.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:an.CALL_END_SUB_CODE.CALL_ACCEPTANCE_INVALID_SERVICE_RESPONSE,phrase:S?.toString()};throw this.logger.info(`[${f}][_processCallAcceptance] ${safeJsonStringify(v)}`),this.telemetryHelper.recordRosterEvent(g,dn.HANDLE_ROSTER_UPDATE_FAIL,f),v}}},this.restartKeepAliveInterval=(g,f=!1,S)=>{this.disposed||(window.clearInterval(this.keepAliveTimer),f&&(this.telemetryHelper.recordEvent(dn.SEND_KEEP_ALIVE_FAILED,S),S?.code===an.RESOURCE_NOT_FOUND_ERROR.code)?this.logger.info(`[${g}][restartKeepAliveInterval] keepAlive stopped since last request returned NOT_FOUND.`):this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval))},this.isCallOngoing=()=>this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===an.SIGNALING_FSM_STATE.IDLE,this.isCallIdleOrRosterOnly=()=>this.fsmState===an.SIGNALING_FSM_STATE.IDLE||this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,this.isCallConnectedOrConnectedForRoster=()=>this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,_&&(this.callStartTime=_),this.signalingSessionCallback=f,this.signalingAgentConfig=S,this.signalingAgent=C,this.urlIdentifier=v,this.piiUtils=new vn(S.piiScrubber),this.isHostLessCall=S.doHostlessCalling||!1,this.logger=S.logger.createChild((()=>`CSA[${this.correlationId}][${this.fsmState}]`),this.correlationId,!0),this.updateCorrelationId(v),this.logger.info(`[endpointId=${truncate(this.signalingAgent.endpointId,8)}]`),this.logger.info(`[participantId=${g.participantId}]`),this.callOperationHandler=new Pn(this.logger.createChild((()=>`[CallOperationHandler][${g.participantId}]`))),this.http=new Hn(this,this.callStartTime),this.telemetryHelper=new Zn(this,g,this.callStartTime),this.mediaRenegotiationManager=new $n(this,f,this.telemetryHelper),this.participantManager=new zn(this,f,g,new Ge(this.logger)),this.proxiedMessageNotificationManager=new Kn(this),this.timeoutManager=new pn(this.logger),this.contentSharingManager=new wn(this,f),this.webRtcSignalingManager=new er(this,f),this.pstnContent={emergencyCallCountry:S.emergencyCallCountry||"",platformName:S.clientInformation,publicApiCall:!1},this.setupTrouterChannel(),this.setupConnectionCheck()}onPromotionCompleted(g,f,S){this.logger.info(`[${S}][onPromotionCompleted] isFailed=${g} error=${getPrintableObject(f)}]`),this.isPromotingToRealtime=!1,this.signalingSessionCallback.onPromotionCompleted(g,f,S)}setRealTimeState(g,f){let S=g;(2===g&&1===this.realTimeState||1===g&&2===this.realTimeState)&&(S=3),S!==this.realTimeState&&(this.logger.info(`[${f}][setRealTimeState] changed: input=${g} old=${this.realTimeState}, new=${S}`),this.realTimeState=S,3===S?this.setCallMode(1,f):0!==this.callMode||2!==S&&(this.signalingAgentConfig.disableRealTimeModeFromRoster||1!==S)||this.setCallMode(1,f))}setCallMode(g,f){this.callMode!==g&&(this.logger.info(`[${f}][setCallMode] oldMode=${this.callMode}, newMode=${g}`),this.callMode=g,this.signalingSessionCallback.onCallModeChanged(this.callMode,f))}configureStreamingMode(g){2!==this.callMode?(this.logger.info(`[${g}][configureStreamingMode]`),this.setCallMode(2,g),this.cleanUpDueToStreaming(g),this.onCallStatusChanged(an.CALL_STATUS.CONNECTED,g)):this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT)}updateDominantSpeakerHistoryMessageSubscription(g){this.webRtcSignalingManager.getIsDominantSpeakerInfoLinkEnabled()!==g&&(this.logger.info(`Signaling dominant speaker history subscription updated: ${g}`),this.webRtcSignalingManager.setIsDominantSpeakerInfoLinkEnabled(g),this.webRtcSignalingManager.areClientURLsGenerated()&&this.updateKeepAliveUrl())}cleanUpDueToStreaming(g){this.setRealTimeState(0,g),this.fsmState=an.SIGNALING_FSM_STATE.CONNECTED,this.isPromotingToRealtime=!1,this.provisionalMediaAnswersSeenSoFar=[],this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=new $n(this,this.signalingSessionCallback,this.telemetryHelper),this.keepAliveTimer&&window.clearInterval(this.keepAliveTimer),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const f={code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.DOWNGRADE_TO_STREAMING_CLIENT,phrase:an.CALL_END_PHRASE.DOWNGRADE_TO_STREAMING_CLIENT},S=hn;for(const v of Object.keys(S))0!==S[v].controller&&4!==S[v].controller&&3!==S[v].controller||this.http.cancelRequestIfPending(S[v].name,g,void 0,f)}updateEndpointMetadata(g,f=causeId2()){let S={};try{S=JSON.parse(g)}catch(g){return Promise.reject("Invalid metadata")}return this.http.sendPutRequest({url:this.links[an.LINKS.UPDATE_ENDPOINT_METADATA],requestName:hn.UPDATE_ENDPOINT_METADATA.name,payload:getPayload51(this,S),causeId:f}).then((()=>{this.telemetryHelper.recordEvent(dn.UPDATE_ENDPOINT_METADATA_SUCCESS,{causeId:f})})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[${f}][updateEndpointMetadata] error: ${getPrintableObject(S)}`),this.telemetryHelper.recordEvent(dn.UPDATE_ENDPOINT_METADATA_FAILURE,{...S.error}),Promise.reject(S.error)}))}isOneToOnePSTNCall(){return this.signalingSessionCallback.isOneToOnePstnCall()}getLocationContent(){return this.isOneToOnePSTNCall()?tryParse(this.locationInfoContent):null}getNetworkContent(){return this.isOneToOnePSTNCall()?tryParse(this.networkInfoContent):null}getAreaContent(){return this.isOneToOnePSTNCall()?tryParse(this.areaContent):null}setLocationInfo(g,f,S){this.locationInfoContent=g,this.networkInfoContent=f,this.areaContent=S}setStreamInformationReceived(){this.disposed||this.streamInformationReceived||(this.streamInformationReceived=!0,this.telemetryHelper.recordEvent(dn.SET_STREAM_INFORMATION_RECEIVED))}getEndpointCapabilities(){let g=0;return this.signalingAgentConfig.brokerEnabledIncoming&&(g|=16),this.signalingAgentConfig.isGVCJoiningEnabled&&(g|=1),"disabled"!==this.signalingAgentConfig.cloudScreenSharingFlag&&(g|=2),this.signalingAgentConfig.supportsHostlessGroupCalls&&(g|=4),this.signalingAgentConfig.autoJoinOnConflict&&(g|=32),this.signalingAgentConfig.supportsCompressedServicePayload&&(g|=128),this.signalingAgentConfig.enableAutoPromotion&&(g|=65536),this.signalingAgentConfig.enableBatchedSendMessageStatus&&(g|=16384),this.signalingAgentConfig.enableBatchedReceiveMessage&&(g|=8192),g|=64,g|=1024,this.signalingAgent?.accountConfig?.clientSupportsAudioOnlyWatermark&&(g|=4096,this.telemetryHelper.setAudioOnlyWatermark(!0)),this.signalingAgent?.accountConfig?.clientSupportsWatermark&&(g|=2048,this.telemetryHelper.setWatermarkSupport(!0)),this.signalingAgent?.accountConfig?.clientSupportsPreventScreenCapture&&(g|=131072,this.telemetryHelper.setClientSupportsPreventScreenCapture(!0)),(this.getMaxReinvitelessMediaForVBSSForWeb()||this.getMaxReinvitelessMediaForVideoForWeb())&&(this.telemetryHelper.setReinviteless(this.callUsesMixer),g|=512),g}handleAdmitAllStatus(g){const f=g.body?.transactionResponse,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAdmitAllStatus][${getPrintableObject(f)}]`);const v=f?.operationId;if(v&&this.callOperationHandler.hasPendingOperation(0,v,S)){this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT,v);const g=f?.result?.code,C=f?.result?.subCode,_=f?.result?.resultCategories,T=f?.additionalDetail;if(0===g||g>=200&&g<300){const f={code:g,subCode:C,resultCategories:_,result:safeJsonStringify(T)};this.telemetryHelper.recordEvent(dn.ADMIT_SUCCESS,{causeId:v,transactionEnd:f}),this.callOperationHandler.resolvePendingOperation(0,v,f,S)}else{const T={code:g||an.CALL_END_CODE.BAD_REQUEST,subCode:C||0,resultCategories:_,result:f,phrase:an.CALL_END_PHRASE.BAD_SERVICE_RESPONSE};this.telemetryHelper.recordEvent(dn.ADMIT_FAILURE,{causeId:v,transactionEnd:T}),this.callOperationHandler.rejectPendingOperation(0,v,"AdmitAllStatus response contains failure",T,S)}}else this.logger.warn(`[${S}][handleAdmitAllStatus] invalid admitAllStatus response or no pending operation. operationId=${v}`)}sendNetworkRequestForAdmit(g){const onceTrouterReady=()=>{this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.ADMIT,(()=>{this.telemetryHelper.recordEvent(dn.ADMIT_TIMEOUT,{causeId:g}),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT,g),this.callOperationHandler.rejectPendingOperation(0,g,"timed out waiting for admit operation",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.ADMIT_TIMEOUT,phrase:an.CALL_END_PHRASE.ADMIT_TIMEOUT},g)}),an.TIMEOUT_VALUES_IN_SECONDS.ADMIT_TIMEOUT,g)};this.http.sendPostRequest({url:this.links[an.LINKS.ADMIT_ALL],requestName:hn.ADMIT.name,payload:getPayload26(this,g),causeId:g,onceTrouterReady:onceTrouterReady}).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingAgentConfig);this.telemetryHelper.recordEvent(dn.ADMIT_FAILURE,{causeId:g,...S.error}),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT,g),this.callOperationHandler.rejectPendingOperation(0,g,f,S.error,g)}))}getConversationType(g,f,S){return g?"emergencyGroupCall":f?"cast":S?"huddleGroupCall":null}getMaxReinvitelessMediaForVideoForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVideoForWeb}getMaxReinvitelessMediaForVBSSForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVBSSForWeb}convertParkType(g){return"teamPark"===g?"TransferTypeTeamPark":"sharedLinePark"===g?"TransferTypeSharedLinePark":"serverHold"===g?"TransferTypeServerHold":(this.logger.info(`convertParkType, parkType: ${g} is unknown`),"none")}parkByTransfer(g,f){this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(f)}),an.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT);const S=this.getNetworkRequestName(g);return this.http.sendPostRequest({url:this.links[an.LINKS.TRANSFER],requestName:S,payload:getPayload39(g,this),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[${f}][parkByTransfer] error: ${getPrintableObject(S)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:an.CALL_END_CODE.NETWORK_ERROR,reason:getPrintableObject(g)}},f),this.telemetryHelper.recordEvent(dn.TRANSFER_REQUEST_FAILED,{causeId:f,...S.error}),Promise.reject(S.error))})),this.telemetryHelper.recordEvent(dn.TRANSFER_REQUEST_SENT,{causeId:f,transferType:this.convertParkType(g)}),Promise.resolve()}park(g,f){this.logger.info(`[${f}][park] context ${g}`),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.PARK_COMPLETION,(()=>{this.handleParkError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.PARK_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.PARK_COMPLETION_TIMEOUT},dn.WAITING_FOR_PARK_COMPLETION_TIMEOUT,f,g)}),an.TIMEOUT_VALUES_IN_SECONDS.PARK_COMPLETION_TIMEOUT);const S=this.getHoldTypeInRequest(g),v={causeId:f};return this.http.sendPostRequest({url:this.links[an.LINKS.PARK],requestName:hn.PARK_REQUEST.name,payload:getPayload40(this,S,v),causeId:f}).then((g=>{this.logger.info(`[${f}][park] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_PARK_COMPLETION,{causeId:f}),assertNotNull(g.response.holdResponse.links,"server response does not include park links"),this.links[an.LINKS.UNPARK]=g.response.holdResponse.links.resume})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${f}][park] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleParkError(v.error,dn.PARK_REQUEST_FAILED,f,g),Promise.reject(v.error))})),Promise.resolve()}getHoldTypeInRequest(g){switch(g){case"serverHoldV2":return"musicOnHold";case"sharedLineParkV2":return"sharedLineAppearance";case"callPark":return"callPark";default:return null}}handleParkError(g,f,S,v){this.disposed?this.logger.info("handleParkError ignored"):(this.logger.info(`[${S}] handleParkError reject reason: ${getPrintableObject(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.PARK_COMPLETION),this.signalingSessionCallback.onParkCompleted&&(this.telemetryHelper.recordEvent(f,{...g,parkContext:v,causeId:S}),this.signalingSessionCallback.onParkCompleted(g,S)),this.links[an.LINKS.UNPARK]=void 0)}handleParkCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.holdCompletion;this.handleOperationCompletionCommon(v,S,void 0,getPrintableObject(f),"handleParkCompletion",an.TIMEOUT_OPERATIONS.PARK_COMPLETION,dn.PARK_COMPLETED,dn.PARK_FAILED,this.signalingSessionCallback.onParkCompleted,this.handleParkError.bind(this))}handleUnparkError(g,f,S,v){this.disposed?this.logger.info("handleUnparkError ignored"):(this.logger.info(`[${S}] handleUnparkError reject reason: ${g}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.signalingSessionCallback.onUnparkCompleted&&(this.telemetryHelper.recordEvent(f,{...g,parkContext:v,causeId:S}),this.signalingSessionCallback.onUnparkCompleted(g,S)),this.links[an.LINKS.UNPARK]=void 0)}handleUnparkCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g);if(this.disposed)return void this.logger.info(`[${S}]handleUnparkCompletion ignored`);this.logger.info(`[${S}][handleUnparkCompletion] body ${getPrintableObject(f)}`);const v=f.resumeCompletion;v.code===an.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.telemetryHelper.recordEvent(dn.UNPARK_COMPLETED,{...v,causeId:S}),this.signalingSessionCallback.onUnparkCompleted(v,S),this.links[an.LINKS.UNPARK]=void 0):this.handleUnparkError(v,dn.UNPARK_FAILED,S)}getNetworkRequestName(g){return{none:null,teamPark:hn.SEND_PARK_REQUEST.name,sharedLinePark:hn.SEND_SHARED_LINE_PARK_REQUEST.name,serverHold:hn.SEND_SERVER_HOLD_REQUEST.name}[g]}updateMeetingsGroupsAsync(g,f){this.logger.info(`[${g}][updateMeetingsGroupsAsync] scope=${f.scope}`),this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_GROUPS,{causeId:g,options:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION,(()=>{this.handleUpdateMeetingGroupsError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT},dn.WAITING_FOR_UPDATE_MEETING_GROUPS_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT);const S=getMeetingGroupsPayload(this,f,g);return this.http.sendPostRequest({url:this.links[an.LINKS.UPDATE_MEETING_GROUPS],requestName:hn.UPDATE_MEETING_GROUPS.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][updateMeetingsGroupsAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UPDATE_MEETING_GROUPS_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${g}][updateMeetingsGroupsAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingGroupsError(v.error,dn.UPDATE_MEETING_GROUPS_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}updateMonitorSessionAsync(g,f){this.logger.info(`[${f}][updateMonitorSessionAsync]`),this.telemetryHelper.recordEvent(dn.UPDATE_MONITOR_SESSION,{causeId:f,options:g}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION,(()=>{this.handleUpdateMonitorSessionError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT},dn.WAITING_FOR_UPDATE_MONITOR_SESSION_COMPLETION,f,g)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT);const S=getPayload55(this,g.monitorActionType,g.monitorData,f);return this.http.sendPostRequest({url:this.links[an.LINKS.UPDATE_MONITOR_SESSION],requestName:hn.UPDATE_MONITOR_SESSION.name,payload:S,causeId:f}).then((g=>{this.logger.info(`[${f}][updateMonitorSessionAsync] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UPDATE_MONITOR_SESSION_COMPLETION,{causeId:f})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${f}][updateMonitorSessionAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMonitorSessionError(v.error,dn.UPDATE_MONITOR_SESSION_REQUEST_FAILED,f,g),Promise.reject(v.error))}))}updateParticipantInterpretationStateAsync(g,f){return assertNotNullOrEmpty(f,"options should be a non null value"),this.logger.info(`[${g}][updateParticipantInterpretationStateAsync]`),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANT_INTERPRETATION_STATE,{causeId:g,options:f}),this.participantManager.updateParticipantInterpretationStateAsync(f,this.links[an.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE],g)}async sendProxiedMessageAsync(g,f){return f&&0!==f.length?this.links[an.LINKS.SEND_MESSAGE]?this.proxiedMessageNotificationManager.sendProxiedMessageAsync(g,f,this.links[an.LINKS.SEND_MESSAGE]):Promise.reject({code:an.VALIDATION.VALIDATION_FAILED,subCode:an.VALIDATION.NULL_OR_EMPTY,phrase:"missing url for CONSTANTS.LINKS.SEND_MESSAGE"}):Promise.reject({code:an.VALIDATION.VALIDATION_FAILED,subCode:an.VALIDATION.NULL_OR_EMPTY,phrase:"options should be a non empty array"})}async updateParticipantsPropertiesAsync(g,f,S,v){this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES,{causeId:v,updateParticipantsPropertiesContext:g});const C=this.links[an.LINKS.UPDATE_PARTICIPANTS_PROPERTIES],_=[],T=g.scope;if("self"===T){const f={id:this.participantManager.localParticipant.id,propertyBag:g.propertyBag};_.push(f)}else{if("specified"!==T)return Promise.reject("This scope is not Supported");{const f=g.participants;for(const g of f){const f={id:g.id,propertyBag:g.propertyBag};_.push(f)}}}return this.sendNetworkRequestForUpdateParticipantsProperties(_,f,C,S,v)}sendNetworkRequestForUpdateParticipantsProperties(g,f,S,v,C){const _=this.logger.createChild(`[${C}][sendNetworkRequestForUpdateParticipantsProperties]`,this.correlationId);if(S){const onceTrouterReady=()=>{const g={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT};this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,(()=>{this.handleUpdateParticipantsPropertiesOnTimeout(f,g,dn.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT,v,C)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION_TIMEOUT,v)},T=getUpdateParticipantsPropertiesPayload(this,g,v);return this.updateParticipantsPromises[v]=f,this.http.sendPostRequest({url:S,payload:T,requestName:hn.UPDATE_PARTICIPANTS_PROPERTIES.name,onceTrouterReady:onceTrouterReady,causeId:C}).then((g=>{_.info(`response: ${getPrintableObject(g)}`)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);_.info(`failed: ${getPrintableObject(f)}`);const S={...f.error};return this.disposed||(this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,v),delete this.updateParticipantsPromises[v]),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED,{causeId:C,transactionEnd:S}),Promise.reject(S)}))}{const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_LINK_MISSING,phrase:"updateParticipantsProperties link is missing"};return _.warn(g),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED,{causeId:C,error:g}),Promise.reject(g)}}checkAndCleanupPromisesForOperationId(g){this.updateParticipantsPromises[g]&&(0===this.updateParticipantsPromises[g].size?(delete this.updateParticipantsPromises[g],this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,g)):this.logger.info(`remaining promises for the operation  ${g} (count: ${this.updateParticipantsPromises[g].size}):\n                ${this.piiUtils.scrubMriOrOmit(safeJsonStringify(this.updateParticipantsPromises[g]))}`))}handleUpdateParticipantsPropertiesOnTimeout(g,f,S,v,C){if(this.disposed)return void this.logger.info("handleUpdateParticipantsPropertiesOnTimeout ignored");this.logger.createChild(`[${C}][handleUpdateParticipantsPropertiesOnTimeout]`,this.correlationId).info(`reason: ${f}`),this.telemetryHelper.recordEvent(S,{...f,causeId:C});const _={};g.forEach((g=>{_[g]=f,this.updateParticipantsPromises[v].delete(g)})),this.checkAndCleanupPromisesForOperationId(v),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(_,v,C)}joinMeetingGroupAsync(g,f){this.logger.info(`[${g}][joinMeetingGroupAsync]`),this.telemetryHelper.recordEvent(dn.JOIN_MEETING_GROUP,{causeId:g,options:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION,(()=>{this.handleJoinMeetingGroupError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.JOIN_MEETING_GROUP_TIMEOUT,phrase:an.CALL_END_PHRASE.JOIN_MEETING_GROUP_TIMEOUT},dn.WAITING_FOR_JOIN_MEETING_GROUP_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.JOIN_MEETING_GROUP_COMPLETION_TIMEOUT);const S=getJoinMeetingGroupPayload(this,f,g);return this.http.sendPostRequest({url:this.links[an.LINKS.JOIN_MEETING_GROUP],requestName:hn.JOIN_MEETING_GROUP.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][joinMeetingGroupAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_JOIN_MEETING_GROUP_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${g}][joinMeetingGroupAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleJoinMeetingGroupError(v.error,dn.JOIN_MEETING_GROUP_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}leaveMeetingGroupAsync(g,f){this.logger.info(`[${g}][leaveMeetingGroupAsync]`),this.telemetryHelper.recordEvent(dn.LEAVE_MEETING_GROUP,{causeId:g,options:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION,(()=>{this.handleLeaveMeetingGroupError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.LEAVE_MEETING_GROUP_TIMEOUT,phrase:an.CALL_END_PHRASE.LEAVE_MEETING_GROUP_TIMEOUT},dn.WAITING_FOR_LEAVE_MEETING_GROUP_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.LEAVE_MEETING_GROUP_COMPLETION_TIMEOUT);const S=getLeaveMeetingGroupPayload(this,f,g);return this.http.sendPostRequest({url:this.links[an.LINKS.LEAVE_MEETING_GROUP],requestName:hn.LEAVE_MEETING_GROUP.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][leaveMeetingGroupAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_LEAVE_MEETING_GROUP_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${g}][leaveMeetingGroupAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleLeaveMeetingGroupError(v.error,dn.LEAVE_MEETING_GROUP_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}handleUpdateMeetingGroupsError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleUpdateMeetingGroupsError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleUpdateMeetingGroupsError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,updateMeetingGroupsOptions:C,causeId:S}),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(g,S,v))}handleUpdateMeetingGroupsCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.updateMeetingGroupsResponse.operationId;if(this.disposed)return void this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] ignored. Call disposed.`);v||this.logger.warn(`[${S}][handleUpdateMeetingGroupsCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] starts`);const{updateMeetingGroupsResponse:C}=f,_=processTransactionResponse(C);_.code===an.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] update meeting group succeeded`),this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_GROUPS_RESPONSE_SUCCESS,{..._,causeId:S})):(this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] update meeting group failed code=${_.code} subCode=${_.subCode}`),this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_GROUPS_RESPONSE_FAILURE,{..._,causeId:S})),this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] completes`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(_,S,v)}handleJoinMeetingGroupError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleJoinedMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleJoinedMeetingGroupError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,joinMeetingGroupOptions:C,causeId:S}),this.signalingSessionCallback.onJoinMeetingGroupCompleted(g,S,v))}handleJoinMeetingGroupCompletion(g){const f=g.body.joinMeetingGroupResponse,S=extractCauseIdFromMessage(g),v=f.operationId;if(this.disposed)return void this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] ignored. Call disposed.`);v||this.logger.warn(`[${S}][handleJoinMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] starts`);const C=processTransactionResponse(f);C.code===an.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] join meeting group succeeded`),this.telemetryHelper.recordEvent(dn.JOIN_MEETING_GROUP_RESPONSE_COMPLETED,{...C,causeId:S})):(this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] join meeting group failed code=${C.code} subCode=${C.subCode}`),this.telemetryHelper.recordEvent(dn.JOIN_MEETING_GROUP_RESPONSE_FAILED,{...C,causeId:S})),this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onJoinMeetingGroupCompleted(C,S,v)}handleLeaveMeetingGroupError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleLeaveMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleLeaveMeetingGroupError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,leaveMeetingGroupOptions:C,causeId:S}),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(g,S,v))}handleLeaveMeetingGroupCompletion(g){const f=g.body.leaveMeetingGroupResponse,S=extractCauseIdFromMessage(g),v=f.operationId;if(this.disposed)return void this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] ignored. Call disposed.`);v||this.logger.warn(`[${S}][handleLeaveMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] starts`);const C=processTransactionResponse(f);C.code===an.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] leave meeting group succeeded`),this.telemetryHelper.recordEvent(dn.LEAVE_MEETING_GROUP_RESPONSE_COMPLETED,{...C,causeId:S})):(this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] leave meeting group failed code=${C.code} subCode=${C.subCode}`),this.telemetryHelper.recordEvent(dn.LEAVE_MEETING_GROUP_RESPONSE_FAILED,{...C,causeId:S})),this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(C,S,v)}handleDisablePreheatError(g,f,S){this.disposed?this.logger.info(`[${S}][handleDisablePreheatError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleDisablePreheatError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),this.telemetryHelper.recordEvent(f,{...g,causeId:S}),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject(g))}handleDisablePreheatCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.transactionEnd;if(this.disposed)this.logger.info(`[${S}][handleDisablePreheatCompletion] ignored. Call disposed.`);else if(this.disablePreheatDefer.isPending()){if(this.logger.info(`[${S}][handleDisablePreheatCompletion] starts`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),v.code===an.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${S}][handleDisablePreheatCompletion] update endpoint state succeeded`),this.handleEndpointStateUpdated(S,!0);else if(this.logger.info(`[${S}][handleDisablePreheatCompletion] update endpoint state failed code=${v.code} subCode=${v.subCode}`),this.disablePreheatDefer.isPending()){const g={response:v};this.disablePreheatDefer.reject(g)}}else this.logger.info(`[${S}][handleDisablePreheatCompletion] ignored. Disable preheat promise is resolved/rejected.`)}handleReceiveMessage(g){const f=extractCauseIdFromMessage(g);if(this.disposed)return void this.logger.info(`[${f}][handleReceiveMessage] ignored. Call disposed.`);let S;S=Array.isArray(g.body?.messageContent)?g.body.messageContent:[g.body];let v="";const C=[];for(let g=0;g<S.length;g++){const f=S[g];v+=f?.operationId,g<S.length-1&&(v+=","),C.push({operationId:f.operationId,messageType:f.type,payload:f.payload,from:{[f.from.id]:{participantLegIdMap:{[f.from.participantId]:{...f.from.endpointId&&{endpointId:f.from.endpointId}}},level:"endpoint"}}})}this.logger.info(`[${f}][handleReceiveMessage] complete. OperationIds:${v}`),this.telemetryHelper.recordEvent(dn.INCOMING_PROXIED_MESSAGES,{causeId:f,operationIds:v}),this.signalingSessionCallback.onIncomingProxiedMessages(C,f)}publishStateAsync(g,f,S,v,C,_){this.logger.info(`[${S}][publishStateAsync][publishType=${g} publishLevel=${f}]`),this.telemetryHelper.recordEvent(dn.PUBLISH_STATE,{causeId:S,publishType:g,publishLevel:f});const T=this.links[an.LINKS.PUBLISH_STATE];if(!T){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PUBLISH_STATE_LINK_MISSING,phrase:"publish state link is missing"};return this.logger.warn(g),Promise.reject(g)}let I={};try{I=JSON.parse(v)}catch(g){const f={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_CONTENT,phrase:"publish state content is invalid"};return this.logger.warn(f),Promise.reject(f)}return this.http.sendPostRequest({url:T,requestName:hn.PUBLISH_STATE.name,payload:getPayload42(this,g,f,I,C,_),causeId:S,requestId:S}).then((g=>{if(g?.response?.publishStateResponse)return this.parsePublishStateResult(g,S);{const f=`Invalid CS response which does not contains publishStateResponse. Respone: ${g?.response?JSON.stringify(g.response):"no response"}`;throw this.logger.warn(f),{response:{code:an.CALL_END_CODE.DECODING_FAILED,subCode:an.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:f}}}})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${S}][publishStateAsync] error: ${getPrintableObject(f)}`);const v=f.error;return this.telemetryHelper.recordEvent(dn.PUBLISH_STATE_FAILURE,{causeId:S,transactionEnd:v}),Promise.reject(v)}))}getPublishStateSequenceNumber(){return++this.publishStateSequenceNumber}getMonitorSequenceId(){return++this.monitorSequenceId}parsePublishStateResult(g,f){let S={};if(g?.response?.publishStateResponse){if(g.response.publishStateResponse.stateId)return g.response.publishStateResponse.stateId;if(g.response.publishStateResponse.results){if(1===g.response.publishStateResponse.results.length){if(g.response.publishStateResponse.results[0].stateId)return g.response.publishStateResponse.results[0].stateId;this.logger.warn("invalid response format")}return g.response.publishStateResponse.results.forEach((g=>{S[g.participantId]={code:g.result.code,phrase:g.result.phrase,subCode:g.result.subCode}})),JSON.stringify(S)}if(g.response.publishStateResponse.result)return S={code:g.response.publishStateResponse.result.code,phrase:g.response.publishStateResponse.result.phrase,subCode:g.response.publishStateResponse.result.subCode,result:g.response.publishStateResponse.additionalDetail},JSON.stringify(S)}const v=`Invalid CS response which does not contains publishStateResponse. Respone: ${g?.response?JSON.stringify(g.response):"no response"}`;throw this.logger.warn(v),{response:{code:an.CALL_END_CODE.DECODING_FAILED,subCode:an.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:v}}}removeStateAsync(g,f,S,v){if(this.logger.info(`[${g}][removeStateAsync][scope=${f} publishType=${S} stateIds=${v}]`),this.telemetryHelper.recordEvent(dn.REMOVE_STATE,{causeId:g,scope:f,publishType:S,stateIds:v}),!S&&!v){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.REMOVE_STATE_MISSING_ARGUMENTS,phrase:"remove state operation miss arguments"};return this.logger.warn(g),Promise.reject(g)}const C=this.links[an.LINKS.REMOVE_STATE];if(!C){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.REMOVE_STATE_LINK_MISSING,phrase:"remove state link is missing"};return this.logger.warn(g),Promise.reject(g)}return this.http.sendPostRequest({url:C,requestName:hn.REMOVE_STATE.name,payload:getPayload44(this,f,v,S),causeId:g,requestId:g}).then((f=>this.parseRemoveStateResult(f,g))).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingAgentConfig);this.logger.info(`[${g}][removeStateAsync] error: ${getPrintableObject(S)}`);const v=S.error;return this.telemetryHelper.recordEvent(dn.REMOVE_STATE_FAILURE,{causeId:g,transactionEnd:v}),Promise.reject(v)}))}parseRemoveStateResult(g,f){let S={};return g?.response?.removeStateResponse&&(g.response.removeStateResponse.results?g.response.removeStateResponse.results.forEach((g=>{S[g.stateId]={code:g.result.code,phrase:g.result.phrase,subCode:g.result.subCode}})):g.response.removeStateResponse.result&&(S={code:g.response.removeStateResponse.result.code,phrase:g.response.removeStateResponse.result.phrase,subCode:g.response.removeStateResponse.result.subCode,result:g.response.removeStateResponse.additionalDetail})),JSON.stringify(S)}updateMeetingSettingsAsync(g,f){this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_SETTINGS,{causeId:f,meetingSettings:g});const S=this.links[an.LINKS.UPDATE_MEETING_SETTINGS];if(!S){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_LINK_MISSING,phrase:"update meeting settings link is missing"};return this.logger.warn(g),Promise.reject(g)}if(!Object.keys(g).length){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_MISSING_ARGUMENTS,phrase:"update meeting settings missing arguments"};return this.logger.warn(g),Promise.reject(g)}return this.http.sendPutRequest({url:S,requestName:hn.UPDATE_MEETING_SETTINGS.name,payload:getPayload54(this,g),causeId:f,requestId:f}).then((()=>{Cn.noop()})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][updateMeetingSettingsAsync] error: ${getPrintableObject(S)}`);const v=S.error;throw this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_SETTINGS_FAILURE,{causeId:f,transactionEnd:v}),v}))}searchParticipantsAsync(g,f){this.logger.info(`[${f}][searchParticipantsAsync][queryOptions=${g}]`),this.telemetryHelper.recordEvent(dn.SEARCH_PARTICIPANTS,{causeId:f,queryOptions:g});const S=this.links[an.LINKS.SEARCH_PARTICIPANTS];if(!S){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_LINK_MISSING,phrase:"search participants link is missing"};return this.logger.warn(g),Promise.reject(g)}return this.http.sendPostRequest({url:S,requestName:hn.SEARCH_PARTICIPANTS.name,payload:getPayload45(this,g),causeId:f,requestId:f}).then((g=>{if(g?.response?.participants)return this.parseSearchParticipantsResult(g,f);{const f=`Invalid CS response which does not contain proper search results. Respone: ${g?.response?JSON.stringify(g.response):"no response"}`;throw this.logger.warn(f),{response:{code:an.CALL_END_CODE.DECODING_FAILED,subCode:an.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:f}}}})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][searchParticipantsAsync] error: ${getPrintableObject(S)}`);const v=S.error;return this.telemetryHelper.recordEvent(dn.SEARCH_PARTICIPANTS_FAILURE,{causeId:f,transactionEnd:v}),Promise.reject(v)}))}parseSearchParticipantsResult(g,f){const S=[];if(g?.response){const f=g.response.participants;if(f)for(const v of Object.keys(f))S.push(cn.fromRosterSearchResults(g.response.participants[v]))}return{participants:S}}getAllParticipantsAsync(g,f){this.logger.info(`[${f}][getAllParticipantsAsync][scope=${g}]`),this.telemetryHelper.recordEvent(dn.GET_ALL_PARTICIPANTS,{causeId:f,scope:g});const S=this.links[an.LINKS.GET_ALL_PARTICIPANTS];if(!S){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_LINK_MISSING,phrase:"get all participants link is missing"};return this.logger.warn(g),Promise.reject(g)}if("lobby"!==g){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SCOPE,phrase:"get all participants scope is invalid"};return this.logger.warn(g),Promise.reject(g)}return this.http.sendPostRequest({url:S,requestName:hn.GET_ALL_PARTICIPANTS.name,payload:getPayload35(this,g),causeId:f,requestId:f}).then((g=>{if(g?.response){return{participants:g.response.participants}}{const g="Invalid CS response which does not contain results.";throw this.logger.warn(g),{response:{code:an.CALL_END_CODE.DECODING_FAILED,subCode:an.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:g}}}})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][getAllParticipantsAsync] error: ${getPrintableObject(S)}`);const v=S.error;return this.telemetryHelper.recordEvent(dn.GET_ALL_PARTICIPANTS_FAILURE,{causeId:f,transactionEnd:v}),Promise.reject(v)}))}resetState(){this.currentCallStatus=null,this.fsmState=an.SIGNALING_FSM_STATE.IDLE}saveUpdatedCallLinksIfAny(g){g.links&&(this.logger.info(`saveUpdatedCallLinksIfAny, updated call links found, update to new links ${getPrintableObject(g)}`),this.links[an.LINKS.MEDIA_RENEGOTIATION]=g.links.mediaRenegotiation||this.links[an.LINKS.MEDIA_RENEGOTIATION],this.links[an.LINKS.TRANSFER]=g.links.transfer||this.links[an.LINKS.TRANSFER],this.links[an.LINKS.REPLACE]=g.links.replacement||this.links[an.LINKS.REPLACE],this.links[an.LINKS.HANGUP]=g.links.callLeg||this.links[an.LINKS.HANGUP],this.links[an.LINKS.KEEPALIVE]=g.links.callLeg||this.links[an.LINKS.KEEPALIVE],this.links[an.LINKS.PARK]=g.links.hold||this.links[an.LINKS.PARK],this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=g.links.updateMediaDescriptions||this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS],this.links[an.LINKS.UPDATE_MONITOR_SESSION]=g.links.monitor||this.links[an.LINKS.UPDATE_MONITOR_SESSION])}ensureMessageChannelReady(g){return this.disposed?(this.logger.info("ensureMessageChannelReady: error: call already disposed"),Promise.reject(this.getCallNotFoundTransactionEnd())):this.brokerService?(this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.STARTED}:${g}`),this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.ENDED}:${g}`),Promise.resolve()):this.ensureLatestTrouterUrl(g)}ensureLatestTrouterUrl(g){return this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.STARTED}:${g}`),this.getTrouterUrlAsync().then((f=>!f||"string"==typeof f&&!f.trim()?(this.telemetryHelper.recordEvent(dn.TROUTER_URL_CHANGED_TO_INVALID),this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.ENDED}:${g}`),Promise.reject(new Error("Invalid trouter url"))):this.disposed?(this.logger.info("ensureLatestTrouterUrl, trouterUrlGetter returned too late. Object is already disposed"),Promise.reject(this.getCallNotFoundTransactionEnd())):(this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.ENDED}:${g}`),this.baseMessagingChannelUrl=this.currentTrouterUrl=f,Promise.resolve()))).catch((f=>(this.disposed||this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.FAILED}:${g}`),this.logger.info(`ensureLatestTrouterUrl, failed because:${f}`),Promise.reject(f))))}signalTransferAcceptedAsync(g,f=causeId2()){return this.logger.info(`[signalTransferAcceptedAsync][${f}] transferType ${g}`),this.disposed?(this.logger.info(`[signalTransferAcceptedAsync][${f}] Call already ended, skip acceptance request`),Promise.reject({code:an.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(this.telemetryHelper.recordEvent(dn.SEND_ACCEPT_TRANSFER,{causeId:f,transferType:g}),this.http.sendPostRequest({url:this.links[an.LINKS.TRANSFER_ACCEPTANCE],requestName:hn.TRANSFER_ACCEPTANCE.name,payload:getPayload47(),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[signalTransferAcceptedAsync][${f}] error: ${getPrintableObject(S)}`),this.telemetryHelper.recordEvent(dn.SEND_ACCEPT_TRANSFER_FAIL,{causeId:f}),Promise.reject(S.error)})))}signalTransferCompletedAsync(g,f=causeId2()){return this.logger.info(`[signalTransferCompletedAsync][${f}] rejectReason ${g}`),this.disposed?(this.logger.info(`[signalTransferCompletedAsync][${f}]  Call already ended by transferor, skip completion request`),Promise.reject({code:an.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(0!==g.code?this.telemetryHelper.recordEvent(dn.TRANSFER_COMPLETION_FAILED,{code:g.code,subcode:g.subCode,causeId:f}):this.telemetryHelper.recordEvent(dn.TRANSFER_COMPLETED,{causeId:f}),this.telemetryHelper.recordEvent(dn.SEND_COMPLETE_TRANSFER,{causeId:f}),this.http.sendPostRequest({url:this.links[an.LINKS.TRANSFER_COMPLETION],requestName:hn.TRANSFER_COMPLETION.name,payload:getPayload49(g),causeId:f}).catch((g=>{this.telemetryHelper.recordEvent(dn.SEND_COMPLETE_TRANSFER_FAILED,{causeId:f});const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[signalTransferCompletedAsync][${f}] error: ${getPrintableObject(S)}`),Promise.reject(S.error)})))}async rejectCallWithFetchAndKeepAlive(g){this.telemetryHelper.recordEvent(dn.REJECT_WITH_FETCH_KEEP_ALIVE,{causeId:g});const f={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.BEACON,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:[Xi.Success]};await this.http.sendDeleteRequest({url:this.links[an.LINKS.REJECT],requestName:hn.REJECT_CALL.name,payload:getPayload43(this,f),causeId:g??causeId2(),requestId:newGuid(),useFetch:!0,fetchUseKeepAlive:!0})}async endCallWithFetchAndKeepAlive(g,f,S,v){this.telemetryHelper.recordEvent(dn.END_WITH_FETCH_KEEP_ALIVE,{causeId:v}),await this.http.sendPostRequest({url:g,requestName:hn.END_CALL.name,payload:f,causeId:v??causeId2(),requestId:newGuid(),useFetch:!0,fetchUseKeepAlive:!0})}endWithBeacon(g){if(this.disposed)return!1;const setTerminatedState=()=>{this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,g,f),this.dispose(f,g)};if(this.signalingAgentConfig.enableFetchRequestWithKeepAlive&&window.Request?.prototype?.hasOwnProperty("keepalive")&&this.currentCallStatus===an.CALL_STATUS.RINGING)return this.rejectCallWithFetchAndKeepAlive(g),setTerminatedState(),!0;const f={code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.BEACON,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED},S=JSON.stringify(getPayload37(this,f).payload),v=-1===this.links[an.LINKS.LEAVE].indexOf("?")?"?":"&",C=this.signalingAgent?.authTokenManager?.getLastTokenType(g),_=this.signalingAgent?.authTokenManager?.getLastToken(g);let T="";switch(C){case 4:case 8:this.logger.info(`[endWithBeacon] with tokenType:${C},token size:${_.length},query parameter:access_token`),T=`${this.links[an.LINKS.LEAVE]}${v}access_token=${_}`;break;default:this.logger.info(`[endWithBeacon] with tokenType:${C},token size:${_.length},query parameter:skypeToken`),T=`${this.links[an.LINKS.LEAVE]}${v}skypeToken=${_}`}return this.signalingAgentConfig.enableFetchApiForBeacon&&window.Request?.prototype?.hasOwnProperty("keepalive")?(this.endCallWithFetchAndKeepAlive(T,S,f,g),setTerminatedState(),!0):!!navigator?.sendBeacon&&(this.telemetryHelper.recordEvent(dn.END_WITH_BEACON,{causeId:g}),navigator.sendBeacon(T,S))}setFsmState(g){this.fsmState=g}setIsHostless(g,f){const S=!!g;this.isHostLessCall!==S&&(this.logger.info(`[${f}][setIsHostless] isHostless=${S}`),this.isHostLessCall=S)}hasGroupModality(){return this.threadId||this.groupId}processConversationServiceResponseHeaders(g,f){this.logger.info(`[${f}][processConversationServiceResponseHeaders]`);try{const S=g.request.headers[an.HEADERS.CORRELATION_ID]||g.request.headers[an.HEADERS.CORRELATION_ID.toLowerCase()];this.updateCorrelationId(S,f)}catch(g){this.logger.info(`[${f}][processConversationServiceResponseHeaders] failed, reason=${getPrintableObject(g)}`)}}processConversationServiceResponse(g,f,S){const v=this.logger.createChild(`[${f}][processConversationServiceResponse]`);if(v.info(`responseType :${S}`),this.processConversationServiceUpdate(g,f),g.subscriptionDetails?.selfParticipant){const S=cn.fromRoster(g.subscriptionDetails.selfParticipant,!0);v.info("converted selfParticipant to Participant type"),this.participantManager.updateLocalParticipantFromSubscribe(S,f)}g.selfParticipant?.enableCaptcha&&this.participantManager.setEnableCaptcha(!0,f),this.handleBrokerSubscription(g,f),g.roster&&this.internalHandleRosterUpdate(g.roster,!0,f),0===S&&(this.startOrJoinConvResponseReceived=!0,this.handlePendingEndpointState(f))}processConversationServiceUpdate(g,f){const S=this.logger.createChild(`[${f}][processConversationServiceUpdate]`);S.info(),this.convJoined=!0;const v=g.sequenceNumber>=0?g.sequenceNumber:-1;v<this.updateSequenceNumber?S.info(`seqNum=${v} is less than latest seqNum=${this.updateSequenceNumber}`):(this.updateSequenceNumber=v,this.links[an.LINKS.CONVERSATION_CONTROLLER]=g.conversationController,this.links[an.LINKS.ADD_PARTICIPANT]=g.links.addParticipant,this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY]=g.links.addParticipantAndModality,this.links[an.LINKS.LEAVE]=g.links.leave,this.links[an.LINKS.NOTIFICATION_LINKS]=g.links.notificationLinks,this.links[an.LINKS.REMOVE_PARTICIPANT]=g.links.removeParticipant,this.links[an.LINKS.ADD_MODALITY]=g.links.addModality,this.links[an.LINKS.REMOVE_MODALITY]=g.links.removeModality,this.links[an.LINKS.MUTE]=g.links.mute||null,this.links[an.LINKS.UNMUTE]=g.links.unmute||null,this.links[an.LINKS.ADMIT]=g.links.admit||null,this.links[an.LINKS.ADMIT_ALL]=g.links.admitAll||null,this.links[an.LINKS.UPDATE_ENDPOINT_STATE]=g.links.updateEndpointState||null,this.links[an.LINKS.UPDATE_ENDPOINT_METADATA]=g.links.updateEndpointMetadata||null,this.links[an.LINKS.UPDATE_PARTICIPANT_ROLE]=g.links.updateParticipantRole||null,this.links[an.LINKS.PUBLISH_STATE]=g.links.publishState||null,this.links[an.LINKS.REMOVE_STATE]=g.links.removeState||null,this.links[an.LINKS.UPDATE_MEETING_SETTINGS]=g.links.updateMeetingSettings||null,this.links[an.LINKS.SEARCH_PARTICIPANTS]=g.links.searchParticipants||null,this.links[an.LINKS.GET_ALL_PARTICIPANTS]=g.links.getAllParticipants||null,this.links[an.LINKS.UPDATE_MEETING_LIVE_STATE]=g.links.updateMeetingLiveState||null,this.links[an.LINKS.UPDATE_MEETING_GROUPS]=g.links.updateMeetingGroups||null,this.links[an.LINKS.SET_MEETING_LAYOUT]=g.links.setMeetingLayout||null,this.links[an.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE]=g.links.updateParticipantInterpretationState||null,this.links[an.LINKS.UPDATE_PARTICIPANTS_PROPERTIES]=g.links.updateParticipantProperties||null,this.links[an.LINKS.JOIN_MEETING_GROUP]=g.links.joinMeetingGroup||null,this.links[an.LINKS.LEAVE_MEETING_GROUP]=g.links.leaveMeetingGroup||null,this.links[an.LINKS.SEND_MESSAGE]=g.links.sendMessage||null,this.links[an.LINKS.UPDATE_MEETING_STATES]=g.links.updateMeetingStates||null,this.convSubject=g.subject,g.state&&(this.setMultiParty(g.state.isMultiParty,f),this.setIsHostless(g.state.isHostless||!1,f),this.conversationType=g.state.conversationType,this.isCastCall="cast"===g.state.conversationType,this.isHuddleGroupCall="huddleGroupCall"===g.state.conversationType),g.activeModalities&&g.activeModalities.groupChat&&this.updateGroupChatIds(g.activeModalities.groupChat,f),g.activeModalities&&g.activeModalities.broadcast&&(this.broadcastSession||(this.broadcastSession=new yn(this,this.signalingSessionCallback)),this.broadcastSession.handleBroadcastDetailsChanged(g,f)),this.handleMeetingDetailsChanged(g,f),this.handleMeetingStatesChanged(g,f),this.linkUpdateRequested.conversationLinks?(S.info("Updating CS links as requested"),this.updateLinks(this.updateConversationLinks,f)):this.scheduleConversationKeepAlive(),g.meetingData&&(this.meetingData=g.meetingData),g.meetingInfo&&(this.meetingInfo=g.meetingInfo),g.region&&(this.region=g.region),g.callLimits&&(this.callLimits=g.callLimits),g.complianceRecordingContent&&(this.complianceRecordingContent=g.complianceRecordingContent),g.conversationStartTime&&(this.conversationStartTime=g.conversationStartTime),this.signalingSessionCallback.onConversationUpdated({conversationType:this.conversationType,groupId:this.groupId,threadId:this.threadId,teamsMessageId:this.teamsMessageId,isMultiParty:this.multiParty,commandUrlPresence:this.getCommandUrlPresence(),meetingData:this.meetingData,region:this.region,meetingInfo:this.meetingInfo,callLimits:this.callLimits,complianceRecordingContent:this.complianceRecordingContent,conversationStartTime:this.conversationStartTime,isHuddleGroupCall:this.isHuddleGroupCall,backroomThreadId:this.backroomThreadId,streamThreadId:this.streamThreadId,lobbyThreadId:this.lobbyThreadId},f))}processLocalParticipantUpdateResponse(g,f){this.logger.info(`[${f}][processLocalParticipantUpdateResponse]`),g.sequenceNumber&&g.sequenceNumber<this.localParticipantUpdateSequenceNumber||(this.breakoutDetails=g.breakoutDetails||{},this.signalingSessionCallback.onBreakoutDetailsUpdated(this.breakoutDetails,f),!0===g.nudgeToJoinAsRealtime&&(this.telemetryHelper.recordEvent(dn.NUDGE_TO_JOIN_REALTIME,{causeId:f}),this.signalingSessionCallback.onNudgeToJoinRealtime(f)))}handlePendingEndpointState(g){this.requestedEndpointStateWhileConnecting&&(this.logger.info(`[${g}][handlePendingEndpointState]sending pending endpoint state now that we are connected.`),this.updateEndpointState(this.requestedEndpointStateWhileConnecting,g,this.requestedPublishedStatesWhileConnecting).catch((g=>{this.isPreheatOnly&&this.disablePreheatDefer.isPending()&&(this.logger.info("handlePendingEndpointState failed"),this.disablePreheatDefer.reject(g))})))}handleMeetingDetailsChanged(g,f){this.logger.info(`[${f}][handleMeetingDetailsChanged]`),g.meetingDetails&&!Cn.isEqual(g.meetingDetails,this.meetingDetails)&&this.signalingSessionCallback.onMeetingDetailsUpdated&&(this.meetingDetails=g.meetingDetails,this.meetingDetails.meetingCapability?.meetingLiveState&&(this.meetingLiveStateSequenceNumber=this.meetingDetails.meetingCapability.meetingLiveState.seqNum,this.logger.info(`[${f}][handleMeetingDetailsChanged] update meeting seqNum as ${this.meetingLiveStateSequenceNumber}`)),this.signalingSessionCallback.onMeetingDetailsUpdated(this.meetingDetails,f))}handleMeetingStatesChanged(g,f){this.logger.info(`[${f}][handleMeetingStatesChanged]`),this.signalingSessionCallback.onMeetingStatesUpdated&&this.signalingSessionCallback.onMeetingStatesUpdated(g.meetingStates,f)}handleBrokerSubscription(g,f){this.logger.info(`[${f}][handleBrokerSubscription]`),g.links.subscribe?(this.telemetryHelper.recordEvent(dn.SUBSCRIBE_URL_FOUND,f),this.brokerService&&!Cn.isEqual(g.links.subscribe,this.brokerService.currentSubscriptionUrl)?this.brokerService.subscribeToBroker(g.links.subscribe):(this.logger.info(`[${f}][handleBrokerSubscription] broker subscribe ignored. Broker is disabled or subscribe url is same.`),this.telemetryHelper.recordEvent(dn.BROKER_DISABLED_SUBSCRIBE_URL_PRESENT,f))):this.telemetryHelper.recordEvent(dn.SUBSCRIBE_URL_MISSING,f)}cancelOutgoingCall(g,f){const S=defer();this.logger.info(`[${f}][cancelOutgoingCall][rejectionData=${g&&getPrintableObject(g)}]`);const v={code:isNaN(g?.code)?an.CALL_END_CODE.CANCEL:g.code,subCode:g?.subCode||an.CALL_END_SUB_CODE.SUCCESS,phrase:g?.phrase||an.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:g?.resultCategories||[Xi.Success],clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase};if(this.signalingAgentConfig.enableSpecificErrorCodesForCallEnd&&(v.code=an.CALL_END_CODE.CANCEL,v.subCode=an.CALL_END_SUB_CODE.SUCCESS,v.phrase=an.CALL_END_PHRASE.LOCAL_USER_INITIATED,v.resultCategories=[Xi.Success]),this.links.hasOwnProperty(an.LINKS.LEAVE)){this.logger.info(`[${f}][cancelOutgoingCall] cancelling outgoing call`),this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const g={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()},C={terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultDetail:v.phrase||"CancelOutgoingCall",endCode:v.code,endSubCode:v.subCode,causeId:f,clientReasonSubCode:v.clientReasonSubCode,clientReasonPhrase:v.clientReasonPhrase,resultCategories:v.resultCategories};this.http.sendPostRequest({url:this.links[an.LINKS.LEAVE],requestName:hn.CANCEL_CALL.name,payload:getPayload32(this,v,g),causeId:f}).then((g=>{this.disposed||(this.telemetryHelper.setTerminatingData(C),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f)),S.resolve(null)})).catch((g=>{const _=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[cancelOutgoingCall][${f}] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(_)}`),this.disposed||(this.telemetryHelper.setTerminatingData(C),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f)),S.resolve(null)}))}else this.logger.info(`[${f}][cancelOutgoingCall] Conversation Service Leave Url is not yet set. Cannot leave conversation. Disposing anyways.`),v.subCode=an.CALL_END_SUB_CODE.CONV_URL_NOT_SET,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultDetail:v.phrase||"CancelOutgoingCall",endCode:v.code,endSubCode:v.subCode,causeId:f,clientReasonSubCode:v.clientReasonSubCode,clientReasonPhrase:v.clientReasonPhrase,resultCategories:v.resultCategories}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f),S.resolve(null);return S.promise}terminateEstablishedCall(g,f){const S=f.causeId||causeId2();this.logger.info(`[${S}][terminateEstablishedCall]`);const v=defer();this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const C=this.convJoined?hn.LEAVE_CONVERSATION.name:hn.END_CALL.name,_=build3(),T={code:g?.code||an.CALL_END_CODE.SUCCESS,subCode:g?.subCode||an.CALL_END_SUB_CODE.SUCCESS,phrase:g?.phrase||an.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:g?.resultCategories,clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase};T.resultCategories=T.resultCategories||[Xi.Success];const I={terminatingEnd:un.CALL_TERMINATING_END.LOCAL,endCode:T.code,endSubCode:T.subCode,resultDetail:T.phrase||"TerminateEstablishedCall",causeId:S,clientReasonSubCode:T.clientReasonSubCode,clientReasonPhrase:T.clientReasonPhrase,resultCategories:T.resultCategories};return this.leaveConversation(T,f).then((()=>{this.logger.info(`[${S}][terminateEstablishedCall]success`),this.disposed||(this.telemetryHelper.setTerminatingData(I),this.telemetryHelper.addNetworkOperationCompleted(C,!0,_.duration()),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,S,T),this.dispose(T,S)),v.resolve(null)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${S}][terminateEstablishedCall][failed] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(f)}]`),this.disposed||(this.telemetryHelper.setTerminatingData(I),this.telemetryHelper.addNetworkOperationCompleted(C,!1,_.duration()),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,S,T),this.dispose(T,S)),v.resolve(null)})),v.promise}deleteConversation(g,f){this.logger.info(`[${f}][deleteConversation]`);const S=defer();this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const v=hn.DELETE_CONVERSATION.name,C=build3(),_={code:g?.code||an.CALL_END_CODE.SUCCESS,subCode:g?.subCode||an.CALL_END_SUB_CODE.SUCCESS,phrase:g?.phrase||an.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED,resultCategories:g?.resultCategories||[Xi.Success],clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase},T={terminatingEnd:un.CALL_TERMINATING_END.LOCAL,endCode:_.code,endSubCode:_.subCode,resultDetail:_.phrase,causeId:f,clientReasonSubCode:_.clientReasonSubCode,clientReasonPhrase:_.clientReasonPhrase,resultCategories:_.resultCategories};return this.deleteConversationController(_,f).then((()=>{this.logger.info(`[${f}][deleteConversation]success`),this.disposed||(this.telemetryHelper.setTerminatingData(T),this.telemetryHelper.addNetworkOperationCompleted(v,!0,C.duration()),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,_),this.dispose(_,f)),S.resolve(null)})).catch((g=>{const I=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][deleteConversation][failed] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(I)}`),this.disposed||(this.telemetryHelper.setTerminatingData(T),this.telemetryHelper.addNetworkOperationCompleted(v,!1,C.duration()),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,_),this.dispose(_,f)),S.resolve(null)})),S.promise}leaveConversation(g,f){const S=f.causeId||causeId2();if(this.convJoined){this.logger.info(`[${S}][leaveConversation]`);const v={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()};return this.http.sendPostRequest({url:this.links[an.LINKS.LEAVE],requestName:hn.LEAVE_CONVERSATION.name,payload:getPayload37(this,g,v,f.scope),withoutTrouter:!0,causeId:S})}return this.logger.info(`[${S}][leaveConversation] ignore, not joined to conversation`),Promise.resolve(void 0)}deleteConversationController(g,f){return this.convJoined?(this.logger.info(`[${f}][deleteConversationController]`),this.http.sendDeleteRequest({url:this.links[an.LINKS.CONVERSATION_CONTROLLER],requestName:hn.DELETE_CONVERSATION.name,payload:getPayload34(this,g),withoutTrouter:!0,causeId:f})):(this.logger.info(`[${f}][deleteConversationController]ignored, not joined to conversation`),Promise.resolve(void 0))}rejectIncomingCall(g,f){this.telemetryHelper.recordEvent(dn.REJECT_INCOMING_CALL,f),this.logger.info(`[${f}][rejectIncomingCall]`);const S=defer();this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const v={code:isNaN(g?.code)?an.CALL_END_CODE.REJECT:g.code,subCode:g?.subCode||an.CALL_END_SUB_CODE.SUCCESS,phrase:g?.phrase||an.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:g?.resultCategories,clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase};v.resultCategories=v.resultCategories||[Xi.Success];const C={terminatingEnd:un.CALL_TERMINATING_END.LOCAL,endCode:v.code,endSubCode:v.subCode,resultDetail:v.phrase||"RejectCall",causeId:f,clientReasonSubCode:v.clientReasonSubCode,clientReasonPhrase:v.clientReasonPhrase,resultCategories:v.resultCategories};return this.http.sendDeleteRequest({url:this.links[an.LINKS.REJECT],requestName:hn.REJECT_CALL.name,payload:getPayload43(this,v),causeId:f}).then((g=>{this.disposed||(this.telemetryHelper.setTerminatingData(C),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f)),S.resolve(null)})).catch((g=>{const _=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[rejectIncomingCall][${f}] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(_)}`),this.disposed||(this.telemetryHelper.setTerminatingData(C),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f)),S.resolve(null)})),S.promise}onCallStatusChanged(g,f,S){const v=`[${f}][onCallStatusChanged]`;if(this.logger.info(`${v}${this.currentCallStatus}=>${g}]`),this.disposed)this.logger.info(`${v}Call is already disposed!!`);else if(S&&this.logger.info(`${v}[statusCode=${getPrintableObject(S)}]`),this.isPromotingToRealtime)g===an.CALL_STATUS.CONNECTED&&this.onPromotionCompleted(!1,void 0,f);else if(this.isValidStateTransitions(g)){this.currentCallStatus=g;const v={callStatus:g,statusCode:S,causeId:f};this.isPreheatOnly&&(v.isPreheatOnly=!0),this.telemetryHelper.recordEvent(dn.UPDATE_CALL_STATUS,v),this.signalingSessionCallback.onCallStatusChanged(g,S,f),this.currentCallStatus===an.CALL_STATUS.CONNECTED&&(this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.telemetryHelper.resetCallCancelationDurationWatch(),this.isPreheatOnly&&this.startCallPreheatTimer(f))}}updateMeetingLiveStateAsync(g,f){this.logger.info(`[${g}][updateMeetingLiveStateAsync][options=${JSON.stringify(f)}]`),this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_LIVE_STATE,{causeId:g,meetingLiveStateOptions:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,(()=>{this.handleUpdateMeetingLiveStateError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT},dn.WAITING_FOR_UPDATE_MEETING_LIVE_STATE_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT);const S=getPayload53(this,{...f,sequenceNumber:this.meetingLiveStateSequenceNumber},g);return this.http.sendPostRequest({url:this.links[an.LINKS.UPDATE_MEETING_LIVE_STATE],requestName:hn.UPDATE_MEETING_LIVE_STATE.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][updateMeetingLiveStateAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UPDATE_MEETING_LIVE_STATE_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${g}][updateMeetingLiveStateAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingLiveStateError(v.error,dn.UPDATE_MEETING_LIVE_STATE_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}updateMeetingStatesAsync(g,f){const S=this.logger.createChild(`[${g}][updateMeetingStatesAsync]`,this.correlationId);if(S.info(`meetingStatesOptions: ${JSON.stringify(f)}`),!f)return Promise.reject({code:an.VALIDATION.VALIDATION_FAILED,subCode:an.VALIDATION.NULL_OR_EMPTY,phrase:"meetingStatesOptions should be a non empty object"});this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_STATES,{causeId:g,meetingStatesOptions:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,(()=>{for(const S in f.meetingStates)this.handleUpdateMeetingStatesError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT},dn.WAITING_FOR_UPDATE_MEETING_STATES_COMPLETION,g,f.operationId+"_"+S)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT);const v=getPayload59(this,{...f.meetingStates},g);return this.http.sendPostRequest({url:this.links[an.LINKS.UPDATE_MEETING_STATES],requestName:hn.UPDATE_MEETING_STATES.name,payload:v,causeId:g}).then((f=>{S.info(`response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UPDATE_MEETING_STATES_COMPLETION,{causeId:g})})).catch((v=>{const C=getErrorForXHRFailure(v,this.signalingAgentConfig);if(S.error(`error: ${getPrintableObject(C)}`),!this.disposed){for(const S in f.meetingStates)this.handleUpdateMeetingStatesError(C.error,dn.UPDATE_MEETING_STATES_RESPONSE_FAILURE,g,f.operationId+"_"+S);return Promise.reject(C.error)}return Promise.reject(this.getCallNotFoundTransactionEnd())}))}handleUpdateMeetingLiveStateError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleUpdateMeetingLiveStateError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleUpdateMeetingLiveStateError] reject reason: ${g}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,updateMeetingGroupsOptions:C,causeId:S}),this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted&&this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted(g,S,v))}handleUpdateMeetingLiveStateCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.updateMeetingLiveStateResponse.result,C=f.updateMeetingLiveStateResponse.operationId;C||this.logger.warn(`[${S}][handleUpdateMeetingLiveStateCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleUpdateMeetingLiveStateCompletion] meetingLiveUpdate completes with operationId=${C}`),this.handleOperationCompletionCommon(v,S,C,getPrintableObject(f),"handleUpdateMeetingLiveStateCompletion",an.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,dn.UPDATE_MEETING_LIVE_STATE_RESPONSE_SUCCESS,dn.UPDATE_MEETING_LIVE_STATE_RESPONSE_FAILURE,this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted,this.handleUpdateMeetingLiveStateError.bind(this))}handleUpdateMeetingStatesError(g,f,S,v){this.disposed?this.logger.info(`[${S}][handleUpdateMeetingStatesError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleUpdateMeetingStatesError] reject reason: ${g}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,causeId:S}),this.signalingSessionCallback.onUpdateMeetingStatesCompleted&&this.signalingSessionCallback.onUpdateMeetingStatesCompleted(g,S,v))}handleUpdateMeetingStatesCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.updateMeetingStatesResponse,C=f.operationId,_=this.logger.createChild(`[${S}][handleUpdateMeetingStatesCompletion]`,this.correlationId);C||_.warn("operationId is undefined.");for(const g of v)_.info(`UpdateMeetingStates completes with operationId=${C}.`),this.handleOperationCompletionCommon(g.transactionEnd,S,C+"_"+g.meetingStateName,getPrintableObject(f),"handleUpdateMeetingStatesCompletion",an.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,dn.UPDATE_MEETING_STATES_RESPONSE_SUCCESS,dn.UPDATE_MEETING_STATES_RESPONSE_FAILURE,this.signalingSessionCallback.onUpdateMeetingStatesCompleted,this.handleUpdateMeetingStatesError.bind(this))}handleUpdateMonitorSessionCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleUpdateMeetingStatesCompletion]`,this.correlationId);const v=f.monitorCompletion;this.handleOperationCompletionCommon(v,S,void 0,getPrintableObject(f),"handleUpdateMonitorSessionCompletion",an.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION,dn.UPDATE_MONITOR_SESSION_RESPONSE_COMPLETED,dn.UPDATE_MONITOR_SESSION_RESPONSE_FAILED,this.signalingSessionCallback.onUpdateMonitorSessionCompleted,this.handleUpdateMonitorSessionError.bind(this))}handleUpdateMonitorSessionError(g,f,S,v){this.disposed?this.logger.info(`[${S}][handleUpdateMonitorSessionError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleUpdateMonitorSessionError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,monitorOptions:v,causeId:S}),this.signalingSessionCallback.onUpdateMonitorSessionCompleted(g,S))}setMeetingLayoutAsync(g,f){this.logger.info(`[${g}][setMeetingLayoutAsync][options=${JSON.stringify(f)}]`),this.telemetryHelper.recordEvent(dn.SET_MEETING_LAYOUT,{causeId:g,setMeetingLayoutOptions:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,(()=>{this.handleSetMeetingLayoutError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT},dn.WAITING_FOR_SET_MEETING_LAYOUT_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT);const S=getPayload46(this,{...f,sequenceNumber:this.meetingLayoutSequenceNumber});return this.http.sendPostRequest({url:this.links[an.LINKS.SET_MEETING_LAYOUT],requestName:hn.SET_MEETING_LAYOUT.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][setMeetingLayoutAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_SET_MEETING_LAYOUT_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S);return this.logger.info(`[${g}][setMeetingLayoutAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleSetMeetingLayoutError(v.error,dn.SET_MEETING_LAYOUT_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}handleSetMeetingLayoutError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleSetMeetingLayoutError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleSetMeetingLayoutError] reject reason: ${g}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,updateMeetingGroupsOptions:C,causeId:S}),this.signalingSessionCallback.onSetMeetingLayoutCompleted&&this.signalingSessionCallback.onSetMeetingLayoutCompleted(g,S,v))}handleSetMeetingLayoutCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.setMeetingLayoutResponse.result,C=f.setMeetingLayoutResponse.operationId;C||this.logger.warn(`[${S}][handleSetMeetingLayoutCompletion] operationId is undefined.`),this.handleOperationCompletionCommon(v,S,C,getPrintableObject(f),"handleSetMeetingLayoutCompletion",an.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,dn.SET_MEETING_LAYOUT_RESPONSE_SUCCESS,dn.SET_MEETING_LAYOUT_RESPONSE_FAILURE,this.signalingSessionCallback.onSetMeetingLayoutCompleted,this.handleSetMeetingLayoutError.bind(this))}handleOperationCompletionCommon(g,f,S,v,C,_,T,I,b,A){this.disposed?this.logger.info(`[${f}][${C}] ignored. Call disposed.`):(this.logger.info(`[${f}][${C}] body ${v}`),g.code===an.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(_),this.telemetryHelper.recordEvent(T,{...g,causeId:f}),b&&b(g,f,S)):A&&A(g,I,f,S))}isValidStateTransitions(g){if(this.currentCallStatus===an.CALL_STATUS.LOCAL_TERMINATED&&g===an.CALL_STATUS.CONNECTING)return!0;const orderOfCallState=g=>{switch(g){case an.CALL_STATUS.IDLE:case an.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY:return 0;case an.CALL_STATUS.CONNECTING:return 1;case an.CALL_STATUS.RINGING:return 2;case an.CALL_STATUS.CONNECTED:return 3;case an.CALL_STATUS.LOCAL_TERMINATED:case an.CALL_STATUS.REMOTE_TERMINATED:return 4;default:return-1}};return orderOfCallState(g)>orderOfCallState(this.currentCallStatus)}handlePSTNBalanceUpdate(g){const f=g.body.balanceUpdate,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handlePSTNBalanceUpdate]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_PSTN_BALANCE_UPDATE,g),f.updateBalance?this.signalingSessionCallback.onPSTNBalanceUpdate(f):this.logger.info(dn.HANDLE_PSTN_BALANCE_UPDATE,"this was a pstn keepAlive message - ignore")}handleCallAcceptanceAck(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleCallAcceptanceAck]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_ACCEPTANCE_ACK,g),this.internalHandleCallAcceptanceAck(f,S)}internalHandleCallAcceptanceAck(g,f){this.logger.info(`[${f}][internalHandleCallAcceptanceAck] ${getPrintableObject(g)}`),this.fsmState!==an.SIGNALING_FSM_STATE.CONNECTED&&(this.links[an.LINKS.MEDIA_RENEGOTIATION]=g.callAcceptanceAcknowledgement.links.mediaRenegotiation,this.links[an.LINKS.TRANSFER]=g.callAcceptanceAcknowledgement.links.transfer,this.links[an.LINKS.REPLACE]=g.callAcceptanceAcknowledgement.links.replacement,this.links[an.LINKS.HANGUP]=g.callAcceptanceAcknowledgement.links.callLeg,this.links[an.LINKS.KEEPALIVE]=g.callAcceptanceAcknowledgement.links.callLeg,this.links[an.LINKS.PARK]=g.callAcceptanceAcknowledgement.links.hold,this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=g.callAcceptanceAcknowledgement.links.updateMediaDescriptions,this.links[an.LINKS.UPDATE_MONITOR_SESSION]=g.callAcceptanceAcknowledgement.links.monitor,this.saveMediaControllerLinksIfAny(g.callAcceptanceAcknowledgement),this.scheduleKeepAlives(g.callAcceptanceAcknowledgement.callKeepAliveInterval),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(g.callAcceptanceAcknowledgement.callProperties?.isSharedLineAppearanceV2Activated),this.fsmState=an.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.INCOMING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(f),this.onCallStatusChanged(an.CALL_STATUS.CONNECTED,f),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${f}][internalHandleCallAcceptanceAck] updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,f)))}isFatalException(g){let f=!0;try{JSON.parse(g.message).code===an.CALL_END_CODE.CONFLICT&&(f=!1,this.logger.info("isFatalException: received non-fatal 409 error"))}catch(g){this.logger.error("isFatalException: failed to parse error")}return f}startOrJoinCall(g,f,S,v,C){if(this.logger.info(`[${S}]startOrJoinCall[${f}]`),this.disposed)return void this.logger.info(`[${S}][${f}] session already disposed, ignore`);this.telemetryHelper.recordEvent(dn.START_OR_JOIN_CALL,{causeId:S,requestName:f}),this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,S);const _=this.getConversationUrl()?this.getConversationUrl():g.conversationServiceUrl;this.telemetryHelper.setConversationServiceUrl(_),this.logger.info(`options.conversationServiceUrl ${g.conversationServiceUrl} conversationServiceUrl ${_}`),g.isPreheatOnly?(this.isPreheatOnly=!0,this.telemetryHelper.recordEvent(dn.PREHEAT_ENABLING,{causeId:S}),this.telemetryHelper.setSelfParticipantRole(un.ROLE.PREHEAT),this.telemetryHelper.setIsPreheated()):this.telemetryHelper.startCallCancelationDurationWatch(),this.mediaTypesToUse=C,this.lastUsedOutgoingMediaContent=v,this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);const T=!this.multiParty&&this.signalingAgentConfig.enableLongOutgoing1To1SetupTimeoutForWeb,I=T?an.TIMEOUT_VALUES_IN_SECONDS.LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:an.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT;this.logger.info(`[${S}][${f}]target endpointType = ${this.transferContext&&this.transferContext.target?this.transferContext.target.endpointType:"default"} timeout = ${I} LongerTimeout = ${T}`);const b=g.newCall?getPayload33(this,v,C,g):getPayload36(this,v,C,g,S);this.signalingAgentConfig.enableCallEstablishmentTimeoutsForStartJoinCall&&this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(S)}),I),this.signalingSessionCallback.onTransferredCallAcceptance(S),g.endpointState&&(this.latestEndpointState=g.endpointState),this.http.sendPostRequest({url:_,requestName:f,operationType:"CallSetup",payload:b,causeId:S}).then((g=>{this.disposed||(this.processConversationServiceResponseHeaders(g,S),this.processConversationServiceResponse(g.response,S,0),this.onCallStatusChanged(an.CALL_STATUS.CONNECTING,S))})).catch((g=>{if(g.stack&&!this.isFatalException(g))return;const v=getErrorForXHRFailure(g,this.signalingAgentConfig);if(this.logger.info(`[startOrJoinCall][${S}][${f}] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(v)}`),!this.disposed){if(this.isPromotingToRealtime)return void this.onPromotionCompleted(!0,v.error,S);this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:v.telemetryEndSubCode,endSubCode:v.error.subCode,resultCategories:v.error.resultCategories,resultDetail:v.error.phrase||"StartOrJoinCallFailure",causeId:S}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,S,v.error),this.dispose(v.error,S)}}))}processIncomingCallPayload(g,f){this.remoteUser=cn.fromWireParticipant(g.callNotification.from),this.participantManager.setLocalParticipantId(g.callNotification.to.participantId,f),g?(g.conversationInvitation&&(this.links[an.LINKS.CONVERSATION_CONTROLLER]=g.conversationInvitation.conversationController,this.setMultiParty(g.conversationInvitation.isMultiParty,f),this.setIsHostless(!!g.conversationInvitation.isHostless,f)),g.callNotification&&(this.links[an.LINKS.ATTACH]=g.callNotification.links?.attach,this.links[an.LINKS.REDIRECT]=g.callNotification.links?.redirection,this.onBehalfOf=g.callNotification.onBehalfOf?.id,this.onBehalfOfUserDisplayName=g.callNotification.onBehalfOf?.displayName,this.callQueueContext=g.callNotification.callQueueContext,this.callPhoneLineType=g.callNotification.callPhoneLineType,this.callType=g.callNotification.callType,this.incomingCallCallerId=g.callNotification.from?.id,this.callUsesMixer=!!g.callNotification.mediaContent?.fromMixer,this.isRedirectAllowed=!!g.callNotification.redirectionProperties?.isRedirectAllowed,this.callQueueSupervisorContent=g.callNotification.callQueueSupervisorContent,this.bannerContent=g.callNotification.bannerContent),g.debugContent&&this.updateCorrelationId(g.debugContent.callId,f),g.callNotification.transferor&&(this.transferor=g.callNotification.transferor.details?g.callNotification.transferor.details.id:null),g.groupChat&&this.updateGroupChatIds(g.groupChat,f),g.meetingData&&(this.meetingData=g.meetingData),g.meetingInfo&&(this.meetingInfo=g.meetingInfo)):this.logger.info(`[${f}][processIncomingCallPayload] empty incoming payload content`)}processAttachResponse(g,f,S){this.telemetryHelper.recordEvent(dn.PROCESS_INITIAL_OFFER,{causeId:S}),this.links[an.LINKS.MEDIA_ANSWER]=f.response.callInvitation.links.mediaAnswer,this.links[an.LINKS.ACCEPT]=f.response.callInvitation.links.acceptance,this.links[an.LINKS.REJECT]=f.response.callInvitation.links.callLeg,this.links[an.LINKS.REDIRECT]=f.response.callInvitation.links.redirection,this.links[an.LINKS.NEW_OFFER]=f.response.callInvitation.links.newOffer,this.signalingAgentConfig.sendProgressFromCC||this.sendProgress(f),this.remoteCaller=f.response.participants.from;const v=this.getInitialMediaOfferFromIncomingCallPayload()||f.response.callInvitation.mediaContent;this.telemetryHelper.setCallerType(this.getParticipantIdForOfferAnswer(v));const C=getMediaTypes(f.response.callInvitation.callModalities);this.telemetryHelper.addIncomingModalities(C),this.telemetryHelper.setOfferedModalities(v.blob,!0),this.callUsesMixer=v.fromMixer,this.isRedirectAllowed=!(!f.response.callInvitation.redirectionProperties||!f.response.callInvitation.redirectionProperties.isRedirectAllowed),this.signalingSessionCallback.onOffer({subject:g.conversationInvitation.subject,remoteParticipantId:this.getParticipantIdForOfferAnswer(v),remoteEndpointId:f.response.participants.from.endpointId,transferor:f.response.callInvitation.transferor,clientTransferContext:g.callNotification.transferContext,customHeaderContext:f.response.callInvitation.customContext,mediaTypes:C,mediaContent:v,renegotiation:!1,invitationData:f.response.callInvitation.invitationData,riskLevel:f.response.callInvitation.spamProperties&&f.response.callInvitation.spamProperties.riskLevel,stirAttestation:f.response.callInvitation.spamProperties&&f.response.callInvitation.spamProperties.stirAttestation,isRedirectAllowed:this.isRedirectAllowed},S)}sendProgress(g,f=causeId2()){this.logger.info(`[${f}][sendProgress]`),this.telemetryHelper.recordEvent(dn.SEND_PROGRESS,{causeId:f}),this.http.sendPostRequest({url:g.response.callInvitation.links.progress,requestName:hn.SEND_CALL_PROGRESS.name,payload:getPayload30(this),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][sendProgress] error: ${getPrintableObject(S)}`),this.disposed||this.telemetryHelper.recordEvent(dn.SEND_PROGRESS_FAILED,{causeId:f,...S.error})}))}handleCallNotification(g){const f=extractCauseIdFromMessage(g);if(this.logger.info(`[${f}][handleCallNotification]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_NOTIFICATION,g),!stringEndsWith(g.url,rn.REPLACE))throw new Error(`[${f}][handleCallNotification]IncomingCallNotification should not be received in handleIncomingMsg`);this.telemetryHelper.recordIncomingEvent(dn.HANDLE_INCOMING_CALL_REPLACEMENT,g),this.logger.info(`[${f}][handleCallNotification]replacementCallNotification`),this.signalingSessionCallback&&this.signalingSessionCallback.onIncomingCallReplacement(g.body,f)}handleMediaAnswer(g){this.telemetryHelper.recordIncomingEvent(dn.HANDLE_MEDIA_ANSWER,g);const f=g.body,S=extractCauseIdFromMessage(g);if(this.logger.info(`[${S}][handleMediaAnswer]`),this.mediaRenegotiationManager.isOutgoingRenegotiationInProgress())this.mediaRenegotiationManager.handleMediaAnswer(f,S);else if(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED);else if(this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING){if(isDuplicateMessage(g.headers,this.provisionalMediaAnswersSeenSoFar))return void this.logger.info(`[${S}][handleMediaAnswer] ignoring provisional answer retried by service`);f.mediaAnswer.sender&&(this.remoteUser=f.mediaAnswer.sender),this.resetCallEstablishmentTimeout(S),f.mediaAnswer.noRingBack||(this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(an.CALL_STATUS.RINGING,S));const v=f.mediaAnswer.mediaContent;this.signalingSessionCallback.onAnswer({provisional:!0,renegotiation:!1,remoteEndpointId:f.mediaAnswer.sender?f.mediaAnswer.sender.endpointId:newGuid(),remoteParticipantId:this.getParticipantIdForOfferAnswer(v),mediaContent:v},S)}}async _sendCallAcceptanceAcknowledgement(g,f){this.http.sendPostRequest({url:g.body.callAcceptance.links.acknowledgement,requestName:hn.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:getPayload28(this),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][_sendCallAcceptanceAcknowledgement] error: ${getPrintableObject(S)}`),this.disposed||this.telemetryHelper.recordEvent(dn.HANDLE_CALL_ACCEPTANCE_FAILED,{causeId:f,...S.error})}))}handleCallAcceptance(g){const f=extractCauseIdFromMessage(g);this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_ACCEPTANCE,g,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:f}),this.logger.info(`[${f}][handleCallAcceptance]enableQuickSendAcceptanceAck:\n            ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?(this._sendCallAcceptanceAcknowledgement(g,f),this._processCallAcceptance(g,f)):(this._processCallAcceptance(g,f),this.http.sendPostRequest({url:g.body.callAcceptance.links.acknowledgement,requestName:hn.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:getPayload28(this),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][handleCallAcceptance] error: ${getPrintableObject(S)}`),this.disposed||this.telemetryHelper.recordEvent(dn.HANDLE_CALL_ACCEPTANCE_FAILED,{causeId:f,...S.error})})))}handleCallAcceptanceSync(g){const f=extractCauseIdFromMessage(g);this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_ACCEPTANCE_SYNC,g,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:f}),this.logger.info(`[${f}][handleCallAcceptanceSync] enableQuickSendAcceptanceAck:\n            ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?Cn.defer(this._processCallAcceptance,g,f):this._processCallAcceptance(g,f);const S=getPayload28(this).payload;return this.telemetryHelper.addNetworkOperationCompleted(hn.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,!0),S}getFakeRoster(g){const f=this.participantManager.getParticipantsToInitiateCallWith();let S;S=1===f.length?f[0].id:g.callAcceptance.acceptedBy.id;const v={id:S,displayName:g.callAcceptance.acceptedBy.id===S?g.callAcceptance.acceptedBy.displayName:"",languageId:g.callAcceptance.acceptedBy.languageId},C=g.callAcceptance.acceptedBy.endpointId;return{type:"MultiPartyEndpoint",participants:{[S]:{acceptedBy:g.callAcceptance.acceptedBy.id,details:v,endpoints:{[C]:{call:{},contentSharing:{},capabilities:g.callAcceptance.capabilities,participantId:g.callAcceptance.acceptedBy.participantId}}}}}}processCallAcceptance(g,f){this.logger.info(`[${f}][processCallAcceptance] ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.PROCESS_CALL_ACCEPTANCE,{causeId:f}),this.fsmState=an.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(f);let S=!1;g.callAcceptance.controllerName===an.MISC.LOBBY_CALL_CONTROLLER&&(this.logger.info(`[${f}][processCallAcceptance] Controller name is lobby so putting user in lobby`),this.participantManager.localParticipant.isLobby=!0,this.participantManager.localParticipant.endpointDetails.push({isLobby:!0,endpointId:this.participantManager.localParticipant.endpointId,participantId:this.participantManager.localParticipant.participantId}),S=!0,this.telemetryHelper.recordEvent(dn.ACCEPTANCE_USER_IN_LOBBY,{causeId:f})),this.participantManager.localParticipant.isStaging=hasStagingGroup(g.callAcceptance),this.signalingSessionCallback.onMeetingGroupDetailsUpdated(g.callAcceptance.meetingGroupDetails,f),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(g.callAcceptance.callProperties?.isSharedLineAppearanceV2Activated),this.logger.info(`[${f}][processCallAcceptance] for localParticipant, isStaging is set to ${this.participantManager.localParticipant.isStaging}`);let v=this.mediaTypesToUse,C=newGuid();g.callAcceptance.acceptedBy&&(this.remoteUser=cn.fromWireParticipant(g.callAcceptance.acceptedBy),C=g.callAcceptance.acceptedBy.endpointId),g.callAcceptance.acceptedCallModalities&&g.callAcceptance.acceptedCallModalities.length>0&&(v=g.callAcceptance.acceptedCallModalities);const _=g.callAcceptance.mediaContent;this.callUsesMixer=_.fromMixer;const T=getMediaTypes(v);this.telemetryHelper.addIncomingModalities(T),this.telemetryHelper.setAnsweredModalities(_.blob,!0),this.links[an.LINKS.MEDIA_RENEGOTIATION]=g.callAcceptance.links.mediaRenegotiation,this.links[an.LINKS.TRANSFER]=g.callAcceptance.links.transfer,this.links[an.LINKS.REPLACE]=g.callAcceptance.links.replacement,this.links[an.LINKS.HANGUP]=g.callAcceptance.links.callLeg,this.links[an.LINKS.KEEPALIVE]=g.callAcceptance.links.callLeg,this.links[an.LINKS.PARK]=g.callAcceptance.links.hold,this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=g.callAcceptance.links.updateMediaDescriptions,this.links[an.LINKS.UPDATE_MONITOR_SESSION]=g.callAcceptance.links.monitor,this.saveMediaControllerLinksIfAny(g.callAcceptance),this.scheduleKeepAlives(g.callAcceptance.callKeepAliveInterval);const I=this.getParticipantIdForOfferAnswer(_);this.signalingSessionCallback.onAnswer({provisional:!1,renegotiation:!1,remoteEndpointId:C,remoteParticipantId:I,callAcceptedByNGCVoicemail:I===an.KNOWN_BOTS.VOICEMAIL_BOT_ID,mediaTypes:T,mediaContent:_},f),this.setRealTimeState(2,f),this.onCallStatusChanged(an.CALL_STATUS.CONNECTED,f),S&&this.signalingSessionCallback.onSelfParticipantUpdated(this.participantManager.localParticipant,f),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${f}][processCallAcceptance] Updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,f))}updateGroupChatIds(g,f){const S=this.groupId,v=this.threadId,C=this.teamsMessageId,_=this.backroomThreadId,T=this.streamThreadId,I=this.lobbyThreadId;this.groupId=g.groupId,this.threadId=g.threadId,this.teamsMessageId=g.messageId,this.backroomThreadId=g.backroomThreadId,this.streamThreadId=g.streamThreadId,this.lobbyThreadId=g.lobbyThreadId,this.groupId===S&&this.threadId===v&&this.teamsMessageId===C&&this.backroomThreadId===_&&this.streamThreadId===T&&this.lobbyThreadId===I||this.signalingSessionCallback.onConversationUpdated({conversationType:this.conversationType,groupId:this.groupId,threadId:this.threadId,teamsMessageId:this.teamsMessageId,isMultiParty:this.multiParty,commandUrlPresence:this.getCommandUrlPresence(),meetingData:this.meetingData,region:this.region,meetingInfo:this.meetingInfo,callLimits:this.callLimits,isHuddleGroupCall:this.isHuddleGroupCall,backroomThreadId:this.backroomThreadId,streamThreadId:this.streamThreadId,lobbyThreadId:this.lobbyThreadId},f)}handleCallEnd(g,f){let S=g.body.callEnd||g.body;const v=extractCauseIdFromMessage(g);if(this.logger.info(`[${v}][handleCallEnd][content=${getPrintableObject(S)}]`),this.telemetryHelper.recordEvent(dn.HANDLE_CALL_END,{origin:g.origin,code:S?S.code:"unknown",subCode:S?S.subCode:"unknown",resultCategories:S?S.resultCategories:[],causeId:v}),this.signalingAgentConfig.enableConversationTypeUpdateOnCallEnd&&(this.conversationType=S?.conversationType||this.conversationType,this.signalingSessionCallback.onConversationTypeUpdated(this.conversationType,v)),this.fsmState!==an.SIGNALING_FSM_STATE.IDLE)if(S.code===an.CALL_END_CODE.CONFLICT&&this.multiParty&&S.conversationUrl?.Location)this.handleConversationResolutionConflict(S,v);else{this.disposing=!0,S.callControllerTransactionEnd&&(this.logger.info("handleCallEnd: using CC end details specified in CS end"),S=S.callControllerTransactionEnd),S.broadcastOperationFailure&&(this.logger.info("handleCallEnd: using broadcastOperationFailure end details specified in CS end"),S=S.broadcastOperationFailure);const g=S.code===an.CALL_END_CODE.SUCCESS||S.code===an.CALL_END_CODE.CANCEL||S.code===an.CALL_END_CODE.REJECT;this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.REMOTE,resultDetail:S.phrase,resultValue:g?un.RESULT_VALUE.SUCCESS:un.RESULT_VALUE.FAILURE,endCode:S.code,endSubCode:S.subCode,resultCategories:S?S.resultCategories:[],causeId:v});const C={code:S.code,subCode:S.subCode,phrase:S.phrase,resultCategories:S.resultCategories,pickupCode:""},_=this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY;this.fsmState=an.SIGNALING_FSM_STATE.IDLE,S.acceptedElsewhereBy&&(this.acceptedElsewhereBy={id:S.acceptedElsewhereBy.id,displayName:S.acceptedElsewhereBy.displayName}),S.unparkContent&&(S.unparkContent.CallParkAdditionalContext&&(this.parkAdditionalContextJson=JSON.stringify(S.unparkContent.CallParkAdditionalContext),this.serverHoldLocation=S.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),S.unparkContent.pickupCode&&(C.pickupCode=S.unparkContent.pickupCode));const T=this.signalingAgentConfig.enableSplitConversationEndUrl;T&&_===f?(this.logger.info("fsmstate = SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY or OUTGOING_FOR_ROSTER_ONLY"),this.onCallStatusChanged(an.CALL_STATUS.REMOTE_TERMINATED,v,C),this.dispose(C,v)):T||(this.onCallStatusChanged(an.CALL_STATUS.REMOTE_TERMINATED,v,C),this.dispose(C,v))}else this.logger.info(`[${v}][handleCallEnd] not handling incoming callEnd since fsmstate = SIGNALING_FSM_STATE.IDLE`)}handleConversationResolutionConflict(g,f){this.logger.info(`[${f}][handleConversationResolutionConflict]`);const S={...g,phrase:g.phrase||"Conflict Resolution Error"};if(this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY)this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.http.cancelRequestIfPending(hn.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,f,void 0,S),this.subscribeToCall(g.conversationUrl.Location,g.correlationId,this.lastUsedJoinCallOptions?this.lastUsedJoinCallOptions.clientEndpointCapabilities:0,{meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,additionalEndpointProperties:this.lastUsedJoinCallOptions?.additionalEndpointProperties},f);else{this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const v={meetingData:this.meetingData,meetingPreferences:this.meetingPreferences};if(this.lastUsedJoinCallOptions){const g=this.lastUsedJoinCallOptions.scenario;v.muted=this.lastUsedJoinCallOptions.muted,v.scenario=`409Redirect${g||""}`,v.isPreheatOnly=this.lastUsedJoinCallOptions.isPreheatOnly,v.clientEndpointCapabilities=this.lastUsedJoinCallOptions.clientEndpointCapabilities,v.clientEndpointDebugContent=this.lastUsedJoinCallOptions.clientEndpointDebugContent,v.additionalEndpointProperties=this.lastUsedJoinCallOptions.additionalEndpointProperties}else v.scenario="409RedirectJoin";this.setInitialTelemetry("JoinCall",{correlationId:g.correlationId,causeId:f,conversationServiceUrl:g.conversationUrl.Location,joinCallOptions:v,offerGenerationTime:void 0}),this.http.cancelRequestIfPending(hn.JOIN_CONVERSATION.name,f,void 0,S),this.http.cancelRequestIfPending(hn.START_CALL.name,f,void 0,S),this.joinGivenConversation(g.conversationUrl.Location,g.correlationId,this.lastUsedOutgoingMediaContent,this.mediaTypesToUse,void 0,v,f)}}handleCallProgress(g){this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_PROGRESS,g);const f=extractCauseIdFromMessage(g);this.logger.info(`[${f}][handleCallProgress]`);const S=g.body.callProgress;this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING&&(this.telemetryHelper.setTimeToRingDuration(),this.resetCallEstablishmentTimeout(f),this.onCallStatusChanged(an.CALL_STATUS.RINGING,f),"forwarded"===S.status&&this.signalingSessionCallback.onCallForwarded({destinationType:S.forwardingDestinationType||"user"},f))}resetCallEstablishmentTimeout(g){const f=this.isOneToOnePSTNCall()?an.TIMEOUT_VALUES_IN_SECONDS.LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:an.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT;this.logger.info(`resetCallEstablishmentTimeout: ${f}s`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(g)}),f)}handleMediaAcknowledgement(g){this.telemetryHelper.recordIncomingEvent(dn.HANDLE_MEDIA_ACK,g);const f=g.body,S=extractCauseIdFromMessage(g);this.currentCallStatus!==an.CALL_STATUS.CONNECTED?this.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_PROVISIONAL_ACK,{causeId:S}):this.mediaRenegotiationManager.handleMediaAcknowledgment(f,S)}handleConversationUpdate(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleConversationUpdate]content=${getPrintableObject(f)}`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CONVERSATION_UPDATE,g),this.processConversationServiceResponse(f,S,2)}endBroadcastMeeting(g){this.logger.info(`[${g}][endBroadcastMeeting]`),this.broadcastSession=null}handleLocalParticipantUpdate(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleLocalParticipantUpdate]content=${getPrintableObject(f)}`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_LOCAL_PARTICIPANT_UPDATE,g),this.processLocalParticipantUpdateResponse(f,S)}handleAddModalityFailure(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAddModalityFailure]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_MODALITY_FAILURE,g),f.modalityFailure.contentSharing?this.contentSharingManager?.handleAddModalityFailure(f,S):f.modalityFailure.groupChat?this.signalingSessionCallback.onChatModalitySetupFailed({code:f.modalityFailure.groupChat.code,subCode:f.modalityFailure.groupChat.subCode,phrase:f.modalityFailure.groupChat.phrase,resultCategories:f.modalityFailure.groupChat.resultCategories},S):f.modalityFailure.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalityFailure(f,S)}handleAddModalitySuccess(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAddModalitySuccess]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_MODALITY_SUCCESS,g),f.modalitySuccess.contentSharing?this.contentSharingManager?.handleAddModalitySuccess(f,S):f.modalitySuccess.groupChat?this.logger.info(`[${S}][handleAddModalitySuccess] group modality ${getPrintableObject(f.modalitySuccess.groupChat)}`):f.modalitySuccess.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalitySuccess(f,S)}handleTransferRequested(g){const f=g.body.callTransfer,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleTransferRequested]`),f.parkType?(this.telemetryHelper.recordIncomingEvent(dn.HANDLE_PARK_REQUESTED,g,{type:f.parkType}),this.telemetryHelper.addSharedCorrelationId(f.sharedCorrelationId)):"voicemail"===f.target.endpointType?(this.logger.info(`[${S}][handleTransferRequested] target endpointType = ${f.target.endpointType}`),this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_REQUEST_RECEIVED,g)):this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_REQUEST_RECEIVED,g),this.links[an.LINKS.TRANSFER_ACCEPTANCE]=f.links.transferAcceptance,this.links[an.LINKS.TRANSFER_COMPLETION]=f.links.transferCompletion,this.signalingSessionCallback.onTransferRequested?this.signalingSessionCallback.onTransferRequested(f,S):this.logger.info(`[${S}][handleTransferRequested] failed, no callback defined`)}handleTransferAcceptance(g){const f=extractCauseIdFromMessage(g);this.logger.info(`[${f}][handleTransferAcceptance]`),this.telemetryHelper.recordIncomingEvent(dn.WAITING_FOR_TRANSFER_COMPLETION,g),this.signalingSessionCallback.onTransferAccepted?this.signalingSessionCallback.onTransferAccepted(f):this.logger.info(`[${f}][handleTransferAcceptance]failed, no callback defined`)}handleTransferCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleTransferCompletion]`),f.sharedCorrelationId&&this.telemetryHelper.addSharedCorrelationId(f.sharedCorrelationId),void 0!==f.unparkContent?.pickupCode&&(f.unparkContent.pickupCode=f.unparkContent.pickupCode.toString(),this.telemetryHelper.recordIncomingEvent(dn.PICKUP_CODE_SET,g)),this.signalingSessionCallback.onTransferCompleted?(g.body.transferCompletion&&(0===g.body.transferCompletion.code?this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_COMPLETED,g):(this.logger.info(`[${S}][handleTransferCompletion]-1-code: ${f.transferCompletion.code}, message: ${getPrintableObject(g)}`),this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_COMPLETION_FAILED,g,{code:f.transferCompletion.code,subcode:f.transferCompletion.subCode,resultCategories:f.transferCompletion.resultCategories}))),this.signalingSessionCallback.onTransferCompleted(f,S)):(g.body.transferCompletion&&(g.body.transferCompletion.code===an.CALL_END_CODE.NETWORK_ERROR?this.telemetryHelper.recordIncomingEvent(dn.WAITING_FOR_TRANSFER_COMPLETION_FAIL,g):this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_COMPLETION_FAILED,g,{code:f.transferCompletion.code,subcode:f.transferCompletion.subCode,resultCategories:f.transferCompletion.resultCategories})),this.logger.info(`[${S}][handleTransferCompletion]failed, no callback defined`))}handleRosterUpdate(g,f){const S=g.body,v=extractCauseIdFromMessage(g);this.disposing||this.disposed?this.logger.info(`[${v}][handleRosterUpdate]failed=ignore call ending or ended`):this.internalHandleRosterUpdate(S,f,v)}handleNewMediaOffer(g){const f=extractCauseIdFromMessage(g);this.telemetryHelper.recordIncomingEvent(dn.HANDLE_NEW_OFFER,g);const S=g.body.mediaOfferReady.mediaContent;this.callUsesMixer=S.fromMixer,this.signalingSessionCallback.onNewOffer({mediaContent:S,renegotiation:!1},f)}internalHandleRosterUpdate(g,f,S){if(g&&"Delta"!==g.type&&"MultiPartyEndpoint"!==g.type)this.logger.warn(`[${S}][internalHandleRosterUpdate] roster.type=${g.type} is invalid`);else{this.logger.info(`[${S}][internalHandleRosterUpdate]`);try{this.participantManager.handleRosterUpdate(g,f,S),this.contentSharingManager?.handleIncomingContentSharingFromRoster(g,f,S)}catch(f){const v={code:an.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:an.CALL_END_SUB_CODE.ROSTER_HANDLING_INVALID_SERVICE_RESPONSE,phrase:f?.toString()};throw this.logger.info(`[${S}][internalHandleRosterUpdate] ${safeJsonStringify(v)}`),this.telemetryHelper.recordRosterEvent(g,dn.HANDLE_ROSTER_UPDATE_FAIL,S),v}}}scheduleKeepAlives(g){const f=.9*g*1e3;this.logger.info(`scheduleKeepAlives: every ${f} milliseconds`),this.keepAliveInterval=f,this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval)}scheduleConversationKeepAlive(){if(!this.conversationKeepAliveTimer&&!this.disposed){if(!this.conversationKeepAliveInterval){const g=getRandomizedTimeout(1e3*this.signalingAgentConfig.csaTimeoutConfiguration.conversationKeepAliveTimeoutSec);this.logger.info(`sendConversationKeepAlive: every ${g} milliseconds`),this.conversationKeepAliveInterval=g}this.conversationKeepAliveTimer=window.setInterval(this.sendConversationKeepAlive.bind(this),this.conversationKeepAliveInterval)}}sendConversationKeepAlive(){this.logger.info("sendConversationKeepAlive"),this.disposed?this.logger.info("sendConversationKeepAlive ignored"):(this.logger.info("sendConversationKeepAlive keepAlive count = "+this.conversationKeepAliveCount++),this.sendToUpdateConversationLinks(!0))}sendKeepAlive(){this.logger.info("sendKeepAlive"),this.disposed?this.logger.info("sendKeepAlive ignored"):(this.logger.info("sendKeepAlive keepAlive count = "+this.keepAliveCount++),this.sendToKeepAliveUrl(null))}sendToUpdateConversationLinks(g,f=causeId2()){if(this.disposed)return Promise.resolve();const S=this.logger.createChild(`[${f}][sendToUpdateConversationLinks]`,this.correlationId),v=g?getPayload56(this):{},C=g?hn.UPDATE_CONVERSATION_LINKS.name:hn.SEND_CONVERSATION_KEEP_ALIVE.name,_=this.links[an.LINKS.NOTIFICATION_LINKS];return S.info(`shouldUpdateUrl: ${g}, url: ${_}, payload: ${getPrintableObject(v)}`),_?(this.conversationKeepAliveTimer&&(window.clearInterval(this.conversationKeepAliveTimer),this.conversationKeepAliveTimer=0),this.http.sendPostRequest({url:_,payload:v,withoutTrouter:!0,requestName:C,causeId:f}).then((g=>{this.disposed||(this.telemetryHelper.recordEvent(dn.UPDATE_CONVERSATION_LINKS_SUCCESS,{causeId:f}),this.processConversationServiceResponse(g.response,f,2))})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig),v=isRetryable(S.error.code);this.logger.info(`[${f}][updateConversationLinks] error: ${getPrintableObject(S)}, retryable: ${v}`),this.disposed||(this.telemetryHelper.recordEvent(dn.UPDATE_CONVERSATION_LINKS_FAILED,{causeId:f,...S.error}),v?this.scheduleConversationKeepAlive():this.links[an.LINKS.NOTIFICATION_LINKS]=null)}))):Promise.resolve()}sendToKeepAliveUrl(g,f=causeId2()){const S=this.logger.createChild(`[${f}][sendToKeepAliveUrl]`,this.correlationId);return S.info(`payload: ${getPrintableObject(g)}`),window.clearInterval(this.keepAliveTimer),this.disposed?Promise.resolve():(this.telemetryHelper.recordEvent(dn.SEND_KEEP_ALIVE),this.http.sendPostRequest({url:this.links[an.LINKS.KEEPALIVE],payload:g,requestName:hn.SEND_KEEP_ALIVE.name,withoutTrouter:!0,causeId:f}).then((()=>{this.restartKeepAliveInterval(f)})).catch((g=>{const v=getErrorForXHRFailure(g,this.signalingAgentConfig);S.info(`error: ${getPrintableObject(v)}`),this.restartKeepAliveInterval(f,!0,v.error)})))}handleCallEstablishmentTimeout(g,f,S){const v={code:an.CALL_END_CODE.TIMEOUT,subCode:f||an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:S||an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT,resultCategories:[Xi.UnexpectedClientError]};this.isPromotingToRealtime?this.onPromotionCompleted(!0,v,g):(this.telemetryHelper.recordEvent(dn.HANDLE_CALL_ESTABLISHMENT_TIMEOUT),this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,resultDetail:v.phrase,endCode:v.code,endSubCode:v.subCode,causeId:g,resultCategories:v.resultCategories}),this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,g,v),this.dispose(v,g))}handleCallTransferTimeout(g,f){if(this.disposed)return void this.logger.info("Transfer: handleCallTransferTimeout ignored");const S={code:an.CALL_END_CODE.TIMEOUT,phrase:an.CALL_END_PHRASE.TRANSFER_COMPLETION_TIMEOUT};this.signalingSessionCallback.onTransferCompleted&&(!1===f?this.telemetryHelper.recordEvent(dn.TRANSFER_COMPLETION_FAILED,{code:an.CALL_END_CODE.TIMEOUT,subcode:an.CALL_END_SUB_CODE.TRANSFER_COMPLETE_TIMEOUT,causeId:g}):!0===f&&this.telemetryHelper.recordEvent(dn.WAITING_FOR_TRANSFER_ACCEPTANCE_FAIL,{causeId:g}),this.signalingSessionCallback.onTransferCompleted({transferCompletion:S},g))}checkCorrelationIdChange(g,f){if(g&&g.headers){const S=g.headers.get(an.HEADERS.CORRELATION_ID);if(S&&S.length){const v=[rn.CONV_CONTENT_SHARING_UPDATE,rn.CONV_CONTENT_SHARING_END].some((f=>g.url&&stringEndsWith(g.url,f)));this.correlationId===S||v||(this.logger.info(`[${f}]checkCorrelationIdChange:${this.correlationId} => ${S}`),this.telemetryHelper.addChangingCorrelationId(this.correlationId,S),this.updateCorrelationId(S,f))}}}getCommandUrlPresence(){let g=0;return this.links[an.LINKS.MUTE]&&(g|=1),this.links[an.LINKS.UNMUTE]&&(g|=2),g}getCallNotFoundTransactionEnd(){return{code:an.CALL_END_CODE.CALL_DOES_NOT_EXIST,subCode:0,phrase:an.CALL_END_PHRASE.CALL_DOES_NOT_EXIST}}dispose(g,f){this.disposed||(this.logger.info(`[${f}][dispose] end reason ${getPrintableObject(g)}`),this.disposed=!0,this.disposing=!1,this.tearDownConnectionCheck(),this.conversationKeepAliveTimer&&(window.clearInterval(this.conversationKeepAliveTimer),this.conversationKeepAliveTimer=0),this.keepAliveTimer&&window.clearInterval(this.keepAliveTimer),this.brokerService&&this.brokerService.dispose(),this.http.cancelAllRequests(f).then((()=>{this.signalingAgent.onCallCompleted(this.sessionId,f),this.signalingAgentConfig.trouterUrlGetter&&this.signalingAgentConfig.trouterUrlGetter.trouterUrl.changed.off(this.onTrouterUrlChanged),this.signalingAgentConfig.trouterServiceProvider&&this.signalingAgentConfig.trouterServiceProvider.offStateChanged(this.onTrouterStateChanged),this.timeoutManager.dispose(),this.timeoutManager=null,this.participantManager.dispose(g,f),this.callOperationHandler.dispose("call ended",g,f),this.participantManager=null,this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=null,this.contentSharingManager?.dispose(g,f),this.contentSharingManager=null,this.telemetryHelper.dispose(),this.telemetryHelper=null,this.webRtcSignalingManager.dispose(),this.webRtcSignalingManager=null})))}};function build5(g,f,S,v,C,_){return new tr(g,f,S,v,C,_)}var ir=class{constructor(g){this.endpointId=newGuid(),this.signalingSessions={},this.clientSupportsGenericTokenAPI=!1,this.getNewSignalingSession=(g,f,S,v)=>{const C=causeId2();assertNotNull(g,"selfParticipant should be a non null value"),assertNotNull(f,"signalingSessionCallback should be a non null value");const _=S||newGuid();assertNotNullOrEmpty(_,"signalingSession id generated cannot be null or empty"),this.checkConfigChange(C);const T=build5(g,f,this.signalingAgentConfig,_,this,v),I=T.sessionId;return this.signalingSessions[I]=T,this.logger.info(`[${C}]Created new signalingSession with correlation ID ${_} and session ID ${I}`),T},this.resolvePotentialCallConflict=g=>{const f=causeId2();if(this.logger.info(`[${f}][resolvePotentialCallConflict]`),g.multiParty)return;const S=Object.values(this.signalingSessions).find((f=>this.isSessionInConflictingState(f,g)));if(!S)return;let v;if(v=g.isIncomingCall?this.getConflictingSessionToEnd(g,S):this.getConflictingSessionToEnd(S,g),!v)return;const C=v===g?S:g;return this.logger.info("Call conflict done.",` conflictingSession.correlationId=${S.correlationId}`,` conflictingSession.urlIdentifier=${S.urlIdentifier}`,` sessionToEnd.correlationId=${v.correlationId}`,` sessionToEnd.urlIdentifier=${v.urlIdentifier}`),v.telemetryHelper.setConflictingCallId(C.correlationId),v.telemetryHelper.recordEvent(dn.CONFLICTED_CALL),this.signalingAgentConfig.endConflictedCall?(this.endConflictedSession(v,f),v):void 0},this.handleIncomingNotification=g=>{if(assertNotNull(g,"request should be a non null value"),this.logger.info(`handleIncomingNotification to : ${g.url}`),!g.body&&!g.rawBody)return this.logger.error("request has no body"),this.buildNotificationResponse(an.HTTP_STATUS_CODES.BAD_REQUEST);let f=an.HTTP_STATUS_CODES.OK;const S=getIdFromUrl(g.url);if(S){const v=this.signalingSessions.hasOwnProperty(S);if(this.logger.info(`Is session found:${v}`),v){const f=this.signalingSessions[S];if(g.headers=new ln(g.headers),isEncodedMessage(g.headers))try{if(!isMessageEncodingSupported(g.headers))throw new Error("Unsupported encoding");const f=decodeMessage(g.rawBody),S=JSON.parse(f);g.body=S}catch(g){return f.telemetryHelper.recordEvent(dn.TROUTER_DECODE_PAYLOAD_FAILURE),this.buildNotificationResponse(an.HTTP_STATUS_CODES.BAD_REQUEST)}if(f.canHandleIncomingMsgSync(g))return f.handleIncomingMsgSync(g);window.setTimeout((()=>{if(this.signalingSessions.hasOwnProperty(S)){const f=this.signalingSessions[S];f.handleIncomingMsgAsync(g).catch((g=>{f&&f.telemetryHelper&&f.telemetryHelper.recordEvent(dn.FAILED_TO_HANDLE_TROUTER_MESSAGE),this.logger.error(`handling IncomingMsg failed with error: ${g}`)}))}}),0)}else this.logger.info(`Incoming message for session ID ${S}, but session was not found!`),f=an.HTTP_STATUS_CODES.NOT_FOUND}else this.logger.error(`Could not retrieve session ID from Url path. Path = ${g.url}`),f=an.HTTP_STATUS_CODES.BAD_REQUEST;const v=this.buildNotificationResponse(f);return this.logger.info(`Result code:${getPrintableObject(v)}`),v},this.onCallCompleted=(g,f)=>{this.signalingSessions.hasOwnProperty(g)?(delete this.signalingSessions[g],this.logger.info(`[${f}][onCallCompleted] Session ID ${g} found. Deleted from signalingSession table`)):this.logger.info(`[${f}][onCallCompleted] Session ID ${g} not found. Could not delete from signalingSession table`)},this.applyAuthTokenCacheConfig=g=>{this.signalingAgentConfig.enableTokenCache?(this.authTokenManager.setTokenCaching(!0,g),this.signalingAgentConfig.enableTokenPrefetch&&this.authTokenManager.getToken(g).then((()=>{this.logger.info(`[${g}] token prefetch success`)})).catch((f=>{this.logger.info(`[${g}] token prefetch failure, error=${getPrintableObject(f)}`)}))):this.authTokenManager.setTokenCaching(!1,g),this.signalingAgentConfig.enableTokenCacheForGenericTokenAPI?this.authTokenManager.setTokenCachingForGenericTokenAPI(!0,g):this.authTokenManager.setTokenCachingForGenericTokenAPI(!1,g)},this.endConflictedSession=(g,f)=>{this.logger.info("Call conflict, ending signalingSession with callId=",g.correlationId,"urlIdentifier=",g.urlIdentifier),g.endAsync({code:an.CALL_END_CODE.CONFLICT,subCode:an.CALL_END_SUB_CODE.CONFLICT_IN_NG,phrase:an.CALL_END_PHRASE.CONFLICT},{forEveryone:!1,causeId:f})},this.getConflictingSessionToEnd=(g,f)=>{if(!is1to1Mri(g.incomingCallCallerId)||!is1to1Mri(f.participantManager.localParticipant.id))return;const S=stripMri(g.incomingCallCallerId),v=f.participantManager.getParticipantsToInitiateCallWith();if(0===v.length)return;const C=stripMri(v[0].id),_=stripMri(f.participantManager.localParticipant.id);return C===S?_>S?g:f:void 0},this.isSessionInConflictingState=(g,f)=>{if(!g)return this.logger.info("Call conflict, ignore, session already disposed"),!1;const S=[an.CALL_STATUS.IDLE,an.CALL_STATUS.CONNECTING,an.CALL_STATUS.RINGING];return!g.multiParty&&S.indexOf(g.getCallStatus())>-1&&f.isIncomingCall!==g.isIncomingCall},this.buildNotificationResponse=(g,f)=>this.signalingAgentConfig.supportsSynchronousTrouterResponse?{resultCode:g,responseBody:f}:g,setDefaultsForSignalingConfig(g),this.signalingAgentConfig=g,this.logger=g.logger.createChild("SignalingAgent"),assertNotNull(g,"signalingAgentConfig should be a non null value"),this.logger.info(g.isWebRtcEnabled?"webRTC enabled":"ORTC enabled");const f={aadTokenExpirationTimeInSeconds:g.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:g.caeTokenExpirationTimeInSeconds,disableTokenMigrationHeader:g.disableTokenMigrationHeader,enablePublishTokenTelemetry:g.enablePublishTokenTelemetry,refreshTimeBeforeTokenTimeoutInSeconds:g.refreshTimeBeforeTokenTimeoutInSeconds,forceClearExpiredTokens:g.forceClearExpiredTokens,enableRefreshToken:g.enableRefreshToken,enableRefreshTokenRetry:g.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:g.enableRefreshTokenRetryInSeconds};this.authTokenManager=Sn.build(this.logger,g.skypeToken,f,g.telemetryManager),this.applyAuthTokenCacheConfig(causeId2()),ln.useLowerCaseHeaders=g.forceLowercaseHttpHeaders}updateSignalingAgentConfig(g){const f=causeId2(),S=JSON.stringify(g,((g,f)=>g?String(f):f));this.logger.info(`[${f}] updateSignalingAgentConfig, SignalingAgentConfig: ${S}`),this.logger.info(`[${f}] ecsEtag=${g.ecsEtag}`),setDefaultsForSignalingConfig(g),this.updatedSignalingAgentConfig=g,this.authTokenManager?.updateTokenSettings({aadTokenExpirationTimeInSeconds:g.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:g.caeTokenExpirationTimeInSeconds,refreshTimeBeforeTokenTimeoutInSeconds:g.refreshTimeBeforeTokenTimeoutInSeconds,disableTokenMigrationHeader:g.disableTokenMigrationHeader,enablePublishTokenTelemetry:g.enablePublishTokenTelemetry,forceClearExpiredTokens:g.forceClearExpiredTokens,enableRefreshToken:g.enableRefreshToken,enableRefreshTokenRetry:g.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:g.enableRefreshTokenRetryInSeconds}),ln.useLowerCaseHeaders=g.forceLowercaseHttpHeaders}updateUrls(g,f,S){this.logger.info(`updateUrls: conversationServiceUrl: ${g}, uploadLogRequestUrl: ${f}, enforceUrls: ${S}`),this.updatedSignalingAgentConfig=this.updatedSignalingAgentConfig||this.signalingAgentConfig,S||!this.updatedSignalingAgentConfig.isConversationServiceUrlFromEcs?this.updatedSignalingAgentConfig.conversationServiceUrl=g||this.updatedSignalingAgentConfig.conversationServiceUrl:this.updatedSignalingAgentConfig.conversationServiceUrl=this.updatedSignalingAgentConfig.conversationServiceUrl||g,S||!this.updatedSignalingAgentConfig.isUploadLogRequestUrlFromEcs?this.updatedSignalingAgentConfig.uploadLogRequestUrl=f||this.updatedSignalingAgentConfig.uploadLogRequestUrl:this.updatedSignalingAgentConfig.uploadLogRequestUrl=this.updatedSignalingAgentConfig.uploadLogRequestUrl||f}update(g){this.logger.info(`update accountConfiguration ${JSON.stringify(g)}`),g&&g.clientSupportsGenericTokenAPI!==this.clientSupportsGenericTokenAPI&&(this.clientSupportsGenericTokenAPI=g.clientSupportsGenericTokenAPI,this.authTokenManager.updateTokenSettings({clientSupportsGenericTokenAPI:this.clientSupportsGenericTokenAPI})),this.accountConfig=g}sendPushAsync(g,f,S,v,C=causeId2()){const _=new vn(this.signalingAgentConfig.piiScrubber),T=`sendPush[local participant mri = ${_.scrubMriOrOmit(g)}][recipientList = ${_.scrubMriOrOmit(f)}][headers = ${S})][causeId = ${C}]`;if(!g?.id)return this.logger.info(`${T} Empty localParticipantId`),Promise.reject("invalid localParticipantId");if(!f||0===f.length||f.every((g=>g&&""===g.id)))return this.logger.info(`${T} Empty recipientList`),Promise.reject("invalid recipientList");if(!S)return this.logger.info(`${T} Empty headers`),Promise.reject("invalid headers");if(!v||null===tryParse(v))return this.logger.info(`${T} Invalid body.`),Promise.reject("invalid body");const I={...tryParse(v),To:Array.from(f,(g=>g.id)),From:g.id},b=new ln(S);b.hasOwnPropertyCaseInsensitive(an.HEADERS.CORRELATION_ID)||b.set(an.HEADERS.CORRELATION_ID,generateGuid()),b.hasOwnPropertyCaseInsensitive(an.HEADERS.MESSAGE_ID)||b.set(an.HEADERS.MESSAGE_ID,generateGuid()),b.hasOwnPropertyCaseInsensitive(an.HEADERS.PARTICIPANT_ID)||b.set(an.HEADERS.PARTICIPANT_ID,generateGuid()),b.hasOwnPropertyCaseInsensitive(an.HEADERS.CONTENT_TYPE)||b.set(an.HEADERS.CONTENT_TYPE,"application/json"),b.hasOwnPropertyCaseInsensitive(an.HEADERS.CLIENT_USER_AGENT)&&b.set(an.HEADERS.CLIENT_USER_AGENT,b.get(an.HEADERS.CLIENT_USER_AGENT)+`/TsCallingVersion=${getTsCallingVersion()}/Ovb=${getOvb()}`);const A=this.signalingAgentConfig.httpRequestDispatcher.getRequestOptions("POST",b?.getAll(),JSON.stringify(I),3e4);return A.useFetch=this.signalingAgentConfig.enableFetchApi,new Promise(((g,f)=>{this.signalingAgentConfig.httpRequestDispatcher.postAsync(this.signalingAgentConfig.uploadLogRequestUrl||an.URL_DEFAULTS.UPLOAD_LOG_URL,A).then((()=>{g()})).catch((g=>{f(g)}))}))}getSignalingSession(g){for(const f of Object.keys(this.signalingSessions)){const S=this.signalingSessions[f];if(S.correlationId===g)return S}return null}updateToken(g,f,S,v,C){this.authTokenManager.updateToken(g,f,S,v,C)}setTokenRequiredCallBack(g){this.authTokenManager.setTokenRequiredCallBack(g)}resetAuthTokenManager(){this.setTokenRequiredCallBack(null),this.authTokenManager.setDisableTimerFlag(!0),this.authTokenManager.dispose()}checkConfigChange(g){this.updatedSignalingAgentConfig&&this.updatedSignalingAgentConfig!==this.signalingAgentConfig&&(this.signalingAgentConfig=this.updatedSignalingAgentConfig,this.updatedSignalingAgentConfig=null,this.applyAuthTokenCacheConfig(g))}},nr=/;aliases=.*$/i,rr="8:",sr=";aliases=",ar="2:",or="4:";function stripMriAliases(g){return g?g.replace(nr,""):g}function generateAliasedMri(g,f){let S=g;return f&&(S+=sr+ar+f),S}var isOneOfPhaseErrors=(g,f)=>f&&void 0!==f.phase&&!!g[f.phase],isPhaseError=(g,f)=>f&&void 0!==f.phase&&f.phase===g;function createPhaseExecutor(g){const f={},recordPhaseStep=g=>{const S={status:"Pending"};f[g]=S},recordStepDoneTelemetry=(g,S)=>{f[g].t=S,delete f[g].status},recordStepFailedTelemetry=(g,S,v)=>{f[g].status="Failed",f[g].t=S,f[g].reason=getPrintableObject(v)};return{execute:async(S,v)=>{const C=g.createChild(`[phase=${S}]`);recordPhaseStep(S),C.info("started");const _=(new Date).getTime();try{const g=await v(),f=+new Date-_;return C.logSuccess(`done, time=${f}`),recordStepDoneTelemetry(S,f),g}catch(g){const v=+new Date-_;throw C.logFailure(`time=${v}, error=${getPrintableObject(g)}`),recordStepFailedTelemetry(S,v,g),{phase:S,error:g,phases:f}}},executeSync:(S,v)=>{const C=g.createChild(`[phase=${S}]`);C.info("started"),recordPhaseStep(S);const _=(new Date).getTime();try{const g=v(),f=+new Date-_;return recordStepDoneTelemetry(S,f),C.logSuccess(`done, time=${f}`),g}catch(g){const v=+new Date-_;throw C.logFailure(`time=${v}, error=${getPrintableObject(g)}`),recordStepFailedTelemetry(S,v,g),{phase:S,error:g,phases:f}}},getTelemetryData:()=>f}}function callStateIsAnyOf(g,f){return-1!==f.indexOf(g)}var lr,cr,dr,hr={0:[1,2,8,6,10,11,9],1:[2,6,7,10,13],2:[1,3,6,7,9,10,13,14],3:[6,7,4,5,10,13],8:[1,11,10,2,9,6,7],4:[6,7,3,5,10,13],5:[6,7,3,4,10,13],9:[3,6,7,10,13],10:[3,6,7,9,4,5,13,15],13:[3,6,7,4,5],14:[3,6,7,10,13],15:[3,6,7,4,5,13],11:[12,1,2,6,7],12:[2,6,7],6:[7],7:[]};(g=>{let f;var S;let v;var C;let _;var T;let I;var b;(S=f=g.VideoEffectType||(g.VideoEffectType={})).Off="off",S.BackgroundBlur="blur",S.BackgroundReplacement="replacement",S.PresenterMode="presenterMode",S.None="none",(C=v=g.PowerPreference||(g.PowerPreference={})).Default="default",C.HighPerformance="high-performance",C.LowPower="low-power",(T=_=g.ProcessorType||(g.ProcessorType={})).Wasm="Wasm",T.Webgl2="Webgl2",(b=I=g.EffectQualityChangeReason||(g.EffectQualityChangeReason={}))[b.ExternalParam=0]="ExternalParam",b[b.Performance=1]="Performance",b[b.RendererSize=2]="RendererSize"})(lr||(lr={})),(g=>{let f;var S;let v;var C;let _;var T;let I;var b;let A;var P;(S=f=g.CallType||(g.CallType={}))[S.P2P=0]="P2P",S[S.Conference=1]="Conference",S[S.PSTN=2]="PSTN",S[S.BroadcastingConf=3]="BroadcastingConf",(C=v=g.AudioUsageMode||(g.AudioUsageMode={}))[C.Default=0]="Default",C[C.LongRangeSpeaker=1]="LongRangeSpeaker",C[C.Auditorium=2]="Auditorium",(T=_=g.AecPerfProfile||(g.AecPerfProfile={}))[T.Normal=0]="Normal",T[T.Soc=1]="Soc",T[T.Mobile=2]="Mobile",T[T.NoisyTimestamps=3]="NoisyTimestamps",(b=I=g.VqeMode||(g.VqeMode={}))[b.Off=0]="Off",b[b.SkypeNS=1]="SkypeNS",b[b.SkypeAEC=2]="SkypeAEC",b[b.SkypeVQE=3]="SkypeVQE",b[b.DeepNS=4]="DeepNS",b[b.DeepVQE=5]="DeepVQE",(P=A=g.AudioEffectType||(g.AudioEffectType={})).Off="Off",P.NoiseSuppressionDeep="Deep NS",P.NoiseSuppressionClassic="Classic NS",P.EchoCancellationClassic="Classic AEC",P.VoiceQualityEnhancementClassic="Classic VQE",P.VoiceQualityEnhancementDeep="Deep VQE"})(cr||(cr={})),(g=>{let f;var S;let v;var C;(S=f=g.FrameType||(g.FrameType={}))[S.None=0]="None",S[S.Software=1]="Software",S[S.Hardware=2]="Hardware",(C=v=g.LogLevel||(g.LogLevel={}))[C.Default=0]="Default",C[C.Debug=1]="Debug",C[C.Info=2]="Info",C[C.Warning=3]="Warning",C[C.Error=4]="Error"})(dr||(dr={}));var ur=M,gr=(g=>(g[g.CallStateChanged=0]="CallStateChanged",g[g.TrouterStateChanged=1]="TrouterStateChanged",g[g.MultiPartyModeSet=2]="MultiPartyModeSet",g[g.MediaRetargetSucceeded=3]="MediaRetargetSucceeded",g[g.MediaRetargetFailed=4]="MediaRetargetFailed",g))(gr||{}),pr=(g=>(g[g.StartModality=0]="StartModality",g[g.StopModality=1]="StopModality",g[g.StreamStateChanged=2]="StreamStateChanged",g[g.NegotiationStateChanged=3]="NegotiationStateChanged",g))(pr||{}),mr=(g=>(g[g.SelectSource=0]="SelectSource",g[g.AttachSource=1]="AttachSource",g[g.DetachSource=2]="DetachSource",g))(mr||{}),fr=(g=>(g[g.Available=0]="Available",g[g.Subscribe=1]="Subscribe",g[g.Subscribed=2]="Subscribed",g[g.Unsubscribe=3]="Unsubscribe",g[g.Unsubscribed=4]="Unsubscribed",g[g.RenderingStarted=5]="RenderingStarted",g[g.RenderingStopped=6]="RenderingStopped",g))(fr||{}),Sr=class{};Sr.agentEnvironmentId="agent_environment_id",Sr.correlationId="CorrelationId",Sr.participantId="participant_id",Sr.displayName="display_name",Sr.tenantId="TenantId",Sr.userHexCID="UserHexCID",Sr.acsResourceId="AcsResourceId",Sr.endpointId="endpoint_id",Sr.mediaLegId="media_leg_id",Sr.webMediaConfigIds="web_media_config_ids",Sr.tsCallingVersion="ts_calling_version",Sr.rpcSessionId="rpc_session_id";var vr=class{};vr.diagnostics="MediaDiagnostic",vr.qoeStats="QoE",vr.webrtcSession="webrtc_session",vr.webrtcSessionInitial="webrtc_session_initial",vr.realtimeTelemetry="realtimetelemetry",vr.webrtcMediaSession="webrtc_call_session",vr.mediaSession="pluginless_modality_session",vr.callSession="pluginless_call_session";var Cr=class{constructor(g){this.eventName=g,this.ended=!1,this.events=[]}setLocalUserId(g){this.localUserId=g}start(){this.ended||(this.startTime=Date.now())}end(g=0){this.ended||(this.ended=!0,this.resultCode=g)}asStatsRecord(g={}){if((0,ur.isEmpty)(this.events))return null;const f=(0,ur.uniqBy)(this.events,(g=>JSON.stringify(g))).map((g=>{const f={[g.type]:g.timestamp-this.startTime};return(0,ur.isEmpty)(g.data)||(f.data=g.data),f}));return{name:this.eventName,record:(0,ur.assign)({LocalUser:this.localUserId,ResultCode:String(this.resultCode),EventTimestampBag:JSON.stringify({eventStart:this.startTime,events:f})},g)}}add(g){!this.ended&&g.type&&((0,ur.isUndefined)(this.startTime)&&(this.startTime=Date.now()),(0,ur.isUndefined)(g.timestamp)&&(g.timestamp=Date.now()),this.events.push(g))}},yr=class _CallStats extends Cr{constructor(){super(vr.callSession)}callStateChanged(g){super.add({type:gr[0],data:_CallStats.callStateToString[g]||g})}event(g){super.add({type:gr[g]})}};yr.callStateToString={0:"None",1:"Notified",2:"Connecting",3:"Connected",4:"LocalHold",5:"RemoteHold",6:"Disconnecting",7:"Disconnected",8:"Observing",10:"Lobby"};var Er=yr,_r=class _MediaModalityStats extends Cr{constructor(g,f){super(vr.mediaSession),this.mediaType=g,this.mediaDirection=f,this.streamDirection=_MediaModalityStats.mediaDirectionToStream[this.mediaDirection]}addEvent(g,f){super.add({type:g,data:f})}lifecycle(g){this.addEvent(pr[g])}streamStateChanged(g,f=this.streamDirection){const S=pr[2];this.addEvent(S,{state:_MediaModalityStats.streamStateToString[g],direction:_MediaModalityStats.streamDirectionToString[f]})}negotiationStateChanged(g,f,S=this.streamDirection){const v=pr[3];this.addEvent(v,{state:_MediaModalityStats.negotiationStateToString[g],reason:f})}asStatsRecord(g={}){return super.asStatsRecord((0,ur.assign)({MediaType:_MediaModalityStats.mediaTypeToString[this.mediaType],Role:_MediaModalityStats.mediaDirectionToRole[this.mediaDirection]},g))}};_r.negotiationStateToString={started:"NegotiationStarted",rejected:"NegotiationRejected",completed:"NegotiationCompleted"},_r.streamStateToString={created:"StreamCreated",started:"StreamStarted",active:"StreamActive",inactive:"StreamInactive",stopped:"StreamStopped",removed:"StreamRemoved",failed:"StreamFailed",cancelled:"StreamCancelled"},_r.streamDirectionToString={send:"Send",receive:"Receive"},_r.mediaTypeToString={0:"Audio",1:"Video",2:"ScreenShare",3:"Data"},_r.mediaDirectionToRole={1:"Receiver",2:"Sender",4:"Bidirectional"},_r.mediaDirectionToStream={1:"receive",2:"send"};var Tr=_r,Ir=class extends Tr{constructor(){super(0,4)}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}},br=class extends Tr{constructor(g){super(g,2),this.mediaType=g}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}event(g){super.addEvent(mr[g])}},Ar=class extends Tr{constructor(g,f){super(g,1),this.mediaType=g,this.remoteParticipantId=f,this.rendererCounter=0}newRendererId(){return this.rendererCounter+=1,String(this.rendererCounter)}event(g,f,S){super.addEvent(fr[g],(0,ur.isUndefined)(S)?{rendererId:f}:{rendererId:f,sourceId:S})}asStatsRecord(){return super.asStatsRecord({TargetUser:this.remoteParticipantId})}},Pr=class{constructor(){this.allStats=[],this.ended=!1}setLocalUserId(g){this.localUserId=g}get call(){return this.callStats||this.startCall()}get audio(){return this.audioStats||this.newSession(0)}get video(){return this.videoStats||this.newSession(1)}get screenShare(){return this.sharingStats||this.newSession(2)}renderer(g,f){let S=this.renderingStats[f];return S||(S=this.renderingStats[f]=this.receive(g,f)),S}startCall(){return this.callStats?this.callStats:(this.callStats=new Er,this.callStats.start(),this.addStats(this.callStats))}endCall(g=0){this.ended=!0,this.call.end(g),this.allStats.forEach((g=>g.end())),this.cleanUp()}cleanUp(){this.audioStats&&(this.audioStats.stop(),this.audioStats=null),this.videoStats&&(this.videoStats.stop(),this.videoStats=null),this.sharingStats&&(this.sharingStats.stop(),this.sharingStats=null)}newSession(g){let f;switch(g){case 0:f=this.audioStats=new Ir;break;case 1:f=this.videoStats=new br(g);break;case 2:f=this.sharingStats=new br(g)}return this.addStats(f)}receive(g,f){const S=new Ar(g,f);return S.start(),this.addStats(S)}buildStatsRecords(){return this.allStats.map((g=>g.asStatsRecord())).filter((g=>!!g))}addStats(g){return this.ended||(this.allStats.push(g),g.setLocalUserId(this.localUserId)),g}},Rr=class _CallTelemetryBuilder{constructor(){this.startTime=Date.now(),this.localStats=new Pr,this.tsCallingVersion=getTsCallingVersion()}setRpcSessionId(g){this.rpcSessionId=g}setCallId(g){this.callId=g}setTenantId(g){this.tenantId=g}setUserHexCID(g){this.userHexCID=g}setParticipantId(g){this.participantId=g}setDisplayName(g){this.displayName=g}setEndpointId(g){this.endpointId=g}setMediaLegId(g){this.mediaLegId=g}setMediaStats(g){this.mediaStats=g}setAcsResourceId(g){this.acsResourceId=g}appendDataChannelInfo(g){this.mediaStats?.data&&g&&(this.mediaStats.data.DataHandlers=g)}appendSharingControlInfo(g){this.mediaStats?.data&&(this.mediaStats.data.SharingControlEnabled=g?"true":"false")}appendMediaControlPlaneInfo(g){this.mediaStats?.data&&g&&(this.mediaStats.data.MediaControlPlane=g)}appendTerminationInfo(g,f){this.mediaStats?.data&&(this.mediaStats.data.TerminatedReason=`${g}`,this.mediaStats.data.TerminatedState=`${f}`)}appendPictureInPictureInfo(g){this.mediaStats?.data&&g&&(this.mediaStats.data.PictureInPicture=g)}appendCallDeviceManagerInfo(g){this.mediaStats?.data&&g&&(this.mediaStats.data.CallDeviceManager=g)}async buildVDItelemetryReport(g){const{transport:f,rpc:S,rpcRemote:v,transportRemote:C}=await g.getStats(this.startTime);return{CallId:this.callId,ParticipantId:this.participantId,Transport:JSON.stringify(f),Rpc:JSON.stringify(S),Rpc_Remote:JSON.stringify(v),Transport_Remote:JSON.stringify(C)}}buildFromMediaStats(){return"WebRtcMediaStats"===this.mediaStats?.type?[this.buildEvent(this.mediaStats.data,vr.webrtcSession)]:[]}buildShortCallEvent(g){const f={};return f[Sr.correlationId]=this.callId||"",f[Sr.participantId]=this.participantId||"",f[Sr.displayName]=new Ue(this.displayName||"",1),f[Sr.tenantId]=this.tenantId||"",f[Sr.tsCallingVersion]=this.tsCallingVersion||"",f[Sr.rpcSessionId]=this.rpcSessionId||"",f.metrics_TerminationReason_code=new Ue(g.data.metrics.TerminationReason_code,0),f.metrics_TerminationReason_subCode=new Ue(g.data.metrics.TerminationReason_subCode,0),f.metrics_eventType=new Ue(g.eventType,0),[{eventName:vr.webrtcMediaSession,props:this.buildProps(g.data,null,f)}]}buildMediaTelemetry(){if(!this.mediaStats)return;const g=this.buildEvent(this.mediaStats.data,null).props,f={};return Object.keys(g).forEach((S=>{void 0===g[S].piiKind?f[S]=g[S]:f[S]=g[S].value})),f}buildMidCallTelemetry(g){if(!this.mediaStats)return[];const f=this.buildEvent(this.mediaStats.data,vr.webrtcSession),S=f.props,v=g.reduce(((g,f)=>(S[f]&&(g[f]=S[f]),g)),{});return[{eventName:f.eventName,props:v}]}buildFromCallSetupStats(g){return"WebRtcMediaStats"===this.mediaStats?.type?(this.mediaStats.data.trouterUrl=g,[this.buildEvent(this.mediaStats.data,vr.webrtcSessionInitial)]):[]}buildFromLocalStats(){return this.localStats.buildStatsRecords().map((g=>this.buildEvent(g.record,g.name)))}buildEvent(g,f){const S={};return S[Sr.agentEnvironmentId]=_CallTelemetryBuilder.agentEnvironmentId,S[Sr.correlationId]=this.callId||"",S[Sr.tenantId]=this.tenantId||"",S[Sr.userHexCID]=this.userHexCID||"",S[Sr.participantId]=this.participantId||"",S[Sr.displayName]=new Ue(this.displayName||"",1),S[Sr.endpointId]=this.endpointId||"",S[Sr.mediaLegId]=this.mediaLegId||"",S[Sr.webMediaConfigIds]=this.webMediaConfigIds||"",S[Sr.tsCallingVersion]=this.tsCallingVersion||"",S[Sr.acsResourceId]=this.acsResourceId||"",S[Sr.rpcSessionId]=this.rpcSessionId||"",{eventName:f,props:this.buildProps(g,null,S)}}normalizeKey(g){return g.replace(/[^a-zA-Z0-9._]/g,"_")}buildProps(g,f,S){return Object.keys(g).forEach((v=>{const C=this.normalizeKey(v),_=f?`${f}_${C}`:C,T=g[v];if((0,ur.isString)(T))S[_]=this.getPiiAwareValue(v,T);else if((0,ur.isArray)(T)){if(T.length>0){const g=T,f=g.map((g=>g.value)).toString();S[_]=new Ue(f,g[0].type)}}else if((0,ur.isObject)(T))if(T.__VALUE__){const g=T;(0,ur.isBoolean)(g.value)&&(g.value=g.value?"true":"false"),S[_]=new Ue(g.value,g.type)}else this.buildProps(T,_,S)})),S}getPiiAwareValue(g,f){return _CallTelemetryBuilder.piiProps.hasOwnProperty(g)?new Ue(f,_CallTelemetryBuilder.piiProps[g]):f}build(){return(0,ur.flatten)([this.buildFromMediaStats(),this.buildFromLocalStats()])}};Rr.agentEnvironmentId=generateGuid(),Rr.piiProps={IPAddr:13,MACAddr:13,IPAddress:13,OpaqueData:0,LocalSite:13,RemoteSite:13,BaseAddress:13,LocalAddress:13,RemoteAddress:13,NetworkName:12,LocalUser:10,TargetUser:10,[Sr.displayName]:1};var Mr=Rr,wr=M;function convertReason(g){return g?getTerminationCode(g.code,g.subCode):0}function convertSignalingEndpointDetails(g,f){const S={clientVersion:g.clientVersion,participantId:g.participantId,endpointId:g.endpointId,endpointType:g.endpointType,endpointMetadata:g.endpointMetadata,originalId:g.originalId,capabilities:g.capabilities,clientEndpointCapabilities:g.clientEndpointCapabilities,mappedTo:g.mappedTo,meetingGroupDetails:g.meetingGroupDetails,endpointMeetingRoles:g.endpointMeetingRoles};return g.mediaStreams&&(S.mediaStreams=g.mediaStreams),g.appliedInteractivityLevel&&(S.appliedInteractivityLevel=g.appliedInteractivityLevel),g.deviceType&&(S.deviceType=g.deviceType),g.streamInformation&&32&f&&(S.streamInformation=g.streamInformation),g.propertyBag&&(S.propertyBag=g.propertyBag),g.negotiationTag&&(S.negotiationTag=g.negotiationTag),S}function getTerminationCode(g,f=null){if(g===Fi.Success)switch(f){case xi.RemovedFromConversation:case xi.RemovedFromCall:return 44;case xi.DeniedInLobby:return 55;case xi.TimedOutInLobby:return 56;default:return 1}if(null!==f&&f>=2e5&&f<=299999){const g=f-2e5;return Vi[g]?Vi[g]:0}return null!==f&&f>=4e5&&f<=499999?Bi[g]?Bi[g]:43:g===Fi.Forbidden?f===xi.UserBlocked?64:f===xi.PolicyRestriction?62:f===xi.AnonymousJoinDisabledByPolicy?66:f===xi.NoLobbyForBroadcastJoin?67:f===xi.NotAllowedDueToInformationBarrier?68:f===xi.TeamParkPolicyDisabled?70:f===xi.B2bJoinDisabledByPolicy?71:(Fi.Success,8):g===Fi.PreconditionFailed&&f===xi.InsufficientCapabilities?63:g===Fi.ServiceUnavailable?f===xi.BroadcastLimitReached?69:48:g===Fi.InternalServerError?7:g===Fi.ConfParticipantCountLimitReached?f===xi.MaxLobbyParticipantLimitReached?73:59:Ui[g]?Ui[g]:g}function getCSAEndCode(g){if(1===g)return Fi.Success;const f=Object.keys(Ui).filter((f=>Ui[f]===g));if(f.length>=1)for(const S of f){const f=parseInt(S);if(f&&Ui[f]===g)return f}return Fi.UnknownError}function getMediaState(g,f){if(void 0!==f&&3!==f&&1!==f)return{mediaType:g,isDisabled:0===f,label:getMediaLabel(g)}}function getCallStartOptions(g){if(g.sendMediaModalities)return g;const f={mediaStates:[]};let S=getMediaState(0,g.audioDirection?g.audioDirection:4);return S&&f.mediaStates.push(S),S=getMediaState(1,g.withVideo?4:g.videoDirection),S&&f.mediaStates.push(S),S=getMediaState(2,g.screenshareDirection?g.screenshareDirection:1),S&&f.mediaStates.push(S),g.sendMediaModalities=f,g}function convertRedirectOptions(g){const f=convertRedirectionTargetIdType(g.type),S=convertRedirectionEndpointType(g.endpointType);return{type:f,id:g.id,endpointType:S}}function convertRedirectionTargetIdType(g){if("mri"===g)return"mri";throw"Unknown RedirectionTargetIdType"}function convertRedirectionEndpointType(g){switch(g){case"voicemail":return"voicemail";case"default":return"default";default:throw"Unknown RedirectionEndpointType"}}var Or=class{constructor(g){this.mediaStateConfiguration=g}isDisabled(g){if(this.mediaStateConfiguration?.mediaStates){const f=this.mediaStateConfiguration.mediaStates.find((f=>f.mediaType===g));return!!f&&!!f.isDisabled}return!1}isInactiveOrDisabled(g){if(this.mediaStateConfiguration?.mediaStates){const f=this.mediaStateConfiguration.mediaStates.find((f=>f.mediaType===g));return!f||!!f.isDisabled}return!1}isSending(g){if(this.mediaStateConfiguration?.mediaStates){return!!this.mediaStateConfiguration.mediaStates.find((f=>f.mediaType===g&&!f.isDisabled))}return!1}disableModality(g){this.setModality(g,!0)}enableModality(g){this.setModality(g,!1)}removeModality(g){this.mediaStateConfiguration?.mediaStates&&(0,wr.remove)(this.mediaStateConfiguration.mediaStates,(f=>f.mediaType===g))}setCallAcceptOptions(g){const f=this.isDisabled(1),S=this.isDisabled(2),v=this.isSending(3);if(g.sendMediaModalities)this.mediaStateConfiguration=g.sendMediaModalities;else{void 0===g.answerMediaType&&(g.answerMediaType=g.withVideo?1:0);const f={mediaStates:[]};switch(g.answerMediaType){case 0:f.mediaStates.push(getMediaState(0,4));break;case 1:f.mediaStates.push(getMediaState(0,4)),f.mediaStates.push(getMediaState(1,4));break;case 2:f.mediaStates.push(getMediaState(1,0))}this.mediaStateConfiguration=f}f&&this.setModality(1,!0),S&&this.setModality(2,!0),v&&this.setModality(3,!1),g.sendMediaModalities=this.mediaStateConfiguration}setModality(g,f){if(this.mediaStateConfiguration?.mediaStates){const S=this.mediaStateConfiguration.mediaStates.find((f=>f.mediaType===g));S?S.isDisabled=f:this.mediaStateConfiguration.mediaStates.push({mediaType:g,isDisabled:f,label:getMediaLabel(g)})}}};function hasValue2(g){return g||!1===g||""===g||0===g}function scrubCallOptions(g){const f={};hasValue2(g.callStartTime)&&(f.callStartTime=g.callStartTime),hasValue2(g.callVoicemailStartOptions)&&(f.callVoicemailStartOptions=g.callVoicemailStartOptions),hasValue2(g.invitationType)&&(f.invitationType=g.invitationType),hasValue2(g.meetingPreferences)&&(f.meetingPreferences=g.meetingPreferences),hasValue2(g.parkContext)&&(f.parkContext=g.parkContext),hasValue2(g.pickupCode)&&(f.pickupCode=g.pickupCode),hasValue2(g.participantsToNudge)&&(f.participantsToNudgeSize=g.participantsToNudge.length);const S=g.callStartOptions;if(S){const g={};hasValue2(S.additionalEndpointProperties)&&(g.additionalEndpointProperties=S.additionalEndpointProperties),hasValue2(S.clientEndpointCapabilities)&&(g.clientEndpointCapabilities=S.clientEndpointCapabilities),hasValue2(S.connectionType)&&(g.connectionType=S.connectionType),hasValue2(S.invitationDataJson)&&(g.invitationDataJson=S.invitationDataJson),hasValue2(S.isCast)&&(g.isCast=S.isCast),hasValue2(S.isHuddleGroupCall)&&(g.isHuddleGroupCall=S.isHuddleGroupCall),hasValue2(S.label)&&(g.label=S.label),hasValue2(S.maxVideoChannels)&&(g.maxVideoChannels=S.maxVideoChannels),hasValue2(S.maxVbssChannels)&&(g.maxVbssChannels=S.maxVbssChannels),hasValue2(S.mediaConfiguration)&&(g.mediaConfiguration=S.mediaConfiguration),hasValue2(S.muteFlags)&&(g.muteFlags=S.muteFlags),hasValue2(S.muted)&&(g.muted=S.muted),hasValue2(S.negotiationTag)&&(g.negotiationTag=S.negotiationTag),hasValue2(S.preheatFlags)&&(g.preheatFlags=S.preheatFlags),hasValue2(S.ringOthers)&&(g.ringOthers=S.ringOthers),hasValue2(S.routingFlags)&&(g.routingFlags=S.routingFlags),hasValue2(S.scenario)&&(g.scenario=S.scenario),hasValue2(S.screenshareDirection)&&(g.screenshareDirection=S.screenshareDirection),hasValue2(S.sendMediaModalities)&&(g.sendMediaModalities=S.sendMediaModalities),hasValue2(S.sharedLineCallInvitationContentJson)&&(g.sharedLineCallInvitationContentJson=S.sharedLineCallInvitationContentJson),hasValue2(S.targetApplicationType)&&(g.targetApplicationType=S.targetApplicationType),hasValue2(S.captchaContentJson)&&(g.captchaContentJson=S.captchaContentJson),hasValue2(S.callQueueContext)&&(g.callQueueContext=S.callQueueContext),hasValue2(S.clientEndpointDebugContent)&&(g.clientEndpointDebugContentSize=S.clientEndpointDebugContent.length),hasValue2(S.alternateId)&&(g.alternateId=scrubMriOrOmit(S.alternateId)),hasValue2(S.callKey)&&(g.callKeySize=S.callKey.length),hasValue2(S.encryptedKey)&&(g.encryptedKeySize=S.encryptedKey.length),f.callStartOptions=g}return f}function getAgentMediaType(g){switch(g){case 0:return"Audio";case 1:return"Video";case 2:return"ScreenShare"}throw new Error("MediaType required")}function getSkypeMediaType(g){switch(g){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2}throw new Error("MediaType required")}function mapMonitorActionType(g){switch(g){case 0:return"Monitor";case 1:return"Whisper";case 2:return"Barge";case 3:return"Takeover";default:return}}var Dr={NEGOTIATION_COMPLETED:"NegotiationCompleted",INITIAL:{OFFER_GENERATION_STARTED:"InitialOfferGenerationStarted",OFFER_GENERATION_ENDED:"InitialOfferGenerationEnded",ANSWER_PROCESSING_STARTED:"InitialAnswerProcessingStarted",ANSWER_PROCESSING_ENDED:"InitialAnswerProcessingEnded",OFFER_PROCESSING_STARTED:"InitialOfferProcessingStarted",OFFER_PROCESSING_ENDED:"InitialOfferProcessingEnded",ANSWER_GENERATION_STARTED:"InitialAnswerGenerationStarted",ANSWER_GENERATION_ENDED:"InitialAnswerGenerationEnded"},RENEGOTIATION:{OFFER_GENERATION_STARTED:"RenegotiationOfferGenerationStarted",OFFER_GENERATION_ENDED:"RenegotiationOfferGenerationEnded",ANSWER_PROCESSING_STARTED:"RenegotiationAnswerProcessingStarted",ANSWER_PROCESSING_ENDED:"RenegotiationAnswerProcessingEnded",OFFER_PROCESSING_STARTED:"RenegotiationOfferProcessingStarted",OFFER_PROCESSING_ENDED:"RenegotiationOfferProcessingEnded",ANSWER_GENERATION_STARTED:"RenegotiationAnswerGenerationStarted",ANSWER_GENERATION_ENDED:"RenegotiationAnswerGenerationEnded"}},Nr=class{constructor(g,f){this.mediaSession=g,this.signalingSession=f,this.operationNames=Dr.INITIAL,this.configureModalitiesAsync=this.mediaSession.configureModalitiesAsync.bind(this.mediaSession),this.getAllowedModalities=this.mediaSession.getAllowedModalities.bind(this.mediaSession),this.rejectNegotiationAsync=this.mediaSession.rejectNegotiationAsync.bind(this.mediaSession),this.createRemoteRenderer=this.mediaSession.createRemoteRenderer.bind(this.mediaSession),this.getStatsAsync=this.mediaSession.getStatsAsync.bind(this.mediaSession),this.getLastKnownStats=this.mediaSession.getLastKnownStats.bind(this.mediaSession),this.getCallTechnicalInfo=this.mediaSession.getCallTechnicalInfo.bind(this.mediaSession),this.muteHold=this.mediaSession.muteHold.bind(this.mediaSession),this.muteInputAsync=this.mediaSession.muteInputAsync.bind(this.mediaSession),this.unmuteInputAsync=this.mediaSession.unmuteInputAsync.bind(this.mediaSession),this.muteOutputAsync=this.mediaSession.muteOutputAsync.bind(this.mediaSession),this.unmuteOutputAsync=this.mediaSession.unmuteOutputAsync.bind(this.mediaSession),this.getSpeakerVolume=this.mediaSession.getSpeakerVolume.bind(this.mediaSession),this.setSpeakerVolume=this.mediaSession.setSpeakerVolume.bind(this.mediaSession),this.terminate=this.mediaSession.terminate.bind(this.mediaSession),this.createAudioElement=this.mediaSession.createAudioElement.bind(this.mediaSession),this.getSessionConfig=this.mediaSession.getSessionConfig.bind(this.mediaSession),this.getDiagnostics=this.mediaSession.getDiagnostics.bind(this.mediaSession),this.getIncomingRawAudioStream=this.mediaSession.getIncomingRawAudioStream.bind(this.mediaSession),this.getUnmixedAudioProvider=this.mediaSession.getUnmixedAudioProvider.bind(this.mediaSession),this.useNullAudioStreamClient=this.mediaSession.useNullAudioStreamClient.bind(this.mediaSession),this.getSubscriptionManager=this.mediaSession.getSubscriptionManager.bind(this.mediaSession),this.configureSpatialAudio=this.mediaSession.configureSpatialAudio.bind(this.mediaSession),this.setParticipantSpatialAudioPositions=this.mediaSession.setParticipantSpatialAudioPositions.bind(this.mediaSession),this.setCallConstraints=this.mediaSession.setCallConstraints.bind(this.mediaSession),this.startMediaDescriptionsUpdateAsync=this.mediaSession.startMediaDescriptionsUpdateAsync.bind(this.mediaSession),this.completeMediaDescriptionsUpdateAsync=this.mediaSession.completeMediaDescriptionsUpdateAsync.bind(this.mediaSession),this.rejectMediaDescriptionsUpdateAsync=this.mediaSession.rejectMediaDescriptionsUpdateAsync.bind(this.mediaSession),this.registerRemoteQualityStateChangedEvent=this.mediaSession.registerRemoteQualityStateChangedEvent.bind(this.mediaSession),this.getMediaControlPlaneInstance=this.mediaSession.getMediaControlPlaneInstance.bind(this.mediaSession)}enableTeamsRealTimeTelemetry(){this.mediaSession.enableTeamsRealTimeTelemetry()}getMediaStatsReport(){return this.mediaSession.getMediaStatsReport()}processOfferAsync(g,f){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_STARTED),this.mediaSession.processOfferAsync(g,f).then((g=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_ENDED),g)))}createAnswerAsync(g,f){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_STARTED),this.mediaSession.createAnswerAsync(g,f).then((f=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_ENDED),g||(this.operationNames=Dr.RENEGOTIATION),f)))}createOfferAsync(g,f){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_STARTED),this.mediaSession.createOfferAsync(g,f).then((g=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_ENDED),g)))}processAnswerAsync(g,f,S,v=!1){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_STARTED),this.mediaSession.processAnswerAsync(g,f,S,v).then((()=>{this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_ENDED),this.operationNames=Dr.RENEGOTIATION}))}completeNegotiationAsync(g){return this.mediaSession.completeNegotiationAsync(g).then((g=>(this.signalingSession.setOfferAnswerGenerationTimestamps(Dr.NEGOTIATION_COMPLETED),g)))}sendDtmf(g){return this.mediaSession.sendDtmf?this.mediaSession.sendDtmf(g):Promise.reject("Not Implemented")}reconnectAsync(g,f=!1,S){return this.mediaSession.reconnectAsync(g,f,S)}completeEscalationAsync(g){return this.mediaSession.completeEscalationAsync(g)}rejectEscalationAsync(g,f){return this.mediaSession.rejectEscalationAsync(g,f)}getAcceptedTypes(){return this.mediaSession.getAcceptedTypes()}getLocalMediaTrackId(g){return this.mediaSession.getLocalMediaTrackId?this.mediaSession.getLocalMediaTrackId(g):null}processNotification(g,f){this.mediaSession.processNotification(g,f)}};function handleServerMutedVersion(g,f,S){if(void 0===f?.serverMuteVersion||void 0===S?.serverMuteVersion||S.serverMuteVersion>=f.serverMuteVersion)return;const v=S&&S.mediaStreams,C=v&&v.filter((g=>"audio"===g.type||"audio-teleconferencing"===g.type)),_=f&&f.mediaStreams,T=_&&_.filter((g=>"audio"===g.type||"audio-teleconferencing"===g.type));C&&C.length&&(S.serverMuteVersion=f.serverMuteVersion,C[0].serverMuted=T[0].serverMuted,g.info(`handleServerMutedVersion: patching server muted state in audio streams updated:${JSON.stringify(C[0])} as we encountered stale muteServerVersion. Updated to ${f.serverMuteVersion}`))}function handleMuteUnmuteParticipantInfo(g,f,S,v){if("success"!==S.reason||void 0===f||S.serverMuteVersion<=f.serverMuteVersion)return g.info(`handleMuteUnmuteParticipantInfo: ignoring updating since we encountered invalid state: ${S.reason} serverMuteVersion: ${S.serverMuteVersion}`),!1;const C=f&&f.mediaStreams,_=C&&C.filter((g=>"audio"===g.type||"audio-teleconferencing"===g.type));return!!_&&(_[0].serverMuted=v,f.serverMuteVersion=S.serverMuteVersion,g.info(`handleMuteUnmuteParticipantInfo: updating since we encountered valid state serverMuteVersion: ${S.serverMuteVersion} to: ${v} streams: ${_[0].sourceId}`),!0)}var kr=R;function scrub(g,f,S,v){const C=JSON.stringify(g),_=JSON.parse(C);return _&&(scrubOneTypeOfParams(g,_,f,kr.pii.Omit),scrubOneTypeOfParams(g,_,S,kr.pii.Mri),scrubOneTypeOfParams(g,_,v,kr.pii.UserName)),JSON.stringify(_)}function scrubOneTypeOfParams(g,f,S,v){S?.forEach((S=>{g[S]&&(f[S]=v(g[S]))}))}function scrubSignalingParticipant(g){return`id=${kr.pii.Mri(g.id)}, participantId=${g.participantId}`}function scrubITransferContext(g){const f=[],S=["transferorMri","targetMri"];return scrub(scrubObjectFields(g),f,S)}var Lr=M,Fr=S.setImmediate?g=>{S.setImmediate(g)}:g=>{(0,Lr.defer)(g)},xr=class _DeferHandler{constructor(){this.deferredOperations=new Map,this.deferredOperationsNames=[],this.isRunning=!1}setLogger(g){this._logger=g.createChild("[DeferHandler]")}setDeferToQueueMicrotask(g){g&&S.queueMicrotask?_DeferHandler.defer=g=>S.queueMicrotask(g):_DeferHandler.defer=Fr}createDeferRunner(g){const f={};return S=>this.runDeferred(f,S,g)}runDeferredWithoutDedup(g,f){const S={};this.runDeferred(S,g,f)}runDeferred(g,f,S){this.deferredOperations.has(g)||(this.deferredOperations.set(g,f),S&&this.deferredOperationsNames.push(" "+S),this.isRunning||(this.isRunning=!0,this._startDeferalTime=Date.now(),this.causeId=generateCauseId(),this._logger?.info(`[${this.causeId}]Deferring operations`),_DeferHandler.defer((()=>{this._timeToRun=Date.now()-this._startDeferalTime,this.deferredOperations.forEach((g=>{_DeferHandler.runWithTryCatch(g)})),this.deferredOperations.clear(),this.isRunning=!1,this._logger?.info(`[${this.causeId}]Deferred operations ran after ${this._timeToRun}ms | Completed after ${Date.now()-this._startDeferalTime}ms | Operations:${this.deferredOperationsNames}`),this.deferredOperationsNames=[]}))))}static runWithTryCatch(g){try{g&&g()}catch(g){}}};xr.defer=Fr;var Ur=xr,Vr=class{};Vr.instance=new Ur;var Br=M,Hr={send:"sendonly",receive:"recvonly",sendReceive:"sendrecv"},$r={audio:"audio",video:"video",sharing:"applicationsharing-video",audioteleconference:"audio-teleconferencing",xsharing:"xapplicationsharing-video"},jr=class extends Ke{constructor(g,f,S){super(f),this.mediaSession=g,this.isAvailable=!1,this.mediaSessionInitPromise=new dt,this.currentIsStreaming=!1,g&&this.mediaSessionInitPromise.resolve(),this.id=S,this.logger=f.createChild(`Stream[${this.id}]`)}set isStreaming(g){this.currentIsStreaming=g,this.logger.info(`isStreaming has changed to ${this.currentIsStreaming}`),this.raiseChanged()}get isStreaming(){return this.currentIsStreaming}update({sourceId:g=null,direction:f=Hr.receive,participantId:S=null,endpointId:v=null}={},C,_){this.logger.info(`[${C}][update before]  sourceId=${g}, direction=${f}, isAvailable=${this.isAvailable}, participantId=${S}, endpointId=${truncate(v,8)}, ${this.negotiationTag?`, negotiationTag=${this.negotiationTag}`:""}`),this.id=g;const T=f===Hr.sendReceive||f===Hr.send;this.isAvailable!==T&&(this.negotiationTag=_?.get(v)),this.isAvailable=T,this.mediaSession?.getSessionConfig().config.streamAvailabilityConsiderModalities&&this.getIsModalityDisabled()&&(this.logger.info(`Disabling current modality, disabled: ${JSON.stringify(this.mediaSession?.getDisabledModalities?.()||"")}`),this.isAvailable=!1),this.participantId=S,this.endpointId=v,this.logger.info(`[${C}][update after]  sourceId=${g}, direction=${f}, isAvailable=${this.isAvailable}, participantId=${S}, endpointId=${truncate(v,8)}, ${this.negotiationTag?`, negotiationTag=${this.negotiationTag}`:""}`),this.raiseChanged()}setMediaSession(g,f){const S=g?.getAllowedModalities?.()||{};this.logger.info(`[${f}][setMediaSession] ${JSON.stringify(S)}`),this.mediaSession=g,g?this.mediaSessionInitPromise.resolve():this.mediaSessionInitPromise.reject(new Error("MediaSession is null"))}isActive(){return this.isAvailable&&this.isStreaming}getIsModalityDisabled(){return!1}},Gr=class extends jr{},qr=M,Wr=class extends jr{constructor(g,f,S,v,C,_){super(void 0,g,f),this.configProvider=S,this.streamOptions=v,this.telemetryLogger=C,this.callInfo=_,this.type=2,this.finalTelemetrySent=!1,this.player=new Dt(g.createChild("UmsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger),this.isAvailable=!0}getStreamOptions(){return this.streamOptions}getDiagnosticData(){return JSON.stringify({id:this.id,type:this.type,rank:this.rank,isAvailable:this.isAvailable,isStreaming:this.isStreaming})}getStats(){const g=this.player.getSnapshotTelemetryReport(),f={isAvailable:this.isAvailable,isStreaming:this.isStreaming,...g};return(0,qr.isEqual)(this.lastStreamStats,f)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=f),{id:this.id,type:this.type,timestampUpdated:this.streamStatsUpdatedTimestamp,rank:this.rank,...this.lastStreamStats}}stop(){return Promise.resolve(void 0)}async start(g){if(this.logger.info("[start]: Starting UMS stream"),!this.renderer){await this.player.configure(this.streamOptions);if(!(await this.player.loadPlayer(g)).setupSucceeded)return this.player.stop(),this.logger.error("[start]: Failed to load UMS player"),Promise.reject("Failed to load UMS player");this.renderer=this.player.getRenderer()}return this.isStreaming=!0,this.renderer}sendSnapshotTelemetry(){const g=this.player.getSnapshotTelemetryReport();this.logger.debug(`[sendSnapshotTelemetry] sending snapshot telemetry report: ${JSON.stringify(g)}`);const f={...this.callInfo,...g};this.telemetryLogger.sendEvent({eventName:"live_events",props:f})}sendTelemetry(g){if(this.finalTelemetrySent)return;g&&(this.finalTelemetrySent=!0);const f=this.player.getTelemetryReport();this.logger.debug(`[sendTelemetry] sending telemetry report: ${JSON.stringify(f)}`);const S={...this.callInfo,...f};this.telemetryLogger.sendEvent({eventName:"live_events",props:S})}};function toMediaAgentScalingMode(g){switch(g){case 1:return"crop";case 0:return"stretch";default:return"fit"}}var zr=class extends Ke{constructor(){super(...arguments),this.isRendering=!1,this.frameType=-1}get rendererType(){return 0}captureFrame(){if(this.renderer.captureFrame)return this.renderer.captureFrame();throw new Error("Not implemented yet")}async getStats(){if(this.renderer.getStats)return this.renderer.getStats();throw new Error("Renderer does not support stats")}async setScalingMode(g){this.renderer.setScalingMode(toMediaAgentScalingMode(g))}async cameraAutoControl(g){throw new Error("Not implemented")}async getCameraManualControlStates(g){throw new Error("Not implemented")}async setCameraManualControlStates(g){throw new Error("Not implemented")}async enumerateCameraManualControls(){throw new Error("Not implemented")}async isCameraAdvancedControlCapable(){throw new Error("Not implemented")}onVideoSizeChanged(g,f){this.streamSize={width:g,height:f},this.event("videoSizeChanged").raise(g,f),this.raiseChanged()}},Kr=class extends zr{constructor(g,f,S){super(),this.renderer=f.createPreviewRenderer(g,S),this.renderer.on("onVideoSizeChanged",((g,f)=>this.onVideoSizeChanged(g,f)))}onVideoSizeChanged(g,f){this.isRendering=g>0&&f>0,super.onVideoSizeChanged(g,f)}setVideoMirroring(g){this.renderer.setVideoMirroring(g)}startVideoAsync(){return this.renderer.startVideoAsync()}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer=null)}},Jr=class extends zr{constructor(g,f,S,v,C){super(),this.logger=g,this.target=f,this.rendererStats=v,this.configProvider=C,this.subscriptionActive=!1,this.firstFrameRendered=!1,this.rendererId=v.newRendererId(),this.renderer=S.createRemoteRenderer(f),this.renderer.on("onVideoSizeChanged",((g,f)=>this.onVideoSizeChanged(g,f))),this.renderer.on("onVideoStateChanged",(g=>this.onVideoStateChanged(g))),this.renderer.on("onIsRenderingChanged",(g=>this.onIsRenderingChanged(g)))}toString(){return`rvr:${this.rendererId}`}onVideoStateChanged(g){this.rendererStats.streamStateChanged(g.stream)}onVideoSizeChanged(g,f){this.configProvider.config.videoIsRenderingCheck&&this.setIsRendering(g>0&&f>0),super.onVideoSizeChanged(g,f)}setIsRendering(g){this.isRendering!==g&&(this.isRendering=g,this.logger.info(`isRendering has changed to ${this.isRendering}`),this.rendererStats.event(this.isRendering?5:6,this.rendererId),this.isRendering&&!this.firstFrameRendered&&(this.firstFrameRendered=!0,this.event("firstFrameRendered").raise()))}onIsRenderingChanged(g){this.setIsRendering(g),this.raiseChanged()}subscribeVideoAsync(g){this.currentVideoStream=g,this.rendererStats.event(1,this.rendererId,g.id);const f=this.renderer.subscribeVideoAsync(g.id,1===g.type);return this.subscriptionActive=!0,f.then((()=>{this.rendererStats.event(2,this.rendererId,g.id),this.watchStream(g)})),f}watchStream(g){this.changeSub&&this.changeSub.dispose(),this.changeSub=g.changed((()=>{g.isAvailable?this.subscriptionActive||this.subscribeVideoAsync(g):(this.subscriptionActive=!1,this.rendererStats.event(3,this.rendererId),this.renderer.unsubscribeNow(),this.rendererStats.event(4,this.rendererId))}))}dispose(){this.renderer&&(this.subscriptionActive&&(this.rendererStats.event(3,this.rendererId),this.currentVideoStream&&!this.currentVideoStream.isAvailable&&this.renderer.unsubscribeNow()),this.renderer.dispose(),this.subscriptionActive&&this.rendererStats.event(4,this.rendererId),this.renderer=null,this.currentVideoStream=null),this.changeSub&&(this.changeSub.dispose(),this.changeSub=null)}},Yr=class extends Ke{constructor(g,f,S){super(S),this.getRawStream=g,this.disposeStream=f,this.logger=S,this.isClientDisposed=!1,this.clientId=uniqueId()}get isDisposed(){return this.isClientDisposed}notifyStreamChange(){this.logger.info(`clientId:${this.clientId} - Stream changed`),this.raiseChanged(),this.event("notifiedOnStreamChanged").raise(this.clientId)}async getMediaStream(){return this.checkDisposed(),this.logger.info(`clientId:${this.clientId} - Stream requested`),this.event("rawStreamRequested").raise(this.clientId),this.getRawStream()}dispose(){this.checkDisposed(),this.disposeStream?.(),this.isClientDisposed=!0,this.event("clientDisposed").raise(this.clientId),super.dispose(),this.logger.info(`clientId:${this.clientId} - Raw stream client disposed`)}checkDisposed(){if(this.isClientDisposed)throw new Error("Raw stream client is already disposed")}},Qr=class{constructor(g,f){this.stream=g,this.rawBaseClient=new Yr((async()=>this.stream),(()=>this.dispose()),f)}client(){return this.rawBaseClient}updateAndNotifyClient(g){this.rawBaseClient&&(this.stream=g,this.rawBaseClient.notifyStreamChange())}dispose(){this.rawBaseClient=null,this.stream=null}},Xr=class{constructor(g,f,S){this.videoStream=g,this.subscriptionManager=f,this.logger=S,this.subscriptionActive=!1,this.modality=0===g.type?qt.MODALITY.video:qt.MODALITY.sharing,this.createSubscription(),this.rawBaseClient=new Yr((async()=>this.subscriptionClient?.subscribedStream),(()=>this.unsubscribeVideo()),S),this.videoStream.changed((()=>{this.rawBaseClient?.isDisposed||(this.logger.info(`isAvailable: ${g.isAvailable}, subscriptionActive: ${this.subscriptionActive}`),g.isAvailable?this.subscriptionActive||this.createSubscription():(this.subscriptionActive=!1,this.unsubscribeVideo()))}))}client(){return this.rawBaseClient}createSubscription(){this.rawBaseClient?.isDisposed?this.logger.error("createSubscription skipped, raw stream client disposed: stream already exists"):(this.logger.info("createSubscription: Creating new subscription"),this.subscriptionClient=this.subscriptionManager.subscribeVideo(this.modality,this.videoStream.mediaSourceId),this.setClientSubscription(),this.subscriptionActive=!0)}unsubscribeVideo(){this.logger.info("unsubscribeVideo: Disposing subcription"),this.subscriptionClient?.unsubscribe(),this.subscriptionClient?.dispose(),this.subscriptionClient=null}setClientSubscription(){this.logger.info("setClientSubscription: setting onMediaStreamChanged callback"),this.subscriptionClient.setOnMediaStreamChangedHandler((()=>this.rawBaseClient?.notifyStreamChange()))}},Zr=class{constructor(g){this.logger=g,this.handlerMap=new Map}dispose(){this.logger.info("dispose"),this.handlerMap.forEach((g=>g.client().dispose())),this.handlerMap.clear()}handlerAdded(g){const f=g.client();f.on("clientDisposed",(()=>this.deleteRawStreamManagerById(f.clientId))),this.handlerMap.set(f.clientId,g)}deleteRawStreamManagerById(g){this.handlerMap.delete(g)}},es=class extends Zr{constructor(g){super(g)}streamChanged(g){this.handlerMap.forEach((f=>f.updateAndNotifyClient(g)))}createIRawStreamClient(g,f){const S=new Qr(g,this.logger);super.handlerAdded(S);const v=S.client();return this.logger.info(`[${f}] - clientId:${v.clientId}, client created`),v}updateHandlers(g){g.forEach(((g,f)=>{this.handlerMap.has(f)||this.handlerMap.set(f,g)}))}},ts=class extends Zr{constructor(g){super(g)}createIRawStreamClient(g,f,S){const v=new Xr(g,f,this.logger);super.handlerAdded(v);const C=v.client();return this.logger.info(`[${S}] - clientId:${C.clientId}, client created`),C}},is=M,ns=class extends jr{constructor(g,f,S,v){super(g,S,v),this.rendererStats=f,this.rawIncomingVideoStreamManager=new ts(this.logger.createChild(`rawVideoStream, [sourceId:${this.id}]`)),this.type=0}get mediaSourceId(){return this.id}getDiagnosticData(){return JSON.stringify({id:this.id,msi:this.mediaSourceId,rank:this.rank,type:this.type,isAvailable:this.isAvailable,isStreaming:this.isStreaming})}getStats(){const g={isAvailable:this.isAvailable,isStreaming:this.isStreaming};return(0,is.isEqual)(this.lastStreamStats,g)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=g),{id:this.id,type:this.type,timestampUpdated:this.streamStatsUpdatedTimestamp,msi:this.mediaSourceId,rank:this.rank,...this.lastStreamStats}}stop(){return this.mediaSessionInitPromise.reject(new Error("Video stream stopped")),Promise.resolve(void 0)}getRawStream(g=generateCauseId()){this.logger.info(`[${g}] - getRawStream called for incoming video stream`);return this.rawIncomingVideoStreamManager.createIRawStreamClient(this,this.mediaSession.getSubscriptionManager(),g)}start(g,f){return this.logger.info(`video start: target=${g}, options=${JSON.stringify(f)}`),this.mediaSessionInitPromise.promise.then((()=>new Jr(this.logger.createChild("RemoteVideoRenderer"),g,this.mediaSession,this.rendererStats,this.mediaSession?.getSessionConfig()))).then((g=>(f&&g.setScalingMode(f.scalingMode),this.logger.info(`subscribeVideoAsync: videoRenderer=${g}, id=${this.id}`),g.subscribeVideoAsync(this).catch((f=>{throw g.dispose(),f})).then((()=>(this.isStreaming=!0,g))))))}update(g,f,S){this.logger.info(`[${f}][update] stream=${JSON.stringify(g)}`);const v=this.isAvailable;super.update(g,f,S),this.isAvailable&&this.isAvailable!==v&&this.rendererStats.event(0)}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().video}},rs=class extends ns{constructor(g,f,S,v){super(g,f,S,v),this.type=1}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().sharing}},ss=1,as=2,os=3,ls=class _PluginlessCallStreamManager extends Ke{constructor(g,f,S,v){super(),this.participantId=g,this.mediaSession=f,this.localStats=S,this.audioSourceIds=[],this.streams={},this.lastUmsStreamId=1;const C=S.receive(1,g),_=S.receive(2,g);this.audio=new Gr(f,v,ss);const T=new ns(f,C,v,as),I=new rs(f,_,v,os),b=this.mediaSession?.getSessionConfig()?.config.participantStreamInitialSubscriptions;b&&(T.changed((()=>this.event("streamChanged").raise())),I.changed((()=>this.event("streamChanged").raise()))),this.streams[0]=[T],this.streams[1]=[I],this.streams[2]=[],this.logger=v.createChild("PluginlessCallStreamManager")}setMediaSession(g,f){this.logger.info(`[${f}][setMediaSession]`),this.mediaSession=g;[[this.audio],this.streams[0],this.streams[1]].forEach((S=>S.forEach((S=>S.setMediaSession(g,f)))))}updateStreams(g,f,S,v){this.logger.info(`[${f}][updateStreams]`);const filterAndSortStreams=f=>g.filter((g=>f.includes(g.type))).sort(_PluginlessCallStreamManager.compareStreams);let C=filterAndSortStreams([$r.audio]);0===C.length&&(C=filterAndSortStreams([$r.audioteleconference])),C.length>0&&(this.audioSourceIds=C.map((g=>g.sourceId)));const _=C[0];_&&this.audio.update(_,f),this.updateMediaStreams(filterAndSortStreams([$r.video]),0,f,S),v?this.updateMediaStreams(filterAndSortStreams([$r.sharing,$r.xsharing]),1,f,S):this.updateMediaStreams(filterAndSortStreams([$r.sharing]),1,f,S)}hasAudioSource(g){return this.audioSourceIds.some((f=>f===g))||this.audio.id===g}useUmsStream(g,f,S,v,C,_){this.logger.info(`[${_}][useUmsStream] Updating ums streams`);const T=this.getUmsInformation(g,v),I=this.streams[2],b=I.filter((g=>!T.some((f=>_PluginlessCallStreamManager.compareUmsStreams(g,f)))));b.forEach((g=>(0,Br.remove)(I,g))),b.length&&this.logger.info(`[${_}][useUmsStream] Removing ${b.length} ums streams`),T.forEach((g=>{let v=I.find((f=>_PluginlessCallStreamManager.compareUmsStreams(f,g)));v||(v=new Wr(this.logger.createChild("UmsStream"),this.lastUmsStreamId++,f,g,C,S),this.logger.info(`[${_}][useUmsStream] Adding ums stream with metadata: ${JSON.stringify(g)}`),I.push(v))}))}getUmsStreamMetadata(g,f){let S=null,v=null;if(S=g.find((function(g){return"MiddleLaneUltraLowLatency"===g.deliveryPipelineType&&f===g.isPrimary})),S){const g=S.urls;if(g&&g.length>0){S.identifier||this.logger.warn(`[getUmsStreamMetadata]: no ums stream identifier found, isPrimary: ${f}`);const C=S.decryptionKey?.id,_=S.decryptionKey?.value;C&&_||this.logger.warn(`[getUmsStreamMetadata]: no valid ums stream decryption key found, isPrimary: ${f}`);const T=S.deliveryPipelineType||void 0;v={url:g[0],streamDeliveryPipeline:T,decryptionKey:C&&_?{id:C,value:_}:null}}else this.logger.info(`[getUmsStreamMetadata]: no ums URLs found, isPrimary: ${f}`)}else this.logger.info(`[getUmsStreamMetadata]: no ums stream information found, isPrimary: ${f}`);return v}getUmsInformation(g,f){const S=[];let v=null,C=null;for(const f in g){const S=g[f].streams;if(S){if(v)this.logger.info(`[getUmsInformation]: primary ums stream already found, skipping finding primary stream for participant: ${f}`);else{const g=this.getUmsStreamMetadata(S,!0);g?v=g:this.logger.info(`[getUmsInformation]: no primary ums stream found for participant: ${f}`)}if(C)this.logger.info(`[getUmsInformation]: alternate ums stream already found, skipping finding alternate stream for participant: ${f}`);else{const g=this.getUmsStreamMetadata(S,!1);g?C=g:this.logger.info(`[getUmsInformation]: no alternate ums stream found for participant: ${f}`)}}else this.logger.warn(`[getUmsInformation]: no stream information found for participant: ${f}`)}return(v||C)&&S.push({stream:v,altStream:C,threadId:f}),S}static compareStreams(g,f){const S="sendonly"===g.direction||"sendrecv"===g.direction,v="sendonly"===f.direction||"sendrecv"===f.direction;return S&&!v?-1:v&&!S?1:f.sourceId-g.sourceId}static compareUmsStreams(g,f){const S=g.getStreamOptions();return _PluginlessCallStreamManager.compareUmsStreamMetadata(S.stream,f.stream)&&_PluginlessCallStreamManager.compareUmsStreamMetadata(S.altStream,f.altStream)}static compareUmsStreamMetadata(g,f){return!g&&!f||!(!g&&f||g&&!f)&&(g.decryptionKey.id===f.decryptionKey.id&&g.decryptionKey.value===f.decryptionKey.value&&g.url===f.url)}updateMediaStreams(g,f,S,v){const C=this.streams[f],_=C.filter((f=>!g.some((g=>g.sourceId===f.id))));_.forEach((g=>(0,Br.remove)(C,g))),_.length&&this.logger.info(`[${S}][updateMediaStreams] Removing ${_.length} streams of type ${f}`),g.forEach(((_,T)=>{let I=C.find((g=>g.id===_.sourceId));I||(0===f?I=new ns(this.mediaSession,this.localStats.receive(1,this.participantId),this.logger,_.sourceId):1===f&&(I=new rs(this.mediaSession,this.localStats.receive(2,this.participantId),this.logger,_.sourceId)),this.logger.info(`[${S}][updateMediaStreams] Adding stream ${_.sourceId} of type ${f}`),C.push(I),I.changed((()=>this.event("streamChanged").raise()))),I.update(_,S,v),I.rank=g.length-T}))}},cs={0:[1],1:[2,6,3,4,5,7,8],2:[6,3,4,8],3:[1,4,5,8],7:[3,4,8],4:[],5:[3,4,8],6:[3,4],8:[3,5,4]},ds={0:"Disconnected",1:"Connecting",2:"Ringing",3:"Connected",5:"Connected",4:"Disconnected",7:"Connecting"},hs=class extends Ke{constructor(g,f,S,v,C,_=generateCauseId(),T=[]){super(S),this.mri=g,this.callTelemetry=C,this.cachedMediaStreams=T,this.state=0,this.voiceLevel=0,this.isServerMuted=!1,this.endpointType="default",this.balanceUpdates={},this._raiseChangeDeferRunner=Vr.instance.createDeferRunner("CallParticipant.RaiseChange"),this.filteredParticipantEndpointDetails={},this.recordTelemetryForStateChange=(g,f,S,v)=>{if(v){const v="_SetParticipantStateInvalid",C={state:f,reason:S,endpoints:[]};this.endpoints?.endpointDetails?.length&&(C.endpoints=getEndpointInformationForTelemetry(this.endpoints.endpointDetails)),this.callTelemetry.recordEvent(v,C,g)}},this.checkIfIncomingServerMutedIsUpdated=g=>{g.endpointDetails.forEach((g=>{const f=this.filteredParticipantEndpointDetails[g.participantId];void 0!==f&&handleServerMutedVersion(this.logger,f,g)}))},this.handleServerMutedInfoUpdate=g=>{let f=!1;for(const S of g){const g=this.filteredParticipantEndpointDetails[S.participantId];handleMuteUnmuteParticipantInfo(this.logger,g,S,!0)&&(f=!0)}f&&this.updateIsServerMuted()},this.id=this.mri,this.logger=S.createChild((()=>`ICallParticipant[${scrubMriOrOmit(this.id)}][${this.state}]`)),this.logger.info(`[${_}]created`),this.streamManager=new ls(this.id,f,v,this.logger),this.streamManager.on("streamChanged",(()=>this.raiseChanged()))}get audio(){return this.streamManager.audio}get streams(){return this.streamManager.streams}getDiagnosticData(){return JSON.stringify({id:scrubMriOrOmit(this.id),state:this.state,isServerMuted:this.isServerMuted})}async getDiagnosticDataAsync(){return this.getDiagnosticData()}isSameParticipantsMri(g){return this.id===g}setMediaSession(g,f=generateCauseId()){this.streamManager.setMediaSession(g,f)}applyCachedMediaStreams(g=generateCauseId()){const f=this.logger.createFnLogger("applyCachedMediaStreams",g);this.cachedMediaStreams?.length?(f.info("applying cachedMediaStreams"),this.updateStreams(this.cachedMediaStreams,g,!1)):f.info("cachedMediaStreams is empty")}updateStreams(g,f=generateCauseId(),S=!1,v,C=!1){this.logger.createFnLogger("updateStreams",f).info(`isStreamingMode=${S} mediaStreams=${safeJsonStringify(g)}`),g?.length&&(this.cachedMediaStreams=g),S||(this.streamManager.updateStreams(g,f,v,C),this.raiseChangedDeferred())}hasAudioSource(g){return this.streamManager.hasAudioSource(g)}raiseChangedDeferred(){this._raiseChangeDeferRunner((()=>this.raiseChanged()))}updateIsServerMuted(){if(!Object.values(this.filteredParticipantEndpointDetails).length)return void this._updateIsServerMuted(!1);let g=!1;Object.values(this.filteredParticipantEndpointDetails).forEach((f=>{const filterAndSortStreams=g=>f.mediaStreams?.filter((f=>f.type===g)).sort(ls.compareStreams);let S=filterAndSortStreams($r.audio)?.[0];S||(S=filterAndSortStreams($r.audioteleconference)?.[0]);const v=!!S?.serverMuted,C=f.endpointState?.state;!1!==v||!1!==!!C?.isMuted||(g=!0)}));const f=!g;this._updateIsServerMuted(f)}_updateIsServerMuted(g){g!==this.isServerMuted&&(this.isServerMuted=g,this.logger.info(`_updateIsServerMuted updating to: ${this.isServerMuted}`),this.raiseChanged())}updateVoiceLevel(g){this.voiceLevel!==g&&(this.voiceLevel=g,this.raiseChanged())}setState(g,f,S){if(this.state===g)return;const v=this.logger.createFnLogger("setState",S);if(3===this.state&&6===g)return void v.info("Ignore Connected->EarlyMedia transition, it is a race between media and signaling");const C=cs[this.state].indexOf(g)>=0;this.recordTelemetryForStateChange(S,g,f,!C),C?(v.info(`state=${this.state}->${g} reason=${this.stateReason}->${f}`),this.state=g,this.stateReason=f,this.raiseChangedDeferred()):v.logFailure(`Invalid state transition ${this.state}->${g} attempted`)}processParticipantDetails(g,f,S){const v=this.logger.createFnLogger("processParticipantDetails","");this.role=g.role,this.meetingRole=g.meetingRole,this.advancedMeetingRole=g.advancedMeetingRole,this.meetingRoles=g.meetingRoles,this.participantType=g.participantType,this.displayName=g.displayName,this.tenantId=g.tenantId,this.propertyBag=g.propertyBag,this.version=g.version,this.otpIdentity=g.otpIdentity,this.isIdentityMasked=!!g.isIdentityMasked,this.nonMaskedId=g.nonMaskedId,this.nonMaskedDisplayName=g.nonMaskedDisplayName,this.nonMaskedObjectId=g.nonMaskedObjectId,this.maskedIdSeqNumber=g.maskedIdSeqNumber,this.maskedId=g.maskedId,this.joinAsStreamingUser=g.joinAsStreamingUser,g.endpointDetails?.length&&(this.endpoints={endpointDetails:[]},this.participantCapabilities={canConference:!1,canShareScreen:!1,canMerge:!0},this.checkIfIncomingServerMutedIsUpdated(g),this.filteredParticipantEndpointDetails={},g.endpointDetails.forEach((g=>{const v=convertSignalingEndpointDetails(g,f);if(this.endpoints.endpointDetails.push(v),!v.mappedTo){if(this.filteredParticipantEndpointDetails[g.participantId]={endpointId:g.endpointId,serverMuteVersion:g.serverMuteVersion,endpointState:g.endpointState,mediaStreams:g.mediaStreams},g.capabilities&&(this.participantCapabilities.canConference||"enabled"!==g.capabilities.cloudAudioVideoConference||(this.participantCapabilities.canConference=!0),this.participantCapabilities.canShareScreen||"enabled"!==g.capabilities.cloudScreenSharing||(this.participantCapabilities.canShareScreen=!0),this.participantCapabilities.canMerge||"enabled"!==g.capabilities.cloudMerge||(this.participantCapabilities.canMerge=!0)),this.contentSharingRole=0,g.contentSharing&&g.contentSharing.sessionInformation){const f=g.contentSharing.sessionInformation;"attendee"===f.role?this.contentSharingRole=1:"presenter"===f.role&&(this.contentSharingRole=2)}v.streamInformation&&S&&S()}})),this.updateIsServerMuted(),v.info(`endpointDetails=${getPIISafeEndpointDetails(this.endpoints)}`),this.raiseChangedDeferred())}toCafeParticipant(){return{audioState:ds[this.state],mri:this.mri}}getSourceIdForMediaType(g){const f=getSourceIdForMediaType(this,g);return-1===f&&this.logger.warn("getSourceIdForMediaType failed"),f}useUmsStream(g,f,S,v,C,_){this.streamManager.useUmsStream(g,f,S,v,C,_),this.raiseChangedDeferred()}hasSourceId(g,f){return void 0!==getParticipantIdForSourceId(this,g,f)}},us=class extends Ke{constructor(g,f,S,v,C,_="",T,I){super(),this.callTelemetry=g,this.signalingSession=S,this.contentSharingGuid=v,this.contentSharingIdentity=C,this.state=_,this.subject=T,this.handleOperationFailure=(g,f,S)=>{S.logFailure(g);const v=this.getTerminatedReasonFromError(g);return f.updateStatusTo&&(this.contentSharingStatus=f.updateStatusTo,this.rejectContentSharing(v)),Promise.reject(v)},this._logger=f.createChild((()=>`[ContentSharingSession][${this.contentSharingGuid}]`)),this.contentSharingStatus=0,this.contentSharingTerminationReason=null,this.contentSharingState=_,this._callOperationHandler=new Li(this._logger,this.callTelemetry),I&&(this.sessionId=I)}get contentSharingStatus(){return this.status}set contentSharingStatus(g){if(this._logger.info(`[set contentSharingStatus][currentStatus=${this.status}][newStatus=${g}]`),this.callTelemetry.recordEvent("_SetContentSharingStatus",{newStatus:g,oldStatus:this.status}),this.status!==g&&7!==this.status&&8!==this.status){if(this._logger.info(`[set contentSharingStatus] Changing content sharing status to: ${g}`),this.status=g,7===this.status){const g={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"[set contentSharingStatus] Content sharing is disconnected"};this._callOperationHandler.maybeResolveOperation("StopContentSharing"),this._callOperationHandler.rejectPendingOperations(g)}if(2===this.status||5===this.status){const g={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Content sharing cannot be ended when not presenting"};this._callOperationHandler.maybeRejectOperation("StopContentSharing",g)}3===this.status&&(this._callOperationHandler.maybeResolveOperation("StartContentSharing"),this._callOperationHandler.maybeResolveOperation("TakeContentSharingControl")),this.raiseChanged()}}get contentSharingState(){return this.state}set contentSharingState(g){this.state!==g&&(this.state=g,this.raiseChanged())}startContentSharing(g=generateCauseId()){const f=this._logger.createFnLogger("StartContentSharing",g);if(0!==this.contentSharingStatus){const S=`[${g}][startContentSharing][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.startContentSharingAsync(this.contentSharingIdentity,this.contentSharingState,this.subject,this.contentSharingGuid,g).then((g=>{this.sessionId=g.sessionId,this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"StartContentSharing",updateStatusTo:8},f))),this._callOperationHandler.waitForOperation("StartContentSharing")}joinContentSharing(g=generateCauseId()){const f=this._logger.createFnLogger("JoinContentSharing",g);if(2!==this.contentSharingStatus){const S=`[${g}][joinContentSharing][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.joinContentSharingAsync(this.contentSharingGuid,g).then((g=>(this.contentSharingStatus=4,this.contentSharingState=g.sessionState,this.presenterId=g.presenter,Promise.resolve()))).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"JoinContentSharing",updateStatusTo:8},f)))}updateContentSharingSessionState(g,f,S=generateCauseId()){const v=this._logger.createFnLogger("UpdateContentSharingSessionState",S);if(3!==this.contentSharingStatus){const g=`[${S}][updateContentSharingSessionState][failed][reason=InvalidState]`,f={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:g};return v.logFailure(`state=${this.contentSharingStatus}, reason=${g}`),Promise.reject(f)}return this.signalingSession.updateContentSharingSessionStateAsync(this.contentSharingGuid,f,S).then((()=>Promise.resolve())).catch((f=>this.handleOperationFailure(f,{causeId:S,operation:"UpdateContentSharingSessionState",operationId:g},v)))}takeContentSharingControl(g=generateCauseId()){const f=this._logger.createFnLogger("TakeContentSharingControl",g);if(5!==this.contentSharingStatus){const S=`[${g}][updateContentSharingSessionState][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.takeContentSharingControlAsync(this.contentSharingGuid,g).then((()=>{this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"TakeContentSharingControl"},f))),this._callOperationHandler.waitForOperation("TakeContentSharingControl")}updateContentSharingParticipantStateToViewer(g=generateCauseId()){const f=this._logger.createFnLogger("UpdateParticipantState",g);if(4!==this.contentSharingStatus){const S=`[${g}][updateContentSharingSessionState][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.updateContentSharingParticipantStateAsync(this.contentSharingGuid,g).then((()=>(this.contentSharingStatus=this.presenterId===this.signalingSession.participantManager.localParticipant.id?3:5,Promise.resolve()))).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"UpdateParticipantState"},f)))}stopContentSharing(g=generateCauseId()){const f=this._logger.createFnLogger("StopContentSharing",g);if(2===this.contentSharingStatus||4===this.contentSharingStatus||5===this.contentSharingStatus){const S=`[${g}][stopContentSharing][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.deleteContentSharingAsync(this.contentSharingGuid,g).then((()=>(this.contentSharingStatus=7,this._callOperationHandler.waitForOperation("StopContentSharing")))).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"StopContentSharing"},f)))}dispose(g=generateCauseId()){const f={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Call ended"};this._callOperationHandler.rejectPendingOperations(f,g),this.contentSharingStatus=7,this.contentSharingState="",super.dispose()}rejectContentSharing(g={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"[rejectContentSharing] Content sharing is disconnected"}){if(7!==this.status&&8!==this.status)throw new Error(`Tried to reject content sharing with status=${this.status}`);this._callOperationHandler.maybeResolveOperation("StopContentSharing"),this._callOperationHandler.rejectPendingOperations(g)}getTerminatedReasonFromError(g){const f=g?.endCode?.code||0,S={terminatedReason:32,terminatedReasonCode:f,terminatedReasonSubCode:g?.endCode?.subCode||0,errorMessage:g};switch(f){case Fi.NotFound:S.terminatedReason=34,S.errorMessage="Active session not found on server";break;case Fi.Forbidden:S.terminatedReason=8,S.errorMessage="Failed due to insufficient permissions"}return S}};__decorateClass([callOperation("StartContentSharing"),__decorateParam(0,causeId)],us.prototype,"startContentSharing",1),__decorateClass([callOperation("JoinContentSharing"),__decorateParam(0,causeId)],us.prototype,"joinContentSharing",1),__decorateClass([callOperation("UpdateContentSharingSessionState"),__decorateParam(0,operationId),__decorateParam(2,causeId)],us.prototype,"updateContentSharingSessionState",1),__decorateClass([callOperation("TakeContentSharingControl"),__decorateParam(0,causeId)],us.prototype,"takeContentSharingControl",1),__decorateClass([callOperation("UpdateParticipantState"),__decorateParam(0,causeId)],us.prototype,"updateContentSharingParticipantStateToViewer",1),__decorateClass([callOperation("StopContentSharing",{waitFor:"StartContentSharing"}),__decorateParam(0,causeId)],us.prototype,"stopContentSharing",1);var gs,ps=class{constructor(g){this.value=g,this.next=void 0}},ms=class{constructor(){this.length=0}enqueue(g){const f=new ps(g);this.front?(this.rear.next=f,this.rear=f):(this.front=f,this.rear=f),this.length++}dequeue(){if(!this.front)return;const g=this.front;return this.front===this.rear?(this.front=void 0,this.rear=void 0):this.front=this.front.next,this.length--,g.value}peek(){return this.front?.value}size(){return this.length}back(){return this.rear?.value}},fs=M,Ss=class{constructor(g){this.comparator=g,this.heap=[]}enqueue(g){this.heap.push(g),this.bubbleUp()}dequeue(){const g=this.peek();if(void 0!==g){const g=this.heap.pop();this.size()>0&&(this.heap[0]=g,this.bubbleDown())}return g}peek(){return this.heap[0]}size(){return this.heap.length}bubbleUp(){let g=this.size()-1,f=this.getParentIndex(g);for(;!this.isRoot(g)&&this.comparator(this.heap[g],this.heap[f]);)[this.heap[f],this.heap[g]]=[this.heap[g],this.heap[f]],g=f,f=this.getParentIndex(g)}bubbleDown(){if(this.size()<=1)return;let g=this.getRootIndex(),f=this.getLeftIndex(g),S=this.getRightIndex(g);for(;this.heap[f]&&this.comparator(this.heap[f],this.heap[g])||this.heap[S]&&this.comparator(this.heap[S],this.heap[g]);)!this.heap[S]||this.comparator(this.heap[f],this.heap[S])?([this.heap[g],this.heap[f]]=[this.heap[f],this.heap[g]],g=f):([this.heap[g],this.heap[S]]=[this.heap[S],this.heap[g]],g=S),f=this.getLeftIndex(g),S=this.getRightIndex(g)}getRootIndex(){return 0}isRoot(g){return 0===g}getLeftIndex(g){return 2*g+1}getRightIndex(g){return 2*g+2}getParentIndex(g){return Math.floor((g-1)/2)}},vs=class{constructor(g,f,S){this.maxPacketRate=f,this.rateLimiterCheckInterval=S,this.maxDataRate=0,this.packetsEndTimeForPacketRate=0,this.packetsEndTimeForBitrate=0,this.maxDataRate=g/8}canSend(g){if(0===this.maxDataRate&&0===this.maxPacketRate)return!0;const f=Jt();if(this.maxPacketRate&&this.packetsEndTimeForPacketRate>f+this.rateLimiterCheckInterval)return!1;if(this.maxDataRate&&this.packetsEndTimeForBitrate>f+this.rateLimiterCheckInterval)return!1;const S=this.maxPacketRate?1e3/this.maxPacketRate:0,v=this.maxDataRate?g.length/this.maxDataRate*1e3:0;return this.packetsEndTimeForPacketRate=Math.max(this.packetsEndTimeForPacketRate,f)+S,this.packetsEndTimeForBitrate=Math.max(this.packetsEndTimeForBitrate,f)+v,!0}},Cs=class{constructor(g){this.dataIds=new Map,this.maxBitrate=g.config.webrtcDataChannel.maxBitrate,this.maxPacketRate=g.config.webrtcDataChannel.maxPacketRate,this.maxQueueSize=g.config.webrtcDataChannel.maxQueueSize,g.config.webrtcDataChannel.dataIds.forEach((g=>{this.dataIds.set(g.dataId,g)}))}getMaxBitrate(g){return this.dataIds.get(g)?.maxBitrate??this.maxBitrate}getMaxPacketRate(g){return this.dataIds.get(g)?.maxPacketRate??this.maxPacketRate}getMaxQueueSize(g){return this.dataIds.get(g)?.maxQueueSize??this.maxQueueSize}getConfig(g){const f=this.dataIds.get(g)||{dataId:g};return f.maxBitrate=f.maxBitrate??this.maxBitrate,f.maxPacketRate=f.maxPacketRate??this.maxPacketRate,f.maxQueueSize=f.maxQueueSize??this.maxQueueSize,f.priorityWeight=f.priorityWeight??1,f}},ys=class{constructor(g,f,S){this.dataIdConfig=f,this.rateLimiterCheckInterval=S,this.timeOffset=0,this.packets=new ms,this.startTime=g(),this.finishTime=this.startTime,this.rateLimiter=new vs(f.maxBitrate,f.maxPacketRate,this.rateLimiterCheckInterval),this.getCurrentTime=g,this.stats={bufferSize:f.maxQueueSize,remainingBytes:0,remainingPackets:0}}enqueue(g){if(0===g.length)return 0;const f=(0,fs.sumBy)(g,(g=>g.length)),S=this.dataIdConfig.maxQueueSize;if(S&&this.stats.remainingBytes+f>S)throw new Error(`dataId ${this.dataIdConfig.dataId} send queue is full`);const v=this.getCurrentTime();let C=0;return 0===this.packets.size()?(this.startTime=v,this.finishTime=v,this.timeOffset=0,C=v):C=this.finishTime,g.forEach((g=>{C+=g.length*this.dataIdConfig.priorityWeight,this.packets.enqueue({finishTime:C,packet:g}),this.stats.remainingBytes+=g.length,this.stats.remainingPackets++})),this.finishTime=C,f}dequeue(){const g=this.peek();if(void 0!==g){if(!this.rateLimiter.canSend(g.packet))return;this.packets.dequeue(),this.stats.remainingBytes-=g.packet.length,this.stats.remainingPackets--}return g}updateTimeOffset(){this.packets.size()?this.timeOffset=this.getCurrentTime()-this.startTime:(this.startTime=this.getCurrentTime(),this.finishTime=this.startTime,this.timeOffset=0)}peek(){if(0===this.packets.size())return;const g=this.packets.peek();return{finishTime:g.finishTime+this.timeOffset,packet:g.packet}}getConfig(){return this.dataIdConfig}getStats(){return(0,fs.clone)(this.stats)}},Es=class{constructor(g){this.senders=new Map,this.currentVirtualClock=0,this.dataIdConfigManager=new Cs(g),this.virtualTimeQueue=new Ss(((g,f)=>g.minTime<f.minTime)),this.sendStats={bufferSize:0,remainingBytes:0,remainingPackets:0},this.rateLimiterCheckInterval=g.config.webrtcDataChannel.rateLimiterCheckInterval}getPacketsToSend(g){if(0===this.virtualTimeQueue.size())return[];const f=[],S=[];for(;g>=0&&this.virtualTimeQueue.size();){const v=this.virtualTimeQueue.peek();if(v.size>g)break;this.virtualTimeQueue.dequeue();const C=v.dataId,_=this.senders.get(C);if(void 0!==_.peek()){const v=_.dequeue();if(void 0!==v){f.push(v.packet),this.sendStats.remainingBytes-=v.packet.length,g-=v.packet.length,this.sendStats.remainingPackets--,this.currentVirtualClock=Math.max(this.currentVirtualClock,v.finishTime);const S=_.peek();S&&this.virtualTimeQueue.enqueue({dataId:C,minTime:S.finishTime,size:S.packet.length})}else S.push(C)}}return S.forEach((g=>{const f=this.senders.get(g);f.updateTimeOffset();const S=f.peek();S&&this.virtualTimeQueue.enqueue({dataId:g,minTime:S.finishTime,size:S.packet.length})})),f}appendPackets(g,f){let S=this.senders.get(g);void 0===S&&(S=new ys((()=>this.currentVirtualClock),this.dataIdConfigManager.getConfig(g),this.rateLimiterCheckInterval),this.senders.set(g,S));const v=S.getStats(),C=S.enqueue(f);if(this.sendStats.remainingBytes+=C,this.sendStats.remainingPackets+=f.length,0===v.remainingPackets){const f=S.peek();void 0!==f&&this.virtualTimeQueue.enqueue({dataId:g,minTime:f.finishTime,size:f.packet.length})}}getStats(g){if(void 0===g)return(0,fs.clone)(this.sendStats);const f=this.senders.get(g);return void 0===f?{bufferSize:this.dataIdConfigManager.getMaxQueueSize(g),remainingBytes:0,remainingPackets:0}:f.getStats()}},_s=class{constructor(g){this.data={protocolCounters:{},id:void 0,label:void 0,ordered:void 0,negotiated:void 0},this.data.id=g.id,this.data.label=g.label,this.data.ordered=g.ordered,this.data.negotiated=g.negotiated,this.data.protocol=g.protocol||void 0,this.data.maxPacketLifeTime=g.maxPacketLifeTime??void 0,this.data.maxRetransmits=g.maxRetransmits??void 0}recordProtocolEvent(g,f,S){this.data.protocolCounters[S]||(this.data.protocolCounters[S]={});const v=this.data.protocolCounters[S];switch(v[g]||(v[g]={successful:0,failed:0,fragmented:0,dismissed:0}),f){case 0:v[g].successful++;break;case 1:v[g].failed++;break;case 2:v[g].fragmented++;break;case 3:v[g].dismissed++}}recordError(g){this.data.error=g}getObjectRef(){return this.data}},Ts=class{constructor(g,f,S){this.dataId=g,this.diagnostics=f,this.logger=S,this.pendingFragments=[]}depacketize(g){const f=new DataView(g.buffer),S=63&f.getUint8(2);if(S!==this.dataId)throw new Error(`Invalid packet dataId: ${this.dataId} !== ${S}`);const v=11,C=((15&f.getUint8(0))<<8)+f.getUint8(1),_=128&f.getUint8(2),T=f.getUint16(3),I=f.getUint8(5),b=f.getUint32(6),A=f.getUint8(10);if(_){this.pendingFragments.length&&this.logger.warn(`Unfinished message: dataId: ${this.dataId} seqNum: ${T}`),this.remainingPackets=I,0!==I&&this.diagnostics.recordProtocolEvent("recv",2,S),this.pendingFragments=[],this.sourceId=b,this.recipients=[];for(let g=0;g<A;g++){const S=f.getUint32(v+4*g);this.recipients.push(S)}}else{if(0===this.pendingFragments.length)return this.logger.safe.error(`No start flag dataId: ${this.dataId} seqNum: ${T}`),this.diagnostics.recordProtocolEvent("recv",3,S),null;if(this.nextSeqNum!==T)return this.logger.safe.error(`Invalid sequence number: dataId: ${this.dataId} seqNum: ${T}`),this.diagnostics.recordProtocolEvent("recv",3,S),null;this.remainingPackets-=1}if(this.nextSeqNum=T+1&65535,this.pendingFragments.push(g.slice(C)),0===this.remainingPackets){const g=this.pendingFragments.reduce(((g,f)=>g+f.length),0),f=new Uint8Array(g);let S=0;for(const g of this.pendingFragments)f.set(g,S),S+=g.length;return this.pendingFragments=[],{dataId:this.dataId,sourceId:this.sourceId,data:f,recipients:this.recipients}}return null}},Is=class{constructor(g){this.dataId=g,this.seqNum=0}packetize(g){if(g.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${g.dataId}`);const f=11,S=f+4*g.recipients.length,v=new Uint8Array(g.data.length+S),C=new DataView(v.buffer);C.setUint8(0,16+(S>>8)),C.setUint8(1,255&S),C.setUint8(2,128|63&g.dataId),C.setUint16(3,this.seqNum),C.setUint8(5,0),C.setUint32(6,g.sourceId),C.setUint8(10,g.recipients.length);for(let S=0;S<g.recipients.length;S++)C.setUint32(f+4*S,g.recipients[S]);return v.set(g.data,S),this.seqNum+=1,[v]}},bs=class{constructor(g,f,S){this.dataId=g,this.fragmentationSize=f,this.diagnostics=S,this.seqNum=0}packetize(g){if(g.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${g.dataId}`);const f=11,S=f+4*g.recipients.length,v=[],C=this.fragmentationSize-S;if(C<0)throw new Error(`message dataId: ${this.dataId} payload size: ${S} exceeds limit`);let _=g.data.length?Math.ceil(g.data.length/C):1;const T=_-1;T>0&&this.diagnostics.recordProtocolEvent("send",2,this.dataId);let I=g.data.length,b=!0,A=0;for(;_>0;){const P=Math.min(I,C),R=new Uint8Array(P+S),M=new DataView(R.buffer);M.setUint8(0,16+(S>>8)),M.setUint8(1,255&S),b?(b=!1,M.setUint8(2,128|63&g.dataId)):M.setUint8(2,63&g.dataId),M.setUint16(3,this.seqNum),M.setUint8(5,T),M.setUint32(6,g.sourceId),M.setUint8(10,g.recipients.length);for(let S=0;S<g.recipients.length;S++)M.setUint32(f+4*S,g.recipients[S]);R.set(g.data.slice(A,A+P),S),A+=P,v.push(R),this.seqNum+=1,_-=1,I-=P}return v}},As=class extends Ht{constructor(g,f,S,v){super(),this.dataChannel=g,this.sessionDiagnostics=f,this.stateInternal="Created",this.packetizers=new Map,this.depacketizers=new Map,this.sendScheduleTimer=0,this.pendingPackets=new ms,this.sourceIdInternal=Ai,this.label=g.label,this.diagnostics=this.sessionDiagnostics.newDataChannelDiagnostics(g),this.logger=S.createChild(`[WebRtcDataChannel ${this.label}]`),this.logger.safe.info(`Created with settings ${stringifyObject(this.getDataChannelSettings(g))}`),this.bufferedAmountLowThreshold=v.config.webrtcDataChannel.bufferedAmountLowThreshold,this.bufferedAmountHighThreshold=v.config.webrtcDataChannel.bufferedAmountHighThreshold,this.fragmentationSize=v.config.webrtcDataChannel.enableFragmentation?v.config.webrtcDataChannel.fragmentationSize:0,v.config.webrtcDataChannel.enableSendScheduler&&(this.sendScheduler=new Es(v)),this.rateLimiterCheckInterval=v.config.webrtcDataChannel.rateLimiterCheckInterval,this.discardOnSendFailure=v.config.webrtcDataChannel.discardOnSendFailure,this.subscribeOnDataChannelEvents()}getDataIdStats(g){return this.sendScheduler?.getStats(g)}get state(){return this.stateInternal}set sourceId(g){this.sourceIdInternal=g}setDataChannel(g){this.dataChannel&&(this.logger.info(`Replacing internal data channel ${this.label}:${this.dataChannel.id} with ${g.label}:${g.id} with settings ${stringifyObject(this.getDataChannelSettings(g))}`),this.unsubscribeOnDataChannelEvents(),this.dataChannel.close()),this.dataChannel=g,this.diagnostics=this.sessionDiagnostics.newDataChannelDiagnostics(g),this.subscribeOnDataChannelEvents()}dispose(){this.logger.info("dispose"),this.dataChannel&&(this.logger.info(`dataChannel.close ${this.dataChannel.id}`),this.unsubscribeOnDataChannelEvents(),this.dataChannel.close(),this.dataChannel=null,this.setState("Destroyed"),super.dispose())}sendMessage(g,f=this.sourceIdInternal,S,v=[]){try{this.packetizers.has(g)||(this.fragmentationSize?this.packetizers.set(g,new bs(g,this.fragmentationSize,this.diagnostics)):this.packetizers.set(g,new Is(g)));const C=this.packetizers.get(g).packetize({dataId:g,sourceId:f,data:S,recipients:v});void 0!==this.sendScheduler?(this.sendScheduler.appendPackets(g,C),this.scheduleSend()):C.forEach((g=>{this.dataChannel.send(g)})),this.diagnostics.recordProtocolEvent("send",0,g)}catch(f){throw this.logger.unsafe.warn(`Failed to construct protocol message: ${stringifyObject(f)}`),this.diagnostics.recordProtocolEvent("send",1,g),f}}scheduleSend(){if("Connected"!==this.state)return;const sendPacket=g=>{try{this.dataChannel.send(g)}catch(g){return this.logger.unsafe.warn(`Failed to send message: ${stringifyObject(g)}`),!1}return!0};if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){const g=Date.now();let f=this.bufferedAmountHighThreshold-this.dataChannel.bufferedAmount;for(;this.pendingPackets.size();){const g=this.pendingPackets.peek();if(g.length>f)break;if(!sendPacket(g))break;this.pendingPackets.dequeue(),f-=g.length}if(0===this.pendingPackets.size()&&f>0){const g=this.sendScheduler.getPacketsToSend(f);for(const f of g)if(!1===sendPacket(f)&&!1===this.discardOnSendFailure){this.pendingPackets.enqueue(f);break}}if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){if(this.sendScheduleTimer)return;if(this.sendScheduler.getStats().remainingPackets>0){const f=Math.max(g+this.rateLimiterCheckInterval-Date.now(),20);this.sendScheduleTimer=window.setTimeout((()=>{this.sendScheduleTimer=0,this.scheduleSend()}),f)}}}}subscribeOnDataChannelEvents(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onmessage=g=>{const f=new Uint8Array(g.data),S=63&f[2];try{this.depacketizers.has(S)||this.depacketizers.set(S,new Ts(S,this.diagnostics,this.logger));const g=this.depacketizers.get(S).depacketize(f);g&&(this.diagnostics.recordProtocolEvent("recv",0,S),this.event("onmessage").raise(S,g.sourceId,g.data))}catch(g){this.logger.unsafe.warn(`Failed to parse incoming message: ${stringifyObject(g)}`),this.diagnostics.recordProtocolEvent("recv",1,S)}},this.dataChannel.onerror=g=>{const f=g?.target,S=stringifyObject(g?.error??g);this.logger.safe.warn(`onerror: label:${f.label} id:${f.id} ${S} `),this.diagnostics.recordError(S)},"open"===this.dataChannel.readyState&&this.dataChannel.id%2==0&&(this.logger.safe.info(`readyState is already 'open' label:${this.dataChannel.label} id:${this.dataChannel.id}`),this.setState("Connected")),this.dataChannel.onopen=g=>{const f=g.target;this.logger.safe.info(`onopen label:${f.label} id:${f.id}`),f.id%2==0&&this.setState("Connected")},this.dataChannel.onclose=g=>{const f=g.target;this.logger.safe.info(`onclose label:${f.label} id:${f.id}`),this.setState("Closed")},this.dataChannel.onclosing=g=>{const f=g.target;this.logger.safe.debug(`onclosing label:${f.label} id:${f.id}`),this.setState("Closed")},void 0!==this.sendScheduler&&(this.dataChannel.bufferedAmountLowThreshold=this.bufferedAmountLowThreshold,this.dataChannel.onbufferedamountlow=()=>{this.scheduleSend()})}unsubscribeOnDataChannelEvents(){this.dataChannel.onmessage=null,this.dataChannel.onerror=null,this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onclosing=null,this.dataChannel.onbufferedamountlow=null}setState(g){this.stateInternal=g,this.event("onStateChanged").raise(),"Connected"===g&&void 0!==this.sendScheduler&&this.scheduleSend()}getDataChannelSettings(g){return{ordered:g.ordered,maxRetransmits:g.maxRetransmits,maxPacketLifeTime:g.maxPacketLifeTime}}},Ps="main-channel",Rs=class extends Ht{constructor(g,f,S,v){const C=S.createChild("PluginlessDataChannel");super(C),this.pc=g,this.diagnostics=f,this.configProvider=v,this._state="Inactive",this.logger=C,this.subscribeOnDatachannel()}get state(){return this._state}getDataChannel(g){if(!this.dataChannel){this.logger.safe.info(`[${g}] creating new dataChannel`);try{const g=this.configProvider.config.dataChannelDebugInitSettings||{};this.dataChannel=new As(this.pc.createDataChannel(Ps,g),this.diagnostics,this.logger,this.configProvider),this.subscribeForDataChannelEvents()}catch(f){const S=stringifyObject(f);return this.logger.safe.error(`[${g}] createDataChannel failed: ${S}`),this.diagnostics.createChannelFailReason=S,this.setState("Failed"),null}}return this.dataChannel}updateDataModalityState(g){"Failed"!==this._state&&"Disabled"!==this._state&&(g===qt.MEDIA_STATE.sendReceive?this.setState("Active"):g===qt.MEDIA_STATE.inactive&&this.setState("Inactive"))}disable(){this.setState("Disabled")}dispose(){this.stopDataChannel(),this.pc=null,super.dispose()}subscribeOnDatachannel(){this.pc.ondatachannel=g=>{this.onDataChannel(g.channel)}}onDataChannel(g){this.logger.safe.info(`onDataChannel id=${g.id} label=${g.label}`),g.id%2==0?this.dataChannel?(this.logger.safe.info("Found existing data channel, replacing"),this.dataChannel.setDataChannel(g)):(this.dataChannel=new As(g,this.diagnostics,this.logger,this.configProvider),this.subscribeForDataChannelEvents()):this.logger.safe.info(`onDataChannel ignoring id ${g.id}`)}subscribeForDataChannelEvents(){this.dataChannel.on("onStateChanged",(()=>{"Closed"===this.dataChannel.state&&(this.stopDataChannel(),this.setState("Inactive"))}))}setState(g){if(this._state!==g){this.diagnostics.dataChannelSessionState=g;const f=generateCauseId();this._state=g,this.logger.safe.info(`[${f}] SessionDataChannelState changed, state=${this._state}`),"Inactive"===this._state||"Disabled"===this._state?this.stopDataChannel():"Active"===this._state&&this.getDataChannel(f),this.event("onStateChanged").raise(this._state)}}stopDataChannel(){this.dataChannel&&(this.logger.safe.info("stopDataChannel"),this.dataChannel.dispose(),this.dataChannel=null)}},Ms=class extends Ke{constructor(g){super(),this.mainChannel=null,this.sourceId=Ai,this._state="Inactive",this.dataHandlers=new Map,this.dataHandlerTelemetry=new Map,this.startTime=Date.now(),this.sendMessage=async(g,f,S)=>{if(!this.mainChannel||"Connected"!==this.mainChannel.state||"Active"!==this.state)throw new Error("No active data channel to send data from");this.mainChannel.sendMessage(g,this.sourceId,f,S)},this.logger=g.createChild("PluginlessDataChannel")}get state(){return this._state}registerSessionDataChannel(g,f){this.sessionDataChannel&&this.stop(f),this.sessionDataChannel=g,this.subscribeForSessionDataChannelEvents()}setDataChannelSourceId(g){this.logger.debug(`setDataChannelSourceId ${g}`),this.mainChannel&&(this.mainChannel.sourceId=g),this.sourceId=g}requestDataChannelHandler(g){return this.sessionDataChannel.getDataChannel(g)}async sendUserEvents(g,f){if(!this.mainChannel)throw this.logger.info("sendUserEvents() no data channel available"),new Error("Main DataChannel is not active");{const S=f?f.map((g=>parseInt(g,10))):[];this.mainChannel.sendMessage(0,this.sourceId,(new TextEncoder).encode(g),S)}}async addHandler(g,f){if(this.logger.info(`Adding handler with dataId ${g}`),this.dataHandlers.get(g))throw new Error(`Data Id ${g} is already registered`);const S={isStarted:!1,handler:f};this.dataHandlers.set(g,S),this.recordDataHandlerEvent(g,"added"),"Connected"===this.mainChannel?.state&&this.startHandler(g,S)}async removeHandler(g){if(this.logger.info(`Removing handler with dataId ${g}`),!this.dataHandlers.has(g))throw new Error(`Handler associated with Data Id ${g} is not attached`);const f=this.dataHandlers.get(g);f.isStarted&&this.stopHandler(g,f),this.dataHandlers.delete(g)}async updateNegotiationTag(g){}getTelemetry(){if(!this.dataHandlerTelemetry.size)return"";const g={};for(const[f,S]of this.dataHandlerTelemetry)g[f]=S;return JSON.stringify(g)}start(g){this.mainChannel?this.logger.info(`[${g}] already started`):(this.logger.info(`[${g}] starting`),this.mainChannel=this.sessionDataChannel.getDataChannel(g),this.subscribeForMainDataChannelEvents())}stop(g){this.mainChannel&&(this.logger.info(`[${g}] stopping`),this.mainChannel.dispose(),this.mainChannel=null)}dispose(){this.stop(void 0),this.sessionDataChannel=null,super.dispose()}setConfigProviderView(g){this.configProviderView=g}subscribeForMainDataChannelEvents(){this.mainChannel.on("onmessage",((g,f,S)=>{this.dataHandlers.has(g)&&(this.recordDataHandlerEvent(g,"recvd"),this.dataHandlers.get(g).handler.onDataReceived(g,S,f)),this.event("remoteUserEventsReceived").raise(g.toString(),(new TextDecoder).decode(S))})),this.onMainChannelStateChanged(),this.mainChannel.on("onStateChanged",(()=>this.onMainChannelStateChanged()))}onMainChannelStateChanged(){if(this.mainChannel)switch(this.mainChannel.state){case"Connected":this.startHandlers();break;case"Closed":case"Destroyed":this.stopHandlers()}}startHandlers(){for(const[g,f]of this.dataHandlers.entries())f.isStarted||this.startHandler(g,f)}stopHandlers(){for(const[g,f]of this.dataHandlers.entries())f.isStarted&&this.stopHandler(g,f)}startHandler(g,f){this.logger.info(`Starting dataHandler id: ${g}`),f.handler.onStarted(g,((f,S)=>(this.recordDataHandlerEvent(g,"sent"),this.sendMessage(g,f,S))),(()=>{const f=this.mainChannel?.getDataIdStats(g);if(void 0!==f){const g={bufferSize:f.bufferSize,remainingBytes:f.remainingBytes,remainingPackets:f.remainingPackets};return Promise.resolve(g)}return Promise.reject(new Error(`Stats of dataId ${g} is not available`))})),f.isStarted=!0,this.recordDataHandlerEvent(g,"started")}stopHandler(g,f){this.logger.info(`Stopping dataHandler id: ${g}`),f.handler.onStopped(g),f.isStarted=!1,this.recordDataHandlerEvent(g,"removed")}subscribeForSessionDataChannelEvents(){this.sessionDataChannel.on("onStateChanged",(g=>{const f=generateCauseId();switch(g){case"Active":this.start(f),this.setState("Active");break;case"Inactive":this.stop(f),this.setState("Inactive");break;case"Failed":this.stop(f),this.setState("Failed");break;case"Disabled":this.stop(f),this.setState("Disabled");break;default:this.logger.warn(`[${f}] unhandled SessionDataChannelState ${g}`)}}))}recordDataHandlerEvent(g,f){this.dataHandlerTelemetry.has(g)||this.dataHandlerTelemetry.set(g,[{}]);const S=this.dataHandlerTelemetry.get(g);let v=S[S.length-1];if("added"===f&&void 0!==v.added){v={},S.push(v);const g=this.configProviderView?.config.maxStoredDataChannelValues??15;S.length>g&&S.shift()}switch(f){case"added":case"started":case"removed":v[f]=Date.now()-this.startTime;break;case"recvd":case"sent":v[f]=isNaN(v[f])?1:v[f]+1}}setState(g){this._state!==g&&(this._state=g,this.logger.info(`PluginlessDataChannelState changed, state=${this._state}`),this.event("onDataChannelStateUpdated").raise(this._state))}},ws=__toESM(be());(g=>{const f=7,S=3;function encodeMouseEvent(g){if(!g)return new Uint8Array(0);g.buttonType||(g.buttonType=0),g.xPos||(g.xPos=0),g.yPos||(g.yPos=0),g.wheelRotation||(g.wheelRotation=0);const S=new ArrayBuffer(f),v=new DataView(S),C=(3&g.type)<<0,_=(7&g.buttonType)<<2,T=(g.buttonDown?1:0)<<5,I=(g.wheelButtonDown?1:0)<<6,b=0;return v.setUint8(0,1),v.setUint8(1,C|_|T|I|b),v.setUint16(2,g.xPos,!0),v.setUint16(4,g.yPos,!0),v.setUint8(6,g.wheelRotation),new Uint8Array(S)}function encodeKeyboardEvent(g){const f=new ArrayBuffer(S),v=new DataView(f),C=(3&g.codeType)<<0,_=0,T=(g.keyUp?1:0)<<4,I=(g.repeat?1:0)<<5,b=0,A=0;return v.setUint8(0,0),v.setUint8(1,C|_|T|I|b|A),v.setUint8(2,g.code),new Uint8Array(f)}function decodeEventType(g){return g[0]}function decodeMouseEvent(g){if(1!==g[0]||g.length!==f)return null;const S=new DataView(g.buffer),v=S.getUint8(1);return{type:3&v,buttonType:v>>2&7,buttonDown:!!(v>>5&1),wheelButtonDown:!!(v>>6&1),xPos:S.getUint16(2,!0),yPos:S.getUint16(4,!0),wheelRotation:S.getUint8(6)}}function decodeKeyboardEvent(g){if(0!==g[0]||g.length!==S)return null;const f=new DataView(g.buffer),v=f.getUint8(1);return{codeType:3&v,code:f.getUint8(2),repeat:!!(v>>5&1),keyUp:!!(v>>4&1)}}g.encodeMouseEvent=encodeMouseEvent,g.encodeKeyboardEvent=encodeKeyboardEvent,g.decodeEventType=decodeEventType,g.decodeMouseEvent=decodeMouseEvent,g.decodeKeyboardEvent=decodeKeyboardEvent})(gs||(gs={}));var Os=M,Ds=R,Ns=3e4,ks=1e4,Ls=2e3,Fs=6,xs="",Us=class extends _i{constructor(g,f,S,v,C,_,T,I,b){super(g,v,(()=>this.recordedEvents.length>100)),this.auditLogger=f,this.config=S,this.negotiationTag=C,this.callId=_,this.participantId=T,this.endpointId=I,this.dataSourceId=b,this.messagesFromUnknownSender={},this.tsCallingVersion=getTsCallingVersion()}setCallId(g){this.callId=g}setParticipantId(g){this.participantId=g}setDataSourceId(g){this.dataSourceId=g}callStateChanged(g){this.recordEvent("CallState",{state:g})}dataChannelAvailable(g){g?this.recordEvent("DataChannelAvailable"):this.recordEvent("DataChannelUnavailable")}shutdownSession(g){this.negotiationTag&&this.negotiationTag!==g?this.recordEvent("ShutdownByOtherSession",null,g):this.recordEvent("Shutdown")}recordProtocolMessage(g,f){g||(f in this.messagesFromUnknownSender||(this.messagesFromUnknownSender[f]=0),this.messagesFromUnknownSender[f]++)}sendAuditEvent(g,f,S,v,C){if(!this.auditLogger)return void this.logger.warn("AuditLogger is not set");const getValue2=g=>g??"",_={TenantId:getValue2(this.tenantId),CorrelationId:getValue2(this.callId),ParticipantId:getValue2(this.participantId),EndpointId:getValue2(this.endpointId),TsCallingVersion:getValue2(this.tsCallingVersion),sharingNegotiationTag:getValue2(this.negotiationTag),timestamp:Date.now(),eventType:f,role:toSharingControlRole(this.role),initiator:toSharingControlRole(S),controlCauseId:g,viewerParticipantId:getValue2(C.participantId),viewerEndpointId:getValue2(C.endpointId),viewerDataSourceId:getValue2(C.dataSourceId),sharerParticipantId:getValue2(v.participantId),sharerEndpointId:getValue2(v.endpointId),sharerDataSourceId:getValue2(v.dataSourceId)};try{this.auditLogger.sendEvent({eventName:"mdsc_gtc_audit",props:_})}catch(g){this.logger.error("Failed to send audit event",g)}}},Vs=class extends Us{constructor(g,f,S,v,C,_,T,I,b,A){super(g,f,S,v,C,_,T,I,b),this.role=2;const P=getSharingParticipantLeg(A);if(P){this.sharerParticipantId=P;const g=(0,Os.find)(A.endpoints.endpointDetails,(g=>g.participantId===P));g&&(this.sharerEndpointId=g.endpointId,this.sharerClientVersion=g.clientVersion)}}startHandshake(g){this.recordOperation("AvailableHandshake",g)}delayHandshakeSending(g,f,S){const v={delay:f,maxDelay:S};this.updateOperationData("AvailableHandshake",v,g)}handshakeSucceeded(g,f){const S={retries:f};this.recordOperationSuccess("AvailableHandshake",S,null,g)}handshakeFailed(g,f,S){const v={retries:f,reason:toAvailableHandshakeTerminatedString(S)};this.recordOperationFailure("AvailableHandshake",v,null,g)}requestControl(g,f){this.recordOperation("ControlRequest",g,g),this.recordAuditEvent(g,2,"ControlRequest",f)}requestControlAccepted(g,f){this.recordOperationSuccess("ControlRequest",g,g),this.recordAuditEvent(g,1,"ControlRequestAccepted",f),this.recordAuditEvent(g,2,"ControlStarted",f)}requestControlRejected(g,f,S){const v={reason:toControlTerminatedReason(f)};2===f?this.recordOperationTimeout("ControlRequest",v,g,g):this.recordOperationFailure("ControlRequest",v,g,g),this.recordAuditEvent(g,1,"ControlRequestDeclined",S)}controlGiven(g,f){this.recordEvent("ControlGiven",{sharerSourceId:f},g),this.recordAuditEvent(g,1,"ControlGiven",f),this.recordAuditEvent(g,2,"ControlStarted",f)}controlTerminated(g,f,S,v){const C={sharerSourceId:S,reason:toControlTerminatedReason(f)};this.recordEvent("ControlTerminated",C,g);const _=v?1:2;this.recordAuditEvent(g,_,"ControlTerminated",S)}recordAuditEvent(g,f,S,v){if(this.config.disableAudit)return;const C={participantId:this.sharerParticipantId,endpointId:this.sharerEndpointId,dataSourceId:v},_={participantId:this.participantId,endpointId:this.endpointId,dataSourceId:this.dataSourceId};this.sendAuditEvent(g,S,f,C,_)}getEvent(g,f){const getValue2=g=>g??"";return{CorrelationId:getValue2(this.callId),ParticipantId:getValue2(this.participantId),EndpointId:getValue2(this.endpointId),NegotiationTag:getValue2(this.negotiationTag),TsCallingVersion:getValue2(this.tsCallingVersion),TenantId:getValue2(this.tenantId),SharerParticipantId:getValue2(this.sharerParticipantId),SharerClientVersion:getValue2(this.sharerClientVersion),EventTimestampBag:super.getEventTimestampBag(g,f),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},Bs=class extends Us{constructor(g,f,S,v,C,_,T,I,b){super(g,f,S,v,C,_,T,I,b),this.role=1}availableAckChanged(g){g?this.recordEvent("AvailableAckEnabled"):this.recordEvent("AvailableAckDisabled")}controlRequest(g,f,S){this.recordOperation("ControlRequest",g,g),this.recordAuditEvent(g,2,"ControlRequest",f,S)}controlRequestAccept(g,f,S){const v={status:"accepting",participantId:S};this.updateOperationData("ControlRequest",v,g,g),this.recordAuditEvent(g,1,"ControlRequestAccepted",f,S)}controlRequestAccepted(g,f,S){const v={participantId:S};this.recordOperationSuccess("ControlRequest",v,g,g),this.recordAuditEvent(g,2,"ControlStarted",f,S)}controlRequestRejected(g,f,S,v){const C={reason:toControlTerminatedReason(f),participantId:v};4===f?this.recordOperationTimeout("ControlRequest",C,g,g):this.recordOperationFailure("ControlRequest",C,g,g),this.recordAuditEvent(g,1,"ControlRequestDeclined",S,v)}giveControl(g,f,S){this.recordOperation("GiveControl",g,g),this.recordAuditEvent(g,1,"ControlGiven",f,S)}giveControlSucceeded(g,f,S){const v={participantId:S};this.recordOperationSuccess("GiveControl",v,g,g),this.recordAuditEvent(g,2,"ControlStarted",f,S)}giveControlFailed(g,f,S,v){const C={reason:toControlTerminatedReason(f)};this.recordOperationTimeout("GiveControl",C,g,g),this.recordAuditEvent(g,1,"ControlGiveFailed",S,v)}controlTerminated(g,f,S,v,C){const _={controllerSourceId:v,reason:toControlTerminatedReason(f)};this.recordEvent("ControlTerminated",_,g);const T=C?2:1;this.recordAuditEvent(g,T,"ControlTerminated",S,v)}recordAuditEvent(g,f,S,v,C){if(this.config.disableAudit)return;const _=getParticipantLegFromStreamSourceId(v,C)??v.endpoints?.endpointDetails?.[0],T={participantId:_?.participantId,endpointId:_?.endpointId,dataSourceId:C},I={participantId:this.participantId,endpointId:this.endpointId,dataSourceId:this.dataSourceId};this.sendAuditEvent(g,S,f,I,T)}getEvent(g,f){const getValue2=g=>void 0===g?"":g;return{CorrelationId:getValue2(this.callId),ParticipantId:getValue2(this.participantId),EndpointId:getValue2(this.endpointId),NegotiationTag:getValue2(this.negotiationTag),TsCallingVersion:getValue2(this.tsCallingVersion),TenantId:getValue2(this.tenantId),EventTimestampBag:this.getEventTimestampBag(g,f),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},Hs=class extends Ke{constructor(g,f,S,v){super(g),this._logger=g,this._call=f,this._telemetryLoggers=S,this._config=v,this.controlState=0,this._role=0,this._enabled=!1,this._availableAckEnabled=!0,this._clientConfiguration={},this._dataChannelAvailable=!1,this._availableHandshakeSent=!1,this._controlRequest=null,this._controlRequestSubscription=null,this._controlCauseId=null,this._controllerParticipant=null,this._controllerParticipantSubscription=null,this._controllerSourceId=null,this._screenSharingVideoRenderer=null,this._screenSharingVideoRendererSubscriptions=[],this._sharerParticipant=null,this._pendingSharer=null,this._controlCapturer=null,this._captureEventSubscription=null,this._mouseControlEventSubscription=null,this._keyboardControlEventSubscription=null,this._requestControlTimer=null,this._grantControlTimer=null,this._acceptControlTimer=null,this._terminateControlTimer=null,this._delayedSendHandshakeTimer=null,this._availableAckTimer=null,this._retryAttempt=0,this._raiseRenderedAtViewer=null,this._participantSubscriptions={},this._viewerSessionLastTerminatedReason=0,this._completedViewerSessions=[],this.isEscalationInProgress=!1,this._logger.info("constructor"),this._callId=this._call.callId,this._call.on("callIdChanged",(g=>{this._callId=g,this._recordSessionTelemetry((f=>f.setCallId(g)))})),this._participantId=this._call.participantId,this._call.on("callLegIdChanged",(g=>{this._participantId=g,this._recordSessionTelemetry((f=>{f.setParticipantId(g),f.setDataSourceId(this.getLocalEndpointDataSourceId())}))})),this._endpointId=this._call.endpointId}get role(){return this._role}setAdapters(g,f,S){this._controlInjector=g,this._rendererAdapter=f,this._dataChannelAdapter=S,this._dataChannelAdapter.on("stateChange",(g=>{this._onDataChannelStatusChanged(g),this._recordSessionTelemetry((f=>f.dataChannelAvailable(g)))})),this._dataChannelAdapter.on("protocolMessage",((g,f,S,v)=>this.processProtocolMessage(g,f,S,v))),this._dataChannelAdapter.on("controlMessage",((g,f)=>this.processControlMessage(g,f)))}testSetControlInjector(g){}enableScreenSharingControl(g,f,S,v){if(this._logger.info(`enableScreenSharingControl() enabled=${g} disabledReason=${f}`),this._availableAckEnabled!==g||this._allowControlForUser!==v){if(this._allowControlForUser=v,g)this._raiseScreenSharingControlCapableEvent(!0,xs);else{if(0===f){const g={reason:2,detail:S};this.event("sharingControlError").raise(g)}this._raiseScreenSharingControlCapableEvent(!1,xs)}this._availableAckEnabled!==g&&this._recordSharerSessionTelemetry((f=>f.availableAckChanged(g)),!1),this._availableAckEnabled=g}}_canEnableGiveControl(){return this._controlInjector.canBeEnabled()}setRaiseRenderedAtViewer(g){this._raiseRenderedAtViewer=g}setScreenSharingControlFeatureFlag(g,f){this._logger.info(`setScreenSharingControlFeatureFlag() enabled=${g} clientConfiguration=${JSON.stringify(f)}`),this._enabled=g,this._availableAckEnabled=g,this._clientConfiguration={...f},this._enabled&&this._handleCallState(this._callState)}isScreenSharingControlEnabled(){return this._enabled}isInternalViewerControlEnabled(){return!this._clientConfiguration.externalViewerControlInitialization}isInternalSharerControlEnabled(){return!this._clientConfiguration.externalSharerControlInitialization}_disposeRenderer(g){this._disposeControlCapturer(g);for(const g of this._screenSharingVideoRendererSubscriptions)g.dispose();this._screenSharingVideoRendererSubscriptions=[],this._screenSharingVideoRenderer=null}setRenderer(g,f){this._logger.info("setRenderer");const S=generateCauseId();if(this._disposeRenderer(S),!g)return Promise.resolve();const v=f||this._rendererAdapter.getTarget(g);return asap((()=>{this._setViewingRenderer(g,v)}))}_isDataChannelActive(){return this._dataChannelAdapter.isActive()&&this._dataChannelAvailable}_raiseScreenSharingControlCapableEvent(g,f,S){if(this._enabled&&this._isDataChannelActive()){this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=true, capable=${g}, role=${this._role}`);const v={capable:g,id:f,disabledBySharer:S};this.event("sharingControlCapable").raise(v)}else{this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=false, capable=${g}, role=${this._role}`);const S={capable:!1,id:f};this.event("sharingControlCapable").raise(S)}}initControlForSharer(g){this._logger.info(`initControlForSharer() negotiationTag: ${g}`),this._isSharing()&&this._logger.warn("initControlForSharer() when already sharing"),this._resetControlState(),this._screenSharingVideoRenderer=null,this._disposeControlCapturer(),this._logger.info(`role is changing from=${this._role} to=1`),this._role=1,this._availableHandshakeSent=!1,this._raiseScreenSharingControlCapableEvent(this._canEnableGiveControl(),xs),this._initiateSharerSessionTelemetry(g)}enableControlInjector(g){this._logger.info(`enableControlInjector() trackId: ${g}`),this._canEnableGiveControl()?this._controlInjector.enableInjector(g).catch((g=>{const f={reason:0,detail:JSON.stringify({errorMsg:g})};this.event("sharingControlError").raise(f)})):this._logger.info("enableControlInjector() give control cannot be enabled")}shutdownControlForSharer(){if(this._logger.info("shutdownControlForSharer()"),this._isSharing()||this._logger.warn("shutdownControlForSharer() when not sharing"),this._controlRequest){this._logger.warn("Rejecting pending control requests");const g=this._getDataSourceIdForParticipantLeg(this._controlRequest),f=this._controlRequest;this._clearControlRequest(),this._raiseControlRequestCanceled(f),this._sendControlRejectRequest(f.causeId,5,f.participant,g)}if(this._controllerParticipant){const g={inControl:!1,id:this._controllerParticipant.participant.id,terminatedReason:5};this._recordSharerSessionTelemetry((f=>f.controlTerminated(this._controlCauseId,g.terminatedReason,this._controllerParticipant.participant,this._controllerSourceId))),this.event("sharingControlChanged").raise(g)}this._finalizeSharerSessionTelemetry(),this._teardownSharerRemoteControl(),this._controlInjector.disableInjector().catch((g=>{const f={reason:0,detail:JSON.stringify({errorMsg:g})};this.event("sharingControlError").raise(f)})),this._resetControlState(),this._resetParticipantSubscriptions(),this._availableAckEnabled=this._enabled,this._logger.info(`role is changing from=${this._role} to=0`),this._role=0}_resetParticipantSubscriptions(){this._logger.info("resetParticipantSubscriptions() Stopping tracking all participant state changes"),(0,Os.each)(this._participantSubscriptions,(g=>{g.dispose()})),this._participantSubscriptions={}}_initiateViewerSessionTelemetry(g,f,S){if(!S&&!f)return null;if(!S&&(0,Os.find)(this._completedViewerSessions,(g=>f===g)))return null;if(this._currentViewerSessionTelemetry){if(this._currentViewerSessionTelemetry.negotiationTag===f)return null;this._finalizeViewerSessionTelemetry(f)}return this._logger.info(`Initiating new viewer session telemetry for ${f}`),this._currentViewerSessionTelemetry=new Vs(this._logger,this._telemetryLoggers?.gtcAudit,this._config,(new Date).getTime(),f,this._callId,this._participantId,this._endpointId,this.getLocalEndpointDataSourceId(),g),this._currentViewerSessionTelemetry.callStateChanged(this._callState),this._isDataChannelActive()&&this._currentViewerSessionTelemetry.dataChannelAvailable(!0),this._currentViewerSessionTelemetry}_recordViewerSessionTelemetry(g,f=!0){this._currentViewerSessionTelemetry?g&&g(this._currentViewerSessionTelemetry):f&&this._logger.error("Cannot record telemetry without current session")}_finalizeViewerSessionTelemetry(g){if(!this._currentViewerSessionTelemetry)return;this._currentViewerSessionTelemetry.shutdownSession(g);const f=this._currentViewerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_viewer_session",f),this._currentViewerSessionTelemetry.negotiationTag&&this._completedViewerSessions.push(this._currentViewerSessionTelemetry.negotiationTag),this._currentViewerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentViewerSessionTelemetry.messagesFromUnknownSender).length&&Ds.RootToolsManager.logExternalForDDL("ScreenSharingControl_viewer: messages received from unkonwn sender",JSON.stringify(f.ProtocolMessages)),this._currentViewerSessionTelemetry=null}_initiateSharerSessionTelemetry(g){if(this._currentSharerSessionTelemetry){if(this._currentSharerSessionTelemetry.negotiationTag===g)return null;this._finalizeSharerSessionTelemetry(this._currentSharerSessionTelemetry.negotiationTag)}this._logger.info(`Initiating new sharer session telemetry for ${g}`),this._currentSharerSessionTelemetry=new Bs(this._logger,this._telemetryLoggers?.gtcAudit,this._config,(new Date).getTime(),g,this._callId,this._participantId,this._endpointId,this.getLocalEndpointDataSourceId()),this._isDataChannelActive()&&this._currentSharerSessionTelemetry.dataChannelAvailable(!0)}_recordSharerSessionTelemetry(g,f=!0){this._currentSharerSessionTelemetry?g&&g(this._currentSharerSessionTelemetry):f&&this._logger.error("Cannot record telemetry without current session")}_finalizeSharerSessionTelemetry(g){if(!this._currentSharerSessionTelemetry)return;this._currentSharerSessionTelemetry.shutdownSession(g);const f=this._currentSharerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_sharer_session",f),this._currentSharerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentSharerSessionTelemetry.messagesFromUnknownSender).length&&Ds.RootToolsManager.logExternalForDDL("ScreenSharingControl_sharer: messages received from unkonwn sender",JSON.stringify(f.ProtocolMessages)),this._currentSharerSessionTelemetry=null}_recordSessionTelemetry(g){g&&(this._currentSharerSessionTelemetry&&g(this._currentSharerSessionTelemetry),this._currentViewerSessionTelemetry&&g(this._currentViewerSessionTelemetry))}_sendTelemetryEvent(g,f){this._logger.info(`Sending event ${g}: `),Object.keys(f).forEach((g=>{this._logger.info(`     ${g} => ${f[g]}`)})),this._telemetryLoggers?.media?.sendEvent({eventName:g,props:f})}reportSharingSessionChangeForViewer(g,f){f&&this._initiateViewerSessionTelemetry(g,f,!1)}initControlForViewer(g,f){if(this._logger.info(`initControlForViewer(${scrubMriOrOmit(g?.id)}, ${f})`),g){if(this._isViewing()&&this._logger.warn("initControlForViewer: called when already viewing"),3!==this._callState)return this._logger.info(`initControlForViewer: postponed until call is connected, callState=${this._callState}`),this._pendingNegotiationTag=f,void(this._pendingSharer=g);this._logger.info(`role is changing from=${this._role} to=2`),this._role=2,this._sharerParticipant?this._sharerParticipant.id!==g.id&&(this._logger.info(`initControlForViewer: sharer switched, new sharer id=${scrubMriOrOmit(g.id)}`),this._availableHandshakeSent=!1,4===this.controlState&&this._terminateControl(!1)):(this._logger.info(`initControlForViewer: setting sharer to id=${scrubMriOrOmit(g.id)}`),this._sharerParticipant=g,this._availableHandshakeSent=!1),this._initiateViewerSessionTelemetry(g,f,!0),this._enabled&&this._isDataChannelActive()&&!this._availableHandshakeSent&&(this._resetControlState(),this._sharerParticipant=g,this._logger.info("initControlForViewer: sending Available message to sharer"),this._startAvailableHandshake())}else this._logger.warn("initControlForViewer: Sharer undefined, ignoring")}shutdownControlForViewer(g){if(this._logger.info(`shutdownControlForViewer() isViewing: ${this._isViewing()}`),this._pendingSharer=null,(!g||g.id===this._sharerParticipant?.id)&&this._isViewing()){if(this._logger.info(`shutdownControlForViewer: sharerParticipant id=${g?scrubMriOrOmit(g.id):null}`),1===this.controlState){if(this._sharerParticipant){const g=this._getSharerDataSourceId();this._sendRequest({action:2,terminatedReason:6,causeId:this._controlCauseId},g)}else this._logger.warn("shutdownControlForViewer: sharer participant is null");const g={inControl:!1,id:xs,terminatedReason:6};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:g,details:""}))):this._logger.error("shutdownControlForViewer: Unexpected, no promise could be resolved, controlState=RequestSent")}else if(4===this.controlState){const g={inControl:!1,id:xs,terminatedReason:6};this._recordViewerSessionTelemetry((f=>f.controlTerminated(this._controlCauseId,g.terminatedReason,this._controllerSourceId,!1))),this.event("sharingControlChanged").raise(g)}this._teardownViewerRemoteControl(),this._resetControlState(),this._screenSharingVideoRenderer=null,this._terminateAvailableHandshake&&this._terminateAvailableHandshake(2),this._availableHandshakeSent=!1,this._finalizeViewerSessionTelemetry(),2===this._role?(this._logger.info(`_raiseScreenSharingControlCapableEvent  with user role=${this._role}, MRI=${xs}, isCapable=false`),this._raiseScreenSharingControlCapableEvent(!1,xs)):this._logger.warn(`can't call _raiseScreenSharingControlCapableEvent, role=${this._role}`),this._logger.info(`role is changing from=${this._role} to=0`),this._role=0}}_resetControlRequest(g){this._clearControlRequest(),this._controlRequest=g,this._registerParticipantListener(g),3===g.participantState&&(this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${scrubMriOrOmit(g.participant.id)}`),this.event("sharingIncomingControlRequest").raise(g.participant.id))}_clearControlRequest(){this._logger.info("_clearControlRequest()"),this._stopListeningToParticipantChanges(this._controlRequest),this._controlRequest=null}_stopListeningToParticipantChanges(g){this._controlRequestSubscription&&(this._logger.info(`_stopListeningToParticipantChanges: stopping tracking changes for ${scrubMriOrOmit(g.participant.id)}`),this._controlRequestSubscription.dispose(),this._controlRequestSubscription=null)}_registerParticipantListener(g){this._logger.info(`_registerParticipantListener: tracking changes for ${scrubMriOrOmit(g.participant.id)}`),this._logger.info(`request.participantState: ${g.participantState} | request.participant.state: ${g.participant.state}`),this._controlRequestSubscription=g.participant.changed((()=>{if(g.participant.state!==g.participantState)switch(this._logger.info(`request.participantState about to changed from: ${g.participantState} to: ${g.participant.state}`),g.participantState=g.participant.state,g.participantState){case 3:this.event("sharingIncomingControlRequest").raise(g.participant.id),this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${scrubMriOrOmit(g.participant.id)}`);break;case 0:case 5:case 4:this.denyControlRequest().catch((g=>{this._logger.info(`It is ok if denyControlRequest rejects here as screensharing may have just been stopped. Err: ${g}`)})),this._logger.info(`_registerParticipantListener: participant ${scrubMriOrOmit(g.participant.id)} is no longer connected. resetting`),this._clearControlRequest(),this._raiseControlRequestCanceled(g);break;case 1:case 2:case 6:case 7:this._logger.info(`participantState: ${g.participantState}, participantId: ${scrubMriOrOmit(g.participant.id)}`);break;default:this._logger.error(`_registerParticipantListener: Unexpected participantState ${g.participantState} unhandled`)}}))}_resetControllerParticipant(g){this._controllerParticipantSubscription&&(this._logger.info(`_resetControllerParticipant: stopping tracking changes for ${scrubMriOrOmit(this._controllerParticipant.participant.id)}`),this._controllerParticipantSubscription.dispose(),this._controllerParticipantSubscription=null),g&&(this._logger.info(`_resetControllerParticipant: tracking changes for ${scrubMriOrOmit(g.participant.id)}`),this._controllerParticipantSubscription=g.participant.changed((()=>{3!==g.participant.state&&this.handleParticipantRemoved(g.participant.id)}))),this._controlCauseId=g?.causeId??null,this._controllerParticipant=g}handleParticipantRemoved(g){if(this._participantSubscriptions[g]&&(this._logger.info(`handleParticipantRemoved(): Stopping tracking state changes for ${scrubMriOrOmit(g)}`),this._participantSubscriptions[g].dispose(),delete this._participantSubscriptions[g]),this._isSharing()){if(this._controllerParticipant&&this._controllerParticipant.participant.id===g){this._logger.info("handleParticipantRemoved: controller left call, tearing down control session"),this._teardownSharerRemoteControl(),this.controlState=0;const f=5;this._recordSharerSessionTelemetry((g=>g.controlTerminated(this._controlCauseId,f,this._controllerParticipant.participant,this._controllerSourceId,!0))),this._resetControllerParticipant();const S={inControl:!1,id:g,terminatedReason:f};this.event("sharingControlChanged").raise(S)}this._raiseScreenSharingControlCapableEvent(!1,g)}else if(this._sharerParticipant&&this._sharerParticipant.id===g&&4===this.controlState){this._logger.info("handleParticipantRemoved: sharer left call, tearing down control session"),this._teardownViewerRemoteControl(),this.controlState=0;const g={inControl:!1,id:xs,terminatedReason:6};this.event("sharingControlChanged").raise(g)}}callStateChanged(g){this._callState=g,this._recordSessionTelemetry((f=>f.callStateChanged(g))),this.isScreenSharingControlEnabled()&&this._handleCallState(g)}setIsEscalationInProgress(g){this.isEscalationInProgress=g}_getHandshakeDelay(){if(!this._config.handshakeSendDelay?.minParticipantThreshold)return 0;let g=0;if(this._call.participants.length>=this._config.handshakeSendDelay.minParticipantThreshold)for(const f of this._call.participants)f.endpoints?.endpointDetails.some((g=>"interactive"===g.appliedInteractivityLevel))&&g++;if(g<=this._config.handshakeSendDelay.minParticipantThreshold)return 0;const f=Math.ceil((g-this._config.handshakeSendDelay.minParticipantThreshold)/this._config.handshakeSendDelay.increaseEveryN);return Math.min(this._config.handshakeSendDelay.maxDelay,f*this._config.handshakeSendDelay.delayPerN)}_handleCallState(g){switch(g){case 3:this._handleCallConnected();break;case 7:this._handleCallDisconnected();break;case 4:case 5:this.isInternalViewerControlEnabled()&&this.shutdownControlForViewer()}}_handleCallConnected(){this._logger.info("_handleCallConnected()"),this._pendingSharer&&(this.initControlForViewer(this._pendingSharer,this._pendingNegotiationTag),this._pendingSharer=null)}_handleCallDisconnected(){this._logger.info("_handleCallDisconnected()"),this._isSharing()?this.isInternalSharerControlEnabled()&&this.shutdownControlForSharer():this.isInternalViewerControlEnabled()&&this.shutdownControlForViewer()}_videoSizeChanged(g,f){null!==this._controlCapturer&&this._controlCapturer.updateVideoSize(g,f)}_onRenderStarted(){const g={action:11,terminatedReason:0};if(this._sharerParticipant){const f=this._getSharerDataSourceId();this._sendRequest(g,f)}else this._logger.error("Attempted to send sharing rendered message to null sharerParticipant")}_setViewingRenderer(g,f){try{this._screenSharingVideoRenderer=g,this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeVideoSizeChangedEvent(this._screenSharingVideoRenderer,((g,f)=>{this._videoSizeChanged(g,f)}))),this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeRenderStartedEvent(this._screenSharingVideoRenderer,(()=>{this._onRenderStarted()})));let S=1;g.streamSize&&g.streamSize.width>0&&g.streamSize.height>0&&(S=g.streamSize.width/g.streamSize.height),this._controlCapturer=new ws.SlimCoreElectronControlCapturer(this._logger,f,!0,S),4===this.controlState?(this._logger.info("_setViewingRenderer: detected local state is controlling"),this._setupViewerRemoteControl()):this._teardownViewerRemoteControl()}catch(g){this._logger.error(`_setViewingRenderer: unable to set _screenSharingVideoRenderer error=${g}`)}}_onDataChannelStatusChanged(g){this._logger.info(`_onDataChannelStatusChanged(): Data channel status=${g}, isEscalationInProgress=${this.isEscalationInProgress}`),g?this._dataChannelAvailable||(this._dataChannelAvailable=!0,this._recordSessionTelemetry((g=>g.dataChannelAvailable(!0))),this._enabled&&(this._isViewing()?this._availableHandshakeSent||(this._sharerParticipant?(this._logger.info("_onDataChannelStatusChanged: sending Available message to sharer"),this._startAvailableHandshake()):this._logger.error("Unexpected null _sharerParticipant trying to send Available to sharer")):this._isSharing()&&(this.isEscalationInProgress||this._raiseScreenSharingControlCapableEvent(!0,xs)))):this._dataChannelAvailable&&(this._recordSessionTelemetry((g=>g.dataChannelAvailable(!1))),this._dataChannelAvailable=!1,this._availableHandshakeSent=!1,this._terminateAvailableHandshake&&this._terminateAvailableHandshake(3),this.isEscalationInProgress||this._raiseScreenSharingControlCapableEvent(!1,xs))}_isSharing(){return 1===this._role}_isViewing(){return 2===this._role}_handleAvailableRequest(g,f,S){if(this._isSharing())return this._enabled&&this._availableAckEnabled&&this._canEnableGiveControl()?f?.id?void(this._allowControlForUser&&"function"==typeof this._allowControlForUser?this._allowControlForUser(f).then((v=>{v?this._acceptAvailableRequest(g.handshakeId,f,S):this._rejectAvailableRequest(g.handshakeId,S,1)})):this._acceptAvailableRequest(g.handshakeId,f,S)):(this._logger.info("Unknown sender. Rejecting available ack"),void this._rejectAvailableRequest(g.handshakeId,S,10)):(this._logger.info(`Rejecting available ack - enabled=${this._enabled}, availableAck=${this._availableAckEnabled}, controlInjector=${this._canEnableGiveControl()}`),void this._rejectAvailableRequest(g.handshakeId,S,9));this._logger.warn(`Ignoring available request since role=${this._role} is not sharing. Expecting for viewer side retries`)}_acceptAvailableRequest(g,f,S){this._raiseScreenSharingControlCapableEvent(!0,f.id),this._participantSubscriptions[f.id]||(this._logger.info(`Tracking participant status for ${scrubMriOrOmit(f.id)}`),this._participantSubscriptions[f.id]=f.changed((()=>{3!==f.state&&(this._logger.info(`Participant ${scrubMriOrOmit(f.id)} is not connected. removing`),this.handleParticipantRemoved(f.id))}))),this._logger.info(`Acking Available for handShake:${S}:${g}`),this.event("controlAvailableHandshake").raise(g,S,3),this._sendRequest({action:9,terminatedReason:0,handshakeId:g},S)}_rejectAvailableRequest(g,f,S){this._logger.info(`Rejecting Available for handShake:${f}:${g}`),this.event("controlAvailableHandshake").raise(g,f,7,this._getAvailableHandshakeTerminatedFromControlTerminated(S)),this._sendRequest({action:10,terminatedReason:S,handshakeId:g},f)}processProtocolMessage(g,f,S,v){return asap((()=>{this._processProtocolMessage(g,f,S,v)}))}_raiseControlRequestCanceled(g){this.event("sharingIncomingControlRequestCancelled").raise(g.participant.id)}_handleControlRequest(g,f,S,v){this._recordSharerSessionTelemetry((S=>S.controlRequest(v,g,f))),this._enabled?this._controlRequest?(this._logger.warn("Sharer is already processing a control request...rejecting new requests"),this._sendControlRejectRequest(v,3,g,f)):this._controllerParticipant&&this._controllerParticipant.participant===g?this._controllerParticipant.participantId&&this._controllerParticipant.participantId!==S?(this._logger.warn(`rejecting control request from second endpoint. participantId: ${S}`),this._sendControlRejectRequest(v,3,g,f)):(this._logger.warn("Got control request for someone already in control"),this._resetControllerParticipant(),this._resetControlRequest({participant:g,participantState:g.state,participantId:S,causeId:v})):g?(this._logger.info(`resetControlRequest for participantId: ${S}`),this._resetControlRequest({participant:g,participantState:g.state,participantId:S,causeId:v})):this._logger.error("Got ControlRequest message but could not find a sender participant, ignoring"):(this._logger.warn("Sharer control is disabled - rejecting request"),this._sendControlRejectRequest(v,9,g,f))}_handleAcceptRequest(g,f){if(1===this.controlState){const S=this._sendRequest({action:5,terminatedReason:0},f);this._logger.info(`_handleAcceptRequest controlMessage.action: ${toControlActionString(g.action)} _sendRequest isSent: ${S}`),S?(this._setupViewerRemoteControl(),this.controlState=4,this._requestControlPromise?this._requestControlPromise.resolve():this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${toControlActionString(g.action)}`),this._recordViewerSessionTelemetry((g=>g.requestControlAccepted(this._controlCauseId,f)))):this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:void 0,details:"request control is accepted, but failed to send ack"}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)} action=${toControlActionString(g.action)}`),this._cancelRequestControlTimer()}else this._logger.warn(`AcceptRequest message received in controlState=${toControlStateString(this.controlState)}`)}_handleRejectRequest(g,f){if(1===this.controlState){this._logger.info(`_handleRejectRequest: controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(0)}`),this.controlState=0;const S={inControl:!1,id:xs,terminatedReason:g.terminatedReason};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:S,details:""}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${toControlActionString(g.action)}`),this._recordViewerSessionTelemetry((S=>S.requestControlRejected(this._controlCauseId,g.terminatedReason,f))),this._cancelRequestControlTimer(),this._controlCauseId=null}else this._logger.warn(`RejectRequest message received in controlState=${toControlStateString(this.controlState)} reason=${g.terminatedReason}`)}_handleCancelControlRequest(g,f){if(this._logger.info(`_handleCancelControlRequest action=${toControlActionString(g.action)} sender=${f}, controlRequest participantId: ${this._controlRequest.participantId}, controlRequest participantState: ${this._controlRequest.participantState}:`),this._controlRequest){const S=this._controlRequest;this._logger.info(`_handleCancelControlRequest action=${toControlActionString(g.action)} sender=${f}, about to raise: _raiseControlRequestCanceled state: ${this._controlRequest.participantState} `),this._recordSharerSessionTelemetry((v=>v.controlRequestRejected(g.causeId,g.terminatedReason,S.participant,f))),this._clearControlRequest(),this._raiseControlRequestCanceled(S)}}_handleGiveControl(g,f,S){const v=this._sendRequest({action:5,terminatedReason:0},f);if(this._logger.info(`_handleGiveControl: controlMessage.action: ${toControlActionString(g.action)} _sendRequest isSent: ${v}`),this._controlCauseId=g.causeId,v){this._setupViewerRemoteControl(),this._logger.info(`controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(4)}`),this.controlState=4,this._recordViewerSessionTelemetry((g=>g.controlGiven(this._controlCauseId,f)));const S={inControl:!0,id:xs,terminatedReason:g.terminatedReason};this.event("sharingControlChanged").raise(S)}}_handleAck(g,f,S){if(2===this.controlState)if(this._controllerParticipant&&this._controllerParticipant.participant.id===f.id){const f=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);S!==f&&this._logger.warn(`acknowledging source id: ${S} does not match requesting source id: ${f}`),this._logger.info(`Setting up remote control for controller source id=${f}`),this._setupSharerRemoteControl(f),this._logger.info(`controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(3)}`),this.controlState=3;const v={inControl:!0,id:this._controllerParticipant.participant.id,terminatedReason:g.terminatedReason};this.event("sharingControlChanged").raise(v),this._grantControlPromise?(this._grantControlPromise.resolve(),this._cancelGrantControlTimer(),this._recordSharerSessionTelemetry((g=>g.giveControlSucceeded(this._controlCauseId,this._controllerParticipant.participant,f)))):this._acceptControlPromise?(this._acceptControlPromise.resolve(),this._cancelAcceptControlTimer(),this._recordSharerSessionTelemetry((g=>g.controlRequestAccepted(this._controlCauseId,this._controllerParticipant.participant,f)))):this._logger.error(`Unexpected, no promise could be resolved - controlState=WaitingForControlAck action=${toControlActionString(g.action)}`)}else f?this._logger.warn(`Ignoring ack from participant that does not match controller id=${scrubMriOrOmit(f.id)}`):this._logger.warn(`Ignoring ack from null participant source id=${S}`);else 5===this.controlState?(this._logger.info(`controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(0)}`),this.controlState=0,this._resetControllerParticipant(),this._terminateControlPromise?(this._terminateControlPromise.resolve(),this._cancelTerminateControlTimer()):this._logger.error(`Unexpected, no promise could be resolved - controlState=WaitingForTerminateAck action=${toControlActionString(g.action)}`)):this._logger.warn(`Unexpected ack in control controlState=${toControlStateString(this.controlState)}`)}_handleTerminate(g,f,S){let v;this._isViewing()?(this._teardownViewerRemoteControl(),v=xs,this._recordViewerSessionTelemetry((f=>f.controlTerminated(this._controlCauseId,g.terminatedReason,S,!0)))):(this._teardownSharerRemoteControl(),f?v=f.id:this._logger.error("Got terminate message but could not find a sender participant!"),this._recordSharerSessionTelemetry((f=>f.controlTerminated(this._controlCauseId,g.terminatedReason,this._controllerParticipant.participant,S,!0)))),this._logger.info(`controlMessage action: ${toControlActionString(g.action)}, controllerId: ${v}`),this._logger.info(`controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(0)}`),this.controlState=0,this._resetControllerParticipant();const C={inControl:!1,id:v,terminatedReason:g.terminatedReason};this.event("sharingControlChanged").raise(C),8===g.action&&this._sendRequest({action:5,terminatedReason:0},S)}_handleAvailableAck(g){this._terminateAvailableHandshake&&(this._logger.info(`_handleAvailableAck: terminate available handshake reason: 1,handshakeId: ${g.handshakeId}`),this._terminateAvailableHandshake(1,g.handshakeId)),2===this._role?this._raiseScreenSharingControlCapableEvent(!0,xs):this._logger.info(`Ignoring AvailableAck as viewer session is not initialized, role: ${this._role}`)}_handleAvailableNack(g){this._logger.info(`_handleAvailableNack: action=${toControlActionString(g.action)} terminate reason: ${toControlTerminatedReason(g.terminatedReason)}`),this._viewerSessionLastTerminatedReason=g.terminatedReason,10!==g.terminatedReason?(this._terminateAvailableHandshake&&(this._terminateAvailableHandshake(this._getAvailableHandshakeTerminatedFromControlTerminated(g.terminatedReason),g.handshakeId),this._logger.info(`_handleAvailableNack: terminateAvailableHandshake reason=${toControlTerminatedReason(g.terminatedReason)}`)),1===g.terminatedReason?(this._logger.warn("_handleAvailableNack: control terminate reason: SharerDenied"),this._raiseScreenSharingControlCapableEvent(!0,xs,!0)):this._raiseScreenSharingControlCapableEvent(!1,xs)):this._logger.warn("_handleAvailableNack: control terminate reason: UnknownSender")}_handleRenderedAtViewer(g,f){this._raiseRenderedAtViewer&&(f?(this._logger.info(`raiseRenderedAtViewer senderId=${scrubMriOrOmit(f.id)}, action=${toControlActionString(g.action)}`),this._raiseRenderedAtViewer(f.id)):this._logger.error("Got RenderedAtViewer message but could not find a sender participant!"))}_processProtocolMessage(g,f,S,v){let C;this._recordSessionTelemetry((g=>g.recordProtocolMessage(f,v)));try{C=JSON.parse(g)}catch(g){return void this._logger.error("Error parsing controlMessage")}switch(f||this._logger.warn(`protocol message from unknown sender with sourceId=${v}`),this._logger.info(`_processProtocolMessage action=${toControlActionString(C.action)}, sourceId=${v}`),C.action){case 0:this._handleAvailableRequest(C,f,v);break;case 1:this._handleControlRequest(f,v,S,C.causeId);break;case 3:this._handleAcceptRequest(C,v);break;case 4:this._handleRejectRequest(C,v);break;case 2:this._handleCancelControlRequest(C,v);break;case 6:this._handleGiveControl(C,v,f);break;case 5:this._handleAck(C,f,v);break;case 8:case 7:this._handleTerminate(C,f,v);break;case 9:this._handleAvailableAck(C);break;case 10:this._handleAvailableNack(C);break;case 11:this._handleRenderedAtViewer(C,f);break;default:this._logger.error(`Unknown request action received on control protocol data sink, action=${toControlActionString(C.action)}`)}}_getAvailableHandshakeTerminatedFromControlTerminated(g){switch(g){case 10:return 6;case 1:return 7;default:return 0}}_sendRequest(g,f){if(f<0)return this._logger.warn(`Unexpected: invalid sourceID=${f}`),!1;this._logger.info(`_sendRequest() action=${toControlActionString(g.action)} recipient sourceid=${f}`);const S={type:0,message:JSON.stringify(g)},v=[f];return this._dataChannelAdapter.sendProtocolMessage(stringToBuffer(JSON.stringify(S)),v),!0}async processControlMessage(g,f){if(f===this._controllerSourceId){if(3===this.controlState)return this._processControlMessage(g,f);this._logger.debug(`Ignoring control message, wrong controlState. Expected: RemoteControlling, got: ${toControlStateString(this.controlState)}`)}else this._logger.debug(`Ignoring control message, wrong sourceId. Expected: ${f}, got: ${this._controllerSourceId}`)}_processControlMessage(g,f){return this._controlInjector.injectRawInput(g,f)}_resetControlState(){this._logger.info("_resetControlState()"),this.controlState=0,this._resetControllerParticipant(),this._sharerParticipant=null,this._controlCauseId=null,this._clearControlRequest(),this._cancelRequestControlTimer(),this._cancelAcceptControlTimer(),this._cancelGrantControlTimer(),this._cancelTerminateControlTimer()}_setupSharerRemoteControl(g){this._logger.info(`_setupSharerRemoteControl() sourceId=${g}`),this._controllerSourceId=g,this._controlInjector.showVirtualCursor(g).catch((f=>{const S={reason:3,detail:JSON.stringify({sourceId:g,errorMsg:f})};this.event("sharingControlError").raise(S)}))}_teardownSharerRemoteControl(){this._logger.info("_teardownSharerRemoteControl()"),this._controllerSourceId=null,this._controlInjector.showVirtualCursor(0).catch((g=>{const f={reason:3,detail:JSON.stringify({sourceId:0,errorMsg:g})};this.event("sharingControlError").raise(f)}))}_setupViewerRemoteControl(){this._logger.info("_setupViewerRemoteControl()"),this._setCapturerMode(3)}_teardownViewerRemoteControl(){this._logger.info("_teardownViewerRemoteControl()"),this._setCapturerMode(0)}_clearCapturerEventSubscriptions(){this._logger.info("_clearCapturerEventSubscriptions()"),this._captureEventSubscription&&(this._captureEventSubscription.dispose(),this._captureEventSubscription=null),this._mouseControlEventSubscription&&(this._mouseControlEventSubscription.dispose(),this._mouseControlEventSubscription=null),this._keyboardControlEventSubscription&&(this._keyboardControlEventSubscription.dispose(),this._keyboardControlEventSubscription=null)}sendRemoteControlEvent(g,f){if(f)switch(g){case"mouseControlEvent":this._sendControlEvent(gs.encodeMouseEvent(f));break;case"keyboardControlEvent":this._sendControlEvent(gs.encodeKeyboardEvent(f));break;default:return void this._logger.error("sendRemoteControlEvent: Invalid type=",g)}else this._logger.error("sendRemoteControlEvent: Invalid argument.")}_sendControlEvent(g){if(!this._isDataChannelActive()||!this._sharerParticipant||4!==this.controlState)return void this._logger.error(`_sendControlEvent: Dropping message - No data channel or wrong controlState. dataConnected: ${this._isDataChannelActive()} controlState: ${toControlStateString(this.controlState)})`);const f=[this._getSharerDataSourceId()];this._dataChannelAdapter.sendControlMessage(g,f)}_setCapturerMode(g){this._logger.info(`_setCapturerMode() capturerMode=${g}`),this._controlCapturer?(this._controlCapturer.setCaptureMode(g),this._clearCapturerEventSubscriptions(),1===g?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(g=>{0===g&&this.event("sharingRendererClicked").raise()})):2===g?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(g=>{1===g?this.event("sharingRendererMouseEntering").raise():2===g&&this.event("sharingRendererMouseLeaving").raise()})):3===g&&(this._mouseControlEventSubscription=this._controlCapturer.on("mouseControlEvent",(g=>{this._sendControlEvent(gs.encodeMouseEvent(g))})),this._keyboardControlEventSubscription=this._controlCapturer.on("keyboardControlEvent",(g=>{this._sendControlEvent(gs.encodeKeyboardEvent(g))})),this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(g=>{1===g?this.event("sharingRendererMouseEntering").raise():2===g&&this.event("sharingRendererMouseLeaving").raise()})))):this._logger.info("_controlCapturer not set, relying on external controlCapturer")}setPointerImage(g,f){return this._logger.warn("setPointerImage is deprecated. Use setLocalPointerImage or setRemotePointerImage"),g?this.setRemotePointerImage(g,f):this.setLocalPointerImage(f)}setLocalPointerImage(g){return 0===g.length?Promise.reject(new Error("setLocalPointerImage invalid image length")):this._setPointerImage(0,g)}async setRemotePointerImage(g,f){if(!g)throw new Error("setRemotePointerImage participant is null");if(0===f.length)throw new Error("setRemotePointerImage invalid image length");const S=this._getParticipantsDataSourceIds(g);if(0===S.length)throw new Error("setRemotePointerImage unable to map participant to sourceIds");this._logger.info(`set pointer image for ${S.length} sources`);for(const g of S)await this._setPointerImage(g,f)}_setPointerImage(g,f){return this._isSharing()||this._logger.warn("_setPointerImage called when not sharing"),this._controlInjector.setPointerImage(g,f)}startPointerMode(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`startPointerMode called in bad control controlState=${toControlStateString(this.controlState)}`)):this._isViewing()?asap((()=>{this._setCapturerMode(2)})):Promise.reject(new Error("startPointerMode when not viewing")):Promise.reject(new Error("startPointerMode when data channel not active")):Promise.reject(new Error("startPointerMode when feature not enabled"))}stopPointerMode(){return 0!==this.controlState?Promise.reject(new Error(`stopPointerMode called in bad control controlState=${toControlStateString(this.controlState)}`)):this._isViewing()?asap((()=>{this._setCapturerMode(1)})):Promise.reject(new Error("stopPointerMode when not viewing"))}_startAvailableHandshake(){const g=this._getSharerDataSourceId(),f=generateGuid(),S=this._getHandshakeDelay(),v=Math.floor(Math.random()*S);if(this._logger.info(`_startAvailableHandshake() - handshakeId: ${g}:${f} ${v>0?`delay: ${v}ms maxDelay: ${S}ms`:""}}`),this._terminateAvailableHandshake&&(this._logger.warn("Replacing existing availble handshake"),this._terminateAvailableHandshake(4)),this._recordViewerSessionTelemetry((g=>g.startHandshake(f))),g<0)this._logger.warn(`_startAvailableHandshake() - sharer: ${scrubMriOrOmit(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(f);else{const sendAvailableHandshake=()=>{this.event("controlAvailableHandshake").raise(f,g,1);this._sendRequest({action:0,terminatedReason:0,handshakeId:f},g)||this._logger.error("Failed to send Available message to sharer, will retry after backoff"),this._waitForAvailableAck(f)};v>0?(this._delayedSendHandshakeTimer=window.setTimeout(sendAvailableHandshake,v),this._recordViewerSessionTelemetry((g=>g.delayHandshakeSending(f,v,S)))):sendAvailableHandshake()}this._availableHandshakeSent=!0,this._terminateAvailableHandshake=(S=0,v)=>{this._logger.info(`_terminateAvailableHandshake() - handshakeId: ${g}:${f}, status: ${S}`),1===S?this._recordViewerSessionTelemetry((g=>g.handshakeSucceeded(f,this._retryAttempt))):(this._logger.error(`GTC handshake terminated with code ${S}, last terminated reason: ${toControlTerminatedReason(this._viewerSessionLastTerminatedReason)}`),Ds.RootToolsManager.logExternalForDDL(`GTC handshake terminated with code ${S},`,this._viewerSessionLastTerminatedReason.toString()),this._recordViewerSessionTelemetry((g=>g.handshakeFailed(f,this._retryAttempt,S)))),this._terminateAvailableHandshake=null,this.event("controlAvailableHandshake").raise(f,g,1===S?5:6,S),v&&v!==f&&this._logger.warn(`AvailableSeries: Got handshake from another series - expected: ${f}, received: ${v}`),this._availableAckTimer&&(clearTimeout(this._availableAckTimer),this._availableAckTimer=null),this._delayedSendHandshakeTimer&&(clearTimeout(this._delayedSendHandshakeTimer),this._delayedSendHandshakeTimer=null),this._retryAttempt=0}}_waitForAvailableAck(g){this._logger.info("_waitForAvailableAck()"),this._availableAckTimer=window.setTimeout((()=>{this._logger.warn(`No Ack received for Available message from attempt=${this._retryAttempt}`),this._availableAckTimer=null;const f=this._getSharerDataSourceId();if(this._retryAttempt<=Fs)f>=0?(this._logger.info(`Re-sending Available message handshakeId: ${f}:${g}`),this.event("controlAvailableHandshake").raise(g,f,2),this._sendRequest({action:0,terminatedReason:0,handshakeId:g},f)):this._logger.warn(`_waitForAvailableAck() - sharer: ${scrubMriOrOmit(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(g);else{if(this._logger.error("Reached Available retry limit! Control capability will be false"),this._terminateAvailableHandshake)this._terminateAvailableHandshake(5);else{const g={reason:4,detail:JSON.stringify({sourceId:f,errorMsg:`Timed out after ${this._retryAttempt} tries`})};this.event("sharingControlError").raise(g)}this._raiseScreenSharingControlCapableEvent(!1,xs)}}),Ls*++this._retryAttempt)}requestControl(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`requestControl called in bad controlState=${toControlStateString(this.controlState)}`)):this._isViewing()?this._sharerParticipant?this._requestControlPromise?Promise.reject(new Error("request control promise has not been resolved yet while requesting control")):this._terminateControlPromise?Promise.reject(new Error("terminate control promise has not been resolved yet while requesting control")):this._requestControl():Promise.reject(new Error("requestControl unexpected null sharer")):Promise.reject(new Error("requestControl when not viewing")):Promise.reject(new Error("requestControl when data channel not active")):Promise.reject(new Error("requestControl when feature not enabled"))}_requestControl(){const g=this._controlCauseId=generateCauseId();this._logger.info(`_requestControl(), controlState: ${this.controlState}, controlCauseId: ${g}`),this._requestControlPromise=new dt;const always=()=>{this._requestControlPromise=null};this._requestControlPromise.promise.then(always,always);const f=this._getSharerDataSourceId();if(!this._sendRequest({action:1,terminatedReason:0,causeId:g},f)){const g={inControl:!1,id:xs,terminatedReason:7};return this._requestControlPromise.reject(new Error),this._logger.error("_requestControl(): failed to send the request."),Promise.reject(new Error(JSON.stringify({controlInfo:g,details:""})))}return this._recordViewerSessionTelemetry((S=>S.requestControl(g,f))),this.controlState=1,this._requestControlTimer=window.setTimeout((()=>{if(1===this.controlState){this.controlState=0,this._controlCauseId=null,this._logger.warn("No response to control request - canceling");this._sendRequest({action:2,terminatedReason:2,causeId:g},f)||this._logger.error("Failed to send the cancel control request");const S={inControl:!1,id:xs,terminatedReason:2};this._recordViewerSessionTelemetry((v=>v.requestControlRejected(g,S.terminatedReason,f))),this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:S,details:"we did not get any response to the control - terminating control"}))):this._logger.error("Unexpected, no promise could be resolved - controlState=RequestSent")}else this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:void 0,details:"request control - times out in bad state - do nothing"}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)}`);this._requestControlTimer=null}),Ns),this._requestControlPromise.promise}_cancelRequestControlTimer(){this._requestControlTimer&&(this._requestControlPromise&&this._requestControlPromise.reject(new Error("cancelled by _cancelRequestControlTimer")),clearTimeout(this._requestControlTimer),this._requestControlTimer=null)}cancelControl(){return this._enabled?this._isDataChannelActive()?1!==this.controlState?Promise.reject(new Error(`cancelControl called in bad state=${toControlStateString(this.controlState)}`)):this._isViewing()?this._sharerParticipant?this._requestControlPromise?this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while cancelling control")):this._cancelControl():Promise.reject(new Error("Request control promise has been resolved while cancelling control")):Promise.reject(new Error("cancelControl unexpected null sharer")):Promise.reject(new Error("cancelControl when not viewing")):Promise.reject(new Error("cancelControl when data channel not active")):Promise.reject(new Error("cancelControl when feature not enabled"))}_cancelControl(){this._logger.info("_cancelControl()");const g=this._getSharerDataSourceId();if(1!==this.controlState)return Promise.reject(new Error("Cancel control - in bad state - do nothing"));this._cancelRequestControlTimer(),this.controlState=0,this._logger.info("Viewer cancels the control");if(!this._sendRequest({action:2,terminatedReason:8,causeId:this._controlCauseId},g))return Promise.reject(new Error("Failed to send cancel control request"));{const f={inControl:!1,id:xs,terminatedReason:8};this._recordViewerSessionTelemetry((S=>S.requestControlRejected(this._controlCauseId,f.terminatedReason,g))),this._controlCauseId=null,this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:f,details:""})))}return new Promise(((g,f)=>{g()}))}acceptControlRequest(){return this._enabled?this._isDataChannelActive()?this._controlRequest?this._isSharing()?this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while accepting control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while accepting control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while accepting control")):this._acceptControlRequest():Promise.reject(new Error("acceptControlRequest when not sharing")):Promise.reject(new Error("acceptControlRequest while no control request pending")):Promise.reject(new Error("acceptControlRequest when data channel not active")):Promise.reject(new Error("acceptControlRequest when feature not enabled"))}async _acceptControlRequest(){this._logger.info("_acceptControlRequest()"),this._acceptControlPromise=new dt;const always=()=>{this._acceptControlPromise=null};if(this._acceptControlPromise.promise.then(always,always),this._controllerParticipant){this._logger.warn("_acceptControlRequest called while another participant already has control - terminating control");try{await this._terminateControl(!1)}catch(g){this._logger.error("_acceptControlRequest: failed to gracefully terminate control of previous controller",g)}this._resetControllerParticipant()}const g=this._getDataSourceIdForParticipantLeg(this._controlRequest),f=this._controlRequest.participant.id,S=this._controlRequest.causeId,v=this._controlRequest.participant;return this._sendControlAcceptRequest(S,v,g)?(this._resetControllerParticipant(this._controlRequest),this._clearControlRequest(),this.controlState=2,this._acceptControlTimer=window.setTimeout((()=>{if(2===this.controlState){this.controlState=0,this._resetControllerParticipant(),this._logger.error("No ack received when accepting control request - terminating control");this._sendRequest({action:7,terminatedReason:4,causeId:S},g)||this._logger.error("Failed to send the TerminateNoAck request");const C={inControl:!1,id:f,terminatedReason:4};this._recordSharerSessionTelemetry((f=>f.controlRequestRejected(S,C.terminatedReason,v,g))),this.event("sharingControlChanged").raise(C),this._acceptControlPromise?this._acceptControlPromise.reject(new Error("No ack received when accept control - terminating control")):this._logger.error("Unexpected, no promise could be resolved - controlState=WaitingForControlAck")}else this._acceptControlPromise?this._acceptControlPromise.reject(new Error("accept control - times out in bad state - do nothing")):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)}`);this._acceptControlTimer=null}),ks),this._acceptControlPromise.promise):(this._logger.error("Failed to send the accept control request"),this._acceptControlPromise.reject(new Error),Promise.reject(new Error("Failed to send the accept control request!")))}_sendControlAcceptRequest(g,f,S){const v=this._sendRequest({action:3,terminatedReason:0,causeId:g},S);return this._recordSharerSessionTelemetry((v=>v.controlRequestAccept(g,f,S))),v}_sendControlRejectRequest(g,f,S,v){const C=this._sendRequest({action:4,terminatedReason:f},v);return this._recordSharerSessionTelemetry((C=>C.controlRequestRejected(g,f,S,v))),C}_cancelAcceptControlTimer(){this._acceptControlTimer&&(this._acceptControlPromise&&this._acceptControlPromise.reject(new Error("cancelled by _cancelAcceptControlTimer")),clearTimeout(this._acceptControlTimer),this._acceptControlTimer=null)}denyControlRequest(){return this._enabled?this._isDataChannelActive()?this._controlRequest?this._isSharing()?this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while denying control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while denying control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while denying control")):this._denyControlRequest():Promise.reject(new Error("denyControlRequest when not sharing")):Promise.reject(new Error("denyControlRequest while no control request pending")):Promise.reject(new Error("denyControlRequest when data channel not active")):Promise.reject(new Error("denyControlRequest when feature not enabled"))}_denyControlRequest(){this._logger.info("_denyControlRequest()");const g=this._getDataSourceIdForParticipantLeg(this._controlRequest),f=this._sendControlRejectRequest(this._controlRequest.causeId,1,this._controlRequest.participant,g);return this._clearControlRequest(),f?Promise.resolve():Promise.reject(new Error("Failed to send the deny control requst"))}grantControl(g){return this._enabled?this._isDataChannelActive()?this._controlRequest?Promise.reject(new Error("grantControl called while control request pending")):this._isSharing()?g?this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while granting control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while granting control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while granting control")):this._grantControl(g):Promise.reject(new Error("grantControl null participant")):Promise.reject(new Error("grantControl when not sharing")):Promise.reject(new Error("grantControl when data channel not active")):Promise.reject(new Error("grantControl when feature not enabled"))}_grantControl(g){this._logger.info("_grantControl()"),this._grantControlPromise=new dt;const always=()=>{this._grantControlPromise=null};if(this._grantControlPromise.promise.then(always,always),3===this.controlState){if(this._controllerParticipant.participant?.id===g.id)return this._logger.warn("_grantControl called for participant who already has control"),this._grantControlPromise.resolve(),new Promise(((g,f)=>{g()}));{this._logger.warn("_grantControl called while another participant already has control - terminating control"),this._teardownSharerRemoteControl();const g=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);this._sendRequest({action:7,terminatedReason:5},g)||this._logger.error("Failed to send the terminateNoAck request")}}const f=this._mapParticipantToSourceId(g),S=generateCauseId(),v=this._sendRequest({action:6,terminatedReason:0,causeId:S},f);if(this._recordSharerSessionTelemetry((v=>v.giveControl(S,g,f))),!v)return this._logger.error("Failed to send the grant control request"),this._grantControlPromise.reject(new Error),Promise.reject(new Error("Failed to send the grant control request!"));const C=this._getParticipantIdForDataSourceId(g,f);return this._resetControllerParticipant({participant:g,participantState:g.state,participantId:C,causeId:S}),this.controlState=2,this._grantControlTimer=window.setTimeout((()=>{if(2===this.controlState){this.controlState=0,this._resetControllerParticipant(),this._logger.error("No ack received when granting control - terminating control");this._sendRequest({action:7,terminatedReason:4},f)||this._logger.error("Failed to send the terminateNoAck request"),this._recordSharerSessionTelemetry((v=>v.giveControlFailed(S,4,g,f))),this._grantControlPromise?this._grantControlPromise.reject(new Error("No ack received when granting control - terminating control")):this._logger.error("Unexpected, no promise could be resolved - controlState=WaitingForControlAck")}else this._grantControlPromise?this._grantControlPromise.reject(new Error("Grant control - times out in bad state - do nothing")):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)}`);this._grantControlTimer=null}),ks),this._grantControlPromise.promise}_cancelGrantControlTimer(){this._grantControlTimer&&(this._grantControlPromise&&this._grantControlPromise.reject(new Error("cancelled by _cancelGrantControlTimer")),clearTimeout(this._grantControlTimer),this._grantControlTimer=null)}_mapParticipantToSourceId(g){return this._dataChannelAdapter.isActive()?getSourceIdForMediaType(g,3):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getParticipantsDataSourceIds(g){const f=[];try{if(g?.endpoints?.endpointDetails){if(1===g.endpoints.endpointDetails.length){const S=g.endpoints.endpointDetails[0];if(!S?.mediaStreams)return f.push(Ai),f}for(const S of g.endpoints.endpointDetails)if(S?.mediaStreams)for(const g of S.mediaStreams)if(3===mapMediaTypeStringToMediaType(g.type)){if(f.push(g.sourceId),f.length>=8)return this._logger.error("Excessive amount of data streams"),f;break}}}catch(g){this._logger.error(`_getParticipantsDataSourceIds caught exception error=${g}`)}return f}_getParticipantIdForDataSourceId(g,f){return getParticipantIdForSourceId(g,3,f)}_getDataSourceIdForParticipantId(g,f){return this._dataChannelAdapter.isActive()?getSourceId(g,f,3):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getDataSourceIdForParticipantLeg(g){return this._getDataSourceIdForParticipantId(g.participant,g.participantId)}_getSharerDataSourceId(){const g=getSharingParticipantLeg(this._sharerParticipant);return g?this._getDataSourceIdForParticipantId(this._sharerParticipant,g):(this._logger.warn("Unable to identify the sharer participantId, falling back to first data channel"),this._mapParticipantToSourceId(this._sharerParticipant))}getLocalEndpointDataSourceId(){const g=findSelfEndpointDetailUsingParticipantLegId(this._call,this._participantId);if(g?.mediaStreams){const f=g.mediaStreams.find((({type:g})=>3===mapMediaTypeStringToMediaType(g)));return f?.sourceId??-1}return-1}terminateControl(g){if(this._isViewing()){if(4!==this.controlState)return Promise.reject(new Error("terminateControl called while not in control"));if(!this._sharerParticipant)return Promise.reject(new Error("terminateControl called but _sharerParticipant is null"))}else{if(!this._isSharing())return Promise.reject(new Error("terminateControl called but not sharing nor viewing"));if(!this._controllerParticipant)return Promise.reject(new Error("terminateControl called but controllerParticipant is null"))}return this._requestControlPromise?Promise.reject(new Error("Request control promise has not been resolved yet while terminating control")):this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while terminating control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while terminating control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while terminating control")):this._terminateControl(!0,g)}_terminateControl(g,f){this._logger.info("_terminateControl()"),this._terminateControlPromise=new dt;const always=()=>{this._terminateControlPromise=null};this._terminateControlPromise.promise.then(always,always);let S=0;const v=g?8:7;let C,_;if(this._isViewing()){if(4!==this.controlState)return this._logger.error("Local viewer called terminateControl when not controlling"),this._terminateControlPromise.reject(new Error),Promise.reject(new Error("Local viewer called terminateControl when not controlling"));this._teardownViewerRemoteControl(),S=f??6,C=this._getSharerDataSourceId(),this._recordViewerSessionTelemetry((g=>g.controlTerminated(this._controlCauseId,S,C))),_=xs,this._logger.info(`Terminating remote control reason: ${toControlTerminatedReason(S)},  recipient: ${C}, controllerId: ${_}`)}else{if(3!==this.controlState||!this._controllerParticipant)return this._logger.error("Local sharer called terminateControl when no one is in control"),this._terminateControlPromise.reject(new Error),Promise.reject(new Error("Local sharer called terminateControl when no one is in control"));this._teardownSharerRemoteControl(),S=f??5,C=this._getDataSourceIdForParticipantLeg(this._controllerParticipant),this._recordSharerSessionTelemetry((g=>g.controlTerminated(this._controlCauseId,S,this._controllerParticipant.participant,C))),_=scrubMriOrOmit(this._controllerParticipant.participant.id),this._logger.info(`Terminating control on the sharer side, reason: ${toControlTerminatedReason(S)}, recipient: ${C}, controllerId: ${_}`)}const T={action:v,terminatedReason:S};if(!this._sendRequest(T,C)){if(g)return this._logger.error("Failed to send the terminate control request"),this._terminateControlPromise.reject(new Error),Promise.reject(new Error("Failed to send the grant control request!"));this._logger.error("Failed to send the terminateNoAck request")}this.controlState=g?5:0;const I={inControl:!1,id:_,terminatedReason:T.terminatedReason};return this._logger.info(`raising event sharingControlChanged reason=${toControlTerminatedReason(I.terminatedReason)} controlState=${toControlStateString(this.controlState)}`),this.event("sharingControlChanged").raise(I),g?(this._terminateControlTimer=window.setTimeout((()=>{if(5===this.controlState){this.controlState=0,this._resetControllerParticipant(),this._logger.error("No ack received when terminating control - resending terminate request");this._sendRequest({action:7,terminatedReason:4},C)||this._logger.error("Failed to send the terminateNoAck request"),this._terminateControlPromise?this._terminateControlPromise.reject(new Error("No ack received when terminating control - resending terminate request")):this._logger.error("Unexpected, no promise could be resolved - controlState=WaitingForTerminateAck")}else this._terminateControlPromise?this._terminateControlPromise.reject(new Error("terminate control - times out in bad state - do nothing")):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)}`);this._terminateControlTimer=null}),ks),this._terminateControlPromise.promise):(this._terminateControlPromise.resolve(),new Promise(((g,f)=>{g()})))}_cancelTerminateControlTimer(){this._terminateControlTimer&&(this._terminateControlPromise&&this._terminateControlPromise.reject(new Error("cancelled by _cancelTerminateControlTimer")),clearTimeout(this._terminateControlTimer),this._terminateControlTimer=null,this._logger.info("_cancelTerminateControlTimer()"))}_disposeControlCapturer(g=generateCauseId()){this._logger.info(`_disposeControlCapturer causeId: ${g}`),this._clearCapturerEventSubscriptions(),this._controlCapturer&&(this._controlCapturer.dispose(g),this._controlCapturer=null)}dispose(g){this._logger.info(`dispose causeId: ${g}`),this._dataChannelAdapter.dispose(g),this._resetControlState(),this._disposeRenderer(g),this._cancelRequestControlTimer(),this._cancelAcceptControlTimer(),this._cancelGrantControlTimer(),this._cancelTerminateControlTimer(),this._terminateAvailableHandshake&&this._terminateAvailableHandshake(2),this._call=null,this._resetParticipantSubscriptions(),this._finalizeViewerSessionTelemetry(),this._finalizeSharerSessionTelemetry(),super.dispose(g)}};function toAvailableHandshakeTerminatedString(g){switch(g){case 1:return"Succeeded";case 2:return"Shutdown";case 3:return"DataChannel";case 4:return"Replaced";case 5:return"TimedOut";case 6:return"UnknownSender";case 7:return"SharerDenied";default:return"Unknown"}}function toControlActionString(g){switch(g){case 0:return"Available";case 1:return"ControlRequest";case 2:return"CancelControlRequest";case 3:return"AcceptRequest";case 4:return"RejectRequest";case 5:return"Ack";case 6:return"GiveControl";case 7:return"TerminateNoAck";case 8:return"Terminate";case 9:return"AvailableAck";case 10:return"AvailableNack";case 11:return"RenderedAtViewer";default:return"Unknown"}}function toControlStateString(g){switch(g){case 0:return"None";case 1:return"RequestSent";case 2:return"WaitingForControlAck";case 3:return"RemoteControlling";case 4:return"LocalControlling";case 5:return"WaitingForTerminateAck";default:return"Unknown"}}function toControlTerminatedReason(g){switch(g){case 0:return"None";case 1:return"SharerDenied";case 2:return"SharerNoResponse";case 3:return"SharerBusy";case 4:return"AckTimeout";case 5:return"SharerTerminated";case 6:return"ViewerTerminated";case 7:return"DataChannelError";case 8:return"ViewerCancelled";case 9:return"SharerControlDisabled";case 10:return"UnknownSender";case 11:return"MultipleSharers";default:return"Unknown"}}function toSharingControlRole(g){switch(g){case 1:return"Sharer";case 2:return"Viewer";default:return"Unknown"}}var $s=(g=>(g[g.LEFT=0]="LEFT",g[g.RIGHT=1]="RIGHT",g[g.MIDDLE=2]="MIDDLE",g[g.BACK=3]="BACK",g[g.FORWARD=4]="FORWARD",g))($s||{}),js=(g=>(g[g.SCAN_CODE=0]="SCAN_CODE",g[g.VIRTUAL_KEY=1]="VIRTUAL_KEY",g[g.RECOGNITION_INPUT=2]="RECOGNITION_INPUT",g))(js||{}),Gs=class{constructor(g){this.logger=g}toEdgeControlMouseEvent(g){let f;switch(g.type){case 0:return{event:this.toMouseMoveEvent(g),apiName:"injectMouseMoveEvent"};case 1:return{event:this.toMouseWheelEvent(g),apiName:"injectMouseWheelEvent"};case 2:return{event:this.toMouseButtonPressedEvent(g),apiName:"injectMouseButtonEvent"};default:throw f=`Uncovered mouse control event type. Event: ${g}`,this.logger.error(f),Error(f)}}toEdgeControlKeyboardEvent(g){return{event:{repeat:g.repeat,keyUp:g.keyUp,codeType:js[g.codeType],keyCode:g.code},apiName:"injectKeyEvent"}}toMouseMoveEvent(g){return{xPos:g.xPos,yPos:g.yPos}}toMouseWheelEvent(g){return{wheelButtonDown:g.wheelButtonDown,wheelRotation:g.wheelRotation}}toMouseButtonPressedEvent(g){return{xPos:g.xPos,yPos:g.yPos,button:$s[g.buttonType],buttonDown:g.buttonDown}}};async function pngBase64ToBitmap(g,f,S){return new Promise(((v,C)=>{const _=Buffer.from(g,"base64"),T=document.createElement("canvas").getContext("2d"),I=new Blob([_],{type:"image/png"});let b=new Image;b.onload=()=>{T.drawImage(b,0,0,b.width,b.height,0,0,f,S);const g=T.getImageData(0,0,f,S);window.URL.revokeObjectURL(b.src),b=null,v(Array.from(g.data))},b.onerror=g=>{C(g)},b.src=window.URL.createObjectURL(I)}))}var qs="ncbjelpjchkpbikbpkcchkhkblodoama",Ws=class{constructor(g){this.logger=g}async sendInjectInputEventMessage(g,f){return this.logger.info("EdgeControlInjectorApi - sendInjectInputEventMessage"),new Promise(((S,v)=>{window.top.chrome.runtime.sendMessage(qs,{api:g,deviceId:this.virtualInputDeviceId,event:f},(g=>{g.error?v(g.error.message):S(0)}))}))}async createInputDeviceId(g,f,S){this.virtualInputDeviceId&&this.logger.warn("EdgeControlInjectorApi - createInputDeviceId virtual input already exists.");try{this.virtualInputDeviceId=await this.sendCreateInputDeviceMessage(g,S)}catch(g){this.logger.error(`EdgeControlInjectorApi - createInputDevice failed, error: ${JSON.stringify(g)}`),f()}}async sendSetLocalUserAvatarMessage(g){const f=await this.generateAvatarBitmap(g);return new Promise(((g,S)=>{const v=window.top;f&&v.chrome.runtime.sendMessage(qs,{api:"setLocalUserAvatar",avatarBitmap:f},(f=>{f.error?S(f.error.message):g()}))}))}async sendCloseVirtualInputDeviceMessage(){const g=this.virtualInputDeviceId;return g?(this.logger.info("EdgeControlInjectorApi - sendCloseVirtualInputDeviceMessage called"),new Promise(((f,S)=>{const v=window.top;v.chrome.runtime.sendMessage(qs,{api:"closeInputDevice",deviceId:g},(g=>{g?g.error?S(g.error.message):(this.virtualInputDeviceId=null,f(g.deviceId)):S(v.chrome.runtime.lastError.message)}))}))):(this.logger.info("EdgeControlInjectorApi - VirtualInputDevice does not exists, nothing to close."),Promise.resolve())}async sendCreateInputDeviceMessage(g,f){this.logger.info("EdgeControlInjectorApi - sendCreateInputDeviceMessage called");const S=await this.generateAvatarBitmap(f);return new Promise(((f,v)=>{const C=window.top,messageCallback=g=>{g?g.deviceId?f(g.deviceId):g.error?v(g.error.message):v("Error: Unexpected response from API"):v(C.chrome.runtime.lastError.message)};S?C.chrome.runtime.sendMessage(qs,{api:"createInputDevice",mediaStreamTrackId:g,avatarBitmap:S},messageCallback):C.chrome.runtime.sendMessage(qs,{api:"createInputDevice",mediaStreamTrackId:g},messageCallback)}))}async generateAvatarBitmap(g){if(!g)return null;try{const f=32;return{width:f,height:f,data:await pngBase64ToBitmap(g,f,f)}}catch(g){return this.logger.error(`EdgeControlInjectorApi - generateAvatarBitmap error: ${JSON.stringify(g)}, continue without avatar.`),null}}};async function sendIsVirtualInputSupportedMessage(g){return new Promise(((f,S)=>{g.info("EdgeControlInjectorApi - sendIsVirtualInputSupportedMessage");const v=window.top;v.chrome.runtime.sendMessage(qs,{api:"isVirtualInputSupported"},(g=>{g?g.error?f(g.error.message):f(g):S(v.chrome.runtime.lastError?.message)}))}))}var zs,Ks,Js=class{constructor(g,f,S){this.logger=g,this.sharingTrackId=f,this.onInitErrorCallback=S,this.images=new Map,this.controlEventConverter=new Gs(g),this.edgeApi=new Ws(this.logger)}showVirtualCursor(g,f){if(this.logger.info(`EdgeControlInjector - showVirtualCursor, id: ${g} sharingTrackId: ${this.sharingTrackId}`),f){this.edgeApi.createInputDeviceId(this.sharingTrackId,this.onInitErrorCallback,this.images[g]);const f=this.images[0];f?this.edgeApi.sendSetLocalUserAvatarMessage(f):this.logger.error("EdgeControllerInjector - local avatar is missing, continue without local avatar")}else this.edgeApi.sendCloseVirtualInputDeviceMessage()}setAvatar(g,f){this.logger.info(`${g} EdgeControlInjector - setAvatar, id: ${g}, data: ${JSON.stringify(f)}`),this.images[g]=f}async injectMouseEvent(g,f){this.logger.info(`${g} EdgeControlInjector - injectMouseEvent ${JSON.stringify(f)}`);const S=this.controlEventConverter.toEdgeControlMouseEvent(f);return this.edgeApi.sendInjectInputEventMessage(S.apiName,S.event)}async injectKeyboardEvent(g,f){const S=this.controlEventConverter.toEdgeControlKeyboardEvent(f);return this.edgeApi.sendInjectInputEventMessage(S.apiName,S.event)}injectClipboardText(g,f){return this.logger.info(`${g} EdgeControlInjector - injectClipboardText is unimplemented`),Promise.resolve(0)}dispose(g){this.logger.info("EdgeControlInjector - dispose"),this.edgeApi.sendCloseVirtualInputDeviceMessage()}},Ys="undefined"!=typeof navigator&&void 0!==navigator.mediaDevices?.getUserMedia,Qs=(g=>(g.AVD="43",g.Citrix="44",g.VMware="45",g))(Qs||{});function setAgentPlatformInfo(g=""){const f=g.match(new RegExp("^SkypeSpaces/(\\d+)/"));f?.length&&Object.values(Qs).includes(f[1])&&(Ks=f[1]),overrideGetUserMediaIfNeeded()}function isVdiPlatform(){return!!Ks}function getVdiPlatform(){return Ks}function overrideGetUserMediaIfNeeded(){"undefined"!=typeof window&&"undefined"!=typeof navigator&&(void 0!==navigator.webkitGetUserMedia&&"undefined"!=typeof webkitRTCPeerConnection&&isVdiPlatform()?(window.RTCPeerConnection=webkitRTCPeerConnection,navigator.getUserMedia=(g,f,S)=>{const polyfillDeviceId=g=>{g?.deviceId?.exact&&(g.mandatory||(g.mandatory={}),g.mandatory.sourceId=g.deviceId.exact,delete g.deviceId)};return g&&(polyfillDeviceId(g.audio),polyfillDeviceId(g.video)),navigator.webkitGetUserMedia(g,f,S)}):Ys&&overrideGumSourceFromWebkit())}function overrideGumSourceFromWebkit(){navigator.getUserMedia=function(g,f,S){return navigator.mediaDevices.getUserMedia(g).then(f).catch(S)}}"undefined"!=typeof window&&"undefined"!=typeof navigator&&(zs=window,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,window.MediaStream=window.MediaStream||window.webkitMediaStream||window.mozMediaStream||window.msMediaStream,window.AudioContext=window.AudioContext||window.webkitAudioContext);var Xs={window:zs},Zs=class{constructor(g){this.logger=g,this.activeSourceId=0,this.pendingPointerImages=new Map}static create(g,f){return g.config.enableGiveControl?isVdiPlatform()||window.ControlInjector?new ta(f):et.isBrowser("EdgeAnaheim")?new ea(f):new ia(f):new ia(f)}async enableInjector(g){this.injector&&this.logger.warn("Control injector already present when enabling injector");try{this.injector=this.createInjector(g)}catch(g){throw this.logger.error(`Control injector creation failed: ${g}`),g}this.pendingPointerImages.forEach(((g,f)=>{this.injector.setAvatar(f,g)})),this.pendingPointerImages.clear()}async disableInjector(){this.injector||this.logger.warn("Control injector not present when disabling injector"),this.logger.info("ControlInjector disposed"),this.injector.dispose(),this.injector=null}async setPointerImage(g,f){this.injector?this.injector.setAvatar(g,f):this.pendingPointerImages.set(g,f)}async showVirtualCursor(g){if(this.logger.info(`showVirtualCursor ${g} ${this.activeSourceId}`),!this.injector)throw new Error("Control injector not present");g?(this.activeSourceId&&this.injector.showVirtualCursor(this.activeSourceId,!1),this.injector.showVirtualCursor(g,!0),this.activeSourceId=g):this.activeSourceId&&(this.injector.showVirtualCursor(this.activeSourceId,!1),this.activeSourceId=0)}async injectRawInput(g,f){if(!this.injector)throw new Error("Control injector not present");const S=this.injector;return new Promise(((v,C)=>{let _,T;const I=gs.decodeEventType(g);switch(I){case 1:_=gs.decodeMouseEvent(g),S.injectMouseEvent(f,_).then((g=>0===g?v():C()));break;case 0:T=gs.decodeKeyboardEvent(g),S.injectKeyboardEvent(f,T).then((g=>0===g?v():C()));break;default:this.logger.error(`Invalid event type in raw input: ${I}`),C()}}))}},ea=class extends Zs{constructor(g){super(g.createChild("EdgeControlInjector")),this.edgeVirtualInputSupported=!1,sendIsVirtualInputSupportedMessage(g).then((f=>{this.edgeVirtualInputSupported=f,g.info(`Edge supports virtual input device: ${JSON.stringify(this.edgeVirtualInputSupported)}`)})).catch((f=>{g.info(`Edge IsVirtualInputSupported: ${JSON.stringify(f)}`)}))}canBeEnabled(){return this.edgeVirtualInputSupported}createInjector(g){if(!this.edgeVirtualInputSupported)return void this.logger.info("Edge doesn't support give control");const f=new Js(this.logger,g,(()=>{this.logger.error("An error occured, disabling control injector."),this.disableInjector()}));return this.logger.info("Edge ControlInjector created"),f}},ta=class extends Zs{constructor(g){super(g.createChild("WindowControlInjector"))}canBeEnabled(){return!!window.ControlInjector}createInjector(g){const f=window.ControlInjector(g);return this.logger.info("Window ControlInjector created"),f}},ia=class extends Zs{constructor(g){super(g.createChild("NoopControlInjector"))}canBeEnabled(){return!1}createInjector(){throw new Error("Control injector creation is disabled")}},na=class{constructor(g){this.logger=g,this.logger.info("RendererAdapter")}getTarget(g){return g.target}subscribeVideoSizeChangedEvent(g,f){const S=g;return S.streamSize&&f(S.streamSize.width,S.streamSize.height),S.renderer.on("onVideoSizeChanged",f)}subscribeRenderStartedEvent(g,f){return g.renderer.on("onVideoStarted",((g,S)=>f()))}};function bufferToString(g){return String.fromCharCode.apply(null,g)}var ra=class extends Ke{constructor(g,f){super(g),this.logger=g,this._call=f}isActive(){return!(!this.protocolSendFunc||!this.controlSendFunc)}sendProtocolMessage(g,f){return this.protocolSendFunc?this.protocolSendFunc(g,f):(this.logger.error("Cannot send protocol message, ProtocolHandler hasn't started"),Promise.resolve())}sendControlMessage(g,f){return this.controlSendFunc?this.controlSendFunc(g,f):(this.logger.error("Cannot send control message, ControlHandler hasn't started"),Promise.resolve())}getProtocolHandler(){return{onStarted:async(g,f)=>{this.logger.info(`ProtocolHandler started for ${g}`),this.protocolSendFunc=f,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async g=>{this.logger.info(`ProtocolHandler stopped for ${g}`);const f=this.isActive();this.protocolSendFunc=null,f&&this.event("stateChange").raise(!1)},onDataReceived:async(g,f,S)=>{if(1===g){const g=JSON.parse(bufferToString(f)),v=this._call.mapDataChannelSourceIdToParticipant(S);let C;return v&&(C=getParticipantIdForSourceId(v,3,S)),this.event("protocolMessage").raise(g.message,v,C,S)}}}}getControlHandler(){return{onStarted:async(g,f)=>{this.logger.info(`ControlHandler started for ${g}`),this.controlSendFunc=f,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async g=>{this.logger.info(`ControlHandler stopped for ${g}`);const f=this.isActive();this.controlSendFunc=null,f&&this.event("stateChange").raise(!1)},onDataReceived:async(g,f,S)=>{if(2===g)return this.event("controlMessage").raise(f,S)}}}},sa=class extends Hs{constructor(g,f,S,v,C,_){const T={disableAudit:C.getEcsConfig("SkypeCalling","gtcAuditDisabled")??!1},I=C.getEcsConfig("SkypeCalling","gtcHandshakeSendDelay");if(I)try{T.handshakeSendDelay=JSON.parse(I)}catch(f){g.error(`Failed to parse ecs config gtcAvailableAckDelay: ${stringifyObject(f)}`)}super(g.createChild("ScreenSharingControl"),S,v,T),this.dataChannel=f;const b=Zs.create(_,g),A=new na(this._logger),P=new ra(this._logger,S);this.setAdapters(b,A,P)}setupDataHandlers(){this.dataChannel.addHandler(1,this.getProtocolHandler()),this.dataChannel.addHandler(2,this.getControlHandler())}startOrStopControlForViewer(g,f,S){if(g&&"nonInteractive"!==S?.appliedInteractivityLevel){if(f&&0===this.role){const g=f.streams[1].find((g=>g.isAvailable))?.negotiationTag;this.initControlForViewer(f,g)}}else 2===this.role&&this.shutdownControlForViewer()}getProtocolHandler(){return this._dataChannelAdapter.getProtocolHandler()}getControlHandler(){return this._dataChannelAdapter.getControlHandler()}};function createParticipantListFromMriMap(g){const f=[];for(const S in g)if(g[S].participantLegIdMap)for(const v in g[S].participantLegIdMap){const C=g[S].participantLegIdMap[v].endpointId;f.push({id:S,mri:S,participantId:v,...C&&{endpointId:C}})}else f.push({id:S,mri:S});return f}function mapParticipantScope(g){switch(g){case 1:return"specified";case 0:return"all";case 3:return"attendees";case 2:return"presenters";case 4:return"self";default:return"none"}}var aa={};__export(aa,{addReceiveDirectionality:()=>addReceiveDirectionality,allowDataChannel:()=>allowDataChannel,areNegotiatedDirectionsAcceptable:()=>areNegotiatedDirectionsAcceptable,areNegotiatedDirectionsFulfilled:()=>areNegotiatedDirectionsFulfilled,areSendDirectionsFulfilled:()=>areSendDirectionsFulfilled,canUseWebrtc1_0:()=>canUseWebrtc1_0,convertToCodecInfo:()=>convertToCodecInfo,getAllowedCodecs:()=>getAllowedCodecs,getSrtpInfo:()=>getSrtpInfo,hasReceiveDirectionality:()=>hasReceiveDirectionality,hasSendDirectionality:()=>hasSendDirectionality,invertModalities:()=>invertModalities,ipAddressConverter:()=>ipAddressConverter,ipV4RegExp:()=>la,ipV6RegExp:()=>ca,ipv4AddressConverter:()=>ipv4AddressConverter,ipv6AddressConverter:()=>ipv6AddressConverter,isOnHold:()=>isOnHold,mediaTypeToModality:()=>mediaTypeToModality,modalityToMediaType:()=>modalityToMediaType,negotiateDirectionality:()=>negotiateDirectionality,negotiateModalities:()=>negotiateModalities,parseCandidateString:()=>parseCandidateString,preferSdesSrtp:()=>preferSdesSrtp,printMediaStream:()=>printMediaStream,removeChangedSendDirection:()=>removeChangedSendDirection,removeSendDirectionality:()=>removeSendDirectionality,scrubConstraints:()=>scrubConstraints,scrubDevices:()=>scrubDevices,scrubObjectExcludingFields:()=>scrubObjectExcludingFields,scrubObjectFields:()=>scrubObjectFields2,scrubSelectedDevices:()=>scrubSelectedDevices,sendStreamsToModalities:()=>sendStreamsToModalities,shouldDisableAudioSendersTroughSetParams:()=>shouldDisableAudioSendersTroughSetParams,shouldDisableVideoSendersTroughSetParams:()=>shouldDisableVideoSendersTroughSetParams});var oa=class _UserAgentConfig extends Ht{constructor(g){super(),this.isAudioOutputSelectionSupportedValue=!1,g.on("configUpdated",(()=>this.updateConfig())),this.updateConfig(),this.isRollbackSupported()}get isAudioOutputSelectionSupported(){return this.isAudioOutputSelectionSupportedValue}get isBrowserRollbackSupported(){return this.isRollbackSupportedValue}static hasApplyConstraints(){return void 0!==MediaStreamTrack.prototype.applyConstraints}static hasPermissionsApi(){return void 0!==navigator.permissions}static get hardwareConcurrency(){return window.navigator.hardwareConcurrency}static get unmaskedGlRenderer(){if(this.renderer)return this.renderer===qt.MEDIA_ERROR.webGlRendererError?void 0:this.renderer;try{const g=document.createElement("canvas").getContext("webgl"),f=g?.getExtension("WEBGL_debug_renderer_info"),S=f&&g.getParameter(f.UNMASKED_RENDERER_WEBGL);return this.renderer=S,S}catch{return void(this.renderer=qt.MEDIA_ERROR.webGlRendererError)}}async isRollbackSupported(){let g;try{if(g=Xs.window.RTCPeerConnection&&new Xs.window.RTCPeerConnection({sdpSemantics:"unified-plan"}),g){const f=await g.createOffer();await g.setLocalDescription(f),await g.setLocalDescription({type:"rollback"}),this.isRollbackSupportedValue=!0}}catch(g){this.isRollbackSupportedValue=!1}finally{g?.close()}}static async isCodecsSupported(g){const f={format:"annexb"},S=1280,v=720,C=["no-preference","prefer-software","prefer-hardware"],_=[];for(const T of g)for(const g of C){const C=await(window.VideoEncoder?.isConfigSupported({codec:T,hardwareAcceleration:g,hevc:f,width:S,height:v})),I=await(window.VideoDecoder?.isConfigSupported({codec:T,hardwareAcceleration:g,hevc:f}));if(C||I){const g={name:T,mode:C?.config.hardwareAcceleration,encode:C?.supported,decode:I?.supported};_.push(g)}}return _}static async hasH264CodecSupport(g){const f="v=0\no=- 596983 0 IN IP4 127.0.0.1\ns=session\nc=IN IP4 0.0.0.0\nt=0 0\na=msid-semantic: WMS *\nm=video 3480 RTP/SAVPF 107 99\na=rtpmap:107 H264/90000\na=rtpmap:99 rtx/90000\na=fmtp:107 max-fs=240;max-mbps=3600;max-br=208;max-fps=1500;profile-level-id=42C02A;packetization-mode=1\na=fmtp:99 apt=107\na=setup:actpass\na=mid:video\na=recvonly\na=rtcp-mux\na=ice-ufrag:CvYq\na=ice-pwd:axsjsa0GOz3kz6TuGvNgJZWO\na=fingerprint:sha-256 34:DF:5C:15:60:FF:28:3E:E8:96:4B:F8:85:61:E4:C0:57:D1:60:82:21:FD:BC:D2:90:41:06:FA:03:FD:12:A2\n",S=Xs.window.RTCPeerConnection&&new Xs.window.RTCPeerConnection;if(!S)return!1;try{return await S.setRemoteDescription({sdp:f,type:"offer"}),!0}catch(f){return g.error("H264 not supported",f),!1}finally{try{S.close()}catch(g){}}}static hasMediaApi(){return navigator.getUserMedia&&"undefined"!=typeof RTCPeerConnection}static hasCapabilitiesApi(){return!!Xs.window.RTCRtpReceiver?.getCapabilities}static isAudioOutputSelectionSupportedByBrowser(){return!!Xs.window?.HTMLAudioElement?.prototype.setSinkId}updateConfig(){const g=_UserAgentConfig.isAudioOutputSelectionSupportedByBrowser();g!==this.isAudioOutputSelectionSupportedValue&&(this.isAudioOutputSelectionSupportedValue=g,this.event("isAudioOutputSelectionSupportedChanged").raise())}static hasUnifiedPlanSupport(){let g;try{g=Xs.window.RTCPeerConnection&&new Xs.window.RTCPeerConnection({sdpSemantics:"unified-plan"})}catch(g){return!1}let f=!1;return g&&(f=!!g.addTransceiver,g.close()),f}static hasEncodedStreamsApi(){return!!RTCRtpReceiver.prototype.createEncodedStreams||_UserAgentConfig.hasScriptTransformApi()}static hasScriptTransformApi(){return!!window.RTCRtpScriptTransform}static isWakeLockSupported(){return!!window.navigator.wakeLock}},la=RegExp(/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/),ca=RegExp(/^\[?(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|:((:[0-9a-fA-F]{1,4}){1,5}|:)((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,5}([0-9a-fA-F]{1,4})?:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\]?(?::\d{1,5})?$/);function invertDirectionality(g){switch(g){case qt.MEDIA_STATE.send:return qt.MEDIA_STATE.receive;case qt.MEDIA_STATE.receive:return qt.MEDIA_STATE.send;default:return g}}function negotiateDirectionality(g,f){const S=hasSendDirectionality(g)&&hasSendDirectionality(f),v=hasReceiveDirectionality(g)&&hasReceiveDirectionality(f);return S&&v?qt.MEDIA_STATE.sendReceive:S?qt.MEDIA_STATE.send:v?qt.MEDIA_STATE.receive:g===qt.MEDIA_STATE.inactive&&f||g&&f===qt.MEDIA_STATE.inactive?qt.MEDIA_STATE.inactive:void 0}function invertModalities(g){const f={},S=invertDirectionality(g.audio);S&&(f.audio=S);const v=invertDirectionality(g.video);v&&(f.video=v);const C=invertDirectionality(g.sharing);C&&(f.sharing=C);const _=invertDirectionality(g.data);return _&&(f.data=_),f}function removeSendDirectionality(g){return g===qt.MEDIA_STATE.sendReceive?qt.MEDIA_STATE.receive:void 0}function hasSendDirectionality(g){return g===qt.MEDIA_STATE.send||g===qt.MEDIA_STATE.sendReceive}function hasReceiveDirectionality(g){return g===qt.MEDIA_STATE.receive||g===qt.MEDIA_STATE.sendReceive}function addReceiveDirectionality(g){return hasReceiveDirectionality(g)?g:g===qt.MEDIA_STATE.send?qt.MEDIA_STATE.sendReceive:qt.MEDIA_STATE.receive}function isOnHold(g){return!(g.audio!==qt.MEDIA_STATE.inactive||g.video&&g.video!==qt.MEDIA_STATE.inactive||g.sharing&&g.sharing!==qt.MEDIA_STATE.inactive)}function negotiateModalities(g,f){const S={},v=negotiateDirectionality(g.audio,f.audio);v&&(S.audio=v);const C=negotiateDirectionality(g.video,f.video);C&&(S.video=C);const _=negotiateDirectionality(g.sharing,f.sharing);_&&(S.sharing=_);const T=negotiateDirectionality(g.data,f.data);return T&&(S.data=T),S}function isNegotiatedDirectionAcceptable(g,f,S){const v=hasSendDirectionality(g)&&hasSendDirectionality(f)||!hasSendDirectionality(g)&&!hasSendDirectionality(S),C=!S||hasReceiveDirectionality(g)&&hasReceiveDirectionality(f)||!hasReceiveDirectionality(g)&&!hasReceiveDirectionality(S);return v&&C}function areNegotiatedDirectionsAcceptable(g,f,S){return isNegotiatedDirectionAcceptable(g.audio,f.audio,S.audio)&&isNegotiatedDirectionAcceptable(g.video,f.video,S.video)&&isNegotiatedDirectionAcceptable(g.sharing,f.sharing,S.sharing)&&isNegotiatedDirectionAcceptable(g.data,f.data,S.data)}function areNegotiatedDirectionsFulfilled(g,f){function isNegotiatedDirectionFulfilled(g,f){const S=hasSendDirectionality(g)===hasSendDirectionality(f),v=hasReceiveDirectionality(g)===hasReceiveDirectionality(f)||hasReceiveDirectionality(g)&&!f;return S&&v}return isNegotiatedDirectionFulfilled(g.audio,f.audio)&&isNegotiatedDirectionFulfilled(g.video,f.video)&&isNegotiatedDirectionFulfilled(g.sharing,f.sharing)&&isNegotiatedDirectionFulfilled(g.data,f.data)}function areSendDirectionsFulfilled(g,f){const isSendDirectionFulfilled=(g,f)=>hasSendDirectionality(g)===hasSendDirectionality(f);return isSendDirectionFulfilled(g.audio,f.audio)&&isSendDirectionFulfilled(g.video,f.video)&&isSendDirectionFulfilled(g.sharing,f.sharing)&&isSendDirectionFulfilled(g.data,f.data)}function getSrtpInfo(g){const f={dtls:!1,sdes:!1};return f.dtls=!!g.fingerprint,g.media.forEach((g=>{f.dtls=f.dtls||!!g.fingerprint,f.sdes=f.sdes||!!g.crypto})),f}function removeChangedSendDirection(g,f){if(!f||isEmpty(f))return g;const S={};return forOwn(g,((g,v)=>{v===qt.MODALITY.data?S[v]=removeChangedDataSendDirection(g,f[v]):S[v]=removeChangedMediaSendDirection(g,f[v])})),S}function removeChangedMediaSendDirection(g,f){return hasSendDirectionality(g)&&!hasSendDirectionality(f)?removeSendDirectionality(g)||f:g}function removeChangedDataSendDirection(g,f){return hasSendDirectionality(g)&&!hasSendDirectionality(f)?f:g}function parseCandidateString(g){const f=(g||"").split(" ");return{component:f[1],protocol:f[2],priority:f[3],ip:f[4],port:f[5],type:f[7]}}function modalityToMediaType(g){switch(g){case"audio":return"Audio";case"video":return"Video";case"sharing":return"ScreenShare";default:return null}}function mediaTypeToModality(g){switch(g){case"Audio":return"audio";case"Video":return"video";case"ScreenShare":return"sharing";default:return null}}function sendStreamsToModalities(g){const f={};return keys(g).forEach((S=>f[S]=!!g[S])),f}function scrubObjectFields2(g,f,S){if(!g)return g;const v={...g};for(const[C,_]of Object.entries(g))"object"==typeof _?v[C]=scrubObjectFields2(_,f):_&&f.includes(C)&&(v[C]=S?S(_):scrubMriOrOmit(_));return v}function scrubObjectExcludingFields(g,f,S){if(!g)return g;const v={...g};for(const[C,_]of Object.entries(g))"object"==typeof _?v[C]=scrubObjectExcludingFields(_,f):_&&!f.includes(C)&&(v[C]=S?S(_):scrubMriOrOmit(_));return v}function scrubSelectedDevices(g){return g?scrubObjectExcludingFields(g,[]):g}function scrubDevices(g,f){if(!g)return g;const S=scrubObjectFields2(g,["deviceId","groupId","guid"]);return scrubObjectFields2(S,["label"],(g=>scrubDeviceLabelPii(g,f)))}function scrubConstraints(g){return scrubObjectFields2(g,["sourceId","deviceId"])}function preferSdesSrtp(g,f){return!(!g.config.webrtcForceSdesForS1||!g.config.checkSupportForWebrtc_1_0||g.mediaConfig.simulcastSessionEnabled)||(f?g.config.preferSdesSrtpPstn:g.config.preferSdesSrtp)}function canUseWebrtc1_0(g){return!g||oa.hasUnifiedPlanSupport()}function allowDataChannel(g){return!!g.configProvider.mediaConfig.simulcastSessionEnabled&&(g.config.isPstnCall?g.configProvider.config.enableDataChannelPstn:g.configProvider.config.enableDataChannel)}function getAllowedCodecs(g,f){switch(f){case qt.MEDIA_TYPE.audio:return g.config.allowedAudioCodecs;case qt.MEDIA_TYPE.video:return g.config.allowedVideoCodecs;default:return[]}}function convertToCodecInfo(g){return g.map((g=>{const f={codec:g.mimeType.split("/").pop(),rate:g.clockRate};return g.channels&&(f.encoding=g.channels),g.sdpFmtpLine&&(f.fmtpLine=g.sdpFmtpLine),f}))}function printMediaStream(g){return`${g?.id}:${JSON.stringify(g?.getTracks().map((g=>g.id)))}}`}function ipAddressConverter(g){try{if(la.test(g))return ipv4AddressConverter(g);if(ca.test(g))return ipv6AddressConverter(g)}catch(f){return g}return g}function ipv6AddressConverter(g){let f,S=g.lastIndexOf("]")+1,v="",C="";S>0?(f=g.substring(0,S),C=g.substring(S)):(f=g,S=f.length);const _=f.lastIndexOf(":");if(f.includes(".")){const g=ipv4AddressConverter(f.substring(_+1,S-1-_));v=f.substring(0,_+1)+g}else _<f.length-1||":"===f[_-1]&&f.match(/:/g).length<7?v=f.substring(0,_+1)+"x":7===f.match(/:/g).length&&(v=f.substring(0,_)+"0:x");return v?C?v+"]"+C:"["===g.substring(0,1)?(v=v.substring(1),v):v:g}function ipv4AddressConverter(g){const f=g.substring(0,g.lastIndexOf(".")+1)+"x",S=g.lastIndexOf(":");return S>0?f+g.substring(S):f}function shouldDisableVideoSendersTroughSetParams(g,f,S){return!(!f&&!S)&&(S?g.config.disableSendersTroughSetParametersVideo&&(S===qt.MODALITY.sharing||S===qt.MODALITY.video):g.config.disableSendersTroughSetParametersVideo&&("Video"===f.mediaType||"ScreenShare"===f.mediaType))}function shouldDisableAudioSendersTroughSetParams(g,f){return g.config.disableSendersTroughSetParametersAudio&&"Audio"===f.mediaType}function getStreamInformation(g){let f=[];return g.forEach((g=>{try{let S=f.find((f=>f.participantId===g.participantId&&f.endpointId===g.endpointId));S||(S={participantId:g.participantId,endpointId:g.endpointId},f.push(S)),"audio"!==g.type&&"audioteleconference"!==g.type||(S.serverMuted=g.serverMuted),S[g.type]=g.direction}catch(g){f=[]}})),f}var da=M,ha=M,ua={maxOutgoingResolution:({settings:g})=>getMaxOutgoingResolution(g),maxParticipantResolutions:({settings:g})=>getMaxParticipantResolutions2(g),maxIncomingStreams:({settings:g})=>getMaxIncomingStreams2(g),maxSimulcastLayers:({settings:g})=>getMaxSimulcastLayers2(g),outgoingVideoLimit:({settings:g,constraints:f})=>getOutgoingVideoLimit2(g,f)},convertSettingsToCallConstraints=(g,f,S)=>(g.info(`Converting settings to constraints and mapping, [requestedConstraints=${JSON.stringify(S)}], [settings=${JSON.stringify(f)}]`),convertConstraints((0,ha.cloneDeep)(S),(0,ha.cloneDeep)(f))),convertConstraints=(g,f)=>Object.keys(g).reduce(((S,v)=>{const C=ua[v]?ua[v]({constraints:g,settings:f}):void 0;return C&&(S[v]=C),S}),{}),getMaxParticipantResolutions2=g=>g.multiviewResolutionLimits,getMaxOutgoingResolution=g=>g.outgoingVideoLimit?.maxResolution,getOutgoingVideoLimit2=(g,f)=>{const S=f?.outgoingVideoLimit;if(!S)return;const{outgoingVideoLimit:v={}}=deepClone(g);if("number"==typeof S)return v?.maxResolution;const C=Object.keys(S).reduce(((g,f)=>{const S=v?.[f];return S&&(g[f]=S),g}),{});return Object.keys(C).length?C:void 0},getMaxIncomingStreams2=g=>g.numVideoChannelsGvc,getMaxSimulcastLayers2=g=>{const f=g.specCompliantSimulcast,S=f.video?.layerScaleFactors,v=f.sharing?.layerScaleFactors,C=S?.length?Math.max(...S):1,_=v?.length?Math.max(...S):1;return Math.min(C,_)},ga=M,isVideoLimit=g=>{const f=["maxResolution","maxBitrate","maxFramerate"],isValidVideoLimitKey=g=>f.includes(g),S=Object.entries(g);return 0!==S.length&&S.every((([g,f])=>(0,ga.isNumber)(f)&&isValidVideoLimitKey(g)))},isVideoLimitOrResolution=g=>!!(0,ga.isNumber)(g)||!!isVideoLimit(g)&&!isEmpty(g),pa={maxIncomingStreams:ga.isNumber,maxSimulcastLayers:ga.isNumber,maxOutgoingResolution:ga.isNumber,maxParticipantResolutions:g=>!!isDefined(g)&&(!!(0,ga.isNumber)(g)||"more"in g&&Object.values(g).every((g=>(0,ga.isNumber)(g)))),outgoingVideoLimit:g=>!!isDefined(g)&&isVideoLimitOrResolution(g)},removeInvalidConstraints=g=>(g=JSON.parse(JSON.stringify(g)),Object.entries(pa).reduce(((f,[S,v])=>(v(g[S])&&(f[S]=g[S]),f)),{}));function arrayMergeCustomizer2(g,f){if(Array.isArray(g))return f.slice()}var deepMergeConstraints=(g,f)=>{for(const S in f){const v=g[S],C=f[S];g[S]="object"==typeof C?deepMergeConstraints({...v},C):getMinDefined(v,C)}return g},ma=class{constructor(g,f,S,v,C,_,T){this.logger=g,this.defaultSettings=f,this._mediaConfig=S,this._userAgentConfig=v,this._countryCode=C,this.platformCallConstraintsProvider=_,this.currentCallConstraints=T,this.mergedConstraints={},this.callConstraintsTelemetry=[],this.iceTransportPolicy=qt.ICE_TRANSPORT_POLICY.all,this.validIceTransportPolicies=[qt.ICE_TRANSPORT_POLICY.all,qt.ICE_TRANSPORT_POLICY.relay],this.mergeConstraintsTelemetryWithGlobal(),this.mergedConstraints=this.mergeConstraintsWithGlobal(this.currentCallConstraints),this.settings=this.mergeSettings((0,da.cloneDeep)(this.defaultSettings))}get config(){return this.settings}get mediaConfig(){return this._mediaConfig}get userAgentConfig(){return this._userAgentConfig}get countryCode(){return this._countryCode}addCallConstraintsTelemetryEvent(g,f){const S={timestamp:(new Date).getTime(),type:f,value:g};arrayLimitedPush2(this.callConstraintsTelemetry,S,this.config.numCallConstraintsEvents)}getCallConstraintsTelemetry(){return this.callConstraintsTelemetry}getCallConstraints(){return this.mergedConstraints}setCallConstraints(g={}){this.addCallConstraintsTelemetryEvent(g,"requested"),this.logger.safe.debug("Saving new call constraints",JSON.stringify(g));const f=this.transformConstraints(removeInvalidConstraints(g));return this.logger.safe.debug("Validated call constraints",JSON.stringify(f)),this.mergedConstraints=this.mergeConstraintsWithGlobal(f),this.settings=this.mergeSettings((0,da.cloneDeep)(this.defaultSettings)),convertSettingsToCallConstraints(this.logger,this.settings,f)}getIceTransportPolicy(){return this.settings.iceTransportPolicyForced||this.iceTransportPolicy}setIceTransportPolicy(g){this.validIceTransportPolicies.includes(g)?(this.logger.info(`Setting transport policy to ${this.iceTransportPolicy}`),this.iceTransportPolicy=g):this.logger.debug(`Unknown incoming transport policy, using ${this.iceTransportPolicy}`)}overrideMaxSessionBandwidth(g){return this.defaultSettings.maxBandwidthInKbps!==g&&(this.defaultSettings.maxBandwidthInKbps=g,this.settings.maxBandwidthInKbps=g,this.mediaConfig.maxBandwidthInKbps=g,!0)}transformConstraints(g){const f=(0,da.cloneDeep)(g);return"maxOutgoingResolution"in f&&(f.outgoingVideoLimit={maxResolution:f.maxOutgoingResolution},delete f.maxOutgoingResolution),"number"==typeof f.outgoingVideoLimit&&(f.outgoingVideoLimit={maxResolution:f.outgoingVideoLimit}),f}mergeConstraintsTelemetryWithGlobal(){this.platformCallConstraintsProvider.callConstraintsTelemetry.forEach((g=>arrayLimitedPush2(this.callConstraintsTelemetry,g,this.defaultSettings.numCallConstraintsEvents)))}mergeConstraintsWithGlobal(g={}){const f=this.transformConstraints(this.platformCallConstraintsProvider.constraints);if(!Object.keys(f).length)return g;const S=(0,da.cloneDeep)(g);return deepMergeConstraints(S,f),this.logger.safe.debug(`Merging call constraints ${JSON.stringify(g)} and global constraints ${JSON.stringify(f)}. Result: ${JSON.stringify(S)}`),S}mergeSettings(g){if(!g.enablePlatformCallConstraints||!g.enablePlatformCallConstraintsPerCall)return g;const f=convertCallConstraintsToSettings(this.logger,g,this.mergedConstraints);return this.logger.safe.info(`Merging settings with platform call constraints: ${stringifyObject(f)}`),(0,da.assign)({},g,f,arrayMergeCustomizer2)}},fa=M,Sa=[qt.MODALITY.audio,qt.MODALITY.video,qt.MODALITY.sharing],va=class{constructor(g,f,S,v,C){this.peerConnection=f,this.mediaManager=S,this.reinvitelessContext=C,this.entityTransceiverMap=new Map,this.logger=g.createChild("TM"),this.configProvider=v.configProvider,this.isMultiparty=v.config.isConference,this.isPstnCall=v.config.isPstnCall,this.isParkedCall=v.config.isParkedCall,this.numVideoChannels=this.isMultiparty&&this.configProvider.config.numVideoChannelsGvc||1,v.configProvider.config.enableRollbackHandler&&this.mediaManager.setRollbackUpdateHandler(this.handleMediaEntitiesRollback.bind(this))}getTransceivers(){return this.peerConnection.getTransceivers().filter(isActiveTransceiver)}assureTransceivers(g){this.assureNegotiatedOrder(),this.addModalities(g),this.logTransceiversInfo("assureTransceivers"),this.setDirections(g)}syncTransceivers(g){this.syncWithMediaEntities(),this.setDirections(g)}assureNegotiatedOrder(){const g=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((f=>{if(-1===Sa.indexOf(f.getModality()))return;isActiveTransceiverInPc(this.entityTransceiverMap.get(f),g)||this.createTransceiverForEntity(f)}))}addModalities(g){const f=this.mediaManager.isEmpty();this.isMultiparty||!f||this.isPstnCall||(g.video=g.video||"inactive",g.sharing=g.sharing||"inactive"),this.configProvider.config.webrctRemoveVideoModalitiesForPstn&&this.isPstnCall&&!this.isParkedCall&&(delete g.video,delete g.sharing);for(const S of Sa){if(this.mediaManager.getMediaEntitiesByModality(S)[0]||!g[S])continue;const v=S===qt.MODALITY.video?this.numVideoChannels:1;(0,fa.times)(v,(g=>{const v=this.mediaManager.createMediaEntity(S);v.setExtension("reinviteless",f&&this.reinvitelessContext.maxStreamsForModality[S]>g),this.createTransceiverForEntity(v)}))}}createTransceiverForEntity(g){const f=g.getModality();this.logger.safe.info(`createTransceiver: modality=${f}`);const S=f===qt.MODALITY.audio?qt.MEDIA_TYPE.audio:qt.MEDIA_TYPE.video,v=g.getSimulcastContext(),C=this.createTransceiver(S,v);this.setCodecPreferences(C,S,!0),this.setExtensionPreferences(C,f),this.entityTransceiverMap.set(g,C),g.setExtension("unnegotiatedModality",!0)}setCodecPreferences(g,f,S){const v=getAllowedCodecs(this.configProvider,f);if(!v?.length||!oa.hasCapabilitiesApi()||this.configProvider.config.filterCodecsInSdp)return;const C=Xs.window.RTCRtpReceiver.getCapabilities(f);if(!C)return;const _=[];if(S)for(const g of v){const f=C.codecs.filter((f=>isCodecsMatch(g,f)));_.push(...f)}else for(const g of C.codecs)v.some((f=>isCodecsMatch(f,g)))&&_.push(g);_.length&&g.setCodecPreferences&&g.setCodecPreferences(_)}setExtensionPreferences(g,f){if(!this.configProvider.config.headerExtensionsToUpdate?.[f])return;if(!g.getHeaderExtensionsToNegotiate||!g.setHeaderExtensionsToNegotiate)return void this.logger.safe.debug("setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate is not supported");const S=this.configProvider.config.headerExtensionsToUpdate[f],v=g.getHeaderExtensionsToNegotiate();for(const g of v){const f=S.find((f=>f.uri===g.uri));f&&(g.direction=f.direction)}try{g.setHeaderExtensionsToNegotiate(v)}catch(g){this.logger.safe.error(`setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate failed, err ${stringifyObject(g)}`)}}async createSender(g,f,S){const v=await this.associateTrackWithTransceiver(g,f,S);if(!v)throw new Error(`Transceiver for modality=${S} is not found`);const C=this.findEntityForTransceiver(v),_=S!==qt.MODALITY.sharing||C?.getExtension("reinviteless")?qt.MEDIA_STATE.sendReceive:qt.MEDIA_STATE.send;return v.direction=_,this.logger.safe.info(`Replace track completed direction:${v.direction} for transceiver mid=${v.mid}`),v.sender}removeSender(g){this.removeSenderInternal(g,!1)}async removeSenderAsync(g){return this.removeSenderInternal(g,!0)}removeSenderInternal(g,f){if("closed"===(this.peerConnection.connectionState||this.peerConnection.iceConnectionState))return void this.logger.safe.info("Not removing sender from pc, connection is closed");const S=this.getTransceivers().find((f=>f.sender===g));if(!S)throw new Error(`Transceiver for sender with track=${g.track?.id} is not found`);const v=this.findEntityForTransceiver(S),C=!!v?.getExtension("reinviteless");this.logger.safe.info(`Remove sender with track=${g.track?.id} for transceiver mid=${S.mid}, reinviteless=${C}, doAsync=${f}`);let _=Promise.resolve();return C&&f?_=S.sender.replaceTrack(null):this.peerConnection.removeTrack(g),f?_:void 0}createTransceiver(g,f){const S={direction:"inactive"};return this.addSimulcastEnvelopeIfNeeded(S,f),this.peerConnection.addTransceiver(g,S)}addSimulcastEnvelopeIfNeeded(g,f){f?.shouldUseSimulcast()&&(g.sendEncodings=(0,fa.times)(f.config.layerScaleFactors.length,(g=>{const S={rid:`${f.ridList[g]}`,scaleResolutionDownBy:f.config.layerScaleFactors[g]};if(this.configProvider.config.specCompliantSimulcast?.disableTilde&&(S.active=!1),f.config.layerScalabilityModes?.length>0){const v=f.config.layerScalabilityModes[g];void 0!==v&&v.length>0?S.scalabilityMode=v:this.logger.safe.warn(`Scalability mode was not set for rid: ${S.rid}`)}return this.logger.safe.debug(`Added layer ${g} with rid: ${S.rid} SF: ${S.scaleResolutionDownBy} SM: ${S.scalabilityMode}`),S})))}async associateTrackWithTransceiver(g,f,S){const v=this.findAvailableTransceiverToSend(S);if(v){this.logger.safe.info(`Associate track=${g?.id} (${S}) with existing transceiver mid=${v.mid}`);try{if(this.isMultiparty&&shouldDisableVideoSendersTroughSetParams(this.configProvider,void 0,S)){this.logger.safe.info(`Disabling encodings for transceiver mid=${v.mid}`);const g=v.sender.getParameters();g.encodings.forEach((g=>g.active=!1)),await v.sender.setParameters(g)}await v.sender.replaceTrack(g),this.configProvider.config.useSetStreamsForSender&&v.sender.setStreams&&v.sender.setStreams(f)}catch(g){throw this.logger.safe.error(`replaceTrack failed, err ${JSON.stringify(g)}`),g}return v}return null}syncWithMediaEntities(){const g=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((f=>{let S=this.entityTransceiverMap.get(f);S=isActiveTransceiverInPc(S,g)?S:g.find((g=>g.mid===f.getMid())),this.entityTransceiverMap.set(f,S)})),this.logTransceiversInfo("syncWithMediaEntities")}getTransceiversByModality(g){return this.mediaManager.getMediaEntitiesByModality(g).map((g=>this.entityTransceiverMap.get(g))).filter(isActiveTransceiver)}setDirections(g){const f=!isOnHold(g);for(const S of Sa)for(const[v,C]of this.getTransceiversByModality(S).entries()){const _=this.findEntityForTransceiver(C);if(_?.getExtension("reinviteless")&&f){C.direction="sendrecv";continue}const T=g[S]||qt.MEDIA_STATE.inactive;C.direction=0===v&&C.currentDirection?T:removeSendDirectionality2(T)}this.logTransceiversInfo("setDirections")}handleMediaEntitiesRollback(g,f){g.forEach((g=>{const S=this.entityTransceiverMap.get(g),v=f.find((f=>f.getMid()===g.getMid()));this.entityTransceiverMap.set(v,S)})),this.logTransceiversInfo("handleMediaEntitiesRollback")}findAvailableTransceiverToSend(g){const f=this.mediaManager.getMediaEntitiesByModality(g)[0];return this.entityTransceiverMap.get(f)}findEntityForTransceiver(g){for(const[f,S]of this.entityTransceiverMap)if(S===g)return f}logTransceiversInfo(g){let f=`${g}: transceivers details:`;for(const g of Sa){const S=this.getTransceiversByModality(g);f+=` ${g}(${S.length}) [${S.map((g=>`mid=${g.mid}, direction=${g.direction}`)).join(";")}]`}this.logger.safe.debug(f)}};function isCodecsMatch(g,f){return!(!(0,fa.isUndefined)(g.channels)&&g.channels!==f.channels)&&(!(!(0,fa.isUndefined)(g.clockRate)&&g.clockRate!==f.clockRate)&&(!(!(0,fa.isUndefined)(g.mimeType)&&g.mimeType.toLowerCase()!==f.mimeType.toLowerCase())&&!(!(0,fa.isUndefined)(g.sdpFmtpLine)&&-1===f.sdpFmtpLine.toLowerCase().indexOf(g.sdpFmtpLine.toLowerCase()))))}function removeSendDirectionality2(g){let f=g;return hasSendDirectionality(g)&&(f=removeSendDirectionality(g)),f||qt.MEDIA_STATE.inactive}function isActiveTransceiver(g){return g&&"stopped"!==g.direction&&!g.stopped}function isActiveTransceiverInPc(g,f){return isActiveTransceiver(g)&&-1!==f.indexOf(g)}var Ca=class extends Ht{constructor(g,f,S){super(),this.configProvider=g,this.workerProvider=f,this.logger=S,this.transformsCollections=new Map}async initialize(){return this.configProvider.config.useInsertableStreams&&this.workerProvider&&oa.hasEncodedStreamsApi()&&(this.worker=new Ha(this.workerProvider,this.logger)),this.worker?this.worker.initialize():Promise.resolve()}initTransformsCollection(g,f,S){const v=oa.hasScriptTransformApi()||this.workerProvider;if(!(this.configProvider.config.useInsertableStreams&&oa.hasEncodedStreamsApi()&&(!v||this.isWorkerLoaded())&&null!==g.track))return null;if(!this.transformsCollections.has(g)){const v=this.worker?new Ea(this.worker,g):new ya(g);this.transformsCollections.set(g,{collection:v,mediaType:S,objType:f})}const C=this.transformsCollections.get(g);return this.event("onTransformsCollectionCreated").raise(C),C.collection}clearTransformsCollection(g){const f=this.transformsCollections.get(g);f&&(this.event("onTransformsCollectionCleared").raise(f),f.collection.clearTransforms())}dispose(){for(const g of this.transformsCollections.values())this.event("onTransformsCollectionCleared").raise(g),g.collection.clearTransforms();this.transformsCollections.clear(),this.worker?.dispose(),super.dispose()}isWorkerLoaded(){return!!this.worker?.isWorkerLoaded()}},ya=class{constructor(g){const{readable:f,writable:S}=g.createEncodedStreams();this.streamTransformer=new Ya(f,S)}addTransform(g){g.createBaseInstance(this.streamTransformer)}clearTransforms(){this.streamTransformer.clearTransforms()}},Ea=class{constructor(g,f){if(this.workerHandler=g,this.clientId=f.track.id,oa.hasScriptTransformApi())return void(f.transform=new RTCRtpScriptTransform(this.workerHandler.worker,{clientId:this.clientId}));const{readable:S,writable:v}=f.createEncodedStreams(),C=[S,v];this.workerHandler.sendTransformCommand(this.clientId,{operation:"init",readable:S,writable:v},C)}addTransform(g){g.createWorkerInstance(this.workerHandler,this.clientId)}clearTransforms(){this.workerHandler.sendTransformCommand(this.clientId,{operation:"clear"})}},_a=class{constructor(g,f=!1){this.logger=g,this.disabled=f,this.audioContext=new AudioContext,this.destination=this.audioContext.createMediaStreamDestination()}get stream(){return this.destination.stream}isSingleInputStream(){return 0===this.mixerImp?.mixerType}dispose(){this.audioContext.close(),this.audioContext=null}stopMixing(){this.disabled=!0,this.mixerImp?.reset()}startMixing(g){this.disabled=!1,this.mixerImp?.setupMixer(this.audioContext,this.destination,g)}setMixerType(g,f){this.mixerImp?.mixerType!==g&&(this.mixerImp?.reset(),this.mixerImp=this.createMixer(g),this.disabled||this.mixerImp.setupMixer(this.audioContext,this.destination,f))}setStreamSources(g){this.disabled||this.mixerImp.setStreamSources?.(g)}setParticipantSpatialAudioPositions(g){this.mixerImp.setParticipantSpatialAudioPositions?.(g)}createMixer(g){switch(g){case 0:return new Ia;case 1:return new ba(this.logger.createChild("MixingStreamsMixer"));case-1:return new Ta;default:throw new Error(`unknown mixer type: ${g}`)}}},Ta=class{constructor(){this.mixerType=-1}reset(){}setupMixer(g,f,S){}},Ia=class{constructor(){this.mixerType=0}reset(){this.sourceNode.disconnect()}setupMixer(g,f,S){this.sourceNode=g.createMediaStreamSource(S[0]),this.sourceNode.connect(f)}},ba=class{constructor(g){this.logger=g,this.sourcePositions=new Map,this.sourceNodes=[],this.pannerNodes=[],this.mixerType=1}reset(){this.logger.safe.info("resetting SpatialMultiStreamMixer");for(const g of this.sourceNodes)g.disconnect();this.sourceNodes=[];for(const g of this.pannerNodes)g.disconnect();this.pannerNodes=[]}setupMixer(g,f,S){(this.sourceNodes.length||this.pannerNodes.length)&&this.reset();for(const v of S){const S=g.createMediaStreamSource(v),C=new PannerNode(g,{panningModel:"HRTF"});S.connect(C),C.connect(f),this.sourceNodes.push(S),this.pannerNodes.push(C)}this.logger.safe.info(`setupMixer is done for ${S.length} streams.`)}setStreamSources(g){for(let f=0;f<g.length;f++)this.setStreamPosition(f,g[f])}setParticipantSpatialAudioPositions(g){this.sourcePositions=new Map(g.map((g=>[g.sourceId,g])))}setStreamPosition(g,f){const S=this.sourcePositions.get(f)??{sourceId:f,x:0,y:0},v=this.pannerNodes[g];v?(v.positionX.value=S.x,v.positionY.value=S.y):this.logger.warn(`panner node for stream ${g} is not found`)}},Aa=class extends Ht{constructor(g){super(),this.logger=g,this.mediaStreams=[],this.cnStream=null,this.isConfigured=!1,this.isNegotiated=!1,this.activeCodec="None"}get streams(){return this.mediaStreams}get comfortNoiseStream(){return this.cnStream}get configured(){return this.isConfigured}get active(){return this.isNegotiated}get codec(){return this.activeCodec}setupStreams(g,f){this.logger.safe.debug(`setup ${g} streams with extra Comfort Noise stream: ${f}`),this.mediaStreams=[];const S=[];for(;g--;){const g=new MediaStreamTrackGenerator({kind:"audio"});S.push(g),this.streams.push(new MediaStream([g]))}const v=f?new MediaStreamTrackGenerator({kind:"audio"}):null;return this.cnStream=v?new MediaStream([v]):null,this.event("onStreamsChanged").raise(),{streams:S.map((g=>g.writable)),cnStream:v?.writable}}setStreamSources(g){this.isNegotiated&&this.event("onStreamSourcesUpdated").raise(g)}setConfiguredState(g){this.isConfigured!==g&&(this.isConfigured=g,this.event("onConfiguredStateChanged").raise(this.isConfigured))}setNegotiatedState(g){this.isNegotiated!==g&&(this.isNegotiated=g,this.event("onActiveStateChanged").raise(this.isNegotiated))}setDetectedCodec(g){this.activeCodec!==g&&(this.activeCodec=g,this.event("onActiveCodecChanged").raise(this.activeCodec))}},Pa=0,Ra={MUCHv2:{CODEC:{NAME:"x-much2",RATE:48e3,ENCODING:2},SUBSTITUTION:{NAME:"L16",RATE:48e3,ENCODING:2},PT:113},SatinFB:{CODEC:{NAME:"SATINFB",RATE:48e3,ENCODING:2},SUBSTITUTION:{NAME:"L16",RATE:48e3,ENCODING:2},PT:109}},Ma=class{constructor(g,f,S,v){this.worker=g,this.clientId=f,this.transformType=S,this.listener=v,this.worker.subscribeClient(this.clientId,this.transformType,(g=>this.processMsg(g))),this.worker.sendTransformCommand(this.clientId,{operation:"add",transformType:this.transformType})}dispose(){this.worker.unsubscribeClient(this.clientId),this.worker.sendTransformCommand(this.clientId,{operation:"clear"})}processMsg(g){if(this.listener&&g.name in this.listener)return this.listener[g.name].apply(this.listener,g.args);throw`unexpected message received for transform type ${this.transformType}: ${JSON.stringify(g)}`}};function createAudioWasmDecoderProxy(g,f,S){return new wa(g,f,S)}var wa=class extends Ma{constructor(g,f,S){super(g,f,2,S)}init(g,f){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[g,f]}})}setCodec(g,f){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[g,f]}})}passWriteableStreams(g,f){const S=g.concat(f);this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"passWriteableStreams",args:[g,f]}},S)}setAvailableStreams(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setAvailableStreams",args:[g]}})}setRecvPayloads(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setRecvPayloads",args:[g]}})}debugLogging(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[g]}})}sendApiRecordingData(){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"sendApiRecordingData",args:[]}})}},Oa=class extends Ht{constructor(g,f,S,v){super(),this.logger=g,this.maxNumOfStreamsFactor=S,this.statsProvider=new Da,this.contributingSources=[],this.unmixedAudioProvider=new Aa(this.logger),this.codec="None",this.recvPayloads=[],this.initCompleted=!1,this.enabledApiRecording=!1;try{this.enabledApiRecording="true"===localStorage.getItem("enableApiRecording")}catch{}this.streamMixer=new _a(this.logger,v),this.unmixedAudioProvider.setConfiguredState(!!f.mediaConfig.spatialAudioEnabled),this.wasmHealerPullStrategy=f.config.useInsertableStreams?.audioWasmCodec?.wasmHealerPullStrategy||-1,this.injectWebMA()}get stream(){return this.streamMixer.stream}dispose(){super.dispose(),this.streamMixer.dispose(),this.imp?.dispose(),this.removeWebMA()}activateTransform(g){this.logger.safe.debug("Activating WASM decoder transform"),g.addTransform(this)}deactivateTransform(){this.logger.safe.debug("Deactivating WASM decoder transform"),this.imp.dispose(),this.imp=null,this.initCompleted=!1,this.codec="None",this.streamMixer.setMixerType(-1,[])}createBaseInstance(g){this.logger.warn("WASM decoder could only be instantiated in worker")}createWorkerInstance(g,f){this.imp=createAudioWasmDecoderProxy(g,f,this),this.imp.init(this.enabledApiRecording,this.wasmHealerPullStrategy)}setCodec(g){if(this.logger.safe.debug(`Setting codec to ${g}`),!this.initCompleted)return this.logger.safe.debug("Decoder is not initialized yet, postponing codec setting"),void(this.codec=g);this.codec!==g&&(this.codec=g,this.setCodecInternal())}setRecvPayloads(g){this.recvPayloads=g,this.initCompleted?this.imp.setRecvPayloads(g):this.logger.safe.debug("Decoder is not initialized yet, postponing Recv payload setting")}negotiationCompleted(g){this.logger.safe.debug(`Negotiation completed, negotiated=${g}`),this.unmixedAudioProvider.setNegotiatedState(g),g||(this.codec="None",this.imp?.setCodec(this.codec,this.streamMixer.isSingleInputStream()))}setParticipantSpatialAudioPositions(g){this.streamMixer.setParticipantSpatialAudioPositions(g)}disableStreamsMixer(g){g?this.streamMixer.stopMixing():this.streamMixer.startMixing(this.unmixedAudioProvider.streams.concat(this.unmixedAudioProvider.comfortNoiseStream??[]))}getStatsProvider(){return this.statsProvider}getUnmixedAudioProvider(){return this.unmixedAudioProvider}configureSpatialAudio(g){this.unmixedAudioProvider.setConfiguredState(g)}async storeApiRecording(){if(this.enabledApiRecording&&this.initCompleted)return this.recordingCompletePromise?.resolve(),this.recordingCompletePromise=new dt,this.imp.sendApiRecordingData(),this.recordingCompletePromise.promise}initDone(g,f){if(this.healerCapabilities=f,this.logger.safe.info(`Init done, errorCode=${g}`),0!==g)return void this.event("initFailed").raise(g);this.logger.safe.info(`healerCapabilities=${JSON.stringify(f)}`),this.initCompleted=!0;const S=Math.floor(this.healerCapabilities.maxNumStreamsPerPacket*this.maxNumOfStreamsFactor),v=this.unmixedAudioProvider.setupStreams(S,!0);this.imp.passWriteableStreams(v.streams,v.cnStream),this.setCodecInternal(),this.imp.setRecvPayloads(this.recvPayloads)}usedDecoderChanged(g){this.logger.safe.info(`Used decoder changed to custom=${g}, configured codec=${this.codec}`),this.event("usedDecoderChanged").raise(g),this.unmixedAudioProvider.setDetectedCodec(this.codec)}packetReceived(g,f,S,v){this.statsProvider.ssrc=f,this.statsProvider.addPushStats(g,v),this.contributingSources.length===S.length&&this.contributingSources.every(((g,f)=>g===S[f]))||(this.contributingSources=S,this.event("contributingSourcesChanged").raise(S))}newDataWrittenToStreams(g){const f=Array.from(new Int32Array(g));this.unmixedAudioProvider.setStreamSources(f),this.streamMixer.setStreamSources(f);const S=f.reduce(((g,f,S)=>(f===Pa&&g.push(S),g)),[]);this.imp?.setAvailableStreams(S)}packetDecoded(g,f,S){this.statsProvider.addPullStats(g,f,S,S.extra.samplingRatekHz*this.healerCapabilities.frameLengthMs)}apiRecordingAvailable(g,f,S){if(this.logger.safe.debug(`API recording available: errorCode=${g}, name=${f}, buffer length=${S.byteLength}`),this.recordingCompletePromise?.resolve(),0===S.byteLength)return;const v=new Blob([S],{type:"application/octet-stream"}),C=URL.createObjectURL(v),_=document.createElement("a");_.href=C,_.download=f,_.click()}setCodecInternal(){this.streamMixer.setMixerType(getStreamGeneratorType(this.codec),this.unmixedAudioProvider.streams.concat(this.unmixedAudioProvider.comfortNoiseStream??[])),this.imp.setCodec(this.codec,this.streamMixer.isSingleInputStream()),this.statsProvider.codecName=this.codec}injectWebMA(){const g=window.webMA;g&&(g.wasmDecoder={debugLogging:g=>this.imp?.debugLogging(g),sendApiRecordingData:()=>this.imp?.sendApiRecordingData()})}removeWebMA(){const g=window.webMA;g&&delete g.wasmDecoder}};function getStreamGeneratorType(g){switch(g){case"SatinFB":return 0;case"MUCHv2":return 1;case"None":return-1;default:throw new Error(`unknown codec: ${g}`)}}var Da=class{constructor(){this.customHealerStats={numSamplesPerFrame:0,FECPayloadDecodedSamples:0,concealSamples:0,stretchSamples:0,healedSamples:0,decodedSamples:0,redPacketsCount:0,pushProcessingTimes:{},pullProcessingTimes:{},pullProcessingTimePerStreamNumber:{},pullTimings:{},pullNumOfStreamsCounter:{}},this.inboudStats={silentConcealedSamples:0,concealedSamples:0,totalSamplesReceived:0,audioLevel:0,jitterBufferDelay:0,jitterBufferEmittedCount:0},this.decoderStats={pushCount:0,pushErrCount:0,pullCount:0,pullErrCount:0},this.packetPushProccesingTimes=new Na(0,1e3),this.packetPullProccesingTimes=new Na(0,1e3),this.numOfStreamsCounter=new Na(0,10),this.pullProcessingTimePerStreamNumber={},this.packetPullTimings=new Na(0,1e3)}get codecName(){return this.codec}set codecName(g){this.codec=g}addPushStats(g,f){this.decoderStats.pushCount++,this.decoderStats.pushErrCount+=0!==g?1:0,this.inboudStats.jitterBufferDelay+=f.webrtc.jitterBufferDelay,this.customHealerStats.packetDurationInMs=f.extra.packetDurationInMs,this.packetPushProccesingTimes.addSample(f.extra.processingTime),this.customHealerStats.cnpPushCount=f.extra.totalCountCNPackets,this.customHealerStats.redPacketsCount+=0!==f.extra.redundancyTimestampOffset?1:0}addPullStats(g,f,S,v){var C;this.decoderStats.pullCount++,this.decoderStats.pullErrCount+=0!==g?1:0,this.inboudStats.audioLevel=S.webrtc.audioLevel,this.inboudStats.totalAudioEnergy=S.webrtc.totalAudioEnergy,this.inboudStats.jitterBufferEmittedCount=S.webrtc.jitterBufferEmittedCount,this.inboudStats.totalSamplesReceived=S.webrtc.totalSamplesReceived,this.inboudStats.concealedSamples=S.webrtc.concealedSamples,this.inboudStats.silentConcealedSamples=S.webrtc.silentConcealedSamples,this.numOfStreamsCounter.addSample(f),this.customHealerStats.FECPayloadDecodedSamples=S.extra.FECPayloadDecodedSamples,this.customHealerStats.numSamplesPerFrame=v,this.customHealerStats.pullAdspPayloadType=S.extra.pullAdspPayloadType,this.customHealerStats.concealSamples=S.extra.concealSamples,this.customHealerStats.stretchSamples=S.extra.stretchSamples,this.customHealerStats.healedSamples=S.extra.healedSamples,this.customHealerStats.decodedSamples=S.extra.decodeSamples,this.packetPullProccesingTimes.addSample(S.extra.processingTime),this.customHealerStats.cnpPullCount=S.extra.totalCountCNGeneratedFrames,this.customHealerStats.cngSamples=S.extra.cngSamples,(C=this.pullProcessingTimePerStreamNumber)[f]??(C[f]=new Na(0,200)),this.pullProcessingTimePerStreamNumber[f].addSample(S.extra.processingTime),this.packetPullTimings.addSample(S.pullTiming)}getWebRtcCompatibleStats(){return this.inboudStats}getWasmStats(){this.customHealerStats.pushProcessingTimes=this.packetPushProccesingTimes.getFrequencies(),this.customHealerStats.pullProcessingTimes=this.packetPullProccesingTimes.getFrequencies(),this.customHealerStats.pullNumOfStreamsCounter=this.numOfStreamsCounter.getFrequencies(),this.customHealerStats.pullTimings=this.packetPullTimings.getFrequencies();for(const g of Object.keys(this.pullProcessingTimePerStreamNumber))this.customHealerStats.pullProcessingTimePerStreamNumber[g]=this.pullProcessingTimePerStreamNumber[g].getFrequencies();return this.customHealerStats}getDecoderStats(){return this.decoderStats}},Na=class{constructor(g,f){this.minSample=g,this.maxSample=f,this.frequencyDict={}}addSample(g){if(void 0===g)return;const f=Math.min(this.maxSample,Math.max(this.minSample,g));this.frequencyDict[f]=(this.frequencyDict[f]??0)+1}getFrequencies(){return{...this.frequencyDict}}};function createAudioWasmEncoderProxy(g,f,S){return new ka(g,f,S)}var ka=class extends Ma{constructor(g,f,S){super(g,f,3,S)}init(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[g]}})}setCodec(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[g]}})}debugLogging(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[g]}})}},La=["SatinFB"],Fa=class extends Ht{constructor(g){super(),this.logger=g,this.codec="None",this.injectWebMA()}dispose(){super.dispose(),this.imp?.dispose(),this.removeWebMA()}activateTransform(g){this.logger.safe.debug("Activating WASM encoder transform"),g.addTransform(this)}deactivateTransform(){this.logger.safe.debug("Deactivating WASM encoder transform"),this.imp.dispose(),this.imp=null,this.encodersInitCodes=void 0,this.codec="None"}createBaseInstance(g){this.logger.warn("WASM encoder could only be instantiated in worker")}createWorkerInstance(g,f){this.imp=createAudioWasmEncoderProxy(g,f,this),this.imp.init(La)}setCodec(g){if(this.logger.safe.debug(`Setting codec to ${g}`),!this.encodersInitCodes)return this.logger.safe.debug("Encoder is not initialized yet, postponing codec setting"),void(this.codec=g);this.codec!==g&&(this.codec=g,this.setCodecInternal())}isCodecAllowed(g){return La.includes(g)}negotiationCompleted(g){g||(this.codec="None",this.imp?.setCodec(this.codec))}initDone(g){this.logger.safe.info(`initDone: ${JSON.stringify(g)}`),this.encodersInitCodes=g,this.setCodecInternal()}packetEncoded(g){0!==g&&this.logger.safe.info(`encode failed: ${g}`)}setCodecInternal(){const g=this.encodersInitCodes[this.codec]??-2147024809;if("None"!==this.codec&&0!==g)return this.logger.safe.error(`WASM encoder is failed to init codec ${this.codec}, err code: ${g}`),void this.event("initCodecFailed").raise(g);this.imp.setCodec(this.codec)}injectWebMA(){const g=window.webMA;g&&(g.wasmEncoder={debugLogging:g=>this.imp?.debugLogging(g)})}removeWebMA(){const g=window.webMA;g&&delete g.wasmEncoder}},xa=M,Ua=class extends Ht{constructor(g,f,S){super(),this.encStreamsManager=g,this.logger=f,this.configProvider=S,this.isEnabled=!1,this.sessionStats=new Ba,this.subs=[],this.codecContext=this.configProvider.mediaConfig.audioCodecContext,this.codecConfig=this.configProvider.config.useInsertableStreams?.audioWasmCodec}get decoder(){return this.decoderImp}get encoder(){return this.encoderImp}init(g,f){if(!g||!this.codecContext||!this.codecConfig?.enable)return;this.isEnabled=!0;const S=this.codecConfig.maxNumOfStreamsFactor||1;this.decoderImp=new Oa(this.logger.createChild("AudioWasmDecoder"),this.configProvider,S,f),this.codecConfig.enableSend&&(this.encoderImp=new Fa(this.logger.createChild("AudioWasmEncoder"))),this.subscribeToStreamManagerEvents(this.encStreamsManager),this.subscribeToCodecsEvents()}dispose(){super.dispose(),this.unsubscribeFromEvents(),this.decoderImp?.dispose(),this.encoderImp?.dispose()}getSessionEvents(){return this.sessionStats.getSessionEvents()}prepareForNegotiation(g){if(!this.isEnabled)return;const f=this.decoderImp?.getUnmixedAudioProvider()?.configured?"MUCHv2":this.codecConfig.codec||"None";this.codecContext.codec!==f&&(this.codecContext.initSendFailed=!1),this.codecContext.lastUsedCodec=this.codecContext.codec,this.codecContext.codec=f,this.codecContext.enabledLocally=!this.codecContext.initFailed&&"None"!==f,this.codecContext.enabledForSend=this.codecContext.enabledLocally&&!this.codecContext.initSendFailed&&!!this.codecConfig?.enableSend&&this.encoder?.isCodecAllowed(f),this.logger.safe.info(`Audio codec state: context=${JSON.stringify(this.codecContext)}`),this.codecContext.initFailed||!g&&this.codecContext.disabledRemotely||(this.sessionStats.toggleState("None"!==f),this.decoderImp?.setCodec(f),this.encoderImp?.setCodec(this.codecContext.enabledForSend?f:"None"))}negotiationCompleted(){if(!this.isEnabled)return!1;const g=this.codecContext.enabledLocally&&!this.codecContext.disabledRemotely;return this.decoderImp?.negotiationCompleted(g),this.encoderImp?.negotiationCompleted(g),this.sessionStats.negotiationCompleted(g,this.codecContext.enabledForSend),g}configureSpatialAudio(g,f){if(!this.isEnabled)return!1;this.decoderImp?.configureSpatialAudio(g);return(g&&"MUCHv2"!==this.codecContext.codec||!g&&"MUCHv2"===this.codecContext.codec)&&this.event("negotiationNeeded").raise(f),!0}subscribeToStreamManagerEvents(g){this.subs.push(g.on("onTransformsCollectionCreated",(g=>this.handleTransformsCollectionCreated(g))),g.on("onTransformsCollectionCleared",(g=>this.handleTransformsCollectionCleared(g))))}handleTransformsCollectionCreated(g){"Audio"===g.mediaType&&(this.decoderImp&&"Receiver"===g.objType?this.decoderImp.activateTransform(g.collection):this.encoderImp&&"Sender"===g.objType&&this.encoderImp.activateTransform(g.collection))}handleTransformsCollectionCleared(g){"Audio"===g.mediaType&&(this.decoderImp&&"Receiver"===g.objType?this.decoderImp.deactivateTransform():this.encoderImp&&"Sender"===g.objType&&this.encoderImp.deactivateTransform())}subscribeToCodecsEvents(){this.decoderImp&&this.subs.push(this.decoderImp.on("initFailed",(g=>this.handleCodecInitFailed("decoder",g)))),this.encoderImp&&this.subs.push(this.encoderImp.on("initCodecFailed",(g=>this.handleCodecInitFailed("encoder",g))))}unsubscribeFromEvents(){this.subs.forEach((g=>g.dispose())),this.subs=[]}handleCodecInitFailed(g,f){"decoder"===g?this.codecContext.initFailed=!0:this.codecContext.initSendFailed=!0;const S=generateCauseId();this.logger.safe.warn(`[${S}] Audio ${g} init failed ${f}`),this.sessionStats.initFailed(f,g),this.event("negotiationNeeded").raise(S)}},Va=class _AudioCodecSessionStats{constructor(){this.sessionEvents={negotiationAttempts:[],toggleCount:0,negotiatedCount:0,failedNegotiationCount:0,decoderInitError:0,encoderInitError:0}}toggleState(g){this.sessionEvents.toggleCount++,this.inProgressNegotiation={ts:Date.now(),enabled:g,negotiated:!1,sendEnabled:!1},arrayLimitedPush2(this.sessionEvents.negotiationAttempts,this.inProgressNegotiation,_AudioCodecSessionStats.maxStoreNegotiations)}negotiationCompleted(g,f){this.inProgressNegotiation&&(this.sessionEvents.negotiatedCount+=g?1:0,this.sessionEvents.failedNegotiationCount+=this.inProgressNegotiation.enabled&&!g?1:0,this.inProgressNegotiation.negotiated=g,this.inProgressNegotiation.sendEnabled=f,this.inProgressNegotiation=void 0)}initFailed(g,f){"decoder"===f?this.sessionEvents.decoderInitError=g:this.sessionEvents.encoderInitError=g}getSessionEvents(){return(0,xa.clone)(this.sessionEvents)}};Va.maxStoreNegotiations=5;var Ba=Va,Ha=class{constructor(g,f){this.logger=f,this.clientsMap=new Map,this.loaded=!1,this.initDefer=new dt;try{this.worker=g.getWorker(this.logger),this.worker.onmessage=g=>this.handleEvent(g.data),this.worker.onerror=g=>{this.logger.safe.error(`error inside worker: ${g.message}`),this.initDefer.resolve()}}catch(g){this.logger.safe.error("failed to create worker"),this.initDefer.resolve()}}initialize(){return Promise.race([this.initDefer.promise,delay(5e3).then((()=>{this.loaded??this.logger.safe.warn("worker initialization timeout")}))])}isWorkerLoaded(){return this.loaded}sendTransformCommand(g,f,S=[]){const v={type:"transform",clientId:g,payload:f};this.worker?.postMessage(v,S)}subscribeClient(g,f,S){const v=this.clientsMap.get(g)??new Map;v.set(f,S),this.clientsMap.set(g,v)}unsubscribeClient(g){this.clientsMap.delete(g)}dispose(){const g={type:"generic",payload:{operation:"dispose"}};this.worker?.postMessage(g),this.worker?.terminate()}handleEvent(g){switch(g.type){case"init":this.initDefer.resolve(),this.loaded=!0,this.logger.safe.info("worker initialized");break;case"transform":{const f=this.clientsMap.get(g.payload.clientId),S=f?.get(g.payload.event.transformType);S?S(g.payload.event):this.logger.safe.error(`received event for unknown Client ${g.payload.clientId} or transformType ${g.payload.event.transformType}: ${g.payload.event.name}`)}break;case"log":switch(g.level){case"debug":this.logger.safe.debug(g.msg);break;case"info":this.logger.safe.info(g.msg);break;case"warn":this.logger.safe.warn(g.msg);break;case"error":this.logger.safe.error(g.msg);break;default:this.logger.safe.error(`unknown log level ${g.level}`)}break;default:this.logger.safe.error(`received unsupported event from worker ${g.type}`)}}},$a=7,ja=31,Ga=class{constructor(g){this.logger=g,this.transformType=0}transform(g){return this.processChunk(g),g}dispose(){}getStartCodeSize(g){const f=g.getUint32(0);return 1===f?4:256==(4294967040&f)?3:0}processChunk(g){if("key"!==g.type)return;const f=this.isH264KeyFrame(g.data)?`${this.getH264Profile(g.data)}(H264)`:"unknown";this.logger.info(`keyframe metadata: ${JSON.stringify(g.getMetadata())}, profile=${f}`)}isH264KeyFrame(g){if(g.byteLength<7)return!1;const f=new DataView(g),S=this.getStartCodeSize(f);return!!S&&(f.getUint8(S)&ja)===$a}getH264Profile(g){const f=new DataView(g),S=this.getStartCodeSize(f);return(16777215&f.getUint32(S)).toString(16)}},qa=class extends Ma{constructor(g,f){super(g,f,0,void 0)}},Wa=class{constructor(g){this.logger=g}createBaseInstance(g){this.imp=new Ga(this.logger.safe),g.addTransform(this.imp)}createWorkerInstance(g,f){this.imp=new qa(g,f)}},za=class{constructor(){this.transformType=1,this.muted=!1}transform(g){return this.muted?null:g}mute(g){this.muted=g}dispose(){}},Ka=class extends Ma{constructor(g,f){super(g,f,1,void 0)}mute(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"mute",args:[g]}})}},Ja=class{constructor(g){this.logger=g}createBaseInstance(g){this.imp=new za,g.addTransform(this.imp)}createWorkerInstance(g,f){this.imp=new Ka(g,f)}mute(g){this.logger.safe.info(`Dropping audio chunks: ${g}`),this.imp.mute(g)}},Ya=class{constructor(g,f){this.transforms=[];const S=new TransformStream({transform:(g,f)=>{let S=g;for(const g of this.transforms)if(S=g.transform(S),!S)return;f.enqueue(S)}});g.pipeThrough(S).pipeTo(f)}clearTransforms(){for(const g of this.transforms)g.dispose();this.transforms=[]}addTransform(g){this.transforms.push(g)}getTransform(g){return this.transforms.find((f=>f.transformType===g))}},Qa=class extends Ke{constructor(){super(),this.subs=[]}get streams(){return this.sessionAudioProvider?.streams??[]}get comfortNoiseStream(){return this.sessionAudioProvider?.comfortNoiseStream??null}get configured(){return this.sessionAudioProvider?.configured??!1}get active(){return this.sessionAudioProvider?.active??!1}get codec(){return this.sessionAudioProvider?.codec??"None"}setSessionStreamsProvider(g){this.unsubscribeFromStreamEvents(),this.sessionAudioProvider=g,this.subscribeForStreamEvents(),this.event("onStreamsChanged").raise(),this.event("onActiveStateChanged").raise(this.active)}dispose(){super.dispose(),this.unsubscribeFromStreamEvents()}subscribeForStreamEvents(){this.sessionAudioProvider&&this.subs.push(this.sessionAudioProvider.on("onStreamsChanged",(()=>this.event("onStreamsChanged").raise())),this.sessionAudioProvider.on("onStreamSourcesUpdated",(g=>this.event("onStreamSourcesUpdated").raise(g))),this.sessionAudioProvider.on("onConfiguredStateChanged",(g=>this.event("onConfiguredStateChanged").raise(g))),this.sessionAudioProvider.on("onActiveStateChanged",(g=>this.event("onActiveStateChanged").raise(g))),this.sessionAudioProvider.on("onActiveCodecChanged",(g=>this.event("onActiveCodecChanged").raise(g))))}unsubscribeFromStreamEvents(){this.subs.forEach((g=>g.dispose())),this.subs=[]}},Xa=class extends Ke{constructor(g,f,S,v,C){super(),this.allowVirtualDeviceInCall=g,this.defaultDeviceManager=f,this.logger=S,this.callStats=v,this.isMediaSending=C,this.stats=[],this.selectedVirtualDevice={camera:void 0,screenshare:void 0},this.subs=[this.defaultDeviceManager.on("onVirtualDevicesChanged",(()=>this.handleRegisteredDeviceChange()))],this.logger.info(`allowVirtualDeviceInCall: ${g}`)}get isVirtualDeviceEnabled(){return this.allowVirtualDeviceInCall}selectDevices(g){const f=this.defaultDeviceManager.getRegisteredDevices(),S=f.find((f=>f.id===g.camera)),v=f.find((f=>f.id===g.screenshare));this.logger.info(`Selecting virtual devices, camera: ${S?.id}, screenshare: ${v?.id}`);const C={camera:this.selectedVirtualDevice.camera?.id,screenshare:this.selectedVirtualDevice.screenshare?.id};g.camera!==C.camera||g.screenshare!==C.screenshare?(this.selectedVirtualDevice={camera:S,screenshare:v},this.addToCallStat({type:"VirtualDeviceSelected",payload:this.selectedVirtualDevice}),this.event("onSelectedVirtualDevicesChanged").raise(g,C)):this.logger.info("Virtual Device did not change.")}getSelectedDevices(){return Object.entries(this.selectedVirtualDevice).reduce(((g,[f,S])=>(g[f]=S?.id,g)),{})}getDeviceManager(g){return this.allowVirtualDeviceInCall?this.getDeviceManagersForVirtualDevice(g)[0]:this.defaultDeviceManager}getDeviceManagersForVirtualDevice(g){return"Video"===g&&this.selectedVirtualDevice.camera?(this.logger.info(`Using Virtual Device (DM), type: ${g}`),this.selectedVirtualDevice.camera.getDeviceManagers()):"ScreenShare"===g&&this.selectedVirtualDevice.screenshare?(this.logger.info(`Using Virtual Device (DM), type: ${g}`),this.selectedVirtualDevice.screenshare.getDeviceManagers()):(this.logger.info(`Using default DM, type: ${g}`),[this.defaultDeviceManager])}getDefaultDeviceManager(){return this.defaultDeviceManager}dispose(){this.stats=[],this.subs.forEach((g=>g.dispose())),super.dispose()}hasDevice(g){return this.defaultDeviceManager.id===g||[...this.selectedVirtualDevice.camera?.getDeviceManagers()??[],...this.selectedVirtualDevice.screenshare?.getDeviceManagers()??[]].some((f=>f?.id===g))}addToCallStat(g){const f=this.stats.push(g);this.callStats.appendCallDeviceManagerInfo({events:JSON.stringify(f)})}handleRegisteredDeviceChange(){const g=this.defaultDeviceManager.getRegisteredDevices(),{camera:f,screenshare:S}=this.selectedVirtualDevice;let v=!1,C=!1;f&&(v=g.some((g=>g.id===f.id)),this.logger.info(`Selected camera(${f.id}) in call, isCameraValid:${v}`)),S&&(C=g.some((g=>g.id===S.id)),this.logger.info(`Selected SS(${S.id}) in call, isScreenShareValid:${C}`)),this.selectDevices({camera:v?f.id:void 0,screenshare:C?S.id:void 0})}isModalityEnabled(g){return this.isMediaSending(getSkypeMediaType(g))}},Za=class{constructor(g,f){this.logger=g,this.configProvider=f,this.debounceMap=new Map,this.configProvider.config.remoteUFD?.enabled&&Object.keys(this.configProvider.config.remoteUFD.list).length&&this.logger.info(`Remote UFDs list: ${JSON.stringify(this.configProvider.config.remoteUFD.list)}`)}raiseIfNeeded(g,f,S){if(this.shouldBeRaised(g,f))if(this.configProvider.config.localUFDDebounceTime)S(this.getState(g));else{clearTimeout(this.debounceMap.get(g.type));const f=setTimeout(S,this.configProvider.config.remoteUFD.debounceTime,this.getState(g));this.debounceMap.set(g.type,f)}}dispose(){for(const g of this.debounceMap.values())clearTimeout(g);this.debounceMap.clear()}shouldBeRaised(g,f){return!!this.configProvider.config.remoteUFD?.enabled&&(!(f>this.configProvider.config.remoteUFD.maxParticipantNumber)&&!!this.configProvider.config.remoteUFD.list[g.type])}getState(g){return{type:"clientMediaUfd",level:"endpoint",content:JSON.stringify(g)}}},eo={reconnect:{metrics:["ReconnectAttempts","ReconnectConnectedCount","RetargetCompletedCount","TerminationReason_code","TerminationReason_subCode","UFDs"],Extensions:["StartTime","EndTime"]},rejectNegotiation:{metrics:["NetworkEvents","ErrorDetail","UFDs","RollbackNegotiation","TerminationReason_code","TerminationReason_subCode"],Extensions:["IceConnectionState","IceConnectionStatePrevious","StartTime","EndTime"]},visibilityHidden:qt.MEDIA_EVENT_FIELDS,lowBattery:qt.MEDIA_EVENT_FIELDS},to=class extends Ke{constructor(g){super(),this.configProvider=g}setDiagnosticsReport(g){this.diagnosticsReport=g}setEventType(g){if(!this.configProvider.config.smallCallTelemetry.enable)return;const f=Object.keys(this.configProvider.config.smallCallTelemetry.mediaUFDEventDictionary),S=this.getLastKnownMediaSessionStats();if(S&&(f?.forEach((f=>{if(f===g){const v=this.configProvider.config.smallCallTelemetry.mediaUFDEventDictionary[f],C={eventType:g,data:this.buildFromDictionary(S,v)};this.setTerminationCodeAndSubCodeToSuccess(C.data),this.event("sendSmallCallTelemetry").raise(C)}})),"reconnect"===g||"rejectNegotiation"===g||"visibilityHidden"===g||"lowBattery"===g)){const f={eventType:g,data:this.buildFromDictionary(S,eo[g])};void 0===f.data.metrics.TerminationReason_code&&this.setTerminationCodeAndSubCodeToSuccess(f.data),this.event("sendSmallCallTelemetry").raise(f)}}getEndCallSmallTelemetry(g){const f=this.getLastKnownMediaSessionStats(),S=this.buildFromDictionary(f,qt.MEDIA_EVENT_FIELDS);return g&&(S.metrics.TerminationReason_code=bi.CODE.SUCCESS,S.metrics.TerminationReason_subCode=bi.SUB_CODE.BEACON),{eventType:g?"tabClosed":"endCall",data:S}}getSmallTelemetryOnBatteryLow(){const g=this.getLastKnownMediaSessionStats(),f=this.buildFromDictionary(g,qt.MEDIA_EVENT_FIELDS);return this.setTerminationCodeAndSubCodeToSuccess(f),{eventType:"lowBattery",data:f}}getLastKnownMediaSessionStats(){if(!this.diagnosticsReport)return;const g=this.diagnosticsReport.rawRootRef.sessions.length;return this.diagnosticsReport.getSessionTelemetry(this.diagnosticsReport.rawRootRef.sessions[g-1]?.sessionId)}buildFromDictionary(g,f){const S={Extensions:{},metrics:{}};if(!g)return S;for(const v in f)g[v]&&(S[v]={},f[v].forEach((f=>{void 0!==g[v][f]&&(S[v][f]=g[v][f])})));return S}setTerminationCodeAndSubCodeToSuccess(g){void 0===g.metrics.TerminationReason_code&&(g.metrics.TerminationReason_code=bi.CODE.SUCCESS,g.metrics.TerminationReason_subCode=bi.CODE.SUCCESS)}},io=class extends Ke{constructor(g,f){super(),this.diagnostics=g,this.configProvider=f,this.hasSentLowBatteryEvent=!1,navigator?.getBattery?.().then((g=>{this.batteryManager=g,g.addEventListener("levelchange",this.onLevelChange.bind(this))}))}dispose(){this.batteryManager&&this.batteryManager.removeEventListener("levelchange",this.onLevelChange)}onLevelChange(g){const f=100*g.level;this.diagnostics.setBatteryLevel(f),f<=this.configProvider.config.lowBatteryThreshold&&!this.hasSentLowBatteryEvent&&(this.event("batteryStatusChanged").raise(f),this.hasSentLowBatteryEvent=!0)}},no=[1,2,9,10,11,12,30,27,28],ro="remote",so="remote",ao=class extends Ke{constructor(g,f){super(),this.isStreaming=g,this.mediaType=f}},oo=class _PluginlessCall extends Ke{constructor(g,f,S,v,C,_,T,I,b,A,P,R,M,w,O,D,N,k){super(S),this.signalingAgent=g,this.mediaAgent=f,this.logger=S,this.telemetryLoggers=v,this.currentUserSkypeIdentity=C,this.groupId=_,this.threadId=T,this.ecsProvider=A,this.trouterService=P,this.accountConfiguration=R,this.vdi3diagnostics=k,this.participants=[],this.isServerMuted=!1,this.isSpeakerMuted=!1,this.isVideoOn=!1,this.isScreenSharingOn=!1,this.callStartedAt=null,this.callHeldAt=null,this.conversationStartTime=null,this.callType=-1,this.failureType=2,this.isEmergency=!1,this.contentSharingSessions=[],this.endpoints={endpointDetails:[]},this.isPreheatEnabled=!1,this.localMediaStreams=[],this.enableRealtimeTelemetry=!1,this.isSharedLineAppearanceV2Activated=!1,this.enableCaptcha=!1,this.requestedHoldState=!1,this.mediaStateConfigurationHelper=new Or({mediaStates:[getMediaState(0,4)]}),this.canToggleAudio=!0,this.canToggleVideo=!0,this.connectCallPromise=Promise.resolve(),this.canToggleScreenSharing=!0,this.callUsesMixer=!1,this.isEscalationInProgress=!1,this.retryOutgoingRenegotiation={retry:!1,causeId:""},this.isHoldInProgress=!1,this.isMuteOnHold=!1,this.callSetupFailed=!1,this.isSomeoneSharing=!1,this.isSomeoneStreamingVideo=!1,this.activeTalkersHistory=[],this.callGotConnected=!1,this.mediaRelayWhiteListingIssue=!1,this.signalingSessionCallOptions=null,this.tsCallingTelemetryReported=!1,this.isCallSetupTelemetrySent=!1,this._isAudioStreamConnected=!1,this._wasAudioStreamConnected=!1,this._callInLobby=!1,this._callIsSetupComplete=!1,this._transferState=0,this._parkState=0,this._muteState=0,this._callCreationTime=(new Date).getTime(),this._commandUrlPresence=0,this._capabilities={canMuteOthers:!1,canUnmuteSelf:!1},this._spamRiskLevel=null,this._spamStirAttestation=null,this._callMode=0,this._isUpdatePropertiesSpecifiedAllowedByEcs=!1,this._deferUsingMicrotask=!1,this._enableResolveScreenSharingWhenNegotiationComplete=!1,this._publishedStatesModified=0,this._participantPublishedStatesMap={},this._endpointPublishedStatesMap={},this._participantChangedEventSkipConfig={skipParticipantsUpdatesOnCall:!0},this._dominantSpeakerChangedEventSkipConfig={skipDominantSpeakerUpdatesOnCall:!0},this.receiveOnlyAudioOnCallStart=!1,this.lastContributingSourceReport=Date.now(),this.instanceNumber=_PluginlessCall.instanceCount++%1e3,this._enableMuteAsync=!1,this._enableUnmuteAsync=!1,this._enableEndpointMeetingRoleCheckForClientCapability=!1,this._enableUserMeetingRolesCheckForClientCapability=!1,this._enableAddModalityGeneric=!1,this._delayedElevationPending=!1,this._delayedElevationQueued=!1,this.maxVbssChannels=0,this.startVM=(g,f,S,v,C)=>this.signalingSession.startOutgoingCall(S,v,{voicemailResourcePath:f.callVoicemailStartOptions.voicemailResourcePath,voicemailItemId:f.callVoicemailStartOptions.voicemailItemId,callToVoicemail:!0},Date.now()-C,g),this.getSignalingSessionCallOptions=g=>{const f={suppressDialout:!g.callStartOptions.ringOthers,isPreheatOnly:1==(1&g.callStartOptions.preheatFlags),onBehalfOf:this.onBehalfOfMri,onBehalfOfUserDisplayName:this.onBehalfOfUserDisplayName,callQueueContext:g.callStartOptions?.callQueueContext,muted:1==(1&g.callStartOptions.muteFlags),invitationType:g.invitationType,participantsToNudge:g.participantsToNudge,routingFlags:g.callStartOptions&&g.callStartOptions.routingFlags,parkContext:g.parkContext,pickupCode:g.pickupCode,scenario:g.callStartOptions&&g.callStartOptions.scenario,callUsesMixer:this.callUsesMixer,clientEndpointCapabilities:g.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:g.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:g.meetingPreferences,alternateId:g.callStartOptions?g.callStartOptions.alternateId:null,meetingRegistrationId:g.callStartOptions?g.callStartOptions.meetingRegistrationId:"",participantPin:g.callStartOptions?g.callStartOptions.participantPin:"",additionalEndpointProperties:g.callStartOptions?.additionalEndpointProperties||null,publishedStates:g.callStartOptions?.publishedStates||null,targetApplicationType:g.callStartOptions?.targetApplicationType,isHuddleGroupCall:g.callStartOptions?.isHuddleGroupCall,captchaContentJson:g.callStartOptions?.captchaContentJson,customHeaderContext:g.callStartOptions?.customHeaderContext,participationPreferences:g.callStartOptions?.participationPreferences,callingLineIdentity:g.callStartOptions?g.callStartOptions.callingLineIdentity:null},S=g.callStartOptions?.invitationDataJson;if(S)try{f.invitationData=JSON.parse(S)}catch(g){throw new Error(`Invalid JSON in invitationData: ${S}`)}return f},this.startOutgoingCall=(g,f,S,v,C)=>this.signalingSession.startOutgoingCall(S,v,this.getSignalingSessionCallOptions(f),Date.now()-C,g),this.joinGivenConversation=(g,f,S,v,C,_)=>{const T=1==(1&f.callStartOptions.muteFlags),I=1==(1&f.callStartOptions.preheatFlags),b=f.callStartOptions?.invitationDataJson,A=f.callStartOptions?.sharedLineCallInvitationContentJson;this.logger.info(`[${g}][joinGivenConversation] muted=${T}, isPreheatOnly=${I},\n            sharedLineCallInvitationContentJson=${A}, invitationDataJson=${b},\n            captchaContentJson=${!!f?.callStartOptions?.captchaContentJson}`);const P={muted:T,isPreheatOnly:I,clientEndpointCapabilities:f.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:f.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:f.meetingPreferences,meetingRegistrationId:f.callStartOptions?f.callStartOptions.meetingRegistrationId:"",participantPin:f.callStartOptions?f.callStartOptions.participantPin:"",additionalEndpointProperties:f?.callStartOptions?.additionalEndpointProperties,applyServerMute:f?.applyServerMute,publishedStates:f?.callStartOptions.publishedStates,invitationData:f?.callStartOptions.invitationDataJson,captchaContentJson:f?.callStartOptions.captchaContentJson,callQueueContext:f?.callStartOptions.callQueueContext,participationPreferences:f?.callStartOptions.participationPreferences};if(A)try{P.sharedLineCallInvitationContent=JSON.parse(A)}catch(g){throw new Error(`Invalid JSON in sharedLineCallInvitationContent: ${A}`)}if(b)try{P.invitationData=JSON.parse(b)}catch(g){throw new Error(`Invalid JSON in invitationDataJson: ${b}`)}return this.signalingSession.joinGivenConversation(_,this.callId,S,v,Date.now()-C,P,g)},this.getParticipantByLegId=(g,f,S)=>{this.logger.info(`getMriByParticipantLegId[${S}] participantLegId ${g}`);for(const S of f.participants)for(const f of S.endpoints.endpointDetails)if(f&&f.participantId&&f.participantId===g)return S;return null},this.executeCallTransfer=(g,f,S,v)=>{this._setTransferState(1);const C=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,f,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return 0===S?this.signalingSession.transferCallAsync(g,"TransferTypeStandard",void 0,v,f):2===S&&this.signalingSession.transferCallAsync(g,"TransferTypeVoicemail",void 0,v,f),C},this.executeConsultCallTransfer=(g,f,S,v,C)=>{this._setTransferState(1);const _=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,v,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return this.signalingSession.consultTransferCallAsync(g,f,S,v,C),_},this.createUpdateParticipantPromise=(g,f)=>this._callOperationHandler.createPendingOperation("UpdateParticipantsProperties",g,f),this._getCallEndOperation=()=>this._callOperationHandler.hasPendingOperation("StopCall")?this._callOperationHandler.waitForOperation("StopCall"):this._callOperationHandler.hasPendingOperation("Reject")?this._callOperationHandler.waitForOperation("Reject"):this._callOperationHandler.hasPendingOperation("CallRedirect")?this._callOperationHandler.waitForOperation("CallRedirect"):Promise.resolve(),this._onAcknowledgeError=(g,f,S,v)=>{S.logFailure(g);let C,_={code:2,success:!1,fatal:!0},T=7;throw isPhaseError("SendAttach",g)&&(C={code:Fi.InternalServerError,subCode:xi.AttachFailed,phrase:Gi.AttachFailed}),isPhaseError("ProcessIncomingCallRequest",g)&&(C={code:Fi.NotAcceptable,subCode:xi.AttachActionFailed,phrase:Gi.BadNotificationPayload},_={code:0,success:!1,fatal:!0}),isOneOfPhaseErrors(zi,g)&&(T=47),g?.error&&g.error.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer&&(C={code:Fi.MediaError,subCode:xi.MediaOfferProcessingError,phrase:Gi.IncompatibleOffer}),this.callTelemetry.updateOperationData("Acknowledge",{phases:v,error:getPIISafeObject(g)},f),this._callOperationHandler.maybeRejectOperation("Acknowledge",_,void 0,f),this.stopInternal({rejectReason:C,causeId:f,terminatedReason:T}),_},this._onAcknowledgeSuccess=(g,f,S)=>(g.logSuccess("success"),this.callTelemetry.updateOperationData("Acknowledge",{phases:f},S),{code:1,success:!0}),this._processOfferedModalities=(g,f)=>{this.handleOfferedModalities(g,f);const S=this.callUsesMixer?void 0:{modalityOverride:g};return this.updateMediaModalities(S,f)},this._handleOfferProcessingError=(g,f,S)=>(S.logFailure(`handleOfferProcessingError=${g}`),g?.error?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer?(this.callTelemetry.recordEvent("IncompatibleOffer",void 0,f),this.signalingSession.supportsNewOfferRequest()?(this.newOfferRequestDeferred=new dt,this.attachToCallAndGetOffer.promise.then((()=>this.mediaSession.rejectNegotiationAsync(g.error,f))).then((()=>this.signalingSession.requestNewOffer(this.mediaSession.getAcceptedTypes(),f))).then((()=>this.newOfferRequestDeferred.promise)).then((g=>this.mediaSession.processOfferAsync(g,f))).catch((g=>(this.callTelemetry.recordEvent("NewOfferFailed",getPrintableObject(g),f),Promise.reject(g))))):Promise.reject(g)):Promise.reject(g)),this._trySendProvisionalMediaAnswer=g=>Promise.resolve(void 0).then((()=>this.mediaSession.createAnswerAsync(!0,g))).then((g=>g.blob?(this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",void 0,generateCauseId(),{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.signalingSession.setProvisionalAnswerAsync(g).then((()=>this.mediaAcknowledgmentOperation))):Promise.resolve(void 0))),this.checkForCallIdUpdate=(g,f)=>{if(this.callId!==g){this.logger.info(`[${f}][checkForCallIdUpdate] old=${this.callId}, new=${g}`),this.setCallId(g);try{this.event("callIdChanged").raise(this.callId)}catch(g){this.logger.error(`Error raising call ID change: ${g}`)}this.raiseChanged()}},this.handleRemoteParticipantStateInOneToOneCall=g=>{if(!this.callUsesMixer&&3===this.state){const f=this.participants[0];f&&f.setState(3,void 0,g)}},this.handleRemoteParticipantJoinedInOneToOneCall=(g,f)=>{if(!this.callUsesMixer&&3===this.state){const S=this.participants.filter((f=>f.id===g.id))[0];S?S.setState(3,void 0,f):this.logger.logFailure(`[${f}][handleRemoteParticipantJoinedInOneToOneCall]unable to find particpant ${scrubMriOrOmit(g.id)}`)}},this.handleRemoteParticipantStateInObservingCall=(g,f,S)=>{const v=f.isLobby;if(8===this.state){const f=v?7:3;g.setState(f,void 0,S)}},this.getTelemetryFromPhaseExecution=g=>{const f={phase:g.phase,phases:g.phases,code:g.error&&g.error.code,subCode:g.error&&g.error.subCode,message:g.error&&g.error.message,error:g.error};return(f.code||f.message)&&delete f.error,f},this._setTransferState=g=>{this.transferState!==g&&(this.logger.info(`Transfer: state set: ${g}`),this._transferState=g,this.callTelemetry.recordEvent("_SetTransferState",{state:g}),this.raiseChanged())},this._setParkState=g=>{this.parkState!==g&&(this.logger.info(`Parking: state set: ${g}`),this._parkState=g,this.callTelemetry.recordEvent("_SetParkState",{state:g}),this.raiseChanged())},this.prepareNegotiationResultForTelemtry=g=>({isComplete:g.isComplete,activeModalities:g.activeModalities,configuredModalities:g.configuredModalities,initiator:scrubMriOrOmit(g.initiator),attemptedModalities:g.attemptedModalities,offeredModalities:g.offeredModalities}),this.prepareTelemetryForOfferAnswer=g=>g&&g.mediaContent&&{isRenegotiation:!!g.renegotiation,isEscalation:!!g.mediaContent.isTwoPartyToMultiPartyEscalation,mediaTypes:g.mediaTypes,newOffer:g.mediaContent.newOffer},this.updateLocalParticipantEndpoints=g=>{const f=this.logger.createFnLogger("updateLocalParticipantEndpoints",""),S=[];(0,Ki.forEach)(g,(g=>{const f=convertSignalingEndpointDetails(g,this.getSelfClientEndpointCapabilities());S.push(f)})),this.endpoints.endpointDetails=S;const v=this.getDataChannelSourceId();-1!==v&&this.dataChannel&&this.dataChannel.setDataChannelSourceId(v),f.info(`selfEndpointDetails=${getPIISafeEndpointDetails(this.endpoints)}`)},this.handleParticipantsMutedUpdated=(g,f)=>{const S=this.logger.createFnLogger("handleParticipantsMutedUpdated",f);if(void 0!==g?.info){this.logger.info(`handleParticipantsMutedUpdated: number of infos: ${Object.keys(g.info).length}`);for(const f of Object.keys(g.info)){const v=this.getParticipant(f);v?v.handleServerMutedInfoUpdate(g.info[f]):S.info(`Cannot find local participant ${scrubMriOrOmit(f)}`)}}else S.info("Ignored, no mute participant info.")},this.handleSelfUnmuteUpdatedInfo=(g,f)=>{const S=this.logger.createFnLogger("handleSelfUnmuteUpdatedInfo",f);if(void 0!==g?.info)for(const v of Object.keys(g.info)){const C=g.info[v];if(v===this.localSignalingParticipant.id){const g=(0,Ki.find)(C,(g=>g.participantId===this.localSignalingParticipant.participantId));if(void 0===g){S.info(`Cannot find local participant ${scrubMriOrOmit(v)}`);continue}const _=(0,Ki.find)(this.localSignalingParticipant.endpointDetails,(f=>f.participantId===g.participantId));handleMuteUnmuteParticipantInfo(this.logger,_,g,!1)&&this.handleSelfServerMutedState(f)}}else S.info("Ignored, no unmute participant info.")},this.state=0,this.terminatedReason=0,this.callStats=new Mr,this.callDeviceManager=this.createCallDeviceManager(),this.callTelemetry=new Ii(this.logger,this._callCreationTime),this.collectMediaStatsDeferred=new dt,this.setCallId(I),this.setGroupId(_),this.setThreadId(T),this.setMessageId(M),this.setSkypeId(this.currentUserSkypeIdentity.id),this.setParticipantId(b),this.setCallOrigin(0),this.vdi3diagnostics&&this.callStats.setRpcSessionId(this.vdi3diagnostics.getRPCSessionId()),this.logger=this.logger.createChild((()=>{const g=(this.endpointId||"").substr(0,8),f=(this.participantId||"").substr(0,8);return`Web/${this.instanceNumber}[${this.callId}][${g}][${f}][${this.state}]`})),this._enableMuteAsync=this.ecsProvider.getEcsConfig("SkypeCalling","enableAsyncMute"),this._enableUnmuteAsync=this.ecsProvider.getEcsConfig("SkypeCalling","enableAsyncUnmute"),this._enableEndpointMeetingRoleCheckForClientCapability=this.ecsProvider.getEcsConfig("SkypeCalling","enableEndpointMeetingRoleCheckForClientCapability"),this._enableUserMeetingRolesCheckForClientCapability=this.ecsProvider.getEcsConfig("SkypeCalling","enableUserMeetingRolesCheckForClientCapability"),this._enableAddModalityGeneric=this.ecsProvider.getEcsConfig("SkypeCalling","enableAddModalityGeneric"),this.initializeSignalingSession(b),this.signalingSession.setLocationInfo(w,O,N),this.streamManager=new ls(this.participantId,null,this.callStats.localStats,this.logger),this.mediaAgent&&(this.dataChannel=new Ms(this.logger),this.dataChannel.on("remoteUserEventsReceived",((g,f)=>this.event("remoteUserEventsReceived").raise(g,f))),this.dataChannel.on("onDataChannelStateUpdated",(g=>{"Failed"===g&&(this.logger.error("onDataChannelStateUpdated: datachannel creation failed, will remove data modality"),this.mediaStateConfigurationHelper.removeModality(3),this.updateSignalingDSHMessageSubscription(!0),this.updateMediaModalities())})),this.screenSharingControl=new sa(this.logger,this.dataChannel,this,this.telemetryLoggers,this.ecsProvider,this.mediaAgent.getConfigProvider()),this.mediaAgent.handleSendMidCallTelemetry(this.sendMidCallTelemetry.bind(this)),this.remoteUFDHandler=new Za(this.logger.createChild("remoteUFDHandler"),this.mediaAgent.getConfigProvider()),this.smallCallTelemetry=new to(this.mediaAgent.getConfigProvider()),this.smallCallTelemetry.on("sendSmallCallTelemetry",(g=>this.reportSmallCallEvent(g))));const L={enableErrorConversion:this.ecsProvider.getEcsConfig("SkypeCalling","enableErrorConversion")};this._deferUsingMicrotask=this.ecsProvider.getEcsConfig("SkypeCalling","deferUsingMicrotask"),Vr.instance.setDeferToQueueMicrotask(this._deferUsingMicrotask),Vr.instance.setLogger(S),this.logger.info(`operationHandlerEcsConfig: ${JSON.stringify(L)}`),this._preferredMpLocation=this.ecsProvider.getEcsConfig("SkypeCalling","preferredMpLocation"),this.logger.debug(`preferredMpLocation: ${this._preferredMpLocation}`),this._isUpdatePropertiesSpecifiedAllowedByEcs=this.ecsProvider.getEcsConfig("SkypeCalling","enableUpdateParticipantsSpecified"),this._enableResolveScreenSharingWhenNegotiationComplete=this.ecsProvider.getEcsConfig("SkypeCalling","enableResolveScreenSharingWhenNegotiationComplete"),this._callOperationHandler=new Li(this.logger,this.callTelemetry,L,void 0,((g,f)=>{this.preconditions(g,f)})),this._participantOperationHandler=new Li(this.logger,this.callTelemetry,L),this.setMeetingData(D),this.initializeLiveStreamConfigProvider()}get callMode(){return this._callMode}get callId(){return this._callId}get endpointId(){return this._endpointId}get isHostless(){return this.signalingSession.isHostLessCall}get transferState(){return this._transferState}get parkState(){return this._parkState}get capabilities(){return this._capabilities}get publishedStates(){return this._publishedStates}get dataChannelAdapter(){return this.dataChannel}get participantId(){try{const g=this.signalingSession?.participantManager?.localParticipant?.participantId;this._participantId=g||this._participantId}catch(g){this.logger.error("Error updating participantId")}return this._participantId}get displayName(){return this.localSignalingParticipant.displayName}get role(){return this.localSignalingParticipant.role}get meetingRole(){return this.localSignalingParticipant.meetingRole}get advancedMeetingRole(){return this.localSignalingParticipant.advancedMeetingRole}get meetingRoles(){return this.localSignalingParticipant.meetingRoles}get maskedIdentityDetails(){return{isIdentityMasked:this.localSignalingParticipant.isIdentityMasked,maskedIdSeqNumber:this.localSignalingParticipant.maskedIdSeqNumber,maskedId:this.localSignalingParticipant.maskedId}}get participantType(){return this.localSignalingParticipant.participantType}get isMuted(){return 2===this._muteState||3===this._muteState}get tenantId(){return this.localSignalingParticipant.tenantId}get mediaLegId(){return this._mediaLegId}get isIncomingOneOnOneVideoCall(){return this.isOneToOneCall()&&this.isSomeoneStreamingVideo}get mediaStreams(){return this.streamManager.streams}get origin(){return this._origin}get propertyBag(){return this.localSignalingParticipant.propertyBag}get version(){return this.localSignalingParticipant.version}get isAudioStreamConnected(){return this._isAudioStreamConnected}set isAudioStreamConnected(g){this._isAudioStreamConnected!==g&&(this._isAudioStreamConnected=g,this._wasAudioStreamConnected=this._wasAudioStreamConnected||g,this.raiseChanged())}setMeetingRole(g){g!==this.localSignalingParticipant.meetingRole&&(this.logger.info(`changing self role to [${g}]`),this.localSignalingParticipant.meetingRole=g,this.event("meetingRoleUpdated").raise(g))}setAdvancedMeetingRole(g){g!==this.localSignalingParticipant.advancedMeetingRole&&(this.logger.info(`changing self advanced meeting role to [${g}]`),this.localSignalingParticipant.advancedMeetingRole=g,this.event("advancedMeetingRoleUpdated").raise(g))}setMeetingRoles(g){(0,Ki.isEqual)(g,this.localSignalingParticipant.meetingRoles)||(this.logger.info(`changing self meeting roles to [${g}]`),this.localSignalingParticipant.meetingRoles=g,this.event("meetingRolesUpdated").raise(g))}setParticipantType(g){g!==this.localSignalingParticipant.participantType&&(this.logger.info(`changing self participant user type to [${g}]`),this.localSignalingParticipant.participantType=g,this.event("participantTypeUpdated").raise(g))}setPropertyBag(g){g&&!(0,Ki.isEqual)(g,this.localSignalingParticipant.propertyBag)&&(this.logger.info(`changing self participant property bag to [${g}]`),this.localSignalingParticipant.propertyBag=g,this.event("propertyBagUpdated").raise(g))}setPropertyRosterVersion(g){g!==this.localSignalingParticipant.version&&(this.logger.info(`changing self participant property version to [${g}]`),this.localSignalingParticipant.version=g,this.event("propertyRosterVersionUpdated").raise(g))}setMaskedIdentityDetails(g=!1,f,S){this.localSignalingParticipant.isIdentityMasked===g&&this.localSignalingParticipant.maskedIdSeqNumber===f&&this.localSignalingParticipant.maskedId===S||(this.localSignalingParticipant.isIdentityMasked=g,this.localSignalingParticipant.maskedIdSeqNumber=f,this.localSignalingParticipant.maskedId=S,this.logger.info(`self participant masked identity details updated to [${JSON.stringify(this.maskedIdentityDetails)}]`),this.event("maskedIdentityDetailsUpdated").raise(this.maskedIdentityDetails))}setIsSomeoneStreamingVideo(g){this.logger.debug(`setting isSomeoneStreamingVideo to [${g}]`),this.isSomeoneStreamingVideo=g}setJoinAsStreamingUser(g){g!==this.joinAsStreamingUser&&(this.logger.info(`setting self join as streaming user to [${g}]`),this.joinAsStreamingUser=g)}setOtpIdentity(g){g!==this.otpIdentity&&(this.logger.info("setting self participant optIdentity"),this.otpIdentity=g)}get spamRiskLevel(){return this._spamRiskLevel}set spamRiskLevel(g){g&&(this._spamRiskLevel=g)}isMultiVBSSEnabled(){return this.maxVbssChannels>=1}get spamStirAttestation(){return this._spamStirAttestation}set spamStirAttestation(g){g&&(this._spamStirAttestation=g)}getScreenHandle(g){if(!this.sharedScreenHandle){const f=!!this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled,S=!!this.mediaSession&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&!this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing,v=this.mediaStateConfigurationHelper.isSending(0)&&S&&f,C=3===g?.getType()?g?.getDeviceId():void 0,_=this.callDeviceManager.getDeviceManager(getAgentMediaType(2));_.setAudioSharingRequested(v),this.sharedScreenHandle=_.createDevicesHandle({audio:v,sharing:!0},"pluginlessCall:getScreenHandle()",C),this.sharedScreenHandle.on("onStreamStateChanged",((g,f)=>this.onSharingStreamStateChanged(g)))}return this.sharedScreenHandle}setCallOrigin(g){this.logger.info(`Set call origin to ${g}`),this._origin=g,this.callTelemetry.setCallOrigin(g),this.callTelemetry.recordEvent("_SetCallOrigin",{origin:g})}setMediaLegId(g){this._mediaLegId=g,this.callStats.setMediaLegId(g)}setCallId(g){this.callTelemetry.setCallId(g),this.callStats.setCallId(g),this._callId=g}setEndpointId(g){this._endpointId=g,this.logger.info(`[endpointId=${truncate(this._endpointId,8)}]`),this.callTelemetry.setEndpointId(g),this.callStats.setEndpointId(g)}setFailureType(g){this.callTelemetry.setFailureType(g),this.failureType=g}setParticipantId(g){this._participantId!==g&&(this._participantId=g,this.logger.info(`[participantId=${this._participantId}]`),this.callTelemetry.setParticipantId(this.participantId),this.event("callLegIdChanged").raise(this.participantId))}setDisplayName(g,f=generateCauseId()){this.logger.info(`[${f}][setDisplayName] displayName=${truncate(g,4)}`),this.localSignalingParticipant.displayName=g,"anonymous"===this.participantType&&(this.callStats.setDisplayName(g),this.callTelemetry.setDisplayName(g),this.signalingSession.setDisplayName(g))}setCallerMri(g){this.callerMri=g,this.logger.info(`[callerMri=${scrubMriOrOmit(this.callerMri)}]`)}setDisplayNameSource(g){this.displayNameSource=g,this.logger.info(`[displayNameSource=${this.displayNameSource}]`)}setTransferorMri(g){const f=stripMriAliases(g);f!==this.transferorMri&&(this.transferorMri=f,this.logger.info(`transferorMri: ${scrubMriOrOmit(this.transferorMri)}`),this.raiseChanged())}setGroupId(g,f=generateCauseId()){this.logger.info(`[${f}][setGroupId] groupId=${scrubMriOrOmit(g)}`),this.groupId!==g&&(this.groupId=g,this.callTelemetry.setGroupId(g),this.event("groupIdChanged").raise(g))}setMeetingData(g){if(g){if(g.meetingCode&&(!this.meetingData||this.meetingData&&g.meetingCode!==this.meetingData.meetingCode)){const f=g.meetingCode;this.logger.info(`[setMeetingData] meetingCode=${!!f}`),this.callTelemetry.setMeetingCode(f),this.signalingSession.setMeetingCode(f)}if(g.meetingUrl&&(!this.meetingData||this.meetingData&&g.meetingUrl!==this.meetingData.meetingUrl)){const f=g.meetingUrl.split("?")[0];this.logger.info(`[setMeetingData] meetingUrl=${!!g.meetingUrl}`),this.callTelemetry.setMeetingUrl(f),this.signalingSession.setMeetingUrl(f)}}this.meetingData=g}setHuddleGroupCall(g){this.isHuddleGroupCall!==!!g&&(this.logger.info(`[setHuddleGroupCall] new isHuddleGroupCall=${g}`),this.isHuddleGroupCall=g,this.callTelemetry.setIsHuddleGroupCall(!0))}onConversationStartTimeChanged(g,f=generateCauseId()){if(this.logger.info(`onConversationStartTimeChanged: Conv start time=${g}`),g&&this._rawConversationStartTime!==g){this.logger.info(`[${f}][onConversationStartTimeChanged] rawConvStartTime=${g}`);try{this.conversationStartTime=new Date(g),this._rawConversationStartTime=g,this.callTelemetry.setConversationStartTime(g)}catch(f){this.logger.warn(`Failed to parse the raw conv start timestamp. Error: ${f}, rawConvStartTime: ${g}`)}}}setComplianceRecordingContent(g,f){try{if(!(0,Ki.isEqual)(this.complianceRecordingContent,f)){this.complianceRecordingContent=f;const S=f?JSON.stringify(f):"";this.callTelemetry.setComplianceRecordingContentLength(S.length),this.logger.info(`[${g}][setComplianceRecordingContent] complianceRecordingContentLength=${S.length}`)}}catch(f){this.logger.error(`[${g}][setComplianceRecordingContent] ${f}`)}}setThreadId(g,f=generateCauseId()){this.threadId!==g&&(this.logger.info(`[${f}][setThreadId] threadId=${getLoggableThreadId(g)}`),this.threadId=g,this.callTelemetry.setThreadId(g))}setBackroomThreadId(g,f=generateCauseId()){this.backroomThreadId!==g&&(this.logger.info(`[${f}][setBackroomThreadId] backroomThreadId=${getLoggableThreadId(g)}`),this.backroomThreadId=g,this.callTelemetry.setBackroomThreadId(g))}setStreamThreadId(g,f=generateCauseId()){this.streamThreadId!==g&&(this.logger.info(`[${f}][setStreamThreadId] streamThreadId=${getLoggableThreadId(g)}`),this.streamThreadId=g,this.callTelemetry.setStreamThreadId(g))}setLobbyThreadId(g,f=generateCauseId()){this.lobbyThreadId!==g&&(this.logger.info(`[${f}][setLobbyThreadId] lobbyThreadId=${getLoggableThreadId(g)}`),this.lobbyThreadId=g,this.callTelemetry.setLobbyThreadId(g))}setMessageId(g,f=generateCauseId()){this.logger.info(`[${f}][setMessageId] messageId=${scrubMriOrOmit(g)}`),this.messageId=g,this.callTelemetry.setMessageId(g)}setSkypeId(g,f=generateCauseId()){this.skypeId!==g&&(this.logger.info(`[${f}][setSkypeId]`),this.skypeId=g,this.callTelemetry.setSkypeId(g))}setCallType(g,f){const S=this.logger.createFnLogger("setCallType",f);S.info(`current=${this.callType}, newValue: ${g}`),2!==this.callType||1!==g?g!==this.callType&&(this.callType=g,this.callTelemetry.setCallType(g),2===g&&this.callStats.localStats.call.event(2),this.raiseChanged()):S.logFailure("De-escalating to P2P should not happen!")}setConversationType(g,f){this.logger.createFnLogger("setConversationType",f).info(`current=${this.conversationType}, newValue=${g}`),g!==this.conversationType&&(this.conversationType=g,this.callTelemetry.setConversationType(g),this.raiseChanged())}setCallUsesMixer(g,f){this.callUsesMixer!==!!g&&(this.logger.info(`[${f}][setCallUsesMixer] new value=${g}`),this.callUsesMixer=g,this.callTelemetry.recordEvent("_CallUsesMixer",{newValue:g},f),this.dataChannel.setConfigProviderView(this.mediaSession?.getSessionConfig()))}_setMaxVbssChannels(g,f){this.logger.createFnLogger("MaxVbssChannels",f).info(`current=${this.maxVbssChannels}, newValue=${g}`),g!==this.maxVbssChannels&&(this.maxVbssChannels=g,this.callTelemetry.recordEvent("_setMaxVbssChannels",{MaxVbssChannels:g},f),this.raiseChanged())}setIsEscalationInProgress(g,f){this.logger.info(`[${f}][setIsEscalationInProgress] currentValue=${this.isEscalationInProgress}, newValue=${g}`),this.isEscalationInProgress=g,this.allowScreenSharingControl()&&this.screenSharingControl.setIsEscalationInProgress(g),this.callTelemetry.recordEvent("_EscalationInProgress",void 0,f)}setFromApplicationType(g,f){g&&(this.fromApplicationType=g,this.callTelemetry.recordEvent("_SetFromApplicationType",{fromApplicationType:g},f))}setEnableCaptcha(g){g!==this.localSignalingParticipant.enableCaptcha&&(this.logger.info(`setting self participant to enable captcha to [${g}]`),this.localSignalingParticipant.enableCaptcha=g,this.enableCaptcha=g)}processCallStartOptions(g,f){const S=this.logger.createFnLogger("_ProcessCallStartOptions",f);try{1&g.preheatFlags&&(this.isPreheatEnabled=!0)}catch(g){S.logFailure(g)}}getlocalScreenShareStream(){return(0,Ki.find)(this.localMediaStreams,(g=>2===g.mediaType))}setMeetingLayout(g,f){throw new Error("Method not implemented.")}async selectDevices(g){this.callDeviceManager.isVirtualDeviceEnabled?this.callDeviceManager.selectDevices(g):this.logger.error("allowVirtualDeviceInCall not enabled.")}async getSelectDevices(){return this.callDeviceManager.getSelectedDevices()}createStage(g){throw new Error("Method not implemented.")}updateDisplayName(g){this.logger.info("updating displayName"),this.setDisplayName(g),this.signalingSession.participantManager.localParticipant.displayName=g}init(g){if(this.logger.info(`init callInitOptions:${getPIISafeCallInitOptions(g)}`),this.signalingSessionCallOptions={teamsMessageId:g.messageId,enableGroupCallMeetupGeneration:g.enableGroupCallMeetupGeneration,meetingInfo:g.meetingInfo,emergencyContent:g.emergencyContent?JSON.parse(g.emergencyContent):void 0,broadcastContext:g.broadcastContext,endpointMetadata:g.endpointMetadata},this.setMessageId(g.messageId),this.onBehalfOfMri=g.onBehalfOf,this.onBehalfOfUserDisplayName=g.onBehalfOfUserDisplayName,g.threadId&&(this.setThreadId(g.threadId),this.signalingSession.setThreadId(g.threadId)),this.groupId&&this.signalingSession.setGroupId(this.groupId),this.signalingSession.setCallOptions(this.signalingSessionCallOptions),g.transferContext){switch(this.logger.info("Transfer: Call.init, set transferContext",scrubITransferContext(g.transferContext)),this.signalingSession.setTransferContext(g.transferContext.context),g.transferContext.transferType){case 1:this.setCallOrigin(2);break;case 0:this.setCallOrigin(1);break;case 2:this.setCallOrigin(3);break;default:throw new Error(`TransferType: ${g.transferContext.transferType} doesn't have a switch option`)}g.transferContext.context.callAcceptanceCallback?this._transferredCallAcceptanceCallback=g.transferContext.context.callAcceptanceCallback:this.logger.info("[failed]Transfer: Missing transferred call acceptance callback"),g.transferContext.transferorMri&&this.setTransferorMri(g.transferContext.transferorMri)}this.setIsEmergency(!!g.isEmergency),this.raiseChanged()}async initAsync(g){return this.init(g)}getIncomingRawAudioStream(g=generateCauseId()){if(!this.mediaSession)throw this.logger.error("can not execute getIncomingRawAudioStream as there is no mediaSession"),new Error("NoMediaSession");return this.mediaSession.getIncomingRawAudioStream(g)}getUnmixedAudioProvider(){return this.unmixedAudioProvider?Promise.resolve(this.unmixedAudioProvider):Promise.reject("No audio provider available")}setDeviceManager(g){}async startVideo(g,f=generateCauseId()){return this.startStopVideo(!0,f,g)}async stopVideo(g,f=generateCauseId()){return this.startStopVideo(!1,f,g)}async dumpVideoSourceImages(){return Promise.reject(60)}async hold(g,f=generateCauseId(),S,v){const C=this.logger.createFnLogger("Hold",f);return C.info(`[Hold][${f}] negotiationTag ${g} hold options: ${safeJsonStringify(S)}`),4===this.state?(C.logFailure("Trying to put a call on hold which is already held state, early resolving the promise"),Promise.resolve(void 0)):S?.isLocal?this.localHold(f,S,v):this.holdWithRenegotiate(f,S)}async holdWithRenegotiate(g,f){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,g,f):(this.logger.logFailure(`[Hold][${g}] Trying to hold a call in an invalid state: ${this.state}`),Promise.reject(`Trying to hold a call in an invalid state: ${this.state}`))}async localHold(g,f,S){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,g,f,S):(this.logger.logFailure(`[LocalHold][${g}] Trying to hold a call in an invalid state: ${this.state}`),Promise.reject(`Trying to hold a call in an invalid state: ${this.state}`))}async unhold(g,f=generateCauseId()){const S=this.logger.createFnLogger("Unhold",f);return 3===this.state?(S.logFailure("Trying to resume a call which is already in connected state, early resolving the promise"),Promise.resolve(void 0)):4===this.state?(S.info(`current hold state ${this.requestedHoldState}`),this.setHold(!1,f)):(S.logFailure(`Trying to resume a call in an invalid state: ${this.state}`),Promise.reject(`Trying to resume a call in an invalid state: ${this.state}`))}canMerge(g,f){const S=g.isOneToOneCall(),v=3===this.state,C=4===g.state,_=S&&v&&C;return this.logger.info(`[${f}][canMerge] Call ${g.callId} isOneToOne ${S} isCallConnected ${v} call.state ${this.state} isMergeOnHold ${C} mergeCall.state ${g.state} CanMerge result: ${_}`),_}async updateEndpointMetadata(g,f=generateCauseId()){return this.signalingSession.updateEndpointMetadata(g,f)}async sendDtmfTone(g){if(this.mediaSession){const f=this.toneToString(g);return f?(this.logger.info(`[${causeId}][sendDtmfTone]DtmfTone: <omitted>`),Promise.resolve(this.mediaSession.sendDtmf(f))):Promise.reject(new Error("Unsupported DtmfTone"))}return Promise.reject(new Error("no mediaSession"))}async setAudioUsageMode(g){return Promise.reject(60)}async setAudioMidcallConfig(g,f){return Promise.reject(60)}async setAudioMidcallConfigJson(g,f=generateCauseId()){if(!g)return Promise.reject(60);isDefined(g.enableSpatialAudio)&&this.mediaSession?.configureSpatialAudio(g.enableSpatialAudio,f),g.noiseSuppressionMode&&await this.setNoiseSuppressionMode(g.noiseSuppressionMode,g.enableAEC)}async setParticipantSpatialAudioPositions(g,f=generateCauseId()){const S=g.map((g=>({sourceId:this.participants.find((f=>f.id===g.participantId))?.audio.id,x:g.x,y:g.y})));return this.mediaSession?.setParticipantSpatialAudioPositions(S,f)}async setNoiseSuppressionMode(g,f){return this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe||this.mediaSession.getSessionConfig().config.wasmdns.enableNoiseSuppression?"Auto"===g?this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe?this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaSession.getSessionConfig().config.wasmvqe.defaultVqeMode)):this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(this.mediaSession.getSessionConfig().config.wasmdns.noiseSuppressionMode,f))):this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe?this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(g,this.mediaSession.getSessionConfig().config.wasmvqe.enableAec))):this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(g,f))):Promise.resolve()}setInitialTelemetry(g,f,S,v){let C,_,T,I,b;switch(g){case"Subscribe":case"SubscribeWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("SUBSCRIBE"),S||this.callTelemetry.setOperationVariant(g,"CCWM"),this.signalingSession.setInitialTelemetry(g,{correlationId:this.callId,causeId:v,conversationServiceUrl:S});break;case"Acknowledge":0!==this.state&&8!==this.state&&this.callTelemetry.maybeRecordOperationSuccess(g,{code:4}),this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("callee"),this.signalingSession.setInitialTelemetry(g,{causeId:v});break;case"JoinCall":case"JoinWithMeetingData":this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("join"),1&f.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(g,"Preheat"),C=this.telemetryDataFromCallStartOptions(f.callStartOptions),C&&this.callTelemetry.updateOperationData(g,C,v),_=1==(1&f.callStartOptions.muteFlags),T=1==(1&f.callStartOptions.preheatFlags),I={muted:_,isPreheatOnly:T},this.signalingSession.setInitialTelemetry(g,{correlationId:this.callId,causeId:v,conversationServiceUrl:S,joinCallOptions:I,offerGenerationTime:Date.now()-f.callStartTime});break;case"StartCall":case"StartWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),1&f.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(g,"Preheat"),C=this.telemetryDataFromCallStartOptions(f.callStartOptions),C&&this.callTelemetry.updateOperationData(g,C,v),b=f.callStartOptions,this.signalingSession.setInitialTelemetry(g,{correlationId:this.callId,causeId:v,conversationServiceUrl:S,callStartOptions:b,offerGenerationTime:Date.now()-f.callStartTime});break;case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),this.signalingSession.setInitialTelemetry(g,{correlationId:this.callId,causeId:v,conversationServiceUrl:S,startCallOptions:f.callStartOptions,offerGenerationTime:Date.now()-f.callStartTime})}}async setHold(g,f,S,v){const C=this.logger.createFnLogger("setHold",f,`hold=${g}`);if(!this.canToggleAudio||this.callHoldResumeDeferred)return Promise.reject(new Error("can not set hold as it is already in progress"));this.callHoldResumeDeferred=new dt,this.isHoldInProgress=g,this.canToggleAudio=!1,this.canToggleVideo=!1,this.canToggleScreenSharing=!1,this.requestedHoldState=g;const always=()=>{this.canToggleAudio=!0,this.canToggleScreenSharing=!0,this.canToggleVideo=!0};C.info(`start, holdOptions: ${JSON.stringify(S)}`);const _=this.callHoldResumeDeferred.promise,T=g?"Hold":"Unhold",I={debugContent:{clientScenario:this.convertClientScenario(v)}};try{if(g?this.isMuteOnHold=S&&S.isLocal&&5!==this.state:this.prepareModalitiesForResume(f),!this.isMuteOnHold){const g=await this.updateMediaModalities(void 0,f);this.updateMediaState(g,f),this.updateScreenSharingState(g,f)}g&&(this.prepareModalitiesForHold(f),5===this.state&&this.finishCallHoldResume(),this.setCallState(4,f)),this.isMuteOnHold&&this.setMuteOnHold(g,f),always();const v={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(T,v,null,f,I)}catch(S){this.callTelemetry.recordOperationFailure(T,{error:getPIISafeObject(S)},null,f,I),C.logFailure(S),always(),this.callHoldResumeDeferred?.reject(new Error(`Failed setting hold state to ${g}`)),this.callHoldResumeDeferred=null}return _}transferCall(g){return this.logger.warn("transferCall is deprecated, please use callBlindTransfer instead"),this.callBlindTransfer(g)}callBlindTransfer(g,f=generateCauseId(),S){return this.executeCallTransfer(g,f,0,S)}callSafeTransfer(g,f=generateCauseId(),S){return this.executeCallTransfer(g,f,0,S)}transferCallToVoicemail(g,f=generateCauseId()){return this.executeCallTransfer(g.transferTargetMri,f,2,void 0)}callConsultativeTransfer(g,f=generateCauseId(),S,v){const C=this.logger.createFnLogger("ConsultativeTransfer",f);let _;g.participants.length>1?(_=this.getParticipantByLegId(S,g),_||(C.warn("getParticipantByLegId did not find a match in the participants list, defaulting to first participant"),_=g.participants[0])):_=g.participants[0];const T=_&&_.acceptedBy||_&&_.id;return C.info(`transferTargetParticipantLegId: ${S} targetMri: ${scrubMriOrOmit(T)}`),this.executeConsultCallTransfer(g.callId,T,S,f,v)}async consultativeTransferWithPickupCode(g,f){const S=this.logger.createFnLogger("ConsultativeTransferWithPickupCode",f);if(S.info(`pickup code: ${g}`),!g||isNaN(Number(g)))return S.info("pickup code cannot be empty"),Promise.reject(getRejectTransactionEnd("TransactionDisallowed"));const v=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,f,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),C=`4:${fi.SERVER_HOLD}`,_={unparkContent:{pickupCode:Number(g)}},T={disableForwardingAndUnanswered:!1};return this.signalingSession.transferCallAsync(C,"TransferTypeStandard",_,T,f),v}callRedirect(g,f=generateCauseId()){return this.logger.createFnLogger("CallRedirect",f).info(`redirectOptions: ${JSON.stringify(g)}`),this.stopInternal({terminatedReason:75,redirectOptions:g,causeId:f}).then((()=>({code:Fi.CallRedirected,subCode:xi.CallRedirectedSuccess,phrase:Gi.CallEndReasonRedirected,resultCategories:["Success"]})))}convertParkContext(g){switch(g){case 1:return"sharedLinePark";case 4:return"sharedLineParkV2";case 0:return"teamPark";case 3:return"serverHoldV2";case 5:return"callPark";default:return"serverHold"}}convertClientScenario(g){switch(g){case 0:return"breakoutRoom";case 1:return"musicOnHoldV2";case 2:return"sharedLineAppearanceV2";default:return}}park(g,f=generateCauseId()){const S=this.convertParkContext(g);return this.logger.info(`[${f}] [ParkCall] start -  context ${g} parkType ${S}`),5===g?(this.callTelemetry.recordOperation(`${getParkTypeName(S)}`,f),this._pendingParkPromise=this._callOperationHandler.createPendingOperation("CallParkV2",void 0,f)):this._pendingParkPromise=this._callOperationHandler.waitForOperation("ParkCall"),"serverHoldV2"!==S&&"callPark"!==S&&this._setParkState(1),this.signalingSession.parkCallAsync(S,f).catch((g=>{this.logger.info(`[${f}] [ParkCall] error in parkCallAsync (synchronous error) : ${getPIISafeObject(g)}. Hold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("ParkCall",{error:getPIISafeObject(g)},f)})),this._pendingParkPromise}async unpark(g,f){const S=this.convertParkContext(g);return this.logger.info(`[${f}] [UnparkCall] start -  context ${g} parkType ${S}`),this._pendingUnparkPromise=this._callOperationHandler.waitForOperation("UnparkCall"),this.signalingSession.unparkAsync(S,f).catch((g=>{this.logger.info(`[${f}] [UnparkCall] error in unparkAsync (synchronous error) : ${getPIISafeObject(g)}. Unhold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UnparkCall",{error:getPIISafeObject(g)},f)})),this._pendingUnparkPromise}getServerHoldLocation(){return this._pendingParkPromise.then((()=>(this.logger.info(`getServerHoldLocation ${this.serverHoldLocation}`),this.serverHoldLocation)))}getParkAdditionalContextJson(){return this._pendingParkPromise.then((()=>(this.logger.info(`getParkAdditionalContextJson ${this.parkAdditionalContextJson}`),this.parkAdditionalContextJson)))}getJoinBlob(){return Promise.resolve(JSON.stringify({conversationUrl:this.signalingSession.getConversationUrl(),conversationId:this.callId}))}getTechnicalInformationJson(){return Promise.resolve(JSON.stringify(this.mediaSession.getCallTechnicalInfo()))}isOneToOneCall(g=!1){if(g){const g=(this.state,[0,1]);return 1===this.callType&&g.includes(this.participants.length)}return 1===this.callType&&1===this.participants.length}setMuteOnHold(g,f){this.mediaSession.muteHold(g,f),g||(this.computeCallState(f),this.isMuteOnHold=!1),this.finishCallHoldResume()}finishCallHoldResume(g){g?this.callHoldResumeDeferred?.reject(g):this.callHoldResumeDeferred?.resolve(),this.isHoldInProgress=!1,this.callHoldResumeDeferred=null}computeCallState(g){let f=3;this._callInLobby?f=10:this.signalingSession.participantManager.localParticipant.isStaging&&(f=13),this.logger.info(`[${g}][computeCallState] the call state will be set to ${f}`),this.setCallState(f,g)}async prepareModalitiesForResume(g){this.mediaStateConfigurationHelper.isSending(1)&&await this.turnOnLocalVideoPreview(g)}async prepareModalitiesForHold(g){await this.turnOffLocalVideoPreview(g)}updateMediaState(g,f){this.setVideoOn(g.video===this.mediaAgent.constants.MEDIA_STATE.sendReceive||g.video===this.mediaAgent.constants.MEDIA_STATE.send,f),this.setAudioOn(g.audio===this.mediaAgent.constants.MEDIA_STATE.sendReceive||g.audio===this.mediaAgent.constants.MEDIA_STATE.send,f)}updateScreenSharingState(g,f){this.setScreenSharingOn(g.sharing===this.mediaAgent.constants.MEDIA_STATE.send,f)}onSharingStreamStateChanged(g){const f=generateCauseId();this.logger.info(`[${f}] Sharing stream state moved to ${g}`);const S={mediaType:2,mediaDirection:1,mediaStreamState:_PluginlessCall.streamingStatetoMediaStreamState(g)};this.event("mediaStreamStateChanged").raise(S),this.callStats.localStats.screenShare.streamStateChanged(g),"stopped"===g&&(this.canToggleScreenSharing=!0,this.stopScreenSharing(),"screenSharingCall"!==this.conversationType||this.participants.some((g=>3===g.state))||this.stop(!0,f))}async startScreenSharing(g,f,S,v=generateCauseId()){this.allowScreenSharingControl()&&(this.screenSharingControl.isInternalViewerControlEnabled()&&this.screenSharingControl.shutdownControlForViewer(),this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.initControlForSharer(S));const C=this.logger.createFnLogger("StartScreenSharing",v);return C.info(`started. negotiationTag is ${S}`),this.canToggleScreenSharing?this.isScreenSharingOn?(C.logSuccess("Resolving early because screen sharing is already on"),Promise.resolve()):(this.screenSharingRenegotiationDeferred&&(C.logFailure("called before the renegotiation deferred for the previous one has been closed"),this.screenSharingRenegotiationDeferred.resolve()),this.screenSharingRenegotiationDeferred=new dt,this.callStats.localStats.newSession(2),this.callStats.localStats.screenShare.start(),this.mediaStateConfigurationHelper.isDisabled(2)&&C.info("sharing modality was skipped till now. Adding it now"),this.canToggleScreenSharing=!1,this.callStats.localStats.screenShare.event(0),this.getScreenHandle(g).acquire().then((()=>(C.logSuccess("sharing stream acquired"),this.mediaStateConfigurationHelper.enableModality(2),this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this._delayedElevationPending&&!this._delayedElevationQueued?this.triggerDelayedReconnectIfNeeded(v):Promise.resolve()))).then((()=>this.updateMediaModalities(void 0,v,S))).then((()=>(C.logSuccess("updateMediaModalities done"),this.callStats.localStats.screenShare.negotiationStateChanged("started"),this.setScreenSharingOn(!0,v),this.canToggleScreenSharing=!0,this.screenSharingRenegotiationDeferred.promise))).then((()=>{this.enableControlInjector(),this.callStats.localStats.screenShare.negotiationStateChanged("completed")})).catch((g=>{this.callTelemetry.updateOperationData("StartScreenSharing",{error:getPIISafeObject(g)},v),this.setScreenSharingOn(!1,v),this.mediaStateConfigurationHelper.removeModality(2),this.canToggleScreenSharing=!0,this.disposeSharingScreenHandle();const f=g.error;throw f&&f.code===Fi.GlareError?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),C.logFailure("starting screen sharing failure with reason glare")):"ScreenSharingStopped"===g.reason?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","sharingStopped"),C.logFailure("expected starting screen sharing failure with reason stopped")):(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","other"),C.logFailure(g)),g}))):Promise.reject(new Error("cannot start screen sharing"))}async stopScreenSharing(g,f,S=generateCauseId()){const v=this.logger.createFnLogger("StopScreenSharing",S);if(v.info(`started. negotiationTag is ${f}`),!this.canToggleScreenSharing)throw v.logFailure("cannot stop screen sharing"),new Error("cannot stop screen sharing");if(this.isScreenSharingOn||this._callOperationHandler.hasPendingOperation("StartScreenSharing")){this.screenSharingRenegotiationDeferred&&(this.screenSharingRenegotiationDeferred.reject({reason:"ScreenSharingStopped"}),this.screenSharingRenegotiationDeferred=null),this.mediaStateConfigurationHelper.removeModality(2),this.canToggleScreenSharing=!1,this.allowScreenSharingControl()&&this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.shutdownControlForSharer(),await this.updateMediaModalities(void 0,S,f),this.canToggleScreenSharing=!0,this.callStats.localStats.screenShare.stop(),this.disposeSharingScreenHandle(),this.mediaAgent.getDeviceManager().shareSystemSound(!1),this.mediaAgent.getDeviceManager().setAudioSharingRequested(!1);try{this.setScreenSharingOn(!1,S)}catch(g){throw v.logFailure(g),this.callTelemetry.updateOperationData("StopScreenSharing",{error:getPIISafeObject(g)},S),g}}else v.logFailure("screensharing is not on, ignore this operation")}async startDataChannel(g,f=generateCauseId()){if(!this.allowDataChannel())throw new Error("startDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.enableModality(3),await this.updateMediaModalities({},f)}async stopDataChannel(g,f=generateCauseId()){if(!this.allowDataChannel())throw new Error("stopDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.removeModality(3),await this.updateMediaModalities({},f)}allowDataChannel(){return this.mediaSession?!!this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled&&(this.isOneToOnePSTNCall()?this.mediaSession.getSessionConfig().config.enableDataChannelPstn:this.mediaSession.getSessionConfig().config.enableDataChannel):(this.logger.warn("datachannel not allowed as there is no mediaSession"),!1)}isInitialSignalingDSHSubscriptionEnabled(){const g=this.mediaSession?.getSessionConfig()?.config;return g?!this.allowDataChannel()||g.enableInitialSignalingDSHSubscription:(this.logger.warn("Initial signaling dsh subscription is enabled as there is no mediaSession, sessionConfig or sessionConfig.config"),!0)}allowScreenSharingControl(){return this.screenSharingControl?.isScreenSharingControlEnabled()&&this.allowDataChannel()}updateSignalingDSHMessageSubscription(g){this.signalingSession.updateDominantSpeakerHistoryMessageSubscription(g),g&&this.mediaSession?.getDiagnostics?.().dshDiagnostics.setCurrentActiveStrategy("signaling")}async sendUserEvents(g,f){return this.dataChannel.sendUserEvents(g,f)}async shareSystemSound(g,f=generateCauseId()){const S=this.logger.createFnLogger("ShareSystemSounds",f,`shareSystemSound=${g}`);if(!(!!this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing))return S.error("shareSystemSound not allowed"),Promise.reject(60);try{return void this.mediaAgent.getDeviceManager().shareSystemSound(g)}catch{return S.error("shareSystemSound failed with device error"),Promise.reject(58)}}async mute(g=generateGuid()){return this.isMuted?Promise.reject(getRejectTransactionEnd("TransactionDisallowed")):this.muteUnmute(!0,g)}async unmute(g=generateGuid()){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")&&await this._callOperationHandler.waitForOperation("_PromotionToRealtime"),this.muteUnmute(!1,g)}async muteSpeaker(g=generateCauseId()){return this.muteUnmuteSpeaker(!0,g)}async unmuteSpeaker(g=generateCauseId()){return this.muteUnmuteSpeaker(!1,g)}async getSpeakerVolume(g=generateCauseId()){return await this.mediaSession.getSpeakerVolume(g)}async setSpeakerVolume(g,f=generateCauseId()){return this.mediaSession.setSpeakerVolume(g,f)}async muteParticipants(g,f,S=generateGuid()){const v=this.logger.createFnLogger("MuteParticipants",S,`muteScope=${g}`);v.info(`callParticipants count=${f.length}`);const C=_PluginlessCall.convertMuteScope(g);if(void 0===C)return v.logFailure(`Unrecognized ${g}`),Promise.reject(new Error("Unrecognized muteScope"));if(callStateIsAnyOf(this.state,[11,12]))return v.logFailure("Can not mute/unmute during preheat call"),Promise.reject(60);const _=[];return f.forEach((g=>{_.push(g.id)})),this.signalingSession.muteAsync(C,_,S).then((g=>this.handleParticipantsMutedUpdated(g,S))).catch((g=>(this.callTelemetry.updateOperationData("MuteParticipants",{error:getPIISafeObject(g)},S),v.logFailure(g),g?.endCode?Promise.reject(g.endCode):Promise.reject(g))))}async startAudio(g,f=generateCauseId()){const S=this.logger.createFnLogger("StartAudio",f);if(this.receiveOnlyAudioOnCallStart=!1,3!==this.state)return S.logFailure("Cannot startAudio when call is not connected"),Promise.reject(60);if(this.mediaStateConfigurationHelper.enableModality(0),this.callUsesMixer&&this.mediaStateConfigurationHelper.removeModality(1),this.mediaStateConfigurationHelper.isSending(1))try{await this.turnOnLocalVideoPreview(f)}catch(g){return S.logFailure(g),Promise.reject(25)}const v=await this.startStopAudio(!0,f);return await this.signalingSession.recordTelemetryForStartAudio(v),{code:v}}async stopAudio(g,f=generateCauseId()){const S=this.logger.createFnLogger("StopAudio",f);if(3!==this.state)return S.logFailure("Cannot stopAudio when call is not connected"),Promise.reject(60);this.mediaStateConfigurationHelper.removeModality(0);const v=await this.startStopAudio(!1,f);return await this.turnOffLocalVideoPreview(f),await this.signalingSession.recordTelemetryForStopAudio(v),{code:v}}assimilate(g,f,S,v=generateCauseId()){return Promise.reject(new Error("Not implemented"))}async merge(g,f,S=generateCauseId()){const v=this.logger.createFnLogger("MergeCall",S);v.error(`merge callId ${g.callId} callMergeOptions ${JSON.stringify(f)}`);const C=this.canMerge(g,S);if(!C)return v.info(`Error. ${getPrintableObject(C)}`),Promise.reject(getRejectTransactionEnd("TransactionDisallowed"));const _=[];g.participants.forEach((g=>{_.push(this._callOperationHandler.createPendingOperation("MergeCall",g.id,S))}));return(await this.mergeCallByAddParticipantWithReplaces(f,g.participants,g,1,"MergeCall",S,_,void 0))[0]}async mergeParticipants(g,f,S,v,C){const _=this.logger.createFnLogger("MergeParticipants",v),T=[];if(!g)return Promise.reject(getRejectTransactionEnd("Invalid callToMerge"));if(0===f.length)return Promise.reject(getRejectTransactionEnd("Invalid participantIds"));const I=[];for(const S of f){let f=findParticipantUsingParticipantLegId(g,S);if(!f&&findSelfEndpointDetailUsingParticipantLegId(g,S)&&(_.info("found self endpoint, use localSignalingParticipant"),f=this.localSignalingParticipant),f){const g=generateGuid(),C={id:f.id,participantId:g,replacementParticipantId:S,nonMaskedId:f.nonMaskedId};T.push(C),I.push(this._callOperationHandler.createPendingOperation("MergeParticipant",g,v))}else{const g={code:406,subCode:5201,phrase:`participantLegId ${S} is invalid!`};I.push(Promise.reject(getRejectTransactionEnd(g)))}}return this.mergeCallByAddParticipantWithReplaces(S,T,g,3,"MergeParticipant",v,I,C)}async mergeWithPickupCode(g,f,S=generateCauseId()){const v=this.logger.createFnLogger("MergeWithPickupCode",S);if(v.info(`mergeWithPickupCode: pickup code: ${g}, groupId: ${scrubMriOrOmit(f.groupId)}, threadId: ${getLoggableThreadId(f.threadId)} messageId: ${f.messageId}`),!g||isNaN(Number(g)))return v.info("mergeWithPickupCode: pickup code cannot be empty"),Promise.reject(getRejectTransactionEnd("mergeWithPickupCode: pickup code cannot be empty"));const C={additionalData:f.additionalData,groupId:f.groupId,threadId:f.threadId,messageId:f.messageId,replacementType:2,pickupCode:Number(g)},_={id:`4:${fi.SERVER_HOLD}`};return Promise.resolve().then((()=>Promise.all(this.signalingSession.addParticipantsAsync([_],C,S)))).then((g=>(g.length>0&&this.signalingNotifications.onParticipantJoined(g[0],S),Promise.resolve({code:0,subCode:0,phrase:"TransactionComplete"})))).catch((g=>{v.logFailure(`Participant was not added to call, error=${getPrintableObject(g)}`);const f=this._handleParticipantOperationFailure("MergeWithPickupCode",g,S,null,!0).reason;return Promise.reject(g?g.endCode:f||0)}))}async setMaxVideoChannels(g){return Promise.reject(60)}async setMaxVbssChannels(g){return Promise.reject(60)}async stop(g=!1,f=generateCauseId(),S,v){const C=this.logger.createFnLogger("StopAudio",f);if(6===this.state)return C.logFailure("Trying to stop a call which is already Disconnecting"),Promise.reject(new Error("cannot stop call in Disconnecting state"));if(7===this.state)return C.logFailure("Trying to stop a call which is already Disconnected"),Promise.reject(new Error("cannot stop call in Disconnected state"));if(this.disposedPromise)return C.logFailure("Call already ended"),Promise.reject("Call already ended");let _=0;1===this.state&&(_=10);const T=v?{clientReasonSubCode:v.clientSubCode,clientReasonPhrase:v.clientPhrase}:{};v?.clientSubCode===bi.SUB_CODE.VDI_DISCONNECTED&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.enabled&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.clientPhrases.includes(v?.clientPhrase)&&(T.code=bi.CODE.MEDIA_ERROR,T.subCode=bi.SUB_CODE.VDI_DISCONNECTED,T.phrase=Gi.CallEndReasonVDIdisconnect,T.resultCategories=["UnexpectedClientError"],_=4);const I={terminatedReason:_,forEveryone:g,causeId:f,...S,rejectReason:T};return this.stopInternal(I)}publishState(g,f){const S=getPluginlessStateType(g.type),v=this.getPluginlessPublishLevel(g.level),C=g.participantIds&&g.participantIds.length>0?"specified":void 0;return this.callTelemetry.setOperationVariant("PublishState","specified"===C?`${S}Specified`:`${S}None`,f),this.signalingSession.publishStateAsync(S,v,f,g.content,C,g.participantIds)}publishStatesForEveryone(g,f){const S=getPluginlessStateType(g.type),v=this.getPluginlessPublishLevel(g.level),C="all";return this.callTelemetry.setOperationVariant("PublishState",`${S}All`),this.signalingSession.publishStateAsync(S,v,f,g.content,C)}removeState(g,f){return this.signalingSession.removeStateAsync(f,"specified",void 0,g.stateIds).then((g=>Promise.resolve()))}removeStatesForEveryone(g,f){const S=getPluginlessStateType(g.type);return this.signalingSession.removeStateAsync(f,"all",S,void 0).then((g=>Promise.resolve()))}updateMeetingSettings(g,f){return this.signalingSession.updateMeetingSettingsAsync({allowRaiseHands:g.allowRaiseHands,attendeeRestrictions:g.attendeeRestrictions,lockMeeting:g.lockMeeting,breakoutRoomsEnabled:g.breakoutRoomsEnabled,allowPresentersToManageBreakoutRooms:g.allowPresentersToManageBreakoutRooms,disableMdpClientAudioRecording:g.disableMdpClientAudioRecording,refreshSettings:g.refreshSettings,aiInterpretationEnabled:g.aiInterpretationEnabled,groupCopilotDetails:g.groupCopilotDetails},f)}updateMeetingGroups(g,f){this.logger.info(`[UpdateMeetingGroups][${g}] options ${safeJsonStringify(f)}`);const S=this._callOperationHandler.waitForOperation("UpdateMeetingGroups",g),v={fromGroup:f.fromGroup,toGroup:f.toGroup,scope:mapParticipantScope(f.scope)};return f.participants&&(v.participants=createParticipantListFromMriMap(f.participants)),this.signalingSession.updateMeetingsGroupsAsync(g,v).catch((f=>{this.logger.info(`[${g}] [UpdateMeetingGroups] error in updateMeetingGroups (synchronous error) : ${getPIISafeObject(f)}. updateMeetingGroupsPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingGroups",{error:getPIISafeObject(f)},g)})),S}updateMeetingLiveState(g,f){return this.logger.info(`[UpdateMeetingLiveState][${g}] options ${safeJsonStringify(f)}`),this.signalingSession.updateMeetingLiveStateAsync(g,f).catch((f=>{this.logger.info(`[${g}] [UpdateMeetingLiveState] error in updateMeetingLiveState (synchronous error) : ${getPIISafeObject(f)}. promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingLiveState",{error:getPIISafeObject(f)},g)})),this._callOperationHandler.waitForOperation("UpdateMeetingLiveState",g)}updateMeetingStates(g,f=generateCauseId()){var S;this.logger.info(`[UpdateMeetingStates][${f}]`);const v={},C=[];g.operationId=g.operationId||f;for(const _ of Object.keys(g.meetingStates)){const T=g.operationId+"_"+_;C.push(T);const I=this._callOperationHandler.createPendingOperation("UpdateMeetingStates",T,f);v[S=g.operationId]??(v[S]={}),v[g.operationId][_]=I,this.callTelemetry.recordOperation("UpdateMeetingStates",f,T)}return Promise.resolve().then((()=>this.signalingSession.updateMeetingStatesAsync(f,g))).then((g=>{for(const S of C)this.callTelemetry.updateOperationData("UpdateMeetingStates",{data:getPIISafeObject(g)},f,S)})).catch((g=>{for(const S of C)this.callTelemetry.updateOperationData("UpdateMeetingStates",{error:getPIISafeObject(g)},f,S);this.logger.logFailure(g)})).then((()=>v))}async updateParticipantInterpretationState(g,f){if(this.logger.info(`[UpdateParticipantInterpretationState][${g}] options ${safeJsonStringify(f)}`),0===f.length)return Promise.reject(getRejectTransactionEnd("Invalid UpdateParticipantInterpretationState options"));const S=this.signalingSession.updateParticipantInterpretationStateAsync(g,f),v=[];f.forEach((f=>{v.push(this._callOperationHandler.createPendingOperation("UpdateParticipantInterpretationState",f.id,g))}));for(let v=0;v<S.length;v++){const C=S[v],_=f[v];C.then((()=>{this.logger.logSuccess(`updateParticipantInterpretationState succeeded for [id=${scrubMriOrOmit(_.id)}]`);const f={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess("UpdateParticipantInterpretationState",f,_.id,g),this._callOperationHandler.maybeResolveOperation("UpdateParticipantInterpretationState",f,_.id,g)})).catch((f=>{this.logger.error(`[${g}] [UpdateParticipantInterpretationState] error in updateParticipantInterpretationState (synchronous error) : ${getPIISafeObject(f)}. updateParticipantInterpretationStatePromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateParticipantInterpretationState",{error:getPIISafeObject(f)},g);const S=this._handleParticipantOperationFailure("UpdateParticipantInterpretationState",f,g,_.id).reason,v=f?.endCode||S||0;this._callOperationHandler.maybeRejectOperation("UpdateParticipantInterpretationState",v,_.id,g)}))}return Promise.resolve(v)}async updateParticipantsProperties(g,f){const S=this.logger.createFnLogger("UpdateParticipantsProperties",f);if(S.info(`options ${scrubMriOrOmit(safeJsonStringify(g))}`),!g)return Promise.reject(getRejectTransactionEnd("Invalid input: UpdateParticipantsPropertiesContext"));const v={},C=g.scope,_=g.operationId,T=new Set;if("self"===C){const S=this.signalingSession.participantManager.localParticipant.id;for(const C in g.propertyBag){const g=mapMriAndPropertyNameToResolveString(S,_,C),I=this.createUpdateParticipantPromise(g,f);v[g]={[S]:I},T.add(g),this.callTelemetry.recordOperation("UpdateParticipantsProperties",f,scrubMriOrOmit(g))}}else{if("specified"!==C||!this._isUpdatePropertiesSpecifiedAllowedByEcs)return Promise.reject("This scope is not supported.");{const S=g.participants;for(const g of S){const S=g.id;for(const C in g.propertyBag){const g=mapMriAndPropertyNameToResolveString(S,_,C),I=this.createUpdateParticipantPromise(g,f);v[g]={[S]:I},T.add(g),this.callTelemetry.recordOperation("UpdateParticipantsProperties",f,scrubMriOrOmit(g))}}}}return S.info(`promises created: ${scrubMriOrOmit(safeJsonStringify(v))}`),this.signalingSession.updateParticipantsPropertiesAsync(g,T,_,f).catch((g=>{const C=getPrintableObject(g);S.info(`[failed][reason=${C}]`);const _={...g};this.callTelemetry.updateOperationData("UpdateParticipantsProperties",{error:getPIISafeObject(C)},f);for(const g of Object.keys(v))this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",_,g,f)})),Promise.resolve().then((()=>v))}joinMeetingGroup(g,f){this.logger.info(`[JoinMeetingGroup][${g}] options ${safeJsonStringify(f)}`);const S=this._callOperationHandler.waitForOperation("JoinMeetingGroup",g),v={..."meetingGroupId"in f&&{meetingGroupId:f.meetingGroupId},..."meetingGroupLabel"in f&&{meetingGroupLabel:f.meetingGroupLabel},...f.groupPreferences&&{groupPreferences:f.groupPreferences}};return this.signalingSession.joinMeetingGroupAsync(g,v).catch((f=>{const S=getPIISafeObject(f);this.logger.info(`[${g}] [JoinMeetingGroup] error in joinMeetingGroup (synchronous error) : ${S}. joinMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("JoinMeetingGroup",{error:S},g)})),S}leaveMeetingGroup(g,f){this.logger.info(`[LeaveMeetingGroup][${g}] options ${safeJsonStringify(f)}`);const S=this._callOperationHandler.waitForOperation("LeaveMeetingGroup",g),v={meetingGroupId:f.meetingGroupId};return this.signalingSession.leaveMeetingGroupAsync(g,v).catch((f=>{const S=getPIISafeObject(f);this.logger.info(`[${g}] [LeaveMeetingGroup] error in leaveMeetingGroup (synchronous error) : ${S}. leaveMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("LeaveMeetingGroup",{error:S},g)})),S}sendMessages(g,f){var S,v;this.logger.info(`[SendMessages][${g}]`);const C={};for(const _ of f)if(0===_.scope){const f=this._callOperationHandler.createPendingOperation("SendMessages",_.operationId,g);C[_.operationId]={all:f},this.callTelemetry.recordOperation("SendMessages",g,_.operationId)}else if(1===_.scope)for(const f in _.to)if("participant"===_.to[f].level){const v=mapMriToResolveString(f,_.operationId),T=this._callOperationHandler.createPendingOperation("SendMessages",v,g);C[S=_.operationId]??(C[S]={}),C[_.operationId][f]=T,this.callTelemetry.recordOperation("SendMessages",g,v)}else if("endpoint"===_.to[f].level)for(const S in _.to[f].participantLegIdMap){const f=mapLegIdToResolveString(S,_.operationId),T=this._callOperationHandler.createPendingOperation("SendMessages",f,g);C[v=_.operationId]??(C[v]={}),C[_.operationId][S]=T,this.callTelemetry.recordOperation("SendMessages",g,f)}return this.signalingSession.sendProxiedMessageAsync(g,f).then((g=>{for(const f of g)f.then((g=>{this._callOperationHandler.maybeResolveOperation("SendMessages",g.transactionEnd,g.resolveString,g.causeId)})).catch((g=>{this._callOperationHandler.maybeRejectOperation("SendMessages",g.transactionEnd,g.resolveString,g.causeId)}));return C}))}async updateMonitorSession(g,f=generateCauseId()){this.logger.info(`updateMonitorSession: monitorActionType: ${g.monitorActionType}, monitorData: ${g.monitorData}`);const S=mapMonitorActionType(g.monitorActionType);if(void 0===S){const f={code:bi.CODE.CLIENT_ERROR_CODE,subCode:bi.SUB_CODE.INVALID_DATA_TYPE,phrase:`Invalid monitor action type ${g.monitorActionType}`};return Promise.reject(f)}const v={monitorActionType:S,monitorData:g.monitorData},C=this._callOperationHandler.waitForOperation("UpdateMonitorSession","",f);return this.signalingSession.updateMonitorSessionAsync(v,f).catch((g=>{const S=getPIISafeObject(g);this.logger.info(`[${f}] [UpdateMonitorSession] error in updateMonitorSession (synchronous error): ${JSON.stringify(S)}. updateMonitorSessionPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMonitorSession",{error:S},f)})),C}switchInterpreterGroup(g){return Promise.reject(new Error("Not implemented"))}setLiveInterpretationAttributes(g,f){return Promise.reject(new Error("Not implemented"))}async updateMeetingRoles(g,f,S=generateCauseId()){return 3===this.state&&this.signalingSession.hasOwnProperty("updateMeetingRolesAsync")?this.signalingSession.updateMeetingRolesAsync(g,f,S):Promise.reject({code:bi.CODE.CLIENT_ERROR_CODE,subCode:bi.SUB_CODE.ACTION_NOT_ALLOWED,phrase:"ActionNotAllowed"})}stopInternal(g){const f=this.logger.createFnLogger("stopInternal",g.causeId),S=g.terminatedReason||0;let v=g.rejectReason&&(g.rejectReason.code||g.rejectReason.subCode)?g.rejectReason:this.getRejectionInfoFromTerminatedReason(S);if(g.rejectReason&&(v||(v={}),v.clientReasonSubCode=g.rejectReason.clientReasonSubCode,v.clientReasonPhrase=g.rejectReason.clientReasonPhrase),f.info(`started, terminatedReason=${S}, rejectReason=${safeJsonStringify(v)}`),6===this.state)return f.logFailure("Trying to stop a call which is already Disconnecting"),this.disconnectingPromise;if(7===this.state)return f.logFailure("Trying to stop a call which is already Disconnected"),this.disconnectingPromise;this.setCallState(6,g.causeId,S);const C={causeId:g.causeId,forEveryone:g.forEveryone,scope:this.mapEndpointScope(g.scope),redirectOptions:g.redirectOptions&&convertRedirectOptions(g.redirectOptions)};return 1===g.scope&&(v.code=bi.CODE.SUCCESS,v.subCode=bi.SUB_CODE.ENDED_BY_REMOTE_ENDPOINT,v.phrase=Gi.EndedByRemoteEndpoint),this.disconnectingPromise=Promise.all([this.cleanUpMedia(g.causeId,v).then((()=>{this.callTelemetry.recordOperationSuccess("_MediaCleanUp")})).catch((S=>{throw f.logFailure(`cleanUpMedia failed with reason=${getPrintableObject(S)}`),this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:getPIISafeObject(S)},g.causeId),S})),this.signalingSession.endAsync(v,C).catch((g=>{throw f.logFailure(`endAsync failed with reason=${getPrintableObject(g)}`),g}))]).catch((S=>{throw f.logFailure(S),this.cleanUp(g.causeId,v),S})).then((()=>this.cleanUp(g.causeId,v))).catch((f=>{throw this.callTelemetry.updateOperationData("StopCall",{error:getPIISafeObject(f)},g.causeId),this.setCallState(7,g.causeId,S),f})),this.disconnectingPromise}async cleanUp(g,f){return this.logger.info(`[${g}][cleanup]start`),this.disposedPromise||(this.disposedPromise=this.cleanUpFinalize(g,f),this._getCallEndOperation().catch(noop).then((()=>{const f={code:bi.CODE.CLIENT_ERROR_CODE,subCode:bi.SUB_CODE.ABANDONED};this._callOperationHandler.rejectPendingOperations(61,g,f),this._participantOperationHandler.rejectPendingOperations(47,g,f)}))),this.disposedPromise}async cleanUpMedia(g,f){return this.mediaDisposedPromise||(this.callTelemetry.recordOperation("_MediaCleanUp",g),this.mediaDisposedPromise=(async()=>{this.callDeviceManager?.dispose(),this.callDeviceManager=null,this.turnOffLocalVideoPreview(g),this.localVideoContainer=null,this.disposeContentSharingSessions(),this.disposeSharingScreenHandle();const S=this.mediaSession;if(this.reportMediaStats=!!S,!S)return;this.unmixedAudioProvider.dispose(),this.dataChannel.dispose(),this.screenSharingControl.dispose(g),this.remoteUFDHandler.dispose(),this.mediaSession=null,this.streamManager.setMediaSession(null,g),this.participants?.forEach((f=>{f.setMediaSession(null,g)}));const v=S.terminate(g,f);this.isVideoOn=!1,this.setMediaStream(this.isVideoOn,!1,1),this.setMediaStream(!1,!1,2),this.setMediaStream(!1,!1,0),this.isScreenSharingOn=!1,this.screenSharingRenegotiationDeferred?.reject(f),this.screenSharingRenegotiationDeferred=null,this.mediaStateConfigurationHelper.removeModality(1),this.mediaStateConfigurationHelper.removeModality(0),this.mediaStateConfigurationHelper.removeModality(3),this.mediaStateConfigurationHelper.removeModality(2),this.batteryStatus?.dispose(),S?.getSessionConfig()?.config?.useOneDsLogger&&S.getSessionConfig().config.addTelemetryReportingCallback&&window.removeEventListener("beforeunload",this.beforeUnloadTelemetrySender);try{await v}finally{await this.collectCallStats(S),this.callStats.appendMediaControlPlaneInfo(JSON.stringify(S.getMediaControlPlaneInstance()?.getTelemetryReport()))}})()),this.mediaDisposedPromise}async cleanUpFinalize(g,f){try{await this.cleanUpMedia(g,f)}catch(f){this.logger.info(`[${g}][cleanUpMedia] failure: ${getPrintableObject(f)}`),this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:getPIISafeObject(f)},g)}this.callTelemetry.recordOperationSuccess("_MediaCleanUp");const S=this.reportCallEndStats(this.reportMediaStats);this.mediaSession?.getSessionConfig().config.waitReportStatsAtCallStop&&await S}async createContentSharingSession(g,f,S,v,C=generateCauseId()){if(this.signalingSession.signalingAgentConfig.checkAttendeeRoleInCreateContentSharing){if("attendee"===(this.advancedMeetingRole||this.meetingRole)){const g={terminatedReason:8,terminatedReasonCode:403,terminatedReasonSubCode:0,errorMessage:"Failed due to insufficient permissions"};return Promise.reject(g)}}const _=new us(this.callTelemetry,this.logger,this.signalingSession,g,f,v,S);return this.contentSharingSessions.push(_),_.changed((()=>this.removeContentSessionIfEnded(_))),this.event("contentSharingChanged").raise(),Promise.resolve(_)}stopWithBeacon(g=generateCauseId()){if(6===this.state||7===this.state)return!0;this.mediaSession?.getSessionConfig()?.config?.enableCallStateChangesOnPageClose&&(this.callEndDiagnosticsInfo={callControllerCode:bi.CODE.SUCCESS,callControllerSubCode:bi.SUB_CODE.BEACON},this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo),this.setCallState(6,g,1));const f=this.signalingSession.endWithBeacon(g);return this.mediaSession?.getSessionConfig()?.config?.enableCallStateChangesOnPageClose&&this.setCallState(7,g,1),f}disposeContentSharingSessions(){this.contentSharingSessions.forEach((g=>{g.dispose(),this.removeContentSessionIfEnded(g)})),this.event("contentSharingChanged").raise()}isPreheatedOnly(){return!!(12===this.state||2===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall")||9===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))}removeContentSessionIfEnded(g){7!==g.contentSharingStatus&&8!==g.contentSharingStatus||(this.logger.info("stopping the content sharing session."),(0,Ki.remove)(this.contentSharingSessions,(f=>f.contentSharingGuid===g.contentSharingGuid)).length&&this.event("contentSharingChanged").raise())}getRejectionInfoFromTerminatedReason(g){switch(g){case 53:return{code:Fi.MediaError,subCode:xi.MediaWhiteListingIssue,phrase:Gi.MediaWhiteListingIssue};case 4:return{code:Fi.MediaError,subCode:this._wasAudioStreamConnected?xi.MediaDropAfterConnect:xi.MediaDropDuringConnect,phrase:this._wasAudioStreamConnected?Gi.MediaDropAfterConnect:Gi.MediaDropDuringConnect};case 47:return{code:Fi.MediaError,subCode:xi.MediaOfferProcessingError,phrase:Gi.MediaOfferProcessingError};case 38:return{code:Fi.MediaError,subCode:xi.MediaRenegotiationError,phrase:Gi.RetargetNotSupported};case 10:return{code:Fi.Reject,subCode:xi.Success,phrase:Gi.CallEndReasonLocalUserInitiated};case 25:return{code:Fi.UnknownError,subCode:xi.MediaUnknownError,phrase:Gi.MediaError};case 58:return{code:Fi.MediaError,subCode:xi.MediaPermissionError,phrase:Gi.MediaPermissionError};case 7:return{code:Fi.UnknownError,subCode:xi.Success,phrase:Gi.Unknown};case 0:case 1:return{code:Fi.Success,subCode:xi.Success,phrase:Gi.CallEndReasonLocalUserInitiated};case 75:return{code:Fi.CallRedirected,subCode:xi.CallRedirectedSuccess,phrase:Gi.CallEndReasonRedirected,resultCategories:["Success"]};case 77:return{code:Fi.Success,subCode:xi.Suspended,phrase:Gi.CallEndReasonSuspended}}return null}async acknowledge(g,f,S=generateCauseId()){const v=this.logger.createFnLogger("Acknowledge",S),C=Date.now();if(this.setInitialTelemetry("Acknowledge",{callStartTime:C},"",S),0!==this.state&&8!==this.state)throw new Error(`Trying to acknowledge a call that has already been acted on ${this.state}`);v.info(`isMultiParty=${g.isMultiParty}`),v.info(`fromMixer=${g.fromMixer}`),v.info(`participantId=${g.participantId}`),v.info(`callType=${g.callType}`),this.attachToCallAndGetOffer=new dt,this.setCallType(g.isMultiParty?2:1,S),this.setCallUsesMixer(!!g.fromMixer,S),this.setCallerMri(stripMriAliases(g.callerId)),this.setDisplayNameSource(g.displayNameSource),this.setTransferorMri(g.transferorId),this.transferorType=g.transferorType,this.transferorDisplayName=g.transferorDisplayName,this.incomingCallType=g.callType,this.consultativeCallId=g.consultativeCallId,this.callQueueInfo=g.callQueueInfo,this.setFromApplicationType(g.fromApplicationType,S),this.callStats.localStats.startCall();const _=createPhaseExecutor(v);try{_.executeSync("ProcessIncomingCallRequest",(()=>this.signalingSession.processIncomingCallRequest(g,f,S))),this.setParticipantId(this.participantId);if(_.executeSync("ResolvePotentialConflict",(()=>this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)))===this.signalingSession)return Promise.reject({code:7,success:!1});const mediaSetup=async()=>{_.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(S))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled());const g=this.signalingSession.getInitialMediaOfferFromIncomingCallPayload();this.callStats.setParticipantId(this.participantId),this.onBehalfOfMri=this.signalingSession.onBehalfOf,this.onBehalfOfUserDisplayName=this.signalingSession.onBehalfOfUserDisplayName,this.callQueueContext=this.signalingSession.callQueueContext,this.callQueueSupervisorContent=this.signalingSession.callQueueSupervisorContent,this.bannerContent=this.signalingSession.bannerContent,this.callPhoneLineType=this.signalingSession.callPhoneLineType;const f=await _.execute("WaitForMediaOffer",(()=>g?Promise.resolve(g):this.attachToCallAndGetOffer.promise));let C;try{C=await _.execute("ProcessOffer",(()=>this.mediaSession.processOfferAsync(f,S)))}catch(g){C=await this._handleOfferProcessingError(g,S,v)}await _.execute("ProcessOfferedModalities",(()=>this._processOfferedModalities(C,S)))},C=(()=>_.execute("SendAttach",(()=>this.signalingSession.sendAttachToCall(S))).then((()=>this.setCallState(1,S))))();return await Promise.all([C,mediaSetup()]).catch((async g=>{throw await C,g})),await _.execute("TrySendingProvisionalAnswer",(()=>this._trySendProvisionalMediaAnswer(S))),_.executeSync("OnAcknowledgeSuccess",(()=>this._onAcknowledgeSuccess(v,_.getTelemetryData(),S)))}catch(g){return this._onAcknowledgeError(g,S,v,_.getTelemetryData())}}_onMessageIdChanged(g,f){g&&this.messageId!==g&&this.setMessageId(g,f)}async accept(g,f=generateCauseId()){const S=this.logger.createFnLogger("Accept",f);if(S.info(`accept, answerMediaType: ${g.answerMediaType},\n                            withVideo: ${g.withVideo},\n                            muted: ${g.muted},\n                            getSendMediaModalities: ${JSON.stringify(g.sendMediaModalities)},\n                            clientEndpointCapabilities: ${g.clientEndpointCapabilities},\n                            muteFlags: ${g.muteFlags}`),1!==this.state)throw new Error("Only calls in Notified state can be accepted");this.setCallOptions({callStartOptions:g,callStartTime:Date.now()}),this.setSessionIceTransportPolicy(g?.mediaConfiguration);const v=this._callOperationHandler.createPendingOperation("_ConnectCall",void 0,f);this.callStats.localStats.audio.start();const C=createPhaseExecutor(S);this.mediaSession.createAudioElement(f);const _=g.muted||1==(1&g.muteFlags),T=2==(2&g.muteFlags);this.setMuted(_?2:this.isServerMuted?1:0,f),this.setSpeakerMuted(T,f),this.setCallState(2,f),this.connectCallPromise=this._callOperationHandler.waitForOperation("Accept");try{g.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient(),this.mediaStateConfigurationHelper.setCallAcceptOptions(g),this.mediaStateConfigurationHelper.isSending(1)&&await C.execute("StartVideoSafe",(()=>this.startVideoSafe(f))),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,f);const _=await C.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,f))),T=C.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(_))),I=await C.execute("evaluateEndpointStatesForAccept",(()=>this.evaluateEndpointStatesForAccept(2===this._muteState,g?.additionalEndpointProperties,f)));await C.execute("MuteUnmuteSpeakers",(()=>this.muteUnmuteSpeaker(this.isSpeakerMuted,f)));const b=C.execute("handleEndpointStatesForAccept",(()=>this.handleEndpointStatesForAccept(I,f)));S.info("Queued the handleEndpointStatesForAccept");const A=await C.execute("CreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,f)));await C.execute("Accept",(()=>this.signalingSession.acceptAsync(A,T,g.clientEndpointCapabilities,f))),await C.execute("WaitForConnect",(()=>v)),this.handleRemoteParticipantStateInOneToOneCall(f),await C.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(f))),await b,this.callTelemetry.updateOperationData("Accept",{phases:C.getTelemetryData()},f)}catch(g){let v=7,C={};throw this.callTelemetry.updateOperationData("Accept",this.getTelemetryFromPhaseExecution(g),f),g?.error&&(C={...g.error}),isOneOfPhaseErrors(Wi,g)&&(v=47),this.mediaSession?.getSessionConfig().config.stopCallOnAcceptFailure&&this.stopInternal({terminatedReason:v,causeId:f,rejectReason:C}),g.terminatedReason=v,S.logFailure(g),g}}async reject(g=generateCauseId(),f){const S=f?{clientReasonSubCode:f.clientSubCode,clientReasonPhrase:f.clientPhrase}:{};return 1!==this.state?Promise.reject(60):this.stopInternal({terminatedReason:10,causeId:g,rejectReason:S})}async join(g,f={},S=generateCauseId()){const v=Date.now();return this.setInitialTelemetry("JoinCall",{callStartOptions:f,callStartTime:v},g.conversationUrl,S),this.setCallerMri(stripMriAliases(g.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinCall"),this.joinOrStartCall({callStartOptions:getCallStartOptions(f),callStartTime:v},this.joinGivenConversation,S,g.conversationUrl)}async joinPreheatedCall(g,f){const S=this.logger.createFnLogger("JoinPreheatedCall",f),v=this.isServerMuted||1==(1&g.muteFlags),C=2==(2&g.muteFlags),_=createPhaseExecutor(S);this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinPreheatedCall");try{const T={endpointProperties:{preheatProperties:0}};this.setCallState(2,f),!this.isCallModeStreaming()&&v&&(T.state={isMuted:!0}),S.info(`captchaContentJson=${!!g.captchaContentJson} publishedStates=${!!g.publishedStates} muteFlags=${g.muteFlags}}`),await this.signalingSession.updateEndpointState(T,f,g.publishedStates,g.captchaContentJson),this.computeCallState(f),this.isCallModeStreaming()||(v||(await _.execute("UnmuteInput",(()=>this.mediaSession.unmuteInputAsync(f))),this.setMuted(0,f)),C||(await _.execute("UnmuteOutput",(()=>this.mediaSession.unmuteOutputAsync(f))),this.setSpeakerMuted(!1,f)))}catch(g){const v=7;let C;return S.logFailure(`error: ${v} ${getPrintableObject(g)}`),isTransactionEnd(g)?C=g:isPhaseError("UnmuteInput",g)?C={code:Fi.LocalError,subCode:xi.MediaUnmuteMicrophoneError,phrase:getPrintableObject(g),causeId:f}:isPhaseError("UnmuteOutput",g)&&(C={code:Fi.LocalError,subCode:xi.MediaUnmuteSpeakerError,phrase:getPrintableObject(g),causeId:f}),this.callTelemetry.updateOperationData("JoinPreheatedCall",{phases:_.getTelemetryData(),error:getPIISafeObject(g)},f),this.stopInternal({causeId:f,terminatedReason:v,rejectReason:C}),Promise.reject(C)}}async start(g={},f=generateCauseId()){const S=Date.now();return this.setCallerMri(rr+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCall",{callStartOptions:g,callStartTime:S},"",f),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCall"),this.joinOrStartCall({callStartOptions:getCallStartOptions(g),callStartTime:S},this.startOutgoingCall,f)}async startCallToVoicemail(g,f=generateCauseId()){const S=Date.now();return this.setCallerMri(rr+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCallToVoiceMail",{callVoicemailStartOptions:g,callStartTime:S},"",f),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallToVoiceMail"),this.joinOrStartCall({callVoicemailStartOptions:g,callStartTime:S},this.startVM,f)}async joinCallWithoutCallModality(g,f={},S=generateCauseId()){const v=Date.now();this.setCallerMri(g.groupCallInitiator),this.setCallType(2,S);const C={callStartOptions:getCallStartOptions(f),callStartTime:v};return this.setInitialTelemetry("Subscribe",C,g.conversationUrl,S),0!==this.state?(this.logger.info(`[${S}][joinCallWithoutCallModality]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(C),this.setCallState(8,S),this.signalingSession.subscribeToCall(g.conversationUrl,this.callId,f.clientEndpointCapabilities,{meetingRegistrationId:f.meetingRegistrationId,participantPin:f.participantPin,clientEndpointDebugContent:f.clientEndpointDebugContent,additionalEndpointProperties:f.additionalEndpointProperties},S).catch((g=>isTransactionEnd(g)?(this.logger.info(`[${S}][joinCallWithoutCallModality] ${getPrintableObject(g)}`),Promise.reject(g)):Promise.reject(convertReason(g)))),this._callOperationHandler.waitForOperation("Subscribe",void 0,S))}startWithMeetingData(g,f){const S=Date.now();return this.setCallerMri(rr+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartWithMeetingData",{callStartOptions:f,callStartTime:S},"",g),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartWithMeetingData"),this.joinOrStartCall({callStartOptions:getCallStartOptions(f),callStartTime:S,meetingPreferences:{shouldResurrect:f.shouldResurrect}},this.startOutgoingCall,g)}joinWithMeetingData(g,f,S){const v=Date.now();return this.setInitialTelemetry("JoinWithMeetingData",{callStartOptions:S,callStartTime:v},f.conversationUrl,g),this.setCallerMri(stripMriAliases(f.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinWithMeetingData"),this.joinOrStartCall({callStartOptions:getCallStartOptions(S),callStartTime:v,meetingPreferences:{shouldResurrect:S.shouldResurrect}},this.joinGivenConversation,g,f.conversationUrl)}subscribeWithMeetingData(g,f,S){const v=Date.now();this.setCallerMri(f.groupCallInitiator),this.setCallType(2,g);const C={callStartOptions:getCallStartOptions(S),callStartTime:v};return this.setInitialTelemetry("SubscribeWithMeetingData",C,f.conversationUrl,g),0!==this.state?(this.logger.info(`[${g}][subscribeWithMeetingData]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(C),this.setCallState(8,g),this.signalingSession.subscribeToCall(f.conversationUrl,this.callId,S.clientEndpointCapabilities,{meetingPreferences:{shouldResurrect:S.shouldResurrect},meetingData:this.meetingData,meetingRegistrationId:S.meetingRegistrationId,participantPin:S.participantPin,additionalEndpointProperties:S.additionalEndpointProperties},g).catch((f=>isTransactionEnd(f)?(this.logger.info(`[${g}][subscribeWithMeetingData] ${getPrintableObject(f)}`),Promise.reject(f)):Promise.reject(convertReason(f)))),this._callOperationHandler.waitForOperation("SubscribeWithMeetingData",void 0,g))}async startCallWithNudge(g,f={},S=generateCauseId()){this.setCallerMri(rr+this.currentUserSkypeIdentity.id),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallWithNudge");const v=Date.now();if(this.logger.info(`[${S}][startCallWithNudge]startCallWithNudge for participants: ${scrubMriOrOmitList(g)}`),this.participants.length)return Promise.reject(48);if(f.isCast&&f.isHuddleGroupCall)return this.logger.logFailure(`isCast: ${f.isCast} isHuddleGroupCall: ${f.isHuddleGroupCall}`),Promise.reject(new Error("isCast or isHuddleGroupCall can only be set exclusively."));const C={};return C.callStartOptions=getCallStartOptions(f),C.invitationType=an.INVITATION_TYPE.NUDGE,C.participantsToNudge=g,C.callStartTime=v,this.setInitialTelemetry("StartCallWithNudge",C,"",S),this.joinOrStartCall(C,this.startOutgoingCall,S)}async startAndUnpark(g,f,S={},v=generateCauseId()){this.setCallerMri(rr+this.currentUserSkypeIdentity.id);const C=this.logger.createFnLogger("StartCallAndUnpark",v),_=Date.now();this.setInitialTelemetry("StartCallAndUnpark",{callStartTime:_},"",v),C.info(`startAndUnpark for context: ${g}, pickupCode :${f}`),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallAndUnpark");const T={};switch(T.callStartOptions=getCallStartOptions(S),T.pickupCode=f,T.parkContext=fi.SERVER_HOLD,g){case 0:T.parkContext=fi.PARK;break;case 1:T.parkContext=fi.SHARED_LINE;break;case 5:T.parkContext=fi.CALL_PARK;break;case 2:T.parkContext=fi.SERVER_HOLD;break;default:throw new Error(`[startAndUnpark] unsupported ParkContext name: ${g}`)}return this.addParticipant(`4:${T.parkContext}`).catch((g=>C.logFailure("Failed to add participant to unparked call"))),this.joinOrStartCall(T,this.startOutgoingCall,v)}async admitParticipant(g,f=generateCauseId()){const S=generateAliasedMri(g),v=this.getParticipant(S),C=this._getParticipantLegId(v),_=C?{participantLegId:C}:{};if(v&&7!==v.state){const S={code:0,subCode:3552,phrase:"Participant is not in lobby state"};return this.callTelemetry.maybeRecordOperationSuccess("AdmitParticipant",S,g,f,_),Promise.reject(S)}return this.admitParticipantToCall(S,f,C)}admit(g,f){return this.signalingSession.admitAsync(f)}async callMeBack(g,f,S=generateCauseId()){const v=generateAliasedMri(`${rr}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri);return this.addCallMeBackParticipant(g,f||v,S)}async addParticipant(g,f={},S=generateCauseId()){return(await this.addParticipantsImpl([g],f,S,"addParticipant"))[0]}async addParticipants(g,f={},S=generateCauseId()){return this.addParticipantsImpl(g,f,S,"addParticipants")}async addParticipantsImpl(g,f={},S=generateCauseId(),v){if(this.logger.info(`[${S}][${v}] start`),this.isEmergency&&0===this.state&&(0!==this.participants.length||1!==g.length))return Promise.reject(new Error("Only 1 participant (the emergency operator) may be added to unstarted emergency calls"));if(f.participantInvitationData)try{JSON.stringify(f.participantInvitationData)}catch(g){throw this.logger.info(`[${S}][${v}] ${g}`),g}const C=[],_=[];if(g.forEach((g=>{const f=this.getOrCreateParticipant(g,S,!0);0===f.state||4===f.state?(_.push(f),C.push(this._participantOperationHandler.createPendingOperation("AddParticipant",f.id,S))):3===f.state?C.push(Promise.resolve(f)):this._participantOperationHandler.hasPendingOperationWithOperationId("AddParticipant",f.id)&&C.push(this._participantOperationHandler.waitForOperation("AddParticipant",f.id))})),0===_.length)return Promise.resolve(C);const T=!!f.disableUnmute,I=this.addParticipantsToCall(_,S,f.participantInvitationData,f.groupId,f.threadId,f.messageId,T,f.alternateId,f.customHeaderContext,f.callingLineIdentity);return(0,Ki.zip)(I,_).forEach((async([g,f])=>{try{await g;const v=this._getParticipantLegId(this.getParticipant(f.id)),C=v?{participantLegId:v}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},f.id,S,C),this._participantOperationHandler.maybeResolveOperation("AddParticipant",f,f.id,S)}catch(g){this._participantOperationHandler.maybeRejectOperation("AddParticipant",g,f.id,S)}})),this.raiseChanged(this._participantChangedEventSkipConfig),Promise.resolve(C)}async nudgeParticipants(g,f,S={},v=generateCauseId()){return 2!==this.state&&3!==this.state?Promise.reject(48):this.signalingSession.nudgeParticipantsAsync({participantsIds:f,causeId:v,invitationData:S.participantInvitationData,newGroupId:S.groupId,newThreadId:S.threadId,newMessageId:S.messageId})}mapRemoveEndpointScope(g){switch(g){case 0:return"specified";case 1:return"all";default:return"none"}}mapEndpointScope(g){return 1===g?"all":"none"}async removeParticipant(g,f=generateCauseId(),S,v){const C=this.logger.createFnLogger("removeParticipant",f);C.info("start");const _=this.mapRemoveEndpointScope(v);return this.signalingSession.removeParticipantAsync({id:g,endpointId:S},f,_).catch((S=>{C.logFailure(`Participant was not removed from call, error=${S}`);const v=this._handleParticipantOperationFailure("RemoveParticipant",S,f,g).reason;return Promise.reject(v||38)}))}async cancelNudge(g,f){throw new Error("Method not implemented.")}async searchParticipants(g,f){return this.signalingSession.searchParticipantsAsync(g.searchQueryOptions,f)}async getAllParticipants(g,f){return this.signalingSession.getAllParticipantsAsync(g.scope,f)}set dominantSpeakerInfo(g){this.internalDominantSpeakerInfo=g}get dominantSpeakerInfo(){return this.internalDominantSpeakerInfo?this.internalDominantSpeakerInfo:this.mediaSession?.getSessionConfig().config.emptyInitialDSH?{speakerList:[],timestamp:null,noCurrentDominantSpeaker:!1}:{speakerList:this.participants.filter((g=>3===g.state)).map((g=>g.id)),timestamp:null,noCurrentDominantSpeaker:!1}}set slowedDownActiveTalkerInfo(g){(0,Ki.isEqual)(this.internalSlowedDownActiveTalkerInfo?.speakerList,g.speakerList)||(this.internalSlowedDownActiveTalkerInfo=g,this.raiseChanged())}get slowedDownActiveTalkerInfo(){return this.internalSlowedDownActiveTalkerInfo}startVideoSafe(g){return this.startVideo(g).catch((f=>{this.logger.info(JSON.stringify(f),"startVideoSafe",g)}))}async joinOrStartCall(g,f,S,v){const C=this.logger.createFnLogger("joinOrStartCall",S);if(0!==this.state&&8!==this.state&&!g.isPromotingToRealtime){const g="Trying to start a call that has already been acted on";return C.logFailure(g),Promise.reject(60)}if(this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)===this.signalingSession)return Promise.reject(57);this.callStats.localStats.startCall();const _=8===this.state||1!==this.participants.length;C.info(`isMultiparty=${_}, reason: participants.length=${this.participants.length}`),this.setCallType(_?2:1,S),this.setCallUsesMixer(_,S),this._setMaxVbssChannels(g?.callStartOptions?.maxVbssChannels,S),this.setCallOptions(g);const T=g.callStartOptions||{};if(1==(1&T.preheatFlags))this.setMuted(2,S),this.setSpeakerMuted(!0,S),this.setCallState(11,S);else{const g=!!T&&(T.muted||1==(1&T.muteFlags)),f=T?.muteFlags?2==(2&T.muteFlags):this.isSpeakerMuted;this.setMuted(g?2:this.isServerMuted?1:0,S),this.setSpeakerMuted(f,S),this.setCallState(2,S)}const I=calculateJoinedFromForTelemetry(this.meetingData,this.threadId,this.messageId,this.groupId,!!v);this.callTelemetry.setJoinedFrom(I),this.signalingSession.setJoinedFrom(I),this.setHuddleGroupCall(!!g.callStartOptions?.isHuddleGroupCall);const b=this._callOperationHandler.createPendingOperation("_ConnectCall","",S);return b.catch(noop),await this.joinOrStartWithMedia(g,f,g.callStartTime,b,S,v),g.callStartOptions?.meetingRegistrationId&&this.callTelemetry.setHasMeetingRegistrationId(!0),g.callStartOptions?.participantPin&&this.callTelemetry.setHasParticipantPin(!0),b}setSessionIceTransportPolicy(g){const f=g?.connectionType;let S=qt.ICE_TRANSPORT_POLICY.all;switch(f){case"AllSupported":S=qt.ICE_TRANSPORT_POLICY.all;break;case"NoDirectConnection":S=qt.ICE_TRANSPORT_POLICY.relay}this.mediaSession?.getSessionConfig().setIceTransportPolicy?.(S)}async joinOrStartWithMedia(g,f,S,v,C,_){const T=this.logger.createFnLogger("joinOrStartWithMedia",C);this.callStats.localStats.audio.start();const I=g.callStartOptions,b=I&&1&I.preheatFlags;if(this._startCallPhase=createPhaseExecutor(T),g.callStartOptions?.sendMediaModalities&&(this.mediaStateConfigurationHelper=new Or(g.callStartOptions.sendMediaModalities)),this._preferredMpLocation){g.callStartOptions=g.callStartOptions||{};const f=g.callStartOptions.clientEndpointDebugContent?JSON.parse(g.callStartOptions.clientEndpointDebugContent):{};g.callStartOptions.clientEndpointDebugContent=JSON.stringify({preferredMpLocation:this._preferredMpLocation,...f})}try{I&&!b&&this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)&&this.mediaStateConfigurationHelper.isSending(2)&&(this.setCallUsesMixer(!0,C),await this.getScreenHandle().acquire()),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,C),this.callUsesMixer||this.mediaStateConfigurationHelper.disableModality(2),T.info(`skipSharingModality=${!this.callUsesMixer}`),this._startCallPhase.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(C,I?.mediaConfiguration))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.getSessionConfig().config.alwaysNegotiateDataChannel&&this.mediaStateConfigurationHelper.enableModality(3),this.setSessionIceTransportPolicy(g?.callStartOptions?.mediaConfiguration),this.mediaSession.createAudioElement(C),this.callUsesMixer||_||this.isOneToOnePSTNCall()||g.callVoicemailStartOptions||this.setIsSomeoneStreamingVideo(!0);const A=this._callOperationHandler.createPendingOperation("_WaitForAnswer","",C,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});A.catch(noop);let P=!1;g.isPromotingToRealtime?(this.isSpeakerMuted=!0,P=!0,await this._startCallPhase.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(C))),await this._startCallPhase.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(C)))):I&&(b?(P=!0,await this._startCallPhase.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(C))),await this._startCallPhase.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(C))),this.setMuted(2,C),this.setCallUsesMixer(!0,C)):this.mediaStateConfigurationHelper.isSending(1)&&await this._startCallPhase.execute("StartVideoSafe",(()=>this.startVideoSafe(C)))),I?.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient();const R=await this._startCallPhase.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,C)));if(!this.mediaSession?.createOfferAsync)throw{error:"NoMediaSession",phase:"CreateOffer"};const M=await this._startCallPhase.execute("CreateOffer",(()=>this.mediaSession.createOfferAsync(C))),w=this._startCallPhase.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(this.calculateModalityDirections({},C))));if(this.mediaStateConfigurationHelper.isSending(2)&&this.updateScreenSharingState(R,C),P||(await this._startCallPhase.execute("MuteUnmute",(()=>this.muteUnmute(2===this._muteState,C))),await this._startCallPhase.execute("MuteUnmuteSpeakers",(()=>this.muteUnmuteSpeaker(this.isSpeakerMuted,C)))),this._startCallPhase.executeSync("CallStart",(()=>f(C,g,M,w,S,_))),await this._startCallPhase.execute("WaitForConnect",(()=>v)),!this.isCallModeStreaming()||g.isPromotingToRealtime){const g=await this._startCallPhase.execute("WaitForAnswer",(()=>A));if(!this.mediaSession?.processAnswerAsync)throw{error:"NoMediaSession",phase:"ProcessAnswer"};await this._startCallPhase.execute("ProcessAnswer",(()=>this.mediaSession.processAnswerAsync(g,C,!1))),await this._startCallPhase.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(C)))}this.callTelemetry.updateOperationData("_ConnectCall",{phases:this._startCallPhase.getTelemetryData()},C),this._startCallPhase=void 0,2!==I?.screenshareDirection&&4!==I?.screenshareDirection||(this.allowScreenSharingControl()&&this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.initControlForSharer(""),this.enableControlInjector())}catch(g){this.catchJoinOrStartCallError(g,C,T)}}catchJoinOrStartCallError(g,f,S){let v,C=0;throw S.logFailure(getPrintableObject(g)),g?.error&&(v={...g.error}),isPhaseError("MuteInput",g)?(C=7,v={code:Fi.LocalError,subCode:xi.MediaMuteMicrophoneError,phrase:getPrintableObject(g),causeId:f}):isPhaseError("MuteOutput",g)?(C=7,v={code:Fi.LocalError,subCode:xi.MediaMuteSpeakerError,phrase:getPrintableObject(g),causeId:f}):g?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer||isOneOfPhaseErrors(Wi,g)?C=47:g?.type===this.mediaAgent.constants.MEDIA_ERROR.permissionDeniedError?(C=58,v={code:Fi.MediaError,subCode:xi.MediaPermissionError,phrase:getPrintableObject(g),causeId:f}):isPhaseError("WaitForAnswer",g)||isPhaseError("WaitForConnect",g)?C=g.error:isOneOfPhaseErrors(qi,g)&&(C=7),this.callTelemetry.updateOperationData("_ConnectCall",this.getTelemetryFromPhaseExecution(g),f),this._startCallPhase=void 0,this.callSetupFailed=!0,Promise.all([this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",C,"",f),this._callOperationHandler.maybeRejectOperation("_ConnectCall",C,"",f)]).then((()=>{this.isPromotingToRealtime()||this.stopInternal({causeId:f,terminatedReason:C,rejectReason:v})})).catch(noop),C}addCallMeBackParticipant(g,f,S){const v=this._participantOperationHandler.waitForOperation("CallMeBack",g),C=this.logger.createFnLogger("CallMeBack",S),_={id:g,assertedId:f};return this.signalingSession.callMeBackAsync(_).then((()=>{C.logSuccess(`successfully executed call me back, participantId = ${scrubMriOrOmit(g)}`),this._participantOperationHandler.resolveOperation("CallMeBack",0,g)})).catch((v=>{C.logFailure(`Call me back failed, participantId = ${scrubMriOrOmit(g)}, error = ${v}`),this._handleParticipantOperationFailure("CallMeBack",v,S,f,!1);const _=this._processError(v);let T={};_&&(T={..._}),T.failureReason=_.reason?_.reason:11,this._participantOperationHandler.rejectOperation("CallMeBack",T,g)})),v}addParticipantsToCall(g,f,S,v,C,_,T,I,b,A){const P=this.logger.createFnLogger("addParticipantsToCall",f);g.forEach((g=>{g.setState(1,void 0,f)}));const R=g.map((g=>({id:g.mri})));P.info(`participantIds=${g.map((g=>scrubMriOrOmit(g.id)))}, disableUnmute=${T}`);const M={additionalData:S,groupId:v,threadId:C,messageId:_,disableUnmute:T,alternateId:I,customHeaderContext:b,callingLineIdentity:A};try{const g=this.signalingSession.addParticipantsAsync(R,M,f);return(0,Ki.zip)(g,R).map((async([g,S])=>{try{const v=await g;this.signalingNotifications.onParticipantJoined(v,f);const C=this._getParticipantLegId(this.getParticipant(S.id)),_=C?{participantLegId:C}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},v.id,f,_)}catch(g){const v=this._handleParticipantOperationFailure("AddParticipant",g,f,S.id).reason;throw this._removeParticipant(S,f,v),v}}))}catch(g){return P.logFailure(`Participants was not added to call, error=${g}`),(0,Ki.range)(R.length).map((()=>Promise.reject(1)))}}async mergeCallByAddParticipantWithReplaces(g,f,S,v,C,_,T,I){const b=this.logger.createFnLogger("mergeCallByAddParticipantWithReplaces",_),A=this.convertClientScenario(I),P={additionalData:g.additionalData,groupId:g.groupId,threadId:g.threadId,messageId:g.messageId,callIdToReplace:S.callId,replacementType:v,clientScenario:A},R=await this.signalingSession.addParticipantsAsync(f,P,_);for(let g=0;g<R.length;g++){const S=3===v?f[g].participantId:f[g].id;try{await R[g],b.logSuccess(` [participantInfos id =${scrubMriOrOmit(f[g].id)}]`);const v={debugContent:{replacementParticipantLegId:f[g].replacementParticipantId||void 0,clientScenario:A},participantLegId:f[g].participantId},T={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(C,T,S,_,v),this._callOperationHandler.maybeResolveOperation(C,T,S,_)}catch(v){b.logFailure(`Participant was not added to call, error=${getPIISafeObject(v)}`);const T=this._handleParticipantOperationFailure(C,v,_,S,!0,A).reason;this._removeParticipant(f[g],_,T);const I=v?v.endCode:T||0;this._callOperationHandler.maybeRejectOperation(C,I,S,_)}}return Promise.resolve(T)}admitParticipantToCall(g,f,S){const v=this.logger.createFnLogger("admitParticipantToCall",f),C={id:g};return v.info("start"),this.signalingSession.admitParticipantAsync(C,f).then((C=>{v.info(`successfully admitted participant to call, participantId = ${scrubMriOrOmit(g)}`);const _=S?{participantLegId:S}:{},T={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess("AdmitParticipant",T,g,f,_)})).catch((S=>{v.logFailure(`Participant was not admitted to call, error=${S}`);const C=this._handleParticipantOperationFailure("AdmitParticipant",S,f,g);return Promise.reject(C)}))}_processError(g){let f;const S={reason:f};if(g?.endCode){const v=getTerminationCode(g.endCode.code,g.endCode.subCode);f=_PluginlessCall.getParticipantReasonFromTerminatedReason(v),S.reason=f,S.code=g.endCode.code,S.subCode=g.endCode.subCode,S.resultCategories=g.endCode.resultCategories,S.phrase=g.endCode.phrase}else S.phrase=`${g}`;return this.logger.info(`_processError error=${g} telemetryData=${JSON.stringify(S)}`),S}_handleParticipantOperationFailure(g,f,S,v,C=!0,_){this.callTelemetry.updateOperationData(g,{error:getPIISafeObject(f)},S,v);const T=this._processError(f),I=this.getParticipant(v);T.code&&I&&(I.callEndDiagnosticsInfo={callControllerCode:T.code,callControllerSubCode:T.subCode,phrase:T.phrase,resultCategories:T.resultCategories});try{if(C){const f={debugContent:{clientScenario:_},participantLegId:this._getParticipantLegId(I)||void 0};this.callTelemetry.recordOperationFailure(g,T,v,S,f)}}catch(g){this.logger.info(`_handleParticipantOperationFailure error during recordOperationFailure ${g}`)}return T}_getParticipantLegId(g){return(0,Ki.has)(g,"endpoints.endpointDetails")&&g.endpoints.endpointDetails.length&&g.endpoints.endpointDetails[0].participantId?g.endpoints.endpointDetails[0].participantId:null}isOneToOnePSTNCall(g=!1){const f=this.signalingSession.isIncomingCall?this.callerMri:this.participants.length>0?this.participants[0].id:"";return this.isOneToOneCall(g)&&(0,Ki.startsWith)(f,or)&&(!this.incomingCallType||!this.callUsesMixer)}isParkedCall(){return this.isOneToOnePSTNCall()&&!!this.callOptions?.parkContext}async updateMediaModalities(g={},f=generateCauseId(),S){let v;const C=this.logger.createFnLogger("updateMediaModalities",f);return C.info(`callUsesMixer=${this.callUsesMixer},isSomeoneSharing=${this.isSomeoneSharing},isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),C.info(`options=${safeJsonStringify(g)},requestHoldState=${this.requestedHoldState},requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}`),v=g.modalityOverride?g.modalityOverride:this.requestedHoldState&&!this.isMuteOnHold?this.getMediaModalitiesForHold(f):this.calculateModalityDirections(g?.offered,f),C.info(`modalities=${safeJsonStringify(v)}`),await this.mediaSession.configureModalitiesAsync(v,f,S),v}calculateModalityDirections(g={},f){const S=this.logger.createFnLogger("calculateModalityDirections",f);S.info(`callUsesMixer=${this.callUsesMixer}, isEscalationInProgress=${this.isEscalationInProgress}`);const v={audio:this.calculateAudioDirection(g.audio,S),video:this.calculateVideoDirection(g.video,S),sharing:this.calculateSharingDirection(g.sharing,S),data:this.calculateDataDirection(g.data,S)};return S.info(`done, modalities=${safeJsonStringify(v)}`),this.deleteExtraneousModalities(v,f),v}calculateAudioDirection(g,f){if(f.info(`calculateAudioDirection, offer=${g}, requestedAudioState=${this.mediaStateConfigurationHelper.isSending(0)}`),this.receiveOnlyAudioOnCallStart)return f.info("calculateAudioDirection, direction=recvonly, receiveOnlyAudioOnCallStart=true"),"recvonly";if(this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)||"inactive"===g)return"inactive";return this.mediaSession.getAllowedModalities().audio.some((g=>g===Hr.send||g===Hr.sendReceive))?"sendrecv":"sendonly"===g?"inactive":"recvonly"}calculateVideoDirection(g,f){const S=this.mediaStateConfigurationHelper.isSending(1);if(f.info(`calculateVideoDirection, offer=${g}, requestedVideoState=${S}, isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),this.mediaStateConfigurationHelper.isInactiveOrDisabled(0))return"inactive";let v=S,C=this.isSomeoneStreamingVideo||this.callUsesMixer||this.isEscalationInProgress;return g&&(v=v&&("sendrecv"===g||"sendonly"===g),C=C&&("sendrecv"===g||"recvonly"===g)),v?"sendrecv":C?"recvonly":"inactive"}calculateSharingDirection(g,f){return f.info(`calculateSharingDirection, offer=${g}, requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}, isSomeoneSharing=${this.isSomeoneSharing}`),"inactive"===g?"inactive":this.mediaStateConfigurationHelper.isSending(2)?"sendonly":this.isSomeoneSharing||this.callUsesMixer||this.isEscalationInProgress?"recvonly":void 0}calculateDataDirection(g,f){const S=this.mediaStateConfigurationHelper.isSending(3);if(f.info(`calculateDataDirection, offer=${g}, dataEnabled=${S}`),this.allowDataChannel())return S?"inactive"===g?"inactive":"sendrecv":void 0;f.info("calculateDataDirection, disabling data since ECS flag prohibits it")}getMediaModalitiesForHold(g){this.logger.info(`[${g}][getMediaModalitiesForHold]`);const f="inactive",S={audio:f,video:f,data:this.allowDataChannel()?f:void 0,sharing:f};return this.deleteExtraneousModalities(S,g),S}deleteExtraneousModalities(g,f){!hasSendDirectionality(g.video)&&this.mediaStateConfigurationHelper.isDisabled(1)&&(this.logger.info(`[${f}][deleteExtraneousModalities] skipping videoModality`),delete g.video),!hasSendDirectionality(g.sharing)&&this.mediaStateConfigurationHelper.isDisabled(2)&&(this.logger.info(`[${f}][deleteExtraneousModalities] skipping sharingModality`),delete g.sharing)}getSignalingMediaTypes(g){const isSendActive=g=>g===this.mediaAgent.constants.MEDIA_STATE.send||g===this.mediaAgent.constants.MEDIA_STATE.sendReceive,f=[];return g.audio&&g.audio!==this.mediaAgent.constants.MEDIA_STATE.inactive&&f.push("Audio"),isSendActive(g.video)&&f.push("Video"),g.sharing===this.mediaAgent.constants.MEDIA_STATE.send?f.push("ScreenSharer"):g.sharing===this.mediaAgent.constants.MEDIA_STATE.receive&&f.push("ScreenViewer"),f}enableControlInjector(){if(this.allowScreenSharingControl()){if(this.getlocalScreenShareStream()){const g=this.mediaSession?.getLocalMediaTrackId("ScreenShare")??"";this.screenSharingControl.enableControlInjector(g)}else this.logger.warn("enableControlInjector: no local screenshare stream found")}}createCallDeviceManager(){return new Xa(this.mediaAgent.getConfigProvider().config.allowVirtualDeviceInCall,this.mediaAgent.getDeviceManager(),this.logger.createChild("CallDeviceManager"),this.callStats,(g=>this.isMediaSending(g)))}initializeSignalingSession(g){if(this.signalingSession)return void this.logger.info("Session already exists!");const f=an.CALL_STATUS;if(this.localSignalingParticipant={id:generateAliasedMri(`${rr}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri),displayName:this.currentUserSkypeIdentity.displayName,endpointDetails:[],languageId:null,participantId:g,endpointId:null},this.accountConfiguration){if(this.localSignalingParticipant.applicationType=this.accountConfiguration.applicationType,this.callTelemetry.setApplicationType(this.accountConfiguration.applicationType),this.localSignalingParticipant.ring=this.accountConfiguration.ring,this.callTelemetry.setRing(this.accountConfiguration.ring),this.localSignalingParticipant.region=this.accountConfiguration.region,this.callTelemetry.setRegion(this.accountConfiguration.region),this.localSignalingParticipant.userHexCID=this.accountConfiguration.userHexCID,this.callTelemetry.setUserHexCID(this.accountConfiguration.userHexCID),this.localSignalingParticipant.partition=this.accountConfiguration.partition,this.callTelemetry.setPartition(this.accountConfiguration.partition),this.localSignalingParticipant.acsResourceId=this.accountConfiguration.acsResourceId,this.callTelemetry.setAcsResourceId(this.accountConfiguration.acsResourceId),this.callStats.setAcsResourceId(this.accountConfiguration.acsResourceId),this.accountConfiguration.serviceUrls){const g=this.accountConfiguration.serviceUrls.calling_conversationServiceUrl,f=this.accountConfiguration.serviceUrls.calling_uploadLogRequestUrl;this.signalingAgent.updateUrls(g,f,this.accountConfiguration.enforceUrls)}this.localSignalingParticipant.clientType=this.accountConfiguration.clientType,this.callTelemetry.setClientType(this.accountConfiguration.clientType)}this.callStats.localStats.setLocalUserId(this.localSignalingParticipant.id),this._callOperationHandler&&this._callOperationHandler.resetOperationChain(),this.signalingNotifications={onPromotionCompleted:(g,f,S)=>{this.logger.info(`[${S}][onPromotionCompleted] isFailed=${g} reason=${safeJsonStringify(f)} callMode=${this.callMode}`);const v=g?f:{code:0,subCode:0};if(this.callTelemetry.recordEvent("PromotionCompleted",{reason:v},S),g){const g=convertReason(f);this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",g,"",S),this._callOperationHandler.maybeRejectOperation("_CallStartOrJoinInitiated",g,"",S),this._callOperationHandler.maybeRejectOperation("_ConnectCall",g,"",S),this.promotionCompletedDeferred?.reject(g)}else this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,S),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,S);this.participants.forEach((g=>{g.applyCachedMediaStreams(S)}))},onCallStatusChanged:(g,S,v=generateCauseId())=>{const C=this.logger.createFnLogger("onCallStatusChanged",v);let _=`[status=${g}]`;if(S&&(_+=`[reason=${safeJsonStringify(S)}]`,void 0!==S.code&&(this.callEndDiagnosticsInfo={callControllerCode:S.code,callControllerSubCode:S.subCode,phrase:S.phrase,resultCategories:S.resultCategories},(S.overflowJoinInformation||S.registrationInformation)&&(this.callEndDiagnosticsInfo.additionalDiagnostics={overflowInformation:S.overflowJoinInformation,registrationInformation:S.registrationInformation}))),C.info(_),this.callTelemetry.recordEvent("_SignalingStateChanged",{status:g,reason:S},v),g===f.CONNECTING)this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,v);else if(g===f.RINGING)2===this.audioStreamState?(this.setCallState(9,v),this.participants.forEach((g=>g.setState(6,void 0,v)))):this.participants.forEach((g=>g.setState(2,void 0,v))),this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,v);else if(g===f.CONNECTED_FOR_ROSTER_ONLY)this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,v),this._callOperationHandler.maybeResolveOperation("SubscribeWithMeetingData",void 0,void 0,v);else if(g===f.CONNECTED){this._callIsSetupComplete=!0;const g=this.getLocalSignalingEndpointDetails();(g?.isLobby||g?.streamLobby)&&(this._callInLobby=!0,this.updateCapabilities(v,!0));const f=this.signalingSession.participantManager.localParticipant.isStaging;if(11===this.state)this.setCallState(12,v);else if(this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))C.info("wait for joinPreheatedCall to resolved");else if(this._callInLobby)C.info("[inLobby] Override Connected state from signaling agent"),this.setCallState(10,v);else if(f)this.setCallState(13,v);else{if(3===this.state&&!this._callOperationHandler.hasPendingOperation("_CallStartOrJoinInitiated")&&!this._callOperationHandler.hasPendingOperation("_ConnectCall"))return void C.info("Return: Don't re-send setup telemetry if call was already connected and operations are completed");this.setCallState(3,v),this.handleRemoteParticipantStateInOneToOneCall(v)}this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,v),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,v),this.reportTsCallingTelemetry(!0)}else if(g===f.LOCAL_TERMINATED||g===f.REMOTE_TERMINATED){let _=this.callSetupFailed?7:convertReason(S);if(8===this.state&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData"]))return this.signalingSession.resetState(),this._callOperationHandler.maybeRejectOperation("Subscribe",_,void 0,v),this._callOperationHandler.maybeRejectOperation("SubscribeWithMeetingData",_,void 0,v),void C.info("Subscribe failed, there is pending start/join operation, ignore call end message");if(1!==_&&S?.code===Fi.MediaError&&S?.subCode===xi.MediaPermissionError&&(_=58,C.info(`[terminated][reason=${safeJsonStringify(S)}]`)),(2===this.state||6===this.state||8===this.state)&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData","Subscribe","SubscribeWithMeetingData"])){const g={code:this.callEndDiagnosticsInfo.callControllerCode,subCode:this.callEndDiagnosticsInfo.callControllerSubCode,phrase:this.callEndDiagnosticsInfo.phrase,reason:_};this._callOperationHandler.maybeRejectOperations(["Accept","JoinCall","JoinWithMeetingData","JoinPreheatedCall","StartCall","StartCallAndUnpark","StartCallToVoiceMail","StartCallWithNudge","StartWithMeetingData","Subscribe","SubscribeWithMeetingData"],_,void 0,v,g)}this.signalingSession.acceptedElsewhereBy&&(this.acceptedElsewhereBy={id:this.signalingSession.acceptedElsewhereBy.id,displayName:this.signalingSession.acceptedElsewhereBy.displayName}),this.signalingSession.parkAdditionalContextJson&&(this.parkAdditionalContextJson=this.signalingSession.parkAdditionalContextJson),this.signalingSession.serverHoldLocation&&(this.serverHoldLocation=this.signalingSession.serverHoldLocation),this._callOperationHandler.hasPendingOperation("CallParkV2")&&S.pickupCode&&0===S.code&&this._callOperationHandler.resolveOperation("CallParkV2",""+S.pickupCode,void 0,v),1!==_&&this.mediaRelayWhiteListingIssue&&(_=53,C.info(`[terminated][reason=${safeJsonStringify(S)}]`)),this._callOperationHandler.maybeRejectOperation("CallParkV2",_,"",v),this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",_,"",v),this._callOperationHandler.maybeRejectOperation("_ConnectCall",_,"",v);const T=this.mediaSession?.getSessionConfig().config.setDisconnectAfterCleanUp;if(T?this.setTerminatedReason(_):this.setCallState(7,v,_),this.participants.forEach((g=>g.setState(4,void 0,v))),!this.disconnectingPromise){const _={...S,remoteTerminated:g===f.REMOTE_TERMINATED};this.disconnectingPromise=this.cleanUp(v,_).catch((g=>{C.logFailure(`Error when cleaning up the call, callId = ${this.callId}, error = ${g}`)}))}T&&this.disconnectingPromise.finally((()=>{7!==this.state&&this.setCallState(7,v,_)}))}},onOffer:(g,f=generateCauseId())=>{const S=this.logger.createFnLogger("onOffer",f);S.info(`${safeJsonStringify((0,Ki.omit)(scrubObjectFields(g),"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(g.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnOffer",this.prepareTelemetryForOfferAnswer(g),f),g.transferor?.details?.id&&this.setTransferorMri(g.transferor.details.id),g.transferor?.transferorType&&(this.transferorType=g.transferor.transferorType),g.transferor?.details?.displayName&&(this.transferorDisplayName=g.transferor.details.displayName),this.clientTransferContext=g.clientTransferContext,this.customHeaderContext=g.customHeaderContext,this.invitationData=g.invitationData,this.spamRiskLevel=g.riskLevel,this.spamStirAttestation=g.stirAttestation,g.mediaContent.isTwoPartyToMultiPartyEscalation&&this.setIsEscalationInProgress(!0,f),g.renegotiation?this.requestedHoldState&&this._pendingParkPromise?this.renegotiateIncoming(g.mediaContent,f):this._delayedElevationPending||this._delayedElevationQueued?(this.signalingSession.rejectRenegotiationAsync({},f),this.triggerDelayedReconnectIfNeeded(f,"onOffer")):this._callOperationHandler.executeChained((()=>this.renegotiateIncoming(g.mediaContent,f)),"_RenegotiateIncoming",f,f,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}):(S.info("resolving attach / offer promise"),this.attachToCallAndGetOffer.resolve(g.mediaContent))},onNewOffer:(g,f=generateCauseId())=>{const S=this.logger.createFnLogger("onNewOffer",f);this.newOfferRequestDeferred?(S.info("onNewOffer"),this.newOfferRequestDeferred.resolve(g.mediaContent)):S.info("callback received but new offer was not requested")},onAnswer:(g,f=generateCauseId())=>{const S=this.logger.createFnLogger("onAnswer",f);if(S.info(`${safeJsonStringify((0,Ki.omit)(g,"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(g.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnAnswer",this.prepareTelemetryForOfferAnswer(g),f),g.renegotiation)S.info("resolving previous renegotiation promise"),this.renegotiationAnswerDeferred.resolve(g.mediaContent);else if(S.info("resolving final answer promise"),g.provisional){const S=this.isOneToOnePSTNCall()&&(0,Ki.startsWith)(g.remoteParticipantId,or);this.mediaSession.processAnswerAsync(g.mediaContent,f,!0,S)}else this._callOperationHandler.maybeResolveOperation("_WaitForAnswer",g.mediaContent,void 0,f),this.handleRemoteParticipantStateInOneToOneCall(f);g.provisional||!g.mediaContent.fromMixer||this.callUsesMixer||this._callOperationHandler.executeChained((async()=>{this.setCallUsesMixer(!0,f),this.mediaStateConfigurationHelper.isDisabled(2)&&this.mediaStateConfigurationHelper.removeModality(2),await this.updateMediaModalities(void 0,f);const g=!(this.isSomeoneSharing||this.isScreenSharingOn||this.isVideoOn);return(this.isOneToOnePSTNCall()?this.mediaSession.getSessionConfig().config.callElevationDelayReconnectPSTN:this.mediaSession.getSessionConfig().config.callElevationDelayReconnect)&&g?(S.info("Delayed elevation: pending"),this._delayedElevationPending=!0,Promise.resolve()):this.mediaSession.reconnectAsync(f,!0)}),"_CallEscalatedToConference",f,f,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})},onMediaAcknowledgementSuccess:(g,f=generateCauseId())=>{this.logger.info(`isRenegotiation: ${g}`,"onMediaAcknowledgementSuccess",f),this._callOperationHandler.resolveOperation("_MediaAcknowledgment",void 0,void 0,f)},onMediaAcknowledgementFailure:(g,f,S=generateCauseId())=>{this.logger.createFnLogger("onMediaAcknowledgementFailure",S).logFailure(safeJsonStringify(f)),this._callOperationHandler.rejectOperation("_MediaAcknowledgment",f,S)},onMediaRenegotiationRejection:(g,f=generateCauseId())=>{this.logger.createFnLogger("onMediaRenegotiationRejection",f).logFailure(safeJsonStringify(g)),this.renegotiationAnswerDeferred.reject(g)},onRosterHandlingComplete:()=>{this.logger.info(`[onRosterHandlingComplete] ${this._publishedStatesModified}`),0!==this._publishedStatesModified&&(this.processPublishedStates(),this._publishedStatesModified=0)},onMeetingGroupDetailsUpdated:(g,f=generateCauseId())=>{this.meetingGroupDetails!==g&&(this.callTelemetry.recordEvent("_UpdateMeetingGroupDetails",g,f),this.logger.info(`[${f}][onMeetingGroupDetailsUpdated] update meetingGroupDetails from ${JSON.stringify(this.meetingGroupDetails)} to ${JSON.stringify(g)}`),this.meetingGroupDetails=g,this.raiseChanged())},onSelfParticipantUpdated:(g,f=generateCauseId())=>{this.logger.info(`[${f}][onSelfParticipantUpdated]`),this.updateLocalParticipant(g,f),this.raiseChanged()},onParticipantMriUpdated:(g,f,S=generateCauseId())=>{this.logger.info(`[${S}][onParticipantMriUpdated]`);const v=this.getParticipant(g);v&&(v.id=f,this.raiseChangedDeferred())},onParticipantUpdated:(g,f=generateCauseId())=>{this.logger.info(`[${f}][onParticipantUpdated]: ${scrubSignalingParticipant(g)}`);const S=this.getOrCreateParticipant(g.id,f,!0);S.displayName=g.displayName;const v=_PluginlessCall.getStreamsFromEndpoints(g.endpointDetails,this.isMultiVBSSEnabled()),C=(0,Ki.some)(g.endpointDetails,(g=>g?.streamInformation));this.callUsesMixer||v.length>0||C?(this.updateParticipantStreams(S,g,v,f),this.updateCallParticipantFromSignalingParticipant(S,g,f)):S.setState(3,void 0,f),S.processParticipantDetails(g,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(g),this.calculateIsSomeoneStreaming(f),this.raiseChangedDeferred()},onParticipantRemoved:(g,f=generateCauseId(),S=!1)=>{if(this.logger.info(`[${f}][onParticipantRemoved]`),S){const S=this.getParticipant(g.id);this.callTelemetry.recordOperationSuccess("_ParticipantJoined",null,S?.id,f,{participantJoinedButReplaced:"Participant joined with original MRI and replaced with participant of RNL MRI"})}else this.callTelemetry.recordOperationSuccess("RemoveParticipant",null,g.id,f),this._participantOperationHandler.maybeRejectOperation("AddParticipant",1,g.id,f);this._removeParticipant(g,f),this.removePublishedStatesByParticipant(g.id),this.calculateIsSomeoneStreaming(f)},onParticipantJoined:(g,f=generateCauseId())=>{this.logger.info(`[${f}][onParticipantJoined]`);const S=!this.getParticipant(g.id),v=this.getOrCreateParticipant(g.id,f,!1);v.displayName=g.displayName,0===v.state&&v.setState(1,void 0,f);const C=_PluginlessCall.filterVirtualEndpoints(g.endpointDetails),_=_PluginlessCall.getStreamsFromEndpoints(C,this.isMultiVBSSEnabled()),T=(0,Ki.some)(g.endpointDetails,(g=>g?.streamInformation));this.callUsesMixer||_.length>0||T?(this.updateParticipantStreams(v,g,_,f),this.updateCallParticipantFromSignalingParticipant(v,g,f),this.calculateIsSomeoneStreaming(f)):(this.handleRemoteParticipantJoinedInOneToOneCall(g,f),this.handleRemoteParticipantStateInObservingCall(v,g,f),g.acceptedBy&&g.acceptedBy!==g.id&&(v.acceptedBy=g.acceptedBy)),this.callTelemetry.recordOperationSuccess("_ParticipantJoined",getEndpointInformationForTelemetry(g.endpointDetails),v.id,f),v.processParticipantDetails(g,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(g),S&&this.event("participantAdded").raise(v),this.raiseChangedDeferred()},onCallModeChanged:(g,f)=>{this.callTelemetry.recordEvent("_CallModeChanged",{newCallMode:g,oldCallMode:this._callMode},f),this.logger.info(`onCallModeChanged[${f}]: new=${g} old=${this._callMode} `),g&&this._callMode!==g&&(this._callMode=g,this.isCallModeStreaming()&&this.cleanUpDueToStreaming(f),1===this._callMode&&(this.participants.forEach((g=>{g.applyCachedMediaStreams(f)})),this.promotionCompletedDeferred?.resolve()),this.monitorCallStart(),this.updateCapabilities(f),this.raiseChanged())},getRemoteParticipantCollection:()=>this.participants.map((g=>g.toCafeParticipant())),onReTargetCompletedSuccess:g=>{const f=this.logger.createFnLogger("onReTargetCompletedSuccess",g);f.info(`started, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetSuccess",void 0,g),this.callStats.localStats.call.event(3);const S=this.isEscalationInProgress;this.screenSharingControl&&this.screenSharingControl.shutdownControlForViewer(),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.completeEscalationAsync(g).then((()=>(f.logSuccess("completeEscalationAsync"),this.callTelemetry.recordEvent("_WebOnEscalationSuccess",void 0,g),this.handleCallEscalation(S,g),this.updateMediaStatus(g)))).catch((S=>{f.logFailure(`completeEscalationAsync, error=${getPrintableObject(S)}`),this.setIsEscalationInProgress(!1,g),this.callTelemetry.recordEvent("_WebOnEscalationFailure",getPIISafeObject(S),g),this.stopInternal({causeId:g,terminatedReason:47})}))},onReTargetCompletedFailure:(g,f)=>{this.logger.createFnLogger("onReTargetCompletedFailure",f).logFailure(`reason=${getPrintableObject(g)}, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetFailure",getPIISafeObject(g),f),this.isEscalationInProgress&&(this.setIsEscalationInProgress(!1,f),this.setCallUsesMixer(!1,f),this.updateMediaStatus(f)),this.callStats.localStats.call.event(4),this.mediaSession.rejectEscalationAsync(g,f)},onChatModalitySetupFailed:g=>{this.logger.debug(`onChatModalitySetupFailed: ${g}`)},onConversationUpdated:(g,f)=>{this.logger.info(`onConversationUpdated[${f}]: ${JSON.stringify(scrubObjectFields(g,["organizerId","meetingData"]))}`),this.setConversationType(g.conversationType,f),this._onMessageIdChanged(g.teamsMessageId,f),this.setGroupId(g.groupId,f),this.setThreadId(g.threadId,f),this.setBackroomThreadId(g.backroomThreadId,f),this.setStreamThreadId(g.streamThreadId,f),this.setLobbyThreadId(g.lobbyThreadId,f),this.setCallType(g.isMultiParty?2:1,f),this._commandUrlPresence=g.commandUrlPresence,this.updateCapabilities(f),this.region=g.region,this.setMeetingData(g.meetingData),this.meetingInfo=g.meetingInfo,this.callLimits=g.callLimits,this.setComplianceRecordingContent(f,g.complianceRecordingContent),this.setHuddleGroupCall(g.isHuddleGroupCall),this.onConversationStartTimeChanged(g.conversationStartTime,f),this.raiseChanged()},onMeetingDetailsUpdated:g=>{this.meetingDetails=g,this.mediaSession&&!this.enableRealtimeTelemetry&&this.meetingDetails.meetingCapability?.enableRealtimeTelemetry&&(this.mediaSession.enableTeamsRealTimeTelemetry(),this.enableRealtimeTelemetry=!0),this.raiseChanged()},onMeetingStatesUpdated:g=>{(0,Ki.isEqual)(g,this.meetingStates)||(this.meetingStates=g,this.logger.info(`[onMeetingStatesUpdated] meetingStates updated to ${JSON.stringify(this.meetingStates)}`),this.raiseChanged())},onParticipantCountsUpdated:g=>{(0,Ki.isEqual)(g,this.participantCounts)||(this.participantCounts={...Si,...g},this.event("participantCountsUpdated").raise(this.participantCounts),this.mediaSession?.processNotification("ParticipantCountChanged",{count:g.totalParticipants}))},updateIsSharedLineAppearanceV2Activated:g=>{this.isSharedLineAppearanceV2Activated!==g&&(this.logger.info(`_updateIsSharedLineAppearanceV2Activated: new value is ${g}`),this.isSharedLineAppearanceV2Activated=g,this.event("sharedLineAppearanceV2ActivatedChanged").raise(this.isSharedLineAppearanceV2Activated))},onBroadcastMeetingUpdated:g=>{g&&(this.broadcastMeeting&&this.broadcastMeeting.metadataChanged(JSON.stringify(g)),this.broadcastMetadata=g,this.raiseChanged())},onBroadcastMeetingConnected:(g,f)=>{this.logger.info(`[${f}][onBroadcastMeetingConnected]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&(0===g.code?this._callOperationHandler.resolveOperation("AddBroadcastModality",g,f):this._callOperationHandler.rejectOperation("AddBroadcastModality",g,f))},onBroadcastMeetingEnded:(g,f)=>{this.logger.info(`[${f}][onBroadcastMeetingEnded]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&this._callOperationHandler.rejectOperation("AddBroadcastModality",g,f),this.signalingSession.endBroadcastMeeting(f)},onTransferRequested:(g,f)=>{const S=this.logger.createFnLogger("onTransferRequested",f);S.info("Transfer: onTransferRequested, target participant",scrubSignalingParticipant(g.target));let v="",C="",_=0;"voicemail"===g.target.endpointType&&(_=2);try{v=g.target.id,C=g.transferor.details.id,g&&g.parkType&&"none"!==g.parkType&&(_=1)}catch(g){return S.logFailure(g),this.callTelemetry.recordEvent("_OnTransferRequestedInvalid"),void this.signalingSession.signalTransferCompletedAsync({code:getCSAEndCode(7)})}const T=this.convertToTransferType(_,g.parkType),I={transferContext:{transferorMri:C,targetMri:v,transferType:_,context:{target:g.target,transferor:g.transferor,transferContext:g.transferContext,newCallModalities:g.newCallModalities,links:g.links,replacementDetails:g.replacementDetails,isConsultative:g.isConsultative,callAcceptanceCallback:()=>{S.logSuccess("Transfer: callAcceptanceCallback called"),this.signalingSession.signalTransferAcceptedAsync(T)}}},onCompleted:g=>{S.logSuccess("Transfer: onCompleted called"),this.signalingSession.signalTransferCompletedAsync({code:getCSAEndCode(g)})}};this.callTelemetry.recordEvent("_OnTransferRequested",{transferType:_}),this.event("transferRequested").raise(I)},onTransferredCallAcceptance:g=>{const f=this.logger.createFnLogger("onTransferredCallAcceptance",g);this._transferredCallAcceptanceCallback&&(f.info("[Transfer] Invoke call acceptance callback for original call"),this._transferredCallAcceptanceCallback())},onTransferAccepted:g=>{this.logger.info("Transfer: onTransferAccepted"),this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&this._setTransferState(2),this._callOperationHandler.hasPendingOperation("BlindTransfer")&&this._callOperationHandler.maybeResolveOperation("_CallTransferInProgress",void 0,void 0,g),this._callOperationHandler.hasPendingOperation("ParkCall")&&this._setParkState(2)},onTransferCompleted:(g,f)=>{const S=this.logger.createFnLogger("onTransferCompleted",f);S.info("Transfer: onTransferCompleted");const v=g.transferCompletion,C=convertReason(v);if(v&&(S.info(`Transfer: Call Transfer Code: ${v.code}`),0===v.code)){if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.resolveOperation("_CallTransferInProgress",void 0,void 0,f),this._setTransferState(3)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const g={code:0,subCode:0,phrase:"TransactionComplete"};this._callOperationHandler.resolveOperation("ConsultativeTransferWithPickupCode",g,void 0,f),this._setTransferState(3)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(g.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation&&(this.serverHoldLocation=g.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),void 0!==g.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("ParkCall",g.unparkContent.pickupCode,void 0,f),S.logSuccess(`pickupCode=${g.unparkContent.pickupCode}`),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",32,f),S.logFailure(`terminatedReason=${C}`),this._setParkState(4)))}else{if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.rejectOperation("_CallTransferInProgress",C,void 0,f),S.logFailure(`terminatedReason=${C}`),this.transferDiagnosticsInfo={callControllerCode:v.code,callControllerSubCode:v.subCode,phrase:v.phrase,resultCategories:v.resultCategories},this._setTransferState(4)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const g={code:v.code,subCode:v.subCode,resultCategories:v.resultCategories};this._callOperationHandler.rejectOperation("ConsultativeTransferWithPickupCode",g,void 0,f)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(this._callOperationHandler.rejectOperation("ParkCall",C,void 0,f),S.logFailure(`terminatedReason=${C}`),this.transferDiagnosticsInfo={callControllerCode:v.code,callControllerSubCode:v.subCode,phrase:v.phrase,resultCategories:v.resultCategories},this._setParkState(4))}},onParkCompleted:(g,f)=>{this.logger.createFnLogger("onParkCompleted",f).info(`transactionEnd ${getPrintableObject(g)}`),this._callOperationHandler.hasPendingOperation("CallParkV2")?0===g.code&&void 0!==g.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("CallParkV2",""+g.unparkContent?.pickupCode,void 0,f),this.callTelemetry.maybeRecordOperationSuccess("CallParkV2"),this.serverHoldLocation=g.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation,this.parkAdditionalContextJson=JSON.stringify(g.unparkContent.CallParkAdditionalContext)):this._callOperationHandler.rejectOperation("CallParkV2",g,f):this._callOperationHandler.hasPendingOperation("ParkCall")&&(0===g.code?(this._callOperationHandler.resolveOperation("ParkCall","",void 0,f),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",g,f),this._setParkState(4)))},onUnparkCompleted:(g,f)=>{this.logger.createFnLogger("onUnparkCompleted",f).info(`transactionEnd ${getPrintableObject(g)}`),this._callOperationHandler.hasPendingOperation("UnparkCall")&&(0===g.code?this._callOperationHandler.resolveOperation("UnparkCall",g,void 0,f):this._callOperationHandler.rejectOperation("UnparkCall",g,f))},onIncomingCallReplacement:(g,f)=>{const S=this.logger.createFnLogger("onIncomingCallReplacement",f);this.callTelemetry.recordEvent("_onIncomingCallReplacement",{},f),g.callNotification.callType="replaces",g.callNotification.consultativeCallId=this.callId,S.info(`consultativeCallId=${this.callId}`),g.body={gp:g,evt:Hi.INCOMING_SKYPE_NGC_CALL,nsp:void 0},this.event("replacementRequested").raise(g)},onContentSharingStopped:g=>{this.logger.debug("ScreenSharing: onContentSharingStopped");for(const f of this.contentSharingSessions)f.contentSharingGuid===g.correlationId&&(f.contentSharingStatus=7)},onContentSharingStarted:g=>{this.logger.debug("ScreenSharing: onContentSharingStarted");const f=new us(this.callTelemetry,this.logger.createChild("ContentSharingSession"),this.signalingSession,g.correlationId||generateGuid(),g.contentIdentifier,g.sessionState,g.subject,g.sessionId);f.contentSharingStatus=2,this.contentSharingSessions.push(f),f.changed((()=>this.removeContentSessionIfEnded(f))),this.event("contentSharingChanged").raise()},onContentSharingUpdated:g=>{this.logger.debug("ScreenSharing: onContentSharingUpdated");const f=(0,Ki.find)(this.contentSharingSessions,(f=>f.contentSharingGuid===g.correlationId));f?(g.presenter&&(f.presenterId=g.presenter),g.subject&&f.subject!==g.subject&&(f.subject=g.subject),g.sessionState&&f.contentSharingState!==g.sessionState&&(f.contentSharingState=g.sessionState),3===f.contentSharingStatus&&this.localSignalingParticipant.id!==g.presenter?f.contentSharingStatus=5:5===f.contentSharingStatus&&this.localSignalingParticipant.id===g.presenter&&(f.contentSharingStatus=3)):this.logger.warn("onContentSharingUpdated: session not found")},onWebRtcMediaNotification:(g,f)=>{this.mediaSession?.processNotification(g,f)},onCorrelationIdUpdated:(g,f)=>this.checkForCallIdUpdate(g,f),onUnmuteRequested:g=>{},onCallForwarded:g=>{g&&g.destinationType!==this.forwardingDestinationType&&(this.forwardingDestinationType=g.destinationType,this.raiseChanged())},onPSTNBalanceUpdate:g=>{},isOneToOnePstnCall:()=>this.isOneToOnePSTNCall(),onUpdateMeetingLiveStateCompleted:(g,f,S)=>{this.logger.info(`[onUpdateMeetingLiveStateCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"UpdateMeetingLiveState",S)},onUpdateMeetingStatesCompleted:(g,f,S)=>{this.logger.info(`[onUpdateMeetingStatesCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"UpdateMeetingStates",S)},onUpdateMeetingGroupsCompleted:(g,f,S)=>{this.logger.info(`[onUpdateMeetingGroupsCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"UpdateMeetingGroups",S)},onSetMeetingLayoutCompleted:(g,f,S)=>{this.logger.info(`[onSetMeetingLayoutCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"SetMeetingLayout",S)},onJoinMeetingGroupCompleted:(g,f,S)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"JoinMeetingGroup",S)},onLeaveMeetingGroupCompleted:(g,f,S)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"LeaveMeetingGroup",S)},onBreakoutDetailsUpdated:(g,f)=>{this.logger.info(`[onBreakoutDetailsUpdated] [${f}]`),this.breakoutDetails=g,this.raiseChanged()},onIncomingProxiedMessages:(g,f)=>{this.logger.info(`[onIncomingProxiedMessages] [${f}] payload ${getPrintableObject(g,!0)}`),this.event("incomingProxiedMessages").raise(g)},onUpdateParticipantsPropertiesCompleted:(g,f,S)=>{this.logger.createFnLogger("onUpdateParticipantsPropertiesCompleted",S).info(`promisesToResolve ${scrubMriOrOmit(safeJsonStringify(g))}`);for(const f of Object.keys(g)){g[f].code===bi.CODE.SUCCESS?this._callOperationHandler.maybeResolveOperation("UpdateParticipantsProperties",g[f],f,S):this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",g[f],f,S)}},onUpdateMonitorSessionCompleted:(g,f)=>{this.logger.info(`[onUpdateMonitorSessionCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"UpdateMonitorSession")},onNudgeToJoinRealtime:g=>{this.logger.info("[onNudgeToJoinRealtime]",g),this.callTelemetry.recordEvent("NudgeToJoinRealTime",g),this.canPromoteToRealTime(1)&&this.promoteToRealtime(1,g).then((()=>this.logger.info(`[onNudgeToJoinRealtime][${g}] completed`))).catch((f=>this.logger.info(`[onNudgeToJoinRealtime][${g}] failed to auto promote: ${getPrintableObject(f)}`)))},onConversationTypeUpdated:(g,f)=>{this.logger.info(`[onConversationTypeUpdated] [${f}] conversationType ${g}`),this.setConversationType(g,f)}};const S=Object.create(this.localSignalingParticipant);this.signalingSession=this.signalingAgent.getNewSignalingSession(S,this.signalingNotifications,this.callId,this._callCreationTime),this.signalingSession.participantManager.setEnableMuteAsync(this._enableMuteAsync),this.signalingSession.participantManager.setEnableUnmuteAsync(this._enableUnmuteAsync),this.accountConfiguration&&this.accountConfiguration.deviceType&&this.signalingSession.setDeviceType(this.accountConfiguration.deviceType),this.setCallId(this.callId||this.signalingSession.correlationId),this.signalingSession.participantManager&&this.signalingSession.participantManager.localParticipant&&(this.setDisplayName(this.signalingSession.participantManager.localParticipant.displayName),this.setEndpointId(this.signalingSession.participantManager.localParticipant.endpointId),this.setParticipantId(this.signalingSession.participantManager.localParticipant.participantId),this.callStats.setParticipantId(this.participantId))}updateParticipantStreams(g,f,S,v){const C=_PluginlessCall.getNegotiationTagsFromEndpoints(f.endpointDetails);g.updateStreams(S,v,this.isCallModeStreaming(),C,this.isMultiVBSSEnabled());const _=this.getStreamInformationMap(f);this.logger.info(`[updateParticipantStreams]: streaming mode with new streamInfoMap: ${safeJsonStringify(_)}`);const T={callId:this.callId,participantId:this.participantId,endpointId:this.endpointId};this.meetingData&&(T.meetingId=this.meetingData.meetingCode);const I=this.telemetryLoggers?this.telemetryLoggers.tlePlayer:null;g.useUmsStream(_,this._liveStreamConfigProvider,T,this.threadId,I,v)}cleanUpDueToStreaming(g){this.logger.info(`cleanUpDueToStreaming[${g}]: cleaning streams and media and canceling cc operations`),this.cancelAllCallingOperationsDueToStreaming(g);const f={code:Fi.Success,subCode:xi.DowngradeToStreamingClient,phrase:Gi.DowngradeToStreamingClient};this.participants.forEach((f=>f.updateStreams([],g,this.isMultiVBSSEnabled()))),this.cleanUpMedia(g,f).then((()=>{this.callTelemetry.recordOperationSuccess("_MediaCleanUp")})).catch((f=>{this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:getPIISafeObject(f)},g)})).finally((()=>{this.mediaDisposedPromise=null})),this.finishCallHoldResume(f),this.renegotiationAnswerDeferred?.reject(f),this.newOfferRequestDeferred?.reject(f),this._parkState=0,this._transferState=0,this.isServerMuted||(this._muteState=0),this.isSpeakerMuted=!1,this.requestedHoldState=!1,this.isMuteOnHold=!1}cancelAllCallingOperationsDueToStreaming(g){this._callOperationHandler.maybeRejectPendingOperationsWithPredicate(74,g,((g,f)=>(0,Ki.some)(f?.preconditionTags,(g=>"NOT_SUPPORTED_IN_STREAMING_MODE"===g))))}onOperationCompleteCommonHandler(g,f,S,v){0===g.code?this._callOperationHandler.maybeResolveOperation(S,g,v,f):this._callOperationHandler.maybeRejectOperation(S,g,v,f)}convertToTransferType(g,f){let S="none";return 1===g&&f&&"none"!==f?"teamPark"===f?S="TransferTypeTeamPark":"sharedLinePark"===f?S="TransferTypeSharedLinePark":"serverHold"===f&&(S="TransferTypeServerHold"):0===g?S="TransferTypeStandard":2===g?S="TransferTypeVoicemail":this.logger.info(`Irrelevant combination of transferTye: ${g} and parkType: ${f}`),S}raiseChangedDeferred(g){(!this.raiseChangedDefer||this.raiseChangedDefer.isSkippable&&!g)&&(Vr.instance.runDeferredWithoutDedup((()=>{delete this.raiseChangedDefer,this.raiseChanged(g)}),"Call.raiseChanged"),this.raiseChangedDefer={isSkippable:!!g})}static getStreamsFromEndpoints(g,f){if(!g)return[];const S=_PluginlessCall.filterVirtualEndpoints(g);return S.forEach((g=>{g.mediaStreams=f?g.mediaStreams:g.mediaStreams?.filter((g=>g.type!==$r.xsharing)),(0,Ki.forEach)(g.mediaStreams,(f=>{f.participantId=g.participantId,f.endpointId=g.endpointId}))})),(0,Ki.flatMap)(S,(g=>g&&g.mediaStreams||[]))}preconditions(g,f){this.logger.info(`check call mode currentMode is ${this.callMode} operationName is ${g}`),(0,Ki.some)(f,(g=>"NOT_SUPPORTED_IN_STREAMING_MODE"===g))&&this.isCallModeStreaming(!0)}mapCallSetupIntent(g){switch(g){case 0:return"None";case 1:return"AutoPromotion";case 2:return"PromotionWithAudio";case 3:return"PromotionWithVideo";default:return"Unknown"}}async promoteToRealtime(g,f){this.logger.info(`[${f}][promoteToRealtime] started with intent=${g}`);const S=this.getPromoteToRealtimeCallOptions(g,this.callOptions);this.callTelemetry.updateOperationData("_PromotionToRealtime",{intent:g},f),this.callTelemetry.recordEvent("StartPromotion",{intent:this.mapCallSetupIntent(g)},f);try{this.promotionCompletedDeferred=new dt,await Promise.all([this.joinOrStartCall(S,this.joinGivenConversation,f,void 0),this.promotionCompletedDeferred.promise])}catch(g){throw this.logger.logFailure(`[${f}][promoteToRealtime] failed with reason=${getPrintableObject(g)}`),this.cleanUpDueToStreaming(f),this.signalingSession.cleanUpDueToStreaming(f),g}}async promoteToRealtimeAndUnmute(g){return this.logger.info(`[${g}][promoteToRealtimeAndUnmute]`),this.isPromotingToRealtime()?(this.logger.info(`[${g}][promoteToRealtimeAndUnmute] already promoting to realtime.`),this._callOperationHandler.waitForOperation("_PromotionToRealtime").then((()=>this.muteUnmute(!1,g)))):this.canPromoteToRealTime(2)?(this.unmutePendingPromise=new dt,setTimeout((()=>{this.unmutePendingPromise?.reject("promoteToRealtime unmute timed out")}),1e3*this.signalingSession.signalingAgentConfig.csaTimeoutConfiguration.promotionUnmuteTimeoutSec),Promise.all([this.promoteToRealtime(2,g),this.unmutePendingPromise.promise]).then((()=>{})).finally((()=>this.unmutePendingPromise=null))):Promise.reject("manual promotion with audio is not allowed")}isPromotingToRealtime(){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")}getPromoteToRealtimeCallOptions(g,f){let S,v=1;1===g?S={value:!0,mediaTypes:["audio"]}:3===g?(S={value:!0,mediaTypes:["audio"]},v=4):2===g&&(S={value:!1});const C={...f.callStartOptions,sendMediaModalities:{mediaStates:[getMediaState(0,4),getMediaState(1,v)].filter((g=>null!=g))},preheatFlags:0};return{...f,callStartOptions:C,applyServerMute:S,isPromotingToRealtime:!0,callStartTime:Date.now()}}canPromoteToRealTime(g){const f=this.logger.createChild("[canPromoteToRealTime]");return f.info(`[promoteType:${g}]`),this.isCallModeStreaming()?this.isPromotingToRealtime()?(f.info("already promoting to realtime"),!1):1===g||2===g:(f.info("cant promote since call mode is not streaming"),!1)}isCallModeStreaming(g=!1){if(2===this.callMode){if(!g)return!0;throw this.logger.info("reject check callmode"),{code:499,subCode:3551,phrase:"TransactionNotAllowedForStreamMode"}}return!1}setCallOptions(g){this.receiveOnlyAudioOnCallStart=!!g.callStartOptions?.receiveOnlyAudioOnCallStart,this.callOptions=g,this.logger.info(`callOptions: ${safeJsonStringify(scrubCallOptions(g))}`)}getSelfClientEndpointCapabilities(){return this.callOptions?.callStartOptions?.clientEndpointCapabilities}getLocalSignalingEndpointDetails(){return(0,Ki.find)(this.localSignalingParticipant.endpointDetails,(g=>g?.endpointId===this._endpointId))}getStreamInformationMap(g){const f={};return g&&this.accountConfiguration?.clientSupportsUms&&(0,Ki.forEach)(g.endpointDetails,(g=>{g?.streamInformation&&g.participantId&&g.participantId!==this._participantId&&(f[g.participantId]=g.streamInformation)})),f}updateSATInfo(g=[]){const f=this.mediaSession?.getSessionConfig().config.slowedDownTalkerInfoAggregationTime;if(!f||f<0)return;const S=Date.now(),v=S-1e3*f;this.activeTalkersHistory=this.activeTalkersHistory.filter((({timestamp:g})=>g>v)).concat({speakers:g.map((g=>g.id)),timestamp:S});const C=Object.entries(this.activeTalkersHistory.reduce(((g,{speakers:f})=>{for(const S of f)g[S]??(g[S]=0),g[S]++;return g}),{})).sort((([,g],[,f])=>f-g)).map((([g])=>g));this.slowedDownActiveTalkerInfo={speakerList:C,timestamp:new Date(S)}}setPlatformCallConstraints(g){this.setCallConstraints(g).catch((g=>{this.logger.error(g)}))}setCallConstraints(g){return this.mediaSession?(this.logger.info(`Applying platform constraints to current call ${JSON.stringify(g)}`),this.mediaSession.setCallConstraints(g,generateCauseId())):(this.logger.info("Saving platform constraints until media session is created"),this.temporaryCallConstraints=g,new Promise(((g,f)=>{this.resolveTemporaryCallConstraints=g,this.rejectTemporaryCallConstraints=f})))}initializeMediaSession(g,f){if(this.mediaSession)return;const S=this.logger.createFnLogger("initializeMediaSession",g),v=((g,f)=>{const S={};return Object.keys(f).forEach((v=>{S[v]=(...S)=>f[v]&&g()&&f[v](...S)})),S})((()=>!this.isCallModeStreaming()||this.isPromotingToRealtime()),{onSessionErrorOccurred:(g,f=generateCauseId())=>{S.error(`[${f}][onSessionErrorOccurred]: ${safeJsonStringify(g)}`);const v=[this.mediaAgent.constants.MEDIA_ERROR.iceConnectionError,this.mediaAgent.constants.MEDIA_ERROR.internalError];(0,Ki.includes)(v,g.type)&&this.event("mediaConnectionFailed").raise(),this.callTelemetry.recordEvent("SessionError",{type:g.type},f)},onNegotiationRequired:(g=generateCauseId(),f)=>{this.executeNegotiation(g,"onNegotiationRequired",!0,f)},onContributingSourcesChanged:g=>{const f=this.mediaSession?.getSessionConfig().config.contributingSourcesLogInterval,v=f&&Date.now()>=this.lastContributingSourceReport+f,C=v?new Map(g.map((g=>[g,"<unknown>"]))):new Map,_=[];for(const f of this.participants){const S=g.some((g=>f.hasAudioSource(g))),T=S?1:0;f.updateVoiceLevel(T),S&&(_.push(f),v&&C.set(f.audio.id,scrubMriOrOmit(f.id)))}this.updateSATInfo(_),v&&(S.info(`[onContributingSourcesChanged], ${g.length?Array.from(C).join(";"):"none"}`),this.lastContributingSourceReport=Date.now())},onDominantSpeakerChanged:(g,f)=>{const v=generateCauseId(),C=[],_=[];g.forEach((g=>{const f=(0,Ki.find)(this.participants,(f=>f.hasAudioSource(g)));f?(C.push(f.id),_.push(scrubMriOrOmit(f.id))):_.push(this.streamManager.audio.id===g?"<self>":"<unknown>")})),S.info(`[${v}][onDominantSpeakerChanged], msidList = ${g} => speakerList = ${_}, timestamp = ${f}`),this.dominantSpeakerInfo={speakerList:C,timestamp:f,noCurrentDominantSpeaker:!1},this.event("dominantSpeakerChanged").raise(),this.raiseChanged(this._dominantSpeakerChangedEventSkipConfig)},onAudioStateChanged:(g,f)=>{const S=generateCauseId(),v=this.logger.createFnLogger("onAudioStateChanged",S);v.info(safeJsonStringify(g)),this.callStats.localStats.audio.streamStateChanged(g.stream,g.direction);const C=_PluginlessCall.streamingStatetoMediaStreamState(g.stream);if(this.audioStreamState=C,!C)return;this.callTelemetry.recordEvent("AudioStateChanged",{state:g,reason:f},S),2===C&&2===this.state&&(this.setCallState(9,S),this.participants.forEach((g=>g.setState(6,void 0,S))));const _={mediaType:0,mediaDirection:_PluginlessCall.streamingDirectionToMediaDirectionMapping(g.direction),mediaStreamState:C};this.event("mediaStreamStateChanged").raise(_),!this.isCallSetupTelemetrySent&&this.mediaSession?.getSessionConfig().config.sendCallStartupTelemetry&&this.sendCallSetupTelemetry(),0===_.mediaDirection&&(this.isAudioStreamConnected=(0,Ki.includes)([2,1],_.mediaStreamState));if((0,Ki.includes)([3,4],_.mediaStreamState)){v.logFailure(`audio stream state changed to ${g.stream} with reason ${f}`);if(!f||["timeout","connection-dropped","connectivity-check-failure","suspended"].indexOf(f)>=0){this.event("mediaConnectionFailed").raise();const g="suspended"===f?77:this.mediaRelayWhiteListingIssue?53:4;this.mediaRelayWhiteListingIssue&&this.callTelemetry.recordEvent("_MediaWhiteListingIssueDetected"),this.stopInternal({causeId:S,terminatedReason:g})}}},onQualityChanged:g=>{const f={type:_PluginlessCall.convertQualityEventType(g.type),value:_PluginlessCall.convertQualityLevel(g.value),isLocalSource:g.isLocalSource,mediaType:_PluginlessCall.convertMediaType(g.mediaType)};this.muteUnmuteWorkaround(f),32===f.type&&(this.mediaRelayWhiteListingIssue=3===f.value,this.mediaRelayWhiteListingIssue&&this.event("mediaConnectionWhitelistingWarning").raise()),5===f.type&&3===f.value&&this.trouterService.checkConnection(!0),this.callTelemetry.recordEvent("AudioQualityChanged",f),this.remoteUFDHandler.raiseIfNeeded(g,this.participantCounts?.totalParticipants,(g=>{this.publishState(g,generateCauseId())})),this.event("callQualityChanged").raise(f)},onOptimalVideoReceiversCountChanged:g=>{S.debug(`onOptimalVideoReceiversCountChanged: ${g}`),this.optimalVideoCount!==g&&(this.optimalVideoCount=g,this.raiseChanged())},onDataChannelUpdated:g=>{const f=generateCauseId();S.debug(`[${f}] onDataChannelUpdated`),this.dataChannel.registerSessionDataChannel(g,f)},onUpdateMediaDescriptionsRequired:(g,f)=>{this.executeNegotiation(g,"onUpdateMediaDescriptionsRequired",!1,f)},onRealtimeTelemetryReport:()=>{this.reportTelemetryEvents([{eventName:vr.realtimeTelemetry,props:{user_object_id:{value:rr+this.currentUserSkypeIdentity.id,piiKind:10},display_name:{value:this.displayName,piiKind:1},call_context_id:{value:this.signalingSession.correlationId,piiKind:0},participant_id:{value:this.participantId,piiKind:0},media_leg_id:{value:this.mediaLegId,piiKind:0},DiagnosticLevel:{value:255,piiKind:0},eventpdclevel:{value:2,piiKind:0},eventpriority:{value:5,piiKind:0},call_technical_info:{value:JSON.stringify(this.mediaSession.getCallTechnicalInfo()),piiKind:0}}}],"realtimeMedia","mdsc")},onTransportConnected:()=>{this.allowDataChannel()||this.mediaStateConfigurationHelper.isSending(3)||this.isInitialSignalingDSHSubscriptionEnabled()||!this.callUsesMixer||this.updateSignalingDSHMessageSubscription(!0),this.unmixedAudioProvider.setSessionStreamsProvider(this.mediaSession.getUnmixedAudioProvider()),this.event("transportConnected").raise()},onTransportDisconnected:()=>{this.event("transportDisconnected").raise()},onTransportFailed:()=>{this.event("transportFailed").raise()},onUpdateSignalingDSHMessageSubscription:g=>this.updateSignalingDSHMessageSubscription(g)});this.callTelemetry.recordEvent("CreatingConference","",g),this.callDeviceManager||(S.info(`[${g}][initializeMediaSession] Creating new callDeviceManager`),this.callDeviceManager=this.createCallDeviceManager());const C={maxReinvitelessMediaForVBSSMultiparty:this.signalingSession.getMaxReinvitelessMediaForVBSSForWeb(),maxReinvitelessMediaForVideoMultiparty:this.signalingSession.getMaxReinvitelessMediaForVideoForWeb()};this.callTelemetry.recordEvent("_ReinvitelessConfig",{reinvitelessConfig:C},g);const _=this.mediaAgent?.getConfigProvider().config.identifyOneToOneCallWithoutParticipants;this.mediaSession=new Nr(this.mediaAgent.createSession(v,this.signalingSession,{isConference:this.callUsesMixer,isPstnCall:this.isOneToOnePSTNCall(_),isParkedCall:this.isParkedCall(),reinvitelessConfig:C},this.callDeviceManager,this.smallCallTelemetry,f),this.signalingSession),this.batteryStatus=new io(this.mediaSession.getDiagnostics(),this.mediaAgent.getConfigProvider()),this.batteryStatus.on("batteryStatusChanged",(()=>this.reportSmallCallEvent(this.smallCallTelemetry?.getSmallTelemetryOnBatteryLow()))),this.temporaryCallConstraints&&(S.info(`Applying saved call constraints to current call ${JSON.stringify(this.temporaryCallConstraints)}`),this.mediaSession.setCallConstraints(this.temporaryCallConstraints,generateCauseId()).then(this.resolveTemporaryCallConstraints).catch(this.rejectTemporaryCallConstraints).finally((()=>{this.temporaryCallConstraints=void 0,this.rejectTemporaryCallConstraints=void 0,this.resolveTemporaryCallConstraints=void 0}))),this.dataChannel.setConfigProviderView(this.mediaSession.getSessionConfig()),this.callTelemetry.recordEvent("CreatedConference","",g),this.streamManager.setMediaSession(this.mediaSession,g),this.participants.forEach((f=>{f.setMediaSession(this.mediaSession,g)}));const T=this.mediaSession.getSessionConfig()?.config;T?.useOneDsLogger&&T?.addTelemetryReportingCallback&&(this.beforeUnloadTelemetrySender=()=>{this.sendLastKnownStats()},window.addEventListener("beforeunload",this.beforeUnloadTelemetrySender)),this.screenSharingControl&&this.allowDataChannel()&&this.screenSharingControl.setupDataHandlers(),this.unmixedAudioProvider=new Qa}executeNegotiation(g,f,S,v){const C=this.logger.createFnLogger(f,g);if(this.isCallModeStreaming()||this.isEscalationInProgress)return void C.info(`ignored due to being in streaming=${this.isCallModeStreaming()},\n                isEscalationInProgress=${this.isEscalationInProgress}`);const _=generateCauseId();3===this.state||4===this.state||5===this.state||10===this.state||this.isPreheatedOnly()?(C.info(`started, state: ${this.state}, runNegotiation: ${S}`),S?(this.callTelemetry.recordEvent("NegotiationRequired","",g),this._callOperationHandler.executeChained((()=>this.renegotiateOutgoing(g,v)),"_RenegotiateOutgoing",_,g,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})):(this.callTelemetry.recordEvent("UpdateMediaDescriptions","",g),this._callOperationHandler.executeChained((()=>this.updateMediaDescriptions(g,v)),"_UpdateMediaDescriptions",void 0,g,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}))):C.info(`not started, state: ${this.state}`)}async muteUnmuteWorkaround(g){if(this.mediaSession?.getSessionConfig().config.enableMuteSpeakerUnmuteSpeakerWorkaround&&!this.isSpeakerMuted&&25===g.type&&3===g.value&&0===g.mediaType){this.logger.log("Performing muteSpeaker->unmuteSpeaker workaround");const g=generateCauseId();await this.muteSpeaker(g),await this.unmuteSpeaker(g)}}sendLastKnownStats(){if(this.tsCallingTelemetryReported)return;this.callEndDiagnosticsInfo={callControllerCode:bi.CODE.SUCCESS,callControllerSubCode:bi.SUB_CODE.BEACON},this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo);const g=this.callTelemetry.getShortEvent();g.Code=this.callEndDiagnosticsInfo.callControllerCode,g.SubCode=this.callEndDiagnosticsInfo.callControllerSubCode;let f="csa_conversation_callmodality";if(this.reportTelemetryEvents([{eventName:f,props:g}],"signaling","skypecosi_concore_web"),f=this._callIsSetupComplete?"in_call_session":"call_setup_session",this.reportTelemetryEvents([{eventName:f,props:this.callTelemetry.getEvent(!0)}],"signaling","skypecosi_concore_web_ts_calling"),this.mediaSession){const g=this.mediaSession.getLastKnownStats(!0);this.callStats.setMediaStats(g),this.reportSmallCallEvent(null,!0),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web")}this.reportVDITelemetryEvents()}reportSmallCallEvent(g,f){this.reportTelemetryEvents(this.callStats.buildShortCallEvent(g??this.smallCallTelemetry?.getEndCallSmallTelemetry(f)),"media","mdsc")}invertDirectionality(g){switch(g){case this.mediaAgent.constants.MEDIA_STATE.sendReceive:return Hr.sendReceive;case this.mediaAgent.constants.MEDIA_STATE.send:return Hr.receive;case this.mediaAgent.constants.MEDIA_STATE.receive:return Hr.send;default:return null}}completeNegotiationAsync(g){const f=this.logger.createFnLogger("completeNegotiationAsync",g),S=this.mediaSession.completeNegotiationAsync(g).then((S=>{f.info(`activeModalities=${S&&Object.keys(S.activeModalities)}`);const v=this.mediaSession.getSessionConfig().config.avoidFakeStreamsDuringEscalation&&this.isEscalationInProgress;if(!this.callUsesMixer&&!v){if(this.mediaStateConfigurationHelper.isSending(3)&&S.initiator){const f=S.offeredModalities.data===this.mediaAgent.constants.MEDIA_STATE.sendReceive,v=S.activeModalities.data===this.mediaAgent.constants.MEDIA_STATE.sendReceive;f&&!v&&(this.logger.info(`[${g}][completeNegotiationAsync] Disabling data modality as it was not wanted by remote`),this.mediaStateConfigurationHelper.removeModality(3))}const f=this.participants[0],v=f?.endpoints?.endpointDetails.length&&f.endpoints.endpointDetails[0].mediaStreams?.length;if(f&&!v){const prepareStreamData=(g,f,S)=>({participantId:so,endpointId:ro,type:g,direction:this.invertDirectionality(f),sourceId:S,serverMuted:!1}),v=[];v.push(prepareStreamData($r.audio,S.activeModalities.audio,ss)),S.activeModalities.video&&v.push(prepareStreamData($r.video,S.activeModalities.video,as)),S.activeModalities.sharing&&v.push(prepareStreamData($r.sharing,S.activeModalities.sharing,os)),f.updateStreams(v,g,this.isMultiVBSSEnabled()),!this.callIsHeld()&&this.calculateIsSomeoneStreaming(g)}}if(f.logSuccess(safeJsonStringify(S)),this.mediaAgent.getConfigProvider().config.syncMuteStateWithAudioDirection&&S?.activeModalities?.audio){const f=S.activeModalities.audio===this.mediaAgent.constants.MEDIA_STATE.receive||S.activeModalities.audio===this.mediaAgent.constants.MEDIA_STATE.inactive;this.setMuted(f?2:this.isServerMuted?1:0,g)}return S}));return S.catch((S=>{f.logFailure(S),this.callTelemetry.recordEvent("_CompleteNegotiationFailed",{e:S},g)})),S}async renegotiateOutgoing(g,f){this.renegotiationAnswerDeferred=new dt;const S=this.logger.createFnLogger("renegotiateOutgoing",g),v=this.inLocalHold()?this.getMediaModalitiesForHold(g):this.calculateModalityDirections({},g);if(this._delayedElevationPending&&!this._delayedElevationQueued){if(hasSendDirectionality(v.video)||hasSendDirectionality(v.sharing))return S.info("mediaModalities",v),void await this.triggerDelayedReconnectIfNeeded(g,"renegotiateOutgoing");S.info("Delayed elevation (renegotiateOutgoing): no outgoing video or sharing, skipping elevation for now")}S.info("start");const C=createPhaseExecutor(S);try{try{const S=await C.execute("MediaCreateOffer",(()=>this.mediaSession.createOfferAsync(g,f))),_=this.getSignalingMediaTypes(v);await C.execute("SignalingStartNegotiation",(()=>this.signalingSession.startRenegotiationAsync(S,_,g)));const T=await C.execute("SignalingRenegotiationAnswer",(()=>this.renegotiationAnswerDeferred.promise));await C.execute("MediaProcessAnswer",(()=>this.mediaSession.processAnswerAsync(T,g,!1)));const I=await C.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(g)));this.onNegotiationCompletion(I,!0,v,g,C.getTelemetryData())}catch(f){if(S.logFailure(f),!f.phase)throw this.callTelemetry.recordEvent("OutgoingNegotiationFailure",f,g),f;let C="unknown";const _=this.mediaAgent.constants.RENEGOTIATION_ERROR;if(C=_.local,"SignalingRenegotiationAnswer"===f.phase||"SignalingStartNegotiation"===f.phase){const g=415;C=f.error.code===Fi.GlareError?_.glare:f.error.code===g?_.media:_.signaling}else"MediaCreateOffer"===f.phase&&f.error.type===this.mediaAgent.constants.MEDIA_ERROR.noNetworkError&&(C=_.media);if(this.callTelemetry.recordEvent("OutgoingNegotiationFailure",this.getTelemetryFromPhaseExecution(f),g),f.error.message?.includes("The requested call does not exist"))throw new Error("Call drop due to remote replying with call not found");S.logFailure(C);const T={type:C,detail:f.error};await this.mediaSession.rejectNegotiationAsync(T,g),this.onNegotiationFailure(f.error,C,g,v)}}catch(f){S.logFailure(f),this.callTelemetry.recordEvent("NegotiationFatalError",getPIISafeObject(f),g),this.stopInternal({causeId:g,terminatedReason:47})}}async renegotiateIncoming(g,f){this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",null,f,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.mediaAcknowledgmentOperation.catch(noop);const S=this.logger.createFnLogger("renegotiateIncoming",f);if(S.info("start"),g.newOffer&&!this.mediaAgent.getCapabilities().retargeting)return S.logFailure("Retarget offer received, but pluginless has no support for retarget"),void this.stopInternal({causeId:f,terminatedReason:38});const v=createPhaseExecutor(S);try{const S=await v.execute("MediaProcessOffer",(()=>this.mediaSession.processOfferAsync(g,f)));this.handleOfferedModalities(S,f),2===this.getRenegotiationOfferType(S)&&await this.prepareModalitiesForResume(f);const C=await this.updateMediaModalities({offered:S},f);1===this.getRenegotiationOfferType(S)&&await this.prepareModalitiesForHold(f),this.updateMediaState(C,f),this.isRenegotiationHoldOrResume(C)&&this.updateScreenSharingState(C,f);const _=await v.execute("MediaCreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,f))),T=this.getSignalingMediaTypes(C);await v.execute("SignalingAcceptRenegotiation",(()=>this.signalingSession.acceptRenegotiationAsync(_,T,f))),await v.execute("SignalingMediaAcknowledgement",(()=>this.mediaAcknowledgmentOperation));const I=await v.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(f)));this.onNegotiationCompletion(I,!1,S,f,v.getTelemetryData())}catch(g){try{if(!g.phase||"CompleteNegotiation"===g.phase)throw this.callTelemetry.recordEvent("IncomingNegotiationFailure",g,f),g;const v=g;this.callTelemetry.recordEvent("IncomingNegotiationFailure",this.getTelemetryFromPhaseExecution(g),f);const C={type:this.mediaAgent.constants.RENEGOTIATION_ERROR.local,detail:g.error};if("SignalingAcceptRenegotiation"===v.phase||"SignalingMediaAcknowledgement"===v.phase)return S.logFailure("Error in renegotiateIncoming() -> rejecting media negotiation"),C.type=this.mediaAgent.constants.RENEGOTIATION_ERROR.signaling,this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",C,void 0,f),void await this.mediaSession.rejectNegotiationAsync(C,f);this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",C,void 0,f),await this.mediaSession.rejectNegotiationAsync(C,f),await this.signalingSession.rejectRenegotiationAsync(void 0,f)}catch(g){S.logFailure(g),this.callTelemetry.recordEvent("NegotiationFatalError",getPIISafeObject(g),f),this.stopInternal({causeId:f,terminatedReason:47})}}}async updateMediaDescriptions(g,f){const S=this.logger.createFnLogger("updateMediaDescriptions",g);S.info("start");try{const v=await this.mediaSession.startMediaDescriptionsUpdateAsync(g,f);S.info(`send updateMediaDesriptions, descriptions=${safeJsonStringify(v)}`),await this.signalingSession.updateMediaDescriptionsAsync(g,v);const C=await this.mediaSession.completeMediaDescriptionsUpdateAsync(g);if(this.mediaAgent.getConfigProvider().config.syncMuteStateWithAudioDirection&&C?.appliedModalities?.audio){const f=C.appliedModalities.audio===this.mediaAgent.constants.MEDIA_STATE.receive||C.appliedModalities.audio===this.mediaAgent.constants.MEDIA_STATE.inactive;this.setMuted(f?2:this.isServerMuted?1:0,g)}this.onUpdateMediaDescriptionsCompletion(C,g)}catch(f){S.logFailure(f),this.callTelemetry.recordEvent("UpdateMediaDescriptionsFailure",f,g);const v=await this.mediaSession.rejectMediaDescriptionsUpdateAsync(g,!0);this.onUpdateMediaDescriptionsFailure(f,v,g)}}handleCallEscalation(g,f){const S=this.logger.createFnLogger("handleCallEscalation",f);if(S.info(`current callType=${this.callType}, escalationInProgress=${g}, isEscalationInProgress=${this.isEscalationInProgress}`),g){const g=this.participants[0];g&&g.audio.participantId===so?g.updateStreams([{type:$r.audio,direction:"inactive",sourceId:null,serverMuted:!1},{type:$r.video,direction:"inactive",sourceId:null,serverMuted:!1},{type:$r.sharing,direction:"inactive",sourceId:null,serverMuted:!1}],f,this.isMultiVBSSEnabled()):S.info("no 1-1 participant found, stream update ignored"),this.setCallType(2,f),this.setCallUsesMixer(!0,f),this.setIsEscalationInProgress(!1,f),this.callTelemetry.recordEvent("_EscalationCompleted",void 0,f),this.raiseChanged()}}async reportTsCallingTelemetry(g){if(this.tsCallingTelemetryReported)return;await this.connectCallPromise.catch(noop);const f=g?"call_setup_session":"in_call_session";this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo),this.reportTelemetryEvents([{eventName:f,props:this.callTelemetry.getEvent(g)}],"signaling","skypecosi_concore_web_ts_calling"),g?this.callTelemetry.switchToInCallTelemetry():this.tsCallingTelemetryReported=!0}async sendMidCallTelemetry(g){this.mediaSession&&g?.length&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(!0)),this.appendInfoToCallStats(),this.reportTelemetryEvents(this.callStats.buildMidCallTelemetry(g),"media","mdsc_mid_call_telemetry"))}sendCallSetupTelemetry(){this.mediaSession&&(this.collectCallStats(this.mediaSession),this.reportCallSetupStats(),this.isCallSetupTelemetrySent=!0)}collectCallStats(g){const always=()=>this.collectMediaStatsDeferred.resolve();return g.getStatsAsync(!1).then((g=>this.callStats.setMediaStats(g))).then(always,always)}reportCallSetupStats(){this.collectMediaStatsDeferred.promise.then((()=>{this.reportTelemetryEvents(this.callStats.buildFromCallSetupStats(this.signalingSession.baseMessagingChannelUrl),"media","mdsc"),this.event("statsReported").raise(),this.collectMediaStatsDeferred=new dt}))}async reportCallEndStats(g){this.callTelemetry.setTerminationState(this.state),this.callTelemetry.setTerminationReason(this.terminatedReason),this.callStats.localStats.endCall(this.terminatedReason),g&&this.mediaAgent.getConfigProvider().config?.smallCallTelemetry?.enable&&this.reportSmallCallEvent(null),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web"),this.reportTsCallingTelemetry(!this._callIsSetupComplete),g&&(await this.collectMediaStatsDeferred.promise,this.callStats.appendTerminationInfo(this.terminatedReason,this.state),this.appendInfoToCallStats(),this.reportTelemetryEvents(this.callStats.buildFromMediaStats(),"media","mdsc")),this.reportVDITelemetryEvents(),this.event("statsReported").raise(),this.collectMediaStatsDeferred=new dt}async reportVDITelemetryEvents(){this.vdi3diagnostics&&this.reportTelemetryEvents([{eventName:"vdi_webrtc_session",props:await this.callStats.buildVDItelemetryReport(this.vdi3diagnostics)}],"media","mdsc")}reportTelemetryEvents(g,f,S){const v=this.telemetryLoggers?this.telemetryLoggers[f]:null;v?g.forEach((g=>v.sendEvent({eventName:`${S?`${S}_`:""}${g.eventName}`,props:g.props}))):this.logger.debug(`reportTelemetryEvents no logger for tenant ${f}`)}onLocalPreviewSizeChanged(g,f){this.logger.debug(`onLocalPreviewSizeChanged: ${g}x${f}`)}onLocalPreviewStateChanged(g){this.logger.debug(`onLocalPreviewStateChanged: ${g}`),this.callStats.localStats.video.streamStateChanged(g.stream)}async configureVideoModalitiesAsync(g,f,S){if(!this.mediaSession)return this.logger.warn("Tried to configure modalities after call end"),Promise.resolve();g&&this._delayedElevationPending&&!this._delayedElevationQueued&&await this.triggerDelayedReconnectIfNeeded(f,"configureVideoModalitiesAsync"),await this.updateMediaModalities(void 0,f,S),g||this.turnOffLocalVideoPreview(f),this.setVideoOn(g,f)}turnOffLocalVideoPreview(g){return this.localVideoRenderer&&(this.localVideoRenderer.dispose(),this.localVideoRenderer=null),this.disposeLocalVideoHandle(),Promise.resolve(void 0)}turnOnLocalVideoPreview(g){return this.mediaSession?.getSessionConfig().config.useDeviceHandleForLocalVideo?this.acquireLocalVideo(g):(this.localVideoContainer||(this.localVideoContainer=document.createElement("div")),this.turnOnLocalVideoPreviewUsingRenderer(g))}acquireLocalVideo(g){const f=this.logger.createFnLogger("_StartPreviewVideo",g);if(!this.mediaStateConfigurationHelper.isSending(1))return Promise.reject("could not start video preview, not configured to send");try{this.disposeLocalVideoHandle();const g=this.callDeviceManager.getDeviceManager(getAgentMediaType(1));return this.localVideoHandle=g.createDevicesHandle({video:!0},"pluginlessCall:acquireLocalVideo()"),this.localVideoHandle.on("onStreamStateChanged",(g=>this.onLocalPreviewStateChanged({stream:g}))),this.localVideoHandle.acquire()}catch(g){return f.logFailure(g),void this.disposeLocalVideoHandle()}}turnOnLocalVideoPreviewUsingRenderer(g){const f=this.logger.createFnLogger("_StartPreviewVideo",g),S=this.mediaStateConfigurationHelper.isSending(1);if(!S||!this.localVideoContainer)return Promise.reject(`could not start video preview: requestedVideoState=${S}, localVideoContainer=${this.localVideoContainer}`);this.turnOffLocalVideoPreview(g);const v=asap((()=>{this.localVideoRenderer=this.callDeviceManager.getDeviceManager(getAgentMediaType(1)).createPreviewRenderer(this.localVideoContainer,"Video"),this.localVideoRenderer.on("onVideoSizeChanged",((g,f)=>this.onLocalPreviewSizeChanged(g,f))),this.localVideoRenderer.on("onVideoStateChanged",(g=>this.onLocalPreviewStateChanged(g)))})).then((()=>this.localVideoRenderer.startVideoAsync(g)));return v.catch((g=>f.logFailure(g))),v}async startStopVideo(g,f,S){const v=this.logger.createFnLogger(g?"startVideo":"stopVideo",f);return v.info("start"),this.canToggleVideo?(g?(this.callStats.localStats.newSession(1),this.callStats.localStats.video.start()):this.callStats.localStats.video.stop(),g&&this.mediaStateConfigurationHelper.isDisabled(1)&&v.info("Video modality was skipped till now. Adding it now."),g?this.mediaStateConfigurationHelper.enableModality(1):this.mediaStateConfigurationHelper.removeModality(1),this.canToggleVideo=!1,this.videoTogglePromise=(async()=>{try{let v=!1;g&&(await this.turnOnLocalVideoPreview(f),v=!0),await this.configureVideoModalitiesAsync(v,f,S)}catch(g){throw v.logFailure(g),this.mediaStateConfigurationHelper.removeModality(1),await this.configureVideoModalitiesAsync(!1,f,S),g}finally{this.canToggleVideo=!0}})(),this.videoTogglePromise):g===this.mediaStateConfigurationHelper.isSending(1)?(await this.videoTogglePromise,void this.turnOnLocalVideoPreview(f)):(v.logFailure(`video switching is in progress ${g}]`),Promise.reject({reason:1}))}async startStopAudio(g,f){const S=this.logger.createFnLogger(g?"startAudio":"stopAudio",f);try{const g=await this.updateMediaModalities(void 0,f);this.updateMediaState(g,f)}catch(g){return S.logFailure(g),9}return 0}updateEndpointStateForMute(g,f){try{this.signalingSession.updateEndpointState({state:{isMuted:g}},f).catch((g=>{this.logger.logFailure(`updateEndpointStateForMute failure: ${g}`)}))}catch(g){this.logger.logFailure(`updateEndpointStateForMute failure: ${g}`)}}async handleServerMutedState(g){const f=this.logger.createFnLogger(`handleServerMutedState, isServerMuted=${!!this.isServerMuted}`,g);if(!this.isServerMuted){const S=3===this._muteState;if(1===this._muteState||S)try{f.info("is unmuting, as we are no longer server muted"),await this.handleMuteUnmuteOnMediaSession(!1,g),this.setMuted(0,g),this.unmutePendingPromise?.resolve(),S&&this.updateEndpointStateForMute(!1,g)}catch(g){throw f.logFailure(g),g}}if(this.isServerMuted&&0===this._muteState){f.info("is muting, as we are unmuted");try{await this.handleMuteUnmuteOnMediaSession(!0,g),this.setMuted(1,g)}catch(g){throw f.logFailure(g),g}}}async handleMuteUnmuteOnMediaSession(g,f){const S=this.logger.createFnLogger(`handleMuteUnmuteOnMediaSession, value=${!!g}`,f);if(this.mediaSession?.getAllowedModalities&&!this.isServerMuted){const v=this.isMuted||this.isServerMuted,C=this.mediaSession.getAllowedModalities().audio.some((g=>g===Hr.send||g===Hr.sendReceive));(v&&C||!v&&!C)&&(S.info(`updating audio modalities: Muted ${v} -> ${g}; audioAllowed = ${C}`),await this.updateMediaModalities(void 0,f))}return g?(S.info("mediaSession.muteInputAsync"),await(this.mediaSession?.muteInputAsync(f))):g||(S.info("mediaSession.unmuteInputAsync"),await(this.mediaSession?.unmuteInputAsync(f))),Promise.resolve()}canMuteOthers(){const g=this._enableUserMeetingRolesCheckForClientCapability&&this.meetingRoles?.some((g=>"attendee"===g))||"attendee"===(this.advancedMeetingRole||this.meetingRole),f=this._enableEndpointMeetingRoleCheckForClientCapability&&!!this.endpoints?.endpointDetails.find((g=>this._endpointId===g.endpointId))?.endpointMeetingRoles?.some((g=>"attendee"===g));return!g&&!f}updateCapabilities(g,f=!1){let S=!1,v=!1;callStateIsAnyOf(this.state,[11,12])||(this.isServerMuted&&!this._callInLobby?2&this._commandUrlPresence&&(S=!0):this.isMuted&&(S=!0),v=!!(1&this._commandUrlPresence)&&this.canMuteOthers()),this._capabilities.canUnmuteSelf===S&&this._capabilities.canMuteOthers===v||(this._capabilities.canUnmuteSelf=S,this._capabilities.canMuteOthers=v,this.logger.info(`[${g}][updateCapabilities] Computed self capabilities: ${JSON.stringify(this._capabilities)}`),f&&this.raiseChanged())}async evaluateEndpointStatesForAccept(g,f,S){const v=this.logger.createFnLogger(`evaluateEndpointStatesForAccept, isMuted=${!!g}`,S),C={};try{await this.handleMuteUnmuteOnMediaSession(g,S),Object.assign(C,{state:{isMuted:g}}),v.info("is updating endpointState for mute"),f&&(Object.assign(C,{endpointProperties:{additionalEndpointProperties:f}}),v.info("is updating endpointState for additionalEndpointProperties"))}catch(g){throw v.logFailure(g),getRejectTransactionEnd(g)}return C}async handleEndpointStatesForAccept(g,f){const S=this.logger.createFnLogger("handleEndpointStatesForAccept",f);try{await this.signalingSession.updateEndpointState(g,f)}catch(g){throw S.logFailure(g),getRejectTransactionEnd(g)}}async muteUnmute(g,f){const S=this.logger.createFnLogger(`muteUnmute, value=${!!g} isServerMuted=${this.isServerMuted} inLobby=${this._callInLobby}`,f);if(callStateIsAnyOf(this.state,[11,12]))return S.logFailure("Can not mute/unmute during preheat call"),Promise.reject(getRejectTransactionEnd("TransactionDisallowed"));const v=!g&&(!this.isServerMuted||this._callInLobby);try{if((g||v)&&await this.handleMuteUnmuteOnMediaSession(g,f),g)this.setMuted(2,f),S.info("is updating endpointState for mute"),this.updateEndpointStateForMute(!0,f);else{if(!v)return S.info("is unmuting on server"),2===this._muteState&&this.setMuted(3,f),this.isCallModeStreaming()?this.promoteToRealtimeAndUnmute(f):this.signalingSession.unmuteAsync(f).then((g=>{this.handleSelfUnmuteUpdatedInfo(g,f)}));S.info("is updating endpointState for unmute"),this.setMuted(0,f),this.updateEndpointStateForMute(!1,f)}}catch(g){throw S.logFailure(g),getRejectTransactionEnd(g)}}async muteUnmuteSpeaker(g,f){this.setSpeakerMuted(g,f),this.mediaSession&&(g?await this.mediaSession.muteOutputAsync(f):await this.mediaSession.unmuteOutputAsync(f))}getParticipant(g){return this.participants.filter((f=>f.isSameParticipantsMri(g)))[0]}getOrCreateParticipant(g,f,S){let v=this.getParticipant(g);return v||(v=new hs(g,this.mediaSession,this.logger,this.callStats.localStats,this.callTelemetry,f),v.changed((()=>this.onParticipantChanged(v))),this.participants.push(v),S&&this.event("participantAdded").raise(v),this.monitorCallStart(),v)}onParticipantChanged(g){this.event("participantUpdated").raise(g),this.raiseChangedDeferred(this._participantChangedEventSkipConfig)}setCallState(g,f,S=0){if(this.state===g)return;const v=this.logger.createFnLogger("setCallState",f);v.info(`currentState=${this.state}, newState=${g}, terminatedReason=${this.terminatedReason}`);(hr[this.state].indexOf(g)>=0||(v.logFailure("invalid state transition"),7===g))&&(this.callTelemetry.recordEvent("_SetCallState",{state:g,reason:S},f),this.state=g,this.callStats.localStats.call.callStateChanged(g),6===g&&this._startCallPhase&&(this.callTelemetry.updateOperationData("_ConnectCall",{phases:this._startCallPhase.getTelemetryData()},f),this._startCallPhase=void 0),7===g&&this.setTerminatedReason(S),3===g&&(this.callGotConnected=!0,this.callHeldAt=null),this.callIsHeld()&&!this.callHeldAt&&(this.callHeldAt=new Date),v.logSuccess(`changed to ${g}, terminatedReason: ${this.terminatedReason}, failureType=${this.failureType}`),this.screenSharingControl.callStateChanged(this.state),this.monitorCallStart(),this.event("callStateChanged").raise(),this.updateCapabilities(f),this.raiseChanged(),this.callTelemetry.recordEvent("_RaiseCallStateChangeEvent",{state:g,reason:S},f))}setTerminatedReason(g){if(this.terminatedReason=g,!(0,Ki.includes)(no,g)){const g=44===this.terminatedReason,f=55===this.terminatedReason,S=56===this.terminatedReason;this.setFailureType(!this.callGotConnected||!this._wasAudioStreamConnected||g||f||S?0:1)}}setMediaStream(g,f,S){if(g){if(!(0,Ki.find)(this.localMediaStreams,(g=>g.mediaType===S))){const g=new ao(f,S);this.logger.info(`setMediaStream ${JSON.stringify(g)}`),this.localMediaStreams.push(g)}}else this.logger.info(`setMediaStream removing ${S}`),(0,Ki.remove)(this.localMediaStreams,(g=>g.mediaType===S))}setVideoOn(g,f){this.logger.info(`[${f}]videoOn=${g}`),this.isVideoOn=g,this.setMediaStream(this.isVideoOn,!0,1),this.callTelemetry.recordEvent("_SetLocalVideo",{value:g},f),this.raiseChanged()}setAudioOn(g,f){this.logger.info(`[${f}]audioOn=${g}`),this.setMediaStream(g,!0,0),this.callTelemetry.recordEvent("_SetLocalAudio",{value:g},f)}setScreenSharingOn(g,f){this.logger.info(`[${f}]screenSharingOn=${g}`),this.isScreenSharingOn=g,this.setMediaStream(this.isScreenSharingOn,this.isScreenSharingOn,2),this.callTelemetry.recordEvent("_SetScreenSharing",{screenSharingOn:g},f),this.event("userActivityChanged").raise(),this.raiseChanged()}disposeSharingScreenHandle(){this.sharedScreenHandle&&(this.sharedScreenHandle.dispose(),this.sharedScreenHandle=null)}disposeLocalVideoHandle(){this.localVideoHandle?.dispose(),this.localVideoHandle=null}setMuted(g,f){this._muteState!==g&&(this._muteState=g,this.callTelemetry.recordEvent("_SetMuted",{isMuted:g},f),this.logger.info(`[${f}]participantMuteState:${g}, isMuted: ${this.isMuted}`),this.updateCapabilities(f),this.raiseChanged(),this.event("muteStateChanged").raise(this.isMuted,f))}setSpeakerMuted(g,f){this.logger.info(`[${f}]speakerMute=${g}]`),this.isSpeakerMuted=g,this.raiseChanged()}monitorCallStart(){3!==this.state||!this.participants.length&&2!==this.callMode||this.callStartedAt||(this.callStartedAt=new Date)}_removeParticipant(g,f,S=0){const v=this.logger.createFnLogger("removeParticipant",f);v.info(`mri=${scrubSignalingParticipant(g)}`);const C=(0,Ki.remove)(this.participants,(f=>f.isSameParticipantsMri(g.id)))[0];C?(C.setState(4,S,f),this.event("participantRemoved").raise(C)):v.logFailure(`unable to remove participant ${scrubMriOrOmit(g.id)}`),this.raiseChanged(this._participantChangedEventSkipConfig)}setIsSomeoneSharing(g,f){const S=this.isSomeoneSharing!==g&&!(g&&this.screenSharingRenegotiationDeferred&&this.callUsesMixer);S&&(this.isSomeoneSharing=g);let v=S;if(this.callUsesMixer&&this.mediaSession?.getSessionConfig().config.enableStopSharingWithIncomingOffer&&(v||(v=f)),!this.isMultiVBSSEnabled()&&v&&this.isSomeoneSharing&&this.isScreenSharingOn&&(this.stopScreenSharing(),this.logger.info("sharingStolen: Cleaning up local screenshare because remote screenshare is running"),this.event("sharingStolen").raise()),this.allowScreenSharingControl()&&this.screenSharingControl?.isInternalViewerControlEnabled()){const g=this.localSignalingParticipant.endpointDetails.find((g=>this._endpointId===g.endpointId)),f=this.participants.find((g=>g.streams[1].some((g=>g.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,f,g)}}handleOfferedModalities(g,f){const S=this.mediaAgent.constants.MEDIA_STATE,v=this.logger.createFnLogger("handleOfferedModalities",f);try{v.info(`offeredModalities=${safeJsonStringify(g)}`)}catch(g){v.logFailure(g)}g.hasOwnProperty("video")||this.mediaStateConfigurationHelper.isSending(1)?g.hasOwnProperty("video")&&!this.mediaStateConfigurationHelper.isSending(1)&&this.mediaStateConfigurationHelper.removeModality(1):this.mediaStateConfigurationHelper.disableModality(1),g.hasOwnProperty("sharing")||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.disableModality(2),g.sharing!==S.receive||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.removeModality(2),g.data===S.sendReceive&&this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this.isReivitelessEnabled()||(this.setIsSomeoneSharing(g.sharing===S.receive,!0),this.setIsSomeoneStreamingVideo(g.video===S.receive||g.video===S.sendReceive))}getRenegotiationOfferType(g){if(g)if(5===this.state){if("sendrecv"===g.audio)return 2}else if(this.modalitiesAreHold(g))return 1;return 0}isRenegotiationHoldOrResume(g){return 1===this.getRenegotiationOfferType(g)||2===this.getRenegotiationOfferType(g)}isReivitelessEnabled(){return(this.signalingSession.getMaxReinvitelessMediaForVideoForWeb()>0||this.signalingSession.getMaxReinvitelessMediaForVBSSForWeb()>0)&&this.callUsesMixer}isValidHoldResumeCallState(g){return[3,5,10,13].includes(g)}onNegotiationCompletion(g,f,S={},v,C){const _=this.logger.createFnLogger("onNegotiationCompletion",v);_.info(`byLocal=${f}, result=${safeJsonStringify(g)}`),this.callTelemetry.recordEvent("NegotiationCompletion",{phaseTelemetryBag:C,...this.prepareNegotiationResultForTelemtry(g)},v);const T=this.isOneToOneCall();if(T&&!this.callUsesMixer){const f=this.modalitiesAreHold(g.activeModalities)?5:3;this.participants[0].setState(f,void 0,v),_.info(`isOneToOneCall: participant[0] state set to ${f}`)}const I=this.modalitiesAreHold(g.configuredModalities),b=this.modalitiesAreHold(g.activeModalities);let A;const P=this.signalingSession.participantManager.localParticipant.isStaging;_.info(`isStaging= ${P}`),this.requestedHoldState?(I&&b||_.info(`Not expected modalities when processing local hold: ${I} ${b}`),4!==this.state&&_.info(`Not expected state when processing local hold: ${this.state}, switching back to LocalHold`)):f||this.callHoldResumeDeferred?!I&&b?A=5:I||b||this._callInLobby||this.isPreheatedOnly()||(A=P?13:3):4===this.state||this._callInLobby||this.isPreheatedOnly()||(A=T&&5===this.participants[0].state?5:P?13:3),A&&this.setCallState(A,v),this.callHoldResumeDeferred&&(_.info(`isHoldInProgress=${this.isHoldInProgress}, state=${this.state}, completed=${b}`),this.isHoldInProgress?b&&this.finishCallHoldResume():this.inLocalHold()||this.finishCallHoldResume(this.isValidHoldResumeCallState(A)?void 0:new Error(`Call state changed to ${A} instead of Connected, Lobby, Staging or RemoteHold`))),this.requestedHoldState||(this.setIsSomeoneSharing((0,Ki.some)(this.participants,(g=>(0,Ki.some)(g.streams[1],(g=>g.isAvailable))))),this.setIsSomeoneStreamingVideo((0,Ki.some)(this.participants,(g=>(0,Ki.some)(g.streams[0],(g=>g.isAvailable))))));const R=S&&S.sharing===this.mediaAgent.constants.MEDIA_STATE.send,M=g?.activeModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(this.resolveScreenSharingRenegotiation(v,R,M,g.isComplete),this.retryOutgoingRenegotiation.retry){const g=this.retryOutgoingRenegotiation.causeId;this._callOperationHandler.executeChained((()=>this.updateMediaModalities(void 0,g)),"_Renegotiate",g,g,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.retryOutgoingRenegotiation.retry=!1}}onUpdateMediaDescriptionsFailure(g,f,S){const v=f?.requestedModalities.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.screenSharingRenegotiationDeferred&&v&&(this.screenSharingRenegotiationDeferred.reject(g),this.screenSharingRenegotiationDeferred=null)}onUpdateMediaDescriptionsCompletion(g,f){this.logger.createFnLogger("onUpdateMediaDescriptionsCompletion",f).info(`result=${safeJsonStringify(g)}`),this.callTelemetry.recordEvent("UpdateMediaDescriptionsCompletion",g,f);const S=g?.requestedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send,v=g?.appliedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.resolveScreenSharingRenegotiation(f,S,v,!0)}resolveScreenSharingRenegotiation(g,f,S,v){const C=this.logger.createFnLogger("resolveScreenShareRenegotiation",g);if(C.info(`invoked with wasSharingOfferred: ${f}, isSharingActive: ${S}, isComplete: ${v}`),this.screenSharingRenegotiationDeferred)if(f&&S)C.info("resolving screenSharingRenegotiationDeferred"),this.screenSharingRenegotiationDeferred.resolve(),this.screenSharingRenegotiationDeferred=null;else if(this._enableResolveScreenSharingWhenNegotiationComplete&&v&&!this.retryOutgoingRenegotiation.retry&&this.canToggleScreenSharing){const g=new Error(`screenSharing error: wasSharingOfferred: ${f}, isSharingActive: ${S}`);C.info(`reject screenSharingRenegotiationDeferred ${g}`),this.screenSharingRenegotiationDeferred.reject(g),this.screenSharingRenegotiationDeferred=null}}async updateMediaStatus(g){if(this.calculateIsSomeoneStreaming(g),this.mediaSession){const f=await this.updateMediaModalities(void 0,g);this.callTelemetry.updateOperationData("_UpdateLocalMediaStatus",f,g)}}calculateIsSomeoneStreaming(g){let f=!1,S=!1;for(const g of this.participants)if(f||(f=(0,Ki.some)(g.streams[1],(g=>g.isAvailable))),S||(S=(0,Ki.some)(g.streams[0],(g=>g.isAvailable))),f&&S)break;this._delayedElevationPending&&(f||S)&&this.triggerDelayedReconnectIfNeeded(g,"roster update"),this.setIsSomeoneSharing(f),this.setIsSomeoneStreamingVideo(S)}async triggerDelayedReconnectIfNeeded(g,f=""){const onReconnectCompleted=()=>{this._delayedElevationPending=!1,this._delayedElevationQueued=!1,this.mediaSession?.getDiagnostics()?.registerElevation("completed")};this.logger.info(`Delayed elevation (${f}): pending=${this._delayedElevationPending} queued=${this._delayedElevationQueued}`),this._delayedElevationPending&&!this._delayedElevationQueued?(this._delayedElevationQueued=!0,this._callOperationHandler.maybeRejectOperations(["_RenegotiateIncoming","_RenegotiateOutgoing","_Renegotiate"]),this.mediaSession?.getDiagnostics()?.registerElevation("attempted"),await this.mediaSession.reconnectAsync(g,!0,onReconnectCompleted)):this.logger.info(`Delayed elevation: was not queued, pending=${this._delayedElevationPending} isQueued=${this._delayedElevationQueued}`)}onNegotiationFailure(g,f,S,v){const C=v&&v.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(f===this.mediaAgent.constants.RENEGOTIATION_ERROR.glare)return this.screenSharingRenegotiationDeferred&&C&&this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),void(this.retryOutgoingRenegotiation={retry:!0,causeId:S});this.finishCallHoldResume(g),this.screenSharingRenegotiationDeferred&&C&&(this.screenSharingRenegotiationDeferred.reject(g),this.screenSharingRenegotiationDeferred=null)}static getParticipantReasonFromTerminatedReason(g){switch(g){case 1:return 0;case 9:return 2;case 10:return 3;case 2:return 4;case 24:return 8;case 3:return 9;case 4:return 10;case 14:return 12;case 0:default:return 11;case 15:return 13;case 16:return 14;case 17:return 15;case 18:return 16;case 19:return 17;case 20:return 18;case 11:return 19;case 21:return 20;case 22:return 21;case 23:return 22;case 33:return 25;case 36:return 26;case 37:return 27;case 41:return 30;case 39:return 28;case 42:return 31;case 40:return 29;case 43:return 32;case 44:return 33;case 45:return 34;case 46:return 35;case 47:return 36;case 48:return 37;case 49:return 38;case 50:return 39;case 51:return 40;case 52:return 41;case 54:return 42;case 55:return 44;case 56:return 45;case 12:return 23;case 59:return 46;case 73:return 59;case 61:return 47;case 60:return 48;case 62:return 49;case 63:return 50;case 64:return 5;case 65:return 51;case 8:return 52}}isRemoteParticipantInStaging(g){if(!g.endpointDetails)return!1;for(const f of g.endpointDetails)if(!hasStagingGroup(f))return!1;return!0}updateCallParticipantFromSignalingParticipant(g,f,S){if((0,Ki.every)(f.endpointDetails,(g=>g?.isLobby||g?.streamLobby)))return void g.setState(7,void 0,S);const v=(0,Ki.some)(f.endpointDetails,(g=>g?.streamInformation)),C=f.endpointDetails&&(0,Ki.some)(f.endpointDetails,(g=>g.mappedTo)),_=_PluginlessCall.filterVirtualEndpoints(f.endpointDetails),T=_&&_[0].mediaStreams,I=this.isRemoteParticipantInStaging(f);if(T&&T.length>0){const f=T.every((g=>"inactive"===g.direction));let v=f?5:I?8:3;1!==this.state||f||this.callUsesMixer||(v=2),this.logger.info(`[updateCallParticipantFromSignalingParticipant]: with mediaStreams is not empty, ParticipantState is set to ${v}`),g.setState(v,void 0,S)}else if(T||C||v){const f=I?8:3;this.logger.info(`[updateCallParticipantFromSignalingParticipant]: ParticipantState is set to ${f}, mediaStreams=${!!T}, hasMappedEndpoints=${C}, hasPlayerStreams=${v}`),g.setState(f,void 0,S)}}handleSelfServerMutedState(g){const f=_PluginlessCall.filterVirtualEndpoints(this.localSignalingParticipant.endpointDetails),S=(0,Ki.find)(f,(g=>this._endpointId===g.endpointId)),v=S&&S.mediaStreams,C=v&&v.filter((g=>"audio"===g.type||"audio-teleconferencing"===g.type)),_=S&&(S.stream||S.streamLobby);if(_){const f=_.serverMuted??!1;S.serverMuteVersion=0,f!==this.isServerMuted&&(this.isServerMuted=f,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${f}`),this.event("serverMutedChanged").raise(f,g),this.updateCapabilities(g,!0),this.isServerMuted&&this.setMuted(1,g))}else if(C&&C.length>0){const f=C.some((g=>g.serverMuted));f!==this.isServerMuted&&(this.isServerMuted=f,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${f}`),this.event("serverMutedChanged").raise(f,g),this.updateCapabilities(g,!0),this.handleServerMutedState(g))}}checkIfIncomingServerMutedIsUpdated(g){const f=(0,Ki.find)(this.localSignalingParticipant.endpointDetails,(g=>g.participantId===this.localSignalingParticipant.participantId));if(void 0===f)return;const S=(0,Ki.find)(g.endpointDetails,(g=>g.participantId===this.localSignalingParticipant.participantId));handleServerMutedVersion(this.logger,f,S)}convertWiredPublishedState(g){if(!g)return;const f=getPluginlessStateTypeFromWire(g.stateType);return{content:g.content,stateType:f,typeRank:g.typeRank,stateId:g.stateId}}updatePublishedStateModified(g,f){g!==this.currentUserSkypeIdentity.id||f&&f!==this.participantId?this._publishedStatesModified=2|this._publishedStatesModified:this._publishedStatesModified=1|this._publishedStatesModified}updatePublishedStates(g){try{let f=[];(0,Ki.forEach)(g.publishedStates,(g=>{f.push(this.convertWiredPublishedState(g))})),(0,Ki.isEqual)(this._participantPublishedStatesMap[g.id],f)||(0!==f.length||void 0!==this._participantPublishedStatesMap[g.id]&&null!==this._participantPublishedStatesMap[g.id])&&(this._participantPublishedStatesMap[g.id]=f,this.updatePublishedStateModified(g.id));const S=[];(0,Ki.forEach)(g.endpointDetails,(v=>{S.push(v.participantId),f=[],(0,Ki.forEach)(v.publishedStates,(S=>{const C=this.convertWiredPublishedState(S);if(this._endpointPublishedStatesMap[g.id]||(this._endpointPublishedStatesMap[g.id]={},this._endpointPublishedStatesMap[g.id][v.participantId]=[]),"clientMediaUfd"===C.stateType)try{const g=JSON.parse(JSON.stringify(C.content));this.mediaSession.registerRemoteQualityStateChangedEvent(g,v.participantId)}catch(g){this.logger.error(`Error while parsing state.content for ClientMediaUFD: ${g}`)}f.push(C)})),this._endpointPublishedStatesMap[g.id]&&!(0,Ki.isEqual)(this._endpointPublishedStatesMap[g.id][v.participantId],f)&&(0!==f.length||null!==this._endpointPublishedStatesMap[g.id][v.participantId]&&void 0!==this._endpointPublishedStatesMap[g.id][v.participantId])&&(this._endpointPublishedStatesMap[g.id][v.participantId]=f,this.updatePublishedStateModified(g.id,v.participantId))})),this._endpointPublishedStatesMap[g.id]&&Object.keys(this._endpointPublishedStatesMap[g.id]).forEach((f=>{S.some((g=>g===f))||(delete this._endpointPublishedStatesMap[g.id][f],this.updatePublishedStateModified(g.id,f))}))}catch(g){this.logger.error(`updatePublishedStates ${JSON.stringify(g)}`)}this.logger.info(`updatePublishedStates ${getLoggableMriKeys(this._participantPublishedStatesMap)}`),this.logger.info(`updatePublishedStates ${getLoggableMriKeys(this._endpointPublishedStatesMap)}`)}removePublishedStatesByParticipant(g){this._endpointPublishedStatesMap[g]&&delete this._endpointPublishedStatesMap[g],this._participantPublishedStatesMap[g]&&delete this._participantPublishedStatesMap[g],this.updatePublishedStateModified(g)}findOrCreateTypeState(g){let f=this._publishedStates.typeStates.findIndex((f=>f.type===g));if(-1===f){const S={participantStates:[],type:g};this._publishedStates.typeStates.push(S),f=this._publishedStates.typeStates.length-1}return f}processPublishedStates(){this.logger.info(`processPublishedStates ${getLoggableMriKeys(this._participantPublishedStatesMap)}`),this.logger.info(`processPublishedStates ${getLoggableMriKeys(this._endpointPublishedStatesMap)}`);try{this._publishedStates||(this._publishedStates={typeStates:[]}),this._publishedStates.typeStates=[];for(const g of Object.keys(this._participantPublishedStatesMap)){const f=this._participantPublishedStatesMap[g];(0,Ki.forEach)(f,(f=>{const S=this.findOrCreateTypeState(f.stateType),v={id:g,publishedState:{content:f.content,stateId:f.stateId,typeRank:f.typeRank}};this._publishedStates.typeStates[S].participantStates.push(v)}))}for(const g of Object.keys(this._endpointPublishedStatesMap))for(const f of Object.keys(this._endpointPublishedStatesMap[g])){this._endpointPublishedStatesMap[g][f].forEach((S=>{const v=this.findOrCreateTypeState(S.stateType),C={id:f,publishedState:{content:S.content,stateId:S.stateId,typeRank:S.typeRank}},_={id:g,endpoints:[C]},T=this._publishedStates.typeStates[v].participantStates.filter((f=>f.id===g));T&&T.length>0?(T[0].endpoints||(T[0].endpoints=[]),T[0].endpoints.push(C)):this._publishedStates.typeStates[v].participantStates.push(_)}))}this.event("publishedStatesChanged").raise(this._publishedStates),this.raiseChanged()}catch(g){this.logger.error(`processPublishedStates ${g}}`)}}updateLocalParticipant(g,f){const S=this.logger.createFnLogger("updateLocalParticipant",f);this.checkIfIncomingServerMutedIsUpdated(g),this.localSignalingParticipant.endpointDetails=g.endpointDetails,this.localSignalingParticipant.role=g.role,this.setMeetingRole(g.meetingRole),this.setAdvancedMeetingRole(g.advancedMeetingRole),this.setMeetingRoles(g.meetingRoles),this.setParticipantType(g.participantType),this.setDisplayName(g.displayName),this.setPropertyBag(g.propertyBag),this.setPropertyRosterVersion(g.version),this.setMaskedIdentityDetails(g.isIdentityMasked,g.maskedIdSeqNumber,g.maskedId),this.setOtpIdentity(g.otpIdentity),this.localSignalingParticipant.tenantId=g.tenantId,this.localSignalingParticipant.isLobby=g.isLobby,g.joinAsStreamingUser&&(this.localSignalingParticipant.joinAsStreamingUser=g.joinAsStreamingUser,this.setJoinAsStreamingUser(g.joinAsStreamingUser)),void 0!==g.enableCaptcha&&this.setEnableCaptcha(g.enableCaptcha),this.callTelemetry.setTenantId(g.tenantId),this.callStats.setTenantId(g.tenantId);const v=this.localSignalingParticipant.isLobby;g.endpointDetails&&this.updateLocalParticipantEndpoints(g.endpointDetails),this.updatePublishedStates(g),this.handleSelfServerMutedState(f);const C=this.getLocalSignalingEndpointDetails();this._callInLobby=v||!!C?.streamLobby,this.signalingSession.participantManager.localParticipant.isStaging=g.isStaging;const _=this.signalingSession.participantManager.localParticipant.isStaging;S.info(`callInLobby = ${v}, callSetupComplete = ${this._callIsSetupComplete}, callIsHeld = ${this.callIsHeld()}, isStaging = ${_}`),!this._callIsSetupComplete||this.callIsHeld()||callStateIsAnyOf(this.state,[11,12])||(v?this.setCallState(10,f):_&&callStateIsAnyOf(this.state,[3,13,10,9,2])?this.setCallState(13,f):this.setCallState(3,f));const T=_PluginlessCall.getStreamsFromEndpoints(g.endpointDetails,this.isMultiVBSSEnabled());if(this.callTelemetry.recordEvent("_UpdateLocalParticipantStream",getStreamInformation(T),f),this.streamManager.updateStreams(T,f),this.updateCapabilities(f,!0),this.allowScreenSharingControl()&&this.screenSharingControl?.isInternalViewerControlEnabled()){const f=g.endpointDetails.find((g=>this._endpointId===g.endpointId)),S=this.participants.find((g=>g.streams[1].some((g=>g.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,S,f)}}modalitiesAreHold(g){return!(g.audio&&"inactive"!==g.audio||g.video&&"inactive"!==g.video||g.sharing&&"inactive"!==g.sharing)}toneToString(g){switch(g){case 0:return"0";case 1:return"1";case 2:return"2";case 3:return"3";case 4:return"4";case 5:return"5";case 6:return"6";case 7:return"7";case 8:return"8";case 9:return"9";case 10:return"*";case 11:return"#";default:return null}}static streamingStatetoMediaStreamState(g){switch(g){case"started":return 0;case"active":return 2;case"inactive":return 1;case"stopped":return 3;default:return 4}}static streamingDirectionToMediaDirectionMapping(g){switch(g){case"send":return 1;case"receive":return 0;default:return}}static convertMuteScope(g){switch(g){case 0:return"EveryoneElse";case 1:return"SpecifiedParticipants";default:return}}callIsHeld(){return 4===this.state||5===this.state}inLocalHold(){return this.isHoldInProgress||4===this.state}telemetryDataFromCallStartOptions(g){const f={};return g.muteFlags&&(f.muteMicrophone=!!(1&g.muteFlags),f.muteSpeaker=!!(2&g.muteFlags)),Object.keys(f).length?f:void 0}reconnect(){const g=generateCauseId();return this.mediaSession.reconnectAsync(g)}async provideCallQualityFeedback(g,f,S,v){}async showCQFInfo(g,f){throw new Error("Not implemented")}async isCqfRendered(g){}async provideCallQualityFeedbackEx(g,f,S,v,C,_){}testTriggerMediaRelayWhiteListingIssue(){this.logger.info("Simulating media relay whitelisting issue for test purposes");const g=this.mediaSession.mediaSession.callback,f={type:"NetworkRelaysNotReachable",value:"Bad",isLocalSource:!0,mediaType:"Audio"};g.onQualityChanged(f);const S={direction:"send",stream:"failed",content:"audio"};g.onAudioStateChanged(S)}async getMediaTelemetry(g=!1){return this.mediaSession&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(g)),this.appendInfoToCallStats()),this.callStats.buildMediaTelemetry()}getMediaSessionStats(){return this.mediaSession?.getMediaStatsReport()}async getMediaSessionStatsAsync(){return this.mediaSession?.getMediaStatsReport()}getDiagnosticsForE2E(){return this.mediaSession?.getDiagnostics().e2eDiagnostics}appendInfoToCallStats(){this.callStats.appendDataChannelInfo(this.dataChannel.getTelemetry()),this.callStats.appendSharingControlInfo(this.screenSharingControl?.isScreenSharingControlEnabled()),this.callStats.appendMediaControlPlaneInfo(JSON.stringify(this.mediaSession?.getMediaControlPlaneInstance()?.getTelemetryReport()))}getMediaLogs(){return this.mediaAgent.getMediaLogs()}testSetCallState(g){this.logger.info(`Overwriting call state for test purposes: ${this.state} -> ${g} `),this.state=g}testSetCallType(g){this.logger.info(`Overwriting call state for test purposes: ${this.callType} -> ${g} `),this.callType=g}addGroupModality(g,f=generateCauseId()){const S=this.logger.createFnLogger("AddGroupModality",f);if(!g.threadId&&!g.groupId)return Promise.reject(getRejectTransactionEnd("No threadId/groupId was provided."));if(6===this.state||7===this.state)return S.info(`Not adding modality because CallState is ${this.state} groupId=${scrubMriOrOmit(g.groupId)}, threadId = ${getLoggableThreadId(g.threadId)} messageId = ${g.messageId}`),Promise.reject(getRejectTransactionEnd("TransactionDisallowed"));let v;if(g.additionalData)try{v=JSON.stringify(g.additionalData)}catch(f){S.logFailure(`additionalData: ${g.additionalData} is not valid Json, error: ${f}`);const v={code:Fi.BadRequest,subCode:0,phrase:`additionalData is not valid Json, error: ${f}`};return Promise.reject(v)}if(S.info(`groupId=${scrubMriOrOmit(g.groupId)}, threadId = ${getLoggableThreadId(g.threadId)} messageId = ${g.messageId} additionalData = ${scrubMriOrOmit(v)}`),this._enableAddModalityGeneric){const v={groupContext:{id:g.groupId},groupChat:{threadId:g.threadId,messageId:g.messageId}};return this.signalingSession.addModalityAsync(v,f).catch((g=>(S.logFailure(getPrintableObject(g)),Promise.reject(g))))}{const C={groupId:g.groupId,threadId:g.threadId,messageId:g.messageId,additionalData:v};return this.signalingSession.addGroupModalityAsync(C,f).catch((g=>(S.logFailure(getPrintableObject(g)),Promise.reject(g))))}}addBroadcastModality(g,f){const S=this.logger.createFnLogger("AddBroadcastModality",f);return Promise.resolve().then((()=>{this.signalingSession.addBroadcastModalityAsync(g,f)})).catch((g=>(S.logFailure(getPrintableObject(g)),Promise.reject(getRejectTransactionEnd(g))))).then((()=>this._callOperationHandler.waitForOperation("AddBroadcastModality"))).catch((g=>{throw this.callTelemetry.updateOperationData("AddBroadcastModality",{error:getPIISafeObject(g)},f),S.logFailure(g),g}))}static convertQualityEventType(g){switch(g){case"NetworkSendQuality":return 1;case"NetworkRecvQuality":return 2;case"NetworkDelay":return 3;case"NetworkBandwidthLow":return 4;case"NetworkReconnect":return 5;case"NetworkPacketLoss":return 6;case"NetworkJitter":return 7;case"NetworkRateMatching":return 8;case"DeviceCaptureNotFunctioning":return 9;case"DeviceRenderNotFunctioning":return 10;case"DeviceRenderGlitches":return 11;case"DeviceLowSNR":return 12;case"DeviceLowSpeechLevel":return 13;case"DeviceClipping":return 14;case"DeviceEcho":return 15;case"DeviceNearEndToEchoRatio":return 16;case"DeviceHalfDuplexAec":return 17;case"DeviceMultipleEndpoints":return 18;case"DeviceHowling":return 19;case"DeviceRenderZeroVolume":return 20;case"DeviceRenderMute":return 21;case"NetworkSendCatastrophic":return 22;case"NetworkRecvCatastrophic":return 23;case"CpuInsufficient":return 24;case"DeviceCaptureMute":return 25;case"DeviceCaptureNotMuteButSilent":return 26;case"DeviceSpeakWhileMuted":return 27;case"VideoVbssRendered":return 28;case"NetworkEthernetInterfaceUsed":return 29;case"NetworkWlanInterfaceUsed":return 30;case"NetworkWwanInterfaceUsed":return 31;case"NetworkRelaysNotReachable":return 32;case"VideoCapturerDeviceStartFailed":return 33;case"VideoCapturerDeviceStartTimedOut":return 34;case"VideoCapturerDeviceStartFailureLackSystemRes":return 35;case"VideoCapturerDeviceStartFailureMFResConflict":return 36;case"NoNetwork":return 37;case"NetworkNotWorking":return 38;case"DeviceCaptureNotFunctioningDeviceInUse":return 39;case"DeviceRenderNotFunctioningDeviceInUse":return 40;case"VideoCaptureDeviceFreeze":return 45;case"ZeroCaptureDevicesEnumerated":return 43;case"ZeroRenderDevicesEnumerated":return 44;case"VideoCapturePermissionDenied":return 47;case"ScreenshareRecordingDisabled":return 55;case"AudioCapturePermissionDenied":return 46;case"VideoCaptureFreezeRecovered":return 48;case"DeviceRenderHowling":return 49;case"PresentationAudioLoopbackDeviceState":return 53;case"RemoteNetworkConnectivityIssue":return 52;case"AudioCaptureUltrasoundDetected":return 54;case"MusicModeNotAvailable":return 57;case"CameraLighting":return 61;case"AudioLoopbackDeviceReady":return 63;case"NoRequiredVideoCodecs":return 64;case"SpatialAudioMUCHUnavailable":return 65;case"AudioMixMUCHUnavailable":return 80;default:return}}static convertQualityLevel(g){switch(g){case"Unknown":return 0;case"Good":return 1;case"Poor":return 2;case"Bad":return 3;default:return}}static convertMediaType(g){switch(g){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2;case"Data":return 3;default:return}}getPluginlessPublishLevel(g){switch(g){case"user":return"user";case"endpoint":return"endpoint";default:throw"Invalid level type."}}setIsEmergency(g){this.logger.info(`Set isEmergency:${g}`),this.isEmergency=g,this.callTelemetry.setIsEmergency(g)}static filterVirtualEndpoints(g){return g&&(0,Ki.filter)(g,(g=>!g.mappedTo))}mapDataChannelSourceIdToParticipant(g){let f=null;return f=1===this.callType?this.participants[0]:(0,Ki.find)(this.participants,(f=>f.hasSourceId(3,g))),f?.id?this.logger.info(`ParticipantId: ${scrubMriOrOmit(f.id)} to SourceId: ${g}`):this.logger.warn(`No Participant found for SourceId: ${g}`),f}getDataChannelSourceId(){const g=(0,Ki.find)(this.endpoints.endpointDetails,(g=>null!==g&&g.participantId===this._participantId));if(!g)return this.logger.warn(`No participantLeg found for participantId: ${this._participantId}`),-1;if(!g.mediaStreams)return this.logger.warn(`ParticipantLeg ${this._participantId} does not have valid mediaStreams`),-1;const f=(0,Ki.find)(g.mediaStreams,(g=>3===mapMediaTypeStringToMediaType(g.type)));return f?f.sourceId:(this.logger.warn(`participantLeg ${this._participantId} has no data channel`),-1)}initializeLiveStreamConfigProvider(){const g="MDN_MIDDLELANE_TEAMS",f="liveStream",S=this.ecsProvider.getEcsConfig(g,f),v=this.ecsProvider.getEcsConfig("ConfigIDs",g);this._liveStreamConfigProvider=new rt(S,null,v,this.logger.createChild("LiveStreamConfigProvider"))}isMediaSending(g){return this.mediaStateConfigurationHelper.isSending(g)}async setAudioStreamConnectedAsync(g){this.isAudioStreamConnected=g}async setSpamRiskLevelAsync(g){this.spamRiskLevel=g}async setSpamStirAttestationAsync(g){this.spamStirAttestation=g}async setDominantSpeakerInfoAsync(g){this.dominantSpeakerInfo=g}async setSlowedDownActiveTalkerInfoAsync(g){this.slowedDownActiveTalkerInfo=g}};oo.instanceCount=0,oo.getNegotiationTagsFromEndpoints=g=>{if(!g)return;const f=new Map;return oo.filterVirtualEndpoints(g).forEach((g=>{f.set(g.endpointId,g.negotiationTag)})),f},__decorateClass([callOperation("Initialize",{type:"Sync",convertError:!0,idempotencyLevel:"NoOp"})],oo.prototype,"init",1),__decorateClass([callOperation("StartVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"startVideo",1),__decorateClass([callOperation("StopVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"stopVideo",1),__decorateClass([callOperation("DumpVideoSourceImages")],oo.prototype,"dumpVideoSourceImages",1),__decorateClass([__decorateParam(1,causeId)],oo.prototype,"hold",1),__decorateClass([callOperation("Hold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"holdWithRenegotiate",1),__decorateClass([callOperation("LocalHold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"localHold",1),__decorateClass([callOperation("Unhold",{waitFor:["Hold","LocalHold"],preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"unhold",1),__decorateClass([callOperation("UpdateEndpointMetadata"),__decorateParam(1,causeId)],oo.prototype,"updateEndpointMetadata",1),__decorateClass([callOperation("SendDtmfTone",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],oo.prototype,"sendDtmfTone",1),__decorateClass([callOperation("SetAudioUsage")],oo.prototype,"setAudioUsageMode",1),__decorateClass([callOperation("SetAudioMidcallConfig")],oo.prototype,"setAudioMidcallConfig",1),__decorateClass([callOperation("SetAudioMidcallConfigJon",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"setAudioMidcallConfigJson",1),__decorateClass([callOperation("SetParticipantSpatialAudioPositions",{waitFor:"_ElectronSlimcoreReady",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"setParticipantSpatialAudioPositions",1),__decorateClass([callOperation("BlindTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"callBlindTransfer",1),__decorateClass([callOperation("SafeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"callSafeTransfer",1),__decorateClass([callOperation("TransferToVoicemail",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"transferCallToVoicemail",1),__decorateClass([callOperation("ConsultativeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"callConsultativeTransfer",1),__decorateClass([callOperation("ConsultativeTransferWithPickupCode",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],oo.prototype,"consultativeTransferWithPickupCode",1),__decorateClass([callOperation("CallRedirect",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"callRedirect",1),__decorateClass([callOperation("ParkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"park",1),__decorateClass([callOperation("UnparkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"unpark",1),__decorateClass([callOperation("getTechnicalInformationJson",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],oo.prototype,"getTechnicalInformationJson",1),__decorateClass([callOperation("StartScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(3,causeId)],oo.prototype,"startScreenSharing",1),__decorateClass([callOperation("StopScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(2,causeId)],oo.prototype,"stopScreenSharing",1),__decorateClass([callOperation("StartDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"startDataChannel",1),__decorateClass([callOperation("StopDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"stopDataChannel",1),__decorateClass([callOperation("ShareSystemSounds",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"shareSystemSound",1),__decorateClass([callOperation("Mute",{waitFor:"JoinPreheatedCall",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]},!0),__decorateParam(0,causeId)],oo.prototype,"mute",1),__decorateClass([callOperation("Unmute",{waitFor:["JoinPreheatedCall"]},!0),__decorateParam(0,causeId)],oo.prototype,"unmute",1),__decorateClass([callOperation("MuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"muteSpeaker",1),__decorateClass([callOperation("UnmuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"unmuteSpeaker",1),__decorateClass([callOperation("GetSpeakerVolume",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"getSpeakerVolume",1),__decorateClass([callOperation("SetSpeakerVolume",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"setSpeakerVolume",1),__decorateClass([callOperation("MuteParticipants",void 0,!0),__decorateParam(2,causeId)],oo.prototype,"muteParticipants",1),__decorateClass([callOperation("StartAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"startAudio",1),__decorateClass([callOperation("StopAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"stopAudio",1),__decorateClass([callOperation("Assimilate"),__decorateParam(3,causeId)],oo.prototype,"assimilate",1),__decorateClass([__decorateParam(2,causeId)],oo.prototype,"merge",1),__decorateClass([callOperation("MergeParticipants"),__decorateParam(1,operationId),__decorateParam(3,causeId)],oo.prototype,"mergeParticipants",1),__decorateClass([callOperation("MergeWithPickupCode"),__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"mergeWithPickupCode",1),__decorateClass([callOperation("SetMaxVideoChannels")],oo.prototype,"setMaxVideoChannels",1),__decorateClass([callOperation("SetMaxVbssChannels")],oo.prototype,"setMaxVbssChannels",1),__decorateClass([callOperation("StopCall"),__decorateParam(1,causeId),__decorateParam(3,reason)],oo.prototype,"stop",1),__decorateClass([callOperation("PublishState"),__decorateParam(1,operationId)],oo.prototype,"publishState",1),__decorateClass([callOperation("PublishState"),__decorateParam(1,operationId)],oo.prototype,"publishStatesForEveryone",1),__decorateClass([callOperation("RemoveState"),__decorateParam(1,operationId)],oo.prototype,"removeState",1),__decorateClass([callOperation("RemoveState"),__decorateParam(1,operationId)],oo.prototype,"removeStatesForEveryone",1),__decorateClass([callOperation("UpdateMeetingSettings"),__decorateParam(1,operationId)],oo.prototype,"updateMeetingSettings",1),__decorateClass([callOperation("UpdateMeetingGroups"),__decorateParam(0,operationId)],oo.prototype,"updateMeetingGroups",1),__decorateClass([callOperation("UpdateMeetingLiveState"),__decorateParam(0,operationId)],oo.prototype,"updateMeetingLiveState",1),__decorateClass([callOperation("UpdateMeetingStates"),__decorateParam(1,operationId)],oo.prototype,"updateMeetingStates",1),__decorateClass([callOperation("UpdateParticipantInterpretationState"),__decorateParam(0,operationId)],oo.prototype,"updateParticipantInterpretationState",1),__decorateClass([callOperation("UpdateParticipantsProperties")],oo.prototype,"updateParticipantsProperties",1),__decorateClass([callOperation("JoinMeetingGroup"),__decorateParam(0,operationId)],oo.prototype,"joinMeetingGroup",1),__decorateClass([callOperation("LeaveMeetingGroup"),__decorateParam(0,operationId)],oo.prototype,"leaveMeetingGroup",1),__decorateClass([callOperation("SendMessages"),__decorateParam(0,operationId)],oo.prototype,"sendMessages",1),__decorateClass([callOperation("UpdateMonitorSession"),__decorateParam(1,causeId)],oo.prototype,"updateMonitorSession",1),__decorateClass([callOperation("SwitchInterpreterGroup")],oo.prototype,"switchInterpreterGroup",1),__decorateClass([callOperation("SetLiveInterpretationAttributes")],oo.prototype,"setLiveInterpretationAttributes",1),__decorateClass([callOperation("UpdateMeetingRole")],oo.prototype,"updateMeetingRoles",1),__decorateClass([callOperation("CreateContentSharingSession"),__decorateParam(4,causeId)],oo.prototype,"createContentSharingSession",1),__decorateClass([callOperation("StopCallWithBeacon",{type:"Sync"}),__decorateParam(0,causeId)],oo.prototype,"stopWithBeacon",1),__decorateClass([callOperation("Acknowledge",{type:"Chained",convertError:!0,idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(2,causeId)],oo.prototype,"acknowledge",1),__decorateClass([callOperation("Accept",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"accept",1),__decorateClass([callOperation("Reject",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId),__decorateParam(1,reason)],oo.prototype,"reject",1),__decorateClass([callOperation("JoinCall",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(1,callStartOptions),__decorateParam(2,causeId)],oo.prototype,"join",1),__decorateClass([callOperation("JoinPreheatedCall",{waitFor:"_CallStartOrJoinInitiated"})],oo.prototype,"joinPreheatedCall",1),__decorateClass([callOperation("StartCall",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(0,callStartOptions),__decorateParam(1,causeId)],oo.prototype,"start",1),__decorateClass([callOperation("StartCallToVoiceMail",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(1,causeId)],oo.prototype,"startCallToVoicemail",1),__decorateClass([callOperation("Subscribe",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(2,causeId)],oo.prototype,"joinCallWithoutCallModality",1),__decorateClass([callOperation("StartWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],oo.prototype,"startWithMeetingData",1),__decorateClass([callOperation("JoinWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],oo.prototype,"joinWithMeetingData",1),__decorateClass([callOperation("SubscribeWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],oo.prototype,"subscribeWithMeetingData",1),__decorateClass([callOperation("StartCallWithNudge",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(1,callStartOptions),__decorateParam(2,causeId)],oo.prototype,"startCallWithNudge",1),__decorateClass([callOperation("StartCallAndUnpark",{type:"Chained",idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(2,callStartOptions),__decorateParam(3,causeId)],oo.prototype,"startAndUnpark",1),__decorateClass([participantOperation("AdmitParticipant"),__decorateParam(0,operationId),__decorateParam(1,causeId)],oo.prototype,"admitParticipant",1),__decorateClass([callOperation("Admit")],oo.prototype,"admit",1),__decorateClass([participantOperation("CallMeBack"),__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"callMeBack",1),__decorateClass([__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"addParticipant",1),__decorateClass([participantOperation("AddParticipants"),__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"addParticipants",1),__decorateClass([__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"addParticipantsImpl",1),__decorateClass([participantOperation("NudgeParticipants"),__decorateParam(0,operationId),__decorateParam(3,causeId)],oo.prototype,"nudgeParticipants",1),__decorateClass([participantOperation("RemoveParticipant"),__decorateParam(0,operationId),__decorateParam(1,causeId)],oo.prototype,"removeParticipant",1),__decorateClass([participantOperation("CancelNudge"),__decorateParam(0,operationId),__decorateParam(0,causeId)],oo.prototype,"cancelNudge",1),__decorateClass([callOperation("SearchParticipants"),__decorateParam(1,operationId),__decorateParam(1,causeId)],oo.prototype,"searchParticipants",1),__decorateClass([callOperation("GetAllParticipants"),__decorateParam(1,operationId),__decorateParam(1,causeId)],oo.prototype,"getAllParticipants",1),__decorateClass([callOperation("_PromotionToRealtime"),__decorateParam(1,causeId)],oo.prototype,"promoteToRealtime",1),__decorateClass([__decorateParam(0,causeId)],oo.prototype,"turnOffLocalVideoPreview",1),__decorateClass([callOperation("_StartPreviewVideo"),__decorateParam(0,causeId)],oo.prototype,"turnOnLocalVideoPreview",1),__decorateClass([__decorateParam(0,causeId)],oo.prototype,"acquireLocalVideo",1),__decorateClass([__decorateParam(0,causeId)],oo.prototype,"turnOnLocalVideoPreviewUsingRenderer",1),__decorateClass([callOperation("_UpdateLocalMediaStatus",{type:"Chained"}),__decorateParam(0,causeId)],oo.prototype,"updateMediaStatus",1),__decorateClass([__decorateParam(0,causeId)],oo.prototype,"calculateIsSomeoneStreaming",1),__decorateClass([callOperation("_Reconnect")],oo.prototype,"reconnect",1),__decorateClass([callOperation("AddGroupModality"),__decorateParam(1,causeId)],oo.prototype,"addGroupModality",1),__decorateClass([callOperation("AddBroadcastModality")],oo.prototype,"addBroadcastModality",1);var lo=oo;function decode(g){const f=new TextDecoder("utf-8"),S=atob(g),v=Uint8Array.from(S,(g=>g.charCodeAt(0)));return f.decode(v)}var co=__toESM(ye()),ho=new RegExp("/callAgent/","i"),uo=class{constructor(g,f){this.signalingAgentProvider=g,this.callRegistry=f}handleMessage(g){if(!g.eventId){if(g.url.search(ho)>-1){const f=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(g);return"number"==typeof f?{isHandled:!0,resultCode:f}:{isHandled:!0,resultCode:f.resultCode,responseBody:f.responseBody,responseHeaders:f.responseHeaders}}return{isHandled:!1}}if(g.eventId in ji){this.callRegistry.logUploadNotification(g);const f=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(g);return"number"==typeof f?{isHandled:!0,resultCode:f}:{isHandled:!0,resultCode:f.resultCode,responseBody:f.responseBody,responseHeaders:f.responseHeaders}}return{isHandled:!1}}},go=class{constructor(g,f,S){this.callRegistry=g,this.recentInvitations=[],this.logger=f.createChild("IncomingCallMessageHandler"),this.ecsProvider=S}handleMessage(g){const f=this.handleIncomingCall(g);return f?{isHandled:f,resultCode:200}:{isHandled:f}}handleIncomingCall(g){const f=generateCauseId(),S=this.logger.createFnLogger("handleIncomingCall",f);if(this.isProxiableNotification(g))return this.callRegistry.proxyPushNotification(g),!0;if(!this.isIncomingCallMessage(g))return!1;let v;this.callRegistry.pushHandlingStarted(f);try{if(g?.body?.gp&&!isStringBase64(g.body.gp))S.info("unencoded payload, skipping decoding."),v=g.body.gp;else{const f=decodeNotificationPayload(g,S);v=JSON.parse(f)}v.body=g.body}catch(g){return this.callRegistry.pushHandlingEnded(f,{result:"Failed to parse incoming call notification payload",code:Fi.BadRequest,subCode:3080,participantId:"",callId:"",resultCategories:["UnexpectedServerError"]}),S.logFailure(`Error parsing notification payload: ${g}`),!1}const C=this.isCallTransferNotification(g)?this.buildTransferCallPayload(v):this.buildNGCCallPayload(v);if(!C)return this.callRegistry.pushHandlingEnded(f,{result:"Failed to get incoming call notification payload",code:Fi.BadRequest,subCode:3081,participantId:"",callId:"",resultCategories:["UnexpectedClientError"]}),!1;if(this.callRegistry.calls.some((g=>g.callId===C.convoCallId&&g.participantId===C.participantId)))return S.logFailure(`Duplicate call filtered because it was in the call registry, callId = ${C.convoCallId}, participantId = ${C.participantId}`),this.callRegistry.pushHandlingEnded(f,{result:"Failed due to duplicate call filtered because it was in the call registry",code:Fi.LocalError,subCode:3082,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["ExpectedError"]}),!1;const _=this.isCallReplacementNotification(g);if(S.log(`replacementCall=${_}`),!_&&this.recentInvitations.some((g=>g.convoCallId===C.convoCallId&&g.participantId===C.participantId)))return S.logFailure(`Duplicate call filtered because it was in the recent calls list, callId = ${C.convoCallId}, participantId = ${C.participantId}`),this.callRegistry.pushHandlingEnded(f,{result:"Failed due to duplicate call filtered because it was in the recent calls list",code:Fi.LocalError,subCode:3083,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["ExpectedError"]}),!1;5===this.recentInvitations.length&&this.recentInvitations.shift(),this.recentInvitations.push({convoCallId:C.convoCallId,participantId:C.participantId});let T=this.callRegistry.calls.find((g=>g.callId===C.convoCallId&&8===g.state));if(!T)if(C.groupId)try{T=this.callRegistry.createCallWithGroupId(C.groupId,C.convoCallId,C.participantId,f)}catch(g){this.callRegistry.pushHandlingEnded(f,{result:"Failed to create incoming call notification with groupId",code:Fi.BadRequest,subCode:3084,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["UnexpectedClientError"]})}else try{T=this.callRegistry.createCall(C.conversationId,C.convoCallId,C.participantId,void 0,f)}catch(g){this.callRegistry.pushHandlingEnded(f,{result:"Failed to create incoming call notification",code:Fi.BadRequest,subCode:3084,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["UnexpectedClientError"]})}return T.init({threadId:C.conversationId,messageId:C.messageId,mediaPeerType:2}),this.callRegistry.testEndpointMetadata?T.acknowledge(C,this.callRegistry.testEndpointMetadata,f).then((()=>this.callRegistry.pushHandlingEnded(f,{code:an.HTTP_STATUS_CODES.OK,subCode:Fi.Success,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["Success"]}))).catch((g=>this.callRegistry.pushHandlingEnded(f,{result:"Failed to acknowledge incoming call notification",code:Fi.LocalError,subCode:3085+g.code,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["UnexpectedClientError"]}))):T.acknowledge(C,void 0,f).then((()=>this.callRegistry.pushHandlingEnded(f,{code:an.HTTP_STATUS_CODES.OK,subCode:Fi.Success,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["Success"]}))).catch((g=>this.callRegistry.pushHandlingEnded(f,{result:"Failed to acknowledge incoming call notification",code:Fi.LocalError,subCode:3085+g.code,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["UnexpectedClientError"]}))),!0}isIncomingCallMessage(g){return Object.keys(Hi).some((f=>Hi[f]===g.eventId))?g.eventId!==Hi.INCOMING_TFL_TFW_CALL||this.ecsProvider?.getEcsConfig("SkypeCalling","enableTFWTFLOneToOneCall"):this.isCallTransferNotification(g)}isCallTransferNotification(g){return g.callNotification&&("transfer"===g.callNotification.callType||"replaces"===g.callNotification.callType)}isCallReplacementNotification(g){return g.callNotification&&"replaces"===g.callNotification.callType}isProxiableNotification(g){return Object.keys($i).some((f=>$i[f]===g.eventId))}buildTransferCallPayload(g){const f={body:g.body,callerId:g.callNotification.from.id,displayNameSource:parseDisplayNameSourceFromWire(g.callNotification.from.displayNameSource),groupId:null,conversationId:null,convoCallId:g.debugContent.callId,isMultiParty:g.conversationInvitation?.isMultiParty,fromMixer:g.callNotification.fromMixer,ngcCall:!0,participantId:g.callNotification.to.participantId,transferorId:g.callNotification.transferor&&g.callNotification.transferor.details&&g.callNotification.transferor.details.id,transferorType:g.callNotification.transferor&&g.callNotification.transferor.transferorType,transferorDisplayName:g.callNotification.transferor&&g.callNotification.transferor.details&&g.callNotification.transferor.details.displayName,callType:g.callNotification.callType,consultativeCallId:g.callNotification.consultativeCallId,messageId:null,callQueueInfo:g.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0};return this.logger.info("Incoming transfer paylod",getPIISafePayload(f,["callerId","transferorId"])),f}buildNGCCallPayload(g){if(!g.callNotification)return this.logger.error("Missing callNotification in parsed incoming NGC call payload"),null;const f={groupId:g.groupContext?.id,conversationId:g.groupChat?.threadId,messageId:g.groupChat?.messageId,callerId:g.callNotification.from.id,displayNameSource:parseDisplayNameSourceFromWire(g.callNotification.from.displayNameSource),isMultiParty:g.conversationInvitation.isMultiParty,fromMixer:g.callNotification.fromMixer,convoCallId:g.debugContent.callId,participantId:g.debugContent.participantId,ngcCall:!0,body:g.body,transferorId:g.callNotification.transferor&&g.callNotification.transferor.details&&g.callNotification.transferor.details.id,transferorType:g.callNotification.transferor&&g.callNotification.transferor.transferorType,transferorDisplayName:g.callNotification.transferor&&g.callNotification.transferor.details&&g.callNotification.transferor.details.displayName,callType:g.callNotification.callType,callQueueInfo:g.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0,fromApplicationType:g.callNotification.fromApplicationType};return this.logger.info("Incoming NGC paylod",getPIISafePayload(f,["callerId","transferorId"])),f}},po=class extends Ke{constructor(g,f,S,v,C,_=null,T,I,b){super(),this.trouterService=g,this.signalingAgentProvider=f,this.mediaAgent=S,this.callingLogger=v,this.telemetryLoggers=C,this.ecsProvider=_,this.skypeIdentity=T,this.oneDsTelemetryLoggers=I,this.vdi3diagnostics=b,this.calls=[],this.isDisposing=!1,this._disposedPromise=new dt,this.testEndpointMetadata=null,this._disconnectingPromiseDefers=new Map,this.skypeIdentity&&(this.identity=this.skypeIdentity.id),this.callSubscriptionsMap=new Map,this.logger=new Ge(this.callingLogger).createChild(`CallRegistry/${generateCauseId()}`),this.registryTelemetry=new Ti(this.logger,(new Date).getTime()),this._callOperationHandler||(this._callOperationHandler=new Li(this.logger,this.registryTelemetry,{},(g=>{this._publishTelemetry(g)})));const A=this.mediaAgent.getConfig().disconnectOnPageHide;this._windowUninitEvent=A?"pagehide":"beforeunload",this.signalingAgentProvider.getSignalingAgent().setTokenRequiredCallBack(this.onTokenRequired.bind(this)),this._createNewCallInDisconnectedState=this.ecsProvider.getEcsConfig("SkypeCalling","createNewCallInDisconnectedState"),this._invokeDeleteCallInDisconnectedState=this.ecsProvider.getEcsConfig("SkypeCalling","invokeDeleteCallInDisconnectedState")}init(g,f,S=generateCauseId()){return this.logger.createFnLogger("init",S).info("init"),this.login(g)}uninit(){return this.logout()}login(g,f=generateCauseId()){return this.logger.createFnLogger("login",f).info("login"),this.skypeIdentity=g,this.identity=this.skypeIdentity.id,this.initialize(f)}initialize(g=generateCauseId(),f){const S=this.logger.createFnLogger("initialize",g),v=f&&f.applicationType?f.applicationType:"null";S.info(`initialize with applicationType: ${v}`),this.accountConfiguration=f,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(f),this.incomingCallMessageHandler=new go(this,this.logger,this.ecsProvider),this.trouterService.registerMessageHandler(new uo(this.signalingAgentProvider,this)),this.trouterService.registerMessageHandler(this.incomingCallMessageHandler),S.info("Call registry init, endpointMetadata",this.testEndpointMetadata);try{this.windowUninitListener=()=>{this._disregardWindowUninitEvents||this.stopCallsWithBeacon()},window.addEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(g){S.logFailure(`Not adding beforeunload listener: ${g}`)}return Promise.resolve(void 0)}logout(g=generateCauseId()){const f=this.logger.createFnLogger("logout",g);f.info("logout");try{this.trouterService.clearMessageHandlers(),window.removeEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(g){f.info(`Not removing beforeunload listener: ${g}`)}return Promise.resolve(void 0)}_publishTelemetry(g){if(!this.telemetryLoggers?.signaling)return;this.registryTelemetry.setSkypeId(this.identity);try{const g=this.signalingAgentProvider.getSignalingAgent();this.registryTelemetry.setEndpointId(g.endpointId)}catch(g){this.logger.warn("Could not get end point ID from signaling agent for call registry telemetry.")}this.accountConfiguration&&(this.registryTelemetry.setAcsResourceId(this.accountConfiguration.acsResourceId),this.registryTelemetry.setApplicationType(this.accountConfiguration.applicationType),this.registryTelemetry.setPartition(this.accountConfiguration.partition),this.registryTelemetry.setRegion(this.accountConfiguration.region),this.registryTelemetry.setRing(this.accountConfiguration.ring),this.registryTelemetry.setTenantId(this.accountConfiguration.tenantId),this.registryTelemetry.setUserHexCID(this.accountConfiguration.userHexCID),this.registryTelemetry.setClientType(this.accountConfiguration.clientType));const f=mi.REGISTRY_WEB;this.telemetryLoggers.signaling.sendEvent({eventName:f,props:this.registryTelemetry.getEvent(null,g)})}async dispose(g=generateCauseId()){const f=this.logger.createFnLogger("dispose",g);if(f.info("dispose"),this.isDisposing)return f.warn("call registry is already in disposing stage!"),this._disposedPromise.promise;this.isDisposing=!0;const always=()=>{this.calls=[],this.event("disposed").raise(),super.dispose(),this._disposedPromise.resolve()},S=this.calls.map((g=>g.stop())),logout=()=>this.logout();return this.clearCallSubscription(),this.signalingAgentProvider.getSignalingAgent().resetAuthTokenManager(),Promise.all(S).then(logout,logout).then(always,always),this._disposedPromise.promise}get disposePromise(){return this._disposedPromise.promise}createCallAsync(g){const f=this.logger.createFnLogger("createCallAsync",g.causeId),S=`callId:${g.callId}, localParticipantId: ${scrubMriOrOmit(g.localParticipantId)},\n            causeId:${g.causeId}, type:${g.type}, `;switch(g.type){case"MeetingData":S.concat(`meetingUrl:${!!g.meetingData?.meetingUrl}, meetingCode:${!!g.meetingData?.meetingCode}`);break;case"GroupId":S.concat(`groupId:${scrubMriOrOmit(g.groupId)}`);break;case"ThreadId":S.concat(`threadId:${getLoggableThreadId(g.threadId)}, messageId:${g.messageId}`);break;default:throw new Error("Invalid type in passing parameter.")}f.info(S);const v=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers,C=this._getCurrentCall(g,f);if(C){if(6===C.state){const g=new dt;return this._disconnectingPromiseDefers.set(C.callId,g),g.promise}return Promise.resolve(C)}return Promise.resolve(this._createNewCall(g,v,f))}createCallWithMeetingData(g,f,S,v){const C=this.logger.createFnLogger("createCallWithMeetingData",v);if(C.info(`meetingData:${!!g}, callId:${f}, localParticipantId: ${scrubMriOrOmit(S)}`),!g)return C.info("meetingData cannot be null"),null;const _=this._generateCreateCallOptions(v,f,S,null,null,null,g),T=this._getCurrentCall(_,C);if(T)return T;const I=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(_,I,C)}createCall(g,f,S,v,C=generateCauseId()){return this._createCall(g,f,S,v,C)}createCallWithGroupId(g,f,S,v){return this._createCall("",f,S,void 0,v,g)}_createNewCall(g,f,S){let v=null,C=null,_=null,T=null;switch(g.type){case"MeetingData":T=g.meetingData;break;case"GroupId":v=g.groupId;break;case"ThreadId":C=g.threadId,_=g.messageId}const I=new lo(this.signalingAgentProvider.getSignalingAgent(),this.mediaAgent,new Ge(this.callingLogger),f,this.skypeIdentity,v,C,g.callId,g.localParticipantId,this.ecsProvider,this.trouterService,this.accountConfiguration,_,this.locationInfoContent,this.networkInfoContent,T,this.areaContent,this.vdi3diagnostics);I.on("callStateChanged",(async()=>{if(7===I.state&&this._createNewCallInDisconnectedState){const v=this._disconnectingPromiseDefers.get(I.callId);v&&(this._disconnectingPromiseDefers.delete(I.callId),v.resolve(this._createNewCall(g,f,S))),this._invokeDeleteCallInDisconnectedState&&setTimeout((()=>{this.deleteCall(I)}),0)}})),this.calls.push(I),this.event("callAdded").raise(I),this.raiseChanged(),S.info(`Created new call with id ${I.callId}`);const b=I.on("replacementRequested",(g=>{this.incomingCallMessageHandler.handleMessage(g)}));return this.addCallSubscriptionToMap(I,b),I}_getCurrentCall(g,f){let S=null;return"MeetingData"===g.type&&(S=this.getCallUsingMeetingData(g.meetingData,g.callId,g.localParticipantId,void 0,void 0,g.causeId),S)?(f.info("Call Registry has an entry for this call's meeting data"),S):(S=this.getCall(g.callId,g.localParticipantId,g.causeId),S?(f.info("Call Registry has an entry for this callId, participantId"),S):"ThreadId"===g.type&&(S=this.getCallUsingThreadIdMessageId(g.threadId,g.callId,g.messageId,g.causeId),S)?(f.info("Call Registry has an entry for this threadId, messageId"),S):"GroupId"===g.type&&(S=this.calls.find((f=>f.groupId===g.groupId)),S)?(f.info("Call Registry has an entry for this groupId"),S):S)}_generateCreateCallOptions(g,f,S,v,C,_,T){let I=null;return I=v?{type:"GroupId",callId:f,localParticipantId:S,causeId:g,groupId:v}:C?{type:"ThreadId",callId:f,localParticipantId:S,causeId:g,threadId:C,messageId:_}:{type:"MeetingData",callId:f,localParticipantId:S,causeId:g,meetingData:T},I}_createCall(g,f,S,v,C=generateCauseId(),_){const T=this.logger.createFnLogger("createCall",C);T.info(`threadId:${getLoggableThreadId(g)}, callId:${f}, localParticipantId: ${scrubMriOrOmit(S)}, messageId:${v}, groupId:${scrubMriOrOmit(_)}`);const I=this._generateCreateCallOptions(C,f,S,_,g,v,null),b=this._getCurrentCall(I,T);if(b)return b;const A=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(I,A,T)}getCall(g,f,S=generateCauseId()){const v=this.logger.createFnLogger(`getCall[callId=${g}][participantId=${scrubMriOrOmit(f)}]`,S);if(!g)return v.logFailure("callId is undefined"),null;const C=this.calls.find((f=>f.callId===g));return C&&v.info("Call Registry already has an entry for this call"),C}async deleteCallAsync(g){return asap((()=>this.deleteCall(g)))}deleteCall(g){const f=this.calls.indexOf(g);return-1!==f&&(this.callSubscriptionsMap.get(g).forEach((g=>{g.dispose()})),this.callSubscriptionsMap.delete(g),this.calls.splice(f,1),this.event("callRemoved").raise(g),this.raiseChanged(),!0)}async setConfiguration(g){this.accountConfiguration=g,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(g)}updateDisplayName(g){return this.skypeIdentity.displayName=g,this.calls.forEach((f=>{f.updateDisplayName(g)})),Promise.resolve()}fireIntent(g,f){return Promise.resolve()}getCallState(g,f){return Promise.reject("Not implemented")}getSetup(){}getEcsConfig(){return Promise.reject()}updateSkypeToken(g){this.logger.debug("CallRegistry.updateSkypeToken() called but not supported in the current set up.")}updateToken(g,f,S,v,C){this.logger.info(`[updateToken], causeId = ${v} tokenType = ${f.tokenType}, factorsJson = ${g}, tokenExpiredTime = ${C}`);try{return this.signalingAgentProvider.getSignalingAgent().updateToken(g,f,S,v,C),Promise.resolve(getSuccessTransactionEnd())}catch(f){return this.logger.info(`Failed to update token with ${g}, error is ${f}`),Promise.reject(getRejectTransactionEnd(`Failed to update token with ${g}, error is ${f}`))}}onTokenRequired(g){const{requestMetadataJson:f,factorsJson:S,tokenType:v,invalidToken:C}=g;this.logger.info(`[onTokenRequired], tokenType ${v}, factorsJson ${S}, requestMetadataJson ${JSON.stringify(f)}`),this.event("tokenRequired").raise(S,v,f,C)}pushHandlingStarted(g){this.logger.info(`handleIncomingCallStarted, causeId=${g}`),this.event("pushHandlingStarted").raise(g)}pushHandlingEnded(g,f){this.logger.info(`pushHandlingEnded, causeId=${g}`),this.event("pushHandlingEnded").raise(g,f)}debugInformation(g){const f=g?`CallInformation\n * CallId=${g.callId}`:void 0;return Promise.resolve(f)}setLocationInfo(g,f,S=generateCauseId()){if(this.logger.info(`setLocationInfo, ${S}, infoType:${g}, contentJson ${f?"is set":"is undefined"}`),f)try{JSON.parse(f)}catch(g){return Promise.reject(`invalid contentJson: ${g}`)}return this.locationInfoType=g,1===this.locationInfoType&&(this.locationInfoContent=f,this.logger.info(`locationInfoContent set to ${this.locationInfoContent}`)),2===this.locationInfoType&&(this.networkInfoContent=f,this.logger.info(`networkInfoContent set to ${this.networkInfoContent}`)),3===this.locationInfoType&&(this.areaContent=f,this.logger.info(`areaContent set to ${this.areaContent}`)),this.event("locationInfoSet").raise(g,f),Promise.resolve()}createDownloader(){return null}async getUnassembledLocalRecordingSessions(g=generateCauseId()){return Promise.reject("Not implemented")}submitBrbReport(g,f){return Promise.reject("Not implemented")}extendBrbFeedback(g,f){return Promise.reject("Not implemented")}proxyPushNotification(g){this.logger.info(`Proxying push notification with event ID ${g.eventId}`);try{const f={eventId:g.eventId,payload:decodeNotificationPayload(g,this.logger)};this.event("proxiedPushNotification").raise(f)}catch(g){this.logger.error(`Error proxying push notification: ${g}`)}}logUploadNotification(g){this.logger.info(`Log upload notification with event ID ${g.eventId}`);try{const f={eventId:g.eventId,payload:decodeNotificationPayload(g,this.logger)};this.event("logUploadNotification").raise(f)}catch(g){this.logger.error(`Error raising log upload notification: ${g}`)}}sendPush(g,f,S,v){const C={id:g},_=[];return f.forEach((g=>{_.push({id:g})})),this.signalingAgentProvider.getSignalingAgent().sendPushAsync(C,_,S,v)}enableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!1}disableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!0}async enableWindowUninitEventHandlerAsync(){this.enableWindowUninitEventHandler()}async disableWindowUninitEventHandlerAsync(){this.disableWindowUninitEventHandler()}getCallUsingThreadIdMessageId(g,f,S,v){this.logger.info(`[getCallUsingThreadIdMessageId][${v}] threadID: ${getLoggableThreadId(g)} callId: ${f} messageId: ${S}`);let C=null;return g&&(C=this.calls.find((v=>v.threadId===g&&(f&&v.callId===f||null!=S&&v.messageId===S))),C)?(this.logger.logFailure(`[getCallUsingThreadIdMessageId][${v}]Call Registry already has an entry for threadId: ${getLoggableThreadId(C.threadId)}, callId: ${C.callId}, messageId: ${C.messageId}`),C):C}getCallUsingMeetingData(g,f,S,v,C,_=generateCauseId()){const T=this.logger.createFnLogger("getCallUsingMeetingData",_);if(T.info(`[callId=${f}][participantId=${scrubMriOrOmit(S)}] meetingData: ${!!g} \n            threadId: ${getLoggableThreadId(v)} messageId: ${C}`),!f)return T.logFailure("callId is undefined"),null;let I;for(const S of this.calls){if(S.callId===f){I=S;break}if(compareMeetingData(S.meetingData,g,_,this.logger)){I=S;break}}return I}stopCallsWithBeacon(){for(const g of this.calls)g.stopWithBeacon()}addCallSubscriptionToMap(g,f){this.callSubscriptionsMap.set(g,(this.callSubscriptionsMap.get(g)||[]).concat(f))}clearCallSubscription(){this.callSubscriptionsMap.forEach((g=>{g.forEach((g=>{g.dispose()}))})),this.callSubscriptionsMap.clear()}};function decodeNotificationPayload(g,f){const S=f.createFnLogger("decodeNotificationPayload");let v="{}";if(g?.body?.gp)S.info("using notification.body.gp"),v=decode(g.body.gp);else if(g?.body?.cp){S.info("using notification.body.cp");const f=atob(g.body.cp);v=co.inflate(f,{to:"string"})}return v}__decorateClass([callOperation("Initialize",{enableInstantTelemetry:!0})],po.prototype,"initialize",1),__decorateClass([callOperation("Logout",{enableInstantTelemetry:!0})],po.prototype,"logout",1);var mo=M,fo=class{constructor(g){this.deviceManager=g}get childDeviceManagers(){return this.deviceManager.getRegisteredDevices()}createPreview(g,f,S,v){return this.executeOnVirtualDeviceManager((v=>S(g,f,v,"Video")),v)}getRawDeviceMediaStream(g,f,S){return this.executeOnVirtualDeviceManager((S=>S.getRawDeviceMediaStream(g,f)),S)}setDeviceEffectsAsync(g,f){return this.executeOnVirtualDeviceManager((g=>g.setVideoEffects(f)),g)}setRawMediaStream(g,f,S){this.executeOnVirtualDeviceManager((S=>S.setRawMediaStream(g,f)),S)}unsetRawMediaStream(g,f){this.executeOnVirtualDeviceManager((f=>f.unsetRawMediaStream(g)),f)}getVirtualDevice(g){return this.childDeviceManagers.find((f=>f.id===g))}executeOnVirtualDeviceManager(g,f){return this.getVirtualDevice(f).getDeviceManagers().map((f=>g(f)))}},So="default_output_device",vo=class _DeviceManagerAdapter extends Ke{constructor(g){super(),this._deviceManager=g,this.virtualDeviceAdapter=new fo(this._deviceManager),g.on("onDevicesChanged",(g=>{const f=this._deviceManager.getDeviceDescriptions(g),S=this._mapDevices(f);this._raiseDevicesChanged(S)})),g.on("onSelectedDevicesChanged",(g=>this._raiseDevicesChanged())),g.on("onPermissionStateChanged",(()=>this.event("onPermissionStateChanged").raise())),g.on("onVideoEffectsEvent",((g,f)=>this.event("videoEffectsEvent").raise(g,f))),g.on("onVideoEffectApplied",(()=>this.event("videoEffectApplied").raise())),g.on("onEffectsError",((g,f,S)=>this.event("onEffectsError").raise(getSkypeMediaType(g),f,S)))}get isAudioOutputSelectionSupported(){return this._deviceManager.isAudioOutputSelectionSupported}getPermissionState(g){return"camera"===g?this.getPermissionStateHelper(this._deviceManager.getPermissionState("camera")):"microphone"===g?this.getPermissionStateHelper(this._deviceManager.getPermissionState("microphone")):"unknown"}async getPermissionStateAsync(g){return this.getPermissionState(g)}askDevicePermission(g){return this._deviceManager.askDevicePermission?this._deviceManager.askDevicePermission(g):Promise.resolve({audio:!0,video:!0})}enumerateDevicesAsync(){return this._deviceManager.enumerateDevicesAsync().then((g=>this._mapDevices(g)))}getPreferredCamera(){throw new Error("Not implemented")}selectDevices(g){if(Object.keys(g).some((g=>this.isVirtualDevice(g))))throw new Error("Virtual Device selection on DM is not supported");const f=(0,mo.assign)({},this._deviceManager.getSelectedDevices(),g);this._deviceManager.selectDevices(f)}selectDevicesAsync(g){return asap((()=>this.selectDevices(g)))}getSelectedDevices(){return this._deviceManager.getSelectedDevices()}getSelectedDevicesAsync(){return asap((()=>this.getSelectedDevices()))}getDeviceNameAsync(g){return this._deviceManager.getDeviceNameAsync(g)}getSpeakerDeviceDomIdAsync(g,f){return this._deviceManager.getSpeakerDeviceDomIdAsync(g)}mapBrowserDevices(g,f){return Promise.reject(new Error("Not implemented"))}async setDeviceEffectsAsync(g,f){if(!this.isVirtualDevice(g))return this._deviceManager.setVideoEffects(f);Promise.all(this.virtualDeviceAdapter.setDeviceEffectsAsync(g,f))}getDeviceEffectsCapabilityAsync(g,f){return this._deviceManager.effectsManager.getEffectsCapability("Video")}setBackgroundImageAsync(g,f,S){return this._deviceManager.effectsManager.configure("Video",{imagePath:f,headers:S})}getImagePropertyAsync(g){return Promise.reject(new Error("Not implemented"))}getMicrophoneGeometryArrayInfoAsync(g){return Promise.reject(new Error("Not implemented"))}transformImageAsync(g,f,S,v){return Promise.reject(new Error("Not implemented"))}setAudioProcessingFlags(g){return this._deviceManager.setAudioProcessingFlags(g)}async sendMessageDeviceVideoEffectsAsync(g,f){return await this._deviceManager.sendMessageDeviceVideoEffectsAsync(g,f)}sendMessageDeviceVideoExtensibilityAsync(g,f){return Promise.reject(new Error("Not implemented"))}setVideoCaptureConfigAsync(g,f){return Promise.reject(new Error("Not implemented"))}captureVideoFrameWithoutEffectsAsync(g,f,S){return Promise.reject(new Error("Not implemented"))}enableSignLanguageDetectionAsync(g,f){return Promise.reject(new Error("Not implemented"))}downloadAiModel(g,f){return Promise.reject(new Error("Not implemented"))}getSpeakerVolume(){return Promise.reject(new Error("Not implemented"))}getSpeakerSystemVolume(){return Promise.reject(new Error("Not implemented"))}setSpeakerVolume(g){return Promise.reject(new Error("Not implemented"))}setSpeakerSystemVolume(g){return Promise.reject(new Error("Not implemented"))}unmuteMicrophone(){return Promise.reject(new Error("Not implemented"))}unmuteSpeaker(){return Promise.reject(new Error("Not implemented"))}getNrgLevelsForDeviceTuner(g){return Promise.reject(new Error("Not implemented"))}async getNrgLevelPollerForDeviceTuner(g){return await this._deviceManager.getNrgLevelPollerForDeviceTuner()}setAudioEffectsAsync(g,f){return this._deviceManager.setAudioEffects(f)}getAudioFeatureCapability(g){return this._deviceManager.effectsManager.getEffectsCapability("Audio")}getAudioFeatureProviderName(){return Promise.resolve(this._deviceManager.effectsManager.getAudioEffectsProviderName())}getMicrophoneVolume(){return Promise.reject(new Error("Not implemented"))}setMicrophoneVolume(g){return Promise.reject(new Error("Not implemented"))}setDeviceTelemetryData(g,f,S,v=0){return Promise.reject(new Error("Not implemented"))}getSourceFormats(g){return Promise.reject(new Error("Not implemented"))}enableShellSharing(){return Promise.reject(new Error("Not implemented"))}disableShellSharing(){return Promise.reject(new Error("Not implemeted"))}enableParticipantCameras(){return Promise.reject(new Error("Not implemeted"))}registerDerivedSource(g,f){return Promise.reject(new Error("Not implemeted"))}unregisterDerivedSource(g){return Promise.reject(new Error("Not implemeted"))}async createPreview(g,f,S){if("camera"===f.kind&&this.isVirtualDevice(f.device))return this.virtualDeviceAdapter.createPreview(g,S,this.getRenderer,f.device)[0];if("sharing"===f.kind)return this.createScreenSharingPreviewRenderer(g,S);if("camera"!==f.kind||!(0,mo.isUndefined)(f.device))throw new Error("Not yet supported");return this.createPreviewRenderer(g,S)}async createPreviewRenderer(g,f){return this.getRenderer(g,f,this._deviceManager,"Video")}async createScreenSharingPreviewRenderer(g,f){return this.getRenderer(g,f,this._deviceManager,"ScreenShare")}getRawDeviceMediaStream(g,f,S){const v=getAgentMediaType(g);return this.isVirtualDevice(S)?this.virtualDeviceAdapter.getRawDeviceMediaStream(v,f,S)[0]:this._deviceManager.getRawDeviceMediaStream(v,f)}setRawMediaStream(g,f,S){const v=getAgentMediaType(f);return this.isVirtualDevice(S)?this.virtualDeviceAdapter.setRawMediaStream(g,v,S):this._deviceManager.setRawMediaStream(g,v)}unsetRawMediaStream(g,f){const S=getAgentMediaType(g);return this.isVirtualDevice(f)?this.virtualDeviceAdapter.unsetRawMediaStream(S,f):this._deviceManager.unsetRawMediaStream(S)}createAudioRenderer(){return this._deviceManager.createAudioRenderer()}startAudioLoopbackDevice(g){return Promise.reject(new Error("Not implemented"))}async dispose(g){return this._deviceManager.dispose(g)}async registerCompositeVideoDevice(g,f,S){return this._deviceManager.registerVirtualDevice(g,f,S)}async unregisterCompositeVideoDevice(g){return this._deviceManager.unregisterVirtualDevice(g)}async createAudioPlayer(){return Promise.reject(new Error("Not implemented"))}_raiseDevicesChanged(g){(g?Promise.resolve(g):this.enumerateDevicesAsync()).then((g=>{this.raiseChanged(),this.event("devicesChanged").raise(g)}))}getPermissionStateHelper(g){switch(g){case"granted":return"granted";case"denied":return"denied";case"prompt":return"prompt";default:return"unknown"}}_mapDevices(g){return g?.map((g=>this._mapDeviceDesc(g)))}_mapDeviceDesc(g){const f=_DeviceManagerAdapter._mapDeviceType(g.kind);if(6===f){return{id:g.id,label:g.label,kind:f,position:0,defaultVideoId:g.id,devicesIds:[]}}if(1===f){return{id:g.id,browserId:g.browserId,label:g.label,kind:f,position:_DeviceManagerAdapter._mapCameraPosition(g.position)}}if(4===f){return{id:null,browserId:null,label:g.label,kind:f,formFactor:g.formFactor,isPcInternalDevice:g.isPcInternalDevice,microphoneId:g.microphoneId,speakerId:g.speakerId}}return{id:g.id,browserId:g.browserId===So?"default":g.browserId,label:g.label,kind:f,isSystemDefault:!!g.isSystemDefault}}static _mapDeviceType(g){switch(g){case"camera":return 1;case"microphone":return 2;case"speaker":return 3;case"compositeAudio":return 4;case"virtualDevice":return 6;default:throw new Error(`Invalid device type '${g}'`)}}static _mapCameraPosition(g){switch(g){case"front":return 1;case"back":return 2;case"external":return 3;default:return 0}}isVirtualDevice(g){return g&&this._deviceManager.getRegisteredDevices().some((f=>f.id===g))}async getRenderer(g,f,S,v){const C=new Kr(g,S,v);try{await C.startVideoAsync(),f&&(C.setScalingMode(f.scalingMode),C.setVideoMirroring(!f.ignoreMirroring))}catch(g){throw C.dispose(),g}return C}},Co=R,yo=R,Eo=class extends yo.AbstractLogAppender{constructor(g){super(new yo.StandardLogFormatter(yo.SLF_Flags.Component)),this._logger=g}log(g,f,S,v){if(!this._logger)return;const C=g.level<=yo.LogLevel.Debug4?this._logger.debug:g.level<=yo.LogLevel.Debug2?this._logger.log:g.level<=yo.LogLevel.Debug1?this._logger.info:g.level<=yo.LogLevel.Warning?this._logger.warn:this._logger.error;C&&C.apply(this._logger,[this.formatter().format(g,f,S,v)])}},_o=R,To=__toESM(Ae()),Io=["CorrelationId","agent_environment_id","UserInfo_TenantId","participant_id","endpoint_id","mediaLegId","metrics_ConfigIds","ts_calling_version","uiVersion"],bo={video:[...Io,"Extensions_WebRTCStats_ssrc_video_recv_framesDecoded","Extensions_WebRTCStats_ssrc_video_recv_packetsReceived","Extensions_WebRTCStats_ssrc_video_recv_ssrc","Extensions_WebRTCStats_ssrc_video_recv_bytesReceived","Extensions_WebRTCStats_ssrc_video_recv_googFrameRateDecoded","Extensions_Video_SubscriptionEvents","Extensions_Video_recv_ResolutionDurations","Extensions_Video_recv_StreamsMax","Extensions_Video_recv_frameRateAvg","Extensions_Video_recv_DurationSeconds","Extensions_Video_recv_FreezeHistogram","Extensions_Video_recv_FreezeTimestamps","Extensions_WebRTCStats_ssrc_video_recv_keyFramesDecoded","Extensions_Video_recv_TotalFreezeDurationMs","Extensions_Video_recv_packetsLostRateMax","metrics_ReconnectAttempts","metrics_ReconnectConnectedCount","metrics_RetargetCompletedCount","metrics_UFDs","Payload"],sharing:[...Io,"Extensions_WebRTCStats_ssrc_sharing_recv_framesDecoded","Extensions_WebRTCStats_ssrc_sharing_recv_packetsReceived","Extensions_WebRTCStats_ssrc_sharing_recv_ssrc","Extensions_WebRTCStats_ssrc_sharing_recv_bytesReceived","Extensions_WebRTCStats_ssrc_sharing_recv_googFrameRateDecoded","Extensions_WebRTCStats_ssrc_sharing_recv_keyFramesDecoded","Extensions_Sharing_SubscriptionEvents","Extensions_Sharing_recv_ResolutionDurations","Extensions_Sharing_recv_StreamsMax","Extensions_Sharing_recv_frameRateAvg","Extensions_Sharing_recv_DurationSeconds","Extensions_Sharing_recv_FreezeHistogram","Extensions_Sharing_recv_FreezeTimestamps","Extensions_Sharing_recv_TotalFreezeDurationMs","Extensions_Sharing_recv_packetsLostRateMax","metrics_ReconnectAttempts","metrics_ReconnectConnectedCount","metrics_RetargetCompletedCount","metrics_UFDs","Payload"]},Ao=class extends Ke{constructor(){super(...arguments),this.stabilizationTimeInAvg=2e4}send(g){g&&setTimeout((()=>{this.event("sendMidCallTelemetry").raise(bo[g])}),this.stabilizationTimeInAvg)}},Po=class extends Ke{constructor(g,f){super(),this._telemetryService=g,this._ecsProvider=f,this._ecsProvider.on("OnECSChanged",(()=>_o.RootToolsManager.OnEcsChange()))}fetchEcsConfig(g,f){return To.Resolved().then((()=>this._ecsProvider.getEcsConfig(g,f)))}sendTelemetry(g,f){this._telemetryService.getGenericTelemetryLogger&&g?this._telemetryService.getGenericTelemetryLogger(g).sendEvent({eventName:"rt_log",props:f}):this._telemetryService.sendEvents([{eventName:"rt_log",props:f}])}sendMidCallTelemetry(g){Object.keys(bo).includes(g)&&this.event("onMidCallTelemetry").raise(g)}};function initLogger(g,f,S){if(!Co.RootToolsManager.isDelegateSet()){const v=new Po(g.telemetryService,f);if(Co.RootToolsManager.setDelegate(v),v.on("onMidCallTelemetry",(g=>S.send(g))),g.logger){const f=new Eo(g.logger);Co.LogFactory.instance().addAppender(f)}}g.logger=new Fe("JS.TsCalling.Pluginless",!0),g.mediaAgentFactoryConfig.logger=new Fe("JS.TsCalling.MediaAgentUnsafe",!1),g.mediaAgentFactoryConfig.safeLogger=new Fe("JS.TsCalling.MediaAgent",!0),g.signalingAgentConfig.logger=new Fe("JS.TsCalling.SignalingAgent",!0)}var Ro=M,Mo=class _NoopLogger{constructor(g){this._prefix=g,this._children=[],this._useConsoleLogger=!1,this.createChild=(g,f)=>{const S="function"==typeof g?"":g,v=new _NoopLogger((this._prefix||"")+S);return this._children.push(v),this._useConsoleLogger&&v.useConsoleLogger(),v},this.createFnLogger=(g,f,...S)=>{const v=`[${f}][${g}]`,C=new _NoopLogger((this._prefix||"")+v);return this._children.push(C),this._useConsoleLogger&&C.useConsoleLogger(),C}}logInfo(){}logFailure(){}logSuccess(){}log(...g){}debug(...g){}info(...g){}warn(...g){}error(...g){}useConsoleLogger(){this._useConsoleLogger=!0;const logWithConsole=(...g)=>{console.info(this._prefix||"",...g)};this.log=logWithConsole,this.debug=logWithConsole,this.info=logWithConsole,this.warn=logWithConsole,this.error=logWithConsole,(0,Ro.each)(this._children,(g=>g.useConsoleLogger()))}},wo=class{constructor(g){this.configProvider=g,this.window=Xs.window,this.updateCapabilityOverrides(),this.configProviderSub=g.on("configUpdated",(()=>this.updateCapabilityOverrides()))}get audio(){return this.getCapability("audio")}get video(){return this.getCapability("video")}get screensharing(){return this.getCapability("screensharing")}get retargeting(){return this.getCapability("retargeting")}dispose(){this.configProviderSub&&this.configProviderSub.dispose()}updateCapabilityOverrides(){let g;this.configProvider.config.capabilities&&(g=this.configProvider.config.capabilities),this.overrides=g||{}}hasMediaCapture(){return!!this.window.navigator.getUserMedia}getCapability(g){return void 0!==this.overrides[g]?!!this.overrides[g]:this.hasMediaCapture()&&this.hasWebRtc()}hasWebRtc(){return void 0!==this.window.RTCPeerConnection}},Oo=class _UFDManager extends Ht{constructor(g,f){super(g),this.logger=g,this.configProvider=f,this.eventStates=new Map,this.debounceMap=new Map,this.logger.safe.info("Initialized")}signalEvent(g,f,S="Audio",v=!0,C=generateCauseId(),_,T){const I={type:g,value:f,isLocalSource:v,mediaType:S,deviceManagerId:_,diagnosticData:T},b=this.getEventKey(I),A=this.eventStates.get(b);if(this.configProvider.config.localUFDDebounceTime&&A){clearTimeout(this.debounceMap.get(b));const g=setTimeout(this.raiseEvent.bind(this),this.configProvider.config.localUFDDebounceTime,I,C);this.debounceMap.set(b,g)}else this.raiseEvent(I,C)}raiseEvent(g,f){const S=this.getEventKey(g);this.shouldRaiseEvent(g)&&(this.eventStates.set(S,g),this.logger.safe.info(`[${f}] Raising UFD ${g.type} for ${g.mediaType}: ${g.value}`),this.event("onQualityChanged").raise(g))}signalDeviceEvent(g,f,S,v){const C=_UFDManager.getQualityEventType(g,S,this.configProvider);C?this.signalEvent(C,f,S,void 0,generateCauseId(),v):this.logger.warn(`Unknown device quality event type: ${g}`)}raisePendingWhitelistingUFD(){this.lastWhitelistingUFD&&(this.logger.safe.debug(`Raising whitelisting UFD ${this.lastWhitelistingUFD.type}: ${this.lastWhitelistingUFD.value}`),this.event("onQualityChanged").raise(this.lastWhitelistingUFD),this.cancelPendingWhitelistingUFD())}cancelPendingWhitelistingUFD(){if(this.lastWhitelistingUFD){const g=this.getEventKey(this.lastWhitelistingUFD);this.eventStates.delete(g)}this.lastWhitelistingUFD=void 0}applyCurrentState(g){this.cancelPendingWhitelistingUFD();let f=0;for(const S of this.eventStates.values())"Good"!==S.value&&(g(S),f++);f>0&&this.logger.safe.info(`Applied ${f} UFDs`)}reset(){this.logger.safe.info("Resetting UFD states");for(const[g,f]of this.eventStates.entries())_UFDManager.persistent.has(f.type)||this.eventStates.delete(g);this.lastWhitelistingUFD=void 0}getEventKey(g){return`${g.type}:${g.mediaType}`}shouldRaiseEvent(g){const f=this.getEventKey(g),S=this.eventStates.get(f);return S&&S.value===g.value?!(!this.configProvider.config.alwaysRaiseBadDeviceEvents||!_UFDManager.deviceQualityEvents.has(g.type)||"Good"===g.value):!(!S&&"Good"===g.value)&&("NetworkRelaysNotReachable"===g.type?(this.lastWhitelistingUFD=g,!1):!("NetworkRecvQuality"===g.type&&!this.configProvider.config.webrtcStatNetworkDetectionEnabled))}static getQualityEventType(g,f,S){switch(g){case 0:return"Audio"===f?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartFailed";case 1:return"DeviceRenderNotFunctioning";case 2:return"Audio"===f?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartTimedOut";case 3:return"DeviceCaptureMute";case 4:switch(f){case"ScreenShare":return"ScreenshareRecordingDisabled";case"Audio":return S.config.enableSignalingAudioPermissionDeniedUFD?"AudioCapturePermissionDenied":"DeviceCaptureNotMuteButSilent";case"Video":return"VideoCapturePermissionDenied";default:return}default:return}}};Oo.persistent=new Set(["ZeroCaptureDevicesEnumerated","ZeroRenderDevicesEnumerated"]),Oo.deviceQualityEvents=new Set(["DeviceCaptureNotFunctioning","VideoCapturerDeviceStartFailed","VideoCapturerDeviceStartTimedOut","DeviceCaptureMute","ScreenshareRecordingDisabled","DeviceCaptureNotMuteButSilent","VideoCapturePermissionDenied"]);var Do=Oo,No=M,ko="function",Lo="object",Fo="undefined",xo="prototype",Uo=Object,Vo=Uo[xo];function _pureAssign(g,f){return g||f}function _pureRef(g,f){return g[f]}var Bo,Ho=void 0,$o=null,jo="",Go="function",qo="object",Wo="prototype",zo="__proto__",Ko="undefined",Jo="constructor",Yo="Symbol",Qo="_polyfill",Xo="length",Zo="name",el="call",tl="toString",il=_pureAssign(Object),nl=_pureRef(il,Wo),rl=_pureAssign(String),sl=_pureRef(rl,Wo),al=_pureAssign(Math),ol=_pureAssign(Array),ll=_pureRef(ol,Wo),cl=_pureRef(ll,"slice");function safe(g,f){try{return{v:g.apply(this,f)}}catch(g){return{e:g}}}function safeGet(g,f){var S=safe(g);return S.e?f:S.v}function _createIs(g){return function(f){return typeof f===g}}function _createObjIs(g){var f="[object "+g+"]";return function(g){return!(!g||objToString(g)!==f)}}function objToString(g){return nl[tl].call(g)}function isUndefined4(g){return typeof g===Ko||g===Ko}function isNullOrUndefined(g){return g===$o||isUndefined4(g)}function isStrictNullOrUndefined(g){return g===$o||!isDefined2(g)}function isDefined2(g){return!!g||g!==Ho}function isPrimitive(g){return g===$o||isPrimitiveType(typeof g)}function isPrimitiveType(g){return!Bo&&(Bo=["string","number","boolean",Ko,"symbol","bigint"]),g!==qo&&-1!==Bo.indexOf(g)}var dl=_createIs("string"),hl=_createIs(Go);function isObject3(g){return!(!g&&isNullOrUndefined(g))&&(!!g&&typeof g===qo)}var ul=_pureRef(ol,"isArray"),gl=_createObjIs("Date"),pl=_createIs("number"),ml=_createIs("boolean"),fl=_createObjIs("Error");function isPromiseLike2(g){return!!(g&&g.then&&hl(g.then))}function isTruthy(g){return!(!g||safeGet((function(){return!(g&&0+g)}),!g))}var Sl=_pureRef(il,"getOwnPropertyDescriptor");function objHasOwnProperty(g,f){return!!g&&nl.hasOwnProperty[el](g,f)}var vl=_pureAssign(_pureRef(il,"hasOwn"),polyObjHasOwn);function polyObjHasOwn(g,f){return objHasOwnProperty(g,f)||!!Sl(g,f)}function objForEachKey(g,f,S){if(g&&isObject3(g))for(var v in g)if(vl(g,v)&&-1===f[el](S||g,v,g[v]))break}var Cl={e:"enumerable",c:"configurable",v:"value",w:"writable",g:"get",s:"set"};function _createProp(g){var f={};if(f[Cl.c]=!0,f[Cl.e]=!0,g.l){f.get=function(){return g.l.v};var S=Sl(g.l,"v");S&&S.set&&(f.set=function(f){g.l.v=f})}return objForEachKey(g,(function(g,S){f[Cl[g]]=isUndefined4(S)?f[Cl[g]]:S})),f}var yl=_pureRef(il,"defineProperty"),El=_pureRef(il,"defineProperties");function objDefine(g,f,S){return yl(g,f,_createProp(S))}function objDefineProps(g,f){var S={};return objForEachKey(f,(function(g,f){S[g]=_createProp(f)})),El(g,S)}function _createKeyValueMap(g,f,S,v,C){var _={};return objForEachKey(g,(function(g,v){_assignMapValue(_,g,f?v:g,C),_assignMapValue(_,v,S?v:g,C)})),v?v(_):_}function _assignMapValue(g,f,S,v){yl(g,f,{value:S,enumerable:!0,writable:!!v})}var _l=_pureAssign(rl),Tl="[object Error]";function dumpObj(g,f){var S=jo,v=nl[tl][el](g);v===Tl&&(g={stack:_l(g.stack),message:_l(g.message),name:_l(g.name)});try{S=(S=JSON.stringify(g,$o,f?"number"==typeof f?f:4:Ho))&&S.replace(/"(\w+)"\s*:\s{0,1}/g,"$1: ")||_l(g)}catch(g){S=" - "+dumpObj(g,f)}return v+": "+S}function throwError(g){throw new Error(g)}function throwTypeError(g){throw new TypeError(g)}var Il=_pureRef(il,"freeze");function _doNothing(g){return g}function _getProto(g){return g[zo]||$o}var bl=_pureRef(il,"assign"),Al=_pureRef(il,"keys");function objDeepFreeze(g){return Il&&objForEachKey(g,(function(g,f){(ul(f)||isObject3(f))&&objDeepFreeze(f)})),Pl(g)}var Pl=_pureAssign(Il,_doNothing),Rl=_pureAssign(_pureRef(il,"getPrototypeOf"),_getProto);function createEnum(g){return _createKeyValueMap(g,1,0,Pl)}function createEnumKeyMap(g){return _createKeyValueMap(g,0,0,Pl)}function createSimpleMap(g){var f={};return objForEachKey(g,(function(g,S){_assignMapValue(f,g,S[1]),_assignMapValue(f,S[0],S[1])})),Pl(f)}function createTypeMap(g){return createSimpleMap(g)}var Ml,wl=createEnumKeyMap({asyncIterator:0,hasInstance:1,isConcatSpreadable:2,iterator:3,match:4,matchAll:5,replace:6,search:7,species:8,split:9,toPrimitive:10,toStringTag:11,unscopables:12}),Ol="__tsUtils$gblCfg";function _getGlobalValue(){var g;return typeof globalThis!==Ko&&(g=globalThis),g||typeof self===Ko||(g=self),g||typeof window===Ko||(g=window),g||typeof S===Ko||(g=S),g}function _getGlobalConfig(){if(!Ml){var g=safe(_getGlobalValue).v||{};Ml=g[Ol]=g[Ol]||{}}return Ml}var Dl=_unwrapFunctionWithPoly;function _unwrapFunctionWithPoly(g,f,S){var v=f&&f[g];return function(f){var C=f&&f[g]||v;if(C||S){var _=arguments;return(C||S).apply(f,C?cl[el](_,1):_)}throwTypeError('"'+_l(g)+'" not defined for '+dumpObj(f))}}function _unwrapProp(g){return function(f){return f[g]}}var Nl=_pureRef(al,"max"),kl=Dl("slice",sl),Ll=Dl("substring",sl),Fl=_unwrapFunctionWithPoly("substr",sl,polyStrSubstr);function polyStrSubstr(g,f,S){return isNullOrUndefined(g)&&throwTypeError("Invalid "+dumpObj(g)),S<0?jo:((f=f||0)<0&&(f=Nl(f+g[Xo],0)),isUndefined4(S)?kl(g,f):kl(g,f,f+S))}function strLeft(g,f){return Ll(g,0,f)}var xl,Ul,Vl,Bl="_urid";function _globalSymbolRegistry(){if(!xl){var g=_getGlobalConfig();xl=g.gblSym=g.gblSym||{k:{},s:{}}}return xl}function polyNewSymbol(g){var f={description:_l(g),toString:function(){return Yo+"("+g+")"}};return f[Qo]=!0,f}function polySymbolFor(g){var f=_globalSymbolRegistry();if(!vl(f.k,g)){var S=polyNewSymbol(g),v=Al(f.s).length;S[Bl]=function(){return v+"_"+S[tl]()},f.k[g]=S,f.s[S[Bl]()]=_l(g)}return f.k[g]}function polyGetKnownSymbol(g){var f;!Ul&&(Ul={});var S=wl[g];return S&&(f=Ul[S]=Ul[S]||polyNewSymbol(Yo+"."+S)),f}function _initTestHooks(){Vl=_getGlobalConfig()}function getLazy(g){var f={};return!Vl&&_initTestHooks(),f.b=Vl.lzy,yl(f,"v",{configurable:!0,get:function(){var S=g();return Vl.lzy||yl(f,"v",{value:S}),f.b=Vl.lzy,S}}),f}function createCachedValue(g){return yl({toJSON:function(){return g}},"v",{value:g})}var Hl,$l="window";function _getGlobalInstFn(g,f){var S;return function(){return!Vl&&_initTestHooks(),(!S||Vl.lzy)&&(S=createCachedValue(safe(g,f).v)),S.v}}function getGlobal(g){return!Vl&&_initTestHooks(),(!Hl||!1===g||Vl.lzy)&&(Hl=createCachedValue(safe(_getGlobalValue).v||$o)),Hl.v}function getInst(g,f){var S=Hl&&!1!==f?Hl.v:getGlobal(f);return S&&S[g]?S[g]:g===$l?Gl():$o}function hasDocument(){return!!jl()}var jl=_getGlobalInstFn(getInst,["document"]);function hasWindow(){return!!Gl()}var Gl=_getGlobalInstFn(getInst,[$l]);function hasNavigator(){return!!Kl()}var ql,Wl,zl,Kl=_getGlobalInstFn(getInst,["navigator"]),Jl=_getGlobalInstFn((function(){return!!safe((function(){return process&&(process.versions||{}).node})).v}));function _initSymbol(){return ql=createCachedValue(safe(getInst,[Yo]).v)}function _getSymbolKey(g){var f=(Vl.lzy?0:ql)||_initSymbol();return f.v?f.v[g]:Ho}function hasSymbol(){return!!getSymbol()}function getSymbol(){return!Vl&&_initTestHooks(),((Vl.lzy?0:ql)||_initSymbol()).v}function getKnownSymbol(g,f){var S=wl[g];!Vl&&_initTestHooks();var v=(Vl.lzy?0:ql)||_initSymbol();return v.v?v.v[S||g]:f?Ho:polyGetKnownSymbol(g)}function newSymbol(g,f){!Vl&&_initTestHooks();var S=(Vl.lzy?0:ql)||_initSymbol();return S.v?S.v(g):f?$o:polyNewSymbol(g)}function symbolFor(g){return!Vl&&_initTestHooks(),((Wl=(Vl.lzy?0:Wl)||createCachedValue(safe(_getSymbolKey,["for"]).v)).v||polySymbolFor)(g)}function isIterator(g){return!!g&&hl(g.next)}function isIterable(g){return!isStrictNullOrUndefined(g)&&hl(g[getKnownSymbol(3)])}function iterForOf(g,f,S){if(g&&(isIterator(g)||(!zl&&(zl=createCachedValue(getKnownSymbol(3))),g=g[zl.v]?g[zl.v]():null),isIterator(g))){var v=Ho,C=Ho;try{for(var _=0;!(C=g.next()).done&&-1!==f[el](S||g,C.value,_,g);)_++}catch(f){v={e:f},g.throw&&(C=$o,g.throw(v))}finally{try{C&&!C.done&&g.return&&g.return(C)}finally{if(v)throw v.e}}}}function fnApply(g,f,S){return g.apply(f,S)}function arrAppend(g,f){return!isUndefined4(f)&&g&&(ul(f)?fnApply(g.push,g,f):isIterator(f)||isIterable(f)?iterForOf(f,(function(f){g.push(f)})):g.push(f)),g}function arrForEach(g,f,S){if(g)for(var v=g[Xo]>>>0,C=0;C<v&&(!(C in g)||-1!==f[el](S||g,g[C],C,g));C++);}var Yl=Dl("indexOf",ll);function arrSlice(g,f,S){return(g&&g.slice||cl).apply(g,cl[el](arguments,1))}function polyArrIncludes(g,f,S){return-1!==Yl(g,f,S)}var Ql,Xl=_unwrapFunctionWithPoly("includes",ll,polyArrIncludes),Zl=_pureAssign(_pureRef(il,"create"),polyObjCreate);function polyObjCreate(g){if(!g)return{};var f=typeof g;function tempFunc(){}return f!==qo&&f!==Go&&throwTypeError("Prototype must be an Object or function: "+dumpObj(g)),tempFunc[Wo]=g,new tempFunc}function objSetPrototypeOf(g,f){return(il.setPrototypeOf||function(g,f){var S;!Ql&&(Ql=createCachedValue(((S={})[zo]=[],S instanceof Array))),Ql.v?g[zo]=f:objForEachKey(f,(function(f,S){return g[f]=S}))})(g,f)}function _createCustomError(g,f,S){function __(){this[Jo]=f,safe(objDefine,[this,Zo,{v:g,c:!0,e:!1}])}return safe(objDefine,[f,Zo,{v:g,c:!0,e:!1}]),(f=objSetPrototypeOf(f,S))[Wo]=S===$o?Zl(S):(__[Wo]=S[Wo],new __),f}function _setName(g,f){f&&(g[Zo]=f)}function createCustomError(g,f,S){var v=S||Error,C=v[Wo][Zo],_=Error.captureStackTrace;return _createCustomError(g,(function(){var S=this,T=arguments;try{safe(_setName,[v,g]);var I=fnApply(v,S,cl[el](T))||S;if(I!==S){var b=Rl(S);b!==Rl(I)&&objSetPrototypeOf(I,b)}return _&&_(I,S[Jo]),f&&f(I,T),I}finally{safe(_setName,[v,C])}}),v)}function utcNow(){return(Date.now||polyUtcNow)()}function polyUtcNow(){return(new Date).getTime()}function _createTrimFn(g){return function _doTrim(f){return isNullOrUndefined(f)&&throwTypeError("strTrim called ["+dumpObj(f)+"]"),f&&f.replace&&(f=f.replace(g,jo)),f}}var ec,tc,ic,nc=_unwrapFunctionWithPoly("trim",sl,_createTrimFn(/^\s+|(?=\s)\s+$/g));function isPlainObject(g){if(!g||typeof g!==qo)return!1;ic||(ic=!hasWindow()||Gl());var f=!1;if(g!==ic){tc||(ec=Function[Wo][tl],tc=ec[el](il));try{var S=Rl(g);(f=!S)||(objHasOwnProperty(S,Jo)&&(S=S[Jo]),f=S&&typeof S===Go&&ec[el](S)===tc)}catch(g){}}return f}function _defaultDeepCopyHandler(g){return g.value&&plainObjDeepCopyHandler(g),!0}var rc=[arrayDeepCopyHandler,plainObjDeepCopyHandler,functionDeepCopyHandler,dateDeepCopyHandler];function _getSetVisited(g,f,S,v){var C;return arrForEach(g,(function(g){if(g.k===f)return C=g,-1})),C||(C={k:f,v:f},g.push(C),v(C)),C.v}function _deepCopy(g,f,S,v){var C=S.handler,_=S.path?v?S.path.concat(v):S.path:[],T={handler:S.handler,src:S.src,path:_},I=typeof f,b=!1,A=!1;f&&I===qo?b=isPlainObject(f):A=f===$o||isPrimitiveType(I);var P={type:I,isPrim:A,isPlain:b,value:f,result:f,path:_,origin:S.src,copy:function(f,v){return _deepCopy(g,f,v?T:S,v)},copyTo:function(f,S){return _copyProps(g,f,S,T)}};return P.isPrim?C&&C[el](S,P)?P.result:f:_getSetVisited(g,f,_,(function(g){objDefine(P,"result",{g:function(){return g.v},s:function(f){g.v=f}});for(var f=0,v=C;!(v||(f<rc.length?rc[f++]:_defaultDeepCopyHandler))[el](S,P);)v=$o}))}function _copyProps(g,f,S,v){if(!isNullOrUndefined(S))for(var C in S)f[C]=_deepCopy(g,S[C],v,C);return f}function objCopyProps(g,f,S){return _copyProps([],g,f,{handler:S,src:f,path:[]})}function objDeepCopy(g,f){return _deepCopy([],g,{handler:f,src:g})}function arrayDeepCopyHandler(g){var f=g.value;if(ul(f)){var S=g.result=[];return S.length=f.length,g.copyTo(S,f),!0}return!1}function dateDeepCopyHandler(g){var f=g.value;return!!gl(f)&&(g.result=new Date(f.getTime()),!0)}function functionDeepCopyHandler(g){return g.type===Go}function plainObjDeepCopyHandler(g){var f=g.value;if(f&&g.isPlain){var S=g.result={};return g.copyTo(S,f),!0}return!1}function _doExtend(g,f){return arrForEach(f,(function(f){objCopyProps(g,f)})),g}function deepExtend(g,f,S,v,C,_,T){return _doExtend(objDeepCopy(g)||{},cl[el](arguments))}var sc=_unwrapProp(Xo);function perfNow(){return utcNow()}var ac=_unwrapFunctionWithPoly("endsWith",sl,polyStrEndsWith);function polyStrEndsWith(g,f,S){dl(g)||throwTypeError("'"+dumpObj(g)+"' is not a string");var v=dl(f)?f:_l(f),C=!isUndefined4(S)&&S<g[Xo]?S:g[Xo];return Ll(g,C-v[Xo],C)===v}var oc=Dl("indexOf",sl),lc=_unwrapFunctionWithPoly("startsWith",sl,polyStrStartsWith);function polyStrStartsWith(g,f,S){dl(g)||throwTypeError("'"+dumpObj(g)+"' is not a string");var v=dl(f)?f:_l(f),C=S>0?S:0;return Ll(g,C,C+v[Xo])===v}var cc="ref",dc="unref",hc="hasRef",uc="enabled";function _createTimerHandler(g,f,S){var v,C=!0,_=g?f($o):$o;function _unref(){return C=!1,_&&_[dc]&&_[dc](),v}function _cancel(){_&&S(_),_=$o}function _refresh(){return _=f(_),C||_unref(),v}function _setEnabled(g){!g&&_&&_cancel(),g&&!_&&_refresh()}return(v={cancel:_cancel,refresh:_refresh})[hc]=function(){return _&&_[hc]?_[hc]():C},v[cc]=function(){return C=!0,_&&_[cc]&&_[cc](),v},v[dc]=_unref,{h:v=yl(v,uc,{get:function(){return!!_},set:_setEnabled}),dn:function(){_=$o}}}function _createTimeoutWith(g,f,S){var v=ul(f),C=v?f.length:0,_=(C>0?f[0]:v?Ho:f)||setTimeout,T=(C>1?f[1]:Ho)||clearTimeout,I=S[0];S[0]=function(){b.dn(),fnApply(I,Ho,cl[el](arguments))};var b=_createTimerHandler(g,(function(g){if(g){if(g.refresh)return g.refresh(),g;fnApply(T,Ho,[g])}return fnApply(_,Ho,S)}),(function(g){fnApply(T,Ho,[g])}));return b.h}function scheduleTimeout(g,f){return _createTimeoutWith(!0,Ho,cl[el](arguments))}function scheduleTimeoutWith(g,f,S){return _createTimeoutWith(!0,g,cl[el](arguments,1))}function createTimeout(g,f){return _createTimeoutWith(!1,Ho,cl[el](arguments))}(getGlobal()||{}).Symbol,(getGlobal()||{}).Reflect;var gc,pc="hasOwnProperty",extendStaticsFn=function(g,f){return(extendStaticsFn=Uo.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f[pc](S)&&(g[S]=f[S])})(g,f)};function __extendsFn(g,f){function __(){this.constructor=g}typeof f!==ko&&null!==f&&throwTypeError("Class extends value "+String(f)+" is not a constructor or null"),extendStaticsFn(g,f),g[xo]=null===f?Zl(f):(__[xo]=f[xo],new __)}function __spreadArrayFn(g,f){for(var S=0,v=f.length,C=g.length;S<v;S++,C++)g[C]=f[S];return g}var mc="constructor",fc="prototype",Sc="function",vc="_dynInstFuncs",Cc="_isDynProxy",yc="_dynClass",Ec="_dynCls$",_c="_dynInstChk",Tc=_c,Ic="_dfOpts",bc="_unknown_",Ac="__proto__",Pc="_dyn"+Ac,Rc="__dynProto$Gbl",Mc="_dynInstProto",wc="useBaseInst",Oc="setInstFuncs",Dc=Object,Nc=Dc.getPrototypeOf,kc=Dc.getOwnPropertyNames,Lc=getGlobal(),Fc=Lc[Rc]||(Lc[Rc]={o:(gc={},gc[Oc]=!0,gc[wc]=!0,gc),n:1e3});function _isObjectOrArrayPrototype(g){return g&&(g===Dc[fc]||g===Array[fc])}function _isObjectArrayOrFunctionPrototype(g){return _isObjectOrArrayPrototype(g)||g===Function[fc]}function _getObjProto(g){var f;if(g){if(Nc)return Nc(g);var S=g[Ac]||g[fc]||(g[mc]?g[mc][fc]:null);f=g[Pc]||S,objHasOwnProperty(g,Pc)||(delete g[Mc],f=g[Pc]=g[Mc]||g[Pc],g[Mc]=S)}return f}function _forEachProp(g,f){var S=[];if(kc)S=kc(g);else for(var v in g)"string"==typeof v&&objHasOwnProperty(g,v)&&S.push(v);if(S&&S.length>0)for(var C=0;C<S.length;C++)f(S[C])}function _isDynamicCandidate(g,f,S){return f!==mc&&typeof g[f]===Sc&&(S||objHasOwnProperty(g,f))&&f!==Ac&&f!==fc}function _throwTypeError(g){throwTypeError("DynamicProto: "+g)}function _getInstanceFuncs(g){var f=Zl(null);return _forEachProp(g,(function(S){!f[S]&&_isDynamicCandidate(g,S,!1)&&(f[S]=g[S])})),f}function _hasVisited(g,f){for(var S=g.length-1;S>=0;S--)if(g[S]===f)return!0;return!1}function _getBaseFuncs(g,f,S,v){function _instFuncProxy(g,f,S){var C=f[S];if(C[Cc]&&v){var _=g[vc]||{};!1!==_[Tc]&&(C=(_[f[yc]]||{})[S]||C)}return function(){return C.apply(g,arguments)}}var C=Zl(null);_forEachProp(S,(function(g){C[g]=_instFuncProxy(f,S,g)}));for(var _=_getObjProto(g),T=[];_&&!_isObjectArrayOrFunctionPrototype(_)&&!_hasVisited(T,_);)_forEachProp(_,(function(g){!C[g]&&_isDynamicCandidate(_,g,!Nc)&&(C[g]=_instFuncProxy(f,_,g))})),T.push(_),_=_getObjProto(_);return C}function _getInstFunc(g,f,S,v){var C=null;if(g&&objHasOwnProperty(S,yc)){var _=g[vc]||Zl(null);if((C=(_[S[yc]]||Zl(null))[f])||_throwTypeError("Missing ["+f+"] "+Sc),!C[_c]&&!1!==_[Tc]){for(var T=!objHasOwnProperty(g,f),I=_getObjProto(g),b=[];T&&I&&!_isObjectArrayOrFunctionPrototype(I)&&!_hasVisited(b,I);){var A=I[f];if(A){T=A===v;break}b.push(I),I=_getObjProto(I)}try{T&&(g[f]=C),C[_c]=1}catch(g){_[Tc]=!1}}}return C}function _getProtoFunc(g,f,S){var v=f[g];return v===S&&(v=_getObjProto(f)[g]),typeof v!==Sc&&_throwTypeError("["+g+"] is not a "+Sc),v}function _populatePrototype(g,f,S,v,C){function _createDynamicPrototype(g,f){var dynProtoProxy=function(){return(_getInstFunc(this,f,g,dynProtoProxy)||_getProtoFunc(f,g,dynProtoProxy)).apply(this,arguments)};return dynProtoProxy[Cc]=1,dynProtoProxy}if(!_isObjectOrArrayPrototype(g)){var _=S[vc]=S[vc]||Zl(null);if(!_isObjectOrArrayPrototype(_)){var T=_[f]=_[f]||Zl(null);!1!==_[Tc]&&(_[Tc]=!!C),_isObjectOrArrayPrototype(T)||_forEachProp(S,(function(f){_isDynamicCandidate(S,f,!1)&&S[f]!==v[f]&&(T[f]=S[f],delete S[f],(!objHasOwnProperty(g,f)||g[f]&&!g[f][Cc])&&(g[f]=_createDynamicPrototype(g,f)))}))}}}function _checkPrototype(g,f){if(Nc){for(var S=[],v=_getObjProto(f);v&&!_isObjectArrayOrFunctionPrototype(v)&&!_hasVisited(S,v);){if(v===g)return!0;S.push(v),v=_getObjProto(v)}return!1}return!0}function _getObjName(g,f){return objHasOwnProperty(g,fc)?g.name||f||bc:((g||{})[mc]||{}).name||f||bc}function dynamicProto(g,f,S,v){objHasOwnProperty(g,fc)||_throwTypeError("theClass is an invalid class definition.");var C=g[fc];_checkPrototype(C,f)||_throwTypeError("["+_getObjName(g)+"] not in hierarchy of ["+_getObjName(f)+"]");var _=null;objHasOwnProperty(C,yc)?_=C[yc]:(_=Ec+_getObjName(g,"_")+"$"+Fc.n,Fc.n++,C[yc]=_);var T=dynamicProto[Ic],I=!!T[wc];I&&v&&void 0!==v[wc]&&(I=!!v[wc]);var b=_getInstanceFuncs(f);S(f,_getBaseFuncs(C,f,b,I));var A=!!Nc&&!!T[Oc];A&&v&&(A=!!v[Oc]),_populatePrototype(C,_,f,b,!1!==A)}dynamicProto[Ic]=Fc.o;var xc,Uc=createEnum,Vc=createTypeMap,Bc=Uc({Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5}),Hc="toLowerCase",$c="blkVal",jc="length",Gc="rdOnly",qc="notify",Wc="warnToConsole",zc="throwInternal",Kc="setDf",Jc="watch",Yc="logger",Qc="apply",Xc="push",Zc="splice",ed="hdlr",td="cancel",id="initialize",nd="identifier",rd="removeNotificationListener",sd="addNotificationListener",ad="isInitialized",od="getNotifyMgr",ld="getPlugin",cd="pollInternalLogs",dd="name",hd="time",ud="processNext",gd="getProcessTelContext",pd="enabled",md="stopPollingInternalLogs",fd="unload",Sd="onComplete",vd="version",Cd="loggingLevelConsole",yd="createNew",Ed="teardown",_d="messageId",Td="message",Id="isAsync",bd="diagLog",Ad="_doTeardown",Pd="update",Rd="getNext",Md="setNextPlugin",wd="protocol",Od="userAgent",Dd="split",Nd="nodeType",kd="replace",Ld="logInternalMessage",Fd="type",xd="handler",Ud="status",Vd="getResponseHeader",Bd="getAllResponseHeaders",Hd="isChildEvt",$d="data",jd="getCtx",Gd="setCtx",qd="complete",Wd="urlString",zd="sendPOST",Kd="headers",Jd="timeout",Yd="setRequestHeader",Qd="traceId",Xd="spanId",Zd="traceFlags";function throwAggregationError(g,f){xc||(xc=createCustomError("AggregationError",(function(g,f){f[jc]>1&&(g.errors=f[1])})));var S=g||"One or more errors occurred.";throw arrForEach(f,(function(g,f){S+="\n".concat(f," > ").concat(dumpObj(g))})),new xc(S,f||[])}var eh="Promise",th="rejected";function doAwaitResponse(g,f){return doAwait(g,(function(g){return f?f({status:"fulfilled",rejected:!1,value:g}):g}),(function(g){return f?f({status:th,rejected:!0,reason:g}):g}))}function doAwait(g,f,S,v){var C=g;try{if(isPromiseLike2(g))(f||S)&&(C=g.then(f,S));else try{f&&(C=f(g))}catch(g){if(!S)throw g;C=S(g)}}finally{v&&doFinally(C,v)}return C}function doFinally(g,f){var S=g;return f&&(isPromiseLike2(g)?S=g.finally?g.finally(f):g.then((function(g){return f(),g}),(function(g){throw f(),g})):f()),S}var ih,nh=["pending","resolving","resolved",th],rh="dispatchEvent";function _hasInitEventFn(g){var f;return g&&g.createEvent&&(f=g.createEvent("Event")),!!f&&f.initEvent}function emitEvent(g,f,S,v){var C=jl();!ih&&(ih=createCachedValue(!!safe(_hasInitEventFn,[C]).v));var _=ih.v?C.createEvent("Event"):v?new Event(f):{};if(S&&S(_),ih.v&&_.initEvent(f,!1,!0),_&&g[rh])g[rh](_);else{var T=g["on"+f];if(T)T(_);else{var I=getInst("console");I&&(I.error||I.log)(f,dumpObj(_))}}}var sh,ah="unhandledRejection",oh=ah.toLowerCase(),lh=[],ch=0,dh=10;function dumpFnObj(g){return hl(g)?g.toString():dumpObj(g)}function _createPromise(g,f,S){var v,C,_=arrSlice(arguments,3),T=0,I=!1,b=[],A=ch++,P=!1,R=null;function _then(f,S){try{return lh.push(A),P=!0,R&&R.cancel(),R=null,g((function(g,C){b.push((function(){try{var _=2===T?f:S,I=isUndefined4(_)?v:hl(_)?_(v):_;isPromiseLike2(I)?I.then(g,C):_?g(I):3===T?C(I):g(I)}catch(g){C(g)}})),I&&_processQueue()}),_)}finally{lh.pop()}}function _catch(g){return _then(void 0,g)}function _finally(g){var f=g,S=g;return hl(g)&&(f=function(f){return g&&g(),f},S=function(f){throw g&&g(),f}),_then(f,S)}function _strState(){return nh[T]}function _processQueue(){if(b.length>0){var g=b.slice();b=[],P=!0,R&&R.cancel(),R=null,f(g)}}function _createSettleIfFn(g,f){return function(S){if(T===f){if(2===g&&isPromiseLike2(S))return T=1,void S.then(_createSettleIfFn(2,1),_createSettleIfFn(3,1));T=g,I=!0,v=S,_processQueue(),P||3!==g||R||(R=scheduleTimeout(_notifyUnhandledRejection,dh))}}}function _notifyUnhandledRejection(){if(!P)if(P=!0,Jl())process.emit(ah,v,C);else{var g=Gl()||getGlobal();!sh&&(sh=createCachedValue(safe(getInst,[eh+"RejectionEvent"]).v)),emitEvent(g,oh,(function(g){return objDefine(g,"promise",{g:function(){return C}}),g.reason=v,g}),!!sh.v)}}function _toString(){return"IPromise "+_strState()+(I?" - "+dumpFnObj(v):"")}return yl(C={then:_then,catch:_catch,finally:_finally},"state",{get:_strState}),hasSymbol()&&(C[getKnownSymbol(11)]="IPromise"),C.toString=_toString,function _initialize(){hl(S)||throwTypeError(eh+": executor is not a function - "+dumpFnObj(S));var g=_createSettleIfFn(3,0);try{S.call(C,_createSettleIfFn(2,0),g)}catch(f){g(f)}}(),C}function _createAllPromise(g){return function(f){var S=arrSlice(arguments,1);return g((function(g,S){try{var v=[],C=1;iterForOf(f,(function(f,_){f&&(C++,doAwait(f,(function(f){v[_]=f,0==--C&&g(v)}),S))})),0===--C&&g(v)}catch(g){S(g)}}),S)}}function _createResolvedPromise(g){return function(f){var S=arrSlice(arguments,1);return isPromiseLike2(f)?f:g((function(g){g(f)}),S)}}function _createRejectedPromise(g){return function(f){var S=arrSlice(arguments,1);return g((function(g,S){S(f)}),S)}}function syncItemProcessor(g){arrForEach(g,(function(g){try{g()}catch(g){}}))}function timeoutItemProcessor(g){var f=pl(g)?g:0;return function(g){scheduleTimeout((function(){syncItemProcessor(g)}),f)}}function createAsyncPromise(g,f){return _createPromise(createAsyncPromise,timeoutItemProcessor(f),g,f)}var hh,uh,gh=_createAllPromise(createAsyncPromise),ph=_createResolvedPromise(createAsyncPromise),mh=_createRejectedPromise(createAsyncPromise);function createNativePromise(g,f){!hh&&(hh=createCachedValue(safe(getInst,[eh]).v||null));var S=hh.v;if(!S)return createAsyncPromise(g);hl(g)||throwTypeError(eh+": executor is not a function - "+dumpObj(g));var v=0;function _strState(){return nh[v]}var C=new S((function(f,S){function _resolve(g){v=2,f(g)}function _reject(g){v=3,S(g)}g(_resolve,_reject)}));return yl(C,"state",{get:_strState}),C}function createPromise(g,f){return!uh&&(uh=createCachedValue(createNativePromise)),uh.v.call(this,g,f)}var fh,Sh,vh=_createAllPromise(createPromise),Ch="reject",yh="Rejected",Eh=0,_h={};function _rejectDone(){}function _createError(g,f,S){!_h[g]&&(_h[g]=createCustomError(g));var v=utcNow();return new _h[g]("Task [".concat(f.id,"] ").concat(S||"","- ").concat(f.st?"Running":"Waiting",": ").concat(_calcTime(v,f.st||f.cr)))}function _calcTime(g,f){return(g-f||"0")+" ms"}function _abortStaleTasks(g,f){var S=utcNow()-f;arrForEach(g,(function(g){(g&&!g.rj&&g.st&&g.st<S||!g.st&&g.cr&&g.cr<S)&&g&&g[Ch](g.rj||_createError("Aborted",g,"Stale "))}))}function _removeTask(g,f){var S=Yl(g,f);-1!==S&&g.splice(S,1)}function _addDebugState(g,f,S){Sh=Sh||{toString:function(){return"[[SchedulerState]]"}},yl(g,fh=fh||{toString:function(){return"[[SchedulerName]]"}},{get:f}),yl(g,Sh,{get:S})}function createTaskScheduler(g,f){var S,v,C=[],_=[],T=6e5,I=T/10,b=0,A=(f?f+".":"")+Eh++;g=g||createPromise;var _startBlockedTimer=function(){var g=sc(C)+sc(_)>0;T>0&&(v||(v=scheduleTimeout((function(){_abortStaleTasks(C,T),_abortStaleTasks(_,T),v&&(v.enabled=sc(C)+sc(_)>0)}),I)).unref(),v&&(v.enabled=g))},_queueTask=function(f,v,C){var _,T=A+"."+b++;v&&(T+="-("+v+")");var I=((_={id:T,cr:utcNow(),to:C})[Ch]=function(g){I.rj=g||_createError(yh,I),I[Ch]=_rejectDone},_);return I.p=S?_waitForPreviousTask(I,S,f):g(_runTask(I,f)),S=I,I.p},_runTask=function(g,f){return g.st=utcNow(),C.push(g),_startBlockedTimer(),function(S,v){var _promiseReject=function(f){g.rj=g.rj||f||_createError(yh,g),g[Ch]=_rejectDone,_doCleanup(g),S=null,v&&v(f),v=null},C=g.id;if(g.rj)_promiseReject(g.rj);else{g[Ch]=_promiseReject;try{var _=f(C);g.to&&isPromiseLike2(_)&&(g.t=scheduleTimeout((function(){_promiseReject(_createError("Timeout",g))}),g.to)),doAwait(_,(function(f){_doCleanup(g);try{S&&S(f)}catch(g){v&&v(g)}v=null,S=null}),_promiseReject)}catch(g){_promiseReject(g)}}}},_waitForPreviousTask=function(f,S,v){return _.push(f),_startBlockedTimer(),g((function(g,C){doAwaitResponse(S.p,(function(){_removeTask(_,f),_runTask(f,v)(g,C)}))}))},_doCleanup=function(g){_removeTask(C,g),g.t&&g.t.cancel(),g.t=null,S&&S===g&&(S=null,sc(C)+sc(_)===0&&(v&&v.cancel(),v=null))},P={idle:!0,queue:_queueTask,setStaleTimeout:function(g,f){v&&v.cancel(),v=null,T=g,I=f||g/10,_startBlockedTimer()}};return objDefine(P,"idle",{g:function(){return sc(C)+sc(_)===0}}),_addDebugState(P,(function(){return A}),(function(){return{l:S,r:C,w:_}})),P}getKnownSymbol(11);var Th=void 0,Ih="",bh="channels",Ah="core",Ph="createPerfMgr",Rh="disabled",Mh="extensionConfig",wh="extensions",Oh="processTelemetry",Dh="priority",Nh="eventsSent",kh="eventsDiscarded",Lh="eventsSendRequest",Fh="perfEvent",xh="offlineEventsStored",Uh="offlineBatchSent",Vh="offlineBatchDrop",Bh="getPerfMgr",Hh="domain",$h="path",jh="Not dynamic - ",Gh=/-([a-z])/g,qh=/([^\w\d_$])/g,Wh=/^(\d+[\w\d_$])/;function isNotNullOrUndefined(g){return!isNullOrUndefined(g)}function normalizeJsName(g){var f=g;return f&&dl(f)&&(f=(f=(f=f[kd](Gh,(function(g,f){return f.toUpperCase()})))[kd](qh,"_"))[kd](Wh,(function(g,f){return"_"+f}))),f}function strContains(g,f){return!(!g||!f)&&-1!==oc(g,f)}function toISOString(g){return g&&g.toISOString()||""}function getExceptionName(g){return fl(g)?g[dd]:Ih}function setValue(g,f,S,v,C){var _=S;return g&&((_=g[f])===S||C&&!C(_)||v&&!v(S)||(_=S,g[f]=_)),_}function getSetValue(g,f,S){var v;return g?!(v=g[f])&&isNullOrUndefined(v)&&(v=isUndefined4(S)?{}:S,g[f]=v):v=isUndefined4(S)?{}:S,v}function _createProxyFunction(g,f){var S=null,v=null;return hl(g)?S=g:v=g,function(){var g=arguments;if(S&&(v=S()),v)return v[f][Qc](v,g)}}function proxyFunctionAs(g,f,S,v,C){g&&f&&S&&(!1!==C||isUndefined4(g[f]))&&(g[f]=_createProxyFunction(S,v))}function proxyFunctions(g,f,S,v){return g&&f&&isObject3(g)&&ul(S)&&arrForEach(S,(function(S){dl(S)&&proxyFunctionAs(g,S,f,S,v)})),g}function optimizeObject(g){return g&&bl&&(g=Uo(bl({},g))),g}function objExtend(g,f,S,v,C,_){var T=arguments,I=T[0]||{},b=T[jc],A=!1,P=1;for(b>0&&ml(I)&&(A=I,I=T[P]||{},P++),isObject3(I)||(I={});P<b;P++){var R=T[P],M=ul(R),w=isObject3(R);for(var O in R){if(M&&O in R||w&&vl(R,O)){var D=R[O],N=void 0;if(A&&D&&((N=ul(D))||isPlainObject(D))){var k=I[O];N?ul(k)||(k=[]):isPlainObject(k)||(k={}),D=objExtend(A,k,D)}void 0!==D&&(I[O]=D)}}}return I}function getResponseText(g){try{return g.responseText}catch(g){}return null}function formatErrorMessageXdr(g,f){return g?"XDomainRequest,Response:"+getResponseText(g)||"":f}function formatErrorMessageXhr(g,f){return g?"XMLHttpRequest,Status:"+g[Ud]+",Response:"+getResponseText(g)||g.response||"":f}function prependTransports(g,f){return f&&(pl(f)?g=[f].concat(g):ul(f)&&(g=f.concat(g))),g}var zh="Microsoft_ApplicationInsights_BypassAjaxInstrumentation",Kh="withCredentials",Jh="timeout";function openXhr(g,f,S,v,C,_){function _wrapSetXhrProp(g,f,S){try{g[f]=S}catch(g){}}void 0===v&&(v=!1),void 0===C&&(C=!1);var T=new XMLHttpRequest;return v&&_wrapSetXhrProp(T,zh,v),S&&_wrapSetXhrProp(T,Kh,S),T.open(g,f,!C),S&&_wrapSetXhrProp(T,Kh,S),!C&&_&&_wrapSetXhrProp(T,Jh,_),T}function convertAllHeadersToMap(g){var f={};dl(g)&&arrForEach(nc(g)[Dd](/[\r\n]+/),(function(g){if(g){var S=g.indexOf(": ");if(-1!==S){var v=nc(g.substring(0,S))[Hc](),C=nc(g.substring(S+1));f[v]=C}else f[nc(g)]=1}}));return f}function _appendHeader(g,f,S){if(!g[S]&&f&&f[Vd]){var v=f[Vd](S);v&&(g[S]=nc(v))}return g}var Yh="kill-duration",Qh="kill-duration-seconds",Xh="time-delta-millis";function _getAllResponseHeaders(g,f){var S={};return g[Bd]?S=convertAllHeadersToMap(g[Bd]()):f&&(S=_appendHeader(S,g,Xh),S=_appendHeader(S,g,Yh),S=_appendHeader(S,g,Qh)),S}var Zh="location",eu="console",tu="JSON",iu="crypto",nu="msCrypto",ru="ReactNative",su="msie",au="trident/",ou="XMLHttpRequest",lu=null,cu=null,du=!1,hu=null,uu=null;function _hasProperty(g,f){var S=!1;if(g){try{if(!(S=f in g)){var v=g[xo];v&&(S=f in v)}}catch(g){}if(!S)try{S=!isUndefined4((new g)[f])}catch(g){}}return S}function getLocation(g){if(g&&du){var f=getInst("__mockLocation");if(f)return f}return typeof location===Lo&&location?location:getInst(Zh)}function getConsole(){return typeof console!==Fo?console:getInst(eu)}function hasJSON(){return Boolean(typeof JSON===Lo&&JSON||null!==getInst(tu))}function getJSON(){return hasJSON()?JSON||getInst(tu):null}function getCrypto(){return getInst(iu)}function getMsCrypto(){return getInst(nu)}function isReactNative(){var g=Kl();return!(!g||!g.product)&&g.product===ru}function isIE(){var g=Kl();if(g&&(g[Od]!==cu||null===lu)){var f=((cu=g[Od])||Ih)[Hc]();lu=strContains(f,su)||strContains(f,au)}return lu}function isBeaconsSupported(g){return null!==uu&&!1!==g||(uu=hasNavigator()&&Boolean(Kl().sendBeacon)),uu}function isFetchSupported(g){var f=!1;try{f=!!getInst("fetch");var S=getInst("Request");f&&g&&S&&(f=_hasProperty(S,"keepalive"))}catch(g){}return f}function useXDomainRequest(){return null===hu&&(hu=typeof XDomainRequest!==Fo)&&isXhrSupported()&&(hu=hu&&!_hasProperty(getInst(ou),"withCredentials")),hu}function isXhrSupported(){var g=!1;try{g=!!getInst(ou)}catch(g){}return g}var gu=4294967296,pu=4294967295,mu=123456789,fu=987654321,Su=!1,vu=mu,Cu=fu;function _mwcSeed(g){g<0&&(g>>>=0),vu=mu+g&pu,Cu=fu-g&pu,Su=!0}function _autoSeedMwc(){try{var g=2147483647&utcNow();_mwcSeed((Math.random()*gu^g)+g)}catch(g){}}function random32(g){var f=0,S=getCrypto()||getMsCrypto();return S&&S.getRandomValues&&(f=S.getRandomValues(new Uint32Array(1))[0]&pu),0===f&&isIE()&&(Su||_autoSeedMwc(),f=mwcRandom32()&pu),0===f&&(f=Math.floor(gu*Math.random()|0)),g||(f>>>=0),f}function mwcRandom32(g){var f=((Cu=36969*(65535&Cu)+(Cu>>16)&pu)<<16)+(65535&(vu=18e3*(65535&vu)+(vu>>16)&pu))>>>0&pu|0;return g||(f>>>=0),f}function newId(g){void 0===g&&(g=22);for(var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S=random32()>>>0,v=0,C=Ih;C[jc]<g;)v++,C+=f.charAt(63&S),S>>>=6,5===v&&(S=(random32()<<2&4294967295|3&S)>>>0,v=0);return C}var yu="3.2.1",Eu="."+newId(6),_u=0;function _canAcceptData(g){return 1===g[Nd]||9===g[Nd]||!+g[Nd]}function _getCache(g,f){var S=f[g.id];if(!S){S={};try{_canAcceptData(f)&&objDefine(f,g.id,{e:!1,v:S})}catch(g){}}return S}function createUniqueNamespace(g,f){return void 0===f&&(f=!1),normalizeJsName(g+_u+++(f?"."+yu:Ih)+Eu)}function createElmNodeData(g){var f={id:createUniqueNamespace("_aiData-"+(g||Ih)+"."+yu),accept:function(g){return _canAcceptData(g)},get:function(g,S,v,C){var _=g[f.id];return _?_[normalizeJsName(S)]:(C&&((_=_getCache(f,g))[normalizeJsName(S)]=v),v)},kill:function(g,f){if(g&&g[f])try{delete g[f]}catch(g){}}};return f}function _isConfigDefaults(g){return g&&isObject3(g)&&(g.isVal||g.fb||vl(g,"v")||vl(g,"mrg")||vl(g,"ref")||g.set)}function _getDefault(g,f,S){var v,C=S.dfVal||isDefined2;if(f&&S.fb){var _=S.fb;ul(_)||(_=[_]);for(var T=0;T<_[jc];T++){var I=_[T],b=f[I];if(C(b)?v=b:g&&(C(b=g.cfg[I])&&(v=b),g.set(g.cfg,_l(I),b)),C(v))break}}return!C(v)&&C(S.v)&&(v=S.v),v}function _resolveDefaultValue(g,f,S){var v,C=S;(S&&_isConfigDefaults(S)&&(C=_getDefault(g,f,S)),C)&&(_isConfigDefaults(C)&&(C=_resolveDefaultValue(g,f,C)),ul(C)?(v=[])[jc]=C[jc]:isPlainObject(C)&&(v={}),v&&(objForEachKey(C,(function(S,C){C&&_isConfigDefaults(C)&&(C=_resolveDefaultValue(g,f,C)),v[S]=C})),C=v));return C}function _applyDefaultValue(g,f,S,v){var C,_,T,I,b,A,P,R,M=v;_isConfigDefaults(M)?(C=M.isVal,_=M.set,A=M[Gc],P=M[$c],I=M.mrg,!(b=M.ref)&&isUndefined4(b)&&(b=!!I),T=_getDefault(g,f,M)):T=v,P&&g[$c](f,S);var w=!0,O=f[S];!O&&isNullOrUndefined(O)||(R=O,w=!1,C&&R!==T&&!C(R)&&(R=T,w=!0),_&&(w=(R=_(R,T,f))===T)),w?R=T?_resolveDefaultValue(g,f,T):T:(isPlainObject(R)||ul(T))&&I&&T&&(isPlainObject(T)||ul(T))&&objForEachKey(T,(function(f,S){_applyDefaultValue(g,R,f,S)})),g.set(f,S,R),b&&g.ref(f,S),A&&g[Gc](f,S)}var Tu=symbolFor("[[ai_dynCfg_1]]"),Iu=symbolFor("[[ai_blkDynCfg_1]]"),bu=symbolFor("[[ai_frcDynCfg_1]]");function _cfgDeepCopy(g){var f;if(g&&(ul(g)?(f=[])[jc]=g[jc]:isPlainObject(g)&&(f={}),f))return objForEachKey(g,(function(g,S){f[g]=_cfgDeepCopy(S)})),f;return g}function getDynamicConfigHandler(g){if(g){var f=g[Tu]||g;if(f.cfg&&(f.cfg===g||f.cfg[Tu]===f))return f}return null}function blockDynamicConversion(g){if(g&&(isPlainObject(g)||ul(g)))try{g[Iu]=!0}catch(g){}return g}function _canMakeDynamic(g,f,S){var v=!1;return S&&!g[f.blkVal]&&((v=S[bu])||S[Iu]||(v=isPlainObject(S)||ul(S))),v}function throwInvalidAccess(g){throwTypeError("InvalidAccess:"+g)}var Au=["push","pop","shift","unshift","splice"],_throwDynamicError=function(g,f,S,v){g&&g[zc](3,108,"".concat(S," [").concat(f,"] failed - ")+dumpObj(v))};function _patchArray(g,f,S){ul(f)&&arrForEach(Au,(function(v){var C=f[v];f[v]=function(){for(var v=[],_=0;_<arguments.length;_++)v[_]=arguments[_];var T=C[Qc](this,v);return _makeDynamicObject(g,f,S,"Patching"),T}}))}function _getOwnPropGetter(g,f){var S=Sl(g,f);return S&&S.get}function _createDynamicProperty(g,f,S,v){var C={n:S,h:[],trk:function(f){f&&f.fn&&(-1===Yl(C.h,f)&&C.h[Xc](f),g.trk(f,C))},clr:function(g){var f=Yl(C.h,g);-1!==f&&C.h[Zc](f,1)}},_=!0,T=!1;function _getProperty(){_&&(T=T||_canMakeDynamic(_getProperty,g,v),v&&!v[Tu]&&T&&(v=_makeDynamicObject(g,v,S,"Converting")),_=!1);var f=g.act;return f&&C.trk(f),v}function _setProperty(I){if(v!==I){_getProperty[g.ro]&&!g.upd&&throwInvalidAccess("["+S+"] is read-only:"+dumpObj(f)),_&&(T=T||_canMakeDynamic(_getProperty,g,v),_=!1);var b=T&&_getProperty[g.rf];if(T)if(b){objForEachKey(v,(function(g){v[g]=I?I[g]:Th}));try{objForEachKey(I,(function(f,S){_setDynamicProperty(g,v,f,S)})),I=v}catch(f){_throwDynamicError((g.hdlr||{})[Yc],S,"Assigning",f),T=!1}}else v&&v[Tu]&&objForEachKey(v,(function(f){var S=_getOwnPropGetter(v,f);if(S){var C=S[g.prop];C&&C.chng()}}));if(I!==v){var A=I&&_canMakeDynamic(_getProperty,g,I);!b&&A&&(I=_makeDynamicObject(g,I,S,"Converting")),v=I,T=A}g.add(C)}}_getProperty[g.prop]={chng:function(){g.add(C)}},objDefine(f,C.n,{g:_getProperty,s:_setProperty})}function _setDynamicProperty(g,f,S,v){if(f){var C=_getOwnPropGetter(f,S);C&&!!C[g.prop]?f[S]=v:_createDynamicProperty(g,f,S,v)}return f}function _setDynamicPropertyState(g,f,S,v){if(f){var C=_getOwnPropGetter(f,S),_=C&&!!C[g.prop],T=v&&v[0],I=v&&v[1],b=v&&v[2];if(!_){if(b)try{blockDynamicConversion(f)}catch(f){_throwDynamicError((g.hdlr||{})[Yc],S,"Blocking",f)}try{_setDynamicProperty(g,f,S,f[S]),C=_getOwnPropGetter(f,S)}catch(f){_throwDynamicError((g.hdlr||{})[Yc],S,"State",f)}}T&&(C[g.rf]=T),I&&(C[g.ro]=I),b&&(C[g.blkVal]=!0)}return f}function _makeDynamicObject(g,f,S,v){try{objForEachKey(f,(function(S,v){_setDynamicProperty(g,f,S,v)})),f[Tu]||(yl(f,Tu,{get:function(){return g[ed]}}),_patchArray(g,f,S))}catch(f){_throwDynamicError((g.hdlr||{})[Yc],S,v,f)}return f}var Pu="[[ai_",Ru="]]";function _createState(g){var f,S,v=newSymbol(Pu+"get"+g.uid+Ru),C=newSymbol(Pu+"ro"+g.uid+Ru),_=newSymbol(Pu+"rf"+g.uid+Ru),T=newSymbol(Pu+"blkVal"+g.uid+Ru),I=newSymbol(Pu+"dtl"+g.uid+Ru),b=null,A=null;function _useHandler(f,v){var C=S.act;try{S.act=f,f&&f[I]&&(arrForEach(f[I],(function(g){g.clr(f)})),f[I]=[]),v({cfg:g.cfg,set:g.set.bind(g),setDf:g[Kc].bind(g),ref:g.ref.bind(g),rdOnly:g[Gc].bind(g)})}catch(f){var _=g[Yc];throw _&&_[zc](1,107,dumpObj(f)),f}finally{S.act=C||null}}function _notifyWatchers(){if(b){var g=b;b=null,A&&A[td](),A=null;var f=[];if(arrForEach(g,(function(g){if(g&&(g[I]&&(arrForEach(g[I],(function(f){f.clr(g)})),g[I]=null),g.fn))try{_useHandler(g,g.fn)}catch(g){f[Xc](g)}})),b)try{_notifyWatchers()}catch(g){f[Xc](g)}f[jc]>0&&throwAggregationError("Watcher error(s): ",f)}}function _addWatcher(g){if(g&&g.h[jc]>0){b||(b=[]),A||(A=scheduleTimeout((function(){A=null,_notifyWatchers()}),0));for(var f=0;f<g.h[jc];f++){var S=g.h[f];S&&-1===Yl(b,S)&&b[Xc](S)}}}function _trackHandler(g,f){if(g){var S=g[I]=g[I]||[];-1===Yl(S,f)&&S[Xc](f)}}return(f={prop:v,ro:C,rf:_})[$c]=T,f[ed]=g,f.add=_addWatcher,f[qc]=_notifyWatchers,f.use=_useHandler,f.trk=_trackHandler,S=f}function _createAndUseHandler(g,f){var S={fn:f,rm:function(){S.fn=null,g=null,f=null}};return objDefine(S,"toJSON",{v:function(){return"WatcherHandler"+(S.fn?"":"[X]")}}),g.use(S,f),S}function _createDynamicHandler(g,f,S){var v,C=getDynamicConfigHandler(f);if(C)return C;var _,T=createUniqueNamespace("dyncfg",!0),I=f&&!1!==S?f:_cfgDeepCopy(f);function _notifyWatchers(){_[qc]()}function _setValue(f,S,v){try{f=_setDynamicProperty(_,f,S,v)}catch(f){_throwDynamicError(g,S,"Setting value",f)}return f[S]}function _watch(g){return _createAndUseHandler(_,g)}function _block(g,f){_.use(null,(function(S){var v=_.upd;try{isUndefined4(f)||(_.upd=f),g(S)}finally{_.upd=v}}))}function _ref(g,f){var S;return _setDynamicPropertyState(_,g,f,(S={},S[0]=!0,S))[f]}function _rdOnly(g,f){var S;return _setDynamicPropertyState(_,g,f,(S={},S[1]=!0,S))[f]}function _blkPropValue(g,f){var S;return _setDynamicPropertyState(_,g,f,(S={},S[2]=!0,S))[f]}function _applyDefaults(g,f){return f&&objForEachKey(f,(function(f,S){_applyDefaultValue(b,g,f,S)})),g}var b=((v={uid:null,cfg:I})[Yc]=g,v[qc]=_notifyWatchers,v.set=_setValue,v[Kc]=_applyDefaults,v[Jc]=_watch,v.ref=_ref,v[Gc]=_rdOnly,v[$c]=_blkPropValue,v._block=_block,v);return objDefine(b,"uid",{c:!1,e:!1,w:!1,v:T}),_makeDynamicObject(_=_createState(b),I,"config","Creating"),b}function _logInvalidAccess(g,f){g?(g[Wc](f),g[zc](2,108,f)):throwInvalidAccess(f)}function createDynamicConfig(g,f,S,v){var C=_createDynamicHandler(S,g||{},v);return f&&C[Kc](C.cfg,f),C}function onConfigChange(g,f,S){var v=g[Tu]||g;return!v.cfg||v.cfg!==g&&v.cfg[Tu]!==v?(_logInvalidAccess(S,jh+dumpObj(g)),createDynamicConfig(g,null,S)[Jc](f)):v[Jc](f)}function runTargetUnload(g,f){if(g&&g[fd])return g[fd](f)}function doUnloadAll(g,f,S){var v;return S||(v=createPromise((function(g){S=g}))),g&&sc(g)>0?doAwaitResponse(runTargetUnload(g[0],f),(function(){doUnloadAll(arrSlice(g,1),f,S)})):S(),v}var Mu=500,wu="Microsoft_ApplicationInsights_BypassAjaxInstrumentation";function cfgDfMerge(g){return{mrg:!0,v:g}}function cfgDfString(g){return{isVal:dl,v:_l(g||Ih)}}var Ou,Du,Nu=[Nh,kh,Lh,Fh],ku=null;function _listenerProxyFunc(g,f){return function(){var S=arguments,v=getDebugExt(f);if(v){var C=v.listener;C&&C[g]&&C[g][Qc](C,S)}}}function _getExtensionNamespace(){var g=getInst("Microsoft");return g&&(ku=g.ApplicationInsights),ku}function getDebugExt(g){var f=ku;return f||!0===g.disableDbgExt||(f=ku||_getExtensionNamespace()),f?f.ChromeDbgExt:null}function getDebugListener(g){if(!Ou){Ou={};for(var f=0;f<Nu[jc];f++)Ou[Nu[f]]=_listenerProxyFunc(Nu[f],g)}return Ou}var Lu="warnToConsole",Fu="AI (Internal): ",xu="AI: ",Uu="AITR_",Vu={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},Bu=((Du={})[0]=null,Du[1]="errorToConsole",Du[2]=Lu,Du[3]="debugToConsole",Du);function _sanitizeDiagnosticText(g){return g?'"'+g[kd](/\"/g,Ih)+'"':Ih}function _logToConsole(g,f){var S=getConsole();if(S){var v="log";S[g]&&(v=g),hl(S[v])&&S[v](f)}}var Hu=function(){function _InternalLogMessage3(g,f,S,v){void 0===S&&(S=!1);var C=this;C[_d]=g,C[Td]=(S?xu:Fu)+g;var _=Ih;hasJSON()&&(_=getJSON().stringify(v));var T=(f?" message:"+_sanitizeDiagnosticText(f):Ih)+(v?" props:"+_sanitizeDiagnosticText(_):Ih);C[Td]+=T}return _InternalLogMessage3.dataType="MessageData",_InternalLogMessage3}();function safeGetLogger(g,f){return(g||{})[Yc]||new Gu(f)}var $u,ju,Gu=function(){function DiagnosticLogger3(g){this.identifier="DiagnosticLogger",this.queue=[];var f,S,v,C,_,T=0,I={};dynamicProto(DiagnosticLogger3,this,(function(b){function _logInternalMessage3(g,f){if(!_areInternalMessagesThrottled()){var C=!0,_=Uu+f[_d];if(I[_]?C=!1:I[_]=!0,C&&(g<=S&&(b.queue[Xc](f),T++,_debugExtMsg(1===g?"error":"warn",f)),T===v)){var A="Internal events throttle limit per PageView reached for this app.",P=new Hu(23,A,!1);b.queue[Xc](P),1===g?b.errorToConsole(A):b[Wc](A)}}}function _setDefaultsFromConfig(g){return onConfigChange(createDynamicConfig(g,Vu,b).cfg,(function(g){var _=g.cfg;f=_[Cd],S=_.loggingLevelTelemetry,v=_.maxMessageLimit,C=_.enableDebug}))}function _areInternalMessagesThrottled(){return T>=v}function _debugExtMsg(f,S){var v=getDebugExt(g||{});v&&v[bd]&&v[bd](f,S)}_=_setDefaultsFromConfig(g||{}),b.consoleLoggingLevel=function(){return f},b[zc]=function(g,S,v,_,T){void 0===T&&(T=!1);var A=new Hu(S,v,T,_);if(C)throw dumpObj(A);var P=Bu[g]||Lu;if(isUndefined4(A[Td]))_debugExtMsg("throw"+(1===g?"Critical":"Warning"),A);else{if(T){var R=+A[_d];!I[R]&&f>=g&&(b[P](A[Td]),I[R]=!0)}else f>=g&&b[P](A[Td]);_logInternalMessage3(g,A)}},b.debugToConsole=function(g){_logToConsole("debug",g),_debugExtMsg("warning",g)},b[Wc]=function(g){_logToConsole("warn",g),_debugExtMsg("warning",g)},b.errorToConsole=function(g){_logToConsole("error",g),_debugExtMsg("error",g)},b.resetInternalMessageCount=function(){T=0,I={}},b[Ld]=_logInternalMessage3,b[fd]=function(g){_&&_.rm(),_=null}}))}return DiagnosticLogger3.__ieDyn=1,DiagnosticLogger3}();function _getLogger(g){return g||new Gu}function _throwInternal(g,f,S,v,C,_){void 0===_&&(_=!1),_getLogger(g)[zc](f,S,v,C,_)}function _warnToConsole(g,f){_getLogger(g)[Wc](f)}var qu,Wu="toGMTString",zu="toUTCString",Ku="cookie",Ju="expires",Yu="isCookieUseDisabled",Qu="disableCookiesUsage",Xu="_ckMgr",Zu=null,eg=null,tg=null,ig={},ng={},rg=(($u={cookieCfg:cfgDfMerge((ju={},ju[Hh]={fb:"cookieDomain",dfVal:isNotNullOrUndefined},ju.path={fb:"cookiePath",dfVal:isNotNullOrUndefined},ju.enabled=Th,ju.ignoreCookies=Th,ju.blockedCookies=Th,ju)),cookieDomain:Th,cookiePath:Th})[Qu]=Th,$u);function _getDoc(){!qu&&(qu=getLazy((function(){return jl()})))}function _gblCookieMgr(g,f){var S=createCookieMgr[Xu]||ng[Xu];return S||(S=createCookieMgr[Xu]=createCookieMgr(g,f),ng[Xu]=S),S}function _isMgrEnabled(g){return!g||g.isEnabled()}function _isIgnoredCookie(g,f){return!!(f&&g&&ul(g.ignoreCookies))&&-1!==Yl(g.ignoreCookies,f)}function _isBlockedCookie(g,f){return!!(f&&g&&ul(g.blockedCookies)&&-1!==Yl(g.blockedCookies,f))||_isIgnoredCookie(g,f)}function _isCfgEnabled(g,f){var S=f[pd];if(isNullOrUndefined(S)){var v=void 0;isUndefined4(g[Yu])||(v=!g[Yu]),isUndefined4(g[Qu])||(v=!g[Qu]),S=v}return S}function safeGetCookieMgr(g,f){var S;if(g)S=g.getCookieMgr();else if(f){var v=f.cookieCfg;S=v&&v[Xu]?v[Xu]:createCookieMgr(f)}return S||(S=_gblCookieMgr(f,(g||{})[Yc])),S}function createCookieMgr(g,f){var S,v,C,_,T,I,b,A,P;g=createDynamicConfig(g||ng,null,f).cfg,T=onConfigChange(g,(function(f){f[Kc](f.cfg,rg),v=f.ref(f.cfg,"cookieCfg"),C=v[$h]||"/",_=v[Hh],I=!1!==_isCfgEnabled(g,v),b=v.getCookie||_getCookieValue,A=v.setCookie||_setCookieValue,P=v.delCookie||_setCookieValue}),f);var R=((S={isEnabled:function(){var S=!1!==_isCfgEnabled(g,v)&&I&&areCookiesSupported(f),C=ng[Xu];return S&&C&&R!==C&&(S=_isMgrEnabled(C)),S},setEnabled:function(g){I=!1!==g,v[pd]=g},set:function(g,f,S,T,I){var b=!1;if(_isMgrEnabled(R)&&!_isBlockedCookie(v,g)){var P={},M=nc(f||Ih),w=oc(M,";");if(-1!==w&&(M=nc(strLeft(f,w)),P=_extractParts(Ll(f,w+1))),setValue(P,Hh,T||_,isTruthy,isUndefined4),!isNullOrUndefined(S)){var O=isIE();if(isUndefined4(P[Ju])){var D=utcNow()+1e3*S;if(D>0){var N=new Date;N.setTime(D),setValue(P,Ju,_formatDate(N,O?Wu:zu)||_formatDate(N,O?Wu:zu)||Ih,isTruthy)}}O||setValue(P,"max-age",Ih+S,null,isUndefined4)}var k=getLocation();k&&"https:"===k[wd]&&(setValue(P,"secure",null,null,isUndefined4),null===eg&&(eg=!uaDisallowsSameSiteNone((Kl()||{})[Od])),eg&&setValue(P,"SameSite","None",null,isUndefined4)),setValue(P,$h,I||C,null,isUndefined4),A(g,_formatCookieValue(M,P)),b=!0}return b},get:function(g){var f=Ih;return _isMgrEnabled(R)&&!_isIgnoredCookie(v,g)&&(f=b(g)),f},del:function(g,f){var S=!1;return _isMgrEnabled(R)&&(S=R.purge(g,f)),S},purge:function(g,S){var v,C=!1;if(areCookiesSupported(f)){var _=((v={})[$h]=S||"/",v[Ju]="Thu, 01 Jan 1970 00:00:01 GMT",v);isIE()||(_["max-age"]="0"),P(g,_formatCookieValue(Ih,_)),C=!0}return C}})[fd]=function(g){T&&T.rm(),T=null},S);return R[Xu]=R,R}function areCookiesSupported(g){if(null===Zu){Zu=!1,!qu&&_getDoc();try{var f=qu.v||{};Zu=void 0!==f[Ku]}catch(f){_throwInternal(g,2,68,"Cannot access document.cookie - "+getExceptionName(f),{exception:dumpObj(f)})}}return Zu}function _extractParts(g){var f={};g&&g[jc]&&arrForEach(nc(g)[Dd](";"),(function(g){if(g=nc(g||Ih)){var S=oc(g,"=");-1===S?f[g]=null:f[nc(strLeft(g,S))]=nc(Ll(g,S+1))}}));return f}function _formatDate(g,f){return hl(g[f])?g[f]():null}function _formatCookieValue(g,f){var S=g||Ih;return objForEachKey(f,(function(g,f){S+="; "+g+(isNullOrUndefined(f)?Ih:"="+f)})),S}function _getCookieValue(g){var f=Ih;if(!qu&&_getDoc(),qu.v){var S=qu.v[Ku]||Ih;tg!==S&&(ig=_extractParts(S),tg=S),f=nc(ig[g]||Ih)}return f}function _setCookieValue(g,f){!qu&&_getDoc(),qu.v&&(qu.v[Ku]=g+"="+f)}function uaDisallowsSameSiteNone(g){return!!dl(g)&&(!(!strContains(g,"CPU iPhone OS 12")&&!strContains(g,"iPad; CPU OS 12"))||(!!(strContains(g,"Macintosh; Intel Mac OS X 10_14")&&strContains(g,"Version/")&&strContains(g,"Safari"))||(!(!strContains(g,"Macintosh; Intel Mac OS X 10_14")||!ac(g,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))||(!(!strContains(g,"Chrome/5")&&!strContains(g,"Chrome/6"))||(!(!strContains(g,"UnrealEngine")||strContains(g,"Chrome"))||!(!strContains(g,"UCBrowser/12")&&!strContains(g,"UCBrowser/11")))))))}var sg={perfEvtsSendAll:!1};function _runScheduledListeners(g){g.h=null;var f=g.cb;g.cb=[],arrForEach(f,(function(g){safe(g.fn,[g.arg])}))}function _runListeners(g,f,S,v){arrForEach(g,(function(g){g&&g[f]&&(S?(S.cb[Xc]({fn:v,arg:g}),S.h=S.h||scheduleTimeout(_runScheduledListeners,0,S)):safe(v,[g]))}))}var ag=function(){function NotificationManager3(g){var f,S;this.listeners=[];var v=[],C={h:null,cb:[]},_=createDynamicConfig(g,sg);S=_[Jc]((function(g){f=!!g.cfg.perfEvtsSendAll})),dynamicProto(NotificationManager3,this,(function(g){objDefine(g,"listeners",{g:function(){return v}}),g[sd]=function(g){v[Xc](g)},g[rd]=function(g){for(var f=Yl(v,g);f>-1;)v[Zc](f,1),f=Yl(v,g)},g[Nh]=function(g){_runListeners(v,Nh,C,(function(f){f[Nh](g)}))},g[kh]=function(g,f){_runListeners(v,kh,C,(function(S){S[kh](g,f)}))},g[Lh]=function(g,f){_runListeners(v,Lh,f?C:null,(function(S){S[Lh](g,f)}))},g[Fh]=function(g){g&&(!f&&g[Hd]()||_runListeners(v,Fh,null,(function(f){g[Id]?scheduleTimeout((function(){return f[Fh](g)}),0):f[Fh](g)})))},g[xh]=function(g){g&&g[jc]&&_runListeners(v,xh,C,(function(f){f[xh](g)}))},g[Uh]=function(g){g&&g[$d]&&_runListeners(v,Uh,C,(function(f){f[Uh](g)}))},g[Vh]=function(g,f){if(g>0){var S=f||0;_runListeners(v,Vh,C,(function(f){f[Vh](g,S)}))}},g[fd]=function(g){var f,_finishUnload=function(){S&&S.rm(),S=null,v=[],C.h&&C.h[td](),C.h=null,C.cb=[]};if(_runListeners(v,"unload",null,(function(S){var v=S[fd](g);v&&(f||(f=[]),f[Xc](v))})),f)return createPromise((function(g){return doAwaitResponse(vh(f),(function(){_finishUnload(),g()}))}));_finishUnload()}}))}return NotificationManager3.__ieDyn=1,NotificationManager3}(),og="ctx",lg="ParentContextKey",cg="ChildrenContextKey",dg=null,hg=function(){function PerfEvent3(g,f,S){var v,C=this;(C.start=utcNow(),C[dd]=g,C[Id]=S,C[Hd]=function(){return!1},hl(f))&&objDefine(C,"payload",{g:function(){return!v&&hl(f)&&(v=f(),f=null),v}});C[jd]=function(g){return g?g===PerfEvent3[lg]||g===PerfEvent3[cg]?C[g]:(C[og]||{})[g]:null},C[Gd]=function(g,f){if(g)if(g===PerfEvent3[lg])C[g]||(C[Hd]=function(){return!0}),C[g]=f;else if(g===PerfEvent3[cg])C[g]=f;else{(C[og]=C[og]||{})[g]=f}},C[qd]=function(){var g=0,f=C[jd](PerfEvent3[cg]);if(ul(f))for(var S=0;S<f[jc];S++){var v=f[S];v&&(g+=v[hd])}C[hd]=utcNow()-C.start,C.exTime=C[hd]-g,C[qd]=function(){}}}return PerfEvent3.ParentContextKey="parent",PerfEvent3.ChildrenContextKey="childEvts",PerfEvent3}(),ug=function(){function PerfManager3(g){this.ctx={},dynamicProto(PerfManager3,this,(function(f){f.create=function(g,f,S){return new hg(g,f,S)},f.fire=function(f){f&&(f[qd](),g&&hl(g[Fh])&&g[Fh](f))},f[Gd]=function(g,S){g&&((f[og]=f[og]||{})[g]=S)},f[jd]=function(g){return(f[og]||{})[g]}}))}return PerfManager3.__ieDyn=1,PerfManager3}(),gg="CoreUtils.doPerf";function doPerf(g,f,S,v,C){if(g){var _=g;if(_[Bh]&&(_=_[Bh]()),_){var T=void 0,I=_[jd](gg);try{if(T=_.create(f(),v,C)){if(I&&T[Gd]&&(T[Gd](hg[lg],I),I[jd]&&I[Gd])){var b=I[jd](hg[cg]);b||(b=[],I[Gd](hg[cg],b)),b[Xc](T)}return _[Gd](gg,T),S(T)}}catch(g){T&&T[Gd]&&T[Gd]("exception",g)}finally{T&&_.fire(T),_[Gd](gg,I)}}}return S()}function getGblPerfMgr(){return dg}function newGuid2(){var g=generateW3CId();return Ll(g,0,8)+"-"+Ll(g,8,12)+"-"+Ll(g,12,16)+"-"+Ll(g,16,20)+"-"+Ll(g,20)}function generateW3CId(){for(var g,f=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],S=Ih,v=0;v<4;v++)S+=f[15&(g=random32())]+f[g>>4&15]+f[g>>8&15]+f[g>>12&15]+f[g>>16&15]+f[g>>20&15]+f[g>>24&15]+f[g>>28&15];var C=f[8+(3&random32())|0];return Fl(S,0,8)+Fl(S,9,4)+"4"+Fl(S,13,3)+C+Fl(S,16,3)+Fl(S,19,12)}var pg="00000000000000000000000000000000",mg="0000000000000000";function _isValid(g,f,S){return!(!g||g[jc]!==f||g===S)&&!!g.match(/^[\da-f]*$/i)}function isValidTraceId(g){return _isValid(g,32,pg)}function isValidSpanId(g){return _isValid(g,16,mg)}var fg=createElmNodeData("plugin");function _getPluginState(g){return fg.get(g,"state",{},!0)}function initializePlugins(g,f){for(var S,v=[],C=null,_=g[Rd]();_;){var T=_[ld]();if(T){C&&C[Md]&&T[Oh]&&C[Md](T);var I=!!(S=_getPluginState(T))[ad];T[ad]&&(I=T[ad]()),I||v[Xc](T),C=T,_=_[Rd]()}}arrForEach(v,(function(v){var C=g[Ah]();v[id](g.getCfg(),C,f,g[Rd]()),S=_getPluginState(v),v[Ah]||S[Ah]||(S[Ah]=C),S[ad]=!0,delete S[Ed]}))}function sortPlugins(g){return g.sort((function(g,f){var S=0;if(f){var v=f[Oh];g[Oh]?S=v?g[Dh]-f[Dh]:1:v&&(S=-1)}else S=g?1:-1;return S}))}function createDistributedTraceContext(g){var f={};return{getName:function(){return f[dd]},setName:function(S){g&&g.setName(S),f[dd]=S},getTraceId:function(){return f[Qd]},setTraceId:function(S){g&&g.setTraceId(S),isValidTraceId(S)&&(f[Qd]=S)},getSpanId:function(){return f[Xd]},setSpanId:function(S){g&&g.setSpanId(S),isValidSpanId(S)&&(f[Xd]=S)},getTraceFlags:function(){return f[Zd]},setTraceFlags:function(S){g&&g.setTraceFlags(S),f[Zd]=S}}}var Sg,vg="TelemetryPluginChain",Cg="_hasRun",yg="_getTelCtx",Eg=0;function _getNextProxyStart(g,f,S){for(;g;){if(g[ld]()===S)return g;g=g[Rd]()}return createTelemetryProxyChain([S],f.config||{},f)}function _createInternalContext(g,f,S,v){var C=null,_=[];f||(f=createDynamicConfig({},null,S[Yc])),null!==v&&(C=v?_getNextProxyStart(g,S,v):g);var T={_next:_moveNext,ctx:{core:function(){return S},diagLog:function(){return safeGetLogger(S,f.cfg)},getCfg:function(){return f.cfg},getExtCfg:_resolveExtCfg,getConfig:_getConfig,hasNext:function(){return!!C},getNext:function(){return C},setNext:function(g){C=g},iterate:_iterateChain,onComplete:_addOnComplete}};function _addOnComplete(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];g&&_[Xc]({func:g,self:isUndefined4(f)?T.ctx:f,args:S})}function _moveNext(){var g=C;if(C=g?g[Rd]():null,!g){var f=_;f&&f[jc]>0&&(arrForEach(f,(function(g){try{g.func.call(g.self,g.args)}catch(g){_throwInternal(S[Yc],2,73,"Unexpected Exception during onComplete - "+dumpObj(g))}})),_=[])}return g}function _getExtCfg(g,S){var v=null,C=f.cfg;if(C&&g){var _=C[Mh];!_&&S&&(_={}),C[Mh]=_,(_=f.ref(C,Mh))&&(!(v=_[g])&&S&&(v={}),_[g]=v,v=f.ref(_,g))}return v}function _resolveExtCfg(g,S){var v=_getExtCfg(g,!0);return S&&objForEachKey(S,(function(g,S){if(isNullOrUndefined(v[g])){var C=f.cfg[g];!C&&isNullOrUndefined(C)||(v[g]=C)}_applyDefaultValue(f,v,g,S)})),f[Kc](v,S)}function _getConfig(g,S,v){var C;void 0===v&&(v=!1);var _=_getExtCfg(g,!1),T=f.cfg;return!_||!_[S]&&isNullOrUndefined(_[S])?!T[S]&&isNullOrUndefined(T[S])||(C=T[S]):C=_[S],C||!isNullOrUndefined(C)?C:v}function _iterateChain(g){for(var f;f=T._next();){var S=f[ld]();S&&g(S)}}return T}function createProcessTelemetryContext(g,f,S,v){var C=createDynamicConfig(f),_=_createInternalContext(g,C,S,v),T=_.ctx;function _processNext(g){var f=_._next();return f&&f[Oh](g,T),!f}function _createNew(g,f){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain(g,C.cfg,S,f)),createProcessTelemetryContext(g||T[Rd](),C.cfg,S,f)}return T[ud]=_processNext,T[yd]=_createNew,T}function createProcessTelemetryUnloadContext(g,f,S){var v=createDynamicConfig(f.config),C=_createInternalContext(g,v,f,S),_=C.ctx;function _processNext(g){var f=C._next();return f&&f[fd](_,g),!f}function _createNew(g,S){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain(g,v.cfg,f,S)),createProcessTelemetryUnloadContext(g||_[Rd](),f,S)}return _[ud]=_processNext,_[yd]=_createNew,_}function createProcessTelemetryUpdateContext(g,f,S){var v=createDynamicConfig(f.config),C=_createInternalContext(g,v,f,S).ctx;function _processNext(g){return C.iterate((function(f){hl(f[Pd])&&f[Pd](C,g)}))}function _createNew(g,S){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain(g,v.cfg,f,S)),createProcessTelemetryUpdateContext(g||C[Rd](),f,S)}return C[ud]=_processNext,C[yd]=_createNew,C}function createTelemetryProxyChain(g,f,S,v){var C=null,_=!v;if(ul(g)&&g[jc]>0){var T=null;arrForEach(g,(function(g){if(_||v!==g||(_=!0),_&&g&&hl(g[Oh])){var I=createTelemetryPluginProxy(g,f,S);C||(C=I),T&&T._setNext(I),T=I}}))}return v&&!C?createTelemetryProxyChain([v],f,S):C}function createTelemetryPluginProxy(g,f,S){var v,C=null,_=hl(g[Oh]),T=hl(g[Md]),I={getPlugin:function(){return g},getNext:function(){return C},processTelemetry:_processTelemetry,unload:_unloadPlugin,update:_updatePlugin,_id:v=g?g[nd]+"-"+g[Dh]+"-"+Eg++:"Unknown-0-"+Eg++,_setNext:function(g){C=g}};function _getTelCtx(){var v;return g&&hl(g[yg])&&(v=g[yg]()),v||(v=createProcessTelemetryContext(I,f,S)),v}function _processChain(f,S,_,T,I){var b=!1,A=g?g[nd]:vg,P=f[Cg];return P||(P=f[Cg]={}),f.setNext(C),g&&doPerf(f[Ah](),(function(){return A+":"+_}),(function(){P[v]=!0;try{var g=C?C._id:Ih;g&&(P[g]=!1),b=S(f)}catch(g){var T=!C||P[C._id];T&&(b=!0),C&&T||_throwInternal(f[bd](),1,73,"Plugin ["+A+"] failed during "+_+" - "+dumpObj(g)+", run flags: "+dumpObj(P))}}),T,I),b}function _processTelemetry(f,S){function _callProcessTelemetry(S){if(!g||!_)return!1;var v=_getPluginState(g);return!v[Ed]&&!v[Rh]&&(T&&g[Md](C),g[Oh](f,S),!0)}_processChain(S=S||_getTelCtx(),_callProcessTelemetry,"processTelemetry",(function(){return{item:f}}),!f.sync)||S[ud](f)}function _unloadPlugin(f,S){function _callTeardown(){var v=!1;if(g){var C=_getPluginState(g),_=g[Ah]||C[Ah];!g||_&&_!==f.core()||C[Ed]||(C[Ah]=null,C[Ed]=!0,C[ad]=!1,g[Ed]&&!0===g[Ed](f,S)&&(v=!0))}return v}_processChain(f,_callTeardown,"unload",(function(){}),S[Id])||f[ud](S)}function _updatePlugin(f,S){function _callUpdate(){var v=!1;if(g){var C=_getPluginState(g),_=g[Ah]||C[Ah];!g||_&&_!==f.core()||C[Ed]||g[Pd]&&!0===g[Pd](f,S)&&(v=!0)}return v}_processChain(f,_callUpdate,"update",(function(){}),!1)||f[ud](S)}return Pl(I)}function createUnloadHandlerContainer(){var g=[];function _addHandler(f){f&&g[Xc](f)}function _runHandlers(f,S){arrForEach(g,(function(g){try{g(f,S)}catch(g){_throwInternal(f[bd](),2,73,"Unexpected error calling unload handler - "+dumpObj(g))}})),g=[]}return{add:_addHandler,run:_runHandlers}}function createUnloadHookContainer(){var g=[];function _doUnload(f){var S=g;g=[],arrForEach(S,(function(g){try{(g.rm||g.remove).call(g)}catch(g){_throwInternal(f,2,73,"Unloading:"+dumpObj(g))}}))}function _addHook(f){f&&arrAppend(g,f)}return{run:_doUnload,add:_addHook}}var _g="getPlugin",Tg=((Sg={})[Mh]={isVal:isNotNullOrUndefined,v:{}},Sg),Ig=function(){function BaseTelemetryPlugin3(){var g,f,S,v,C,_=this;function _getTelCtx(g){void 0===g&&(g=null);var v=g;if(!v){var C=f||createProcessTelemetryContext(null,{},_[Ah]);v=S&&S[_g]?C[yd](null,S[_g]):C[yd](null,S)}return v}function _setDefaults(g,v,C){createDynamicConfig(g,Tg,safeGetLogger(v)),!C&&v&&(C=v[gd]()[Rd]());var T=S;S&&S[_g]&&(T=S[_g]()),_[Ah]=v,f=createProcessTelemetryContext(C,g,v,T)}function _initDefaults(){g=!1,_[Ah]=null,f=null,S=null,C=createUnloadHookContainer(),v=createUnloadHandlerContainer()}_initDefaults(),dynamicProto(BaseTelemetryPlugin3,_,(function(f){f[id]=function(f,S,v,C){_setDefaults(f,S,C),g=!0},f[Ed]=function(g,_){var T,I=f[Ah];if(I&&(!g||I===g[Ah]())){var b,A=!1,P=g||createProcessTelemetryUnloadContext(null,I,S&&S[_g]?S[_g]():S),R=_||((T={reason:0})[Id]=!1,T);return f[Ad]&&!0===f[Ad](P,R,_unloadCallback)?b=!0:_unloadCallback(),b}function _unloadCallback(){A||(A=!0,v.run(P,_),C.run(P[bd]()),!0===b&&P[ud](R),_initDefaults())}},f[Pd]=function(g,v){var C=f[Ah];if(C&&(!g||C===g[Ah]())){var _,T=!1,I=g||createProcessTelemetryUpdateContext(null,C,S&&S[_g]?S[_g]():S),b=v||{reason:0};return f._doUpdate&&!0===f._doUpdate(I,b,_updateCallback)?_=!0:_updateCallback(),_}function _updateCallback(){T||(T=!0,_setDefaults(I.getCfg(),I.core(),I[Rd]()))}},proxyFunctionAs(f,"_addUnloadCb",(function(){return v}),"add"),proxyFunctionAs(f,"_addHook",(function(){return C}),"add"),objDefine(f,"_unloadHooks",{g:function(){return C}})})),_[bd]=function(g){return _getTelCtx(g)[bd]()},_[ad]=function(){return g},_.setInitialized=function(f){g=f},_[Md]=function(g){S=g},_[ud]=function(g,f){f?f[ud](g):S&&hl(S[Oh])&&S[Oh](g,null)},_._getTelCtx=_getTelCtx}return BaseTelemetryPlugin3.__ieDyn=1,BaseTelemetryPlugin3}();function _addInitializer(g,f,S){var v={id:f,fn:S};return arrAppend(g,v),{remove:function(){arrForEach(g,(function(f,S){if(f.id===v.id)return g[Zc](S,1),-1}))}}}function _runInitializers(g,f,S){for(var v=!1,C=g[jc],_=0;_<C;++_){var T=g[_];if(T)try{if(!1===T.fn[Qc](null,[f])){v=!0;break}}catch(g){_throwInternal(S,2,64,"Telemetry initializer failed: "+getExceptionName(g),{exception:dumpObj(g)},!0)}}return!v}var bg,Ag=function(g){function TelemetryInitializerPlugin2(){var f,S,v=g.call(this)||this;function _initDefaults(){f=0,S=[]}return v.identifier="TelemetryInitializerPlugin",v.priority=199,_initDefaults(),dynamicProto(TelemetryInitializerPlugin2,v,(function(g,v){g.addTelemetryInitializer=function(g){return _addInitializer(S,f++,g)},g[Oh]=function(f,v){_runInitializers(S,f,v?v[bd]():g[bd]())&&g[ud](f,v)},g[Ad]=function(){_initDefaults()}})),v}return __extendsFn(TelemetryInitializerPlugin2,g),TelemetryInitializerPlugin2.__ieDyn=1,TelemetryInitializerPlugin2}(Ig),Pg="Plugins must provide initialize method",Rg="_notificationManager",Mg="SDK is still unloading...",wg="SDK is not initialized",Og=objDeepFreeze(((bg={cookieCfg:{}})[wh]={rdOnly:!0,ref:!0,v:[]},bg[bh]={rdOnly:!0,ref:!0,v:[]},bg[Mh]={ref:!0,v:{}},bg[Ph]=Th,bg.loggingLevelConsole=0,bg.diagnosticLogInterval=Th,bg));function _createPerfManager(g,f){return new ug(f)}function _validateExtensions(g,f,S){var v,C=[],_=[],T={};return arrForEach(S,(function(S){(isNullOrUndefined(S)||isNullOrUndefined(S[id]))&&throwError(Pg);var v=S[Dh],I=S[nd];S&&v&&(isNullOrUndefined(T[v])?T[v]=I:_warnToConsole(g,"Two extensions have same priority #"+v+" - "+T[v]+", "+I)),!v||v<f?C[Xc](S):_[Xc](S)})),(v={})[Ah]=C,v[bh]=_,v}function _isPluginPresent(g,f){var S=!1;return arrForEach(f,(function(f){if(f===g)return S=!0,-1})),S}function _deepMergeConfig(g,f,S,v){S&&objForEachKey(S,(function(S,C){v&&isPlainObject(C)&&isPlainObject(f[S])&&_deepMergeConfig(g,f[S],C,v),v&&isPlainObject(C)&&isPlainObject(f[S])?_deepMergeConfig(g,f[S],C,v):g.set(f,S,C)}))}function _findWatcher(g,f){var S=null,v=-1;return arrForEach(g,(function(g,C){if(g.w===f)return S=g,v=C,-1})),{i:v,l:S}}function _addDelayedCfgListener(g,f){var S=_findWatcher(g,f).l;return S||(S={w:f,rm:function(){var S=_findWatcher(g,f);-1!==S.i&&g[Zc](S.i,1)}},g[Xc](S)),S}function _registerDelayedCfgListener(g,f,S){arrForEach(f,(function(f){var v=onConfigChange(g,f.w,S);delete f.w,f.rm=function(){v.rm()}}))}function _initDebugListener(g,f,S,v){return f.add(g[Jc]((function(g){var f=g.cfg.disableDbgExt;!0===f&&v&&(S[rd](v),v=null),S&&!v&&!0!==f&&(v=getDebugListener(g.cfg),S[sd](v))}))),v}function _createUnloadHook(g){return objDefine({rm:function(){g.rm()}},"toJSON",{v:function(){return"aicore::onCfgChange<"+JSON.stringify(g)+">"}})}var Dg=function(){function AppInsightsCore4(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G;dynamicProto(AppInsightsCore4,this,(function(q){function _startLogPoller(f){$&&$[pd]||G||(f||S&&S.queue[jc]>0)&&(j||(j=!0,_addUnloadHook(g[Jc]((function(g){var f=g.cfg.diagnosticLogInterval;f&&f>0||(f=1e4);var S=!1;$&&(S=$[pd],$[td]()),($=createTimeout(_flushInternalLogs,f)).unref(),$[pd]=S})))),$[pd]=!0);return $}function _setPluginVersions(){var g={};B=[];var _addPluginVersions=function(f){f&&arrForEach(f,(function(f){if(f[nd]&&f[vd]&&!g[f.identifier]){var S=f[nd]+"="+f[vd];B[Xc](S),g[f.identifier]=f}}))};_addPluginVersions(R),P&&arrForEach(P,(function(g){_addPluginVersions(g)})),_addPluginVersions(A)}function _initDefaults(){f=!1,(g=createDynamicConfig({},Og,q[Yc])).cfg[Cd]=1,objDefine(q,"config",{g:function(){return g.cfg},s:function(g){q.updateCfg(g,!1)}}),objDefine(q,"pluginVersionStringArr",{g:function(){return B||_setPluginVersions(),B}}),objDefine(q,"pluginVersionString",{g:function(){return H||(B||_setPluginVersions(),H=B.join(";")),H||Ih}}),objDefine(q,"logger",{g:function(){return S||(S=new Gu(g.cfg),g[Yc]=S),S},s:function(f){g[Yc]=f,S!==f&&(runTargetUnload(S,!1),S=f)}}),q[Yc]=new Gu(g.cfg),V=[];var L=q.config[wh]||[];L.splice(0,L[jc]),arrAppend(L,V),w=new Ag,v=[],runTargetUnload(C,!1),C=null,_=null,T=null,runTargetUnload(I,!1),I=null,b=null,A=[],P=null,R=null,M=!1,O=null,D=createUniqueNamespace("AIBaseCore",!0),N=createUnloadHandlerContainer(),F=null,x=null,k=createUnloadHookContainer(),U=[],H=null,B=null,G=!1,$=null,j=!1}function _createTelCtx(){var f=createProcessTelemetryContext(_getPluginChain(),g.cfg,q);return f[Sd](_startLogPoller),f}function _initPluginChain(g){var f=_validateExtensions(q[Yc],Mu,A);b=null,H=null,B=null,R=sortPlugins(arrAppend(R=(P||[])[0]||[],f[bh]));var S=arrAppend(sortPlugins(f[Ah]),R);V=Pl(S);var v=q.config[wh]||[];v.splice(0,v[jc]),arrAppend(v,V);var C=_createTelCtx();R&&R[jc]>0&&initializePlugins(C[yd](R),S),initializePlugins(C,S),g&&_doUpdate(g)}function _getPlugin(g){var f=null,S=null,v=[];return arrForEach(V,(function(f){if(f[nd]===g&&f!==w)return S=f,-1;f.getChannel&&v[Xc](f)})),!S&&v[jc]>0&&arrForEach(v,(function(f){if(!(S=f.getChannel(g)))return-1})),S&&(f={plugin:S,setEnabled:function(g){_getPluginState(S)[Rh]=!g},isEnabled:function(){var g=_getPluginState(S);return!g[Ed]&&!g[Rh]},remove:function(g,f){var v;void 0===g&&(g=!0);var C=[S],_=((v={reason:1})[Id]=g,v);_removePlugins(C,_,(function(g){g&&_initPluginChain({reason:32,removed:C}),f&&f(g)}))}}),f}function _getPluginChain(){if(!b){var f=(V||[]).slice();-1===Yl(f,w)&&f[Xc](w),b=createTelemetryProxyChain(sortPlugins(f),g.cfg,q)}return b}function _removePlugins(f,S,v){if(f&&f[jc]>0){var C=createProcessTelemetryUnloadContext(createTelemetryProxyChain(f,g.cfg,q),q);C[Sd]((function(){var g=!1,S=[];arrForEach(A,(function(v,C){_isPluginPresent(v,f)?g=!0:S[Xc](v)})),A=S,H=null,B=null;var C=[];P&&(arrForEach(P,(function(S,v){var _=[];arrForEach(S,(function(S){_isPluginPresent(S,f)?g=!0:_[Xc](S)})),C[Xc](_)})),P=C),v&&v(g),_startLogPoller()})),C[ud](S)}else v(!1)}function _flushInternalLogs(){if(S&&S.queue){var g=S.queue.slice(0);S.queue[jc]=0,arrForEach(g,(function(g){var f,S=((f={})[dd]=O||"InternalMessageId: "+g[_d],f.iKey=x,f[hd]=toISOString(new Date),f.baseType=Hu.dataType,f.baseData={message:g[Td]},f);q.track(S)}))}}function _flushChannels(g,f,S,v){var C=1,_=!1,T=null;function doCallback(){C--,_&&0===C&&(T&&T[td](),T=null,f&&f(_),f=null)}(v=v||5e3,R&&R[jc]>0)&&_createTelCtx()[yd](R).iterate((function(f){if(f.flush){C++;var _=!1;f.flush(g,(function(){_=!0,doCallback()}),S)||_||(g&&null==T?T=scheduleTimeout((function(){T=null,doCallback()}),v):doCallback())}}));return _=!0,doCallback(),!0}function _initPerfManager(){var f;_addUnloadHook(g[Jc]((function(g){if(g.cfg.enablePerfMgr){var S=g.cfg[Ph];f!==S&&(S||(S=_createPerfManager),getSetValue(g.cfg,Ph,S),f=S,T=null),_||T||!hl(S)||(T=S(q,q[od]()))}else T=null,f=null})))}function _doUpdate(g){var f=createProcessTelemetryUpdateContext(_getPluginChain(),q);f[Sd](_startLogPoller),q._updateHook&&!0===q._updateHook(f,g)||f[ud](g)}function _logOrThrowError(g){var f=q[Yc];f?(_throwInternal(f,2,73,g),_startLogPoller()):throwError(g)}function _notifyInvalidEvent(g){var f=q[od]();f&&f[kh]([g],2)}function _addUnloadHook(g){k.add(g)}_initDefaults(),q._getDbgPlgTargets=function(){return[V]},q[ad]=function(){return f},q[id]=function(v,_,T,I){M&&throwError(Mg),q[ad]()&&throwError("Core cannot be initialized more than once"),v=(g=createDynamicConfig(v,Og,T||q[Yc],!1)).cfg,_addUnloadHook(g[Jc]((function(g){x=g.cfg.instrumentationKey;var f=g.ref(g.cfg,Mh);objForEachKey(f,(function(S){g.ref(f,S)})),isNullOrUndefined(x)&&throwError("Please provide instrumentation key")}))),L=_initDebugListener(g,k,(C=I)&&q[od](),L),_initPerfManager(),q[Yc]=T;var b=v[wh];if((A=[])[Xc].apply(A,__spreadArrayFn(__spreadArrayFn([],_,!1),b)),P=v[bh],_initPluginChain(null),R&&0!==R[jc]||throwError("No "+bh+" available"),P&&P[jc]>1){var w=q[ld]("TeeChannelController");w&&w.plugin||_throwInternal(S,1,28,"TeeChannel required")}_registerDelayedCfgListener(v,U,S),U=null,f=!0,q.releaseQueue(),q[cd]()},q.getChannels=function(){var g=[];return R&&arrForEach(R,(function(f){g[Xc](f)})),Pl(g)},q.track=function(g){doPerf(q[Bh](),(function(){return"AppInsightsCore:track"}),(function(){null===g&&(_notifyInvalidEvent(g),throwError("Invalid telemetry item")),!g[dd]&&isNullOrUndefined(g[dd])&&(_notifyInvalidEvent(g),throwError("telemetry name required")),g.iKey=g.iKey||x,g[hd]=g[hd]||toISOString(new Date),g.ver=g.ver||"4.0",!M&&q[ad]()?_createTelCtx()[ud](g):v[Xc](g)}),(function(){return{item:g}}),!g.sync)},q[gd]=_createTelCtx,q[od]=function(){return C||(C=new ag(g.cfg),q[Rg]=C),C},q[sd]=function(g){q.getNotifyMgr()[sd](g)},q[rd]=function(g){C&&C[rd](g)},q.getCookieMgr=function(){return I||(I=createCookieMgr(g.cfg,q[Yc])),I},q.setCookieMgr=function(g){I!==g&&(runTargetUnload(I,!1),I=g)},q[Bh]=function(){return _||T||getGblPerfMgr()},q.setPerfMgr=function(g){_=g},q.eventCnt=function(){return v[jc]},q.releaseQueue=function(){if(f&&v[jc]>0){var g=v;v=[],arrForEach(g,(function(g){_createTelCtx()[ud](g)}))}},q[cd]=function(g){return O=g||null,G=!1,$&&$[td](),_startLogPoller(!0)},q[md]=function(){G=!0,$&&$[td](),_flushInternalLogs()},proxyFunctions(q,(function(){return w}),["addTelemetryInitializer"]),q[fd]=function(g,v,_){var T;void 0===g&&(g=!0),f||throwError(wg),M&&throwError(Mg);var b,A=((T={reason:50})[Id]=g,T.flushComplete=!1,T);g&&!v&&(b=createPromise((function(g){v=g})));var P=createProcessTelemetryUnloadContext(_getPluginChain(),q);function _doUnload(g){A.flushComplete=g,M=!0,N.run(P,A),q[md](),P[ud](A)}return P[Sd]((function(){k.run(q[Yc]),doUnloadAll([I,C,S],g,(function(){_initDefaults(),v&&v(A)}))}),q),_flushInternalLogs(),_flushChannels(g,_doUnload,6,_),b},q[ld]=_getPlugin,q.addPlugin=function(g,f,S,v){if(!g)return v&&v(!1),void _logOrThrowError(Pg);var C=_getPlugin(g[nd]);if(C&&!f)return v&&v(!1),void _logOrThrowError("Plugin ["+g[nd]+"] is already loaded!");var _={reason:16};function _addPlugin(f){A[Xc](g),_.added=[g],_initPluginChain(_),v&&v(!0)}if(C){var T=[C.plugin];_removePlugins(T,{reason:2,isAsync:!!S},(function(g){g?(_.removed=T,_.reason|=32,_addPlugin()):v&&v(!1)}))}else _addPlugin()},q.updateCfg=function(f,S){var v;if(void 0===S&&(S=!0),q[ad]()){v={reason:1,cfg:g.cfg,oldCfg:deepExtend({},g.cfg),newConfig:deepExtend({},f),merge:S},f=v.newConfig;var C=g.cfg;f[wh]=C[wh],f[bh]=C[bh]}g._block((function(g){var v=g.cfg;_deepMergeConfig(g,v,f,S),S||objForEachKey(v,(function(S){vl(f,S)||g.set(v,S,Th)})),g[Kc](v,Og)}),!0),g[qc](),v&&_doUpdate(v)},q.evtNamespace=function(){return D},q.flush=_flushChannels,q.getTraceCtx=function(g){return F||(F=createDistributedTraceContext()),F},q.setTraceCtx=function(g){F=g||null},q.addUnloadHook=_addUnloadHook,proxyFunctionAs(q,"addUnloadCb",(function(){return N}),"add"),q.onCfgChange=function(S){return _createUnloadHook(f?onConfigChange(g.cfg,S,q[Yc]):_addDelayedCfgListener(U,S))},q.getWParam=function(){return hasDocument()||g.cfg.enableWParam?0:-1}}))}return AppInsightsCore4.__ieDyn=1,AppInsightsCore4}(),Ng="",kg="&"+"NoResponseBody"+"=true",Lg="POST",Fg=function(){function SenderPostManager3(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w=0;dynamicProto(SenderPostManager3,this,(function(O,D){var N=!0;function _onSuccess(g,f){_doOnComplete(f,200,{},g)}function _onError(g,f){_throwInternal(S,2,26,"Failed to send telemetry.",{message:g}),_doOnComplete(f,400,{})}function _onNoPayloadUrl(g){_onError("No endpoint url is provided for the batch",g)}function _getSenderInterface(g,f){for(var S,v=0,C=null,_=0;null==C&&_<g[jc];)v=g[_],I||1!==v?2!==v||!isFetchSupported(f)||f&&P?3!==v||!isBeaconsSupported()||(f?A:b)||(C=_beaconSender):C=_doFetchSender:useXDomainRequest()?C=_xdrSender:isXhrSupported()&&(C=_xhrSender),_++;return C?((S={_transport:v,_isSync:f})[zd]=C,S):null}function _doOnComplete(g,f,S,v){try{g&&g(f,S,v)}catch(g){}}function _doBeaconSend(g,f){var S=Kl(),C=g[Wd];if(!C)return _onNoPayloadUrl(f),!0;C=g[Wd]+(R?kg:Ng);var _=g[$d],T=v?_:new Blob([_],{type:"text/plain;charset=UTF-8"});return S.sendBeacon(C,T)}function _beaconSender(g,f,_){var I=g[$d];try{if(I)if(_doBeaconSend(g,f))_onSuccess(Ng,f);else{var b=C&&C.beaconOnRetry;b&&hl(b)?b(g,f,_doBeaconSend):(T&&T[zd](g,f,!0),_throwInternal(S,2,40,". Failed to send telemetry with Beacon API, retried with normal sender."))}}catch(g){v&&_warnToConsole(S,"Failed to send telemetry using sendBeacon API. Ex:"+dumpObj(g)),_doOnComplete(f,v?0:400,{},Ng)}}function _xhrSender(f,S,_){var T,I,b,A=f[Kd]||{};!_&&g&&(T=createPromise((function(g,f){I=g,b=f}))),v&&_&&f.disableXhrSync&&(_=!1);var P=f[Wd];if(!P)return _onNoPayloadUrl(S),void(I&&I(!1));var R=openXhr(Lg,P,N,!0,_,f[Jd]);function _doOnReadyFunc(g){var _=C&&C.xhrOnComplete;if(_&&hl(_))_(g,S,f);else{var T=getResponseText(g);_doOnComplete(S,g[Ud],_getAllResponseHeaders(g,v),T)}}return v||R[Yd]("Content-type","application/json"),arrForEach(Al(A),(function(g){R[Yd](g,A[g])})),R.onreadystatechange=function(){v||(_doOnReadyFunc(R),4===R.readyState&&I&&I(!0))},R.onload=function(){v&&_doOnReadyFunc(R)},R.onerror=function(g){_doOnComplete(S,v?R[Ud]:400,_getAllResponseHeaders(R,v),v?Ng:formatErrorMessageXhr(R)),b&&b(g)},R.ontimeout=function(){_doOnComplete(S,v?R[Ud]:500,_getAllResponseHeaders(R,v),v?Ng:formatErrorMessageXhr(R)),I&&I(!1)},R.send(f[$d]),T}function _doFetchSender(f,S,_){var T,I,b,A,P=f[Wd],O=f[$d],D=v?O:new Blob([O],{type:"application/json"}),k=new Headers,L=O[jc],F=!1,x=!1,U=f[Kd]||{},V=((T={method:Lg,body:D})[wu]=!0,T);f.headers&&Al(f.headers)[jc]>0&&(arrForEach(Al(U),(function(g){k.append(g,U[g])})),V[Kd]=k),N&&v&&(V.credentials="include"),_&&(V.keepalive=!0,w+=L,v?2===f._sendReason&&(F=!0,R&&(P+=kg)):F=!0);var B=new Request(P,V);try{B[wu]=!0}catch(g){}if(!_&&g&&(I=createPromise((function(g,f){b=g,A=f}))),!P)return _onNoPayloadUrl(S),void(b&&b(!1));function _handleError(g){_doOnComplete(S,v?0:400,{},v?Ng:g)}function _onFetchComplete(g,f,v){var _=g[Ud],T=C.fetchOnComplete;T&&hl(T)?T(g,S,v||Ng,f):_doOnComplete(S,_,{},v||Ng)}try{doAwaitResponse(fetch(v?P:B,v?V:null),(function(g){if(_&&(w-=L,L=0),!x)if(x=!0,g.rejected)_handleError(g.reason&&g.reason[Td]),A&&A(g.reason);else{var S=g.value;try{v||S.ok?v&&!S.body?(_onFetchComplete(S,null,Ng),b&&b(!0)):doAwaitResponse(S.text(),(function(g){_onFetchComplete(S,f,g.value),b&&b(!0)})):(_handleError(S.statusText),b&&b(!1))}catch(g){_handleError(dumpObj(g)),A&&A(g)}}}))}catch(g){x||(_handleError(dumpObj(g)),A&&A(g))}return F&&!x&&(x=!0,_doOnComplete(S,200,{}),b&&b(!0)),v&&!x&&f[Jd]>0&&M&&M.set((function(){x||(x=!0,_doOnComplete(S,500,{}),b&&b(!0))}),f[Jd]),I}function _xdrSender(g,f,_){var T=Gl(),I=new XDomainRequest,b=g[$d];I.onload=function(){var S=getResponseText(I),v=C&&C.xdrOnComplete;v&&hl(v)?v(I,f,g):_doOnComplete(f,200,{},S)},I.onerror=function(){_doOnComplete(f,400,{},v?Ng:formatErrorMessageXdr(I))},I.ontimeout=function(){_doOnComplete(f,500,{})},I.onprogress=function(){};var A=T&&T.location&&T.location[wd]||"",P=g[Wd];if(P){if(!v&&0!==P.lastIndexOf(A,0)){var R="Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.";return _throwInternal(S,2,40,". "+R),void _onError(R,f)}var w=v?P:P[kd](/^(https?:)/,"");I.open(Lg,w),g[Jd]&&(I[Jd]=g[Jd]),I.send(b),v&&_?M&&M.set((function(){I.send(b)}),0):I.send(b)}else _onNoPayloadUrl(f)}function _initDefaults(){w=0,f=!1,g=!1,S=null,v=null,C=null,_=null,T=null,I=!1,b=!1,A=!1,P=!1,R=!1,M=null}_initDefaults(),O[id]=function(g,v){S=v,f&&_throwInternal(S,1,28,"Sender is already initialized"),O.SetConfig(g),f=!0},O._getDbgPlgTargets=function(){return[f,v,_,g]},O.SetConfig=function(f){try{if(C=f.senderOnCompleteCallBack||{},_=!!f.disableCredentials,v=!!f.isOneDs,g=!!f.enableSendPromise,I=!!f.disableXhr,b=!!f.disableBeacon,A=!!f.disableBeaconSync,M=f.timeWrapper,R=!!f.addNoResponse,P=!!f.disableFetchKeepAlive,T={sendPOST:_xhrSender},v||(N=!1),_){var S=getLocation();S&&S.protocol&&"file:"===S.protocol[Hc]()&&(N=!1)}return!0}catch(g){}return!1},O.getSyncFetchPayload=function(){return w},O.getSenderInst=function(g,f){return g&&g[jc]?_getSenderInterface(g,f):null},O.getFallbackInst=function(){return T},O[Ad]=function(g,f){_initDefaults()}}))}return SenderPostManager3.__ieDyn=1,SenderPostManager3}(),xg="on",Ug="attachEvent",Vg="addEventListener",Bg="detachEvent",Hg="removeEventListener",$g="events",jg="visibilitychange",Gg="pagehide",qg="pageshow",Wg="unload",zg="beforeunload",Kg=createUniqueNamespace("aiEvtPageHide"),Jg=createUniqueNamespace("aiEvtPageShow"),Yg=/\.[\.]+/g,Qg=/[\.]+$/,Xg=1,Zg=createElmNodeData("events"),ep=/^([^.]*)(?:\.(.+)|)/;function _normalizeNamespace(g){return g&&g[kd]?g[kd](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g,Ih):g}function _getEvtNamespace(g,f){var S;if(f){var v=Ih;ul(f)?(v=Ih,arrForEach(f,(function(g){(g=_normalizeNamespace(g))&&("."!==g[0]&&(g="."+g),v+=g)}))):v=_normalizeNamespace(f),v&&("."!==v[0]&&(v="."+v),g=(g||Ih)+v)}var C=ep.exec(g||Ih)||[];return(S={})[Fd]=C[1],S.ns=(C[2]||Ih).replace(Yg,".").replace(Qg,Ih)[Dd](".").sort().join("."),S}function _getRegisteredEvents(g,f,S){void 0===S&&(S=!0);var v=Zg.get(g,$g,{},S),C=v[f];return C||(C=v[f]=[]),C}function _doDetach(g,f,S,v){g&&f&&f[Fd]&&(g[Hg]?g[Hg](f[Fd],S,v):g[Bg]&&g[Bg](xg+f[Fd],S))}function _doAttach(g,f,S,v){var C=!1;return g&&f&&f[Fd]&&S&&(g[Vg]?(g[Vg](f[Fd],S,v),C=!0):g[Ug]&&(g[Ug](xg+f[Fd],S),C=!0)),C}function _doUnregister(g,f,S,v){for(var C=f[jc];C--;){var _=f[C];_&&(S.ns&&S.ns!==_.evtName.ns||v&&!v(_)||(_doDetach(g,_.evtName,_[xd],_.capture),f[Zc](C,1)))}}function _unregisterEvents(g,f,S){if(f[Fd])_doUnregister(g,_getRegisteredEvents(g,f[Fd]),f,S);else{var v=Zg.get(g,$g,{});objForEachKey(v,(function(v,C){_doUnregister(g,C,f,S)})),0===Al(v)[jc]&&Zg.kill(g,$g)}}function mergeEvtNamespace(g,f){return f?_getEvtNamespace("xx",ul(f)?[g].concat(f):[g,f]).ns[Dd]("."):g}function eventOn(g,f,S,v,C){var _;void 0===C&&(C=!1);var T=!1;if(g)try{var I=_getEvtNamespace(f,v);if((T=_doAttach(g,I,S,C))&&Zg.accept(g)){var b=((_={guid:Xg++,evtName:I})[xd]=S,_.capture=C,_);_getRegisteredEvents(g,I.type)[Xc](b)}}catch(g){}return T}function eventOff(g,f,S,v,C){if(void 0===C&&(C=!1),g)try{var _=_getEvtNamespace(f,v),T=!1;_unregisterEvents(g,_,(function(g){return!((!_.ns||S)&&g[xd]!==S)&&(T=!0,!0)})),T||_doDetach(g,_,S,C)}catch(g){}}function addEventHandler(g,f,S){var v=!1,C=Gl();C&&(v=eventOn(C,g,f,S),v=eventOn(C.body,g,f,S)||v);var _=jl();return _&&(v=eventOn(_,g,f,S)||v),v}function removeEventHandler(g,f,S){var v=Gl();v&&(eventOff(v,g,f,S),eventOff(v.body,g,f,S));var C=jl();C&&eventOff(C,g,f,S)}function _addEventListeners(g,f,S,v){var C=!1;return f&&g&&g[jc]>0&&arrForEach(g,(function(g){g&&(S&&-1!==Yl(S,g)||(C=addEventHandler(g,f,v)||C))})),C}function addEventListeners(g,f,S,v){var C=!1;return f&&g&&ul(g)&&!(C=_addEventListeners(g,f,S,v))&&S&&S[jc]>0&&(C=_addEventListeners(g,f,null,v)),C}function removeEventListeners(g,f,S){g&&ul(g)&&arrForEach(g,(function(g){g&&removeEventHandler(g,f,S)}))}function addPageUnloadEventListener(g,f,S){return addEventListeners([zg,Wg,Gg],g,f,S)}function removePageUnloadEventListener(g,f){removeEventListeners([zg,Wg,Gg],g,f)}function addPageHideEventListener(g,f,S){function _handlePageVisibility(f){var S=jl();g&&S&&"hidden"===S.visibilityState&&g(f)}var v=mergeEvtNamespace(Kg,S),C=_addEventListeners([Gg],g,f,v);return f&&-1!==Yl(f,jg)||(C=_addEventListeners([jg],_handlePageVisibility,f,v)||C),!C&&f&&(C=addPageHideEventListener(g,null,S)),C}function removePageHideEventListener(g,f){var S=mergeEvtNamespace(Kg,f);removeEventListeners([Gg],g,S),removeEventListeners([jg],null,S)}function addPageShowEventListener(g,f,S){function _handlePageVisibility(f){var S=jl();g&&S&&"visible"===S.visibilityState&&g(f)}var v=mergeEvtNamespace(Jg,S),C=_addEventListeners([qg],g,f,v);return!(C=_addEventListeners([jg],_handlePageVisibility,f,v)||C)&&f&&(C=addPageShowEventListener(g,null,S)),C}function removePageShowEventListener(g,f){var S=mergeEvtNamespace(Jg,f);removeEventListeners([qg],g,S),removeEventListeners([jg],null,S)}var tp,ip="",np="https://browser.events.data.microsoft.com/OneCollector/1.0/",rp="version",sp="properties",ap="initialize",op="logger",lp="indexOf",cp="timings",dp="pollInternalLogs",hp="value",up="kind",gp="length",pp="processTelemetryStart",mp="1DS-Web-JS-"+"4.2.1",fp=Vo.hasOwnProperty,Sp=((tp={})[0]=0,tp[2]=6,tp[1]=1,tp[3]=7,tp[4098]=6,tp[4097]=1,tp[4099]=7,tp);function isValueAssigned(g){return!(g===ip||isNullOrUndefined(g))}function getTenantId(g){if(g){var f=oc(g,"-");if(f>-1)return strLeft(g,f)}return ip}function isLatency(g){return!!(g&&pl(g)&&g>=1&&g<=4)}function sanitizeProperty(g,f,S){if(!f&&!isValueAssigned(f)||"string"!=typeof g)return null;var v=typeof f;if("string"===v||"number"===v||"boolean"===v||ul(f))f={value:f};else if("object"!==v||fp.call(f,"value")){if(isNullOrUndefined(f[hp])||f[hp]===ip||!dl(f[hp])&&!pl(f[hp])&&!ml(f[hp])&&!ul(f[hp]))return null}else f={value:S?JSON.stringify(f):f};if(ul(f[hp])&&!isArrayValid(f[hp]))return null;if(!isNullOrUndefined(f[up])){if(ul(f[hp])||!isValueKind(f[up]))return null;f[hp]=f[hp].toString()}return f}function getCommonSchemaMetaData(g,f,S){var v=-1;if(!isUndefined4(g))if(f>0&&(32===f?v=8192:f<=13&&(v=f<<5)),isDataType(S))-1===v&&(v=0),v|=S;else{var C=Sp[getFieldValueType(g)]||-1;-1!==v&&-1!==C?v|=C:6===C&&(v=C)}return v}function getCookieValue(g,f,S){var v;return void 0===S&&(S=!0),g&&(v=g.get(f),S&&v&&decodeURIComponent&&(v=decodeURIComponent(v))),v||ip}function createGuid(g){void 0===g&&(g="D");var f=newGuid2();return"B"===g?f="{"+f+"}":"P"===g?f="("+f+")":"N"===g&&(f=f.replace(/-/g,ip)),f}function extend(g,f,S,v,C){var _={},T=!1,I=0,b=arguments[gp],A=arguments;for(ml(A[0])&&(T=A[0],I++);I<b;I++){objForEachKey(A[I],(function(g,f){T&&f&&isObject3(f)?ul(f)?(_[g]=_[g]||[],arrForEach(f,(function(f,S){f&&isObject3(f)?_[g][S]=extend(!0,_[g][S],f):_[g][S]=f}))):_[g]=extend(!0,_[g],f):_[g]=f}))}return _}var vp=perfNow;function isValueKind(g){return 0===g||g>0&&g<=13||32===g}function isDataType(g){return g>=0&&g<=9}function isArrayValid(g){return g[gp]>0}function setProcessTelemetryTimings(g,f){var S=g;S[cp]=S[cp]||{},S[cp][pp]=S[cp][pp]||{},S[cp][pp][f]=vp()}function getFieldValueType(g){var f=0;if(null!=g){var S=typeof g;"string"===S?f=1:"number"===S?f=2:"boolean"===S?f=3:S===Lo&&(f=4,ul(g)?(f=4096,g[gp]>0&&(f|=getFieldValueType(g[0]))):fp.call(g,"value")&&(f=8192|getFieldValueType(g[hp])))}return f}function isChromium(){return!!getInst("chrome")}function isGreaterThanZero(g){return g>0}var Cp=objDeepFreeze({endpointUrl:np,propertyStorageOverride:{isVal:_chkPropOverride}});function _chkPropOverride(g){return!g||g.getProperty&&g.setProperty||throwError("Invalid property storage override passed."),!0}var yp=function(g){function AppInsightsCore4(){var f=g.call(this)||this;return dynamicProto(AppInsightsCore4,f,(function(g,f){g[ap]=function(S,v,C,_){doPerf(g,(function(){return"AppInsightsCore.initialize"}),(function(){try{f[ap](createDynamicConfig(S,Cp,C||g[op],!1).cfg,v,C,_)}catch(f){var T=g[op],I=dumpObj(f);-1!==I[lp]("channels")&&(I+="\n - Channels must be provided through config.channels only!"),_throwInternal(T,1,514,"SDK Initialization Failed - no telemetry will be sent: "+I)}}),(function(){return{config:S,extensions:v,logger:C,notificationManager:_}}))},g.track=function(S){doPerf(g,(function(){return"AppInsightsCore.track"}),(function(){var v=S;if(v){v[cp]=v[cp]||{},v[cp].trackStart=vp(),isLatency(v.latency)||(v.latency=1);var C=v.ext=v.ext||{};C.sdk=C.sdk||{},C.sdk.ver=mp;var _=v.baseData=v.baseData||{};_[sp]=_[sp]||{};var T=_[sp];T[rp]=T[rp]||g.pluginVersionString||ip}f.track(v)}),(function(){return{item:S}}),!S.sync)},g[dp]=function(g){return f[dp](g||"InternalLog")}})),f}return __extendsFn(AppInsightsCore4,g),AppInsightsCore4.__ieDyn=1,AppInsightsCore4}(Dg),Ep=Uc({Normal:1,CostDeferred:2,RealTime:3,Immediate:4}),_p=Uc({Normal:1,Critical:2}),Tp="REAL_TIME",Ip="NEAR_REAL_TIME",bp="BEST_EFFORT",Ap="",Pp="drop",Rp="send",Mp="requeue",wp="rspFail",Op="oth",Dp="no-cache, no-store",Np="application/x-json-stream",kp="cache-control",Lp="content-type",Fp="kill-tokens",xp="kill-duration",Up="time-delta-millis",Vp="client-version",Bp="client-id",Hp="time-delta-to-apply-millis",$p="upload-time",jp="apikey",Gp="AuthMsaDeviceTicket",qp="WebAuthToken",Wp="AuthXToken",zp="NoResponseBody",Kp="msfpc",Jp="trace",Yp="user",Qp="allowRequestSending",Xp="firstRequestSent",Zp="shouldAddClockSkewHeaders",em="getClockSkewHeaderValue",tm="setClockSkew",im="length",nm="concat",rm="iKey",sm="count",am="events",om="push",lm="split",cm="splice",dm="toLowerCase",hm="hdrs",um="useHdrs",gm="initialize",pm="setTimeoutOverride",mm="clearTimeoutOverride",fm="payloadPreprocessor",Sm="overrideEndpointUrl",vm="avoidOptions",Cm="disableEventTimings",ym="stringifyObjects",Em="enableCompoundKey",_m="disableXhrSync",Tm="disableFetchKeepAlive",Im="addNoResponse",bm="excludeCsMetaData",Am="useSendBeacon",Pm="alwaysUseXhrOverride",Rm="unloadTransports",Mm="serializeOfflineEvt",wm="getOfflineRequestDetails",Om="createPayload",Dm="createOneDSPayload",Nm="payloadBlob",km="headers",Lm="_thePayload",Fm="urlString",xm="batches",Um="sendType",Vm="addHeader",Bm="canSendRequest",Hm="sendQueuedRequests",$m="isCompletelyIdle",jm="setUnloading",Gm="isTenantKilled",qm="sendSynchronousBatch",Wm="_transport",zm="getWParam",Km="isBeacon",Jm="timings",Ym="isTeardown",Qm="isSync",Xm="data",Zm="timeout",ef="_sendReason",tf="setKillSwitchTenants",nf="_backOffTransmission",rf="identifier",sf="disableOptimizeObj",af="ignoreMc1Ms0CookieProcessing",of="eventsLimitInMem",lf="autoFlushEventsLimit",cf="disableAutoBatchFlushLimit",df="overrideInstrumentationKey",hf="disableTelemetry",uf="baseData",gf="sendAttempt",pf="latency",mf="sync";function _getEventMsfpc(g){var f=(g.ext||{}).intweb;return f&&isValueAssigned(f[Kp])?f[Kp]:null}function _getMsfpc(g){for(var f=null,S=0;null===f&&S<g[im];S++)f=_getEventMsfpc(g[S]);return f}var ff=function(){function EventBatch2(g,f){var S=f?[][nm](f):[],v=this,C=_getMsfpc(S);v[rm]=function(){return g},v.Msfpc=function(){return C||Ap},v[sm]=function(){return S[im]},v[am]=function(){return S},v.addEvent=function(g){return!!g&&(S[om](g),C||(C=_getEventMsfpc(g)),!0)},v[lm]=function(f,v){var _;if(f<S[im]){var T=S[im]-f;isNullOrUndefined(v)||(T=v<T?v:T),_=S[cm](f,T),C=_getMsfpc(S)}return new EventBatch2(g,_)}}return EventBatch2.create=function(g,f){return new EventBatch2(g,f)},EventBatch2}(),Sf=function(){function ClockSkewManager2(){var g=!0,f=!0,S=!0,v="use-collector-delta",C=!1;dynamicProto(ClockSkewManager2,this,(function(_){_[Qp]=function(){return g},_[Xp]=function(){S&&(S=!1,C||(g=!1))},_[Zp]=function(){return f},_[em]=function(){return v},_[tm]=function(S){C||(S?(v=S,f=!0,C=!0):f=!1,g=!0)}}))}return ClockSkewManager2.__ieDyn=1,ClockSkewManager2}(),vf=1e3,Cf=function(){function KillSwitch2(){var g={};function _normalizeTenants(g){var f=[];return g&&arrForEach(g,(function(g){f[om](nc(g))})),f}dynamicProto(KillSwitch2,this,(function(f){f[tf]=function(f,S){if(f&&S)try{var v=_normalizeTenants(f[lm](","));if("this-request-only"===S)return v;for(var C=parseInt(S,10)*vf,_=0;_<v[im];++_)g[v[_]]=utcNow()+C}catch(g){return[]}return[]},f[Gm]=function(f){var S=g,v=nc(f);return void 0!==S[v]&&S[v]>utcNow()||(delete S[v],!1)}}))}return KillSwitch2.__ieDyn=1,KillSwitch2}(),yf=.8,Ef=1.2,_f=3e3,Tf=6e5;function retryPolicyShouldRetryForStatus(g){return!(g>=300&&g<500&&429!=g||501==g||505==g)}function retryPolicyGetMillisToBackoffForRetry(g){var f=0,S=_f*yf,v=_f*Ef,C=Math.floor(Math.random()*(v-S))+S;return f=Math.pow(2,g)*C,Math.min(f,Tf)}var If,bf=20,Af=3984588,Pf=65e3,Rf=2e6,Mf=Math.min(Rf,Pf),wf="metadata",Of="f",Df=/\./,Nf=function(){function Serializer2(g,f,S,v,C,_){var T="data",I="baseData",b="ext",A=!!v,P=!0,R=f,M={},w=!!_,O=C||getCommonSchemaMetaData;dynamicProto(Serializer2,this,(function(f){function _isReservedField(g,f){var S=M[g];return void 0===S&&(g.length>=7&&(S=lc(g,"ext.metadata")||lc(g,"ext.web")),M[g]=S),S}function _processPathKeys(g,f,v,C,_,T,I){objForEachKey(g,(function(g,b){var P=null;if(b||isValueAssigned(b)){var M=v,w=g,O=_,D=f;if(A&&!C&&Df.test(g)){var N=g.split("."),k=N.length;if(k>1){O&&(O=O.slice());for(var L=0;L<k-1;L++){var F=N[L];D=D[F]=D[F]||{},M+="."+F,O&&O.push(F)}w=N[k-1]}}if(P=!(C&&_isReservedField(M))&&R&&R.handleField(M,w)?R.value(M,w,b,S):sanitizeProperty(w,b,S)){var x=P.value;if(D[w]=x,T&&T(O,w,P),I&&"object"==typeof x&&!ul(x)){var U=O;U&&(U=U.slice()).push(w),_processPathKeys(b,x,M+"."+w,C,U,T,I)}}}}))}f.createPayload=function(g,f,S,v,C,_){return{apiKeys:[],payloadBlob:Ap,overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:g,isTeardown:f,isSync:S,isBeacon:v,sendType:_,sendReason:C}},f.appendPayload=function(S,v,C){var _=S&&v&&!S.overflow;return _&&doPerf(g,(function(){return"Serializer:appendPayload"}),(function(){for(var g=v.events(),_=S.payloadBlob,T=S.numEvents,I=!1,b=[],A=[],P=S.isBeacon,R=P?Pf:Af,M=P?Mf:Rf,w=0,O=0;w<g.length;){var D=g[w];if(D){if(T>=C){S.overflow=v.split(w);break}var N=f.getEventBlob(D);if(N&&N.length<=M){var k=N.length;if(_.length+k>R){S.overflow=v.split(w);break}_&&(_+="\n"),_+=N,++O>bf&&(Fl(_,0,1),O=0),I=!0,T++}else N?b.push(D):A.push(D),g.splice(w,1),w--}w++}if(b.length>0&&S.sizeExceed.push(ff.create(v.iKey(),b)),A.length>0&&S.failedEvts.push(ff.create(v.iKey(),A)),I){S.batches.push(v),S.payloadBlob=_,S.numEvents=T;var L=v.iKey();-1===Yl(S.apiKeys,L)&&S.apiKeys.push(L)}}),(function(){return{payload:S,theBatch:{iKey:v.iKey(),evts:v.events()},max:C}})),_},f.getEventBlob=function(f){try{return doPerf(g,(function(){return"Serializer.getEventBlob"}),(function(){var g={};g.name=f.name,g.time=f.time,g.ver=f.ver,g.iKey="o:"+getTenantId(f.iKey);var S,v={};w||(S=function(g,f,S){_addJSONPropertyMetaData(O,v,g,f,S)});var C=f[b];C&&(g[b]=v,objForEachKey(C,(function(g,f){_processPathKeys(f,v[g]={},"ext."+g,!0,null,null,!0)})));var _=g[T]={};_.baseType=f.baseType;var A=_[I]={};return _processPathKeys(f.baseData,A,I,!1,[I],S,P),_processPathKeys(f.data,_,T,!1,[],S,P),JSON.stringify(g)}),(function(){return{item:f}}))}catch(g){return null}}}))}return Serializer2.__ieDyn=1,Serializer2}();function _addJSONPropertyMetaData(g,f,S,v,C){if(C&&f){var _=g(C.value,C.kind,C.propertyType);if(_>-1){var T=f[wf];T||(T=f[wf]={f:{}});var I=T[Of];if(I||(I=T[Of]={}),S)for(var b=0;b<S.length;b++){var A=S[b];I[A]||(I[A]={f:{}});var P=I[A][Of];P||(P=I[A][Of]={}),I=P}I=I[v]={},ul(C.value)?I.a={t:_}:I.t=_}}}function createTimeoutWrapper(g,f){return{set:function(S,v){for(var C=[],_=2;_<arguments.length;_++)C[_-2]=arguments[_];return scheduleTimeoutWith([g,f],S,v,C)}}}var kf="sendAttempt",Lf="&"+zp+"=true",Ff="?cors=true&"+Lp[dm]()+"="+Np,xf=((If={})[1]=Mp,If[100]=Mp,If[200]="sent",If[8004]=Pp,If[8003]=Pp,If),Uf={},Vf={};function _addCollectorHeaderQsMapping(g,f,S){Uf[g]=f,!1!==S&&(Vf[f]=g)}function _hasHeader(g,f){var S=!1;if(g&&f){var v=Al(g);if(v&&v[im]>0)for(var C=f[dm](),_=0;_<v[im];_++){var T=v[_];if(T&&objHasOwnProperty(f,T)&&T[dm]()===C){S=!0;break}}}return S}function _addRequestDetails(g,f,S,v){f&&S&&S[im]>0&&(v&&Uf[f]?(g[hm][Uf[f]]=S,g[um]=!0):g.url+="&"+f+"="+S)}function _addQueryStringParameter(g,f,S){for(var v=0;v<g[im];v++)if(g[v].name===f)return void(g[v].value=S);g[om]({name:f,value:S})}function _removeQueryStringParameter(g,f){for(var S=0;S<g[im];S++)if(g[S].name===f)return void g[cm](S,1)}_addCollectorHeaderQsMapping(Gp,Gp,!1),_addCollectorHeaderQsMapping(Vp,Vp),_addCollectorHeaderQsMapping(Bp,"Client-Id"),_addCollectorHeaderQsMapping(jp,jp),_addCollectorHeaderQsMapping(Hp,Hp),_addCollectorHeaderQsMapping($p,$p),_addCollectorHeaderQsMapping(Wp,Wp);var Bf=function(){function HttpManager2(g,f,S,v){var C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q,W,z,K,J,Y,Q,X=!1;dynamicProto(HttpManager2,this,(function(Z){_initDefaults();var ee=!0;function _getSenderInterface(g,f){try{return Q&&Q.getSenderInst(g,f)}catch(g){}return null}function _getSendPostMgrConfig(){try{return{enableSendPromise:!1,isOneDs:!0,disableCredentials:!ee,disableXhr:!1,disableBeacon:!X,disableBeaconSync:!X,disableFetchKeepAlive:H,timeWrapper:J,addNoResponse:j,senderOnCompleteCallBack:{xdrOnComplete:_xdrOncomplete,fetchOnComplete:_fetchOnComplete,xhrOnComplete:_xhrOnComplete,beaconOnRetry:_onBeaconRetry}}}catch(g){}return null}function _xdrOncomplete(g,f,S){var v=getResponseText(g);_doOnComplete(f,200,{},v),_handleCollectorResponse(v)}function _initDefaults(){var g;C=null,_=new Cf,T=!1,I=new Sf,X=!1,b=0,A=null,P=null,R=null,M=null,w=!0,O=[],D={},N=[],k=null,L=!1,F=null,x=!1,U=!1,V=g,B=g,H=g,$=g,j=g,G=[],q=g,W=g,z=[],K=!1,J=createTimeoutWrapper(),Y=!1,Q=null}function _fetchOnComplete(g,f,S,v){var handleResponse=function(g,S,v){_doOnComplete(f,g,S,v),_handleCollectorResponse(v)},C={},_=g[km];_&&_.forEach((function(g,f){C[f]=g})),handleResponse(g.status,C,S||Ap)}function _xhrOnComplete(g,f,S){var v=getResponseText(g);_doOnComplete(f,g.status,_getAllResponseHeaders(g,!0),v),_handleCollectorResponse(v)}function _doOnComplete(g,f,S,v){try{g(f,S,v)}catch(g){_throwInternal(P,2,518,dumpObj(g))}}function _onBeaconRetry(g,f,S){var v=200,C=g[Lm],_=g[Fm]+(j?Lf:Ap);try{var T=Kl();if(C){var I=!!M.getPlugin("LocalStorage"),b=[],A=[];arrForEach(C[xm],(function(g){if(b&&g&&g[sm]()>0)for(var f=g[am](),S=0;S<f[im];S++){if(!T.sendBeacon(_,k.getEventBlob(f[S]))){b[om](g[lm](S));break}A[om](g[S])}else b[om](g[lm](0))})),A[im]>0&&(C.sentEvts=A),I||_sendBatchesNotification(b,8003,C[Um],!0)}else v=0}catch(g){_warnToConsole(P,"Failed to send telemetry using sendBeacon API. Ex:"+dumpObj(g)),v=0}finally{_doOnComplete(f,v,{},Ap)}}function _isBeaconPayload(g){return 2===g||3===g}function _adjustSendType(g){return x&&_isBeaconPayload(g)&&(g=2),g}function _hasIdleConnection(){return!T&&b<f}function _clearQueue(){var g=N;return N=[],g}function _canSendPayload(g,f,S){var v=!1;return g&&g[im]>0&&!T&&R[f]&&k&&(v=0!==f||_hasIdleConnection()&&(S>0||I[Qp]())),v}function _createDebugBatches(g){var f={};return g&&arrForEach(g,(function(g,S){f[S]={iKey:g[rm](),evts:g[am]()}})),f}function _sendBatches(f,S,v,C,I){if(f&&0!==f[im])if(T)_sendBatchesNotification(f,1,C);else{C=_adjustSendType(C);try{var b=f,A=0!==C;doPerf(M,(function(){return"HttpManager:_sendBatches"}),(function(T){T&&(f=f.slice(0));for(var b=[],P=null,M=vp(),w=R[C]||(A?R[1]:R[0]),O=w&&w[Wm],D=$&&(x||_isBeaconPayload(C)||3===O||w._isSync&&2===O);_canSendPayload(f,C,S);){var L=f.shift();L&&L[sm]()>0&&(_.isTenantKilled(L[rm]())?b[om](L):(P=P||k[Om](S,v,A,D,I,C),k.appendPayload(P,L,g)?null!==P.overflow&&(f=[P.overflow][nm](f),P.overflow=null,_doPayloadSend(P,M,vp(),I),M=vp(),P=null):(_doPayloadSend(P,M,vp(),I),M=vp(),f=[L][nm](f),P=null)))}P&&_doPayloadSend(P,M,vp(),I),f[im]>0&&(N=f[nm](N)),_sendBatchesNotification(b,8004,C)}),(function(){return{batches:_createDebugBatches(b),retryCount:S,isTeardown:v,isSynchronous:A,sendReason:I,useSendBeacon:_isBeaconPayload(C),sendType:C}}),!A)}catch(g){_throwInternal(P,2,48,"Unexpected Exception sending batch: "+dumpObj(g))}}}function _buildRequestDetails(g,f){var S={url:C,hdrs:{},useHdrs:!1};f?(S[hm]=extend(S[hm],D),S.useHdrs=Al(S.hdrs)[im]>0):objForEachKey(D,(function(g,f){Vf[g]?_addRequestDetails(S,Vf[g],f,!1):(S[hm][g]=f,S[um]=!0)})),_addRequestDetails(S,Bp,"NO_AUTH",f),_addRequestDetails(S,Vp,mp,f);var v=Ap;arrForEach(g.apiKeys,(function(g){v[im]>0&&(v+=","),v+=g})),_addRequestDetails(S,jp,v,f),_addRequestDetails(S,$p,utcNow().toString(),f);var _=_getMsfpc3(g);if(isValueAssigned(_)&&(S.url+="&ext.intweb.msfpc="+_),I[Zp]()&&_addRequestDetails(S,Hp,I[em](),f),M[zm]){var T=M[zm]();T>=0&&(S.url+="&w="+T)}for(var b=0;b<O[im];b++)S.url+="&"+O[b].name+"="+O[b].value;return S}function _setTimingValue(g,f,S){g[f]=g[f]||{},g[f][A.identifier]=S}function _doPayloadSend(g,f,S,v){if(g&&g.payloadBlob&&g.payloadBlob[im]>0){var C=!!q,_=R[g.sendType];!_isBeaconPayload(g[Um])&&g[Km]&&2===g.sendReason&&(_=R[2]||R[3]||_);var T=U;(g.isBeacon||3===_[Wm])&&(T=!1);var A=_buildRequestDetails(g,T);T=T||A[um];var O=vp();doPerf(M,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var R=0;R<g.batches[im];R++)for(var D=g[xm][R][am](),N=0;N<D[im];N++){var k=D[N];if(L){var F=k[Jm]=k[Jm]||{};_setTimingValue(F,"sendEventStart",O),_setTimingValue(F,"serializationStart",f),_setTimingValue(F,"serializationCompleted",S)}k[kf]>0?k[kf]++:k[kf]=1}_sendBatchesNotification(g[xm],1e3+(v||0),g[Um],!0);var x={data:g[Nm],urlString:A.url,headers:A[hm],_thePayload:g,_sendReason:v,timeout:V,disableXhrSync:B,disableFetchKeepAlive:H};T&&(_hasHeader(x[km],kp)||(x[km][kp]=Dp),_hasHeader(x[km],Lp)||(x[km][Lp]=Np));var U=null;_&&(U=function(f){I[Xp]();var onComplete=function(f,S){_retryRequestIfNeeded(f,S,g,v)},S=g[Ym]||g[Qm];try{_.sendPOST(f,onComplete,S),W&&W(x,f,S,g[Km])}catch(g){_warnToConsole(P,"Unexpected exception sending payload. Ex:"+dumpObj(g)),_doOnComplete(onComplete,0,{})}}),doPerf(M,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(U)if(0===g[Um]&&b++,C&&!g.isBeacon&&3!==_[Wm]){var f={data:x[Xm],urlString:x[Fm],headers:extend({},x[km]),timeout:x[Zm],disableXhrSync:x[_m],disableFetchKeepAlive:x[Tm]},S=!1;doPerf(M,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{q(f,(function(g){S=!0,w||g[Lm]||(g[Lm]=g[Lm]||x[Lm],g[ef]=g[ef]||x[ef]),U(g)}),g.isSync||g[Ym])}catch(g){S||U(x)}}))}else U(x)}))}),(function(){return{thePayload:g,serializationStart:f,serializationCompleted:S,sendReason:v}}),g[Qm])}g.sizeExceed&&g.sizeExceed[im]>0&&_sendBatchesNotification(g.sizeExceed,8003,g[Um]),g.failedEvts&&g.failedEvts[im]>0&&_sendBatchesNotification(g.failedEvts,8002,g[Um])}function _addEventCompletedTimings(g,f){L&&arrForEach(g,(function(g){_setTimingValue(g[Jm]=g[Jm]||{},"sendEventCompleted",f)}))}function _retryRequestIfNeeded(g,f,v,C){var T=9e3,A=null,P=!1,R=!1;try{var M=!0;if(typeof g!==Fo){if(f){I[tm](f[Up]);var w=f[xp]||f["kill-duration-seconds"];arrForEach(_[tf](f[Fp],w),(function(g){arrForEach(v[xm],(function(f){if(f[rm]()===g){A=A||[];var S=f[lm](0);v.numEvents-=S[sm](),A[om](S)}}))}))}if(200==g||204==g)return void(T=200);(!retryPolicyShouldRetryForStatus(g)||v.numEvents<=0)&&(M=!1),T=9e3+g%1e3}if(M){T=100;var O=v.retryCnt;0===v[Um]&&(O<S?(P=!0,_doAction((function(){0===v[Um]&&b--,_sendBatches(v[xm],O+1,v[Ym],x?2:v[Um],5)}),x,retryPolicyGetMillisToBackoffForRetry(O))):(R=!0,x&&(T=8001)))}}finally{P||(I[tm](),_handleRequestFinished(v,T,C,R)),_sendBatchesNotification(A,8004,v[Um])}}function _handleRequestFinished(g,f,S,v){try{v&&A[nf]();var C=g[xm];200===f&&(C=g.sentEvts||g[xm],v||g[Qm]||A._clearBackOff(),_addCompleteTimings(C)),_sendBatchesNotification(C,f,g[Um],!0)}finally{0===g[Um]&&(b--,5!==S&&Z.sendQueuedRequests(g[Um],S))}}function _addCompleteTimings(g){if(L){var f=vp();arrForEach(g,(function(g){g&&g[sm]()>0&&_addEventCompletedTimings(g[am](),f)}))}}function _doAction(g,f,S){f?g():J.set(g,S)}function _getMsfpc3(g){for(var f=0;f<g.batches[im];f++){var S=g[xm][f].Msfpc();if(S)return encodeURIComponent(S)}return Ap}function _handleCollectorResponse(g){var f=z;try{for(var S=0;S<f[im];S++)try{f[S](g)}catch(g){_throwInternal(P,1,519,"Response handler failed: "+g)}if(g){var v=JSON.parse(g);isValueAssigned(v.webResult)&&isValueAssigned(v.webResult[Kp])&&F.set("MSFPC",v.webResult[Kp],31536e3)}}catch(g){}}function _sendBatchesNotification(g,f,S,C){if(g&&g[im]>0&&v){var _=v[_getNotificationAction(f)];if(_){var T=0!==S;doPerf(M,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){_doAction((function(){try{_.call(v,g,f,T,S)}catch(g){_throwInternal(P,1,74,"send request notification failed: "+g)}}),C||T,0)}),(function(){return{batches:_createDebugBatches(g),reason:f,isSync:T,sendSync:C,sendType:S}}),!T)}}}function _getNotificationAction(g){var f=xf[g];return isValueAssigned(f)||(f=Op,g>=9e3&&g<=9999?f=wp:g>=8e3&&g<=8999?f=Pp:g>=1e3&&g<=1999&&(f=Rp)),f}Z[gm]=function(g,f,S){K||(M=f,F=f.getCookieMgr(),P=(A=S).diagLog(),arrAppend(G,onConfigChange(g,(function(g){var v,_=g.cfg,T=g.cfg.extensionConfig[S.identifier];J=createTimeoutWrapper(T[pm],T[mm]),isValueAssigned(_.anonCookieName)?_addQueryStringParameter(O,"anoncknm",_.anonCookieName):_removeQueryStringParameter(O,"anoncknm"),q=T[fm],W=T.payloadListener;var I=T.httpXHROverride,b=T[Sm]?T[Sm]:_.endpointUrl;C=b+Ff,U=!!isUndefined4(T[vm])||!T[vm],L=!T[Cm];var A=T.valueSanitizer,D=T[ym],N=!!_[Em];isUndefined4(T[Em])||(N=!!T[Em]),V=T.xhrTimeout,B=!!T[_m],H=!!T[Tm],j=!1!==T[Im],Y=!!T[bm],f.getPlugin("LocalStorage")&&(H=!0),X=!isReactNative(),k=new Nf(M,A,D,N,getCommonSchemaMetaData,Y),isNullOrUndefined(T[Am])||(X=!!T[Am]);var F=_getSendPostMgrConfig();Q?Q.SetConfig(F):(Q=new Fg)[gm](F,P);var x=I,G=T[Pm]?I:null,z=T[Pm]?I:null,K=[3,2];if(!I){w=!1;var Z=[];isReactNative()?(Z=[2,1],K=[2,1,3]):Z=[1,2,3],(I=_getSenderInterface(Z=prependTransports(Z,T.transports),!1))||_warnToConsole(P,"No available transport to send events"),x=_getSenderInterface(Z,!0)}G||(G=_getSenderInterface(K=prependTransports(K,T[Rm]),!0)),$=!w&&(X&&isBeaconsSupported()||!H&&isFetchSupported(!0)),(v={})[0]=I,v[1]=x||_getSenderInterface([1,2,3],!0),v[2]=G||x||_getSenderInterface([1],!0),v[3]=z||_getSenderInterface([2,3],!0)||x||_getSenderInterface([1],!0),R=v}))),K=!0)},Z.addResponseHandler=function(g){return z[om](g),{rm:function(){var f=z.indexOf(g);f>=0&&z[cm](f,1)}}},Z[Mm]=function(g){try{if(k)return k.getEventBlob(g)}catch(g){}return Ap},Z[wm]=function(){try{return _buildRequestDetails(k&&k[Om](0,!1,!1,!1,1,0),U)}catch(g){}return null},Z[Dm]=function(f,S){try{var v=[];arrForEach(f,(function(g){S&&(g=optimizeObject(g));var f=ff.create(g[rm],[g]);v[om](f)}));for(var C=null;v[im]>0&&k;){var _=v.shift();_&&_[sm]()>0&&(C=C||k[Om](0,!1,!1,!1,1,0),k.appendPayload(C,_,g))}var T=_buildRequestDetails(C,U),I={data:C[Nm],urlString:T.url,headers:T[hm],timeout:V,disableXhrSync:B,disableFetchKeepAlive:H};return U&&(_hasHeader(I[km],kp)||(I[km][kp]=Dp),_hasHeader(I[km],Lp)||(I[km][Lp]=Np)),I}catch(g){}return null},Z._getDbgPlgTargets=function(){return[R[0],_,k,R]},Z[Vm]=function(g,f){D[g]=f},Z.removeHeader=function(g){delete D[g]},Z[Bm]=function(){return _hasIdleConnection()&&I[Qp]()},Z[Hm]=function(g,f){isUndefined4(g)&&(g=0),x&&(g=_adjustSendType(g),f=2),_canSendPayload(N,g,0)&&_sendBatches(_clearQueue(),0,!1,g,f||0)},Z[$m]=function(){return!T&&0===b&&0===N[im]},Z[jm]=function(g){x=g},Z.addBatch=function(g){if(g&&g[sm]()>0){if(_.isTenantKilled(g[rm]()))return!1;N[om](g)}return!0},Z.teardown=function(){N[im]>0&&_sendBatches(_clearQueue(),0,!0,2,2),arrForEach(G,(function(g){g&&g.rm&&g.rm()})),G=[]},Z.pause=function(){T=!0},Z.resume=function(){T=!1,Z[Hm](0,4)},Z[qm]=function(g,f,S){g&&g[sm]()>0&&(isNullOrUndefined(f)&&(f=1),x&&(f=_adjustSendType(f),S=2),_sendBatches([g],0,!1,f,S||0))}}))}return HttpManager2.__ieDyn=1,HttpManager2}(),Hf=.25,$f=500,jf=20,Gf=6,qf=2,Wf=4,zf=2,Kf=1,Jf=1e4,Yf="eventsDiscarded",Qf="",Xf=void 0,Zf=objDeepFreeze({eventsLimitInMem:{isVal:isGreaterThanZero,v:Jf},immediateEventLimit:{isVal:isGreaterThanZero,v:500},autoFlushEventsLimit:{isVal:isGreaterThanZero,v:0},disableAutoBatchFlushLimit:!1,httpXHROverride:{isVal:isOverrideFn,v:Xf},overrideInstrumentationKey:Xf,overrideEndpointUrl:Xf,disableTelemetry:!1,ignoreMc1Ms0CookieProcessing:!1,setTimeoutOverride:Xf,clearTimeoutOverride:Xf,payloadPreprocessor:Xf,payloadListener:Xf,disableEventTimings:Xf,valueSanitizer:Xf,stringifyObjects:Xf,enableCompoundKey:Xf,disableOptimizeObj:!1,transports:Xf,unloadTransports:Xf,useSendBeacon:Xf,disableFetchKeepAlive:Xf,avoidOptions:!1,xhrTimeout:Xf,disableXhrSync:Xf,alwaysUseXhrOverride:!1,maxEventRetryAttempts:{isVal:pl,v:Gf},maxUnloadEventRetryAttempts:{isVal:pl,v:qf},addNoResponse:Xf,excludeCsMetaData:Xf});function isOverrideFn(g){return g&&g.sendPOST}var eS,tS=function(g){function PostChannel2(){var f,S=g.call(this)||this;S.identifier="PostChannel",S.priority=1011,S.version="4.2.1";var v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q=!1,W=[],z=!1,K=0,J=0,Y={},Q=Tp;return dynamicProto(PostChannel2,S,(function(g,S){function _removeUnloadHandlers(){removePageUnloadEventListener(null,x),removePageHideEventListener(null,x),removePageShowEventListener(null,x)}function _hookWParam(g){var f=g[zm];g[zm]=function(){var S=0;return V&&(S|=2),S|f.call(g)}}function _batch(g){var f=Qf;return g&&g[im]&&arrForEach(g,(function(g){f&&(f+="\n"),f+=g})),f}function _serialize(g){var f=Qf;try{_cleanEvent(g),f=P[Mm](g)}catch(g){}return f}function _handleUnloadEvents(g){"beforeunload"!==(g||Gl().event).type&&(k=!0,P[jm](k)),_releaseAllQueues(2,2)}function _handleShowEvents(g){k=!1,P[jm](k)}function _cleanEvent(g){g.ext&&g.ext[Jp]&&delete g.ext[Jp],g.ext&&g.ext[Yp]&&g.ext[Yp].id&&delete g.ext[Yp].id,N&&(g.ext=optimizeObject(g.ext),g[uf]&&(g[uf]=optimizeObject(g[uf])),g[Xm]&&(g[Xm]=optimizeObject(g[Xm])))}function _addEventToQueues(g,f){if(g[gf]||(g[gf]=0),g[pf]||(g[pf]=1),_cleanEvent(g),g[mf])if(b||z)g[pf]=3,g[mf]=!1;else if(P)return N&&(g=optimizeObject(g)),void P[qm](ff.create(g[rm],[g]),!0===g[mf]?1:g[mf],3);var S=g[pf],v=J,T=_;4===S&&(v=K,T=C);var I=!1;if(v<T)I=!_addEventToProperQueue(g,f);else{var A=1,R=jf;4===S&&(A=4,R=1),I=!0,_dropEventWithLatencyOrLess(g[rm],g[pf],A,R)&&(I=!_addEventToProperQueue(g,f))}I&&_notifyEvents(Yf,[g],Bc.QueueFull)}function _sendEventsForLatencyAndAbove(g,f,S){var v=_queueBatches(g,f,S);return P[Hm](f,S),v}function _hasEvents(){return J>0}function _scheduleTimer(){if(O>=0&&_queueBatches(O,0,D)&&P[Hm](0,D),K>0&&!I&&!z){var g=Y[Q][2];g>=0&&(I=_createTimer((function(){I=null,_sendEventsForLatencyAndAbove(4,0,1),_scheduleTimer()}),g))}var f=Y[Q][1];!T&&!v&&f>=0&&!z&&(_hasEvents()?T=_createTimer((function(){T=null,_sendEventsForLatencyAndAbove(0===A?3:1,0,1),A++,A%=2,_scheduleTimer()}),f):A=0)}function _initDefaults(){f=null,q=!1,W=[],v=null,z=!1,K=0,C=500,J=0,_=Jf,Y={},Q=Tp,T=null,I=null,b=0,A=0,R={},M=0,$=!1,w=0,O=-1,D=null,N=!0,k=!1,L=Gf,F=qf,x=null,j=null,G=!1,U=createTimeoutWrapper(),P=new Bf($f,zf,Kf,{requeue:_requeueEvents,send:_sendingEvent,sent:_eventsSentEvent,drop:_eventsDropped,rspFail:_eventsResponseFail,oth:_otherEvent}),_initializeProfiles(),_clearQueues(),_setAutoLimits()}function _createTimer(g,f){0===f&&b&&(f=1);var S=1e3;return b&&(S=retryPolicyGetMillisToBackoffForRetry(b-1)),U.set(g,f*S)}function _clearScheduledTimer(){return null!==T&&(T.cancel(),T=null,A=0,!0)}function _releaseAllQueues(g,f){_clearScheduledTimer(),v&&(v.cancel(),v=null),z||_sendEventsForLatencyAndAbove(1,g,f)}function _clearQueues(){R[4]={batches:[],iKeyMap:{}},R[3]={batches:[],iKeyMap:{}},R[2]={batches:[],iKeyMap:{}},R[1]={batches:[],iKeyMap:{}}}function _getEventBatch(g,f,S){var v=R[f];v||(v=R[f=1]);var C=v.iKeyMap[g];return!C&&S&&(C=ff.create(g),v.batches[om](C),v.iKeyMap[g]=C),C}function _performAutoFlush(f,S){P[Bm]()&&!b&&(M>0&&J>M&&(S=!0),S&&null==v&&g.flush(f,(function(){}),20))}function _addEventToProperQueue(g,f){N&&(g=optimizeObject(g));var S=g[pf],v=_getEventBatch(g[rm],S,!0);return!!v.addEvent(g)&&(4!==S?(J++,f&&0===g[gf]&&_performAutoFlush(!g.sync,w>0&&v[sm]()>=w)):K++,!0)}function _dropEventWithLatencyOrLess(g,f,S,v){for(;S<=f;){var C=_getEventBatch(g,f,!0);if(C&&C[sm]()>0){var _=C[lm](0,v),T=_[sm]();if(T>0)return 4===S?K-=T:J-=T,_notifyBatchEvents(Yf,[_],Bc.QueueFull),!0}S++}return _resetQueueCounts(),!1}function _resetQueueCounts(){for(var g=0,f=0,_loop_1=function(S){var v=R[S];v&&v[xm]&&arrForEach(v[xm],(function(v){4===S?g+=v[sm]():f+=v[sm]()}))},S=1;S<=4;S++)_loop_1(S);J=f,K=g}function _queueBatches(f,S,v){var C=!1,_=0===S;return!_||P[Bm]()?doPerf(g.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var g=[],S=4;S>=f;){var v=R[S];v&&v.batches&&v.batches[im]>0&&(arrForEach(v[xm],(function(f){P.addBatch(f)?C=C||f&&f[sm]()>0:g=g[nm](f[am]()),4===S?K-=f[sm]():J-=f[sm]()})),v[xm]=[],v.iKeyMap={}),S--}g[im]>0&&_notifyEvents(Yf,g,Bc.KillSwitch),C&&O>=f&&(O=-1,D=0)}),(function(){return{latency:f,sendType:S,sendReason:v}}),!_):(O=O>=0?Math.min(O,f):f,D=Math.max(D,v)),C}function _flushImpl(g,f){_sendEventsForLatencyAndAbove(1,0,f),_resetQueueCounts(),_waitForIdleManager((function(){g&&g(),W[im]>0?v=_createTimer((function(){v=null,_flushImpl(W.shift(),f)}),0):(v=null,_scheduleTimer())}))}function _waitForIdleManager(g){P[$m]()?g():v=_createTimer((function(){v=null,_waitForIdleManager(g)}),Hf)}function _resetTransmitProfiles(){_clearScheduledTimer(),_initializeProfiles(),Q=Tp,_scheduleTimer()}function _initializeProfiles(){(Y={})[Tp]=[2,1,0],Y[Ip]=[6,3,0],Y[bp]=[18,9,0]}function _requeueEvents(f,S){var v=[],C=L;k&&(C=F),arrForEach(f,(function(f){f&&f[sm]()>0&&arrForEach(f[am](),(function(f){f&&(f[mf]&&(f[pf]=4,f[mf]=!1),f[gf]<C?(setProcessTelemetryTimings(f,g[rf]),_addEventToQueues(f,!1)):v[om](f))}))})),v[im]>0&&_notifyEvents(Yf,v,Bc.NonRetryableStatus),k&&_releaseAllQueues(2,2)}function _callNotification(f,S){var v=H||{},C=v[f];if(C)try{C.apply(v,S)}catch(S){_throwInternal(g.diagLog(),1,74,f+" notification failed: "+S)}}function _notifyEvents(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];f&&f[im]>0&&_callNotification(g,[f][nm](S))}function _notifyBatchEvents(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];f&&f[im]>0&&arrForEach(f,(function(f){f&&f[sm]()>0&&_callNotification(g,[f.events()][nm](S))}))}function _sendingEvent(g,f,S){g&&g[im]>0&&_callNotification("eventsSendRequest",[f>=1e3&&f<=1999?f-1e3:0,!0!==S])}function _eventsSentEvent(g,f){_notifyBatchEvents("eventsSent",g,f),_scheduleTimer()}function _eventsDropped(g,f){_notifyBatchEvents(Yf,g,f>=8e3&&f<=8999?f-8e3:Bc.Unknown)}function _eventsResponseFail(g){_notifyBatchEvents(Yf,g,Bc.NonRetryableStatus),_scheduleTimer()}function _otherEvent(g,f){_notifyBatchEvents(Yf,g,Bc.Unknown),_scheduleTimer()}function _setAutoLimits(){w=B?0:Math.max($f*(zf+1),_/6)}_initDefaults(),g._getDbgPlgTargets=function(){return[P,f]},g[gm]=function(v,T,I){doPerf(T,(function(){return"PostChannel:initialize"}),(function(){S[gm](v,T,I),H=T.getNotifyMgr();try{x=mergeEvtNamespace(createUniqueNamespace(g[rf]),T.evtNamespace&&T.evtNamespace()),g._addHook(onConfigChange(v,(function(S){var v=S.cfg,I=createProcessTelemetryContext(null,v,T);f=I.getExtCfg(g[rf],Zf),U=createTimeoutWrapper(f[pm],f[mm]),N=!f[sf]&&isChromium(),V=f[af],_hookWParam(T),_=f[of],C=f.immediateEventLimit,M=f[lf],L=f.maxEventRetryAttempts,F=f.maxUnloadEventRetryAttempts,B=f[cf],_setAutoLimits(),j=f[df],G=!!f[hf],$&&_removeUnloadHandlers();var b=v.disablePageUnloadEvents||[];$=addPageUnloadEventListener(_handleUnloadEvents,b,x),$=addPageHideEventListener(_handleUnloadEvents,b,x)||$,$=addPageShowEventListener(_handleShowEvents,v.disablePageShowEvents,x)||$}))),P[gm](v,g.core,g)}catch(f){throw g.setInitialized(!1),f}}),(function(){return{theConfig:v,core:T,extensions:I}}))},g.processTelemetry=function(f,S){setProcessTelemetryTimings(f,g[rf]),S=S||g._getTelCtx(S);var v=f;G||q||(j&&(v[rm]=j),_addEventToQueues(v,!0),k?_releaseAllQueues(2,2):_scheduleTimer()),g.processNext(v,S)},g.getOfflineSupport=function(){try{var g=P&&P[wm]();if(P)return{getUrl:function(){return g?g.url:null},serialize:_serialize,batch:_batch,shouldProcess:function(g){return!G},createPayload:function(g){return null},createOneDSPayload:function(g){if(P[Dm])return P[Dm](g,N)}}}catch(g){}return null},g._doTeardown=function(g,f){_releaseAllQueues(2,2),q=!0,P.teardown(),_removeUnloadHandlers(),_initDefaults()},g.setEventQueueLimits=function(g,S){f[of]=_=isGreaterThanZero(g)?g:Jf,f[lf]=M=isGreaterThanZero(S)?S:0,_setAutoLimits();var v=J>g;if(!v&&w>0)for(var C=1;!v&&C<=3;C++){var T=R[C];T&&T[xm]&&arrForEach(T[xm],(function(g){g&&g[sm]()>=w&&(v=!0)}))}_performAutoFlush(!0,v)},g.pause=function(){_clearScheduledTimer(),z=!0,P.pause()},g.resume=function(){z=!1,P.resume(),_scheduleTimer()},g._loadTransmitProfiles=function(g){_resetTransmitProfiles(),objForEachKey(g,(function(g,f){var S=f[im];if(S>=2){var v=S>2?f[2]:0;if(f[cm](0,S-2),f[1]<0&&(f[0]=-1),f[1]>0&&f[0]>0){var C=f[0]/f[1];f[0]=Math.ceil(C)*f[1]}v>=0&&f[1]>=0&&v>f[1]&&(v=f[1]),f[om](v),Y[g]=f}}))},g.flush=function(g,f,S){var C;if(void 0===g&&(g=!0),!z)if(S=S||1,g)f||(C=createPromise((function(g){f=g}))),null==v?(_clearScheduledTimer(),_queueBatches(1,0,S),v=_createTimer((function(){v=null,_flushImpl(f,S)}),0)):W[om](f);else{var _=_clearScheduledTimer();_sendEventsForLatencyAndAbove(1,1,S),f&&f(),_&&_scheduleTimer()}return C},g.setMsaAuthTicket=function(g){P[Vm](Gp,g)},g.setAuthPluginHeader=function(g){P[Vm](qp,g)},g.removeAuthPluginHeader=function(){P.removeHeader(qp)},g.hasEvents=_hasEvents,g._setTransmitProfile=function(g){Q!==g&&void 0!==Y[g]&&(_clearScheduledTimer(),Q=g,_scheduleTimer())},proxyFunctions(g,(function(){return P}),["addResponseHandler"]),g[nf]=function(){b<Wf&&(b++,_clearScheduledTimer(),_scheduleTimer())},g._clearBackOff=function(){b&&(b=0,_clearScheduledTimer(),_scheduleTimer())}})),S}return __extendsFn(PostChannel2,g),PostChannel2.__ieDyn=1,PostChannel2}(Ig),iS="locale",nS="ver",rS="browser",sS="browserVer",aS="popSample",oS="eventFlags",lS="name",cS="serviceName",dS=Vc({UserExt:[0,"user"],DeviceExt:[1,"device"],TraceExt:[2,"trace"],WebExt:[3,"web"],AppExt:[4,"app"],OSExt:[5,"os"],SdkExt:[6,"sdk"],IntWebExt:[7,"intweb"],UtcExt:[8,"utc"],LocExt:[9,"loc"],CloudExt:[10,"cloud"],DtExt:[11,"dt"]}),hS=Vc({id:[0,"id"],ver:[1,nS],appName:[2,lS],locale:[3,iS],expId:[4,"expId"],env:[5,"env"]}),uS=Vc({domain:[0,"domain"],browser:[1,rS],browserVer:[2,sS],screenRes:[3,"screenRes"],userConsent:[4,"userConsent"],consentDetails:[5,"consentDetails"]}),gS=Vc({locale:[0,iS],localId:[1,"localId"],id:[2,"id"]}),pS=Vc({osName:[0,lS],ver:[1,nS]}),mS=Vc({ver:[0,nS],seq:[1,"seq"],installId:[2,"installId"],epoch:[3,"epoch"]}),fS=Vc({msfpc:[0,"msfpc"],anid:[1,"anid"],serviceName:[2,cS]}),SS=Vc({popSample:[0,aS],eventFlags:[1,oS]}),vS=Vc({tz:[0,"tz"]}),CS=Vc({sessionId:[0,"sesId"]}),yS=Vc({localId:[0,"localId"],deviceClass:[1,"deviceClass"],make:[2,"make"],model:[3,"model"]}),ES=Vc({role:[0,"role"],roleInstance:[1,"roleInstance"],roleVer:[2,"roleVer"]}),_S=Vc({traceId:[0,"traceID"],traceName:[1,lS],parentId:[2,"parentID"]}),TS=Vc({traceId:[0,"traceId"],spanId:[1,"spanId"],traceFlags:[2,"traceFlags"]});function canUseLocalStorage(){return void 0===eS&&(eS=!!_getVerifiedStorageObject(0)),eS}function _getLocalStorageObject(){return canUseLocalStorage()?_getVerifiedStorageObject(0):null}function _getVerifiedStorageObject(g){var f,S,v=null;try{var C=getGlobal();if(!C)return null;S=new Date,(v=0===g?C.localStorage:C.sessionStorage)&&hl(v.setItem)&&(v.setItem(S,S),f=v.getItem(S)!==S,v.removeItem(S),f&&(v=null))}catch(g){v=null}return v}function setStorage(g,f,S){var v=_getLocalStorageObject();if(null!==v)try{return v.setItem(f,S),!0}catch(f){eS=!1,_throwInternal(g,1,504,"Browser failed write to local storage. "+f)}return!1}function getStorage(g,f){var S=_getLocalStorageObject();if(null!==S)try{return S.getItem(f)}catch(f){eS=!1,_throwInternal(g,1,503,"Browser failed read of local storage. "+f)}return null}function _getId(){return this.getId()}function _setId(g){this.setId(g)}var IS=function(){function Session3(){dynamicProto(Session3,this,(function(g){g.setId=function(f){g.customId=f},g.getId=function(){return dl(g.customId)?g.customId:g.automaticId}}))}return Session3._staticInit=void objDefine(Session3.prototype,"id",{g:_getId,s:_setId}),Session3}(),bS="ai_session",AS=function(){function SessionManager2(g,f,S){var v,C,_,T=safeGetLogger(g),I=safeGetCookieMgr(g);dynamicProto(SessionManager2,this,(function(g){var b=onConfigChange(f,(function(){_=f,g.config=_}));function _initializeAutomaticSession(){var f=I.get(C());if(f&&hl(f.split))_initializeAutomaticSessionWithData(f);else{var S=getStorage(T,C());S&&_initializeAutomaticSessionWithData(S)}g.automaticSession.getId()||_renew()}function _initializeAutomaticSessionWithData(f){var S=g.automaticSession,v=f.split("|");v.length>0&&S.setId(v[0]);try{if(v.length>1){var C=+v[1];S.acquisitionDate=+new Date(C),S.acquisitionDate=S.acquisitionDate>0?S.acquisitionDate:0}if(v.length>2){var _=+v[2];S.renewalDate=+new Date(_),S.renewalDate=S.renewalDate>0?S.renewalDate:0}}catch(g){_throwInternal(T,1,510,"Error parsing ai_session cookie, session will be reset: "+g)}0===S.renewalDate&&_throwInternal(T,2,517,"AI session renewal date is 0, session will be reset.")}function _renew(){var f=g.automaticSession,S=(new Date).getTime(),v=g.config.sessionAsGuid;!isUndefined4(v)&&v?ml(v)?f.setId(createGuid()):f.setId(createGuid(v)):f.setId(newId(_.idLength||22)),f.acquisitionDate=S,f.renewalDate=S,_setCookie(f.getId(),f.acquisitionDate,f.renewalDate),canUseLocalStorage()||_throwInternal(T,2,505,"Browser does not support local storage. Session durations will be inaccurate.")}function _setCookie(f,S,_){var T=S+g.config.sessionExpirationMs,b=_+g.config.sessionRenewalMs,A=new Date,P=[f,S,_];T<b?A.setTime(T):A.setTime(b);var R=g.config.cookieDomain||null;I.set(C(),P.join("|")+";expires="+A.toUTCString(),null,R),v=(new Date).getTime()}function _setStorage(g,f,S){setStorage(T,C(),[g,f,S].join("|"))}S&&S.add(b),C=function(){return g.config.namePrefix?bS+g.config.namePrefix:bS},g.automaticSession=new IS,g.update=function(){g.automaticSession.getId()||_initializeAutomaticSession();var f=g.automaticSession,S=g.config,C=(new Date).getTime(),_=C-f.acquisitionDate>S.sessionExpirationMs,T=C-f.renewalDate>S.sessionRenewalMs;if(_||T)_renew();else{(!v||C-v>SessionManager2.cookieUpdateInterval)&&(f.renewalDate=C,_setCookie(f.getId(),f.acquisitionDate,f.renewalDate))}},g.backup=function(){var f=g.automaticSession;_setStorage(f.getId(),f.acquisitionDate,f.renewalDate)}}))}return SessionManager2.cookieUpdateInterval=6e4,SessionManager2}(),PS=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function _validateAppExpId(g,f){void 0===f&&(f=PS);var S=null;if(g)for(var v=g.split(","),C=0;C<v.length;C++)_isValidAppFlightId(v[C],f)&&(S?S+=","+v[C]:S=v[C]);return S}function _isValidAppFlightId(g,f){if(void 0===f&&(f=PS),!g||g.length<4)return!1;for(var S=!1,v=256,C=g.substring(0,3).toString().toUpperCase(),_=0;_<f.length;_++)if(f[_]+":"===C&&g.length<=v){S=!0;break}return S}function _getExpId(){return this.getExpId()}var RS=function(){function Application2(g,f,S){var v,C=null,_=PS.slice(0),T="Treatments",I=null;dynamicProto(Application2,this,(function(b){if(_populateDefaults(g),hasDocument()){var A=jl().documentElement;A&&(b.locale=A.lang)}function _getMetaDataFromDOM(g){var f,S={},v=jl();if(v){f=v&&v.querySelectorAll("meta");for(var C=0;C<f.length;C++){var _=f[C];if(_.name)if(0===_.name.toLowerCase().indexOf(g))S[_.name.replace(g,"")]=_.content}}return S}function _setAppExpId(g){g!==C&&(C=_validateAppExpId(g,_))}function _readExpIdFromCookie(){return _setAppExpId(getCookieValue(v,T)),C}function _readExpIdFromCoreData(g){return _setAppExpId(g),C}function _populateDefaults(g){var C=onConfigChange(g,(function(){v=f&&f.getCookieMgr(),I=g||{},b.env=I.env||_getMetaDataFromDOM("awa-").env}));S&&S.add(C)}b.getExpId=function(){return I.expId?_readExpIdFromCoreData(I.expId):_readExpIdFromCookie()}}))}return Application2.validateAppExpId=_validateAppExpId,Application2._staticInit=void objDefine(Application2.prototype,"expId",{g:_getExpId}),Application2}(),MS=function(){function Cloud2(){}return Cloud2}(),wS=function(){function Device3(){}return Device3}();function _getMsfpc2(){return this.getMsfpc()}function _getAnid(){return this.getAnid()}var OS=function(){function IntWeb2(g,f,S){var v;dynamicProto(IntWeb2,this,(function(C){function _populateDefaults(g){var _=onConfigChange(g,(function(){v=f&&f.getCookieMgr();var S=g||{};S.serviceName&&(C.serviceName=S.serviceName)}));S&&S.add(_)}_populateDefaults(g),C.getMsfpc=function(){return getCookieValue(v,"MSFPC")},C.getAnid=function(){return getCookieValue(v,"ANON").slice(0,34)}}))}var g;return IntWeb2._staticInit=(objDefine(g=IntWeb2.prototype,"msfpc",{g:_getMsfpc2}),void objDefine(g,"anid",{g:_getAnid})),IntWeb2}(),DS=function(){function Loc2(){var g=(new Date).getTimezoneOffset(),f=g%60,S=(g-f)/60,v="+";S>0&&(v="-"),S=Math.abs(S),f=Math.abs(f),this.tz=v+(S<10?"0"+S:S.toString())+":"+(f<10?"0"+f:f.toString())}return Loc2}(),NS={WIN:/(windows|win32)/i,WINRT:/ arm;/i,WINPHONE:/windows\sphone\s\d+\.\d+/i,OSX:/(macintosh|mac os x)/i,IOS:/(ipad|iphone|ipod)(?=.*like mac os x)/i,LINUX:/(linux|joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)/i,ANDROID:/android/i,CROS:/CrOS/i},kS={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},LS="([\\d,.]+)",FS="([\\d,_,.]+)",xS="Unknown",US=[{r:NS.WINPHONE,os:"Windows Phone"},{r:NS.WINRT,os:"Windows RT"},{r:NS.WIN,os:"Windows"},{r:NS.IOS,os:"iOS"},{r:NS.ANDROID,os:"Android"},{r:NS.LINUX,os:"Linux"},{r:NS.CROS,os:"Chrome OS"},{s:"x11",os:"Unix"},{s:"blackberry",os:"BlackBerry"},{s:"symbian",os:"Symbian"},{s:"nokia",os:"Nokia"},{r:NS.OSX,os:"Mac OS X"}];function _getOsName(g){for(var f=0;f<US.length;f++){var S=US[f];if(S.r&&g.match(S.r))return S.os;if(S.s&&-1!==g.indexOf(S.s))return S.os}return xS}function _getOsVersion(g,f){return"Windows"===f?_getGenericOsVersion(g,"Windows NT"):"Android"===f?_getGenericOsVersion(g,f):"Mac OS X"===f?_getMacOsxVersion(g):"iOS"===f?_getIosVersion(g):xS}function _getGenericOsVersion(g,f){var S=g.match(new RegExp(f+" "+LS));return S?kS[S[1]]?kS[S[1]]:S[1]:xS}function _getMacOsxVersion(g){var f=g.match(new RegExp("Mac OS X "+FS));if(f){var S=f[1].replace(/_/g,".");if(S){var v=_getDelimiter(S);return v?S.split(v)[0]:S}}return xS}function _getIosVersion(g){var f=g.match(new RegExp("OS "+FS));if(f){var S=f[1].replace(/_/g,".");if(S){var v=_getDelimiter(S);return v?S.split(v)[0]:S}}return xS}function _getDelimiter(g){return g.indexOf(".")>-1?".":g.indexOf("_")>-1?"_":null}var VS=function(){function OperatingSystem2(g,f){var S=this,v=null,C=null,_=null,T=null,_setSysName=function(g){_=g},_setSysVer=function(g){T=g},_getSysName=function(){return _||v},_getSysVer=function(){return T||C},I=onConfigChange(g,(function(){if((g||{}).populateOperatingSystemInfo){var f=Kl()||{},S=g.userAgent||f.userAgent||"",_=(g.userAgentData||{}).platform||(f.userAgentData||{}).platform;if(S){var T=_getOsName(S.toLowerCase());v=T,C=_getOsVersion(S,T)}v&&v!==xS||!dl(_)||(v=_)}}));f&&f.add(I),objDefine(S,"name",{s:_setSysName,g:_getSysName}),objDefine(S,"ver",{s:_setSysVer,g:_getSysVer})}return OperatingSystem2}(),BS="MicrosoftApplicationsTelemetryDeviceId";function _saveData(g,f,S,v){f?f.setProperty(S,v):g.set(S,v,31536e3)}function _getData(g,f,S){return f?f.getProperty(S)||"":getCookieValue(g,S)}var HS=function(){function Sdk2(g,f,S){var v,C=0;dynamicProto(Sdk2,this,(function(_){_.seq=C,_.epoch=random32(!1).toString(),_.getSequenceId=function(){return++C};var T=onConfigChange(g,(function(g){v=f&&f.getCookieMgr();var S=g.cfg.propertyStorageOverride;if(v.isEnabled()||S){var C=_getData(v,S,BS);C||(C=newGuid2()),_saveData(v,S,BS,C),_.installId=C}else v.purge(BS)}));S&&S.add(T)}))}return Sdk2.__ieDyn=1,Sdk2}(),$S=function(){function Trace2(g,f,S,v,C){var _=this;_.traceId=f||generateW3CId();var T=onConfigChange(g,(function(){var f=g;if(f.enableDistributedTracing&&!S&&(S=generateW3CId().substring(0,16)),_.parentId=_.parentId||S,f.enableApplicationInsightsTrace&&!v){var C=getLocation();C&&C.pathname&&(v=C.pathname)}_.name=_.name||v}));C&&C.add(T)}return Trace2}(),jS="setLocalId";function _getLocalId(){return this.getLocalId()}function _setLocalId(g){this[jS](g)}var GS=function(){function User2(g,f,S,v){var C,_,T;dynamicProto(User2,this,(function(I){if(_populateDefaults(f),"undefined"!=typeof navigator){var b=navigator;I.locale=b.userLanguage||b.language}function _populateMuidFromCookie(){if(!C.hashIdentifiers&&!C.dropIdentifiers){var g=getCookieValue(T,"MUID");g&&(_="t:"+g)}return _}function _populateDefaults(f){var b=onConfigChange(f,(function(){if(T=S&&S.getCookieMgr(),C=f,_=null,T&&T.isEnabled()&&(_populateMuidFromCookie(),C.enableApplicationInsightsUser)){var v=getCookieValue(T,User2.userCookieName);if(v){var b=v.split(User2.cookieSeparator);b.length>0&&(I.id=b[0])}if(!I.id){I.id=newId(g&&!isUndefined4(g.idLength)?g.idLength:22);var A=toISOString(new Date);I.accountAcquisitionDate=A;var P=[I.id,A],R=C.cookieDomain?C.cookieDomain:void 0;T.set(User2.userCookieName,P.join(User2.cookieSeparator),31536e3,R)}}}));v&&v.add(b)}I.getLocalId=function(){return _||_populateMuidFromCookie()},I[jS]=function(g){_=g}}))}return User2.cookieSeparator="|",User2.userCookieName="ai_user",User2._staticInit=void objDefine(User2.prototype,"localId",{g:_getLocalId,s:_setLocalId}),User2}(),qS=1048576,WS=2097152,zS=4194304,KS=function(){function Utc2(g,f){var S=this;S.popSample=100;var v=onConfigChange(g,(function(){S.eventFlags=0,g.hashIdentifiers&&(S.eventFlags=S.eventFlags|qS),g.dropIdentifiers&&(S.eventFlags=S.eventFlags|WS),g.scrubIpOnly&&(S.eventFlags=S.eventFlags|zS)}));f&&f.add(v)}return Utc2}(),JS=["Required","Analytics","SocialMedia","Advertising"],YS="([\\d,.]+)",QS="Unknown",XS="Edg/",ZS=[{ua:"OPR/",b:"Opera"},{ua:"PhantomJS",b:"PhantomJS"},{ua:"Edge",b:"Edge"},{ua:XS,b:"Edge"},{ua:"Electron",b:"Electron"},{ua:"Chrome",b:"Chrome"},{ua:"Trident",b:"MSIE"},{ua:"MSIE ",b:"MSIE"},{ua:"Firefox",b:"Firefox"},{ua:"Safari",b:"Safari"},{ua:"SkypeShell",b:"SkypeShell"}],ev=[{br:"Microsoft Edge",b:"Edge"},{br:"Google Chrome",b:"Chrome"},{br:"Opera",b:"Opera"}];function _userAgentContainsString(g,f){return f.indexOf(g)>-1}function _getBrandVersion(g,f){for(var S=0;S<f.length;S++)if(g==f[S].brand)return f[S].version;return null}function _getBrowserName(g){if(g)for(var f=0;f<ZS.length;f++){if(_userAgentContainsString(ZS[f].ua,g))return ZS[f].b}return QS}function _getBrowserVersion(g,f){return"MSIE"===f?_getIeVersion(g):_getOtherVersion(f,g)}function _getIeVersion(g){var f=g.match(new RegExp("MSIE "+YS));if(f)return f[1];var S=g.match(new RegExp("rv:"+YS));return S?S[1]:void 0}function _getOtherVersion(g,f){"Safari"===g?g="Version":"Edge"===g&&_userAgentContainsString(XS,f)&&(g="Edg");var S=f.match(new RegExp(g+"/"+YS));return S||"Opera"===g&&(S=f.match(new RegExp("OPR/"+YS)))?S[1]:QS}function _getScreenResolution(){var g={h:0,w:0},f=Gl();return f&&f.screen&&(g.h=screen.height,g.w=screen.width),g}function _getUserConsent(){return this.getUserConsent()}var tv=function(){function Web2(g,f,S){var v=safeGetCookieMgr(f),C=g||{},_=null,T=null,I=null,b=null,A=null,P=null,R=null;dynamicProto(Web2,this,(function(f){_populateDefaults(g);var M=getLocation();if(M){var w=M.hostname;w&&(f.domain="file:"===M.protocol?"local":w)}var O=_getScreenResolution();function _parseUserAgent(g,f){if(ul(f))try{for(var S=0;S<ev.length;S++){var v=_getBrandVersion(ev[S].br,f);if(v)return A=ev[S].b,void(P=v)}}catch(g){}if(g){var C=_getBrowserName(g);A=C,P=_getBrowserVersion(g,C)}}function _setBrowser(g){I=g}function _setBrowserVer(g){b=g}function _getBrowser(){return I||A}function _getBrowserVer(){return b||P}f.screenRes=O.w+"X"+O.h,f.getUserConsent=function(){return C.userConsented||!!getCookieValue(v,C.userConsentCookieName||"MSCC")},f.getUserConsentDetails=function(){var g=null;try{var f=C.callback;if(f&&f.userConsentDetails){var S=f.userConsentDetails();if(S){g=C.disableConsentDetailsSanitize?S:{};for(var v=0;v<JS.length;v++){var _=JS[v];g[_]=S[_]||!1}}}return null!==R&&((g=g||{}).GPC_DataSharingOptIn=!!R),g?JSON.stringify(g):null}catch(g){}};var _getGpcDataSharing=function(){return R},_setGpcDataSharing=function(g){R=ml(g)?g:null,C.gpcDataSharingOptIn=R};function _populateDefaults(g){var f=onConfigChange(g,(function(){if((C=g).populateBrowserInfo){var f=C.userAgent,S=(C.userAgentData||{}).brands;if(f!==_||S!==T){if(!f||!S||0===S.length){var v=Kl();v&&(f=f||v.userAgent||"",S=S||(v.userAgentData||{}).brands)}_parseUserAgent(f,S),_=f,T=S}}R=ml(C.gpcDataSharingOptIn)?C.gpcDataSharingOptIn:null}));S&&S.add(f)}objDefineProps(f,{userConsent:{g:f.getUserConsent},browser:{s:_setBrowser,g:_getBrowser},browserVer:{s:_setBrowserVer,g:_getBrowserVer},gpcDataSharingOptIn:{g:_getGpcDataSharing,s:_setGpcDataSharing}})}))}return Web2._staticInit=void objDefine(Web2.prototype,"userConsent",{g:_getUserConsent}),Web2}();function _applyExtValues(g,f,S,v,C){var _=f.ext[dS[g]];if(_)try{objForEachKey(v,(function(g,f){if(dl(f)||pl(f)||ml(f)){var v=_[S[g]];!C&&(v||dl(v)||pl(v)||ml(v))&&(f=v),_[S[g]]=f}}))}catch(g){}return _}var iv,nv=function(){function TelemetryContext4(g,f,S,v){dynamicProto(TelemetryContext4,this,(function(C){C.app=new RS(f,S,v),C.cloud=new MS,C.user=new GS(g,f,S,v),C.os=new VS(f,v),C.web=new tv(f,S,v);var _=new HS(g,S,v),T=new OS(f,S,v),I=new KS(f,v);C.loc=new DS,C.device=new wS;var b=new AS(S,f,v);C.session=new IS;var A=void 0,P=createDistributedTraceContextFromTraceCtx(new $S(f,A,A,A,v),_getTraceCtx()),R=!(f||{}).eventContainExtFields;function _getSessionId(){var g=C.session;if(g&&dl(g.customId))return g.customId;b.update();var f=b.automaticSession;if(f){var S=f.getId();S&&dl(S)&&(g.automaticId=S)}return g.automaticId}function _getTraceCtx(){var g=P;return S&&S.getTraceCtx&&(g=S.getTraceCtx(!1)||P),g}C.getTraceCtx=function(){return P},C.getSessionId=_getSessionId,C.applyApplicationContext=function(g){var f,S=C.app;_applyExtValues(4,g,hS,((f={})[0]=S.id,f[1]=S.ver,f[2]=S.name,f[3]=S.locale,f[4]=S.getExpId(),f[5]=S.env,f),R)},C.applyUserContext=function(g){var f,S=C.user;_applyExtValues(0,g,gS,((f={})[1]=S.getLocalId(),f[0]=S.locale,f[2]=S.id,f),R)},C.applyWebContext=function(g){var f,S=C.web;_applyExtValues(3,g,uS,((f={})[0]=S.domain,f[1]=S.browser,f[2]=S.browserVer,f[3]=S.screenRes,f[5]=S.getUserConsentDetails(),f[4]=S.getUserConsent(),f),R)},C.applyOsContext=function(g){var f,S=C.os;_applyExtValues(5,g,pS,((f={})[0]=S.name,f[1]=S.ver,f),R)},C.applySdkContext=function(g){var f;_applyExtValues(6,g,mS,((f={})[2]=_.installId,f[1]=_.getSequenceId(),f[3]=_.epoch,f),R)},C.applyIntWebContext=function(g){var f;_applyExtValues(7,g,fS,((f={})[0]=T.getMsfpc(),f[1]=T.getAnid(),f[2]=T.serviceName,f),R)},C.applyUtcContext=function(g){var f,S=((f={})[0]=I.popSample,f);I.eventFlags>0&&(S[1]=I.eventFlags),_applyExtValues(8,g,SS,S,R)},C.applyLocContext=function(g){var f;_applyExtValues(9,g,vS,((f={})[0]=C.loc.tz,f),R)},C.applySessionContext=function(g){var f;_applyExtValues(4,g,CS,((f={})[0]=_getSessionId(),f),R)},C.applyDeviceContext=function(g){var f,S=C.device;_applyExtValues(1,g,yS,((f={})[0]=S.localId,f[2]=S.make,f[3]=S.model,f[1]=S.deviceClass,f),R)},C.applyCloudContext=function(g){var f,S=C.cloud;_applyExtValues(10,g,ES,((f={})[0]=S.role,f[1]=S.roleInstance,f[2]=S.roleVer,f),R)},C.applyAITraceContext=function(g){var S;if(f.enableApplicationInsightsTrace){var v=_getTraceCtx();v&&_applyExtValues(2,g,_S,((S={})[0]=v.getTraceId(),S[1]=v.getName(),S[2]=v.getSpanId(),S),!1)}},C.applyDistributedTraceContext=function(g){var f,S=_getTraceCtx();if(S){var v=((f={})[0]=S.getTraceId(),f[1]=S.getSpanId(),f),C=S.getTraceFlags();isNullOrUndefined(C)||(v[2]=C),_applyExtValues(11,g,TS,v,!1)}}}))}return TelemetryContext4.__ieDyn=1,TelemetryContext4}();function createDistributedTraceContextFromTraceCtx(g,f){var S=g||{};return{getName:function(){return S.name},setName:function(g){f&&f.setName(g),S.name=g},getTraceId:function(){return S.traceId},setTraceId:function(g){f&&f.setTraceId(g),isValidTraceId(g)&&(S.traceId=g)},getSpanId:function(){return S.parentId},setSpanId:function(g){f&&f.setSpanId(g),isValidSpanId(g)&&(S.parentId=g)},getTraceFlags:function(){return S.traceFlags},setTraceFlags:function(g){f&&f.setTraceFlags(g),S.traceFlags=g}}}var rv=[dS[4],dS[0],dS[3],dS[5],dS[6],dS[7],dS[8],dS[9],dS[1],dS[2],dS[11],dS[10]],sv=objDeepFreeze({populateBrowserInfo:!1,populateOperatingSystemInfo:!1,userAgent:cfgDfString(),userAgentData:cfgDfMerge({brands:iv,mobile:iv,platform:iv}),userConsentCookieName:cfgDfString(),userConsented:!1,serviceName:cfgDfString(),env:cfgDfString(),expId:cfgDfString(),sessionRenewalMs:18e5,sessionExpirationMs:864e5,sessionAsGuid:null,cookieDomain:cfgDfString(),namePrefix:cfgDfString(),enableApplicationInsightsTrace:!1,enableApplicationInsightsUser:!1,hashIdentifiers:!1,dropIdentifiers:!1,scrubIpOnly:!1,callback:cfgDfMerge({userConsentDetails:null}),gpcDataSharingOptIn:iv,idLength:22,enableDistributedTracing:!1,eventContainExtFields:!1}),av=function(g){function PropertiesPlugin2(){var f,S,v,C=g.call(this)||this;return C.identifier="SystemPropertiesCollector",C.priority=3,C.version="4.2.1",dynamicProto(PropertiesPlugin2,C,(function(g,C){function _initDefaults(){f=null,S={}}function _populateDefaults(S){var C=g.identifier,_=g.core;g._addHook(onConfigChange(S,(function(){var g=createProcessTelemetryContext(null,S,_);v=g.getExtCfg(C,sv)}))),f=new nv(S,v,_,g._unloadHooks),_&&_.setTraceCtx&&_.setTraceCtx(f.getTraceCtx())}function _addPropertiesIfAbsent(g,f){g&&objForEachKey(g,(function(g,S){f[g]||(f[g]=S)}))}_initDefaults(),g.initialize=function(g,f,S){C.initialize(g,f,S),_populateDefaults(g)},g.processTelemetry=function(C,_){setProcessTelemetryTimings(C,g.identifier),_=g._getTelCtx(_);var T=C.ext=C.ext?C.ext:{};C.data=C.data?C.data:{},arrForEach(rv,(function(g){T[g]=T[g]||{}})),f&&(f.applyUtcContext(C),f.applyApplicationContext(C),f.applyUserContext(C),f.applyWebContext(C),f.applyOsContext(C),f.applySdkContext(C),f.applyIntWebContext(C),f.applyLocContext(C),f.applySessionContext(C),f.applyDeviceContext(C),v.enableApplicationInsightsTrace&&f.applyAITraceContext(C),v.enableDistributedTracing&&f.applyDistributedTraceContext(C),f.applyCloudContext(C)),arrForEach(Al(T),(function(g){0===Al(T[g]).length&&delete T[g]})),_addPropertiesIfAbsent(S,C.data),g.processNext(C,_)},g.getPropertiesContext=function(){return f},g.setProperty=function(g,f){S[g]=f},g._doTeardown=function(g,S){var v=(g||{}).core();if(v&&v.getTraceCtx&&f){var C=v.getTraceCtx(!1);C&&C===f.getTraceCtx()&&v.setTraceCtx(null)}_initDefaults()},g._getDbgPlgTargets=function(){return[v]}})),C}return __extendsFn(PropertiesPlugin2,g),PropertiesPlugin2.__ieDyn=1,PropertiesPlugin2}(Ig),ov=function(){function BaseContext2(g){this._setOverride=function(f,S){g.setOverride(f,S)},this._getOverride=function(f){return g.getOverride(f)}}return BaseContext2}(),lv=function(g){function ApplicationContext2(f,S,v){var C=g.call(this,f)||this,_=C;_.setId=function(g){_._setOverride(hS.id,g)},_.getId=function(){return _._getOverride(hS.id)},_.setVer=function(g){_._setOverride(hS.ver,g)},_.getVer=function(){return _._getOverride(hS.ver)},_.setName=function(g){_._setOverride(hS.appName,g)},_.getName=function(){return _._getOverride(hS.appName)},_.setLocale=function(g){_._setOverride(hS.locale,g)},_.getLocale=function(){return _._getOverride(hS.locale)},_.setEnv=function(g){_._setOverride(hS.env,g)},_.getEnv=function(){return _._getOverride(hS.env)},_.setExpId=function(g){_._setOverride(hS.expId,RS.validateAppExpId(g))},_.getExpId=function(){return _._getOverride(hS.expId)};var T=onConfigChange(S,(function(){S&&(isUndefined4(S.env)||_.setEnv(S.env),isNullOrUndefined(S.expId)||_.setExpId(S.expId))}));return v&&v.add(T),C}return __extendsFn(ApplicationContext2,g),ApplicationContext2}(ov),cv=function(g){function CloudContext2(f){var S=g.call(this,f)||this,v=S;return v.setRole=function(g){v._setOverride(ES.role,g)},v.getRole=function(){return v._getOverride(ES.role)},v.setRoleInstance=function(g){v._setOverride(ES.roleInstance,g)},v.getRoleInstance=function(){return v._getOverride(ES.roleInstance)},v.setRoleVer=function(g){v._setOverride(ES.roleVer,g)},v.getRoleVer=function(){return v._getOverride(ES.roleVer)},S}return __extendsFn(CloudContext2,g),CloudContext2}(ov),dv=function(g){function DataContext2(f){var S=g.call(this,f)||this,v=S;return v.setProperty=function(g,f){v._setOverride(g,f)},v.getProperty=function(g){return v._getOverride(g)},S}return __extendsFn(DataContext2,g),DataContext2}(ov),hv=function(g){function DeviceContext2(f){var S=g.call(this,f)||this,v=S;return v.setLocalId=function(g){v._setOverride(yS.localId,g)},v.getLocalId=function(){return v._getOverride(yS.localId)},v.setDeviceClass=function(g){v._setOverride(yS.deviceClass,g)},v.getDeviceClass=function(){return v._getOverride(yS.deviceClass)},v.setMake=function(g){v._setOverride(yS.make,g)},v.getMake=function(){return v._getOverride(yS.make)},v.setModel=function(g){v._setOverride(yS.model,g)},v.getModel=function(){return v._getOverride(yS.model)},S}return __extendsFn(DeviceContext2,g),DeviceContext2}(ov),uv=function(g){function LocContext2(f){var S=g.call(this,f)||this,v=S;return v.setTz=function(g){v._setOverride(vS.tz,g)},v.getTz=function(){return v._getOverride(vS.tz)},S}return __extendsFn(LocContext2,g),LocContext2}(ov),gv=function(g){function OperatingSystemContext2(f,S,v){var C=g.call(this,f)||this,_=C,T=null;_.setOsName=function(g){_._setOverride(pS.osName,g)},_.getOsName=function(){return _._getOverride(pS.osName)},_.setVer=function(g){_._setOverride(pS.ver,g)},_.getVer=function(){return _._getOverride(pS.ver)};var I=onConfigChange(S,(function(){!T&&S.userAgent&&S.populateOperatingSystemInfo&&(T=new VS(S,v)),T&&(_.setOsName(T.name),_.setVer(T.ver))}));return v&&v.add(I),C}return __extendsFn(OperatingSystemContext2,g),OperatingSystemContext2}(ov);function _getEventRoot(g,f){if(g)for(var S=0;S<f.length;S++){var v=f[S];isNullOrUndefined(g[v])&&(g[v]={}),g=g[v]}return g}function _setOverride(g,f,S){if(g&&f){var v=f.split("."),C=v[v.length-1];v.length>1&&(g=_getEventRoot(g,v.slice(0,-1))),isNullOrUndefined(S)?isUndefined4(g[C])||delete g[C]:g[C]=S}}var pv,mv,fv=function(){function OverrideContainer2(g){var f=this,S=[];f.setOverride=function(g,f){g&&S.push({key:g,value:f})},f.hasOverride=function(g){var f=!1;return arrForEach(S,(function(S){S.key===g&&(f=!0)})),f},f.getOverride=function(g){var f;return arrForEach(S,(function(S){S.key===g&&(f=S.value)})),f},f.applyOverrides=function(f,v){if(S.length>0)try{var C=_getEventRoot(f,g);arrForEach(S,(function(g){_setOverride(C,g.key,g.value)}))}catch(g){}}}return OverrideContainer2}(),Sv=function(g){function UserContext2(f){var S=g.call(this,f)||this,v=S;return v.setLocalId=function(g){v._setOverride(gS.localId,g)},v.getLocalId=function(){return v._getOverride(gS.localId)},v.setLocale=function(g){v._setOverride(gS.locale,g)},v.getLocale=function(){return v._getOverride(gS.locale)},v.setId=function(g){v._setOverride(gS.id,g)},v.getId=function(){return v._getOverride(gS.id)},S}return __extendsFn(UserContext2,g),UserContext2}(ov),vv=function(g){function WebContext2(f,S,v){var C=g.call(this,f)||this,_=C;_.setDomain=function(g){_._setOverride(uS.domain,g)},_.getDomain=function(){return _._getOverride(uS.domain)},_.setBrowser=function(g){_._setOverride(uS.browser,g)},_.getBrowser=function(){return _._getOverride(uS.browser)},_.setBrowserVer=function(g){_._setOverride(uS.browserVer,g)},_.getBrowserVer=function(){return _._getOverride(uS.browserVer)},_.setScreenRes=function(g){_._setOverride(uS.screenRes,g)},_.getScreenRes=function(){return _._getOverride(uS.screenRes)},_.setUserConsent=function(g){_._setOverride(uS.userConsent,g)},_.getUserContext=function(){return _._getOverride(uS.userConsent)};var T=onConfigChange(S,(function(){S&&(isUndefined4(S.userConsented)||_.setUserConsent(S.userConsented))}));return v&&v.add(T),C}return __extendsFn(WebContext2,g),WebContext2}(ov),Cv="ext",yv="data",Ev=function(){function OverrideContext2(g,f,S,v){var C=this,_={};function _getContainer(g){for(var f="",S=0;S<g.length;S++)f&&(f+="_"),f+=g[S];return isUndefined4(_[f])&&(_[f]=new fv(g)),f?_[f]:null}C.data=new dv(_getContainer([yv])),C.app=new lv(_getContainer([Cv,dS.AppExt]),f,v),C.user=new Sv(_getContainer([Cv,dS.UserExt])),C.os=new gv(_getContainer([Cv,dS.OSExt]),f,v),C.web=new vv(_getContainer([Cv,dS.WebExt]),f,v),C.device=new hv(_getContainer([Cv,dS.DeviceExt])),C.loc=new uv(_getContainer([Cv,dS.LocExt])),C.cloud=new cv(_getContainer([Cv,dS.CloudExt])),C.applyOverrides=function(g,f){var S=Al(_);S&&S.length>0&&arrForEach(S,(function(S){_[S].applyOverrides(g,f)}))}}return OverrideContext2}(),_v=void 0,Tv=objDeepFreeze({env:_v,expId:_v,populateOperatingSystemInfo:!1,userAgent:_v,userAgentData:cfgDfMerge({brands:_v,mobile:_v,platform:_v}),userConsented:_v}),Iv="OverridePropertiesPlugin",bv=function(g){function OverridePropertiesPlugin2(){var f=g.call(this)||this;f.identifier=Iv,f.priority=4,f.version="4.2.1";var S=null;return dynamicProto(OverridePropertiesPlugin2,f,(function(g,v){g.initialize=function(f,S,C){v.initialize(f,S,C),g._baseInit(f,S,C)},g.processTelemetry=function(S,v){setProcessTelemetryTimings(S,f.identifier),v=g._getTelCtx(v);var C=g.getOverrideContext();C&&C.applyOverrides(S,v),g.processNext(S,v)},g._baseInit=function(v,C,_){S=new Ev(v,f._getTelCtx().getExtCfg(f.identifier,Tv),C,g._unloadHooks)},g.setProperty=function(g,f){S&&S.data.setProperty(g,f)},g.getOverrideContext=function(){return S}})),f}return __extendsFn(OverridePropertiesPlugin2,g),OverridePropertiesPlugin2.__ieDyn=1,OverridePropertiesPlugin2}(Ig),Av="_dropInst",Pv=["channelConfiguration","propertyStorageOverride"];function _fixupExtensionConfig(g){if(g&&ul(g.extensionConfig)){var f=g.extensionConfig,S={};objForEachKey(f,(function(g,f){hl(f)||lc(g,"Symbol(")||(S[g]=f)})),g.extensionConfig=S}return g}function _copyObjProperties(g,f){if(f)for(var S=Al(f),v=0;v<S.length;v++){var C=S[v];vl(g,C)||lc(C,"Symbol(")||(g[C]=f[C])}}function _proxyReadonlyProperty(g,f,S){var v;return objDefine(g,f,{g:function(){return isPrimitive(S)?S:(ul(S)?(ul(v)||(v=[]),v.length=S.length):isObject3(v)||(v={}),objForEachKey(S,(function(g,f){lc(g,"Symbol(")||_proxyReadonlyProperty(v,g,f)})),v)}})}function _isChannel(g){return g.pause&&g.teardown&&g.flush}function _getEndpointUrl(g,f){var S=null;if(f){f.endpointUrl&&(S=f.endpointUrl);var v=(f.extensionConfig||{})[g]||{};v.overrideEndpointUrl&&(S=v.overrideEndpointUrl)}return S}var Rv=objDeepFreeze({cookieCfg:{},channelConfiguration:cfgDfMerge({}),propertyConfiguration:cfgDfMerge({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:cfgDfMerge({}),createPerfMgr:mv,loggingLevelConsole:0}),Mv=objDeepFreeze({propertyConfiguration:cfgDfMerge({}),cookieCfg:cfgDfMerge({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:cfgDfMerge((pv={},pv[Iv]=cfgDfMerge({}),pv)),createPerfMgr:mv,loggingLevelConsole:0}),wv=function(g){function ChildNotificationManager2(f,S){var v=g.call(this)||this;return dynamicProto(ChildNotificationManager2,v,(function(g,v){function _getEvents(g){var S=[];return g&&arrForEach(g,(function(g){g.iKey===f&&S.push(g)})),S}function _hasListeners(f){if(g[f]&&g.listeners)for(var S=0;S<g.listeners.length;S++){var v=g.listeners[S];if(v&&v[f])return!0}return!1}var C={eventsSent:function(f){if(_hasListeners("eventsSent")){var S=_getEvents(f);S.length>0&&g.eventsSent(S)}},eventsDiscarded:function(f,S){if(_hasListeners("eventsDiscarded")){var v=_getEvents(f);v.length>0&&g.eventsDiscarded(v,S)}},eventsSendRequest:function(f,S){_hasListeners("eventsSendRequest")&&g.eventsSendRequest(f,S)},perfEvent:function(f){_hasListeners("perfEvent")&&g.perfEvent(f)}};S.addNotificationListener(C)})),v}return __extendsFn(ChildNotificationManager2,g),ChildNotificationManager2.__ieDyn=1,ChildNotificationManager2}(ag),Ov=function(){function ApplicationInsightsManager2(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w,O=null,D=null;dynamicProto(ApplicationInsightsManager2,this,(function(N){function _initDefaults(){g=createDynamicConfig({},Rv,null),f=[],S=null,v=null,C=[],_=[],T={},I=null,b=null,A=null,R=null,M=null,w=!1,g.cfg.loggingLevelConsole=1,P=new Gu(g.cfg),objDefine(N,"sharedConfig",{g:function(){return w&&_initializeSharedInstance(),g.cfg}})}function _registerPlugin(f,S){var v;if(void 0===S&&(S=null),f){(_isChannel(f)?_:C).push(f);var T=f.identifier,I=g.cfg.extensionConfig;g.setDf(I,((v={})[T]={ref:!0,v:S||{}},v))}return f}function _initializeSharedChannels(){var f=g.cfg,S=f.channels,v=new tS,C=v.identifier,_=!1;b=null,A=null,arrForEach(S,(function(g){_||arrForEach(g,(function(g){if(!hl(g)&&(_registerPlugin(g),g.identifier===C))return b=g,_=!0,-1}))})),_||(b=_registerPlugin(v,f.channelConfiguration),S.length>0?arrAppend(S[0],b):f.channels.push([b]))}function _initializeSharedExtensions(S){var v=g.cfg;f=[],I=_registerPlugin(new av,v.propertyConfiguration),f.push(I),v.extensions&&arrForEach(v.extensions,(function(g){hl(g)||_registerPlugin(g)})),S&&arrForEach(S,(function(g){g&&!hl(g)&&f.push(_registerPlugin(g))}))}function _initializeSharedInstance(){S||(w||_throwInternal(N.diagLog(),2,520,"The Shared Manager is not yet created, the returned shared instance will be overwritten"),g.cfg.instrumentationKey=g.cfg.instrumentationKey||"_not_defined_",v=new ag,(S=new Dv(N,N.diagLog(),v)).initialize(g.cfg,f),S.isInitialized()&&(objDefineProps((g=getDynamicConfigHandler(S.config)).cfg,{channelConfiguration:{g:function(){return g.cfg.extensionConfig[b.identifier]}},propertyConfiguration:{g:function(){return g.cfg.extensionConfig[I.identifier]}}}),b&&(A=_getEndpointUrl(b.identifier,g.cfg))),O&&S.setCookieMgr(O))}function _createInstanceConfig(f,S){var v=[],C=g.cfg,_={};if(objForEachKey(C.extensionConfig,(function(g,f){g===b.identifier||g===I.identifier||lc(g,"Symbol(")||(g!==Iv?_proxyReadonlyProperty(_,g,f):(_[g]={},_copyObjProperties(_[g],f)))})),S){S.extensions&&S.extensions.length>0&&(v=arrAppend(v,S.extensions));var T=S.extensionConfig;T&&(vl(T,b.identifier)&&Al(T).length>0&&_throwInternal(N.diagLog(),2,511,"Instances cannot override the shared Post channel configuration, the shared will be used!"),_copyObjProperties(_,T))}var A={instrumentationKey:f,channels:_createMergedChannels(S),extensions:v,extensionConfig:_};return _copyObjProperties(A,S),A}function _createMergedChannels(f){var S=g.cfg,v=[[]];return S.channels&&arrForEach(S.channels,(function(g,f){hl(g)||(v[f]=v[f]||[],v[f]=v[f].concat(g))})),f&&f.channels&&arrForEach(f.channels,(function(g,f){hl(g)||(v[f]=v[f]||[],v[f]=v[f].concat(g))})),v}function _createMergedExtensions(g){var S=[];return f&&f.length>0&&(S=S.concat(f)),g&&g.length>0&&(S=S.concat(g)),S}function _unloadInstance(g,f,S,v){var C=T[g];C&&(C.inst&&C.inst.isInitialized()?C.inst.unload(f,(function(f){S&&S(g,f)}),v):S&&S(g,{reason:50,isAsync:f,flushComplete:!1}))}_initDefaults(),N.diagLog=function(){return P||(P=new Gu(g.cfg)),P},N.getCookieMgr=function(){return _initializeSharedInstance(),O||S.getCookieMgr()},N.setCookieMgr=function(g){O=g,S&&S.setCookieMgr(g)},N.getPerfMgr=function(){return M||g&&g.cfg.enablePerfMgr&&(M=D||new ug(N.getNotifyMgr())),M},N.setPerfMgr=function(g){D=g,M=g},N.create=function(f,v){w?_throwInternal(N.diagLog(),2,514,"Shared Manager has already been initialized."):(g=createDynamicConfig(_fixupExtensionConfig(f?objExtend({},f):{}),Rv,null),S=null,_initializeSharedChannels(),_initializeSharedExtensions(v),w=!0)},N.getInst=function(g){return(T[g]||{}).inst},N.newInst=function(f,C,_){var I=N.getInst(f);if(I)return _throwInternal(N.diagLog(),2,514,"Instance already exists for ["+f+"]"),I;if(_initializeSharedInstance(),S.isInitialized()){var P=_createInstanceConfig(f,C);if(b){var R=_getEndpointUrl(b.identifier,P);A&&R&&A!==R&&_throwInternal(N.diagLog(),2,511,"The endpointUrl mismatch, shared Url ["+A+"] is different from configured ["+R+"] shared will be used!")}var M=new wv(f,v);if(I=new Dv(N,N.diagLog(),M),T[f]={iKey:f,inst:I,notifyMgr:M},I.setPerfMgr(N.getPerfMgr()),I.initialize(P,_createMergedExtensions(_)),I.isInitialized()){var w=I.config;objDefineProps(w,{propertyConfiguration:{g:function(){return w.extensionConfig[Iv]}}});try{delete w.endpointUrl,delete w.channelConfiguration,delete w.propertyStorageOverride}catch(g){_throwInternal(N.diagLog(),2,108,"Failed to remove unused defaults!")}objForEachKey(g.cfg,(function(g,f){vl(w,g)||lc(g,"Symbol(")||Xl(Pv,g)||_proxyReadonlyProperty(w,g,f)}))}else _throwInternal(N.diagLog(),2,520,"Failed to initialize new instance!"),I=null,delete T[f]}return I},N.getSharedPlugin=function(g){_initializeSharedInstance();var f=null,v=S.getPlugin(g);return v&&(f=v.plugin),f},N.getPropertyManager=function(){return _initializeSharedInstance(),I},N.getPostChannel=function(){return _initializeSharedInstance(),b},N.getNotifyMgr=function(){return R||(R=new ag),R},N.unload=function(g,f,v){var C,_=Al(T),I=_.length+1,b={reason:50,isAsync:g,flushComplete:!1};function _doUnload(g,S){0===--I&&(_initDefaults(),f&&f(S))}return g&&!f&&(C=createPromise((function(g){f=g}))),S&&(arrForEach(_,(function(f){_unloadInstance(f,g,(function(g,f){_doUnload(g,f)}),v)})),S.isInitialized()&&(S.unload(g,(function(g){_doUnload(null,b=g)}),v),S=null)),_doUnload(null,b),C},N.addUnloadHook=function(g){_initializeSharedInstance(),S.addUnloadHook(g)},N.addSharedPlugin=function(g,f,v,C){return _initializeSharedInstance(),S.addPlugin(g,f,v,C)},N.updateCfg=function(g,f){return _initializeSharedInstance(),S.updateCfg(g,f)},N.evtNamespace=function(){return _initializeSharedInstance(),S.evtNamespace()},N.addUnloadCb=function(g){_initializeSharedInstance(),S.addUnloadCb(g)},N.onCfgChange=function(g){return _initializeSharedInstance(),S.onCfgChange(g)},N[Av]=function(g){g&&T.iKey&&delete T[g]}}))}return ApplicationInsightsManager2.__ieDyn=1,ApplicationInsightsManager2}(),Dv=function(g){function ApplicationInsights3(f,S,v){var C,_=g.call(this)||this,T=f;return dynamicProto(ApplicationInsights3,_,(function(g,f){g.getSharedPropertyManager=function(){return T.getPropertyManager()},g.getSharedPostChannel=function(){return T.getPostChannel()},g.getOverridePropertyManager=function(){return C},g.initialize=function(_,T){doPerf(g,(function(){return"ApplicationInsights:initialize"}),(function(){var I=[C=new bv];T&&(I=I.concat(T));var b=_.propertyConfiguration||{};if(_.propertyConfiguration)try{delete _.propertyConfiguration}catch(g){_.propertyConfiguration={}}_.extensionConfig=_.extensionConfig||{},_.extensionConfig[C.identifier]=b,_=createDynamicConfig(_,Mv,S||g.logger,!1).cfg;try{f.initialize(_,I,S,v)}catch(f){_throwInternal(g.logger,1,514,"Failed to initialize SDK."+dumpObj(f))}}),(function(){return{config:_,extensions:T}}))},g.unload=function(S,v,C){return T[Av]&&T[Av]((g.config||{}).instrumentationKey),f.unload(S,v,C)}})),_}return __extendsFn(ApplicationInsights3,g),ApplicationInsights3.__ieDyn=1,ApplicationInsights3}(yp),Nv=class{constructor(g){this.key=g.config.bwSeedOptions.localStorageKey||"bwSeed";const f=localStorage.getItem(this.key);parseInt(f)||localStorage.setItem(this.key,g.config.bwSeedOptions.constValue.toString())}getSeed(){const g=localStorage.getItem(this.key),f=parseInt(g);return isNaN(f)?void 0:f}saveSeed(g){localStorage.setItem(this.key,g.toString())}static localStorageAvailable(){try{const g=window.localStorage,f="someKey",S="someValue";return g.setItem(f,S),g.removeItem(f),!0}catch(g){return!1}}},kv=class _BandwidthMemoryStorage{constructor(g){_BandwidthMemoryStorage.value??(_BandwidthMemoryStorage.value=g.config.bwSeedOptions.constValue)}getSeed(){return _BandwidthMemoryStorage.value}saveSeed(g){_BandwidthMemoryStorage.value=g}},Lv=class{constructor(g){this.value=g}addValue(g){}getAggregated(){return this.value}},Fv=class{addValue(g){this.value=g}getAggregated(){return this.value}},xv=class{constructor(g){this.size=g,this.items=[]}clear(){this.items=[]}},Uv=class extends xv{get isFull(){return this.items.length>=this.size}add(g){return this.isFull&&this.items.shift(),this.items.push(g),!0}},Vv=class extends xv{add(g){return!(this.items.length>=this.size)&&(this.items.push(g),!0)}},Bv=class{constructor(g){this.values=new Uv(g)}addValue(g){this.values.add(g)}getAggregated(){return Math.floor(average(this.values.items))}},Hv=class{constructor(){this.total=0,this.duration=0,this.max=0,this.minNonZero=Number.MAX_SAFE_INTEGER}get avg(){return 0!==this.duration?this.total/this.duration:0}get maxSample(){return this.max}get minNonZeroSample(){return this.minNonZero}captureSample(g){(g||0===g)&&(this.total+=g,this.duration++,this.max=Math.max(g,this.max),0!==g&&(this.minNonZero=Math.min(g,this.minNonZero)))}},$v=class{constructor(){this.sampleCounts={}}get min(){const g=Object.keys(this.sampleCounts).map(Number).filter((g=>g>0));return g.length>0?Math.min(...g):0}get max(){const g=Object.keys(this.sampleCounts).map(Number);return g.length>0?Math.max(...g):0}get mode(){const g=Object.keys(this.sampleCounts).map(Number);return g.length>0?g.reduce(((g,f)=>this.sampleCounts[f]>this.sampleCounts[g]?f:g),g[0]):0}captureSample(g){var f;if(void 0!==g){const S=`${g}`;(f=this.sampleCounts)[S]??(f[S]=0),this.sampleCounts[S]++}}},jv=class{get delta(){if(void 0!==this.cur&&void 0!==this.last)return this.cur-this.last}captureSample(g,f){void 0!==g&&(void 0!==this.cur&&(this.last=this.cur),this.cur=g)}},Gv=class{constructor(g=0){this.precision=g}get delta(){if(void 0!==this.currentSample&&void 0!==this.prevSample){let g=1;return void 0!==this.currentTimestamp&&void 0!==this.prevTimestamp&&(g=(this.currentTimestamp-this.prevTimestamp)/1e3),g&&round((this.currentSample-this.prevSample)/g,this.precision)}}captureSample(g,f){if(this.currentTimestamp!==f){if(void 0===g)return this.prevSample=void 0,this.currentSample=void 0,this.prevTimestamp=void 0,void(this.currentTimestamp=void 0);void 0!==this.currentSample&&(this.prevSample=this.currentSample),this.prevTimestamp=this.currentTimestamp,this.currentTimestamp=f,this.currentSample=g}}},qv=class{constructor(){this.startTime=Date.now()}get elapsed(){return round((Date.now()-this.startTime)/1e3,0)}},Wv=class{constructor(g){this.numOfHistogramSamples=g,this.eventCount=0,this.totalActiveDuration=0,this.countBuckets={seconds1to3:0,seconds3to5:0,seconds5to8:0,seconds8to15:0,seconds15to60:0,seconds60toMax:0},this.timestampBuckets={seconds1to3:[],seconds3to5:[],seconds5to8:[],seconds8to15:[],seconds15to60:[],seconds60toMax:[]},this.averager=new Hv}get active(){return!!this.current}get ongoingDuration(){return this.current?.elapsed||0}get avgDuration(){return this.averager.avg}get longestDuration(){return this.averager.maxSample}get numEvents(){return this.eventCount}get totalDuration(){return this.current?this.totalActiveDuration+this.current.elapsed:this.totalActiveDuration}get timestamps(){return deepClone(this.timestampBuckets)}get counts(){return deepClone(this.countBuckets)}set active(g){if(!this.current&&g)this.current=new qv;else if(this.current&&!g){const g=this.current.elapsed;this.averager.captureSample(g),this.totalActiveDuration+=g;for(const f of Object.keys(qt.HISTOGRAM_BATCH))if(g<=qt.HISTOGRAM_BATCH[f]){this.countBuckets[f]++,arrayLimitedPush2(this.timestampBuckets[f],this.current.startTime,this.numOfHistogramSamples);break}this.eventCount++,this.current=void 0}}},zv=class{constructor(){this.sampleChangeCount=0,this.sampleDurations={}}get durations(){return deepClone(this.sampleDurations)}get sortedDurations(){return Object.keys(this.sampleDurations).sort(((g,f)=>this.sampleDurations[f]-this.sampleDurations[g]))}get durationRatios(){const g={};let f=0;for(const g in this.sampleDurations)f+=this.sampleDurations[g];for(const S in this.sampleDurations)g[S]=round(this.sampleDurations[S]/f*100);return g}get changeCount(){return this.sampleChangeCount}captureSample(g){this.sampleDurations[g]||(this.sampleDurations[g]=0),this.sampleDurations[g]++,g!==this.lastSample&&(this.sampleChangeCount++,this.lastSample=g)}},Kv=class{constructor(g,f){this.validTimeBetweenFramesArrival=g,this.invalidFPSAboveMax=f,this.lastSampleTimestamp=-1,this.fpsHarmonicSumWeigtsTs=0,this.fpsHarmonicWeigtedSumsFramePerDelayTs=0}captureSample(g){const f=Date.now();if(g>0&&this.lastSampleTimestamp>0){const S=f-this.lastSampleTimestamp;if(this.lastSampleTimestamp=f,S<0||S>this.validTimeBetweenFramesArrival||g>this.invalidFPSAboveMax)return;const v=S/g;this.fpsHarmonicSumWeigtsTs+=S,this.fpsHarmonicWeigtedSumsFramePerDelayTs+=S*v}(this.lastSampleTimestamp<0||0===g)&&(this.lastSampleTimestamp=f)}get harmonicMean(){return this.fpsHarmonicWeigtedSumsFramePerDelayTs>0?1e3*this.fpsHarmonicSumWeigtsTs/this.fpsHarmonicWeigtedSumsFramePerDelayTs:0}},Jv=class{constructor(g){this.samplesNum=g,this.samples=[],this.sortedSamples=[],this.lastReport={avg:-1,max:-1,median:-1,p90:-1,volatilityPercent:-1}}isReportComplete(){return this.samples.length===this.samplesNum}getReport(){return this.lastReport}captureSample(g){void 0===g||g<0||(arrayLimitedPush2(this.samples,g,this.samplesNum),this.sortedSamples=deepClone(this.samples).sort(((g,f)=>g-f)),this.lastReport={avg:this.getAvg(),median:this.calculatePercentile(50),p90:this.calculatePercentile(90),max:this.calculatePercentile(100),volatilityPercent:this.getVolatility()})}getAvg(){return average(this.samples)}getVolatility(){const g=this.getAvg();if(0===g)return 0;let f=0;this.samples.forEach((S=>{f+=Math.abs(S-g)}));return round(f/this.samples.length*100/g,2)}calculatePercentile(g){if(g<0||g>100)throw new Error("Percentile must be between 0 and 100");const f=g/100*(this.sortedSamples.length-1),S=Math.floor(f),v=Math.ceil(f),C=f-S;return v>=this.sortedSamples.length?this.sortedSamples[S]:this.sortedSamples[S]*(1-C)+this.sortedSamples[v]*C}},Yv=class{constructor(){this.duration=0,this.reportAggr={avg:0,max:0,median:0,p90:0,volatilityPercent:0}}captureSample(g){!g||g.avg<0||(this.reportAggr={avg:this.reportAggr.avg+g.avg,max:Math.max(this.reportAggr.max,g.max),median:this.reportAggr.median+g.median,p90:this.reportAggr.p90+g.p90,volatilityPercent:this.reportAggr.volatilityPercent+g.volatilityPercent},this.duration++)}getReport(){if(0!==this.duration)return{avg:this.reportAggr.avg/this.duration,max:this.reportAggr.max,median:this.reportAggr.median/this.duration,p90:this.reportAggr.p90/this.duration,volatilityPercent:this.reportAggr.volatilityPercent/this.duration}}},Qv=class{constructor(g,f=0){this.overshootType=g,this.allowedOvershoot=f,this.past=[],this.totalOvershootDuration=0,this.lastAllowed=0}get isOvershooting(){return!!this.current}get events(){return this.current?[...this.past,this.current]:this.past}get totalDuration(){return this.totalOvershootDuration}captureSample(g,f){const S=round(g-f);S>this.allowedOvershoot&&(0===this.lastAllowed||f===this.lastAllowed||!this.current&&f>this.lastAllowed)?(this.totalOvershootDuration++,this.current?(this.current.min=Math.min(this.current.min,S),this.current.max=Math.max(this.current.max,S)):this.current={timestamp:Date.now(),min:S,max:S,type:this.overshootType}):this.current&&(this.current.duration=Date.now()-this.current.timestamp,this.past.push(this.current),this.current=void 0),this.lastAllowed=f}},Xv=class{constructor(g=!1){this.disableNormalization=g,this.prevLost=0,this.prevReceived=0,this.minPackets=100}calculate(g,f){if(void 0===g||void 0===f)return;const S=g-this.prevReceived,v=f-this.prevLost;if(S+v<this.minPackets)return;this.prevReceived=g,this.prevLost=f;const C=v*(this.disableNormalization?1:this.minPackets)/(v+S);return C>(this.disableNormalization?1:this.minPackets)?0:C}},Zv=class{constructor(){this.capturedSamples=[]}captureSample(g){g&&this.capturedSamples.push(g)}calculateStd(){if(!this.capturedSamples.length)return;const g=this.capturedSamples.reduce(((g,f)=>g+f),0)/this.capturedSamples.length,f=this.capturedSamples.map((f=>(f-g)**2)),S=f.reduce(((g,f)=>g+f),0)/f.length;return round(Math.sqrt(S),2)}getFirst(){return this.capturedSamples[0]}getLast(){if(this.capturedSamples.length)return this.capturedSamples[this.capturedSamples.length-1]}calculatePercentile(g){if(!this.capturedSamples.length)return;const f=this.capturedSamples.sort(((g,f)=>g-f)),S=(f.length-1)*g,v=Math.floor(S),C=S-v;return void 0!==f[v+1]?f[v]+C*(f[v+1]-f[v]):f[v]}};function isPowerEfficient(g){if(!g)return;const f=["libvpx","ffmpeg"];let S=!0;for(const v of f)if(g.toLowerCase().includes(v)){S=!1;break}return S}var eC=class{constructor(g){this.samplesCount=g,this.capturedSamples=[]}captureSample(g){void 0!==g&&arrayLimitedPush2(this.capturedSamples,g,this.samplesCount)}getRate(){if(!this.capturedSamples.length)return;const g=this.samplesCount/this.capturedSamples.length;return this.capturedSamples.reduce(((g,f)=>g+f))*g/this.samplesCount}},tC=class{constructor(g=5){this.limit=g,this.curWidth=0,this.curHeight=0,this.resolutionSwitches=[]}captureSample(g,f){g===this.curWidth&&f===this.curHeight||(arrayLimitedPush2(this.resolutionSwitches,`${g}x${f}`,this.limit),this.curWidth=g,this.curHeight=f)}get switches(){if(this.resolutionSwitches.length)return this.resolutionSwitches}};function calcMacroblockRate(g,f,S){return g&&f?Math.ceil(g/qt.MACROBLOCK_SIZE)*Math.ceil(f/qt.MACROBLOCK_SIZE)*S:0}var iC=class{constructor(){this.macroblockRateAveragerReceived=new Hv,this.macroblockRateAveragerDecoded=new Hv,this.maxDecoderLoss=0,this.decoderLoss=0}captureSample(g,f){this.macroblockRateAveragerReceived.captureSample(g),this.macroblockRateAveragerDecoded.captureSample(f);let S=this.maxDecoderLoss;g&&(S=(g-f)/g*100),this.decoderLoss=S,this.maxDecoderLoss=Math.max(S,this.maxDecoderLoss)}getReport(){return{macroblockRateReceivedMax:this.macroblockRateAveragerReceived.maxSample,macroblockRateReceivedAvg:this.macroblockRateAveragerReceived.avg,macroblockRateDecodedMax:this.macroblockRateAveragerDecoded.maxSample,macroblockRateDecodedAvg:this.macroblockRateAveragerDecoded.avg,macroblockRateMaxDecoderLossPercent:Math.floor(this.maxDecoderLoss),macroblockRateDecoderLossPercent:Math.floor(this.decoderLoss)}}},nC=class{constructor(){this.codecReport={}}captureSample(g,f){var S,v;const C=g.split("/").pop();return void 0===this.activeMsi||this.activeMsi!==f?(this.activeMsi=f,this.previousCodec=C,void((S=this.codecReport)[f]??(S[f]={[C]:1,codecSwitchCounter:0}))):this.previousCodec!==C?((v=this.codecReport[f])[C]??(v[C]=0),this.codecReport[f][C]++,this.codecReport[f].codecSwitchCounter++,void(this.previousCodec=C)):void this.codecReport[f][C]++}get report(){return this.codecReport}},rC=class{constructor(g=5){this.limit=g,this.curPowerEfficientCodecState=!1,this.powerEfficientCodecEvents=[],this.powerEfficientCodecEventOnCount=0,this.powerEfficientCodecEventOffCount=0}captureSample(g,f){if(g!==this.curPowerEfficientCodecState){const S={timestamp:Date.now(),powerEfficient:g,frameHeight:f};arrayLimitedPush2(this.powerEfficientCodecEvents,S,this.limit),this.curPowerEfficientCodecState=g,g?this.powerEfficientCodecEventOnCount++:this.powerEfficientCodecEventOffCount++}}get events(){if(this.powerEfficientCodecEvents.length)return this.powerEfficientCodecEvents}get eventOnCount(){return this.powerEfficientCodecEventOnCount}get eventOffCount(){return this.powerEfficientCodecEventOffCount}get curPowerEfficientEncoderState(){return this.curPowerEfficientCodecState}},sC=class{constructor(){this.bandwidthAverager=new Hv}addValue(g){this.bandwidthAverager.captureSample(g)}getAggregated(){return Math.floor(this.bandwidthAverager.avg)}},aC=-1,oC=class{constructor(g){this.configProvider=g,this.aggregator=this.getAggregator(),this.storage=this.getStorage(),this.cappingValue=this.configProvider.config.bwSeedOptions.cappingValue,this.minValue=this.configProvider.config.bwSeedOptions.minValue??aC}getSeed(){const g=this.storage.getSeed()??aC;return this.cappingValue>0?Math.min(Math.max(g,this.minValue),this.cappingValue):Math.max(g,this.minValue)}saveSeed(g){this.aggregator.addValue(g);const f=this.aggregator.getAggregated();this.storage.saveSeed(f)}getAggregator(){switch(this.configProvider.config.bwSeedOptions.aggregation){case"avg":return this.configProvider.config.bwSeedOptions.aggregateLastN>0?new Bv(this.configProvider.config.bwSeedOptions.aggregateLastN):new sC;case"last":return new Fv;default:return new Lv(this.configProvider.config.bwSeedOptions.constValue)}}getStorage(){return this.configProvider.config.bwSeedOptions.useLocalStorage&&Nv.localStorageAvailable()?new Nv(this.configProvider):new kv(this.configProvider)}},lC=M;function adjustResolutionToAspectRatio(g,f){const S=g.width/g.height,v=(0,lC.clone)(g);return S>f?v.width=Math.floor(g.height*f):S<f&&(v.height=Math.floor(g.width/f)),v}var cC=class _ConstraintsObject{constructor(g,f,S=!0,v=!1,C){this.audio=g,this.video=f,this.withTimeout=S,this.withEffect=v,this.withOverridenStream=C}clone(){const g=deepClone(this.video),f=deepClone(this.audio);return new _ConstraintsObject(f,g,this.withTimeout,this.withEffect,this.withOverridenStream)}},dC=class{constructor(g){this.logger=g}dispose(){}updateVideoConstraints(g,f,S){const v=this.calculateConstraints(f,S);this.logger.safe.info(`Calculated constraints: ${JSON.stringify(v)} from capabilities: ${JSON.stringify(f)}`);const C=v.resolution,_=v.fps,T=C&&(!isInRange(C.width,g.video.minWidth,g.video.maxWidth)||!isInRange(C.height,g.video.minHeight,g.video.maxHeight)),I=g.video.fps!==_;if(!T&&!I)return g;const b=g.clone();return T&&this.setResolution(b,C),I&&(b.video.fps=_),b}updateResolution(g,f){const S=g.clone();return this.setResolution(S,f),S}setResolution(g,f){g.video.maxWidth=f.width,g.video.minWidth=f.width,g.video.maxHeight=f.height,g.video.minHeight=f.height}getKey(g){return g.video?isEmpty(g.video)?"video":g.video.deviceId&&g.video.minWidth&&g.video.minHeight?`${g.video.deviceId}x${g.video.minWidth}x${g.video.minHeight}`:g.video.minWidth&&g.video.minHeight?`${g.video.minWidth}x${g.video.minHeight}`:g.video.deviceId?`${g.video.deviceId}`:(this.logger.safe.error(`Cannot create key for constraints: ${scrubConstraints(g)}`),""):"audio"}convertConstraints(g,f={}){if(!g)return null;const S=deepClone(f);return g?.deviceId&&(S.deviceId=g.deviceId),S}},hC=class{constructor(){this.MAX_SHARING_WIDTH=1920,this.MAX_SHARING_HEIGHT=1080}getResolutionTable(g,f){const S=this.constraintToMaxResolution(g,f);return this.generateResolutionTable(S)}constraintToMaxResolution(g,f){const S=this.getPortraitOrLandscapeMaxResolution(g),v=adjustResolutionToAspectRatio({width:g.width,height:g.height},f),C=S.width/v.width,_=S.height/v.height,T=Math.min(C,_);return this.resizeResolution(v,T)}resizeResolution(g,f){return{width:Math.round(g.width*f),height:Math.round(g.height*f)}}getPortraitOrLandscapeMaxResolution(g){return g.width>g.height?{width:this.MAX_SHARING_WIDTH,height:this.MAX_SHARING_HEIGHT}:{width:this.MAX_SHARING_HEIGHT,height:this.MAX_SHARING_WIDTH}}ceilToMackroblockSize(g){const f=g.width,S=g.height;return{width:Math.ceil(f/qt.MACROBLOCK_SIZE)*qt.MACROBLOCK_SIZE,height:Math.ceil(S/qt.MACROBLOCK_SIZE)*qt.MACROBLOCK_SIZE}}generateResolutionTable(g){return[1,2/3,1/3,1/6].map((f=>this.resizeResolution(g,f))).map((g=>this.ceilToMackroblockSize(g)))}},uC=class{constructor(g){this.logger=g,this.FPS_TABLE=[15,7.5,3.75,1.875],this.resolutionTableCalculator=new hC,this.initialAspectRatio=null}calculateConstraints(g,f){this.initialAspectRatio||(this.initialAspectRatio=f.width/f.height);const S=this.resolutionTableCalculator.getResolutionTable(f,this.initialAspectRatio);let v={resolution:S[S.length-1],fps:this.FPS_TABLE[this.FPS_TABLE.length-1]};return S.some((f=>{const S=this.getFs(f);return this.FPS_TABLE.some((C=>{const _=this.getMbps(S,C);return S<=g.maxFs&&C<=g.maxFps&&_<=g.maxMbps&&(v={resolution:f,fps:C},!0)}))}))?this.logger.safe.info(`Calculated resolution: ${JSON.stringify(v)}`):this.logger.safe.error(`None of available resolutions are suitable: ${JSON.stringify(S)}. Fallback to: ${JSON.stringify(v)}`),v}getMbps(g,f){return g*f}getFs(g){return Math.ceil(g.width/qt.MACROBLOCK_SIZE)*Math.ceil(g.height/qt.MACROBLOCK_SIZE)}},gC=class{constructor(g,f){this.logger=g,this.maxCapabilities=f}ensureValidity(g){this.throwIfMissing(g);const f=this.calculateMissing(g);return this.maxCapabilities&&this.applyMaxCapabilities(f),this.logger.safe.info(`Validating capabilities ${JSON.stringify(f)}`),f}throwIfMissing(g){if(!g.maxFs&&!g.maxMbps&&!g.maxFps||g.maxFs&&!g.maxMbps&&!g.maxFps||!g.maxFs&&g.maxMbps&&!g.maxFps||!g.maxFs&&!g.maxMbps&&g.maxFps)throw new Error(`Missing video capabilities ${JSON.stringify(g)}`)}calculateMissing(g){const f=shallowClone(g);return!g.maxFs&&g.maxMbps&&g.maxFps&&(f.maxFs=g.maxMbps/g.maxFps),g.maxFs&&!g.maxMbps&&g.maxFps&&(f.maxMbps=g.maxFs*g.maxFps),g.maxFs&&g.maxMbps&&!g.maxFps&&(f.maxFps=g.maxMbps/g.maxFs),f}applyMaxCapabilities(g){this.maxCapabilities.maxFs&&(g.maxFs=Math.min(g.maxFs,this.maxCapabilities.maxFs)),this.maxCapabilities.maxMbps&&(g.maxMbps=Math.min(g.maxMbps,this.maxCapabilities.maxMbps)),this.maxCapabilities.maxFps&&(g.maxFps=Math.min(g.maxFps,this.maxCapabilities.maxFps))}},pC=8160,mC=15,fC=class extends dC{constructor(g,f){super(g),this.initialConstraints={maxWidth:1920,minWidth:1920,maxHeight:1080,minHeight:1080,fps:15},this.maxCapabilities={maxFs:pC,maxFps:mC},this.validator=new gC(this.logger.createChild("CV"),this.maxCapabilities),this.constraintsCalculator=new uC(this.logger.createChild("CC")),f.config.resizeModeForSharing&&(this.initialConstraints.resizeMode=f.config.resizeModeForSharing)}createConstraintsObject(g){if(!g.sharing)throw new Error(`Sharing constraints are not presented: ${JSON.stringify(g)}`);const f=this.convertConstraints(g.sharing,this.initialConstraints),S=g.audio?g.audio:null;return S?.deviceId===qt.SYSTEM_AUDIO_SOURCE_ID&&delete S.deviceId,new cC(S,f,!1,!1,g.withOverridenStream)}generatePolicies(g){return[g]}calculateConstraints(g,f){this.logger.safe.info(`Stream resolution is ${JSON.stringify(f)}`);const S=this.validator.ensureValidity(g);return this.constraintsCalculator.calculateConstraints(S,f)}},SC=class extends fC{constructor(g,f,S){super(g,S);const v=f.screen.width/f.screen.height;v<1&&([this.initialConstraints.maxWidth,this.initialConstraints.maxHeight]=[this.initialConstraints.maxHeight,this.initialConstraints.maxWidth],[this.initialConstraints.minWidth,this.initialConstraints.minHeight]=[this.initialConstraints.minHeight,this.initialConstraints.minWidth]);let C=adjustResolutionToAspectRatio({width:this.initialConstraints.maxWidth,height:this.initialConstraints.maxHeight},v);[this.initialConstraints.maxWidth,this.initialConstraints.maxHeight]=[C.width,C.height],C=adjustResolutionToAspectRatio({width:this.initialConstraints.minWidth,height:this.initialConstraints.minHeight},v),[this.initialConstraints.minWidth,this.initialConstraints.minHeight]=[C.width,C.height]}},vC=class extends dC{constructor(g,f){super(f),this.configProvider=g}get currentMaxFS(){return this.streamConstraintsMaxFS??this.configProvider.config.webrtcCameraOpenFs}createConstraintsObject(g){const f={};void 0!==g.audioProcessingFlags&&(et.isEngine("Chromium","ChromiumAVD")?(f.autoGainControl=!!(1&g.audioProcessingFlags),f.echoCancellation=!!(2&g.audioProcessingFlags),f.noiseSuppression=!!(4&g.audioProcessingFlags),this.configProvider.config.useGoogPrefixAudioConstraints&&(f.googAutoGainControl=!!(1&g.audioProcessingFlags),f.googAutoGainControl2=!!(1&g.audioProcessingFlags),f.googEchoCancellation=!!(2&g.audioProcessingFlags),f.googHighpassFilter=!!(4&g.audioProcessingFlags),f.googNoiseSuppression=!!(4&g.audioProcessingFlags),f.googTypingNoiseDetection=!!(4&g.audioProcessingFlags))):et.isEngine("Safari","Firefox")?(f.autoGainControl=!!(1&g.audioProcessingFlags),f.echoCancellation=!!(2&g.audioProcessingFlags),f.noiseSuppression=!!(4&g.audioProcessingFlags)):this.logger.warn(`Unsupported browser engine for audio processing flags ${et.getBrowserInfo().engine}`));const S=this.convertConstraints(g.audio,f);this.streamConstraintsMaxFS=g.videoMaxFS;const v=this.convertConstraints(g.video,this.initialVideoConstraints(this.currentMaxFS));return new cC(S,v,g.withTimeout,g.withEffect,g.withOverridenStream)}calculateConstraints(g){const f=Math.min(g.maxFs,this.currentMaxFS);return{resolution:ei.Send.getResolutionByFs(f),fps:g.maxFps}}initialVideoConstraints(g){const f=ei.Send.getResolutionByFs(g);return{maxWidth:f.width,minWidth:f.width,maxHeight:f.height,minHeight:f.height,fps:this.configProvider.config.maxCameraOpenFps}}},CC=class{static getProvider(g,f,S){if("ScreenShare"===g){const g=S.createChild("SharingCP");return et.isBrowser("Safari")?new SC(g,Xs.window,f):new fC(g,f)}return new vC(f,S.createChild("VideoCP"))}},yC=class{constructor(g,f,S){this.error=g,this.constraints=f,this.configProvider=S,this.permissionDeniedBySystemErrorMsg=["Permission denied by system","The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission."]}getMediaError(){let g;switch(this.error.name){case"SourceUnavailableError":case"TrackStartError":case"NotReadableError":case"AbortError":g={type:qt.MEDIA_ERROR.sourceUnavailableError,detail:`media device is already used by another process: ${stringifyObject(this.error)}`};break;case"ConstraintNotSatisfiedError":case"OverconstrainedError":g={type:qt.MEDIA_ERROR.constraintNotSatisfiedError,detail:`could not obtain constrained media stream: ${stringifyObject(this.error)}`};break;case"DevicesNotFoundError":case"NotFoundError":g=this.configProvider.config.permissionDeniedUFDWorkaround?{type:qt.MEDIA_ERROR.permissionDeniedBySystemError,detail:`no system permissions: ${stringifyObject(this.error)}`}:{type:qt.MEDIA_ERROR.devicesNotFoundError,detail:`specified device not found: ${stringifyObject(this.error)}`};break;case"NotAllowedError":g=this.permissionDeniedBySystemErrorMsg.some((g=>g===this.error.message))?{type:qt.MEDIA_ERROR.permissionDeniedBySystemError,detail:`no system permissions: ${stringifyObject(this.error)}`}:{type:qt.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${stringifyObject(this.error)}`};break;case"PermissionDeniedError":case"PermissionDismissedError":g={type:qt.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${stringifyObject(this.error)}`};break;case qt.MEDIA_ERROR.extensionNotFoundError:g={type:qt.MEDIA_ERROR.extensionNotFoundError,detail:`extension is not found: ${stringifyObject(this.error)}`};break;case qt.MEDIA_ERROR.chromeRuntimeNotDefinedError:g={type:qt.MEDIA_ERROR.chromeRuntimeNotDefinedError,detail:`chrome runtime is not defined: ${stringifyObject(this.error)}`};break;case qt.MEDIA_ERROR.sharingCancelledError:g=this.getSharingCancelledError(this.error);break;case qt.MEDIA_ERROR.mediaStreamRequestTimedOut:g={type:qt.MEDIA_ERROR.mediaStreamRequestTimedOut,detail:"Media Stream request timed out."};break;default:g=this.error.message===qt.MEDIA_ERROR.sharingCancelledError?this.getSharingCancelledError(this.error):{type:qt.MEDIA_ERROR.mediaStreamRequestError,detail:`media stream request error: ${stringifyObject(this.error)}`}}return g.isAudio=!!this.constraints.audio,g.detail+=` constraints: ${stringifyObject(scrubConstraints(this.constraints))}`,g.message=g.detail,g}getSharingCancelledError(g){return{type:qt.MEDIA_ERROR.sharingCancelledError,detail:`screen sharing cancelled: ${stringifyObject(g)}`}}},EC=class{constructor(g,f){this.logger=g,this.configProvider=f}static isSupported(){return!0}getStream(g){const f=this.constraintsAdapter.toGumConstraints(g);return this.logger.safe.info(`Constraints to be applied: ${JSON.stringify(scrubConstraints(f))}`),new Promise(((g,S)=>{Xs.window.navigator.getUserMedia(f,g,S)})).catch((f=>{throw new yC(f,g,this.configProvider).getMediaError()}))}applyConstraints(g,f){if(!g?.getVideoTracks()?.[0])return Promise.reject("No video tracks found");const S=g.getVideoTracks()[0];return this.applyConstraintsForTrack(S,f)}applyConstraintsForTrack(g,f){const S=this.constraintsAdapter.toTrackConstraints(f);return g.applyConstraints?(this.logger.safe.info(`Apply constraints: ${JSON.stringify(S)} on ${JSON.stringify(g.id)}`),g.applyConstraints(S).catch((g=>{throw new yC(g,f,this.configProvider).getMediaError()}))):Promise.reject("track.applyConstraints() is not supported")}},_C=class{constructor(g){this.configProvider=g}toGumConstraints(g){const f={};return g.audio&&(f.audio=deepClone(g.audio),f.audio.deviceId&&delete f.audio.deviceId,g.audio.deviceId&&g.audio.deviceId!==qt.MEDIA_DEVICE.defaultId&&(f.audio.deviceId=g.audio.deviceId)),g.video&&(f.video={mandatory:{}},g.video.deviceId&&(f.video.mandatory.sourceId=g.video.deviceId),g.video.minWidth&&(f.video.mandatory.minWidth=g.video.minWidth),g.video.maxWidth&&(f.video.mandatory.maxWidth=g.video.maxWidth),g.video.minHeight&&(f.video.mandatory.minHeight=g.video.minHeight),g.video.maxHeight&&(f.video.mandatory.maxHeight=g.video.maxHeight),g.video.fps&&(f.video.mandatory.maxFrameRate=g.video.fps,this.configProvider.config.setMinFpsForWebkit&&(f.video.mandatory.minFrameRate=this.configProvider.config.minCameraOpenFps,f.video.mandatory.idealFrameRate=g.video.fps)),isEmpty(f.video.mandatory)&&delete f.video.mandatory),f}toTrackConstraints(g){const f={};return g.video&&(g.video.minWidth&&(f.width=g.video.minWidth),g.video.minHeight&&(f.height=g.video.minHeight),g.video.fps&&(f.frameRate=g.video.fps)),f}},TC=class{constructor(g){this.configProvider=g}toGumConstraints(g){const f={};if(g.audio&&(f.audio=deepClone(g.audio),f.audio.deviceId&&delete f.audio.deviceId,g.audio.deviceId&&g.audio.deviceId!==qt.MEDIA_DEVICE.defaultId&&(f.audio.deviceId={exact:g.audio.deviceId})),g.video){f.video={width:{},height:{},frameRate:{}},g.video.deviceId&&(f.video.deviceId={exact:g.video.deviceId}),g.video.minWidth&&(f.video.width.min=g.video.minWidth),g.video.maxWidth&&(f.video.width.max=g.video.maxWidth),g.video.minHeight&&(f.video.height.min=g.video.minHeight),g.video.maxHeight&&(f.video.height.max=g.video.maxHeight),g.video.fps&&(f.video.frameRate.max=g.video.fps,f.video.frameRate.min=this.configProvider.config.minCameraOpenFps,f.video.frameRate.ideal=g.video.fps);for(const g in f.video)isEmpty(f.video[g])&&delete f.video[g]}return f}toTrackConstraints(g){const f={};return g.video&&(g.video.minWidth&&(f.width=g.video.minWidth),g.video.minHeight&&(f.height=g.video.minHeight),g.video.fps&&(f.frameRate=g.video.fps)),f}},IC=class{toGumConstraints(g){if(!g?.video)throw new Error(`constraints cannot be applied: ${g}`);const f={video:{}},S=g.video.deviceId&&g.video.deviceId!==qt.DISPLAY_SOURCE_ID;return g.video.resizeMode&&(f.video.resizeMode=g.video.resizeMode),S&&(f.video.deviceId={exact:g.video.deviceId}),g.video.maxWidth&&(f.video.width={max:g.video.maxWidth},S&&(f.video.width.ideal=g.video.maxWidth)),g.video.maxHeight&&(f.video.height={max:g.video.maxHeight},S&&(f.video.height.ideal=g.video.maxHeight)),g.video.fps&&(f.video.frameRate=g.video.fps),g.audio&&(f.audio=!g.audio.deviceId||{deviceId:{exact:g.audio.deviceId}}),f}toTrackConstraints(g){const f=navigator.mediaDevices.getSupportedConstraints();if(!f)throw new Error("Constraints are not supported by browser");const S={};return f.width&&g.video.minWidth&&(S.width=g.video.minWidth),f.height&&g.video.minHeight&&(S.height=g.video.minHeight),f.frameRate&&g.video.fps&&(S.frameRate=g.video.fps),S.resizeMode=g.video.resizeMode,S}},bC=class extends EC{constructor(g,f){if(super(f.createChild("WebRTCProvider"),g),this.timeoutId=null,void 0!==navigator.webkitGetUserMedia&&void 0!==webkitRTCPeerConnection&&isVdiPlatform()){if(!this.configProvider.config.overrideGumFromWebkit||!Ys)return void(this.constraintsAdapter=new _C(g));this.logger.safe.info("Overriding getUserMedia from webkit"),overrideGumSourceFromWebkit()}this.constraintsAdapter=new TC(g)}getStream(g){if(!g.withTimeout||!this.configProvider.config.gumRequestTimeout)return super.getStream(g);const f=this.startGumRequestTimer(g),S=super.getStream(g).then((f=>{if(!this.timeoutId)throw this.stopStreamAfterTimeout(f,g),this.getMediaStreamTimeoutError(g);return this.stopGumRequestTimer(),f}));return Promise.race([f,S]).catch((g=>{throw this.stopGumRequestTimer(),g}))}getMediaStreamTimeoutError(g){const f={name:qt.MEDIA_ERROR.mediaStreamRequestTimedOut,message:`Media stream request timed out. Constraints: ${stringifyObject(scrubConstraints(g))}`};return new yC(f,g,this.configProvider).getMediaError()}startGumRequestTimer(g){return new Promise(((f,S)=>{this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,S(this.getMediaStreamTimeoutError(g))}),this.configProvider.config.gumRequestTimeout)}))}stopGumRequestTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}stopStreamAfterTimeout(g,f){this.logger.safe.info(`Stopping media stream acquired after timeout: ${JSON.stringify(g.id)} with constraints: ${JSON.stringify(f)}`);try{g.getTracks().forEach((g=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(g.id)}`),g.stop()})),this.logger.safe.info(`Media stream stopped: ${g.id}`)}catch(g){this.logger.safe.warn(`Failed to stop media stream: ${stringifyObject(g)}`)}}},AC=class extends EC{constructor(g,f){super(g.createChild("WebRTCDispProvider"),f),this.constraintsAdapter=new IC}static isSupported(){return!!window.navigator.mediaDevices.getDisplayMedia}getStream(g){const f=this.constraintsAdapter.toGumConstraints(g);return this.logger.safe.info(`Constraints to be used: ${JSON.stringify(f)}`),Promise.resolve().then((()=>g.video?.deviceId&&g.video?.deviceId!==qt.DISPLAY_SOURCE_ID?Xs.window.navigator.mediaDevices.getUserMedia(f):Xs.window.navigator.mediaDevices.getDisplayMedia(f))).catch((f=>{throw new yC(f,g,this.configProvider).getMediaError()}))}},PC=class{constructor(g){this.detail=g}getStream(g){throw this.getError(g)}applyConstraints(g,f){throw this.getError(f)}applyConstraintsForTrack(g,f){throw this.getError(f)}getError(g){return{type:qt.MEDIA_ERROR.unsupportedStream,detail:this.detail,message:this.detail,isAudio:!!g.audio}}},RC=class{static getStreamProvider(g,f,S){return"ScreenShare"===g?AC.isSupported()?new AC(S,f):(S.error("GUM stream provider cannot be created for display stream"),new PC("Sharing not supported")):new bC(f,S)}},MC=[30,15,7.5,3.75,1.875];function getResolutionForStream(g){return g?.getVideoTracks?.()[0]?getResolutionForTrack(g.getVideoTracks()[0]):null}function getResolutionForTrack(g){const f=g?.getSettings?.();return f?{width:f.width,height:f.height}:null}function getFrameRateForStream(g){return g?.getVideoTracks?.()[0]?getFrameRateForTrack(g.getVideoTracks()[0]):0}function getFrameRateForTrack(g){const f=g?.getSettings?.();return f?getClosestValue(MC,f.frameRate,!0):0}var wC=class extends Ht{constructor(g,f,S,v,C,_,T){super(T),this.id=g,this.masterStream=f,this.currentConstraints=S,this.constraintsProvider=v,this.streamProvider=C,this.configProvider=_,this._isDisposed=!1,this.masterStreamSubscriptions=[],this.mixerSubscriptions=[],this.parentId=f.id,this.logger=T.createChild(`C:${this.parentId}:${this.id}`),this.subscribeOnMasterStreamEvents()}get rawTrack(){return this.mediaTrack}get rawStream(){return this.rawMediaStream||(this.rawMediaStream=new MediaStream([this.mediaTrack]),this.configProvider.config.reassignMediaStreamAudioTrackAfterCreation&&this.rawMediaStream.getAudioTracks().length>0&&(this.rawMediaStream.removeTrack(this.rawMediaStream.getAudioTracks()[0]),this.rawMediaStream.addTrack(this.mediaTrack))),this.rawMediaStream}get deviceId(){return this.masterStream.deviceId}get mediaType(){return this.masterStream.mediaType}get originalMediaStream(){return this.masterStream.getOriginalMediaStream()}getCurrentConstraints(){return this.currentConstraints}dispose(g){this._isDisposed||(this._isDisposed=!0,this.logger.safe.info(`dispose: ${g}`),this.logger=this.logger.createChild("DISPOSED"),this.event("onStreamClientDisposing").raise(this),this.mediaTrack&&(this.unsubscribeFromMediaTrackEvents(),this.mediaTrack=null),this.masterStream&&(this.unsubscribeFromMasterStreamEvents(),this.masterStream.disposeClient(this),this.masterStream=null),this.unsubscribeFromMixerTrackEvents(),super.dispose(),this.event("onStreamClientDisposed").raise(this))}async applyCapabilities(g){if(!this.mediaTrack)return!1;const f=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,g,this.getResolution());if(!f||!this.configProvider.config.recoverOnStreamUnmute&&this.currentConstraints===f)return!1;this.configProvider.config.waitForVideoEffectsBeforeApplyingConstraints&&this.masterStream.mediaStreamReady&&await this.masterStream.mediaStreamReady();const applyConstraints=async g=>{try{return await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,f),this.currentConstraints=f,!0}catch(f){if(g)throw this.logger.safe.error(`Apply constraints error: ${JSON.stringify(f)}`),f;return this.logger.safe.warn(`Apply constraints failed and will be re-tried, error ${JSON.stringify(f)}`),!1}},S=this.currentConstraints.withEffect&&this.configProvider.config.effectsApplyConstraintsRetryMs;return!await applyConstraints(!S)&&S&&(await delay(this.configProvider.config.effectsApplyConstraintsRetryMs),await applyConstraints(!0)),!0}start(){return this.masterStream.start()}clone(g){return this.masterStream||this.logger.safe.error(`clone: master stream is null, reason: ${g}`),this.masterStream.getClient(`streamclient: ${g}`)}setMuted(g,f){this.isMuted=g,this.applyState(f)}setHold(g,f){this.isHold=g,this.applyState(f)}isSameStream(g){return this.parentId===g.parentId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},f=getResolutionForTrack(this.mediaTrack),S=f?.width?f:g,v=`Track resolution is ${S.width}x${S.height}.`;return f?.width?this.logger.safe.info(v):this.logger.safe.error(`${v}. Resolution not found, assuming default resolution.'`),S}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g=getFrameRateForTrack(this.mediaTrack);return 0===g?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${g}`),g}update(g){g?this.mediaTrack?this.logger.safe.error(`Media track is already created: ${this.mediaTrack.id}`):(this.mediaTrack=this.getTrackByMediaType(g,this.mediaType),this.updateTrackConstraints(),this.subscribeOnMediaTrackEvents(this.mediaTrack),this.hasMasterAudio=g&&g.getAudioTracks().length>0,this.hasMasterVideo=g&&g.getVideoTracks().length>0,this.hasMasterAudio&&this.hasMasterVideo&&(this.rawMediaStream=g),this.logger.safe.info(`Updated: ${printMediaStream(g)}`)):this.logger.safe.error("No master media stream, skipping update")}resetEffectsOutputConstraints(g){this.masterStream.resetEffectsOutputConstraints(g)}async updateTrackConstraints(){if("ScreenShare"!==this.mediaType)return;const g=this.masterStream.getResolution();if(g){const f=this.currentConstraints.clone();f.video.maxWidth=g.width,f.video.minWidth=g.width,f.video.maxHeight=g.height,f.video.minHeight=g.height;try{await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,f),this.currentConstraints=f}catch(g){this.logger.safe.error(`Apply constraints error: ${JSON.stringify(g)}`)}}}getTrackByMediaType(g,f){return"Audio"===f?g.getAudioTracks()[0]:g.getVideoTracks()[0]}applyState(g){void 0!==this.mediaTrack?.enabled&&(this.mediaTrack.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`[${g}] Track ${JSON.stringify(this.mediaTrack.id)} enabled state set to => ${this.mediaTrack.enabled}`))}subscribeOnMediaTrackEvents(g){g.onended=f=>{this.logger.safe.info(`Track ${g.id} ended: ${JSON.stringify(f)}`),this.event("onStreamClientEnded").raise(this,f)},g.onmute=()=>{this.logger.safe.info(`Track ${g.id} muted`),this.event("onStreamClientMuted").raise(this,!0)},g.onunmute=()=>{this.logger.safe.info(`Track ${g.id} unmuted`),this.event("onStreamClientMuted").raise(this,!1)}}unsubscribeFromMediaTrackEvents(){this.mediaTrack.onended=null,this.mediaTrack.onmute=null,this.mediaTrack.onunmute=null}unsubscribeFromMixerTrackEvents(){this.mixerSubscriptions.forEach((g=>g.dispose())),this.mixerSubscriptions=[]}subscribeOnMasterStreamEvents(){this.masterStreamSubscriptions.push(this.masterStream.on("onStreamStarted",((g,f)=>this.event("onStreamClientStarted").raise(this,f))),this.masterStream.on("onStreamError",((g,f)=>this.event("onStreamClientError").raise(this,f))),this.masterStream.on("onStreamTrackMuted",((g,f)=>this.event("onStreamClientMuted").raise(this,f))),this.masterStream.on("onStreamDisposing",(g=>this.dispose())),this.masterStream.on("onStreamQualityChanged",((g,f,S,v)=>this.event("onStreamQualityChanged").raise(this,f,S,v))),this.masterStream.on("onStreamTrackEnded",((g,f)=>this.event("onStreamClientEnded").raise(this,f))))}unsubscribeFromMasterStreamEvents(){this.masterStreamSubscriptions.forEach((g=>g.dispose())),this.masterStreamSubscriptions=[]}hasAudio(){return this.hasMasterAudio}hasVideo(){return this.hasMasterVideo}isActive(){return this.mediaTrack?.enabled&&!this.mediaTrack?.muted&&"live"===this.mediaTrack?.readyState}onVideoStreamQualityChanged(g,f,S){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(g)}@${f}, reason=${S}`),this.masterStream.onVideoStreamQualityChanged(g,f,S)}isDisposed(){return this._isDisposed}},OC=class extends Ht{constructor(g,f,S,v,C,_){super(_),this.stream=g,this.constraints=f,this.constraintsProvider=S,this.gumStreamProvider=v,this.configProvider=C,this.logger=_,this.clients=[],this.streams=[],this.clientId=0,this.mediaStreamSubscription=this.stream.on("onStreamAcquired",(()=>this.onStreamAcquired()))}getClient(){const g=new wC(this.clientId++,this.stream,this.constraints,this.constraintsProvider,this.gumStreamProvider,this.configProvider,this.logger);return this.addClient(g),g}disposeClient(g){this.removeClient(g),this.clients.length||this.event("onAllClientsDisposed").raise()}dispose(){this.mediaStreamSubscription.dispose(),this.clients.length&&this.logger.safe.error(`Not all clients are disposed! ${JSON.stringify(this.clients.map((g=>g.id)))}`),this.streams.forEach((g=>this.disposeStream(g))),super.dispose()}getOrCreateStream(){const g=this.streams.length?this.streams[this.streams.length-1]:this.stream.rawStream;if(!g)return null;const f=g.clone();return this.logger.safe.info(`Cloned: ${printMediaStream(g)} -> ${printMediaStream(f)}`),this.resetStream(f),this.streams.push(f),f}addClient(g){this.updateClient(g),this.clients.push(g)}updateClient(g){const f=this.getOrCreateStream();f&&g.update(f)}removeClient(g){const f=this.clients.indexOf(g);this.clients.splice(f,1)}addStream(){this.clients.forEach((g=>this.updateClient(g)))}disposeStream(g){g.getTracks().forEach((g=>{this.logger.safe.info(`Stopping track: ${JSON.stringify(g.id)}`),g.stop()}))}onStreamAcquired(){this.addStream()}resetStream(g){g.getTracks().forEach((g=>{this.logger.safe.info(`Resetting state for track: ${g.id}`),g.enabled=!0}))}},DC=class{constructor(){}getPolicies(g){if(g.audio&&!g.video&&this.hasAudioProcessingConstraints(g))return[g,new cC({deviceId:g.audio.deviceId},null)];if(!g.video)return[g];const f=this.getSuitableResolutions(g).map((f=>this.getConstraintsForResolution(g,f))),S=g.audio,v={deviceId:g.video.deviceId},C=new cC(S,v,g.withTimeout);return f.push(C),f}getSuitableResolutions(g){return ei.Send.getResolutions().filter((f=>f.width<=g.video.maxWidth&&f.height<=g.video.maxHeight)).reverse()}getConstraintsForResolution(g,f){const S=g.clone();return S.video.minWidth=f.width,S.video.minHeight=f.height,S}hasAudioProcessingConstraints(g){const f=g&&g.audio;return f&&(void 0!==f.echoCancellation||void 0!==f.autoGainControl||void 0!==f.noiseSuppression)}},NC=class{static getStrategy(g,f,S,v,C,_){return _?new xC(S,v):"Video"===g?new FC(f,S,v,C):new LC(f,S,v)}},kC=class{constructor(g,f,S){this.gumStreamProvider=g,this.serialQueue=f,this.logger=S}getStream(g){return this.logger.safe.info(`Requesting stream with constraints: ${JSON.stringify(scrubConstraints(g))}`),this.serialQueue.add((()=>this.request(g)))}},LC=class extends kC{constructor(g,f,S){super(g,f,S.createChild("SimpleStrat"))}request(g){return this.gumStreamProvider.getStream(g)}},FC=class extends kC{constructor(g,f,S,v){super(g,f,S.createChild("MultStrat")),this.policyGenerator=new DC}request(g){const f=this.policyGenerator.getPolicies(g);return this.makeRequests(f)}makeRequests(g){const f=g[0];return this.logger.safe.info(`Requesting media stream with policy: ${JSON.stringify(f)}`),this.makeRequestWithPolicy(f).catch((f=>{const S=g.slice(1);if(S.length&&qt.MEDIA_ERROR.constraintNotSatisfiedError===f.type)return this.logger.safe.warn("Could not obtain constrained media stream, will attempt weaker policy"),this.makeRequests(S);throw f}))}makeRequestWithPolicy(g){return this.gumStreamProvider.getStream(g)}},xC=class extends kC{constructor(g,f){super(null,g,f.createChild("WithOveriddenStreamStart"))}request(g){return new Promise(((f,S)=>f(g.withOverridenStream)))}},UC=class _SimulcastMediaStream extends Ht{constructor(g,f,S,v,C){super(v),this.serialQueue=f,this.configProvider=S,this.effectManager=C,this.gumRequestTime=0,this.effectsSubs=[],this.id=_SimulcastMediaStream.streamId++,this.logger=v.createChild(`MediaStream:${this.id}`),this.mediaType=this.getMediaType(g),this.initialize(g)}get rawStream(){return this.mediaStream}get deviceId(){return this.originalMediaStream?this.originalMediaStream.getTracks()?.[0]?.getSettings?.()?.deviceId:null}start(){return this.mediaStreamStartPromise||(this.mediaStreamStartPromise=this.startStream(this.currentConstraints)),this.mediaStreamStartPromise}dispose(g){this.event("onStreamDisposing").raise(this),this.stopMediaStream(g).catch((g=>{this.event("onStreamError").raise(this,g)})).finally((()=>{this.constraintsProvider=null,this.serialQueue=null,this.configProvider=null,this.logger=this.logger.createChild("DISPOSED"),this.clientGenerationStrategy.dispose(),this.event("onStreamDisposed").raise(this),super.dispose()}))}disposeClient(g){this.clientGenerationStrategy.disposeClient(g)}getClient(g){return this.logger.safe.debug(`getClient: ${g}`),this.clientGenerationStrategy.getClient()}getOriginalMediaStream(){return this.originalMediaStream}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},f=getResolutionForStream(this.mediaStream),S=f??g,v=`Stream resolution is ${S.width}x${S.height}.`;return f?this.logger.safe.info(v):this.logger.safe.error(`${v}. Resolution not found, assuming default resolution.'`),S}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g=getFrameRateForStream(this.mediaStream);return 0===g?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${g}`),g}getMediaType(g){if(g.sharing)return"ScreenShare";if(g.video)return"Video";if(g.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(g)}`)}resetEffectsOutputConstraints(g){const f=getResolutionForStream(this.originalMediaStream);this.effectManager.resetOutputConstraints("Video",{width:Math.min(g.width,f.width||Number.MAX_SAFE_INTEGER),height:Math.min(g.height,f.height||Number.MAX_SAFE_INTEGER)})}initialize(g){this.constraintsProvider=CC.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(g),this.gumStreamProvider=RC.getStreamProvider(this.mediaType,this.configProvider,this.logger),this.mediaStreamRequestStrategy=NC.getStrategy(this.mediaType,this.gumStreamProvider,this.serialQueue,this.logger,this.configProvider,!!this.currentConstraints.withOverridenStream),this.clientGenerationStrategy=new OC(this,this.currentConstraints,this.constraintsProvider,this.gumStreamProvider,this.configProvider,this.logger),this.clientGenerationStrategy.on("onAllClientsDisposed",(()=>this.onAllClientsDisposed()))}onAllClientsDisposed(){this.logger.safe.info("All clients are disposed, disposing master stream"),this.dispose()}async startStream(g){try{await this.getOrCreateMediaStream(g),this.event("onStreamStarted").raise(this,this.currentConstraints)}catch(g){throw this.event("onStreamError").raise(this,g),g}}mediaStreamReady(){return this.effectsApplied?this.effectsApplied.promise:Promise.resolve()}async getOrCreateMediaStream(g){if(this.mediaStream)return Promise.resolve();const f=this.getRequestStartTimestamp(),S=await this.mediaStreamRequestStrategy.getStream(g);return this.gumRequestTime=this.getRequestDuration(f),this.handleMediaStreamRequestSuccess(S,g)}async handleMediaStreamRequestSuccess(g,f){this.logger.safe.info(`Media stream acquired: ${printMediaStream(g)} with constraints: ${JSON.stringify(scrubConstraints(f))}`),this.originalMediaStream=g,this.subscribeToTrackEvents(this.originalMediaStream),this.currentConstraints=f,this.mediaStream=await this.applyEffects(g),this.applyState(this.mediaStream),this.event("onStreamAcquired").raise(this,this.gumRequestTime,"Audio"!==this.mediaType&&this.getResolution()||void 0)}async applyEffects(g){switch(this.mediaType){case"Video":return this.getVideoEffectStream(g);case"Audio":return this.startNoiseSuppression(g);case"ScreenShare":return this.delayScreenShare(g)}return g}async delayScreenShare(g){return this.configProvider.config.useDelayedScreenShareStream?this.effectManager.startEffect("ScreenShare",g):g}async startNoiseSuppression(g){return this.configProvider.config.applyAudioEffectOnDemand&&!this.currentConstraints.withEffect?g:(this.logger.safe.info(`ECS keys for wasmvqe are: ${JSON.stringify(this.configProvider.config.wasmvqe)}`),this.logger.safe.info(`ECS keys for wasmdns are: ${JSON.stringify(this.configProvider.config.wasmdns)}`),await this.effectManager.startEffect("Audio",g))}async getVideoEffectStream(g){if(!this.currentConstraints.withEffect||this.currentConstraints.withOverridenStream&&this.configProvider.config.useRawMediaApiForVideoEffects)return g;this.effectsSubs.push(this.effectManager.on("onVideoStreamQualityChanged",((g,f,S)=>this.onVideoStreamQualityChanged(g,f,S)))),this.configProvider.config.waitForVideoEffectsBeforeApplyingConstraints&&(this.effectsApplied=new dt,this.effectsSubs.push(this.effectManager.on("onVideoEffectApplied",(()=>{this.logger.safe.info("Resolving effects applied promise"),this.effectsApplied.resolve()}))));const f=await this.effectManager.startEffect("Video",g);return this.logger.safe.info(`Media stream switched: ${printMediaStream(g)} -> ${printMediaStream(f)}`),f}subscribeToTrackEvents(g){const f=g?this.getTrackByMediaType(g,this.mediaType):null;f&&(f.onended=g=>{this.logger.safe.info(`Track ${f.id} ended: ${JSON.stringify(g)}`),this.event("onStreamTrackEnded").raise(this,g)},f.onmute=()=>{this.logger.safe.info(`Track ${f.id} muted`),this.event("onStreamTrackMuted").raise(this,!0)},f.onunmute=()=>{this.logger.safe.info(`Track ${f.id} unmute`),this.event("onStreamTrackMuted").raise(this,!1)})}unsubscribeFromTrackEvents(g){const f=g?this.getTrackByMediaType(g,this.mediaType):null;f&&(f.onended=null,f.onmute=null,f.onunmute=null)}getTrackByMediaType(g,f){return"Audio"===f?g.getAudioTracks()[0]:g.getVideoTracks()[0]}removeVideoEffectStream(){this.effectsSubs.forEach((g=>g?.dispose())),this.effectsSubs=[],this.effectManager.stopEffect("Video",this.mediaStream)}applyState(g){g.getAudioTracks()?.forEach((g=>this.applyAudioState(g)));const f=g.getVideoTracks()[0];this.applyVideoState(f)}applyAudioState(g){g&&(this.hasNonDefaultAudioProcessingConstraints()||"ScreenShare"===this.mediaType?this.applyContentHint(g,"music"):this.configProvider.config.defaultAudioContentHint&&this.applyContentHint(g,this.configProvider.config.defaultAudioContentHint),g.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(g.id)}`))}applyVideoState(g){g&&("ScreenShare"===this.mediaType&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(g,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(g.id)}`))}applyContentHint(g,f){this.logger.safe.info(`Apply content hint: ${f}`),g.contentHint=f}hasNonDefaultAudioProcessingConstraints(){const g=this.currentConstraints.audio;if(g){const f=this.configProvider.config.defaultAudioProcessingFlags;let S;return void 0===g.echoCancellation&&void 0===g.autoGainControl&&void 0===g.noiseSuppression||(S=0,void 0!==g.echoCancellation&&(S+=g.echoCancellation?2:0),void 0!==g.autoGainControl&&(S+=g.autoGainControl?1:0),void 0!==g.noiseSuppression&&(S+=g.noiseSuppression?4:0)),S!==f}return!1}getRequestStartTimestamp(){return Date.now()}getRequestDuration(g){return 0===g?0:Date.now()-g}stopMediaStream(g){return this.mediaStreamStartPromise?(this.logger.safe.info(`Queueing media stream stop: ${g}`),this.serialQueue.add((()=>this.stopMediaStreamInternal()))):Promise.resolve()}stopOneMediaStream(g){try{g.getTracks().forEach((g=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(g.id)}`),g.stop()})),this.logger.safe.info(`Media stream stopped: ${g.id}`)}catch(g){this.logger.safe.warn(`Failed to stop media stream: ${stringifyObject(g)}`)}}stopMediaStreamInternal(){"Video"===this.mediaType&&this.configProvider.config.enableVideoEffects&&this.removeVideoEffectStream(),this.mediaStream&&(this.stopOneMediaStream(this.mediaStream),this.mediaStream=null),this.originalMediaStream&&(this.stopOneMediaStream(this.originalMediaStream),this.unsubscribeFromTrackEvents(this.originalMediaStream),this.originalMediaStream=null)}onVideoStreamQualityChanged(g,f,S){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(g)}@${f}, reason=${S}`),this.event("onStreamQualityChanged").raise(this,g,f,S)}};UC.streamId=0;var VC=UC,BC=class{static getStrategy(g){switch(g.config.diagnostics.performanceMonitoring.monitoringStrategy){case"decodeTime":default:return new HC(g);case"renderedFps":return new $C(g);case"rendererVolatility":return new jC(g)}}},HC=class{constructor(g){this.configProvider=g,this.decodeThresholds=this.configProvider.config.diagnostics.performanceMonitoring.decodeThresholds,this.defaultThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultThrehold,this.badPerfCount=new Map}checkQuality(g){let f=!1,S=!1;const v=ei.Recv.getResolutionRecord(Math.min(g.frameHeight,g.frameWidth)).height,C=this.decodeThresholds[v]||this.defaultThreshold,_=g.decodeTimeTracker.getReport();return _.median>C.maxDecodeTime&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)||1),f=!0),_.median<C.maxDecodeTime&&this.badPerfCount.get(g.msi)&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)-1),S=!0),f?0:S?2:1}},$C=class{constructor(g){this.configProvider=g,this.fpsDiffThresholds=this.configProvider.config.diagnostics.performanceMonitoring.fpsDiffThresholds,this.defaultFpsDiffThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultFpsDiffThreshold,this.badPerfCount=new Map}checkQuality(g){let f=!1,S=!1;const v=ei.Recv.getResolutionRecord(Math.min(g.frameHeight,g.frameWidth)).height,C=this.fpsDiffThresholds[v]||this.defaultFpsDiffThreshold,_=g.incomingFps.getReport(),T=g.rendererFps.getReport(),I=_.median-T.median;return I>=C.fpsDiff&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)||1),f=!0),I<C.fpsDiff&&this.badPerfCount.get(g.msi)&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)-1),S=!0),f?0:S?2:1}},jC=class{constructor(g){this.configProvider=g,this.volatilityThresholds=this.configProvider.config.diagnostics.performanceMonitoring.volatilityThresholds,this.defaultVolatilityThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultVolatilityThreshold,this.badPerfCount=new Map}checkQuality(g){let f=!1,S=!1;const v=ei.Recv.getResolutionRecord(Math.min(g.frameHeight,g.frameWidth)).height,C=this.volatilityThresholds[v]||this.defaultVolatilityThreshold,_=g.rendererFps.getReport(),T=g.incomingFps.getReport(),I=Math.abs(_.volatilityPercent-T.volatilityPercent);return C&&I>=C&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)||1),f=!0),I<C&&this.badPerfCount.get(g.msi)&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)-1),S=!0),f?0:S?2:1}},GC=class{constructor(g,f){this.streamClient=g,this.logger=f,this.rawBaseClient=new Yr((()=>this.getStream()),(()=>this.activeRawInputMediaStreamClient?.dispose()),f)}client(){return this.rawBaseClient}disposeActiveMediaStreamClient(){this.logger.info("Disposing active media stream client"),this.activeRawInputMediaStreamClient?.dispose("Disposed by RawDeviceStreamManager"),this.activeRawInputMediaStreamClient=null}async getStream(){return this.activeRawInputMediaStreamClient?.originalMediaStream?.active?(this.logger.info("Returning stream from active mediaStreamClient"),this.activeRawInputMediaStreamClient.originalMediaStream):(this.activeRawInputMediaStreamClient=await this.streamClient(),await this.activeRawInputMediaStreamClient.start(),this.activeRawInputMediaStreamClient.originalMediaStream)}},qC=class{constructor(g,f){this.logger=g,this.raiseTelemetryEvent=f,this.handlerMap=new Map([["Audio",new Map],["Video",new Map],["ScreenShare",new Map]])}dispose(g){this.logger.info(`disposing IRawStream ${g}`),this.handlerMap.get(g).forEach((g=>g.client().dispose()))}disposeAll(){this.logger.info("Dispose All clients"),this.handlerMap.forEach((g=>g.forEach((g=>g.client().dispose()))))}notifyChange(g){this.handlerMap.get(g).forEach((g=>{g.disposeActiveMediaStreamClient(),g.client().notifyStreamChange()}))}createIRawStreamClient(g,f){this.logger.info(`Create new IRawStream client for ${f}`);const S=new GC(g,this.logger);this.handlerAdded(S,f);return S.client()}handlerAdded(g,f){const S=g.client();this.setClientSubscription(S,f),this.handlerMap.get(f).set(S.clientId,g)}deleteRawStreamManagerById(g,f){this.logger.info(`Deleting from map: ${f}`),this.handlerMap.get(f).delete(g)}setClientSubscription(g,f){this.logger.info(`Setting subscription on IRawStream client for ${f}`),g.on("clientDisposed",(S=>{this.deleteRawStreamManagerById(g.clientId,f),this.raiseTelemetryEvent("IRawStream_client_disposed",{mediaType:f,clientId:S})})),g.on("rawStreamRequested",(g=>{this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:f,clientId:g})})),g.on("notifiedOnStreamChanged",(g=>this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:f,clientId:g})))}},WC=class extends Ht{constructor(g,f,S){super(g),this.logger=g,this.configProvider=f,this.audioRendererDiagnostics=S,this.window=Xs.window,this.isMuted=!1,this.isPlayingAllowed=!1,this.hadPlaybackError=!1,this.id=uniqueId(),this.onAudioError=g=>{const f=g&&g.target||this.audio;if(this.hadPlaybackError=!0,f?.error){const g=f.error.code,S=`error with rendering audio code: ${g}, message: ${f.error.message}`;this.event("onAudioPlaybackError").raise(g,qt.MEDIA_ERROR.audioPlaybackError,S),this.logger.safe.error(S)}else this.logger.safe.error("error with audio rendering")},this.onAudioPaused=async()=>{if(this.configProvider.config.audioRendererRestartOnPause&&this.canPlay&&!this.isMuted){const g=generateCauseId();this.logger.safe.info(`[${g}] audio playback is paused by OS, resuming it`),await this.startStream(g)}},this.onAudioPlayed=()=>{this.audioRendererDiagnostics?.registerSuccessfullReopen(this.deviceId),this.logger.safe.info("Audio element started playing")}}get canPlay(){return this.stream&&this.isPlayingAllowed}get muted(){return this.isMuted}async setMuted(g,f){return this.isMuted=g,g?this.stopStream(f):this.startStream(f)}async getSpeakerVolume(g){const f=this.audio?.volume??0;return this.logger.safe.info(`[${g}] get speaker volume: ${f}`),f}async setSpeakerVolume(g,f){this.assureAudioElement(f),this.audio.volume=g,this.logger.safe.info(`[${f}] set speaker volume: ${g}`)}getStream(){return this.stream}getDeviceId(){return this.deviceId}async play(g){if(this.stream=g,this.isPlayingAllowed=!0,!this.isMuted)return this.startStream()}stop(){this.stopStream(),this.isPlayingAllowed=!1}async setOutputDevice(g,f=generateCauseId()){if(this.audio)if(this.configProvider.config.disableAudioOutputSelection)this.logger.safe.warn(`[${f}] audio-output selection is disabled, disableAudioOutputSelection: true`);else if(this.audio.setSinkId){if(g&&g!==this.currentSinkId){this.logger.safe.info(`[${f}] setting audio output device ID to ${scrubMriOrOmit(g)}`),this.deviceId=g;try{this.configProvider.config.audioSetSinkIdWorkaround&&this.stream&&!this.stream.active?(this.audio.srcObject=null,await this.audio.setSinkId(g),this.audio.srcObject=this.stream):await this.audio.setSinkId(g),this.currentSinkId=g}catch(g){this.logger.safe.warn(`[${f}] setSinkId operation was aborted with error ${stringifyObject(g)}`)}this.configProvider.config.audioRendererRestartOnDeviceError&&this.hadPlaybackError&&!this.isMuted&&(this.audioRendererDiagnostics?.registerReopenRequest(g),this.logger.safe.info(`[${f}] audio playback error happened, restarting audio stream on new device`),await this.startStream(f),this.hadPlaybackError=!1)}}else this.logger.safe.warn(`[${f}] setting output device is not supported`);else this.deviceId=g}dispose(){this.logger.safe.info("dispose"),super.dispose(),this.audio&&(this.stop(),this.stream=void 0,this.audio.removeEventListener("error",this.onAudioError),this.audio.removeEventListener("pause",this.onAudioPaused),this.audio.removeEventListener("play",this.onAudioPlayed),this.window.document.body.removeChild(this.audio),this.event("onAudioElementRemoved").raise(this.audio),this.currentSinkId=void 0,this.audio=void 0),this.detachGainNode()}async startStream(g=generateCauseId()){if(this.canPlay)try{await this.assureAudioElement(g),this.logger.safe.info(`[${g}] attaching stream to renderer: ${this.stream?.id}`),this.configProvider.config.speakerGainLevel&&this.reattachToGainNode(this.stream,this.configProvider.config.speakerGainLevel),this.audio.srcObject=this.stream,await this.audio.play(),this.event("onAudioStateChanged").raise(this.stream,this.id)}catch(f){this.logger.safe.warn(`[${g}] play operation was aborted with error ${stringifyObject(f)}`)}}async assureAudioElement(g=generateCauseId()){if(!this.audio)return this.logger.safe.info(`[${g}] creating audio element`),this.audio=this.window.document.createElement("audio"),this.audio.addEventListener("error",this.onAudioError),this.audio.addEventListener("pause",this.onAudioPaused),this.audio.addEventListener("play",this.onAudioPlayed),this.window.document.body.appendChild(this.audio),this.audio.autoplay=!0,this.event("onAudioElementAdded").raise(this.audio),this.setOutputDevice(this.deviceId,g)}stopStream(g=generateCauseId()){this.audio&&this.canPlay&&(this.detachGainNode(),this.configProvider.config.audioRendererUsePauseOnDetach?(this.logger.safe.info(`[${g}] Pausing with stream: ${this.stream?.id}`),this.audio.pause()):(this.logger.safe.info(`[${g}] Detaching from stream: ${this.stream?.id}`),this.audio.srcObject=null),this.event("onAudioStateChanged").raise(null,this.id))}attachToGainNode(g,f){this.audioContext=new Xs.window.AudioContext,this.sourceNode=this.audioContext.createMediaStreamSource(g),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=f,this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination)}detachGainNode(){this.sourceNode?.disconnect(),this.sourceNode=void 0,this.gainNode?.disconnect(),this.gainNode=void 0,this.audioContext?.close(),this.audioContext=void 0}reattachToGainNode(g,f){this.detachGainNode(),this.attachToGainNode(g,f)}},zC=class{constructor(g){this.logger=g,this.queue=Promise.resolve()}add(g,f=generateCauseId()){let S;S=g instanceof dt?()=>g.promise:g;const v=this.queue.then(S);return this.queue=v.catch((g=>{if(this.queue){let S="";g instanceof TypeError&&(S=g.stack),this.logger.safe.error(`[${f}] Error from promiseQueue! ${stringifyObject(g)} ${S}`)}})),v}dispose(){this.queue=null}},KC=M,JC=(g=>(g[g.NONE=0]="NONE",g[g.VIDEO=1]="VIDEO",g[g.AUDIO=2]="AUDIO",g))(JC||{});function getRecvOverlayStats(g,f,S){const{ssrc:v,keyFramesDecoded:C,nackCount:_,firCount:T,pliCount:I,decoderImplementation:b,packetsLost:A}=g.inboundRTP,{frameRateReceived:P,frameRateDecoded:R,bitrate:M,decodeTime:w,isFrozen:O}=g.extensions??{},{sourceId:D,msid:N,streamSize:k,rendererSize:L}=S,F=g.renderer?.modality===qt.MODALITY.sharing,{audioLevel:x}=f.inboundRTP,{mimeType:U}=f.codec??{},{healedRatio:V,lossRate:B}=f.extensions??{};return{streamSize:{overlayTab:1,format:"{0}x{1}",values:[k?.width,k?.height],undefinedFallback:0},rendererSize:{overlayTab:1,format:"{0}x{1}",values:[L?.width,L?.height],undefinedFallback:0},ssrc:{overlayTab:1,values:[v]},msid:{overlayTab:1,text:"sourceId/msid",format:"{0}/{1}",values:[D(),N()]},fps:{overlayTab:1,text:"FPS(r/d)",format:"{0}/{1}",values:[P,R],highlightUndefined:!0,lowerThreshold:1,upperThreshold:45,allowedDeviationThreshold:.2,suppressHighlighting:F},bitrate:{overlayTab:1,format:"{0} kbps",values:[toKbps(M)],lowerThreshold:24,suppressHighlighting:F},decodeTime:{overlayTab:1,format:"{0} ms",values:[w],upperThreshold:15,highlightUndefined:!0,suppressHighlighting:F},keyFramesDecoded:{overlayTab:1,text:"KFs",values:[C]},nacksFirsPlisSent:{overlayTab:1,text:"N/F/P",format:"{0}/{1}/{2}",values:[_,T,I],undefinedFallback:0,highlightChange:!0},packetsLost:{overlayTab:1,text:"lost",values:[A],undefinedFallback:0,highlightChange:!0},codecImplementationName:{overlayTab:1,text:"decoder",values:[b],highlightUndefined:!0},isFrozen:{overlayTab:1,values:[O?"YES":"NO"],fixedValueThreshold:"NO"},audioCodec:{overlayTab:2,values:[U?.split("/").pop()]},audioLevel:{overlayTab:2,values:[round(x,4)]},healedRatio:{overlayTab:2,values:[round(V,4)],upperThreshold:.2},lossRate:{overlayTab:2,values:[round(B,4)],upperThreshold:.1}}}function getSendOverlayStats(g,f){const{rid:S,ssrc:v,frameWidth:C,frameHeight:_,framesPerSecond:T,keyFramesEncoded:I,nackCount:b,firCount:A,pliCount:P,encoderImplementation:R,qualityLimitationReason:M}=g.outboundRTP,{cameraOpenResolution:w,bitrate:O,encodeTime:D,frameRateEncoded:N,frameRateSent:k,qp:L}=g.extensions??{},{mimeType:F}=f.codec??{},{lossRate:x}=f.extensions??{},{audioLevel:U}=f.mediaSource??{};return{rid:{overlayTab:1,values:[S],hideUndefined:!0},cameraSize:{overlayTab:1,format:"{0}x{1}",values:[w?.width,w?.height]},inputSize:{overlayTab:1,format:"{0}x{1}",values:[g.mediaSource?.width,g.mediaSource?.height]},sentSize:{overlayTab:1,format:"{0}x{1}",values:[C,_]},ssrc:{overlayTab:1,values:[v]},fps:{overlayTab:1,text:"FPS(i/e/s)",format:"{0}/{1}/{2}",values:[T,N,k],lowerThreshold:7,upperThreshold:45,allowedDeviationThreshold:.2},bitrate:{overlayTab:1,format:"{0} kbps",values:[toKbps(O)],lowerThreshold:24},encodeTime:{overlayTab:1,format:"{0} ms",values:[D],upperThreshold:15},keyFramesEncoded:{overlayTab:1,text:"KFs",values:[I]},qp:{overlayTab:1,values:[L]},nacksFirsPlisRecv:{overlayTab:1,text:"N/F/P",format:"{0}/{1}/{2}",values:[b,A,P],undefinedFallback:0,highlightChange:!0},codecImplementationName:{overlayTab:1,text:"encoder",values:[R],highlightUndefined:!0},qualityLimitationReason:{overlayTab:1,text:"limited",values:[M],fixedValueThreshold:"none"},bwe:{overlayTab:1,format:"{0} kbps",values:[toKbps(g.transport?.selectedCandidatePair?.availableOutgoingBitrate)],lowerThreshold:100},audioCodec:{overlayTab:2,values:[F?.split("/").pop()]},audioLevel:{overlayTab:2,values:[round(U,4)]},lossRate:{overlayTab:2,values:[round(x,4)]}}}function toKbps(g){return g&&Math.floor((g||0)/1e3)}var YC=class{constructor(g){this.container=g,this.formatRegexPattern=new RegExp(/{(\d+)}/g),this.elements={},this.previousSamples={},this.overlayTab=1,this.createTableCell=(g,f,S)=>{this.elements[g]=document.createElement("td"),this.elements[g].title=g,this.addElementStyle(g,S),this.elements[f].appendChild(this.elements[g])},this.topElement=g.ownerDocument.createElement("div"),this.topElement.classList.add("vdi-occlusion"),this.topElement.style.position="absolute",this.topElement.style.top="0px",this.topElement.style.left="0px",this.topElement.style.zIndex="100",this.topElement.style.transform="inherit",this.topElement.style.backgroundColor="rgba(0, 0, 0, 0.25)",this.topElement.style.pointerEvents="all",this.topElement.style.minWidth="15px",this.topElement.style.minHeight="15px",this.topElement.style.cursor="pointer",this.topElement.onclick=()=>{this.overlayTab=getNextTab(this.overlayTab)},this.container.appendChild(this.topElement),this.table=document.createElement("table"),this.table.style.borderCollapse="collapse",this.table.style.fontSize="smaller",this.topElement.appendChild(this.table)}dispose(){this.topElement.removeChild(this.table),this.container.removeChild(this.topElement),this.table=null,this.topElement=null,this.container=null}createTableColumn(g,f){for(const S of Object.keys(g)){const v=g[S];v.overlayTab===this.overlayTab&&(v.hideUndefined&&v.values.every((g=>!g))||this.createTableRow(S,v,f))}}createTableRow(g,f,S){this.elements[g]||(this.elements[g]=document.createElement("tr"),this.table.appendChild(this.elements[g]));const v=`${g}-title`,C=`${g}-${S}`,_=this.formatValue(f),T=this.previousSamples[C]!==_;this.previousSamples[C]=_;const I=isOutlier(f)||!(!f.highlightChange||!T);this.elements[v]||(this.createTableCell(v,g,!1),this.elements[v].innerText=f.text?f.text:g),this.createTableCell(C,g,!f.suppressHighlighting&&I),this.elements[C].innerText=_}clearTable(){for(;this.table.hasChildNodes();)this.table.removeChild(this.table.lastChild);this.elements={}}getOverlayTab(){return this.overlayTab}addElementStyle(g,f){this.elements[g].style.color=f?"#F72F35":"#FBF719",this.elements[g].style.fontSize="smaller",this.elements[g].style.lineHeight="1",this.elements[g].style.padding="0px 1px 0px 1px",this.elements[g].style.maxWidth="60px",this.elements[g].style.overflow="hidden",this.elements[g].style.whiteSpace="nowrap",this.elements[g].style.textOverflow="ellipsis"}formatValue(g){const{values:f,format:S,undefinedFallback:v="N/A"}=g;return S?S.replace(this.formatRegexPattern,((g,S)=>f?.[S]?.toString()??v.toString())):f?.[0]?.toString()??v.toString()}},QC=class{constructor(g,f,S){this.container=f,this.renderer=S,this.subs=[],g&&!this.overlay&&(this.overlay=new YC(this.container),this.rendererStats={msid:()=>this.renderer.getLocalMsi(),sourceId:()=>this.renderer.getMsi()},this.subs.push(this.renderer.on("onVideoSizeChanged",((g,f)=>this.rendererStats.streamSize={width:g,height:f}))),this.subs.push(this.renderer.on("onRendererSizeChanged",((g,f)=>this.rendererStats.rendererSize={width:Math.ceil(f.width),height:Math.ceil(f.height)}))))}setStats(g,f){this.overlay&&(this.overlay.clearTable(),this.overlay.createTableColumn(getRecvOverlayStats(g,f,this.rendererStats),g.inboundRTP.id))}dispose(){this.subs.forEach((g=>g.dispose())),this.subs=[],this.overlay?.dispose(),this.overlay=null,this.container=null,this.renderer=null}},XC=class{constructor(g,f){this.container=f,g&&!this.overlay&&(this.overlay=new YC(this.container))}setStats(g,f){if(!this.overlay)return;if(this.overlay.clearTable(),2===this.overlay.getOverlayTab())return void this.overlay.createTableColumn(getSendOverlayStats(g,f),g.outboundRTP.id);const S=[g,...g.altLayouts??[]];for(const g of S)this.overlay.createTableColumn(getSendOverlayStats(g,f),g.outboundRTP.id)}dispose(){this.overlay?.dispose(),this.overlay=null,this.container=null}};function getNextTab(g){const f=Object.keys(JC).filter((g=>isNaN(Number(g)))),S=(g+1)%f.length;return JC[f[S]]}function isOutlier(g){const{values:f,lowerThreshold:S,upperThreshold:v,highlightUndefined:C,fixedValueThreshold:_,allowedDeviationThreshold:T}=g;for(const g of f){if(void 0===g&&null===g&&C)return!0;if(_&&_!==g)return!0;if(null==g||!(0,KC.isNumber)(g))return!1;if(S&&Number(g)<=S)return!0;if(v&&Number(g)>=v)return!0;if(T){const S=(0,KC.mean)(f),v=S*T;if(Math.abs(Number(g)-S)>v)return!0}}return!1}function getObjectFitValue(g){switch(g){case"crop":return"cover";case"stretch":return"fill";default:return"contain"}}var ZC=class _VideoRendererBase extends Ht{constructor(g,f,S){const v=f.createChild(""+_VideoRendererBase.rendererId++);super(v),this.container=g,this.configProvider=S,this.video=this.container.ownerDocument.createElement("video"),this.lastNotifiedVideoWidth=0,this.lastNotifiedVideoHeight=0,this.isVideoAttached=!1,this.onVideoDataUpdated=()=>{let g=this.video.videoWidth,f=this.video.videoHeight;(g<32||f<32)&&(g=f=0),this.lastNotifiedVideoWidth===g&&this.lastNotifiedVideoHeight===f||(this.lastNotifiedVideoWidth=g,this.lastNotifiedVideoHeight=f,this.event("onVideoSizeChanged").raise(g,f)),this.playVideo()},this.onVideoError=()=>{this.logger.safe.info(`onVideoError: error with video rendering: ${JSON.stringify(this.video.error)||"no video"}`),this.event("onVideoRendererStateChanged").raise({timestamp:Date.now(),state:"onError",payload:JSON.stringify(this.video.error)||"no video"})},this.onVideoPaused=()=>{this.logger.safe.info("onVideoPaused: video playback is paused"),this.event("onVideoRendererStateChanged").raise({timestamp:Date.now(),state:"onVideoPaused"}),this.playVideo()},this.onVideoPlayed=()=>{this.logger.safe.info("onVideoPlayed"),this.event("onVideoRendererStateChanged").raise({timestamp:Date.now(),state:"onVideoPlayed"})},this.onContextMenu=g=>{g.preventDefault()},this.logger=v,this.video.style.width="100%",this.video.style.height="100%",this.video.setAttribute("playsinline","true"),this.video.disablePictureInPicture=!0,this.video.autoplay=!0,this.video.muted=!0,this.attachEventListeners(),this.logger.safe.info("created")}getVideoElement(){return this.video}dispose(){super.dispose(),this.isVideoAttached&&(this.container.removeChild(this.video),this.isVideoAttached=!1),this.detachEventListeners(),this.attachMediaStream(null),this.video=null,this.stream=null,this.canvas=null,this.context=null}attachMediaStream(g){this.stream!==g&&(this.stream&&(this.video.srcObject=null),g&&(this.video.hidden=0===g.getVideoTracks().length,this.video.srcObject=g,this.isVideoAttached||(this.container.appendChild(this.video),this.isVideoAttached=!0)),this.stream=g)}setScalingMode(g){this.video.style.objectFit=getObjectFitValue(g)}getMediaStream(){return this.stream}getTrackId(){return this.stream?.getTracks()[0]?.id??void 0}async captureFrame(){const g=this.stream;if(!g)throw this.logger.safe.error("Mediastream not found"),new Error("Mediastream not found");const f=g.getVideoTracks?.()?.[0]?.getSettings(),S=f?.width,v=f?.height;if(!S||!v)throw this.logger.safe.error("Failed to get video track width/height"),new Error("Failed to get video track width/height");const C=this.getImageData(S,v);return{getSize:()=>({width:S,height:v}),isMirrored:()=>!1,getImageData:()=>C}}playVideo(){this.video?.paused&&this.video.play().catch((g=>{this.logger.safe.error(`Play video error: ${g}`)}))}getImageData(g,f){if(this.canvas??(this.canvas=this.container.ownerDocument.createElement("canvas")),this.context??(this.context=this.canvas.getContext("2d")),!this.context)throw this.logger.safe.error("Failed to get canvas 2d context"),new Error("Failed to get canvas 2d context");this.canvas.width=g,this.canvas.height=f,this.context.drawImage(this.video,0,0,g,f);return this.context.getImageData(0,0,g,f)}attachEventListeners(){this.video.addEventListener("loadedmetadata",this.onVideoDataUpdated),this.video.addEventListener("timeupdate",this.onVideoDataUpdated),this.video.addEventListener("error",this.onVideoError),this.video.addEventListener("pause",this.onVideoPaused),this.video.addEventListener("contextmenu",this.onContextMenu),this.video.addEventListener("play",this.onVideoPlayed)}detachEventListeners(){this.video.removeEventListener("loadedmetadata",this.onVideoDataUpdated),this.video.removeEventListener("timeupdate",this.onVideoDataUpdated),this.video.removeEventListener("error",this.onVideoError),this.video.removeEventListener("pause",this.onVideoPaused),this.video.removeEventListener("contextmenu",this.onContextMenu),this.video.removeEventListener("play",this.onVideoPlayed)}};ZC.rendererId=0;var ey=ZC,ty=class extends ey{constructor(g,f,S,v,C){super(g,S.createChild("local"),v),this.mediaStreamProvider=f,this.mediaType=C,this.isDisposed=!1,this.serialQueue=new zC(this.logger.createChild("rendererQueue")),this.logger.safe.info("ctor"),this.overlayStats=new XC(this.configProvider.config.showStatsInCall,g)}dispose(){this.logger.safe.info("dispose"),this.isDisposed=!0,this.event("onRendererDisposed").raise(this),super.dispose(),this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),this.overlayStats.dispose()}setVideoMirroring(g){this.configProvider.config.localPreviewMirroringSupported&&(this.getVideoElement().style.transform=g?"scaleX(-1)":void 0)}startVideoAsync(g=generateCauseId()){return this.logger.safe.info(`[${g}] starting local video`),this.event("onRendererStarted").raise(this),this.serialQueue.add((()=>this.restartVideo()),g)}updateStreamAsync(g=generateCauseId()){return this.logger.safe.info(`[${g}] updating local video`),this.serialQueue.add((()=>this.restartVideo()),g)}onDiagnosticUpdated(g){g.video?.send?.length&&g.audio?.send?.length&&this.overlayStats.setStats(g.video.send[0],g.audio.send[0])}async restartVideo(){try{let g;if("Video"===this.mediaType)g=await this.mediaStreamProvider.getVideoStream(!1,"localVideoRenderer");else{if("ScreenShare"!==this.mediaType)throw new Error("Not yet supported");g=await this.mediaStreamProvider.getDisplayStream("localSSRenderer")}if(await g.start(),this.isDisposed)throw g.dispose(),new Error("local video renderer is disposed");this.attachStream(g)}catch(g){throw this.mediaStreamProvider.raiseTelemetryEvent("video_preview_error",{mediaType:this.mediaType,error:stringifyObject(g)}),g}}attachStream(g){if(this.mediaStream!==g)if(this.mediaStream?.parentId!==g?.parentId){this.logger.safe.info(`attach media stream ${g?.id}`);try{this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),g&&super.attachMediaStream(g.rawStream),this.mediaStream=g}catch(f){throw g&&g.dispose(),f}}else g.dispose()}},iy=class extends Ht{constructor(g,f,S){super(S),this.mediaStream=g,this.logger=S,this.mediaStreamSubscriptions=[],this.isHold=!1,this.isMuted=this.mediaStream.getMuted(),this._isDisposed=!1,this.originalId=g.id,this.subscribeOnMediaStreamEvents(),this.update(f),this.logger.safe.info("ctor"),this.mediaType=this.mediaStream.mediaType}get id(){return this.originalId}get parentId(){return this.originalId}get rawStream(){return this.gumStream}get rawTrack(){return this.getTrackByMediaType(this.rawStream,this.mediaType)}get deviceId(){return this.mediaStream.deviceId}update(g){g&&(this.gumStream=g,this.enableDisableTracks())}dispose(){this._isDisposed?this.logger.safe.info("already disposed"):(this._isDisposed=!0,this.logger.safe.info("dispose"),this.logger=this.logger.createChild("DISPOSED"),this.event("onStreamClientDisposing").raise(this),this.mediaStream&&(this.mediaStream.disposeClient(this),this.unsubscribeFromMediaStreamEvents(),this.mediaStream=null),this.event("onStreamClientDisposed").raise(this))}clone(){const g=this.mediaStream.getClient();return this.isMuted&&g.setMuted(!0),this.isHold&&g.setHold(!0),g}applyCapabilities(g){return this.mediaStream.applyCapabilities(g)}setMuted(g,f=generateCauseId()){this.isMuted=g||this.mediaStream.getMuted(),this.logger.safe.info(`[${f}] setMuted => ${this.isMuted}`),this.enableDisableTracks()}setHold(g){this.isHold=g,this.enableDisableTracks()}start(){return this.mediaStream.start()}hasAudio(){return this.mediaStream.hasAudio()}hasVideo(){return this.mediaStream.hasVideo()}hasDisplay(){return this.mediaStream.hasDisplay()}isSameStream(g){return this.parentId===g.parentId}getResolution(){return this.mediaStream.getResolution()}getFrameRate(){return this.mediaStream.getFrameRate()}isActive(){return!0}isDisposed(){return this._isDisposed}subscribeOnMediaStreamEvents(){this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamStarted",((g,f)=>{this.event("onStreamClientStarted").raise(this,f)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamError",((g,f)=>{this.event("onStreamClientError").raise(this,f)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackMuted",((g,f)=>{this.event("onStreamClientMuted").raise(this,f)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackEnded",((g,f)=>{this.event("onStreamClientEnded").raise(this,f)})))}unsubscribeFromMediaStreamEvents(){this.mediaStreamSubscriptions.forEach((g=>g.dispose())),this.mediaStreamSubscriptions=[]}enableDisableTracks(){this.gumStream?this.gumStream.getTracks().forEach((g=>{void 0!==g.enabled&&(g.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`Track ${JSON.stringify(g.id)} enabled state set to => ${g.enabled}`))})):this.logger.safe.warn("gumStream stream doesn't exist")}getTrackByMediaType(g,f){return"Audio"===f?g.getAudioTracks()[0]:g.getVideoTracks()[0]}},ny=class _MediaStreamInternal extends Ht{constructor(g,f,S,v){super(S),this.streamConstraints=g,this.serialQueue=f,this.configProvider=v,this.clientId=0,this.clients=[],this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.isMuted=!1,this.isHold=!1,this.gumStartTime=0,this.streamId=_MediaStreamInternal.streamGeneration++,this.logger=S.createChild(`MediaStream:${this.streamId}`),this.mediaType=this.getMediaType(this.streamConstraints),this.constraintsProvider=CC.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(g)}get id(){return this.streamId}get rawStream(){return this.currentGumStream}get deviceId(){return this.rawStream?.getTracks()?.[0]?.getSettings?.()?.deviceId??null}applyCapabilities(g){if(this.currentGumStream){const f=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,g,this.getResolution());if(!f)return Promise.resolve(!1);if(this.currentConstraints!==f){this.currentConstraints=f;const g=this.currentConstraints;return this.hasDisplay()?this.applyConstraints(this.currentConstraints).then((()=>deepEqual(this.currentConstraints,g))).catch((g=>(this.logger.safe.error(`Apply constraints error: ${stringifyObject(g)}`),!1))):this.applyConstraintsInternal().then((()=>deepEqual(this.currentConstraints,g)))}}return Promise.resolve(!1)}getClient(){let g;this.currentGumStream?(g=this.getClone(),this.clientGumStreams.push({[this.constraintsProvider.getKey(this.currentConstraints)]:g})):this.clientGumStreams.push({});const f=new iy(this,g,this.logger.createChild("Client:"+this.clientId++));return this.clients.push(f),f}getClone(){return this.hasDisplay()?this.currentGumStream:this.currentGumStream.clone()}setMuted(g){this.isMuted=g,this.clients.forEach((f=>{f.setMuted(g)})),this.enableDisableTracks()}getMuted(){return this.isMuted}setHold(g){this.isHold=g,this.clients.forEach((f=>{f.setHold(g)})),this.enableDisableTracks()}start(){return this.mediaStreamStartPromise||(this.mediaStreamStartPromise=this.startStream(this.currentConstraints)),this.mediaStreamStartPromise}dispose(){for(let g=this.clients.length-1;g>=0;g--)this.clients[g].dispose()}disposeClient(g){const f=this.clients.indexOf(g);f>=0&&(this.clients.splice(f,1),this.streamsDump.push(this.clientGumStreams[f]),this.clientGumStreams.splice(f,1),0===this.clients.length)&&this.disposeStream()}async disposeStream(){this.event("onStreamDisposing").raise(this);try{await this.stopGumStream(),this.event("onStreamDisposed").raise(this)}catch(g){this.event("onStreamError").raise(this,g)}this.constraintsProvider=null,this.serialQueue=null,this.configProvider=null,this.logger=this.logger.createChild("DISPOSED"),super.dispose()}hasAudio(){return!!this.currentGumStream&&0!==this.currentGumStream.getAudioTracks().length}hasVideo(){return!!this.currentGumStream&&0!==this.currentGumStream.getVideoTracks().length&&this.currentConstraints.video&&this.currentConstraints.video.deviceId!==qt.DISPLAY_SOURCE_ID}hasDisplay(){return!!this.currentGumStream&&0!==this.currentGumStream.getVideoTracks().length&&this.currentConstraints.video&&this.currentConstraints.video.deviceId===qt.DISPLAY_SOURCE_ID}getVideoDeviceId(){return this.currentConstraints.video.deviceId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},f=getResolutionForStream(this.currentGumStream),S=f??g,v=`Stream resolution is ${S.width}x${S.height}.`;return f?this.logger.safe.info(v):this.logger.safe.error(`${v}. Resolution not found, assuming default resolution.'`),S}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g=getFrameRateForStream(this.currentGumStream);return 0===g?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${g}`),g}async startStream(g){let f;f=g.video?this.applyConstraintsInternal():this.updateGumStreamInternal(g);try{await f,this.event("onStreamStarted").raise(this,g)}catch(g){throw this.event("onStreamError").raise(this,g),g}}getMediaType(g){if(g.sharing)return"ScreenShare";if(g.video)return"Video";if(g.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(g)}`)}updateClients(g){const f=this.constraintsProvider.getKey(g);this.clients.forEach(((g,S)=>{this.clientGumStreams[S][f]||(this.clientGumStreams[S][f]=this.getClone()),g.update(this.clientGumStreams[S][f])}))}applyConstraints(g){const f=this.getGumStreamProvider();return Promise.all(this.clients.map((S=>f.applyConstraints(S.rawStream,g)))).then((()=>{}))}applyConstraintsInternal(){return new Promise(((g,f)=>{this.logger.safe.info(`applying stream constraints: ${JSON.stringify(scrubConstraints(this.currentConstraints))}`);const S=new dt;this.clients.forEach((g=>{g.onApplyConstraints&&g.onApplyConstraints(S.promise)}));const v=this.serialQueue.add((()=>{const g=(new DC).getPolicies(this.currentConstraints);return this.mediaStreamStartPromise=this.updateGumStreamInternal(g[0]),g.slice(1).forEach((g=>{this.mediaStreamStartPromise=this.mediaStreamStartPromise.catch((f=>{if(qt.MEDIA_ERROR.constraintNotSatisfiedError===f.type)return this.logger.safe.warn("could not obtain constrained media stream, will attempt weaker policy"),this.updateGumStreamInternal(g);throw f.constraints=g,f}))})),this.mediaStreamStartPromise})).then((()=>{S.resolve()})).catch((g=>{throw this.logger.safe.error(`failed to apply constraints: ${JSON.stringify(scrubConstraints(g.constraints))} error: ${stringifyObject(g)}`),S.reject(g),g}));g(v)}))}enableDisableTracks(){this.currentGumStream&&this.currentGumStream.getTracks().forEach((g=>{void 0!==g.enabled&&(g.enabled=!("audio"===g.kind&&this.isMuted||this.isHold),this.logger.safe.info(`control media stream track kind: ${g.kind} enabled: ${g.enabled} muted: ${g.muted}`))}))}getGumStreamProvider(){return RC.getStreamProvider(this.mediaType,this.configProvider,this.logger.createChild("MSProvider"))}async updateGumStreamInternal(g){this.logger.safe.info(`querying user media for stream: ${JSON.stringify(g)}`),this.logger.safe.info("Getting GUM stream");const f=await this.getGumStream(g);this.logger.safe.info("Updating gum stream audio tracks"),this.updateGumStreamAudioTracks(f),this.currentGumStream=f,this.logger.safe.info("Updating stream constraints"),this.updateConstraints(g,f),this.logger.safe.info("Caching GUM stream"),this.cacheGumStream(this.currentConstraints,f),this.updateClients(this.currentConstraints),this.updateGumStreamVideoTracks(f),this.enableDisableTracks(),this.logger.safe.info("media stream updated");const S=this.stopRequestCalculation();this.event("onStreamAcquired").raise(this,S,(this.hasVideo()||this.hasDisplay())&&this.getResolution()||void 0)}async getGumStream(g){const f=this.gumStreams[this.constraintsProvider.getKey(g)];if(f)return f;const S=this.getGumStreamProvider();return this.startRequestCalculation(),S.getStream(g)}updateGumStreamAudioTracks(g){g.getAudioTracks().forEach((g=>{g.onended=g=>{this.logger.safe.info(`Audio stream track ended: ${JSON.stringify(g.error?.name||g)}`),this.event("onStreamTrackEnded").raise(this,g)},g.onmute=()=>{this.logger.safe.info("Audio stream track muted"),this.event("onStreamTrackMuted").raise(this,!0)},g.onunmute=()=>{this.logger.safe.info("Audio stream track unmuted"),this.event("onStreamTrackMuted").raise(this,!1)},g.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(g.id)}`)}))}updateGumStreamVideoTracks(g){const[f]=g.getVideoTracks();f&&(f.onmute=g=>{this.logger.safe.error(`Video stream track muted: ${JSON.stringify(scrubConstraints(this.currentConstraints))}; ${JSON.stringify(g)}`)},f.onended=g=>{this.logger.safe.info(`Video stream track ended: ${JSON.stringify(scrubConstraints(this.currentConstraints))}; ${JSON.stringify(g?.error.name||g)}`),this.event("onStreamTrackEnded").raise(this,g)},this.hasDisplay()&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(f,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(f.id)}`))}cacheGumStream(g,f){const S=this.constraintsProvider.getKey(g);this.gumStreams[S]!==f&&(this.gumStreams[S]&&(this.logger.safe.info(`Stream cache hit for ${S}, stopping old stream`),this.stopOneGumStream(this.gumStreams[S])),this.gumStreams[S]=f)}updateConstraints(g,f){this.currentConstraints=g.video?this.constraintsProvider.updateResolution(g,this.getResolution()):g,this.logger.safe.info(`Stream constraints updated: ${JSON.stringify(this.currentConstraints)}`)}applyContentHint(g,f){["","text","detail","motion"].indexOf(f)<0?this.logger.safe.error(`Cannot apply content hint: ${f}`):(this.logger.safe.info(`Apply content hint: ${f}`),g.contentHint=f)}startRequestCalculation(){this.gumStartTime=Date.now()}stopRequestCalculation(){if(0===this.gumStartTime)return 0;const g=Date.now()-this.gumStartTime;return this.gumStartTime=0,g}stopGumStream(){return this.mediaStreamStartPromise?(this.logger.safe.info("queueing media stream stop"),this.serialQueue.add((()=>{this.stopGumStreamInternal()}))):Promise.resolve()}stopOneGumStream(g){try{g.getTracks().forEach((g=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(g.id)}`),g.onended=null,g.onmute=null,g.stop()})),this.logger.safe.info("media stream stopped")}catch(g){this.logger.safe.warn(`failed to stop media stream: ${stringifyObject(g)}`)}}stopGumStreamInternal(){this.currentGumStream&&([...this.clientGumStreams,...this.streamsDump,this.gumStreams].forEach((g=>{forOwn(g,(g=>{this.stopOneGumStream(g)}))})),this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.currentGumStream=null)}};ny.streamGeneration=0;var ry=ny,sy=class _MediaStreamManager extends Ht{constructor(g,f,S){super(g),this.logger=g,this.configProvider=f,this.effectsManager=S,this.cachedStreamsSubs=new Map,this.cachedStreamsMap=new Map,this.mediaStreamSerialQueue=new zC(this.logger),this.couldUseWebrtc_1_0=!1}getMediaStream(g,f){this.logger.safe.info(`retrieving media stream: ${JSON.stringify(scrubConstraints(g))}`),this.cachedStreamsMap.size||(this.couldUseWebrtc_1_0=canUseWebrtc1_0(this.configProvider.config.checkSupportForWebrtc_1_0));let S=this.getSuitableStream(g);S||(this.logger.safe.info(`cached stream is not found. Creating a new one with constraints: ${stringifyObject(scrubConstraints(g))}`),S=this.createCachedStream(g)),this.logger.safe.info(`starting cached stream id=${S.id}`,f);const v=S.getClient(f);return v.start().catch((g=>{this.logger.safe.error(`could not start media stream: ${S.id}, total streams: ${this.cachedStreamsMap.size}, error: ${stringifyObject(g)}`),this.removeStream(S)})),v}dispose(){this.cachedStreamsSubs&&(this.cachedStreamsSubs.forEach((g=>{g.forEach((g=>{g.dispose()}))})),this.cachedStreamsSubs=null),this.cachedStreamsMap&&(this.cachedStreamsMap.forEach((g=>g.dispose("MSM dispose"))),this.cachedStreamsMap=null),this.mediaStreamSerialQueue&&(this.mediaStreamSerialQueue.dispose(),this.mediaStreamSerialQueue=null),super.dispose()}getCachedStreams(){return this.cachedStreamsMap}getActiveConstraints(){const g={audio:!1,video:!1,sharing:!1};return this.cachedStreamsMap.forEach(((f,S)=>{S.audio&&(g.audio=!0),S.video&&(g.video=!0),S.sharing&&(g.sharing=!0)})),g}onDevicesChanged(g){this.configProvider.config.enablePermissionsWorkaround&&_MediaStreamManager.isDeviceListEmpty(g)?this.logger.safe.info("Device list is empty, permission workaround enabled"):this.cachedStreamsMap.forEach(((f,S)=>{if(!S.sharing){const f=this.isDeviceOutdated(S.audio,g),v=this.isDeviceOutdated(S.video,g);(f||v)&&this.cachedStreamsMap.delete(S)}}))}getSuitableStream(g){let f;return this.cachedStreamsMap.forEach(((S,v)=>{this.isSuitable(this.addDeviceIdIfNecessary(S,v),g)&&(f=v)})),f&&this.cachedStreamsMap.get(f)}addDeviceIdIfNecessary(g,f){if(!g.deviceId)return f;const S=this.cloneStreamConstraints(f);return f.audio&&void 0===f.audio.deviceId&&(S.audio.deviceId=g.deviceId),f.video&&void 0===f.video.deviceId&&(S.video.deviceId=g.deviceId),f.sharing&&(S.sharing.deviceId=qt.DISPLAY_SOURCE_ID),S}cloneStreamConstraints(g){return{...deepClone(g),withOverridenStream:g.withOverridenStream}}createCachedStream(g){const f=this.createStream(g);return this.event("onStreamCreated").raise(f.id,f.mediaType),this.subscribeOnStreamEvents(f),this.logger.safe.info(`created media stream, id: ${f.id} total: ${this.cachedStreamsMap.size}`),this.cachedStreamsMap.set(g,f),f}disposeCurrentDeviceStream(g){for(const[f,S]of this.cachedStreamsMap.entries())g.sharing||f.sharing||(_MediaStreamManager.deviceChanged(g.audio,f.audio)||_MediaStreamManager.deviceChanged(g.video,f.video))&&S.dispose("MSM dispose oneStreamPerDeviceType")}createStream(g){return this.configProvider.config.oneStreamPerDeviceType&&this.couldUseWebrtc_1_0&&this.disposeCurrentDeviceStream(g),this.configProvider.config.webrtcSimulcastSessionEnabled&&oa.hasApplyConstraints()&&this.couldUseWebrtc_1_0?new VC(g,this.mediaStreamSerialQueue,this.configProvider,this.logger,this.effectsManager):new ry(g,this.mediaStreamSerialQueue,this.logger,this.configProvider)}subscribeOnStreamEvents(g){const f=[];f.push(g.on("onStreamAcquired",((g,f,S)=>this.onStreamAcquired(g,f,S)))),f.push(g.on("onStreamDisposing",(g=>this.onStreamDisposing(g)))),this.cachedStreamsSubs.set(g,f)}unsubscribeFromStreamEvents(g){this.cachedStreamsSubs.get(g).forEach((g=>g.dispose())),this.cachedStreamsSubs.delete(g)}removeStream(g){this.logger.safe.info(`release media stream generation: ${g.id} cached: ${this.cachedStreamsMap.size}`),this.cachedStreamsSubs.has(g)?(this.unsubscribeFromStreamEvents(g),this.cachedStreamsMap.delete(this.getConstraintsForStream(g)),this.getStreamsCountByType("Audio")||this.effectsManager.stopEffect("Audio"),this.cachedStreamsMap.size||this.event("onAllStreamsRemoved").raise()):this.logger.safe.warn(`skipping unknown stream ${g.id}`)}getConstraintsForStream(g){let f;return this.cachedStreamsMap.forEach(((S,v)=>{g===S&&(f=v)})),f}isSuitable(g,f){const S=!(!g.withOverridenStream||!f.withOverridenStream),v=S||f.sharing||this.isAcceptable(g.audio,f.audio)&&g.audioProcessingFlags===f.audioProcessingFlags,C=S||this.isAcceptable(g.video,f.video),_=this.configProvider.config.requireUserActionForAudioSharing&&f.sharing&&!!g.audio!=!!f.audio,T=this.isAcceptable(g.sharing,f.sharing),I=T&&this.isAcceptable(g.audio,f.audio),b=_?I:T,A=g.withEffect===f.withEffect,P=g.withOverridenStream?.id===f.withOverridenStream?.id;return!f.force&&v&&C&&b&&A&&P}isAcceptable(g,f){return!g&&!f||g&&f&&g.deviceId===f.deviceId}isDeviceOutdated(g,f){return g?.deviceId&&!f.some((f=>f.deviceId===g.deviceId))}onStreamDisposing(g){this.logger.safe.info(`onStreamDisposing event ${g.id}`),this.event("onStreamDisposing").raise(g.id,g.mediaType),this.removeStream(g)}onStreamAcquired(g,f,S){const v="Audio"===g.mediaType?void 0:!!g.rawStream.getAudioTracks()[0],C="ScreenShare"===g.mediaType?this.getSharingSource(g):void 0,_="Audio"===g.mediaType||v?g.rawStream?.getAudioTracks?.()[0]?.getSettings?.()?.sampleRate:void 0;this.event("onStreamAcquired").raise({id:g.id,mediaType:g.mediaType,timestamp:f,resolution:S,withAudio:v,source:C,sampleRate:_})}getSharingSource(g){const f=g.rawStream.getVideoTracks()[0],S=f.getConstraints();if(S?.deviceId)return"camera";const v=f.getSettings();return v?.displaySurface??"unknown"}static deviceChanged(g,f){return!(!g||!f)&&g.deviceId!==f.deviceId}static isDeviceListEmpty(g){return g.every((g=>""===g.label))}getStreamsCountByType(g){let f=0;return this.cachedStreamsMap.forEach((S=>{f+=S.mediaType===g?1:0})),f}},ay=class{constructor(g){this.configProvider=g,this.data={deviceList:[],deviceSelectionChangeCount:0,deviceSelectionChangeCountFromInterface:0,permissionStates:{microphone:"unknown",camera:"unknown"},devicesCount:{microphone:0,camera:0,speaker:0,compositeAudio:0,audioIngestDevice:0,virtualDevice:0},devicesChangeCount:0,devicesPollChangeCount:0,deviceTelemetryEvents:[],videoEffectsEvents:[],audioEffectsEvents:[],workerEvents:[],audioSourceNumOfReopenRequests:0,audioSourceNumOfSuccessfulReopens:0,audioRenderDeviceErrorFlags:[],audioCaptureDeviceErrorFlags:[]},Object.defineProperty(this.data,"rawUsedDevices",{get:()=>this.rawUsedDevices,configurable:!1,enumerable:!1})}set permissionStates(g){this.data.permissionStates=g}setSelectedDevices(g,f){const S={microphone:scrubDeviceLabelPii(g.microphone?.label,this.configProvider.config.devices.piiSafeWords),camera:scrubDeviceLabelPii(g.camera?.label,this.configProvider.config.devices.piiSafeWords),speaker:scrubDeviceLabelPii(g.speaker?.label,this.configProvider.config.devices.piiSafeWords)};this.rawUsedDevices={microphone:g.microphone?.label,camera:g.camera?.label,speaker:g.speaker?.label},this.data.usedDevices&&(this.data.deviceSelectionChangeCount++,f&&this.data.deviceSelectionChangeCountFromInterface++),this.data.usedDevices=S}setDeviceList(g,f,S){this.data.deviceList=g.map((g=>({label:scrubDeviceLabelPii(g.label,this.configProvider.config.devices.piiSafeWords),kind:g.type}))),S&&(this.data.deviceDebugStrings=deepClone(S)),this.data.devicesCount.microphone=g.filter((g=>"microphone"===g.type)).length,this.data.devicesCount.camera=g.filter((g=>"camera"===g.type)).length,this.data.devicesCount.speaker=g.filter((g=>"speaker"===g.type)).length,this.data.devicesCount.compositeAudio=g.filter((g=>"compositeAudio"===g.type)).length,this.data.devicesChangeCount++,f&&this.data.devicesPollChangeCount++}registerDeviceTelemetryEvent(g){if("stream_acquired"===g.eventType){const f=g.payload;"Video"===f.mediaType&&(this.data.latestCameraOpenResolution=f.resolution)}"Audio"===g.payload.mediaType&&("stream_acquired"===g.eventType&&(this.data.audioSourceNumOfReopenRequests++,this.data.audioSourceNumOfSuccessfulReopens++),"stream_error"===g.eventType&&this.data.audioSourceNumOfReopenRequests++),arrayLimitedPush(this.data.deviceTelemetryEvents,g,this.configProvider.config.diagnostics.collectionLimits.numDeviceEvents)}logAudioDeviceError(g,f){switch(g){case"reconnect_on_audio_playback_error":{const g=this.getAudioPlaybackErrorCode(f.error);this.registerAudioRenderError(g);break}case"enumeration_failed":this.registerAudioRenderError(1),this.registerAudioCaptureError(1);break;case"permissions_state_changed":"denied"===f.microphone&&this.registerAudioCaptureError(0x800000000000);break;case"stream_ended_error":this.registerAudioCaptureError(4194304)}}getAudioPlaybackErrorCode(g){switch(g){case 3:return 4194304;case 4:return 128;default:return 0x8000000000000000}}registerVideoEffectsEvent(g){arrayLimitedPush(this.data.videoEffectsEvents,g,this.configProvider.config.diagnostics.collectionLimits.numVideoEffectsEvents)}registerAudioEffectsEvent(g){arrayLimitedPush(this.data.audioEffectsEvents,g,this.configProvider.config.diagnostics.collectionLimits.numAudioEffectsEvents)}registerWorkerEvent(g){arrayLimitedPush(this.data.workerEvents,g,this.configProvider.config.diagnostics.collectionLimits.numWorkerEvents)}registerAudioCaptureError(g){const f={timestamp:Date.now(),audioDeviceErrorFlag:g};arrayLimitedPush(this.data.audioCaptureDeviceErrorFlags,f,this.configProvider.config.diagnostics.collectionLimits.numAudioCaptureErrors)}registerAudioRenderError(g){const f={timestamp:Date.now(),audioDeviceErrorFlag:g};arrayLimitedPush(this.data.audioRenderDeviceErrorFlags,f,this.configProvider.config.diagnostics.collectionLimits.numAudioRenderErrors)}getObjectRef(){return this.data}},oy=class{constructor(g,f,S,v,C){this.deviceId=g,this.label=f,this.kind=S,this.groupId=v,this.capabilities=C,this.type=this.getType(this.kind),this.guid=`${this.type}:${this.deviceId}`,this.isSystemDefault=this.deviceId===qt.MEDIA_DEVICE.defaultId}toDeviceDesc(){return{id:this.guid,browserId:this.deviceId,label:this.label,kind:this.type}}getType(g){switch(g){case qt.MEDIA_DEVICE_KIND.audioInput:return qt.MEDIA_DEVICE.microphone;case qt.MEDIA_DEVICE_KIND.audioOutput:return qt.MEDIA_DEVICE.speaker;case qt.MEDIA_DEVICE_KIND.videoInput:return qt.MEDIA_DEVICE.camera;case qt.MEDIA_DEVICE_KIND.compositeAudio:return qt.MEDIA_DEVICE.compositeAudio;case qt.MEDIA_DEVICE_KIND.virtualDevice:return qt.MEDIA_DEVICE.virtualDevice;default:throw new Error(`Device kind to recognized: ${g}`)}}},ly=class extends oy{constructor(g,f,S,v){super(g,f,S,v)}},cy=class extends oy{constructor(g,f,S,v,C){super(g,f,S,v,C)}toDeviceDesc(){const g=super.toDeviceDesc();return g.isSystemDefault=this.isSystemDefault,g}},dy=class extends oy{constructor(g,f,S,v,C){if(super(g,f,S,v,C),this.position="unknown",C&&C.facingMode&&1===C.facingMode.length)switch(C.facingMode[0]){case"user":this.position="front";break;case"environment":this.position="back"}}toDeviceDesc(){const g=super.toDeviceDesc();return g.position=this.position,g}},hy=class extends oy{constructor(g,f,S,v,C,_){super(null,S,v,""),this.micDevice=g,this.speakerDevice=f,this.formFactor=C,this.isPcInternalDevice=_,this.guid=null,this.isSystemDefault=!1}get micDeviceId(){return this.micDevice.guid}get speakerDeviceId(){return this.speakerDevice.guid}toDeviceDesc(){const g=super.toDeviceDesc();return g.microphoneId=this.micDeviceId,g.speakerId=this.speakerDeviceId,g.formFactor=this.formFactor,g.isPcInternalDevice=this.isPcInternalDevice,g}};function createDevice(g){const f=g.getCapabilities&&g.getCapabilities();switch(f&&(delete f.groupId,delete f.deviceId),g.kind){case qt.MEDIA_DEVICE_KIND.audioInput:case qt.MEDIA_DEVICE_KIND.audioOutput:return new cy(g.deviceId,g.label,g.kind,g.groupId,f);case qt.MEDIA_DEVICE_KIND.videoInput:return new dy(g.deviceId,g.label,g.kind,g.groupId,f);default:throw new Error(`Device kind is not recognized: ${g.kind}`)}}function createCompositeAudioDevice(g,f,S){return new hy(g,f,S,"compositeAudio",0,!1)}function createDefaultDevice(g){const f={deviceId:qt.MEDIA_DEVICE.defaultId,label:qt.MEDIA_DEVICE.defaultDeviceLabel,kind:getKind(g),groupId:"",toJSON:()=>JSON.stringify(f)};return createDevice(f)}function getKind(g){switch(g){case qt.MEDIA_DEVICE.microphone:return qt.MEDIA_DEVICE_KIND.audioInput;case qt.MEDIA_DEVICE.speaker:return qt.MEDIA_DEVICE_KIND.audioOutput;case qt.MEDIA_DEVICE.camera:return qt.MEDIA_DEVICE_KIND.videoInput;default:throw new Error(`Device type to recognized: ${g}`)}}function compilePrimitiveDeviceList(g,f,S,v,C={str:""}){C.str+=`|input(${f.length})`;let _=[];const T=[v.config.devices.blacklist[g],v.defaultConfig.devices.blacklist[g]];for(const g of T)try{const S=new RegExp(g,"i");_=f.filter((f=>g&&f.label.match(S)?(C.str+=`|-blacklisted(${f.label})`,!1):f.deviceId!==qt.MEDIA_DEVICE.communicationsId||(C.str+="|-communications",!1)));break}catch(S){C.str+=`|filterError('${g}', ${stringifyObject(S)})`,_=f}if(_.length){const f=deductDefaultDevice(S,_,C);if(f&&(f.isSystemDefault=!0,C.str+=`|default(${scrubMriOrOmit(f.guid)})`),f&&f.deviceId!==qt.MEDIA_DEVICE.defaultId&&_.length>1&&(_=_.filter((g=>g.deviceId!==qt.MEDIA_DEVICE.defaultId||(C.str+="|-defaultId",!1)))),g===qt.MEDIA_DEVICE.camera||f||(C.str+="|+syntheticDefault",_.unshift(createDefaultDevice(g))),S.forEach((g=>{const f=_.find((f=>f.guid===g.guid));f&&!f.label&&g.label&&(C.str+=`|migrateLabel(${scrubMriOrOmit(f.guid)})`,f.label=g.label)})),g===qt.MEDIA_DEVICE.speaker){const g=_.filter((g=>""===g.label));g.length>1&&g.length===_.length&&(_=f?[f]:[_[0]],C.str+=`|-filteredEmptyLabels(${g.length})`)}}return _}function deductDefaultDevice(g,f,S){if(1===f.length)return S.str+="|default:only",f[0];const v=f.find((g=>g.isSystemDefault&&g.deviceId===qt.MEDIA_DEVICE.defaultId));if(!v)return S.str+="|default:noSynthetic",f.find((g=>g.isSystemDefault))||f[0];{const C=f.filter((g=>g!==v));if(1===C.length)return S.str+="|default:firstNonDefault",C[0];if(""!==v.groupId){const g=C.filter((g=>g.groupId===v.groupId));if(1===g.length)return S.str+=`|default:groupId(${scrubMriOrOmit(g[0].guid)})`,g[0]}const _=C.map((g=>g.label)),T=getMaxSubstring(v.label,_),I=C.find((g=>g.label===T));if(I)return S.str+=`|default:label(${scrubMriOrOmit(I.guid)})`,I;const b=g.find((g=>g.isSystemDefault));if(b){const g=C.find((g=>g.deviceId===b.deviceId));if(g)return S.str+=`|default:previousList(${scrubMriOrOmit(g.guid)})`,g}}return S.str+="|default:anyOrNull",f.find((g=>g.isSystemDefault))||null}function compileAudioDeviceList(g,f,S=.5,v={str:""}){const C=[];if(g.length&&f.length){const _=getGroupedPairs(g.filter((g=>""!==g.groupId)),f.filter((g=>""!==g.groupId)),v);_.length&&(C.push(..._.map((g=>createCompositeAudioDevice(g.microphone,g.speaker,createCompositeDeviceLabel(g.microphone.label,g.speaker.label))))),v.str+=`|directMatched(${C.length})`);const T=C.length;C.push(...composeAudioDevicesFromLabels(g.filter((g=>!C.some((f=>f.micDeviceId===g.guid)))),f.filter((g=>!C.some((f=>f.speakerDeviceId===g.guid)))),S,v)),v.str+=`|otherMatched(${C.length-T})`}return C}function getGroupedPairs(g,f,S={str:""}){const v=new Set;for(const S of[...g,...f])v.add(S.groupId);const C=[];for(const _ of v.values()){let v=g.filter((g=>g.groupId===_)),T=f.filter((g=>g.groupId===_));if(v&&T)if(1===v.length&&1===T.length)C.push({microphone:v[0],speaker:T[0]}),S.str+=`|pairSimple(${scrubMriOrOmit(v[0].guid)}, ${scrubMriOrOmit(T[0].guid)})`;else if(v.length>1||T.length>1){let g=getMostSimilarPair(v,T);for(;g;)S.str+=`|pairComplex(${scrubMriOrOmit(g.microphone.guid)}, ${scrubMriOrOmit(g.speaker.guid)})`,C.push(g),v=v.filter((f=>f!==g.microphone)),T=T.filter((f=>f!==g.speaker)),g=getMostSimilarPair(v,T)}}return C}function getMostSimilarPair(g,f){let S=999,v=null;if(g.length>0&&f.length>0)for(const C of g)for(const g of f){const f=levenshteinDistance(C.label,g.label);f<S&&(S=f,v={microphone:C,speaker:g})}return v}function composeAudioDevicesFromLabels(g,f,S,v){const C=[];return g.length&&f.length?(g.forEach((g=>{const _=f.filter((f=>f.groupId===g.groupId));if(!_.length)return void(v.str+=`|lbl_nocand(${scrubMriOrOmit(g.guid)})`);let T=getLongestCommonContiguousSubstring(g.label,_[0].label).length;const I=_.sort(((f,S)=>{const v=getLongestCommonContiguousSubstring(g.label,f.label),C=getLongestCommonContiguousSubstring(g.label,S.label);return v.length>T&&(T=v.length),C.length>T&&(T=C.length),C.length-v.length}));if(I.length){const f=T/g.label.length;f>S&&(C.push(createCompositeAudioDevice(g,I[0],createCompositeDeviceLabel(g.label,I[0].label))),v.str+=`|lbl_matched(${scrubMriOrOmit(g.guid)} & ${scrubMriOrOmit(I[0].guid)}, ${Math.round(1e4*f)/100}%)`)}})),C):C}function createCompositeDeviceLabel(g,f){if(g===f)return g;let S=getLongestCommonContiguousSubstring(g,f);S=S.trim().replace(/^\((.+)\)$/,"$1");let v="",C="",_=0;const T=[countBraces(g),countBraces(f)];if(0===T[0]||0===T[1])return S;for(let g=0;g<S.length;g++)if("("===S[g])_++,C+=S[g];else if(")"===S[g]){if(!(_>0))break;_--,C+=S[g],v+=C,C=""}else _>0?C+=S[g]:v+=S[g];const I=countBraces(v);return I!==T[0]&&I!==T[1]||(v=v.replace(/\w+\s?\((.+)\)/,"$1"),v=createCompositeDeviceLabel(S,v)),v.trim()}function countBraces(g){const f=["(",")"];let S=0;for(let v=0;v<g.length;v++)f.some((f=>g[v]===f))&&S++;return S}var uy={microphone:"",camera:"",speaker:"",compositeAudio:"",audioIngestDevice:"",virtualDevice:""},gy=class extends Ht{constructor(g,f){super(f),this.configProvider=g,this.logger=f,this.debugInfo=uy,this.lists=new Map,this.lists.set(qt.MEDIA_DEVICE.microphone,[]),this.lists.set(qt.MEDIA_DEVICE.camera,[]),this.configProvider.userAgentConfig.isAudioOutputSelectionSupported&&(this.lists.set(qt.MEDIA_DEVICE.speaker,[]),this.lists.set(qt.MEDIA_DEVICE.compositeAudio,[])),g.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>this.onConfigUpdated())),this.logger.safe.info("Initialized")}get devices(){const g=[];return this.lists.forEach((f=>g.push(...f))),g}getDevicesByType(g){return this.lists.get(g)??[]}updateDevices(g,f=!1){if(deepEqual(this.latestRawList,g))return;this.latestRawList=g;const S=this.devices;this.debugInfo.microphone="microphone",this.debugInfo.camera="camera",this.debugInfo.speaker="speaker",this.debugInfo.compositeAudio="compositeAudio",this.updatePrimitiveDeviceList(qt.MEDIA_DEVICE.microphone,g.filter((g=>g.type===qt.MEDIA_DEVICE.microphone))),this.updatePrimitiveDeviceList(qt.MEDIA_DEVICE.camera,g.filter((g=>g.type===qt.MEDIA_DEVICE.camera))),this.lists.get(qt.MEDIA_DEVICE.speaker)&&(this.updatePrimitiveDeviceList(qt.MEDIA_DEVICE.speaker,g.filter((g=>g.type===qt.MEDIA_DEVICE.speaker))),this.lists.get(qt.MEDIA_DEVICE.compositeAudio)&&this.updateCompositeAudioDeviceList(this.lists.get(qt.MEDIA_DEVICE.microphone),this.lists.get(qt.MEDIA_DEVICE.speaker)));const v=this.lists.get(qt.MEDIA_DEVICE.compositeAudio)||[];this.lists.set(qt.MEDIA_DEVICE.microphone,this.orderDeviceList(this.lists.get(qt.MEDIA_DEVICE.microphone),v)),this.lists.get(qt.MEDIA_DEVICE.speaker)&&this.lists.set(qt.MEDIA_DEVICE.speaker,this.orderDeviceList(this.lists.get(qt.MEDIA_DEVICE.speaker),v));const C=this.lists.get(qt.MEDIA_DEVICE.microphone);this.setTopItemToDefault(C);const _=this.lists.get(qt.MEDIA_DEVICE.speaker);this.setTopItemToDefault(_),deepEqual(S,this.devices)||(this.logger.safe.info("Device lists updated and changed"),this.logger.safe.info(this.debugInfo.microphone),this.logger.safe.info(this.debugInfo.camera),this.logger.safe.info(this.debugInfo.speaker),this.logger.safe.info(this.debugInfo.compositeAudio),this.event("onDevicesChanged").raise(this.devices,f))}updateVirtualDeviceList(g){const f=this.lists.get(qt.MEDIA_DEVICE.virtualDevice),S=g.map((g=>new ly(g.id,g.label,"virtualDevice","")));deepEqual(f,S)?this.logger.safe.info("Device lists did not change."):(this.lists.set(qt.MEDIA_DEVICE.virtualDevice,S),this.event("onDevicesChanged").raise(this.devices,!1))}updateActiveMicrophone(g){if(!g||g.deviceId===qt.MEDIA_DEVICE.defaultId)return;const f=this.lists.get(qt.MEDIA_DEVICE.microphone),S=f.findIndex((g=>g.isSystemDefault));-1!==S&&f[S]!==g?(this.logger.safe.info("Removing synthetic default microphone"),g.isSystemDefault=!0,f.splice(S,1),this.lists.set(qt.MEDIA_DEVICE.microphone,f),this.event("onDevicesChanged").raise(this.devices,!1)):g.isSystemDefault=!0}updatePrimitiveDeviceList(g,f){const S={str:this.debugInfo[g]};this.lists.set(g,compilePrimitiveDeviceList(g,f,this.lists.get(g)||[],this.configProvider,S)),this.debugInfo[g]=S.str}updateCompositeAudioDeviceList(g,f){const S={str:this.debugInfo.compositeAudio};this.lists.set(qt.MEDIA_DEVICE.compositeAudio,compileAudioDeviceList(g,f,this.configProvider.config.devices.compositeLabelMatchingThreshold,S)),this.debugInfo.compositeAudio=S.str}orderDeviceList(g,f){return g.sort(((g,S)=>this.getDevicePriority(S,this.getCompositeAudioDeviceCounterpart(S,f))-this.getDevicePriority(g,this.getCompositeAudioDeviceCounterpart(g,f))))}getCompositeAudioDeviceCounterpart(g,f){const S=f.find((f=>f.micDeviceId===g.guid||f.speakerDeviceId===g.guid));return S?S[g.type===qt.MEDIA_DEVICE.speaker?"micDevice":"speakerDevice"]:null}getDevicePriority(g,f){let S=0;return this.configProvider.config.devices.overrideDefault&&f&&(!g.isSystemDefault&&f.isSystemDefault?(this.debugInfo[g.type]+=`|overrideDefault(${scrubMriOrOmit(g.guid)})`,S+=10):g.isSystemDefault&&!f.isSystemDefault&&"microphone"===g.type&&(S+=15)),g.isSystemDefault&&(S+=5),f&&(S+=1,f.isSystemDefault&&(S+=2)),S}setTopItemToDefault(g){g?.length&&(g.forEach((g=>g.isSystemDefault=!1)),g[0].isSystemDefault=!0)}onConfigUpdated(){let g=!1;this.configProvider.userAgentConfig.isAudioOutputSelectionSupported?this.lists.has(qt.MEDIA_DEVICE.speaker)||(this.lists.set(qt.MEDIA_DEVICE.speaker,[]),this.lists.set(qt.MEDIA_DEVICE.compositeAudio,[]),g=!0):(this.lists.has(qt.MEDIA_DEVICE.speaker)&&(this.lists.delete(qt.MEDIA_DEVICE.speaker),g=!0),this.lists.has(qt.MEDIA_DEVICE.compositeAudio)&&(this.lists.delete(qt.MEDIA_DEVICE.compositeAudio),g=!0)),g&&(this.logger.safe.info("Updating device list due to config update"),this.updateDevices(this.latestRawList||[]))}},py=class _DeviceEnumerator extends Ht{constructor(g,f){super(f),this.pollingInterval=0,_DeviceEnumerator.enumeratorUsers.add(this),_DeviceEnumerator.initialize(this,g,f)}startDevicePolling(g){this.pollingInterval=g?_DeviceEnumerator.configProvider.config.devices.pollingIntervalIdle:_DeviceEnumerator.configProvider.config.devices.pollingIntervalActive,_DeviceEnumerator.updatePollingTask()}stopDevicePolling(g){this.pollingInterval=g?0:_DeviceEnumerator.configProvider.config.devices.pollingIntervalIdle,_DeviceEnumerator.updatePollingTask()}dispose(){super.dispose(),this.stopDevicePolling(!0),_DeviceEnumerator.enumeratorUsers.delete(this),0===_DeviceEnumerator.enumeratorUsers.size&&(_DeviceEnumerator.logger.safe.info("disposing"),_DeviceEnumerator.initializeCalled=!1,_DeviceEnumerator.isDeviceListAvailable=new dt,_DeviceEnumerator.list=void 0,_DeviceEnumerator.window.navigator.mediaDevices.ondevicechange=void 0)}static get isPolling(){return 0!==_DeviceEnumerator.currentPollingInterval}static initialize(g,f,S){_DeviceEnumerator.initializeCalled||(_DeviceEnumerator.initializeCalled=!0,_DeviceEnumerator.window=Xs.window,_DeviceEnumerator.configProvider=f,_DeviceEnumerator.logger=S,_DeviceEnumerator.list=new gy(f,S.createChild("DeviceList")),f.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>_DeviceEnumerator.enumerateDevices())),f.on("configUpdated",(()=>{void 0!==f.config.devices.pollingIntervalIdle&&null!==_DeviceEnumerator.pollingTimer&&g.startDevicePolling(!0)})),f.config.devices.pollingIntervalIdle&&f.config.devices.idlePollingOnStart&&g.startDevicePolling(!0),_DeviceEnumerator.window.navigator.mediaDevices&&(_DeviceEnumerator.window.navigator.mediaDevices.ondevicechange=()=>{S.safe.info("enumerating due to ondevicechange callback"),_DeviceEnumerator.enumerateDevices().catch((g=>{S.safe.error(`unable to enumerate ondevicechange: ${stringifyObject(g)}`)}))}),_DeviceEnumerator.enumerateDevices())}static async enumerateDevices(g=!1){if(!_DeviceEnumerator.window.navigator?.mediaDevices?.enumerateDevices){const g=new Error("device enumeration unsupported");throw _DeviceEnumerator.isDeviceListAvailable.isPending&&_DeviceEnumerator.isDeviceListAvailable.reject(g),g}if(_DeviceEnumerator.enumerateDevicesPromise&&!g)return _DeviceEnumerator.logger.safe.info("enumeration request postponed"),_DeviceEnumerator.hasPendingUpdate=!0,void(_DeviceEnumerator.isDeviceListAvailable.isPending&&et.isEngine("Firefox")&&_DeviceEnumerator.isDeviceListAvailable.resolve());try{if(!_DeviceEnumerator.enumerateDevicesPromise)if(_DeviceEnumerator.configProvider.config.devices.enumerateDevicesTimeout){const g=deferWithTimeout(_DeviceEnumerator.configProvider.config.devices.enumerateDevicesTimeout);_DeviceEnumerator.enumerateDevicesPromise=g.promise,_DeviceEnumerator.window.navigator.mediaDevices.enumerateDevices().then(g.resolve,g.reject)}else _DeviceEnumerator.enumerateDevicesPromise=_DeviceEnumerator.window.navigator.mediaDevices.enumerateDevices();const f=await _DeviceEnumerator.enumerateDevicesPromise;_DeviceEnumerator.list.updateDevices(f.map((g=>createDevice(g))),g),_DeviceEnumerator.isDeviceListAvailable.isPending&&_DeviceEnumerator.isDeviceListAvailable.resolve()}catch(g){const f=stringifyObject(g);throw _DeviceEnumerator.logger.safe.warn(`error with enumerating devices: ${f}`),_DeviceEnumerator.raiseFailedEnumeration(f),_DeviceEnumerator.isDeviceListAvailable.isPending&&_DeviceEnumerator.isDeviceListAvailable.reject(g),g}finally{_DeviceEnumerator.enumerateDevicesPromise=void 0,_DeviceEnumerator.hasPendingUpdate&&(_DeviceEnumerator.hasPendingUpdate=!1,_DeviceEnumerator.logger.safe.info("running postponed enumeration"),_DeviceEnumerator.enumerateDevices())}}static updatePollingTask(){let g=Number.MAX_SAFE_INTEGER;for(const f of _DeviceEnumerator.enumeratorUsers.values())f.pollingInterval<g&&(g=f.pollingInterval);if(g===Number.MAX_SAFE_INTEGER&&(g=0),(_DeviceEnumerator.pollingTimer||_DeviceEnumerator.currentPollingInterval!==g)&&_DeviceEnumerator.pollingTimer&&(_DeviceEnumerator.window.clearTimeout(_DeviceEnumerator.pollingTimer),_DeviceEnumerator.pollingTimer=void 0),_DeviceEnumerator.currentPollingInterval=g,0===g)return;const pollingTask=async()=>{if(_DeviceEnumerator.currentPollingInterval)try{await _DeviceEnumerator.enumerateDevices(!0),_DeviceEnumerator.pollingTimer=_DeviceEnumerator.window.setTimeout(pollingTask,_DeviceEnumerator.currentPollingInterval)}catch(g){throw _DeviceEnumerator.pollingTimer=null,g}};_DeviceEnumerator.logger.safe.info(`starting device polling with interval ${g}ms`),_DeviceEnumerator.pollingTimer=1,pollingTask()}static raiseFailedEnumeration(g){for(const f of _DeviceEnumerator.enumeratorUsers.values())f.event("onDeviceEnumerationfailed").raise(g)}};py.isDeviceListAvailable=new dt,py.initializeCalled=!1,py.currentPollingInterval=0,py.hasPendingUpdate=!1,py.enumeratorUsers=new Set;var my=py,fy=class extends Ht{constructor(g,f,S){super(S),this.deviceList=g,this.configProvider=f,this.logger=S,this.userSelectedDevices={microphone:null,camera:null,speaker:null},this.currentlySelectedDevices={microphone:null,camera:null,speaker:null,audioIngestDevice:null},this.deviceList.on("onDevicesChanged",(g=>this.onDevicesChanged(g))),g.devices.length>0&&this.onDevicesChanged(g.devices),this.logger.safe.info("Initialized")}get selectedDevices(){return deepClone(this.currentlySelectedDevices)}selectDevices(g){let f=!1;if(forOwn(g,((g,S)=>{const v=this.getDeviceToSelect(S,this.deviceList.getDevicesByType("audioIngestDevice"===S?"microphone":S),g);"camera"===S&&(this.userSelectedDevices[S]=v?.guid||this.userSelectedDevices[S]),v?.guid!==this.currentlySelectedDevices[S]?.guid&&(this.userSelectedDevices[S]=v?.guid||this.userSelectedDevices[S],f=!0),this.currentlySelectedDevices[S]=v})),f){const g=values(this.currentlySelectedDevices).map((g=>JSON.stringify(scrubDevices(g,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed from public interface: ${g}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!0)}}getDeviceToSelect(g,f,S){let v;const C=this.userSelectedDevices[g];return S?v=f.find((g=>g.guid===S)):C&&(v=f.find((g=>g.guid===C))),"audioIngestDevice"===g?v:v||f[0]}onDevicesChanged(g){let f=!1;if(Object.keys(this.currentlySelectedDevices).forEach((S=>{const v="audioIngestDevice"===S?"microphone":S,C=g.filter((g=>g.type===v));if(C.length>0){const g=this.getDeviceToSelect(S,C);g?.guid!==this.currentlySelectedDevices[S]?.guid&&(this.currentlySelectedDevices[S]=g,f=!0)}else this.currentlySelectedDevices[S]&&(this.currentlySelectedDevices[S]=null,f=!0)})),f){const g=values(this.currentlySelectedDevices).map((g=>JSON.stringify(scrubDevices(g,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed due to device list change: ${g}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!1)}}},Sy=class extends Ht{constructor(g,f){super(g),this.logger=g,this.mediaStream=f,this.subs=[],this.subscribeOnMediaStreamEvents(f)}acquire(){return this.mediaStream?this.mediaStream.start().then((()=>this.logger.safe.info("Stream acquired"))).catch((g=>{throw this.logger.safe.warn(`Failed to acquire the stream: ${stringifyObject(g)}`),g})):Promise.reject("Disposed")}dispose(){this.logger.safe.info("Disposing stream"),this.unsubscribeFromMediaStreamEvents(),this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),super.dispose()}subscribeOnMediaStreamEvents(g){this.subs=[g.on("onStreamClientStarted",(()=>this.event("onStreamStateChanged").raise("active"))),g.on("onStreamClientMuted",((g,f)=>this.event("onStreamStateChanged").raise(f?"inactive":"active"))),g.on("onStreamClientEnded",(()=>this.event("onStreamStateChanged").raise("stopped"))),g.on("onStreamClientError",((g,f)=>{const S=f.type===qt.MEDIA_ERROR.permissionDeniedError||f.type===qt.MEDIA_ERROR.sharingCancelledError;this.event("onStreamStateChanged").raise(S?"cancelled":"failed")}))]}unsubscribeFromMediaStreamEvents(){this.subs.forEach((g=>g.dispose())),this.subs=[]}},vy=[qt.MEDIA_STATE.inactive,qt.MEDIA_STATE.receive,qt.MEDIA_STATE.send,qt.MEDIA_STATE.sendReceive],Cy=[qt.MEDIA_STATE.inactive,qt.MEDIA_STATE.receive],yy=class extends Ht{constructor(g,f,S){super(S),this.configProvider=g,this.deviceManager=f,this.logger=S,this.currentState={microphone:"unknown",camera:"unknown"},this.lastGum={audio:!1,video:!1},this.registeredTrackers=new Set,this.accessIssuePermissionOther={audio:!1,video:!1},this.window=Xs.window,this.permittedModalities={audio:vy,video:vy,sharing:vy},this.initialize()}async initialize(){!oa.hasPermissionsApi()||"unknown"!==this.currentState.microphone&&"unknown"!==this.currentState.camera?"unknown"!==this.currentState.microphone&&"unknown"!==this.currentState.camera||this.logger.safe.warn(`Permissions API is not supported in this browser. Microphone: ${this.currentState.microphone}, camera: ${this.currentState.camera}`):(this.logger.safe.info("Initializing"),await this.registerPermissionTracker("microphone"),await this.registerPermissionTracker("camera"))}getPermissionState(g){return this.currentState[g]||"unknown"}isPermissionKnown(g){const f=this.getPermissionState(g);return"unknown"!==f&&"prompt"!==f}get browserPermittedModalities(){return this.permittedModalities}get knownPermissionStates(){return deepClone(this.currentState)}update(g,f){const S=deepClone(f);g.audio||delete S.audio,g.video||delete S.video;const v=deepClone(this.permittedModalities);forOwn(S,((g,f)=>{this.permittedModalities[f]=g?vy:Cy})),deepEqual(v,this.permittedModalities)||this.event("onDevicesPermissionChanged").raise()}async askDevicePermission(g){const f=g?deepClone(g):{audio:!0,video:this.deviceManager.hasCamera()};if(this.accessIssuePermissionOther={audio:!1,video:!1},this.configProvider.config.permissions.rememberNegative&&(f.audio=f.audio&&this.permittedModalities.audio===vy,f.video=f.video&&this.permittedModalities.video===vy),f.sharing)throw new Error("askDevicePermission does not support sharing constraints.");const S={audio:!1,video:!1};this.lastGum={audio:!1,video:!1};const resolve=async(S,v,C)=>{const _={audio:!!S.audio,video:!!S.video,sharing:!0};return!(this.configProvider.config.permissions.adpRequestAVLast&&f.audio&&f.video)||this.lastGum.audio&&this.lastGum.video||(this.logger.safe.info("Prompting for audio and video to ensure omnibar state"),await this.askDevicePermissionPrompt({audio:!0,video:!0},!1)),this.update(f,_),this.deviceManager.raiseTelemetryEvent("ask_device_permission",{constraints:g,resultConstraints:S,error:C,reason:v}),_};await this.initialize();const v=this.getPermissionState("microphone"),C=this.getPermissionState("camera");if(this.logger.safe.info(`Permission state { audio: ${v}, video: ${C} }`),this.configProvider.config.permissions.useNegativeInAdp&&(!f.audio||"denied"===v)&&(!f.video||"denied"===C))return resolve(S,"navigator_permissions_denied");if(this.configProvider.config.permissions.usePositiveInAdp&&(!f.audio||f.audio&&"granted"===v)&&(!f.video||f.video&&"granted"===C))return resolve(f,"navigator_permissions_granted");try{return resolve(this.getConstrainsWithPermissionError(await this.askDevicePermissionPrompt(f,this.configProvider.config.permissions.adpFallback)),"stream_acquisition")}catch(g){return resolve(S,"stream_acquisition",g)}}async askDevicePermissionPrompt(g,f=!0){const S={audio:!1,video:!1};try{const f=this.deviceManager.getMediaStream(g);return f&&(this.lastGum=deepClone(g),await f.start(),S.audio=f.hasAudio(),S.video=f.hasVideo(),this.disposeLater(f)),S}catch(v){if(g.audio&&g.video&&f){try{S.video=this.configProvider.config.permissions.adpFallbackVideo&&(await this.askDevicePermissionPrompt({video:!0})).video}catch(g){g.type!==qt.MEDIA_ERROR.permissionDeniedError&&g.type!==qt.MEDIA_ERROR.permissionDeniedBySystemError&&(this.accessIssuePermissionOther.video=!0)}try{S.audio=this.configProvider.config.permissions.adpFallbackAudio&&(await this.askDevicePermissionPrompt({audio:!0})).audio}catch(g){g.type!==qt.MEDIA_ERROR.permissionDeniedError&&g.type!==qt.MEDIA_ERROR.permissionDeniedBySystemError&&(this.accessIssuePermissionOther.audio=!0)}}else if(f)throw v;return S}}getConstrainsWithPermissionError(g){return this.configProvider.config.permissions.disableOnPermissionDeniedOnly?{audio:this.accessIssuePermissionOther.audio||g.audio,video:this.accessIssuePermissionOther.video||g.video}:g}disposeLater(g){setTimeout((()=>{g.dispose()}),this.configProvider.config.mediaStreamHoldInterval)}async registerPermissionTracker(g){if(!this.registeredTrackers.has(g))try{const f=await this.window.navigator.permissions.query({name:g});this.handlePermissionStateChanged(g,f.state),f.onchange=()=>this.handlePermissionStateChanged(g,f.state),this.registeredTrackers.add(g)}catch(f){this.logger.safe.error(`Error querying permissions for ${g}: ${stringifyObject(f)}`)}}handlePermissionStateChanged(g,f){if(this.logger.safe.info(`Permission state for ${g} changed ${this.currentState[g]} -> ${f}`),this.configProvider.config.permissions.enumerateDevicesAfterChange){this.logger.safe.info(`enumerateDevicesAfterChange: ${JSON.stringify(this.configProvider.config.permissions)}`),my.logger.safe.info("enumerating due to permission change");try{my.enumerateDevices()}catch(g){my.logger.safe.error(`unable to enumerate on permission change: ${stringifyObject(g)}`)}}this.currentState[g]=f,this.deviceManager.raiseTelemetryEvent("permissions_state_changed",this.knownPermissionStates),this.deviceManager.handlePermissionStateChange()}},Ey=class extends Ke{constructor(g,f=uniqueId()){super(),this.dms=g,this.label=f,this.id=uniqueId(),this.receivedEvents=new Map,this.subscribeToDeviceManagers(g)}getDeviceManagers(){return this.dms}dispose(){super.dispose(),this.dms?.forEach((g=>g.dispose())),this.dms=null}subscribeToDeviceManagers(g){g.forEach(((g,f)=>{g.on("onVideoEffectsEvent",((...f)=>this.eventHandler("onVideoEffectsEvent",g,(()=>this.event("onVideoEffectsEvent").raise(...f))))),g.on("onVideoEffectApplied",((...f)=>this.eventHandler("onVideoEffectApplied",g,(()=>this.event("onVideoEffectApplied").raise(...f))))),g.on("onDeviceTelemetryEvent",(g=>this.event("onDeviceTelemetryEvent").raise({deviceId:`${this.id}/${f}`,...g}))),g.on("onVideoEffectsTelemetryEvent",(g=>this.event("onVideoEffectsTelemetryEvent").raise({deviceId:`${this.id}/${f}`,...g}))),g.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise(`${this.id}/${f}`))),g.on("onStreamUpdateRequested",((...g)=>this.event("onStreamUpdateRequested").raise(...g)))}))}eventHandler(g,f,S){let v=this.receivedEvents.get(g);v??(v=new Set),v.add(f);if(this.dms.every((g=>v.has(g))))return S(),void v.clear();this.receivedEvents.set(g,v)}},sequentialize=()=>(g,f,S)=>{const v=S.value;return S.value=function(...g){return this.serialQueue.add(v.bind(this,...g))},S},_y=class{constructor(g,f,S){this.configProvider=g,this.statistics=f,this.logger=S}isWasmEffectSupported(){return this.configProvider.config.webcv.useWasmEffects?!!window.MediaStreamTrackProcessor||(this.logger.info("wasmEffects disabled, insertable streams are not supported"),!1):(this.logger.info("wasmEffects disabled by feature flag"),!1)}isWebgl2EffectSupported(){return this.isCurrentRendererSupported()&&this.isWebGL2Supported()}isCurrentRendererSupported(){const g=this.configProvider.config.webcv.webGLUnsupportedRenderers;let f=!1;const S=oa.unmaskedGlRenderer;return S&&!g.some((g=>g===S))?f=!0:(this.statistics.setError("RendererIsNotSupported",`Blacklisted from ${JSON.stringify(g)}`),this.logger.info(`Unsupported renderer: ${stringifyObject(S)}`)),f}isWebGL2Supported(){try{const g=document.createElement("canvas").getContext("webgl2");if(!g)return this.statistics.setError("WebGL2IsNotSupported"),this.logger.info("WebGL2 context is not supported"),!1;const f=g.getSupportedExtensions(),S=this.configProvider.config.webcv.webGLRequiredExtensions.filter((g=>!f.includes(g)));if(S.length>0)return this.statistics.setError("WebGL2RequiredExtensionsNotSupported","Required WebGL2 extensions not supported."),this.logger.info(`Unsupported WebGL2 extensions: ${stringifyObject(S)}`),!1}catch(g){return this.statistics.setError("WebGL2IsNotSupported",`Error: ${stringifyObject(g)}`),this.logger.error(`isWebGL2Supported: ${stringifyObject(g)}`),!1}return!0}},Ty=class{constructor(g){this.error=new Vv(g)}startLoadTimer(){this.loadStartTimestamp=Date.now()}stopLoadTimer(){this.loadDuration=Date.now()-this.loadStartTimestamp}clearErrors(){this.error.clear()}setError(g,f){this.error.add({type:g,message:f})}getReport(){return{loadDuration:this.loadDuration,error:this.error.items}}},Iy=class extends Ht{constructor(g,f,S,v){super(S),this.webcvProvider=g,this.configProvider=f,this.logger=S,this.wasmLoader=v,this.serialQueue=new zC(this.logger),this.videoEffectToWebCVEffectMapping={0:lr.VideoEffectType.Off,1:lr.VideoEffectType.BackgroundBlur,16:lr.VideoEffectType.BackgroundReplacement,512:lr.VideoEffectType.PresenterMode,256:lr.VideoEffectType.None,2048:lr.VideoEffectType.None,262144:lr.VideoEffectType.None},this.currentEffect=0,this.effectProviderSubs=[],this.statistics=new Ty(this.configProvider.config.effectsTelemetryBufferSize),this.processorType=lr.ProcessorType.Webgl2,this.queryMessageProcessor=new by(this.configProvider,this.logger)}get isEffectEnabled(){return 0!==this.currentEffect||0!==this.queryMessageProcessor.payload.effectType}async init(){if(!this.effectProvider)try{this.effectProvider=await this.initializeVideoEffectProvider()}catch(g){throw Error(g)}}async dispose(){this.logger.safe.debug("Dispose"),this.effectProvider&&(this.effectProviderSubs.forEach((g=>g.dispose())),this.effectProviderSubs=null,await this.effectProvider.disposeAsync()),super.dispose()}async configure(g){if(this.logger.safe.debug(`Set config: ${JSON.stringify(g)}`),this.effectConfig={backgroundImageUrl:g.imagePath,headers:g.headers},this.effectProvider)return this.effectProvider.configureEffect(this.effectConfig);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async setEffectAsync(g){if(this.currentEffect===g)return void this.logger.safe.debug(`Effect ${this.currentEffect} is already set`);this.effectProvider||(this.logger.safe.debug("Initializing effect provider"),await this.init()),this.logger.safe.debug(`Set effect: ${g}`);const f=this.getWebCVEffect(g);if(!f)throw new Error(`Effect with type ${g} is not supported`);if(this.shouldCollectStats(g)&&this.notifyAboutLastSessionStats("EffectChanged"),this.currentEffect=g,this.effectProvider)try{await this.effectProvider.setEffectAsync(f)}catch(g){throw await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to apply ${f}, error:${stringifyObject(g)}`),g}else this.logger.safe.debug("WebCV is not initialized. Do nothing")}async processingVideoEffectMessage(g){let f={code:0,response:{effects:[]},type:"EnableEffects"};try{await this.init()}catch(g){return this.logger.error(`Failed to initialize WebCV, error:${stringifyObject(g)}`),this.notifyError("FailedToInitialize",`Initialization failed, error:${stringifyObject(g)}`),f}const S=this.currentEffect;this.logger.info(`Processing video effect request type: ${JSON.stringify(g.type)}`),f=await this.queryMessageProcessor.processVideoEffectMessage(g),this.queryMessageProcessor.reconfigure&&(await this.configure({imagePath:this.queryMessageProcessor.payload.imageConfig.backgroundImageUrl,headers:this.queryMessageProcessor.payload.imageConfig.headers}),this.queryMessageProcessor.reconfigure=!1);try{this.shouldCollectStats(S)&&this.notifyAboutLastSessionStats("EffectChanged"),await this.effectProvider.setEffectAsync(this.getWebCVEffect(this.queryMessageProcessor.payload.effectType),this.queryMessageProcessor.payload)}catch{this.logger.error("Failed to apply video effect")}return f}async setSourceAsync(g){if(this.logger.safe.debug(`Set source: ${g?g.id:"no stream"}`),!this.effectProvider)return this.logger.safe.debug("WebCV is not initialized. Do nothing"),g;let f=g;try{f=await this.effectProvider.setSourceAsync(g)}catch(g){await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to set source, error:${stringifyObject(g)}`)}return f}async removeSourceAsync(g){if(this.logger.safe.debug(`Remove source: ${g?g.id:"no stream"}`),this.effectProvider)return this.effectProvider.removeSourceAsync(g);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async getEffectsCapability(){let g=0;const f=await this.getCapability();this.logger.safe.debug(`Get capabilty with return: ${JSON.stringify(f)}`);for(const S of f)g|=S;return g}getStats(g){if(!this.effectProvider)return;const f=this.effectProvider.getStats(),S=this.statistics.getReport();return f||S.error.length?{timestamp:Date.now(),statsReason:g,...this.createTelemetryEvent(f,S)}:void 0}getVersion(){return this.effectProvider?.getVersion?.()??"Unknown"}async resetOutputConstraints(g,f=lr.EffectQualityChangeReason.ExternalParam){const S={...this.configProvider.config.webcv.qualityConfig};return S.outputResolution=g.height,this.effectProvider?.configureStreamProcessor(S,lr.EffectQualityChangeReason.ExternalParam)}createTelemetryEvent(g,f){return{payload:{version:this.getVersion(),...f,...g,isWasmEnabled:this.processorType===lr.ProcessorType.Wasm}}}notifyError(g,f){this.statistics.setError(g,f),this.notifyAboutLastSessionStats("EffectError")}notifyAboutLastSessionStats(g){const f=this.getStats(g);f&&this.event("onVideoEffectTelemetryEvent").raise(f)}async initializeVideoEffectProvider(){if(!this.webcvProvider)return this.logger.safe.debug("WebCV provider is not set"),null;this.statistics.startLoadTimer();const g=await this.webcvProvider.getVideoEffectProvider();if(this.statistics.stopLoadTimer(),!g)return this.statistics.setError("FailedToInitialize"),this.logger.safe.warn("WebCV is not initialized"),null;this.logger.safe.debug(`WebCV v${g.getVersion?.()} is initialized`);const f=await this.webcvProvider.getModelConfig();return await g.configureModel(f),this.configProvider.config.webcv.loadWorkerCallback=this.wasmLoader.getWorkerFunction("wasmcv"),this.configProvider.config.webcv.loadTimerWorkerCallback=this.wasmLoader.getWorkerFunction("timer"),await g.configure({...this.configProvider.config.webcv,processorType:this.processorType}),this.effectConfig&&await g.configureEffect(this.effectConfig),this.effectProviderSubs=[g.on("onEffectApplied",(()=>this.event("onMediaStreamUpdateRequested").raise("Video"))),g.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats("EffectStopped"))),g.on("onVideoEffectQualityChanged",(g=>this.event("onVideoEffectQualityChanged").raise(g))),g.on("onVideoStreamQualityChanged",(g=>this.event("onVideoStreamQualityChanged").raise(g.resolution,g.fps,g.reason))),g.on("onCapabilitiesChanged",(()=>this.event("onVideoEffectCapabilitiesChanged").raise())),g.on("onFirstFrameProcessed",(()=>this.onFirstFrameProcessed())),g.on("onErrorNotified",(g=>this.notifyError("WebcvProcessorError",g))),g.on("videoFreezeDetected",(g=>this.event("videoFreezeDetected").raise(g)))],g}async getCapability(){if(!this.configProvider.config.enableVideoEffects)return this.logger.debug("Video effects disabled"),[0];if(!this.webcvProvider)return this.logger.debug("WebCVProvider is not configured"),[0];const g=new _y(this.configProvider,this.statistics,this.logger.createChild("CapabilityChecker"));let f=[0];return g.isWasmEffectSupported()?(f=[0,1,16,262144,512,2048],this.processorType=lr.ProcessorType.Wasm):g.isWebgl2EffectSupported()&&(f=[0,1,16],this.processorType=lr.ProcessorType.Webgl2),f}getWebCVEffect(g){return this.videoEffectToWebCVEffectMapping[g]||lr.VideoEffectType.None}onFirstFrameProcessed(){this.event("onVideoEffectApplied").raise(),this.logger.safe.debug("onVideoEffectApplied event raised")}async handleFailedProcessing(){this.currentEffect=0;try{await this.effectProvider.setEffectAsync(lr.VideoEffectType.Off)}catch(g){this.notifyError("WebcvProcessorError",`Failed to handle error state, error:${stringifyObject(g)}`)}}shouldCollectStats(g){return 0!==this.currentEffect&&0!==g&&this.currentEffect!==g}};__decorateClass([sequentialize()],Iy.prototype,"init",1),__decorateClass([sequentialize()],Iy.prototype,"dispose",1),__decorateClass([sequentialize()],Iy.prototype,"configure",1),__decorateClass([sequentialize()],Iy.prototype,"setSourceAsync",1),__decorateClass([sequentialize()],Iy.prototype,"removeSourceAsync",1),__decorateClass([sequentialize()],Iy.prototype,"getEffectsCapability",1);var by=class{constructor(g,f){this.configProvider=g,this.logger=f,this.currentEffects=0,this.currentEffectPayload={effectType:0},this.shouldReconfigure=!1}get payload(){return this.currentEffectPayload.effectType=this.currentEffects,this.currentEffectPayload}get reconfigure(){return this.shouldReconfigure}set reconfigure(g){this.shouldReconfigure=g}async processVideoEffectMessage(g){switch(g.type){case"EnableEffects":return await this.processEnableEffectsMessage(g);case"DisableEffects":return await this.processDisableEffectsMessage(g);case"QueryEffects":return await this.processQueryEffectsMessage(g);default:return this.logger.error(`Unsupported video effect message type: ${g.type}`),null}}async processEnableEffectsMessage(g){const f={code:0,response:{effects:[]},type:"EnableEffects"};for(let S=0;S<g.request.effects.length;S++){const v=g.request.effects[S];switch(v.type){case"BackgroundModification":if("Blur"===v.options.variant){this.currentEffects|=1;const g={type:"BackgroundModification",options:{variant:"Blur"}};f.response.effects.push(g),this.currentEffects&=-262673}else if("Replacement"===v.options.variant){this.currentEffects|=16;const g={type:"BackgroundModification",options:{variant:"Replacement",location:v.options.location}};this.shouldReconfigure=!0,this.currentEffectPayload.imageConfig={backgroundImageUrl:v.options.location,headers:v.options?.headers},f.response.effects.push(g),this.currentEffects&=-262658}else if("WeatherPerson"===v.options.variant){if(!this.configProvider.config.webcv.useWasmEffects){this.logger.error("WeatherPerson effect is not supported on non wasm effect provider");break}this.currentEffects|=512;const g={type:"BackgroundModification",options:{variant:"WeatherPerson"}};f.response.effects.push(g),this.currentEffects&=-262162}else if("Bokeh"===v.options.variant){if(!this.configProvider.config.webcv.useWasmEffects){this.logger.error("Bokeh effect is not supported on non wasm effect provider");break}this.currentEffects|=262144;const g={type:"BackgroundModification",options:{variant:"Bokeh"}};f.response.effects.push(g),this.currentEffects&=-530}break;case"TouchUp":this.logger.error("TouchUp effect is not supported on non wasm effect provider");break;case"AutoAdjust":if(!this.configProvider.config.webcv.useWasmEffects){this.logger.error("AutoAdjust effect is not supported on non wasm effect provider");break}this.currentEffects|=2048,f.response.effects.push({type:"AutoAdjust"})}}return f}async processQueryEffectsMessage(g){const f={code:0,response:{effects:[]},type:"QueryEffects"};if(1&this.currentEffects){const g={type:"BackgroundModification",options:{variant:"Blur"},state:"On"};f.response.effects.push(g)}else{const g={type:"BackgroundModification",options:{variant:"Blur"},state:"Off"};f.response.effects.push(g)}if(262144&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const g={type:"BackgroundModification",options:{variant:"Bokeh"},state:"On"};f.response.effects.push(g)}else if(this.configProvider.config.webcv.useWasmEffects){const g={type:"BackgroundModification",options:{variant:"Bokeh"},state:"Off"};f.response.effects.push(g)}else{const g={type:"BackgroundModification",options:{variant:"Bokeh"},state:"Unavailable"};f.response.effects.push(g)}if(16&this.currentEffects){const g={variant:"Replacement",location:""};this.currentEffectPayload?.imageConfig&&(g.location=this.currentEffectPayload?.imageConfig.backgroundImageUrl);const S={type:"BackgroundModification",options:g,state:"On"};f.response.effects.push(S)}else{const g={type:"BackgroundModification",options:{variant:"Replacement",location:""},state:"Off"};f.response.effects.push(g)}if(512&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const g={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"On"};f.response.effects.push(g)}else if(this.configProvider.config.webcv.useWasmEffects){const g={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"Off"};f.response.effects.push(g)}else{const g={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"Unavailable"};f.response.effects.push(g)}if(256&this.currentEffects){const g={type:"TouchUp",state:"Unavailable",options:{strength:0}};f.response.effects.push(g)}if(2048&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const g={type:"AutoAdjust",state:"On"};f.response.effects.push(g)}else if(this.configProvider.config.webcv.useWasmEffects){const g={type:"AutoAdjust",state:"Off"};f.response.effects.push(g)}else{const g={type:"AutoAdjust",state:"Unavailable"};f.response.effects.push(g)}return f}async processDisableEffectsMessage(g){const f={code:0,response:{effects:[]},type:"DisableEffects"},S=g,v={effects:[]};for(let g=0;g<S.request.effects.length;g++){const f=S.request.effects[g];switch(f.type){case"BackgroundModification":if("Blur"===f.options.variant){const g={type:"BackgroundModification",options:{variant:"Blur"}};v.effects.push(g),this.currentEffects&=-2}if("Bokeh"===f.options.variant){const g={type:"BackgroundModification",options:{variant:"Bokeh"}};v.effects.push(g),this.currentEffects&=-262145}if("Replacement"===f.options.variant){const g={variant:"Replacement",location:""};void 0!==this.payload?.imageConfig&&(g.location=this.payload?.imageConfig.backgroundImageUrl);const f={type:"BackgroundModification",options:g};v.effects.push(f),this.currentEffects&=-17}if("WeatherPerson"===f.options.variant){const g={type:"BackgroundModification",options:{variant:"WeatherPerson"}};v.effects.push(g),this.currentEffects&=-513}break;case"TouchUp":this.logger.error("TouchUp effect is not supported now"),v.effects.push({type:"TouchUp",options:{strength:0}}),this.currentEffects&=-257,this.currentEffectPayload.softfocusStrength=0;break;case"AutoAdjust":v.effects.push({type:"AutoAdjust"}),this.currentEffects&=-2049}}return f.response=v,f}},Ay=class extends Ht{constructor(g,f,S,v,C,_){super(C),this.wasmdnsProvider=g,this.wasmaecProvider=f,this.wasmVqeProvider=S,this.configProvider=v,this.logger=C,this.wasmLoader=_,this.serialQueue=new zC(this.logger),this.stopped=!0,this.hasError=!1,this.statistics=new Ty(this.configProvider.config.effectsTelemetryBufferSize),this.currentEffect=cr.AudioEffectType.Off,this.currentEffectCapability=0,this.audioEffectToWasmAudioEffectType={0:cr.AudioEffectType.Off,1:cr.AudioEffectType.NoiseSuppressionClassic,2:cr.AudioEffectType.NoiseSuppressionDeep,4:cr.AudioEffectType.EchoCancellationClassic,8:cr.AudioEffectType.VoiceQualityEnhancementClassic,16:cr.AudioEffectType.VoiceQualityEnhancementDeep},this.noiseSuppressionModeToWasmDnsEffectMapping={Off:cr.AudioEffectType.Off,High:cr.AudioEffectType.NoiseSuppressionDeep,Low:cr.AudioEffectType.NoiseSuppressionClassic}}get isEffectEnabled(){return this.currentEffect!==cr.AudioEffectType.Off}shouldFallbackToNativeProcessing(){return!!this.configProvider.config.enableAudioProcessingFallback&&(this.configProvider.config.wasmvqe.enableVqe||this.configProvider.config.wasmdns.enableNoiseSuppression?this.hasError?(this.logger.safe.info("shouldFallbackToNativeProcessing: error was encountred initializing the package"),!0):this.configProvider.config.wasmvqe.enableVqe&&!this.wasmVqeProvider?(this.logger.safe.info("shouldFallbackToNativeProcessing: VQE provider is enabled but not loaded"),!0):!(!this.configProvider.config.wasmdns.enableNoiseSuppression||this.wasmdnsProvider&&this.wasmaecProvider)&&(this.logger.safe.info("shouldFallbackToNativeProcessing: DNS/AEC provider is enabled but not loaded"),!0):(this.logger.safe.info("shouldFallbackToNativeProcessing: custom processing is not enabled"),!0))}nsModeToVqeMode(g,f){switch(g){case"High":return f?cr.VqeMode.DeepVQE:cr.VqeMode.DeepNS;case"Low":return f?cr.VqeMode.SkypeVQE:cr.VqeMode.SkypeNS;default:return f?cr.VqeMode.SkypeAEC:cr.VqeMode.Off}}vqeModeToNsMode(g){switch(g){case cr.VqeMode.DeepVQE:case cr.VqeMode.DeepNS:return"High";case cr.VqeMode.SkypeVQE:case cr.VqeMode.SkypeNS:return"Low";case cr.VqeMode.SkypeAEC:case cr.VqeMode.Off:default:return"Off"}}vqeModeToAudioEffectType(g){switch(g){case cr.VqeMode.DeepVQE:return 16;case cr.VqeMode.DeepNS:return 2;case cr.VqeMode.SkypeVQE:return 8;case cr.VqeMode.SkypeNS:return 1;case cr.VqeMode.SkypeAEC:return 4;case cr.VqeMode.Off:default:return 0}}audioEffectTypeToVqeMode(g){switch(g){case 16:return cr.VqeMode.DeepVQE;case 2:return cr.VqeMode.DeepNS;case 8:return cr.VqeMode.SkypeVQE;case 1:return cr.VqeMode.SkypeNS;case 4:return cr.VqeMode.SkypeAEC;default:return cr.VqeMode.Off}}async initializeProvider(){if(this.configProvider.config.wasmvqe.enableVqe&&!this.vqeProvider)return this.logger.safe.debug("Initializing VQE provider ..."),void(this.vqeProvider=await this.initializeAudioEffectProvider(cr.AudioEffectType.VoiceQualityEnhancementDeep));this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.dnsProvider&&(this.logger.safe.debug("Initializing DNS provider ..."),this.dnsProvider=await this.initializeAudioEffectProvider(cr.AudioEffectType.NoiseSuppressionDeep)),this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.aecProvider&&(this.logger.safe.debug("Initializing AEC provider ..."),this.aecProvider=await this.initializeAudioEffectProvider(cr.AudioEffectType.EchoCancellationClassic))}async configureEffect(g){this.statistics.clearErrors();let f=g;if(!f){let g=this.configProvider.mediaConfig.noiseSuppressionMode;this.logger.safe.info(`Configuring the audio effect manager for Noise Suppression mode: ${g}`),"Auto"===g&&(g=this.configProvider.config.wasmvqe.enableVqe?this.vqeModeToNsMode(this.configProvider.config.wasmvqe.defaultVqeMode):this.configProvider.config.wasmdns.noiseSuppressionMode,this.logger.safe.info(`Overriding 'Auto' with ${g}`)),f={...this.configProvider.config.wasmdns,...this.configProvider.config.wasmvqe},f.noiseSuppressionMode=g}if(await this.getEffectsCapability(),this.configProvider.config.wasmvqe.enableVqe)try{if(!this.vqeProvider)return void this.logger.safe.error("VQE provider is not initialized");this.userNoiseSuppressionMode&&(f.defaultVqeMode=this.userNoiseSuppressionMode),f.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmVqeWorklet,f.loadWasmWorkerCallback=this.wasmLoader?.audioWorklet?.getWasmVqeWorker,this.logger.safe.debug("Configuring VQE audio effects ..."),await this.vqeProvider.configureEffect(f),this.logger.safe.debug(`The audio effects were configured as follows: ${stringifyObject(f)}, and current capability is ${this.currentEffectCapability}.`)}catch(g){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${g}), while trying to use this configuration: ${stringifyObject(f)},\n                    under the following capability: ${this.currentEffectCapability}.`),this.requestStreamUpdate(!1,!0)}else if(this.configProvider.config.wasmdns.enableNoiseSuppression){f.noiseSuppressionMode||(this.logger.safe.debug("configureEffect was called without a noiseSuppressionMode. Using noiseSuppressionMode from config provider ..."),f.noiseSuppressionMode=this.configProvider.mediaConfig.noiseSuppressionMode),this.currentEffect=this.noiseSuppressionModeToWasmDnsEffectMapping[f.noiseSuppressionMode],this.logger.safe.debug(`currentEffect is ${this.currentEffect}`);try{if(!this.dnsProvider||!this.aecProvider)return void this.logger.safe.debug("DNS & AEC providers not initialized");this.logger.safe.debug("Configuring DNS/AEC audio effects ..."),f.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmDnsWorklet,await this.dnsProvider.configureEffect(f),f.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmAecWorklet,await this.aecProvider.configureEffect(f),this.logger.safe.debug(`The audio effects were configured as follows: ${stringifyObject(f)}, and current capability is ${this.currentEffectCapability}.`)}catch(g){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${g}), while trying to use this configuration: ${stringifyObject(f)},\n                    under the following capability: ${this.currentEffectCapability}.`),this.requestStreamUpdate(!1,!0)}}}async setSourceAsync(g){if(this.logger.safe.debug(`Set source: ${g?g.id:"no stream"}, currentEffect = ${this.currentEffect}`),this.stopped||(this.stop(),this.stopped=!1),this.shouldFallbackToNativeProcessing())return this.logger.safe.info("No custom audio effect is used. Fallback to native audio processing"),g;if(await this.initializeProvider(),await this.configureEffect(),!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const f=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setSourceAsync: audio effect provider not initialized (${f}).`),this.logger.safe.warn(`Unable to configure audio effects: audio effect provider not initialized (${f}).`),g}if(!this.configProvider.config.wasmvqe.enableVqe&&!this.configProvider.config.wasmdns.enableNoiseSuppression)return g;if(this.effectProviderSubs=[this.vqeProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onErrorNotified",((g,f)=>this.notifyError("WasmVqeProcessorError",g,f))),this.dnsProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onErrorNotified",(g=>this.notifyError("WasmDnsProcessorError",g))),this.aecProvider?.on("onErrorNotified",(g=>this.notifyError("WasmAecProcessorError",g)))],this.configProvider.config.wasmvqe.enableVqe)try{const f=await this.vqeProvider.setSourceAsync(g);return this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId)),f}catch(f){return this.notifyError("WasmVqeProcessorError",`setSourceAsync: Failed to asynchronously set source for VQE (${f})`),g}let f=g;try{f=await this.aecProvider.setSourceAsync(g),this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId))}catch(g){this.notifyError("WasmAecProcessorError",`setSourceAsync: Failed to asynchronously set source for AEC (${g})`)}try{return await this.dnsProvider.setSourceAsync(f)}catch(g){this.notifyError("WasmDnsProcessorError",`setSourceAsync: Failed to asynchronously set source for DNS (${g})`)}return f}setAecRefStream(g,f){try{if(!g&&this.rendererId!==f)return void this.logger.safe.debug(`Ref stream can't be set to null by renderer ${f}`);if(this.logger.safe.debug(`Setting the reference stream to: ${g?g.id:"Null"} requested by renderer ${f}`),this.aecRefStream=g,this.rendererId=f,!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const g=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setAecRefStream: audio effect provider not initialized (${g}).`),void this.logger.safe.warn(`Unable to setAecRefStream for audio effects: audio effect provider not initialized (${g}).`)}this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider.setRefStream(g):this.configProvider.config.wasmdns.enableNoiseSuppression&&this.aecProvider.setRefStream(g)}catch(g){this.notifyError("WasmVqeProcessorError",`setRefStream: Failed to set reference stream for echo cancellation (${g})`)}}async setEffectAsync(g){const f=this.audioEffectToWasmAudioEffectType[g];if(this.currentEffect===f)return;const S=this.currentEffect===cr.AudioEffectType.Off||f===cr.AudioEffectType.Off;if(this.currentEffect=f,this.userNoiseSuppressionMode=this.audioEffectTypeToVqeMode(g),await this.initializeProvider(),await this.configureEffect(),!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const g=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";throw this.notifyError("FailedToInitialize",`setEffectAsync: audio effect provider not initialized (${g}).`),Error("FailedToInitialize")}try{this.configProvider.config.wasmvqe.enableVqe?await this.vqeProvider.setEffectAsync(f):this.configProvider.config.wasmdns.enableNoiseSuppression&&(await this.dnsProvider.setEffectAsync(f),await this.aecProvider.setEffectAsync(f)),this.configProvider.config.applyAudioEffectOnDemand&&this.configProvider.config.wasmvqe.enableVqe&&S&&this.requestStreamUpdate(!0),this.logger.safe.debug(`The audio effect was set to '${f}'`)}catch(g){throw this.notifyError("WasmVqeProcessorError",`setEffectAsync: Failed to apply '${f}' audio effect, error: ${stringifyObject(g)}`),g}}stop(){try{this.aecRefStream=null,this.dnsProvider?.dispose(),this.dnsProvider=null,this.aecProvider?.dispose(),this.aecProvider=null,this.vqeProvider?.dispose(),this.vqeProvider=null,this.effectProviderSubs?.forEach((g=>g?.dispose())),this.effectProviderSubs=null,this.stopped=!0,this.logger.safe.debug("The audio effects provider was stopped.")}catch(g){this.logger.safe.error(`Failed to stop the audio effects provider (${g})`)}}dispose(){try{this.hasError=!1,this.stop(),super.dispose(),this.logger.safe.debug("The audio effects provider was disposed.")}catch(g){this.logger.safe.error(`dispose: Failed to dispose the audio effects provider (${g})`)}}async getEffectsCapability(){return this.currentEffectCapability=0,this.configProvider.config.wasmvqe.enableVqe?(this.currentEffectCapability|=1,this.currentEffectCapability|=2,this.configProvider.config.wasmvqe.enableAec&&(this.currentEffectCapability|=4,this.currentEffectCapability|=8,this.currentEffectCapability|=16)):this.configProvider.config.wasmdns.enableNoiseSuppression&&(this.currentEffectCapability|=1,this.currentEffectCapability|=2,this.currentEffectCapability|=4),this.currentEffectCapability}getVersion(){return`${`WasmDns ${this.dnsProvider?.getVersion()??"Unknown"}`} / ${`WasmAec ${this.aecProvider?.getVersion()??"Unknown"}`} / ${`WasmVqe ${this.vqeProvider?.getVersion()??"Unknown"}`}`}getStats(){const g=this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider?.getStats():this.dnsProvider?.getStats();return g?(g.userNoiseSuppressionMethod=this.userNoiseSuppressionMode,{timestamp:Date.now(),...this.createTelemetryEvent(g)}):null}async initializeAudioEffectProvider(g){if(!this.wasmVqeProvider&&g===cr.AudioEffectType.VoiceQualityEnhancementDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmVqe package not available."),this.logger.safe.warn("WasmVqe package not available."),null;if(!this.wasmdnsProvider&&g===cr.AudioEffectType.NoiseSuppressionDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmDns package not available."),this.logger.safe.warn("WasmDns package not available."),null;if(!this.wasmaecProvider&&g===cr.AudioEffectType.EchoCancellationClassic)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmAec package not available."),this.logger.safe.warn("WasmAec package not available."),null;let f;this.statistics.startLoadTimer();try{this.configProvider.config.wasmvqe.enableVqe&&g===cr.AudioEffectType.VoiceQualityEnhancementDeep&&(f=await this.wasmVqeProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&g===cr.AudioEffectType.NoiseSuppressionDeep&&(f=await this.wasmdnsProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&g===cr.AudioEffectType.EchoCancellationClassic&&(f=await this.wasmaecProvider.getAudioEffectProvider())}catch(g){this.logger.safe.warn(`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${g})`),this.statistics.setError("FailedToInitialize",`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${g})`)}return this.statistics.stopLoadTimer(),f?(g===cr.AudioEffectType.VoiceQualityEnhancementDeep&&this.logger.safe.debug(`WasmVqe v${f.getVersion?.()} initialized!`),g===cr.AudioEffectType.NoiseSuppressionDeep&&this.logger.safe.debug(`WasmDns v${f.getVersion?.()} initialized!`),g===cr.AudioEffectType.EchoCancellationClassic&&this.logger.safe.debug(`WasmAec v${f.getVersion?.()} initialized!`),f):(this.logger.safe.warn("Unitialized Wasm audio effect provider."),null)}createTelemetryEvent(g){return{payload:{audioEffectsCapability:this.currentEffectCapability,version:this.getVersion(),...this.statistics.getReport(),...g}}}notifyError(g,f,S=!1){this.logger.error(`Audio effect error: ${g}, message: ${f}`),this.statistics.setError(g,f),this.notifyAboutLastSessionStats(),S&&this.requestStreamUpdate(!1,!0),this.event("onEffectsError").raise("Audio",g,f)}notifyAboutLastSessionStats(){const g=this.getStats();g&&this.event("onAudioEffectTelemetryEvent").raise(g)}requestStreamUpdate(g=!1,f=!1){(g||this.configProvider.config.enableAudioProcessingFallback&&!this.hasError)&&(this.hasError=f,this.event("onMediaStreamUpdateRequested").raise("Audio"))}};__decorateClass([sequentialize()],Ay.prototype,"setSourceAsync",1),__decorateClass([sequentialize()],Ay.prototype,"setAecRefStream",1),__decorateClass([sequentialize()],Ay.prototype,"setEffectAsync",1),__decorateClass([sequentialize()],Ay.prototype,"stop",1),__decorateClass([sequentialize()],Ay.prototype,"dispose",1);var Py=class{constructor(g){this.logger=g}async setSourceAsync(g){let f=document.createElement("video");return f.srcObject=g,this.logger.info(`Stream settings before play: ${JSON.stringify(this.getSettings(g))}`),await f.play(),this.logger.info(`Stream settings after play: ${JSON.stringify(this.getSettings(g))}`),f.pause(),f.srcObject=null,f.remove(),f=null,g}getSettings(g){return g.getVideoTracks()?.[0]?.getSettings()}},Ry=class extends Ht{constructor(g,f){super(),this.configProvider=g,this.logger=f}isEffectEnabled(g){switch(g){case"Video":return this.videoEffectManager?.isEffectEnabled;case"Audio":return this.audioEffectManager?.isEffectEnabled;default:return!1}}shouldFallbackToNativeProcessing(g){return"Audio"===g&&this.audioEffectManager?.shouldFallbackToNativeProcessing()}addEffectManager(g,f){switch(g){case"Audio":this.addAudioEffectManagerAndSubscribe(f);break;case"Video":this.addVideoEffectManagerAndSubscribe(f);break;case"ScreenShare":this.delayedScreenShareEffectManager=new Py(this.logger.createChild("DelayedScreenShareEffectManager"))}}async startEffect(g,f){switch(g){case"Audio":return this.audioEffectManager.setSourceAsync(f);case"Video":return this.videoEffectManager.setSourceAsync(f);case"ScreenShare":return this.delayedScreenShareEffectManager.setSourceAsync(f);default:return f}}async setEffectType(g,f){switch(g){case"Audio":return this.audioEffectManager?.setEffectAsync(f);case"Video":return this.videoEffectManager?.setEffectAsync(f)}}async processingVideoEffectMessage(g){return this.videoEffectManager.processingVideoEffectMessage(g)}stopEffect(g,f){switch(g){case"Audio":this.logger.safe.info("stopping audio effect"),this.audioEffectManager?.stop();break;case"Video":this.logger.safe.info("stopping video effect"),this.videoEffectManager?.removeSourceAsync(f)}}resetOutputConstraints(g,f,S){if("Video"===g)this.videoEffectManager?.resetOutputConstraints(f,S)}getStats(g,f){switch(g){case"Audio":return this.audioEffectManager?.getStats();case"Video":return this.videoEffectManager?.getStats(f);default:return}}async configure(g,f){if("Video"===g)return this.videoEffectManager?.configure(f)}async getEffectsCapability(g){switch(g){case"Audio":return this.audioEffectManager?.getEffectsCapability();case"Video":return this.videoEffectManager?.getEffectsCapability();default:return 0}}setAecRefStream(g,f){return this.audioEffectManager.setAecRefStream(g,f)}vqeModeToAudioEffectType(g){return this.audioEffectManager.vqeModeToAudioEffectType(g)}nsModeToVqeMode(g,f){return this.audioEffectManager.nsModeToVqeMode(g,f)}getAudioEffectsProviderName(){let g="None";return this.configProvider.config.wasmvqe.enableVqe?g="DeepVqe":this.configProvider.config.wasmdns.enableNoiseSuppression&&(g="DNS"),g}dispose(){super.dispose(),this.audioEffectManager?.dispose(),this.audioEffectManager=null,this.videoEffectManager?.dispose(),this.videoEffectManager=null}addAudioEffectManagerAndSubscribe(g){this.audioEffectManager||(this.audioEffectManager=new Ay(g.wasmdnsProvider,g.wasmaecProvider,g.wasmVqeProvider,this.configProvider,this.logger.createChild("AudioEffectManager"),g.wasmLoader),this.audioEffectManager.on("onAudioEffectTelemetryEvent",(g=>{this.event("onAudioEffectTelemetryEvent").raise(g)})),this.audioEffectManager.on("onMediaStreamUpdateRequested",(g=>{this.event("onMediaStreamUpdateRequested").raise(g)})),this.audioEffectManager.on("onEffectsError",((g,f,S)=>{this.event("onEffectsError").raise(g,f,S)})))}addVideoEffectManagerAndSubscribe(g){this.videoEffectManager||(this.videoEffectManager=new Iy(g.webcvProvider,this.configProvider,this.logger.createChild("VideoEffectManager"),g.wasmLoader),this.videoEffectManager.on("onMediaStreamUpdateRequested",(g=>{this.event("onMediaStreamUpdateRequested").raise(g)})),this.videoEffectManager.on("onVideoEffectQualityChanged",(g=>{this.event("onVideoEffectQualityChanged").raise(g)})),this.videoEffectManager.on("onVideoStreamQualityChanged",((g,f,S)=>{this.event("onVideoStreamQualityChanged").raise(g,f,S)})),this.videoEffectManager.on("onVideoEffectCapabilitiesChanged",(()=>{this.event("onVideoEffectCapabilitiesChanged").raise()})),this.videoEffectManager.on("onVideoEffectTelemetryEvent",(g=>{this.event("onVideoEffectTelemetryEvent").raise(g)})),this.videoEffectManager.on("onVideoEffectApplied",(()=>{this.event("onVideoEffectApplied").raise()})),this.videoEffectManager.on("videoFreezeDetected",(g=>{this.event("videoFreezeDetected").raise(g)})))}},My=class{constructor(g){this.audioContext=new Xs.window.AudioContext,g?(this.sourceNode=this.audioContext.createMediaStreamSource(g),this.analyzerNode=this.createAnalyserNode(this.sourceNode),this.freqs=new Uint8Array(this.analyzerNode.frequencyBinCount),this.ffreqs=new Float32Array(this.analyzerNode.frequencyBinCount)):(this.freqs=new Uint8Array(0),this.ffreqs=new Float32Array(0))}dispose(){this.sourceNode.disconnect(),this.audioContext.close(),this.audioContext=null,this.sourceNode=null,this.analyzerNode=null,this.freqs=null}getData(g){return 1===g?this.analyzerNode?.getByteFrequencyData(this.freqs):0===g&&this.analyzerNode?.getByteTimeDomainData(this.freqs),this.freqs}getDataFloat(g){return 1===g?this.analyzerNode?.getFloatFrequencyData(this.ffreqs):0===g&&this.analyzerNode?.getFloatTimeDomainData(this.ffreqs),this.ffreqs}getInputLevel(){return this.analyzerNode?.getByteFrequencyData(this.freqs),getAverage(this.freqs)}getInputLevelNormalized(g=65535,f=255){return Math.floor(this.getInputLevel()*g/f)}createAnalyserNode(g){const f=this.audioContext.createAnalyser();return f.fftSize=1024,f.smoothingTimeConstant=.1,g.connect(f),f}},wy=class _AudioStreamAnalyzerWrapper{constructor(g,f,S){this.logger=g,this.audioStreamAnalyzer=f,this.rawStream=S}getInputLevel(){return this.audioStreamAnalyzer.getDataFloat(0).reduce(((g,f)=>Math.max(Math.abs(f),g)),0)}getInputLevelNormalized(g,f){throw new Error("Method not implemented.")}dispose(g){this.logger.safe.info(`[${g}] AudioStreamAnalyzerWrapper disposed`),this.audioStreamAnalyzer.dispose(),this.rawStream?.dispose()}static async init(g,f){try{const S=g.getRawDeviceMediaStream("Audio"),v=await S.getMediaStream(),C=new My(v),_=new _AudioStreamAnalyzerWrapper(f,C,S);return _.rawStream.changed((async()=>{const g=await S.getMediaStream();_.audioStreamAnalyzer.dispose(),_.audioStreamAnalyzer=new My(g)})),f.safe.info("AudioStreamAnalyzerWrapper created"),_}catch(g){f.safe.warn(`failed to acquire audio stream for mic level: ${g}`);const S=new My;return new _AudioStreamAnalyzerWrapper(f,S)}}},Oy=class _DeviceManager extends Ht{constructor(g,f,S,v,C,_,T,I,b,A){super(g),this.logger=g,this.configProvider=f,this.diagnostics=S,this.domOverrides=v,this.ufdManager=C,this.id=uniqueId(),this.virtualDeviceRecord=new Map,this.deviceEnumerator=new my(this.configProvider,this.logger.createChild("DeviceEnumerator")),this.deviceSelection=new fy(my.list,this.configProvider,this.logger.createChild("DeviceSelection")),this.permissionManager=new yy(this.configProvider,{getMediaStream:g=>this.getMediaStream({...g,withEffect:!1,withTimeout:!0,force:!1,audioProcessingFlags:g.audio&&!g.video?this.getAudioProcessingFlags():void 0},"permissionManager"),hasCamera:()=>this.hasDeviceType("camera"),raiseTelemetryEvent:(g,f)=>this.raiseTelemetryEvent(g,f),getActiveConstraints:()=>this.mediaStreamManager.getActiveConstraints(),handlePermissionStateChange:()=>this.handlePermissionStateChange()},this.logger.createChild("PermissionManager")),this.activeRenderers=[],this.selectedDevices={camera:null,microphone:null,speaker:null,audioIngestDevice:null},this.pendingDevices=null,this.deviceManagerSubscriptions=[],this.streamManagerSubscriptions=[],this.streamSubscriptions=new Map,this.rendererSubscriptions=new Map,this.rawDeviceStreamManager=new qC(this.logger.createChild("RawDeviceStream"),this.raiseTelemetryEvent.bind(this)),this.customDeviceMediaStreamMap=new Map,this.clientAudioRenderers=new Map,this.audioSharingRequested=!1,this.virtualDeviceSubs=new Map,this.effectsManagerInternal=new Ry(this.configProvider,this.logger.createChild("EffectsManager")),this.effectsManagerInternal.addEffectManager("Audio",{wasmdnsProvider:T,wasmaecProvider:I,wasmVqeProvider:b,wasmLoader:A}),this.effectsManagerInternal.addEffectManager("Video",{webcvProvider:_,wasmLoader:A}),this.effectsManagerInternal.addEffectManager("ScreenShare",null),this.mediaStreamManager=new sy(this.logger.createChild("MediaStreamManager"),this.configProvider,this.effectsManager),this.deviceManagerSubscriptions=[this.permissionManager.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise())),my.list.on("onDevicesChanged",((g,f)=>this.onDevicesChanged(g,f))),this.deviceSelection.on("onSelectedDevicesChanged",((g,f)=>this.onSelectedDevicesChanged(g,f))),this.effectsManager.on("onAudioEffectTelemetryEvent",(g=>{this.diagnostics.registerAudioEffectsEvent(deepClone(g)),this.event("onAudioEffectsTelemetryEvent").raise(g)})),this.effectsManager.on("onMediaStreamUpdateRequested",(g=>this.onMediaStreamUpdateRequested(g,!0))),this.effectsManager.on("onVideoEffectQualityChanged",(g=>this.onVideoEffectsQualityEventHandler(g))),this.effectsManager.on("onVideoEffectTelemetryEvent",(g=>{this.diagnostics.registerVideoEffectsEvent(deepClone(g)),this.event("onVideoEffectsTelemetryEvent").raise(g)})),this.effectsManager.on("onVideoEffectApplied",(()=>{this.raiseTelemetryEvent("video_effect_applied",{}),this.event("onVideoEffectApplied").raise()})),this.effectsManager.on("onEffectsError",((g,f,S)=>this.event("onEffectsError").raise(g,f,S)))],this.subscribeOnStreamManagerEvents(),this.subscribeOnDeviceEnumeratorEvents(),this.deviceList.length&&this.onSelectedDevicesChanged(this.deviceSelection.selectedDevices,!1),this.createChildDeviceManager=g=>new _DeviceManager(g,f,new ay(f),v,C,_,T,I,b,A)}get deviceList(){return my.list.devices}get isDeviceListAvailable(){return my.isDeviceListAvailable}get isAudioOutputSelectionSupported(){return this.configProvider.userAgentConfig.isAudioOutputSelectionSupported}get effectsManager(){return this.effectsManagerInternal}createPreviewRenderer(g,f){const S=new ty(g,this,this.logger.createChild("videorenderer"),this.configProvider,f);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(S.getVideoElement()),this.subscribeOnRendererEvents(S),S}async askDevicePermission(g){await this.isDeviceListAvailable.promise;const f=await this.permissionManager.askDevicePermission(g);if(this.configProvider.config.devices.enumerateDevicesAfterADP)try{await my.enumerateDevices()}catch(g){this.logger.safe.warn(`Post-ADP device enumeration failed: ${stringifyObject(g)}`)}return f}getPermissionState(g){return this.permissionManager.getPermissionState(g)}handlePermissionStateChange(){this.diagnostics&&(this.diagnostics.permissionStates=this.permissionManager.knownPermissionStates),this.event("onPermissionStateChanged").raise()}onMediaStreamUpdateRequested(g,f=!1){if("Video"===g&&(this.updateRenderersAsync(),this.effectsManager.isEffectEnabled("Video")))return this.logger.safe.info("onStreamUpdateRequested will be called after the first frame is proccessed of the video effect stream"),void this.effectsManager.once("onVideoEffectApplied",(()=>this.event("onStreamUpdateRequested").raise(g)));this.event("onStreamUpdateRequested").raise(g,f)}createAudioRenderer(){const g=new WC(this.logger.createChild("CustomAudioRenderer"),this.configProvider),f=g.id;this.clientAudioRenderers.set(f,g);const S=g.play.bind(g),v=g.stop.bind(g);return this.raiseTelemetryEvent("custom_audio_renderer_created",this.getSelectedDevices()),{play:S,stop:v,dispose:()=>{this.clientAudioRenderers.get(f)?.dispose(),this.clientAudioRenderers.delete(f)},setMuted:(f,S=generateCauseId())=>g.setMuted(f,S),isMuted:()=>g.muted}}setAudioSharingRequested(g){this.audioSharingRequested=g}createDevicesHandle(g,f,S){const v=g.sharing?"ScreenShare":g.video?"Video":"Audio";return new Sy(this.logger.createChild("DevicesHandle"),this.getMediaStream({...g,...S&&{deviceId:S},withTimeout:!1,withEffect:!1,audioProcessingFlags:this.audioProcessingFlags,force:!1,withOverridenStream:this.customDeviceMediaStreamMap.get(v)?.active&&this.customDeviceMediaStreamMap.get(v)},f))}shareSystemSound(g){this.configProvider.config.postponeAudioMixerForAudioSharing&&(this.audioSharingRequested=g,this.event("onAudioSharingToggled").raise(g))}getAllowedModalities(){const g=shallowClone(this.permissionManager.browserPermittedModalities);return this.hasDeviceType("microphone")||(g.audio=[qt.MEDIA_STATE.inactive,qt.MEDIA_STATE.receive]),this.hasDeviceType("camera")||(g.video=[qt.MEDIA_STATE.inactive,qt.MEDIA_STATE.receive]),g}getRawDeviceMediaStream(g,f){if("ScreenShare"!==g&&!this.hasDeviceType(this.getDeviceType(g)))throw new Error("NoInputDevice");this.audioSharingRequested=f;const S=this.getStreamHandlerByType(g);if(!S)return this.logger.safe.debug(`method not found for ${g}`),null;const v=this.rawDeviceStreamManager.createIRawStreamClient(S,g);return this.raiseTelemetryEvent("IRawStream_client_created",g),v}setRawMediaStream(g,f){if(!g)throw this.logger.error(`Could not set ${g} as to ${f}`),new Error("InvalidStream");this.customDeviceMediaStreamMap.set(f,g),this.onMediaStreamUpdateRequested(f),this.raiseTelemetryEvent("set_raw_outgoing_media_stream",f)}unsetRawMediaStream(g){this.customDeviceMediaStreamMap.get(g)?(this.customDeviceMediaStreamMap.delete(g),this.onMediaStreamUpdateRequested(g),this.raiseTelemetryEvent("unset_raw_outgoing_media_stream",g)):this.logger.safe.debug("no custom stream")}async setVideoEffects(g){return this.effectsManager.setEffectType("Video",g)}async sendMessageDeviceVideoEffectsAsync(g,f){return this.effectsManager.processingVideoEffectMessage(f)}async setAudioEffects(g){return this.effectsManager.setEffectType("Audio",g)}async getAudioStream(g,f,S=!1){const v=this.configProvider.config.devices.enumerateBeforeGettingStream;return v&&("always"!==v&&my.isPolling||await my.enumerateDevices()),this.getMediaStream({audio:!0,withTimeout:this.permissionManager.isPermissionKnown("microphone"),withEffect:!S&&this.effectsManager.isEffectEnabled("Audio"),audioProcessingFlags:this.getAudioProcessingFlags(),force:g,withOverridenStream:!S&&this.customDeviceMediaStreamMap.get("Audio")?.active&&this.customDeviceMediaStreamMap.get("Audio")},f)}async getVideoStream(g,f,S=!1,v){const C=this.configProvider.config.devices.enumerateBeforeGettingStream;return C&&("always"!==C&&my.isPolling||await my.enumerateDevices()),this.getMediaStream({video:!0,withTimeout:this.permissionManager.isPermissionKnown("camera"),withEffect:!S&&this.configProvider.config.enableVideoEffects&&this.effectsManager.isEffectEnabled("Video"),force:g,withOverridenStream:!S&&this.customDeviceMediaStreamMap.get("Video")?.active&&this.customDeviceMediaStreamMap.get("Video"),videoMaxFS:v},f)}getDisplayStream(g,f=!1){const S=!(!this.configProvider.config.enableAudioSharing||!this.audioSharingRequested);return this.getMediaStream({audio:S,sharing:!0,withTimeout:!1,withEffect:!1,audioProcessingFlags:S?0:void 0,force:!1,withOverridenStream:!f&&this.customDeviceMediaStreamMap.get("ScreenShare")?.active&&this.customDeviceMediaStreamMap.get("ScreenShare")},g)}async enumerateDevicesAsync(){return await this.isDeviceListAvailable.promise,this.getDeviceDescriptions(this.deviceList)}async getDeviceNameAsync(g){await this.isDeviceListAvailable.promise;const f=this.deviceList.find((f=>f.guid===g));return f?.label??""}async getSpeakerDeviceDomIdAsync(g){await this.isDeviceListAvailable.promise;const f=this.deviceList.find((f=>f.guid===g));return f?.deviceId??""}selectDevices(g){return this.pendingDevices?(this.logger.safe.info(`Overriding device selection until enumeration is complete with ${JSON.stringify(scrubSelectedDevices(this.pendingDevices))}`),void(this.pendingDevices=g)):this.isDeviceListAvailable.isPending?(this.logger.safe.info("Postponing device selection until enumeration is complete"),this.pendingDevices=g,void this.isDeviceListAvailable.promise.then((()=>{this.logger.safe.info("Performing postponed device selection");const g=this.pendingDevices;this.pendingDevices=null,this.selectDevices(g)}))):void this.deviceSelection.selectDevices(g)}getSelectedDevices(){return this.toSelectedDevices(this.deviceSelection.selectedDevices)}setAudioProcessingFlags(g){g!==this.audioProcessingFlags&&(this.logger.debug(`Setting audio processing flags: ${this.audioProcessingFlags} -> ${g}`),this.audioProcessingFlags=g,this.event("onStreamUpdateRequested").raise("Audio"))}getOutputDeviceId(){return this.selectedDevices.speaker?.deviceId}getDeviceDescriptions(g){return(g||this.deviceList).map((g=>g.toDeviceDesc()))}getDevicesCount(){return this.deviceList.reduce(((g,f)=>(g[f.type]++,g)),{camera:0,speaker:0,microphone:0,compositeAudio:0,virtualDevice:0,audioIngestDevice:0})}async getKnownPermissionStates(){return await this.permissionManager.initialize(),this.permissionManager.knownPermissionStates}getLocalVideoRenderers(){return this.activeRenderers}dispose(){this.deviceManagerSubscriptions?.forEach((g=>g.dispose())),this.deviceManagerSubscriptions=null,this.virtualDeviceSubs?.forEach((g=>g.forEach((g=>g.dispose())))),this.virtualDeviceSubs?.clear(),this.virtualDeviceSubs=null,this.virtualDeviceRecord?.forEach((g=>g.dispose())),this.virtualDeviceRecord=null,this.unsubscribeFromStreamManagerEvents(),this.deviceEnumerator.dispose(),this.mediaStreamManager.dispose(),this.activeVideoEffectSub?.dispose(),this.activeVideoStreamForEffect?.dispose(),this.disposeRawStreamAccess(),this.disposeClientAudioRenderer(),this.effectsManager.dispose(),super.dispose()}async registerVirtualDevice(g,f){const S=g.length?g.map((({id:g},f)=>{const S=this.createChildDeviceManager(this.logger.createChild(`VirtualDevice-${f}`));return S.selectDevices({camera:g}),S})):[this.createChildDeviceManager(this.logger.createChild("VirtualDevice"))],v=new Ey(S,f),C=v.id,_=[v.on("onVideoEffectApplied",((...g)=>this.event("onVideoEffectApplied").raise(...g))),v.on("onVideoEffectsEvent",((...g)=>this.event("onVideoEffectsEvent").raise(...g))),v.on("onDeviceTelemetryEvent",((...g)=>this.event("onDeviceTelemetryEvent").raise(...g))),v.on("onVideoEffectsTelemetryEvent",((...g)=>this.event("onVideoEffectsTelemetryEvent").raise(...g))),v.on("onDevicesPermissionChanged",((...g)=>this.event("onDevicesPermissionChanged").raise(...g))),v.on("onStreamUpdateRequested",((...g)=>this.event("onStreamUpdateRequested").raise(...g)))];return this.virtualDeviceSubs.set(C,_),this.virtualDeviceRecord.set(C,v),my.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.raiseTelemetryEvent("register_virtual_device",{deviceCount:S.length,id:C}),this.event("onVirtualDevicesChanged").raise(),C}async unregisterVirtualDevice(g){this.virtualDeviceRecord.has(g)?(this.virtualDeviceSubs.get(g).forEach((g=>g.dispose())),this.virtualDeviceSubs.delete(g),this.virtualDeviceRecord.get(g).dispose(),this.virtualDeviceRecord.delete(g),my.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.event("onVirtualDevicesChanged").raise(),this.raiseTelemetryEvent("unregister_virtual_device",{id:g})):this.logger.error(`No virtual device found with id ${g}`)}getRegisteredDevices(){return Array.from(this.virtualDeviceRecord.values())}async getNrgLevelPollerForDeviceTuner(){return await wy.init(this,this.logger)}getAudioProcessingFlags(){if(!this.effectsManager.shouldFallbackToNativeProcessing("Audio"))return this.audioProcessingFlags??this.configProvider.config.defaultAudioProcessingFlags}disposeClientAudioRenderer(){this.clientAudioRenderers.size&&(this.clientAudioRenderers.forEach((g=>{g.dispose()})),this.clientAudioRenderers.clear(),this.raiseTelemetryEvent("custom_audio_renderer_disposed",this.getSelectedDevices()))}disposeRawStreamAccess(){this.rawDeviceStreamManager.disposeAll(),this.rawDeviceStreamManager=null}toSelectedDevices(g){return Object.entries(g).reduce(((g,[f,S])=>(S&&(g[f]=S.guid),g)),{})}getStreamConstraints(g){const f={deviceId:g?.deviceId||void 0};return this.configProvider.config.audioSampleRate&&(f.sampleRate=this.configProvider.config.audioSampleRate),f}hasDeviceType(g){return values(this.deviceList).some((f=>f.type===g))}getConstraints(g){if(!g.audio&&!g.video&&!g.sharing)throw new Error("requesting nothing");if(this.logger.safe.info(`retrieving media stream: ${JSON.stringify(g)}`),g.sharing){let f;const S=this.selectedDevices.audioIngestDevice;return f=S&&g.deviceId?{deviceId:S.deviceId}:g.audio&&!g.deviceId?{deviceId:qt.SYSTEM_AUDIO_SOURCE_ID}:void 0,{audio:f,sharing:{deviceId:g.deviceId||qt.DISPLAY_SOURCE_ID},withTimeout:g.withTimeout,withEffect:!1,audioProcessingFlags:g.audioProcessingFlags,force:!1,withOverridenStream:g.withOverridenStream}}const f=this.selectedDevices.microphone,S=this.selectedDevices.camera,v=g.audio&&f,C=g.video&&S;if(!v&&!C){throw{type:qt.MEDIA_ERROR.noDeviceSelected,detail:`audio requested ${g.audio}, video requested: ${g.video} Devices: ${JSON.stringify(this.deviceList.map((g=>JSON.stringify(scrubDevices(g,this.configProvider.config.devices.piiSafeWords)))))}`}}const _=this.getStreamConstraints(f),T=this.getStreamConstraints(S);let I=g.audioProcessingFlags;return void 0!==I&&g.audio&&!g.video&&f?.capabilities&&(f.capabilities.echoCancellation&&!f.capabilities.echoCancellation.includes(!!(2&I))&&(I^=2),f.capabilities.autoGainControl&&!f.capabilities.autoGainControl.includes(!!(1&I))&&(I^=1),f.capabilities.noiseSuppression&&!f.capabilities.noiseSuppression.includes(!!(4&I))&&(I^=4)),I!==g.audioProcessingFlags&&this.logger.safe.warn(`Unable to fulfill processing flags ${g.audioProcessingFlags}, using ${I} instead`),{audio:g.audio?_:void 0,video:g.video?T:void 0,withTimeout:g.withTimeout,withEffect:g.withEffect,audioProcessingFlags:I,force:g.force,withOverridenStream:g.withOverridenStream,videoMaxFS:g.videoMaxFS}}getMediaStream(g,f){const S=this.getConstraints(g),v=this.mediaStreamManager.getMediaStream(S,f);return this.subscribeOnStreamEvents(v),v.start().then((()=>{const f=v.hasAudio(),S=v.hasVideo();f&&this.signalDeviceGood("Audio",v.rawTrack.muted),S&&this.signalDeviceGood(v.mediaType,v.rawTrack.muted),this.permissionManager.update(g,g)})).catch((f=>this.handleUserMediaError(g,f))),v}signalDeviceGood(g,f){this.ufdManager.signalDeviceEvent(0,"Good",g,this.id),this.ufdManager.signalDeviceEvent(2,"Good",g,this.id),this.ufdManager.signalDeviceEvent(4,"Good",g,this.id),f||"Audio"!==g&&!this.configProvider.config.raiseVideoMuteUfd||this.ufdManager.signalDeviceEvent(3,"Good",g,this.id)}handleUserMediaError(g,f){const S=this.getMediaType(g),v=g.audio&&g.video,signalUFD=(g,f)=>{!v&&this.ufdManager.signalDeviceEvent(g,f,S,this.id)},logAudioError=g=>{!v&&"Audio"===S&&this.diagnostics.registerAudioRenderError(g)};switch(f.type){case qt.MEDIA_ERROR.permissionDeniedError:"ScreenShare"!==S&&(signalUFD(4,"Bad"),logAudioError(0x800000000000),this.configProvider.config.permissions.persistOnDeniedError&&this.refreshPermissions(g));break;case qt.MEDIA_ERROR.permissionDeniedBySystemError:signalUFD(4,"Bad"),logAudioError(0x800000000000);break;case qt.MEDIA_ERROR.sourceUnavailableError:signalUFD(0,"Bad"),logAudioError(512);break;case qt.MEDIA_ERROR.mediaStreamRequestTimedOut:signalUFD(2,"Bad"),logAudioError(35184372088832);break;default:this.logger.safe.error(`getMediaStream() error: ${stringifyObject(f)}`),signalUFD(0,"Bad"),logAudioError(4194304)}}refreshPermissions(g){const f=g.audio&&!g.video,S=!g.audio&&g.video;f?this.permissionManager.update({audio:!0},{audio:!1}):S&&this.permissionManager.update({video:!0},{video:!1})}getMediaType(g){if(g.sharing)return"ScreenShare";if(g.video)return"Video";if(g.audio)return"Audio";throw new Error(`mediaType is not defined for this constraint ${JSON.stringify(g)}`)}subscribeOnStreamEvents(g){const f=[];f.push(g.on("onStreamClientStarted",((g,f)=>this.onStreamStarted(g,f)))),f.push(g.on("onStreamClientDisposing",(g=>this.onStreamDisposing(g)))),f.push(g.on("onStreamClientEnded",((g,f)=>this.onStreamEnded(g,f)))),f.push(g.on("onStreamClientMuted",((g,f)=>this.onStreamMuted(g,f)))),f.push(g.on("onStreamClientError",((g,f)=>this.onStreamError(g,f)))),this.configProvider.config.useRawMediaApiForVideoEffects&&f.push(g.on("onStreamClientDisposed",(g=>this.removeVideoEffectStream(g)))),this.streamSubscriptions.set(g,f)}async removeVideoEffectStream(g){if(g.getCurrentConstraints().withEffect){this.logger.safe.info(`this.activeVideoEffectSub: ${this.activeVideoEffectSub} to be disposed`),this.activeVideoEffectSub?.dispose();const g=await(this.activeVideoStreamForEffect?.getMediaStream());this.effectsManager.stopEffect("Video",g)}}unsubscribeFromStreamEvents(g){this.streamSubscriptions.has(g)&&(this.streamSubscriptions.get(g).forEach((g=>g.dispose())),this.streamSubscriptions.delete(g))}subscribeOnRendererEvents(g){const f=[];f.push(g.on("onRendererDisposed",(g=>this.onRendererDisposed(g)))),f.push(g.on("onRendererStarted",(g=>this.onRendererStarted(g)))),this.rendererSubscriptions.set(g,f)}unsubscribeFromRendererEvents(g){this.rendererSubscriptions.has(g)&&(this.rendererSubscriptions.get(g).forEach((g=>g.dispose())),this.rendererSubscriptions.delete(g))}subscribeOnStreamManagerEvents(){this.streamManagerSubscriptions=[],this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onAllStreamsRemoved",(()=>this.onAllStreamsRemoved()))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamAcquired",(g=>this.onStreamAcquired(g)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamCreated",((g,f)=>this.onStreamCreated(g,f)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamDisposing",((g,f)=>this.onMasterStreamDisposing(g,f))))}subscribeOnDeviceEnumeratorEvents(){this.deviceEnumerator.on("onDeviceEnumerationfailed",(g=>this.raiseTelemetryEvent("enumeration_failed",{error:g})))}unsubscribeFromStreamManagerEvents(){this.streamManagerSubscriptions.forEach((g=>g.dispose()))}async updateRenderersAsync(){try{await Promise.all(this.activeRenderers.map((g=>g.updateStreamAsync()))),this.logger.safe.info("Renderers updates finished")}catch(g){this.logger.safe.error(`Error updating renderers: ${stringifyObject(g)}`)}}onSelectedDevicesChanged(g,f){const S=this.selectedDevices;this.selectedDevices=g,this.diagnostics.setSelectedDevices(g,f);if(!("camera"in S^"camera"in this.selectedDevices||"microphone"in S^"microphone"in this.selectedDevices)){const g=this.toSelectedDevices(this.selectedDevices),f=this.toSelectedDevices(S);this.event("onSelectedDevicesChanged").raise(g,f),g.microphone!==f.microphone&&this.rawDeviceStreamManager.notifyChange("Audio"),g.camera!==f.camera&&this.rawDeviceStreamManager.notifyChange("Video"),this.clientAudioRenderers.forEach((g=>{g.setOutputDevice(this.getOutputDeviceId())}))}const v=this.configProvider.config.devices.piiSafeWords;this.raiseTelemetryEvent("selected_devices_changed",{microphone:this.selectedDevices.microphone&&scrubDeviceLabelPii(this.selectedDevices.microphone.label,v),camera:this.selectedDevices.camera&&scrubDeviceLabelPii(this.selectedDevices.camera.label,v),speaker:this.selectedDevices.speaker&&scrubDeviceLabelPii(this.selectedDevices.speaker.label,v),fromInterface:f}),this.updateRenderersAsync()}onDevicesChanged(g,f){this.event("onDevicesChanged").raise(g,f),this.mediaStreamManager.onDevicesChanged(g),this.diagnostics.setDeviceList(g,f,this.getDeviceListDebugInfo());const S=this.getDevicesCount(),v=S.microphone>0,C=S.speaker>0;this.ufdManager.signalEvent("ZeroCaptureDevicesEnumerated",v?"Good":"Bad"),v||this.diagnostics.registerAudioCaptureError(1),this.isAudioOutputSelectionSupported&&(this.ufdManager.signalEvent("ZeroRenderDevicesEnumerated",C?"Good":"Bad"),C||this.diagnostics.registerAudioRenderError(1));const _=new Map;let T=1;this.raiseTelemetryEvent("devices_changed",{devices:g.map((g=>{const f=_.get(g.groupId)||T++;return _.set(g.groupId,f),{label:scrubDeviceLabelPii(g.label,this.configProvider.config.devices.piiSafeWords),isSystemDefault:g.isSystemDefault,kind:g.kind,type:g.type,capabilities:g.capabilities,groupId:`${f}`}})),debug:this.getDeviceListDebugInfo()})}getDeviceListDebugInfo(){return my.list.debugInfo}raiseTelemetryEvent(g,f){this.logger.safe.info(`Device event: ${g}: ${JSON.stringify(this.scrubPayload(g,f))}`);const S={eventType:g,timestamp:Date.now(),payload:f};this.diagnostics.registerDeviceTelemetryEvent(deepClone(S)),this.diagnostics.logAudioDeviceError(g,f),this.event("onDeviceTelemetryEvent").raise(S)}scrubPayload(g,f){if("devices_changed"===g){return{devices:values(f.devices).map((g=>scrubDevices(g,this.configProvider.config.devices.piiSafeWords))),debug:f.debug}}return f}async onStreamStarted(g,f){if(this.permissionManager.browserPermittedModalities.audio.some((g=>g===qt.MEDIA_STATE.send))||this.permissionManager.browserPermittedModalities.video.some((g=>g===qt.MEDIA_STATE.send)))try{await my.enumerateDevices()}catch(g){this.logger.safe.warn(`onStreamStarted device enumeration failed: ${stringifyObject(g)}`)}if(g.rawTrack){switch(g.mediaType){case"Audio":this.deviceEnumerator.startDevicePolling(),this.updateActiveMicrophone(g,f);break;case"Video":this.deviceEnumerator.startDevicePolling()}this.configProvider.config.useRawMediaApiForVideoEffects&&g.getCurrentConstraints().withEffect&&(this.activeVideoEffectSub=this.effectsManager.on("onVideoStreamQualityChanged",((f,S,v)=>g.onVideoStreamQualityChanged(f,S,v))))}else this.logger.safe.warn(`stream:${g.id} is already disposed`)}updateActiveMicrophone(g,f){if(g.deviceId){const S=this.deviceList.find((f=>f.deviceId===g.deviceId));if(!S&&"default"!==g.deviceId)return void this.logger.safe.error("Active device not found",`Device id from track: '${scrubMriOrOmit(g.deviceId)}', known devices: [${this.deviceList.map((g=>JSON.stringify(scrubDevices(g,this.configProvider.config.devices.piiSafeWords))))}]}`,JSON.stringify(scrubConstraints(f)));S&&"default"!==g.deviceId&&f.audio&&f.audio.deviceId===qt.MEDIA_DEVICE.defaultId&&my.list.updateActiveMicrophone(S)}}onStreamDisposing(g){this.unsubscribeFromStreamEvents(g)}onStreamMuted(g,f){("Audio"===g.mediaType||this.configProvider.config.raiseVideoMuteUfd)&&this.ufdManager.signalDeviceEvent(3,f?"Bad":"Good",g.mediaType,this.id),"Audio"===g.mediaType&&this.event("onAudioStreamMuted").raise(f),this.raiseTelemetryEvent(f?"stream_muted":"stream_unmuted",g.mediaType)}onStreamEnded(g,f){f.error?(this.raiseTelemetryEvent("stream_ended_error",{mediaType:g.mediaType,error:{type:f.error.name,detail:f.error.message}}),"SourceUnavailableError"===f.error.name&&this.ufdManager.signalDeviceEvent(0,"Bad","Audio",this.id)):("Audio"!==g.mediaType&&"Video"!==g.mediaType||this.ufdManager.signalDeviceEvent(0,"Bad",g.mediaType,this.id),this.raiseTelemetryEvent("stream_ended",g.mediaType))}onStreamError(g,f){this.raiseTelemetryEvent("stream_error",{mediaType:g.mediaType,error:f})}onAllStreamsRemoved(){this.deviceEnumerator.stopDevicePolling(),this.audioSharingRequested=!1}onStreamAcquired({id:g,mediaType:f,timestamp:S,resolution:v,withAudio:C,source:_,sampleRate:T}){0!==S&&this.raiseTelemetryEvent("stream_acquired",{id:g,mediaType:f,timestamp:S,resolution:v,withAudio:C,source:_,sampleRate:T})}onStreamCreated(g,f){this.raiseTelemetryEvent("stream_created",{id:g,mediaType:f})}onMasterStreamDisposing(g,f){this.raiseTelemetryEvent("stream_disposed",{id:g,mediaType:f})}onRendererDisposed(g){remove2(this.activeRenderers,(f=>f===g)),this.domOverrides.onMediaElementRemoved?.(g.getVideoElement()),this.unsubscribeFromRendererEvents(g)}onRendererStarted(g){this.activeRenderers.push(g),this.event("onLocalRendererStarted").raise(g)}onVideoEffectsQualityEventHandler(g){const f=this.deviceSelection.selectedDevices.camera;if(f?.deviceId){const S={type:"onVideoEffectQualityChanged",payload:{message:g.message,effectType:g.effectType}};this.event("onVideoEffectsEvent").raise(f.deviceId,S)}}getDeviceType(g){if("Video"===g)return"camera";if("Audio"===g)return"microphone";throw new Error(`DeviceType for mediaType: ${g} doesn't exist`)}getStreamHandlerByType(g){return"Video"===g?()=>this.getVideoStream(!1,"rawStream",!0):"Audio"===g?()=>this.getAudioStream(!1,"rawStream",!0):"ScreenShare"===g?()=>Promise.resolve(this.getDisplayStream("rawStream",!0)):null}};function getPlatformConfig(){return et.isEngine("ChromiumAVD")?new ky:et.isEngine("Safari")?new Ly:et.isEngine("Firefox")?new Fy:isVdiPlatform()?new xy:et.isEngine("Chromium")?new Uy:new Dy}var Dy=class{getInitialSettings(){return{resizeModeForSharing:"none",enableAudioProcessingFallback:!0,allowVirtualDeviceInCall:!1,activeSpeaker:{timeToPromote:1e4},dtmf:{toneDuration:200,toneGap:100},mediaStreamHoldInterval:5e3,webrtcContributingSourcesPollingStartDelay:1e3,webrtcContributingSourcesPollingInterval:1e3,webrtcContributingSourcesPollingEmptySources:0,webrtcIceGatheringTimeoutMs:2e4,webrtcAllowedMediaContentType:qt.ALLOWED_CONTENT_TYPES.SDP_NGC,webrtcMediaContentType:qt.CONTENT_TYPE.SDP,useNGC1webrtcContentType:!1,webrtcScreensharingCapabilityMaxFS:8160,webrtcScreensharingCapabilityMaxFPS:1500,webrtcStatHwSilentDetectionDuration:5,webrtcStatHwSilentDetectionLevel:14,webrtcStatPollInterval:1e3,webrtcStatStoredRecordsNumber:60,webrtcStatNetworkDetectionDuration:10,webrtcHealedRatioWindowSize:5,webrtcHealedRatioExtendedWindowSize:20,webrtcStatNetworkDetectionHysteresis:.01,webrtcStatNetworkDetectionBadLevel:.17,webrtcStatNetworkDetectionGoodLevel:.15,webrtcMinAudioSamplesRecvForNetworkRecvQuality:48e4,webrtcVideoCapabilityCheckIntervalMin:2e4,webrtcVideoCapabilityCheckIntervalMinMultiparty:5e3,webrtcVideoCapabilityCheckIntervalMax:3e4,webrtcVideoCapabilityCheckIntervalMaxMultiparty:5500,webrtcScreensharingCapabilityCheckIntervalMin:0,webrtcScreensharingCapabilityCheckIntervalMax:0,webrtcVideoCapabilityMaxFS:3600,webrtcVideoCapabilityMaxFPS:3e3,webrtcMultiPartyRecvVideoMaxFS:3600,webrtcRecvVideoMaxFS:8160,webrtcCameraOpenFs:3600,minCameraOpenFps:15,maxCameraOpenFps:30,maxCameraFsViaCallConstraints:-1,webrtcMultipartyMaxScalingFs:3600,webrtcMaxScalingFs:8160,webrtcVideoScaling:!1,webrtcVideoScalingMultiparty:!0,enableOptimalVideoCount:!1,ovcBandwidthPerVideoReceiver:2e5,ovcSlidingWindowPercentile:.3,ovcSlidingWindowSamples:20,nonEstimatedDefaultVideoReceiversCount:4,ovcMaxCount:4,ovcMaxCountXL:4,ovcMaxCountMultiStream:16,ovcXLParticipantsCount:100,ovcIgnoreFirstSamples:10,ovcAvailableConcurrencyForBiggerGrid:4,ovcMemoryForBiggerGrid:2,ovcRampUpCooldown:15e3,ovcRampDownCooldown:1e4,webrtcStatNetworkDetectionEnabled:!0,webrtcUseNewStatsApi:!0,useAudioAnalyzer:!0,webrtcVideoSubscriptionDisposeTimeout:2e3,webrtcCompareContentTypeInOffer:!0,iceServerTransport:"udp,tcp,tls",iceHostCandidateOnly:!0,iceUdpAddressType:"ip",iceTcpAddressType:"ip",renegotiationAttempts:3,reconnectTimeLimit:9e4,initialReconnectTimeLimit:0,maxReconnectDelayTime:5,waitForRelayOnReconnect:!0,relayWaitSaneTimeoutMs:25e3,reconnectOnDisconnect:!1,reconnectWithNoRelays:!1,reconnectWithProbes:!1,reconnectWaitTimeAfterProbe:1e3,reconnectOnPcClose:!0,reconnectWakeupTimeLimit:18e4,webrtcSpeakingWhileMutedDetectionWindow:3,webrtcSpeakingWhileMutedBadDuration:3,webrtcSpeakingWhileMutedDetectionLevel:4e3,webrtcNegotiateDisabledDataModality:!1,recoverableMediaErrors:[qt.MEDIA_ERROR.iceConnectionError,qt.MEDIA_ERROR.noNetworkError,qt.MEDIA_ERROR.srtpError,qt.MEDIA_ERROR.incompatibleOffer,qt.MEDIA_ERROR.internalError].join(","),forceReconnectErrors:[qt.MEDIA_ERROR.audioPlaybackError].join(","),sendCallStartupTelemetry:!0,webrtcMultiPartyRecvVideoSignaling:!0,webrtcVideoDelayThreshold:10,webrtcEndOfCallFreezeThreshold:3,webrtcSubscriptionEventLimit:300,webrtcHandleRollback:!0,webrtcHandleRemoteRollback:!0,losingConnectivityTimeoutMs:-1,iceCandidateFilterMDns:!0,webrtcInjectTransportCCAudio:!1,webrtcInjectTransportCCAudioMultiparty:!0,webrtcRejectedFeatures:"byPass",webrtcRequiredFeatures:"nonByPass",webrtcSimulcastSessionEnabled:!1,webrtcSimulcastStreamsCountForVideo:1,webrtcSimulcastStreamsCountForSharing:1,webrtcFmtParamListSupported:!0,webrtcNegotiatedSsrcRangeForVideo:0,webrtcNegotiatedSsrcRangeForSharing:0,webrtcNegotiatedSsrcRangeForVideoOneToOne:0,webrtcNegotiatedSsrcRangeForSharingOneToOne:0,webrtcAllowRestoreKeyframe:!1,webrtcEnabledCustomBwEstimationForVideo:!1,webrtcDisabledSenderBitrate:1e3,maxStoredPreferredResolutionCount:4,maxStoredQualityLimitationReasonEvents:30,maxStoredUFDCount:50,simulcastTelemetryLayoutsPerSession:5,simulcastTelemetryNumModalitySessions:3,simulcastTelemetryNumFMTP:10,maxSendVideoCapabilities:{enableForVideo:!1,enableForSharing:!1,useMaximumWidthHeight:!1,sendMaxMbps:!1,sendMaxFs:!1},maxReportedOvershootingEvents:20,broadcastMode:{townHallScenarioNames:["premiumtownhall","basetownhall"]},performanceFallbackMaxFsFor1080pSend:3600,sendVideoCapabilityManager:{priorityOrder:["Performance","BroadcastMode","HardwareEncoder","Software1080P"],allowOptIn:["HardwareEncoder"]},video1080p:{software:{}},permissions:{usePositiveInAdp:!1,useNegativeInAdp:!1,adpFallback:!0,adpFallbackAudio:!0,adpFallbackVideo:!0,adpRequestAVLast:!0,rememberNegative:!1,persistOnDeniedError:!0,disableOnPermissionDeniedOnly:!0,enumerateDevicesAfterChange:!0},devices:{blacklist:{microphone:"stereo mix \\(",camera:"(^ir camera|avstream media device)",speaker:"stereo mix \\("},overrideDefault:!1,compositeLabelMatchingThreshold:.5,piiSafeWords:["airpod","bluetooth","hands-free","stereo","wireless","citrix hdx","remote audio","vmware","built-in","integrated","internal","teams","high definition","facetime","macbook","smartaudio","front","rear","back","iphone","ipad","display","displayport","dp","hdmi","amd","nvidia","intel","analog","digital","dock","line( in| out)?","s/pdif","external","thunderbolt\\d*","usb","panoramic","desktop","capture","cable","cam","virtual","manycam","snap camera","obs","vb-audio","vaio","effect","sink","source","default","test"],pollingIntervalActive:3e3,enumerateDevicesTimeout:25e3,enumerateDevicesAfterADP:!1,setSinkImmediately:!0,enumerateBeforeGettingStream:"always"},useGoogPrefixAudioConstraints:!0,multiviewResolutionLimits:{1:720,2:720,3:540,4:360,more:360},maxSpotlightResolution:1080,excludeUnsizedRenderersFromMultiviewResolutionLimits:!1,multiviewResolutionLimitUpdateThrottleDelay:300,useMultiviewLimitsOnInitialRequest:!0,useApplyChannelParametersForSourceRequests:!0,maxVideoFreezeTimestampsInBucket:5,webrtcSendBandwidthIgnoredUpdateLimit:6,webrtcSendBandwidthThreshold:.1,checkSupportForWebrtc_1_0:!1,webrtcLastAppliedVideoCapabilitiesCount:5,webrtcLastAppliedVideoCapabilitiesSequenceCount:5,gumRequestTimeout:2e4,overrideGumFromWebkit:!1,setMinFpsForWebkit:!1,videoCaptureFreezeTimeout:5e3,webrtcCloseAfterIceFailure:!0,audioBandwidthInKbps:90,maxBandwidthInKbps:7e3,maxBandwidthInKbpsFallback:7e3,videoBandwidthAllocation:.3,enableQosSupport:!1,forceUnbundledTransport:!1,allowedAudioCodecs:[],allowedVideoCodecs:[],allowedVideoCodecsMultiparty:[{clockRate:9e4,mimeType:"video/H264"},{clockRate:9e4,mimeType:"video/rtx"}],filterCodecsInSdp:!1,filterCodecsInSdpMultiparty:!0,filterCodecsInSdpV2:!1,reduceRtcpFbInSdp:[],reduceRtcpFbInSdpMultiparty:["goog-remb","transport-cc","ccm/fir","nack","nack/pli"],subscribeToSsrcForVideo:!1,audioRendererUsePauseOnDetach:!0,audioRendererRestartOnPause:!1,audioRendererRestartOnDeviceError:!0,disableAudioOutputSelection:!1,preferSdesSrtp:!1,preferSdesSrtpPstn:!1,useLocalStorageForOneDs:!0,oneDSDisabledPageUnloadEvents:[],oneDSLocalStorage:{sendStaleEvents:!1,accessThresholdInMs:6e5},oneDSNotificationManager:{blockNotificationsOnPageUnload:!1,blockEventsDiscardedNotifications:!1},useOneDsLogger:!1,addTelemetryReportingCallback:!0,eventsLimitInMem:200,eventLatency:Ep.Normal,eventLatencyRealTime:Ep.RealTime,enableCompoundKey:!1,telemetryTenants:{signaling:"53fdaa090eb946b5a1d6cbdeb4f2ef66-bcbf6380-2590-41cc-ae60-9e467cd51835-7413",gtcAudit:"53fdaa090eb946b5a1d6cbdeb4f2ef66-bcbf6380-2590-41cc-ae60-9e467cd51835-7413",media:"1cae5691997646c98b01d15beddae7a3-ce16e198-bc32-420f-ac64-42bb916111af-6865",realtimeMedia:"5aea257f81424f5d8574e57a50974ead-d3a768ce-590c-4595-ab85-3dd046114290-6701",tlePlayer:"2efdf03d07594586a5977c404e185186-71b046c4-f48f-4ba7-96d3-2a74b54e1d46-7326"},transmitProfileName:"REAL_TIME",transmitProfileTimings:[],waitReportStatsAtCallStop:!1,oneStreamPerDeviceType:!1,enableWebRtcInternalsLogs:!1,enableMultiViewStats:!0,webrtcBWJumpLowerLimit:1e5,webrtcBWJumpUpperLimit:3e5,uplinkBWStabilizationSlidingWindowSize:10,uplinkBWStabilizationMaxDeviation:.1,uplinkBWStabilizationMinBandwidth:1e5,downlinkBWStabilizationSlidingWindowSize:10,downlinkBWStabilizationMaxDeviation:.1,downlinkBWStabilizationMinBandwidth:1e5,maxKeyFrameTimestampsInBucket:5,enableAudioSharing:!1,audioSharingContextOptions:{sampleRate:48e3},enableStopSharingWithIncomingOffer:!0,enableDevtoolsAPI:!1,enableDataChannel:!1,enableDataChannelMultiparty:!0,enableDataChannelPstn:!1,alwaysNegotiateDataChannel:!0,webrtcDataChannel:{enableFragmentation:!1,fragmentationSize:0,enableSendScheduler:!1,rateLimiterCheckInterval:250,discardOnSendFailure:!1,bufferedAmountLowThreshold:65535,bufferedAmountHighThreshold:262144,maxBitrate:0,maxPacketRate:0,maxQueueSize:524288,dataIds:[]},acceptDisabledDataModality:!0,rejectUnbundledDataModality:!0,sctpPort:5e3,removeRtcpRsizeFromLocalSdp:!1,enableGiveControl:!1,maxStoredDataChannelValues:15,mediaControlPlaneConfig:{enableBweNotifications:!0,enableDominantSpeakerHistory:!0,enableSourceRequests:!0,enableSendBandwidthNotificationsEnabled:!1,sourceRequestsMessagesTimeout:1e4,storedSRRecordsCount:60,verboseTelemetry:!1,sendBeforeAck:!1,handshakeTimeout:1e4,setResendingMechanism:!1},localPreviewMirroringSupported:!1,enableVideoEffects:!0,waitForVideoEffectsBeforeApplyingConstraints:!1,useRawMediaApiForVideoEffects:!1,forceKeyFrameV2ScaleFactor:1.1,effectsTelemetryBufferSize:20,useDelayedScreenShareStream:!1,applyAudioEffectOnDemand:!1,wasmdns:{pTime:10,goodPerfThreshold:8,poorPerfThreshold:10,badPerfThreshold:12,perfWindowLength:10,enableNoiseSuppression:!1,noiseSuppressionMode:"Off",backgroundMode:!1},wasmvqe:{enableAec:!1,enableVqe:!1,backgroundMode:!1,performanceThresholdMs:8,performanceWindowDurationSecs:10,defaultVqeMode:cr.VqeMode.Off,callType:cr.CallType.Conference,audioUsageMode:cr.AudioUsageMode.Default,performanceProfile:cr.AecPerfProfile.Normal},webcv:{qualityConfig:{outputFps:{min:15,max:30},outputResolution:720,preserveResolution:!0,degradationLadder:[{resolution:{width:1920,height:1080},fps:{min:15,max:30}},{resolution:{width:1280,height:720},fps:{min:15,max:30}},{resolution:{width:960,height:540},fps:{min:15,max:30}},{resolution:{width:640,height:360},fps:{min:13,max:30}},{resolution:{width:416,height:234},fps:{min:10,max:20}},{resolution:{width:320,height:180},fps:{min:10,max:20}}],initialLadderResolution:720,improvementFpsThresholdPercent:20,statsIntervalSec:5,enableMaskPropagation:!1,maskPropagationFramesInterval:30},powerPreference:lr.PowerPreference.HighPerformance,useInsertableStreams:!1,webGLUnsupportedRenderers:["Google SwiftShader"],webGLRequiredExtensions:["EXT_color_buffer_float","WEBGL_debug_renderer_info","OES_texture_float_linear"],usePreheat:!1,useSharedArrayBuffer:!0,useWasmEffects:!1,processorType:lr.ProcessorType.Webgl2},insertFakeCandidateIfNeeded:!0,useSdpCapabilitiesLegacySession:!0,useSdpCapabilities:!0,enableH264SpsPpsIdrKeyframe:!0,disableMsSdp:!1,disableSdes:!1,disableIceReinvite:!1,iceDisconnectedTimeoutMs:3e4,enableLocalVideoConstraints:!0,webrtcAudioChannelSignalingFeedback:"app recv:dsh",webrtcVideoChannelSignalingFeedback:"app send:src recv:src,vc",webrtcResolutionManagerCooldownTimeout:15e3,webrtcResolutionManagerRetryDelay:5e3,webrtcNativeCpuOveruseDisabled:!1,webrtcDisplayStreamContentHint:"text",h264SendProfileOverride:"42C02A",learnCodecSendCapabilitiesFromSenderApi:!1,addFmtpToInitialSubscription:!0,h264SubscribeProfile:"64001f",notRenderingTimeInterval:{video:3,sharing:10},notRenderingLowBitrateThreshold:6,notRenderingLowFramerateThreshold:3,isBytesRecvUsedInIsRenderingCalculation:!0,useConnectionState:!0,transportStateFailedFix:!1,useDtlsTrasportConnectionCheck:!1,enableNetworkRecvQualityUFD:!0,enableNetworkSendQualityUFD:!0,enableSignalingAudioPermissionDeniedUFD:!1,webrtcJitterLowThreshold:.2,webrtcJitterHighThreshold:.35,webrtcJitterSticknessTime:5e3,webrtcLossRateLowThreshold:.2,webrtcLossRateHighThreshold:.3,webrtcLossRateSticknessTime:5e3,webrtcMinPacketsSentForNetworkSendQuality:200,webrtcLossRateWindowSize:3,webrtcJitterWindowSize:3,networkSendQualityDiagnostics:!1,networkRecvQualityDiagnostics:!1,webrtcJitterExtendedWindowSize:6,webrtcLossRateExtendedWindowSize:6,freezeMinDuration:128,freezeIntervalFrequency:1e3,disableNormalizationToCalculatePacketLossRate:!1,healedRatioPrecision:8,jitterPrecision:3,requestNewStreamOnUnmute:!0,raiseVideoMuteUfd:!1,useMediaQualityController:!1,useMediaQualityControllerForceKeyFrame:!1,bandwidthAllocatorV2:{sharingLadder:[8e4,5e5,8e5,1e6,12e5,25e5,3e6],videoLadders:[{maxFS:240,ladder:[4e4,7e4,1e5,15e4,25e4,3e5,35e4]}],defaultVideoMaxFS:240},layoutControlTimeout:1e4,extmapAllowMixed:!1,enableVla:!1,allowRemoteVla:!1,enableNonAdvVla:!1,specCompliantSimulcast:{},specCompliantSimulcastMultiparty:{video:{enableLocally:!1,allowEnableRemotely:!1,layerScaleFactors:[1],minFsForSimulcast:[920],useApplyConstraints:!1},sharing:{enableLocally:!1,allowEnableRemotely:!1,layerScaleFactors:[1]},allowOverride:!1,constraintsDisableVla:!0,collectResolutionInfo:!0,maxBrControlEnabled:!1,allowedBweOvershootRatio:1,allowResLimit:!1,disableTilde:!1},enforceOpusFmtpMultiparty:{usedtx:1},videoIsRenderingCheck:!1,fixSdpForPartialIceRestart:!1,mapSsrcToTrackForStats:!1,enableVideoOrientationExtension:!1,speakerGainLevel:0,ignoreClosedDtlsTransportState:!1,disconnectOnPageHide:!1,renderThroughCanvas:!1,isRenderingBasedOnRawStatistics:!1,enableDevicePixelRatio:!0,useSetParametersToApplyCapabilities:!1,useSetParametersToApplySSCapabilities:!1,enablePlatformCallConstraints:!1,enablePlatformCallConstraintsPerCall:!1,enableDynamicCallConstraints:!0,numCallConstraintsEvents:6,setParametersMaxBitrateUndefined:!1,onAddTrackRemoveOtherTracks:!0,avoidFakeStreamsDuringEscalation:!0,navConnectionPollingInterval:1e3,navConnectionNumSamplesToCollect:60,acceptProvisionalAnswer:!1,acceptProvisionalAnswerPstn:!0,acceptProvisionalAnswerFromPstnOnly:!0,createProvisionalAnswer:{enabled:!1,enabledPstn:!1,forceRecvonly:!1,streamsBeforeSetFullRD:!1,setProperAnswerType:!1,connectTransport:!0,audioState:"active",dtlsRole:"",dtlsRolePstn:""},webrtcPranswerCheckAudioEnergy:!1,webrtcPranswerMediaPollingTimeout:500,webrtcPranswerWaitFinalAnswer:!1,webrtcPranswerAudioThreshold:0,webrtcPranswerWaitIntervalBeforePolling:500,webrtcPranswerStopPollingAfterError:!1,disableIncomingDtlsRoleOverride:!1,disableOutgoingDtlsRoleOverride:!1,statsAllowAnyVideoSendTrack:!1,pictureInPicture:{enablePictureInPicture:!1,aspectRatioHorizontal:16,aspectRatioVertical:9,maxActiveStreams:1,minStreamGridCellWidth:160,dominantStreamChangeDebounce:3e3,statisticsBufferSize:20,multiStreamWorkerURL:""},showStatsInCall:!1,useSetStreamsForSender:!0,addPrefixForMsidInSdp:!1,enableMuteSpeakerUnmuteSpeakerWorkaround:!1,alwaysRaiseBadDeviceEvents:!1,removeRecvStreamOnEnded:!0,requiredVideoCodecs:["h264"],primaryVideoCodecs:["h264","vp8","vp9"],removeUnsupportedVideoModality:!1,enableActiveSpeakerBasedDSH:!0,enableInitialSignalingDSHSubscription:!0,enableSignalingDSHFallback:!1,emptyInitialDSH:!0,bwPercentiles:[5,50,95],enableTimerTracker:!0,diagnostics:{sideBySide:!0,useForTelemetry:!1,collectWhileNotConnected:!1,traceLogging:!1,collectionLimits:{numOfHistogramSamples:100,numDeviceEvents:200,numVideoEffectsEvents:100,numAudioEffectsEvents:100,numOvershootEvents:100,numIsRenderingEvents:100,numStatsReports:600,numStatsErrors:100,numSubscriptionEvents:100,numPerformanceEvents:50,numUFDs:100,numNativeSessions:3,numSessions:3,numNetworkEvents:50,numReconnects:50,numReconnectRecords:20,numCapabilitiesRequested:60,numCapabilitiesApplied:60,numAudioCaptureErrors:100,numAudioRenderErrors:100,numResolutionSwitches:10,numSamplesForE2E:4,numWorkerEvents:50,numTransportStateEvents:100,numElevation:5,numVideoStatsAfterSubscription:30,numVideoSubscriptionStats:30,numPowerEfficientEncoderEvents:60},telemetryLimits:{numOfHistogramSamples:50,numDeviceEvents:40,numVideoEffectsEvents:20,numAudioEffectsEvents:30,numWorkerEvents:25,numOvershootEvents:20,numIsRenderingEvents:4,numPreferredResolutions:3,numSubscriptionEvents:100,numPerformanceEvents:30,numUFDs:50,numAggregatedSamples:60,numStatsErrors:20,numCapabilitiesRequested:5,numCapabilitiesApplied:3,numNetworkEvents:20,numReconnects:10,numRendererStateChangedEvents:10,numAuthTokenErrors:20,numPowerEfficientEncoderEvents:20},teamsRealtimeTelemetry:{pollingInterval:15},performanceMonitoring:{usePerfConstrainedOvc:!1,useCpuSample:!1,useComputePressure:!1,fluctuationSamplesNum:5,enableRemoteVideoCalculator:!1,enableLowerResolution:!1,monitoringStrategy:"decodeTime",decodeThresholds:{1080:{fps:30,maxDecodeTime:20},720:{fps:30,maxDecodeTime:15},540:{fps:30,maxDecodeTime:11},360:{fps:30,maxDecodeTime:9},234:{fps:15,maxDecodeTime:10},180:{fps:15,maxDecodeTime:10}},defaultThrehold:{fps:30,maxDecodeTime:60},fpsDiffThresholds:{1080:{fps:30,fpsDiff:4},720:{fps:30,fpsDiff:4},540:{fps:30,fpsDiff:4},360:{fps:30,fpsDiff:4},234:{fps:15,fpsDiff:2},180:{fps:15,fpsDiff:2}},defaultFpsDiffThreshold:{fps:30,fpsDiff:10},volatilityThresholds:{1080:10,720:10,540:10,360:10,234:5,180:5},defaultVolatilityThreshold:10,remoteVideoTrackInterval:10,telemetryResolutionRequestSpanMs:5e3,cpuMetricCollector:3},features:{takeFreezeTelemetryFromGathererV2:!0,useLastSampleDeltaPerSecondConverter:!1,useNewerStatisticsMetrics:!1,useNewNetworkUFD:!1,useNewSendBandwidthCalculation:!0,useNewStatsForLocalVideoStreamWatcher:!0,useFallbackToNewExtensions:!0,logContributingSourcesError:!0,useTwoSampleVBSSFreezeDetection:!1,useNewSimulcastTelemetryExtension:!1}},requireUserActionForAudioSharing:!1,postponeAudioMixerForAudioSharing:!1,reassignMediaStreamAudioTrackAfterCreation:!1,deactiveAudioSender:!1,webrtcForceSdesForS1:!1,webrctRemoveVideoModalitiesForPstn:!1,removeSendersOnConfigureModalities:!0,negotiationParallelStreamAcquisitionCreateOffer:!1,negotiationParallelStreamAcquisitionCreateAnswer:!1,streamAvailabilityConsiderModalities:!0,setBWSeed:!0,bwSeedOptions:{mids:["*"],aggregation:"last",aggregateLastN:null,constValue:6e5,minValue:-1,cappingValue:15e5,useLocalStorage:!0,localStorageKey:"bwSeed"},stopCallOnAcceptFailure:!0,allowMediaBypass:!0,enablePermissionsWorkaround:!1,disposeSendersSync:!1,disposeStreamsSync:!1,maxVideoStatsAfterSubscription:30,ecsConfigTimeout:2e4,contributingSourcesLogInterval:1e4,useNewTokenApi:!1,audioRendererFailedReconnectTimes:0,audioRendererFailedRetryCodes:[3],effectsApplyConstraintsRetryMs:1e3,isSpotlightEnabled:!0,addAudioStreamBeforeConnection:!1,redReceiveEnabled:!1,mediaEventDictionary:qt.MEDIA_EVENT_FIELDS,smallCallTelemetry:{enable:!1,mediaUFDEventDictionary:{}},applySenderParamsBeforeStart:!0,applyMaxCapabilitiesToSenderParamsDirectly:!1,reuseLastSetParameters:!0,hevcCodecs:["hev1.1.6.L120.90","hev1.1.4.L93.B0","hev1.1.6.L93.B0"],useInactiveAudioTrack:!1,enableRollbackHandler:!1,callElevationDelayReconnect:!1,callElevationDelayReconnectPSTN:!1,enableCachingFMTP:!0,enableCachingFMTPAwait:!1,enableCachingFMTPDelay:0,setDisconnectAfterCleanUp:!1,sendResolutionTableOverride:qt.RES_TABLE.SEND,recvResolutionTableOverride:qt.RES_TABLE.RECV,maxSendVideoCapabilitiesMultiparty:{enableForVideo:!0,enableForSharing:!1,useMaximumWidthHeight:!0,sendMaxMbps:!1,sendMaxFs:!1},participantStreamInitialSubscriptions:!0,holdRetryActivationDelay:-1,holdSkipActivation:!0,recoverOnStreamUnmute:!1,isAv1Allowed:!1,audioSharingMemoryLeakFix:!0,h264SdpProfileMultiparty:"64001f",rejectIncompatibleOriginator:!0,coeffOfValidTimeDelayBetweenFramesArrival:2,invalidFPSAboveMax:40,useWakeLockApi:!0,noRequiredCodecsWorkaround:!1,vdiDisconnectedTracking:{enabled:!0,clientPhrases:["failure"]},multiStreamSupported:!1,nonMultiStreamChannels:9,useTokenMigrationHeader:!1,clientSupportsAadToken:!1,clientSupportsCaeToken:!1,clientSupportsSkypeToken:!0,supportMissingTokenTypesInResponse:!0,useSkypeTokenWhenNoAuthenticateHeader:!1,useKeyFrameApi:!1,enablePlayVideoOnStreamUnmuteWorkaround:!1,useDeviceHandleForLocalVideo:!0,enableCallStateChangesOnPageClose:!0,remoteUFD:{enabled:!1,maxParticipantNumber:20,debounceTime:1e3,list:{}},fixOpusComfortNoise:!1,streamModalitiesExcludeData:!0,muteDuringRemotePranswer:!0,syncMuteStateWithAudioDirection:!1,permissionDeniedUFDWorkaround:!1,audioSetSinkIdWorkaround:!1,identifyOneToOneCallWithoutParticipants:!1,emptyIceCandidateMarksGatheredAnswerer:!1,disableSendersTroughSetParametersVideo:!1,disableSendersTroughSetParametersAudio:!1,maxNumberOfPinnedVideos:1,localUFDDebounceTime:0,audioSampleRate:0,lowBatteryThreshold:10}}getEnforcedSettings(){return{}}},Ny=class extends Dy{getInitialSettings(){const g=super.getInitialSettings();return g.oneStreamPerDeviceType=!0,g.removeUnsupportedVideoModality=!0,g.webrtcPranswerWaitForMediaPollingInterval=100,g.diagnostics.features.useLastSampleDeltaPerSecondConverter=!0,et.isFormFactor("Mobile")&&(g.webrtcCameraOpenFs=920,g.webrtcVideoCapabilityMaxFS=920),g}},ky=class extends Dy{getEnforcedSettings(){return{useAudioAnalyzer:!1,enableAudioSharing:!1}}},Ly=class extends Ny{getEnforcedSettings(){const g={webrtcSimulcastSessionEnabled:!0,webrtcAllowRestoreKeyframe:!0,permissions:{usePositiveInAdp:!1,useNegativeInAdp:!1,adpFallback:!0,adpFallbackAudio:!0,adpFallbackVideo:!1,adpRequestAVLast:!1,rememberNegative:!1},devices:{pollingIntervalIdle:1e4},audioRendererRestartOnPause:!0,subscribeToSsrcForVideo:!0,noRequiredCodecsWorkaround:!0,degradationPreference:"maintain-framerate"};return et.isVersionGreaterOrEqual("15.0")||(g.statsAllowAnyVideoSendTrack=!0),et.isVersionGreaterOrEqual("16.0")&&et.isFormFactor("Mobile")&&(g.enablePermissionsWorkaround=!0),et.isVersionGreaterOrEqual("17.0")&&et.isFormFactor("Mobile")&&(g.recoverOnStreamUnmute=!0,g.enablePlayVideoOnStreamUnmuteWorkaround=!0),g}},Fy=class extends Ny{getEnforcedSettings(){return{webrtcSimulcastSessionEnabled:!0,webrtcAllowRestoreKeyframe:!0,useDtlsTrasportConnectionCheck:!0,videoIsRenderingCheck:!1,fixSdpForPartialIceRestart:!0,mapSsrcToTrackForStats:!0,ignoreClosedDtlsTransportState1on1:!0,subscribeToSsrcForVideo1on1:!0,devices:{enumerateDevicesTimeout:0,pollingIntervalIdle:1e4,idlePollingOnStart:!0},webrtcInjectTransportCCAudioMultiparty:!1,videoCaptureFreezeTimeout:0,filterCodecsInSdp:!0,useSetParametersToApplyCapabilities:!0,removeRecvStreamOnEnded:!0,webrtcDisabledSenderBitrate:0,disableAudioOutputSelection:!0,permissionDeniedUFDWorkaround:!0}}},xy=class extends Dy{getEnforcedSettings(){const g={checkSupportForWebrtc_1_0:!1,requireUserActionForAudioSharing:!0,webrtcSimulcastSessionEnabled:!0,webrtcAllowRestoreKeyframe:!0,useAudioAnalyzer:!1,enablePlatformCallConstraints:!0,specCompliantSimulcastMultiparty:{video:{layerScaleFactors:[1,2],enableLocally:!0,allowEnableRemotely:!0},maxBrControlEnabled:!0,allowResLimit:!0,allowOverride:!0,disableTilde:!1},extmapAllowMixedMultiparty:!0,enableVlaMultiparty:!0,allowRemoteVlaMultiparty:!0,enableNonAdvVlaMultiparty:!0,useMediaQualityControllerMultiparty:!0,useSdpCapabilities:!1,enableRollbackHandler:!0,allowedAudioCodecs:[{channels:2,clockRate:48e3,mimeType:"audio/opus"},{channels:1,clockRate:8e3,mimeType:"audio/G722"},{channels:1,clockRate:8e3,mimeType:"audio/PCMU"},{channels:1,clockRate:8e3,mimeType:"audio/PCMA"},{channels:1,clockRate:8e3,mimeType:"audio/CN"},{channels:1,clockRate:8e3,mimeType:"audio/telephone-event"}]};return"43"===getVdiPlatform()&&(g.postponeAudioMixerForAudioSharing=!0,g.enableAudioSharing=!0,g.filterCodecsInSdp=!0,g.webrtcPranswerWaitForMediaPollingInterval=250,g.specCompliantSimulcastMultiparty.video.useApplyConstraints=!1,g.localPreviewMirroringSupported=!0,g.webrtcContributingSourcesPollingStartDelay=3e3),"44"===getVdiPlatform()&&(g.postponeAudioMixerForAudioSharing=!0,g.enableAudioSharing=!0,g.disposeSendersSync=!0,g.disposeStreamsSync=!0,g.filterCodecsInSdp=!0,g.useInactiveAudioTrack=!0,g.specCompliantSimulcastMultiparty.video.useApplyConstraints=!0,g.specCompliantSimulcastMultiparty.video.minFsForSimulcast=[920],g.webrtcPranswerWaitForMediaPollingInterval=250,g.webrtcContributingSourcesPollingStartDelay=5e3),"45"===getVdiPlatform()&&(g.setParametersMaxBitrateUndefined=!0,g.specCompliantSimulcastMultiparty.video.useApplyConstraints=!0,g.specCompliantSimulcastMultiparty.video.minFsForSimulcast=[920]),g}},Uy=class extends Ny{getEnforcedSettings(){const g={};return et.isVersionGreaterOrEqual("74.0")&&(g.webrtcSimulcastSessionEnabled=!0,g.webrtcAllowRestoreKeyframe=!0,g.enableAudioSharing=!0),et.isVersionGreaterOrEqual("122.0")&&(g.useKeyFrameApi=!0),et.isFormFactor("RoomAudioProcessing")&&(g.defaultAudioProcessingFlags=0,g.wasmvqe={enableAec:!1,enableVqe:!1,backgroundMode:!1},g.wasmdns={enableNoiseSuppression:!1,backgroundMode:!1}),(et.isBrowser("CiscoOS")||et.isBrowser("ZoomRoom"))&&(g.waitReportStatsAtCallStop=!0,g.setDisconnectAfterCleanUp=!0),et.isFormFactor("Mobile")&&(g.enableAudioSharing=!1,g.audioRendererFailedReconnectTimes=3,g.devices={pollingIntervalIdle:1e4}),et.isBrowser("SamsungTV")&&(g.useSetParametersToApplyCapabilities=!0),et.isVersionGreaterOrEqual("98.0")&&et.isFormFactor("Desktop")&&(g.specCompliantSimulcastMultiparty={video:{layerScaleFactors:[1,2],enableLocally:!0,allowEnableRemotely:!0,useApplyConstraints:!0,minFsForSimulcast:[920]},maxBrControlEnabled:!0,allowResLimit:!0,disableTilde:!1},g.extmapAllowMixedMultiparty=!0,g.enableVlaMultiparty=!0,g.allowRemoteVlaMultiparty=!0,g.enableNonAdvVlaMultiparty=!0,g.useMediaQualityControllerMultiparty=!0),et.isVersionGreaterOrEqual("100.0")&&(g.redReceiveEnabledMultiparty=!0),g.webcv={useWasmEffects:!0,processorType:lr.ProcessorType.Wasm},g}},Vy=class{constructor(g){this.settings=g,this.isTransportUnbundled=!1,this.webrtcRejectedFeatures="",this.webrtcRequiredFeatures="",this.spatialAudioEnabled=!1,this._maxBandwidthInKbps=0,this._noiseSuppressionMode="Auto",this._enableMediaBypass=!1,this.audioContext={enabledLocally:!1,disabledRemotely:!1,enabledForSend:!1,initFailed:!1,initSendFailed:!1,codec:"None",lastUsedCodec:"None"}}setMediaConfiguration(g,f){this.maxBandwidthInKbps=Math.floor((g.maxBandwidthInBps||0)/1e3),this.isTransportUnbundled=this.settings.forceUnbundledTransport||this.settings.enableQosSupport&&(g.enableMediaQoS||!!g.mediaPortRanges),this._mediaPortRanges=g.mediaPortRanges,this.simulcastSessionEnabled=this.settings.webrtcSimulcastSessionEnabled&&canUseWebrtc1_0(this.settings.checkSupportForWebrtc_1_0),this._noiseSuppressionMode=g.noiseSuppressionMode||"Auto",this._enableMediaBypass=this.settings.allowMediaBypass&&g.enableMediaBypass,this.webrtcRejectedFeatures=this._enableMediaBypass?"":this.settings.webrtcRejectedFeatures,this.webrtcRequiredFeatures=this._enableMediaBypass?"":this.settings.webrtcRequiredFeatures,this.spatialAudioEnabled=f?f.spatialAudioEnabled:g.enableSpatialAudio}get mediaBypassEnabled(){return this._enableMediaBypass}get noiseSuppressionMode(){return this._noiseSuppressionMode}get maxBandwidthInKbps(){return this._maxBandwidthInKbps}set maxBandwidthInKbps(g){this._maxBandwidthInKbps=g,this.settings.maxBandwidthInKbps&&(this._maxBandwidthInKbps=Math.min(this.settings.maxBandwidthInKbps,this._maxBandwidthInKbps||Number.MAX_SAFE_INTEGER))}get audioPortRange(){if(this.isTransportUnbundled&&this._mediaPortRanges&&this._mediaPortRanges.audioMin&&this._mediaPortRanges.audioMax)return{min:this._mediaPortRanges.audioMin,max:this._mediaPortRanges.audioMax}}get videoPortRange(){if(this.isTransportUnbundled&&this._mediaPortRanges&&this._mediaPortRanges.videoMin&&this._mediaPortRanges.videoMax)return{min:this._mediaPortRanges.videoMin,max:this._mediaPortRanges.videoMax}}get audioCodecContext(){return this.settings.useInsertableStreams?.audioWasmCodec?.enable?this.audioContext:void 0}},By=class extends Ht{constructor(g,f,S={}){super(g),this.logger=g,this.platformCallConstraintsProvider=f,this.platformConfig=getPlatformConfig(),this.sessionCount=0,this._consoleOverrides={},this.uaConfig=new oa(this),this.mediaConfiguration={},this.configReceivedDefer=new dt,this.logger.info(`initializing configProvider ${this.constructor.name} from BrowserInfo: ${et.toString()}`),this.initialSettings=(0,No.mergeWith)({},(0,No.cloneDeep)(this.platformConfig.getInitialSettings()),(0,No.cloneDeep)(S),this.platformConfig.getEnforcedSettings(),arrayMergeCustomizer2),this.settings=this.initialSettings,this.settingsWithoutOverrides=this.initialSettings,this.stackSettings=(0,No.cloneDeep)(S),this.mediaSettings=new Vy(this.settings),this.platformCallConstraintsProvider.changed((()=>{this.updateSettings();const g=this.platformCallConstraintsProvider.constraints,f=this.logger.createChild("SettingsToCallConstraintsConverter"),S=convertSettingsToCallConstraints(f,this.settings,g);this.platformCallConstraintsProvider.addCallConstraintsTelemetryEvent(S,"applied")})),this.configReceivedTimeout=window.setTimeout((()=>{this.configReceivedTimeout=void 0,this.configReceivedDefer.resolve()}),this.settings.ecsConfigTimeout),this.logger.safe.info("Initialized")}getCallConstraints(){return this.platformCallConstraintsProvider.constraints}setCallConstraints(g){return this.platformCallConstraintsProvider.setConstraints(g),g}getCallConstraintsTelemetry(){return this.logger.error("Not supported globally, returning empty array"),[]}addCallConstraintsTelemetryEvent(g,f){this.logger.error("Not supported globally")}overrideMaxSessionBandwidth(g){return this.logger.error("Not supported globally"),!1}getIceTransportPolicy(){return this.logger.warn(`Not supported globally, returning default ${qt.ICE_TRANSPORT_POLICY.all}`),qt.ICE_TRANSPORT_POLICY.all}setIceTransportPolicy(g){this.logger.error("Not supported globally")}getConfigReceivedOrTimeout(){return this.configReceivedDefer.promise}getConfigView(g,f){const S=g?"Multiparty":"1on1",v=Object.entries((0,No.cloneDeep)(this.settings)).reduce(((g,[f,v])=>(g[f]=v,f.endsWith(S)&&(g[f.replace(S,"")]=v),g)),{}),C=new Vy(v);return C.setMediaConfiguration(this.mediaConfiguration,f?.mediaConfig),new ma(this.logger.createChild("ConfigProviderView"),v,C,this.userAgentConfig,this.countryCode,this.platformCallConstraintsProvider,f?.getCallConstraints())}updateConfig(g,f,S,v){this.etag=f||this.etag,this.configIds=S||this.configIds,this.country=v||this.country,this.event("newConfigReceived").raise(g,f,S),this.settingsWithoutOverrides=(0,No.mergeWith)({},this.settingsWithoutOverrides,g,arrayMergeCustomizer2),this.updateSettings(),this.configReceivedTimeout&&(window.clearTimeout(this.configReceivedTimeout),this.configReceivedTimeout=void 0),this.configReceivedDefer.resolve()}updateSessionCount(g){this.sessionCount=g,0===g&&this.pendingSettings&&(this.logSettings("Applying pending configuration",this.pendingSettings),this.updateSettings(this.pendingSettings),this.pendingSettings=null),g>0&&this.configReceivedTimeout&&this.configReceivedDefer.resolve()}get config(){return this.settings}get stackConfig(){return this.stackSettings}get consoleOverrides(){return this._consoleOverrides}get defaultConfig(){return this.initialSettings}get userAgentConfig(){return this.uaConfig}get countryCode(){return this.country}setMediaConfiguration(g){this.mediaConfiguration=g,this.mediaSettings.setMediaConfiguration(g)}get mediaConfig(){return this.mediaSettings}get ETag(){return this.etag}get ecsConfigIds(){return this.configIds}setConsoleOverrides(g){this._consoleOverrides=(0,No.mergeWith)({},this._consoleOverrides,g,arrayMergeCustomizer2),this.updateSettings()}setConsoleOverride(g,f){this._consoleOverrides[g]=f,this.updateSettings()}clearConsoleOverride(g){delete this._consoleOverrides[g],this.updateSettings()}clearAllConsoleOverrides(){this._consoleOverrides={},this.updateSettings()}updateSettings(g=this.settingsWithoutOverrides){if(this.sessionCount>0)return this.pendingSettings=g,void this.logSettings("pendingSettings updated",g);this.settings=this.mergeSettings(g),this.event("configUpdated").raise(),this.logSettings("Settings updated",this.settings)}logSettings(g,f){const S=Object.entries(f).reduce(((g,[f,S])=>(S!==this.initialSettings[f]&&(g[f]=S),g)),{});this.logger.safe.info(`${g}: ${JSON.stringify(S)}`)}mergeSettings(g){if(!(g.enablePlatformCallConstraints||this._consoleOverrides.enablePlatformCallConstraints))return this.mergeSettingsWithConsoleOverrides(g);let f=g;const{setConsoleOverridesBeforeCallConstraints:S}=this._consoleOverrides;return S&&(f=this.mergeSettingsWithConsoleOverrides(f)),f=this.mergeSettingsWithPlatformConstraints(f),S||(f=this.mergeSettingsWithConsoleOverrides(f)),f}mergeSettingsWithConsoleOverrides(g){return this.logger.safe.info(`Merging settings with console overrides: ${stringifyObject(this._consoleOverrides)}`),(0,No.mergeWith)({},g,this._consoleOverrides,arrayMergeCustomizer2)}mergeSettingsWithPlatformConstraints(g){const f=this.platformCallConstraintsProvider.getSettings(g);return this.logger.safe.info(`Merging settings with platform call constraints: ${stringifyObject(f)}`),(0,No.assign)({},g,f,arrayMergeCustomizer2)}},Hy=class{constructor(){this.data={clientDSH:void 0,signalingDSH:void 0,serverDSH:void 0,activeStrategy:void 0,lastMsgOrigin:void 0,changedCountContributingSources:0,changedCountDSH:0}}contributingSourcesChanged(){this.data.changedCountContributingSources++}setCurrentActiveStrategy(g){this.data.activeStrategy=g}resetState(){return this.data.lastMsgOrigin=void 0,this}recordHistoryEvent(g,f){var S,v;this.data.changedCountDSH++,(S=this.data)[v=f+"DSH"]??(S[v]={count:0,duplicateCount:0}),this.data.lastMsgOrigin=f;const C=this.data[f+"DSH"];C.count++,C.firstMsgTime??(C.firstMsgTime=Date.now()),deepEqual(this.data.lastHistory,g)&&C.duplicateCount++,this.data.lastHistory=g,this.data.lastMsgDate=Date.now()}getObjectRef(){return this.data}},$y=class{constructor(g,f,S,v,C,_,T,I){this.mediaStream=g,this.receiver=f,this.modality=S,this.sourceStreamId=v,this.controller=C,this.videoCapabilities=_,this.getMaxAllowedVideoFS=T,this.substreamIndex=I,this.msi=-1,this.operations=Promise.resolve()}dispose(){this.receiver=null,this.mediaStream=null}getId(){return this.mediaStream.id}getModality(){return this.modality}getMsi(){return this.msi}getMediaStream(){return this.mediaStream}getReceiver(){return this.receiver}getSourceStreamId(){return this.sourceStreamId}getSubstreamIndex(){return this.substreamIndex}requestSource(g){this.msi=g;const f=this.operations.then((()=>{let f;return this.videoCapabilities&&(this.videoCapabilities.resetToInitial(),this.getMaxAllowedVideoFS&&this.videoCapabilities.setMaxFS(Math.min(this.getMaxAllowedVideoFS(),this.videoCapabilities.getMaxFS())),f=this.videoCapabilities.buildFmtp(),this.videoCapabilities.resetToInitial()),this.controller.requestSource(this.mediaStream.id,g,f)}));return this.operations=f.catch((()=>{})),f}},jy=class{constructor(g){this.subscription=g}get subscribedStream(){return this.subscription.stream?.getMediaStream()}get msi(){return this.checkDisposed(),this.subscription.msi}get modality(){return this.checkDisposed(),this.subscription.modality}get localMsi(){return this.checkDisposed(),this.subscription.localMsi}setOnMediaStreamChangedHandler(g){this.checkDisposed(),this.mediaStreamChanged=g,this.subscription.isStreamReady&&this.notifyMediaStreamChanged()}setOnErrorHandler(g){this.checkDisposed(),this.error=g}dispose(){this.subscription&&(this.subscription.dispose(generateCauseId(),this),this.subscription=null)}unsubscribe(){this.subscription&&(this.subscription.unsubscribe(),this.subscription=null)}notifyMediaStreamChanged(){if(this.mediaStreamChanged){const g=this.subscription.stream,f=this.subscription.isStreamReady;this.mediaStreamChanged(g&&f?g.getMediaStream():null)}}notifyError(g){this.error&&this.error(g)}checkDisposed(){if(!this.subscription)throw new Error("subscription disposed")}},Gy=class extends Ht{constructor(g,f,S){super(),this.modality=g,this.msi=f,this.disposeDelay=S,this.clients=[],this.streamReady=!1}createClient(){const g=new jy(this);return this.clients.push(g),g}get isStreamReady(){return this.streamReady}get localMsi(){return this.subStream?.getSourceStreamId()}get isInactive(){return!this.clients.length}get stream(){return this.subStream}set stream(g){try{if(g===this.subStream)return;this.subStream&&(this.unsubscribe(!1),this.notifyStreamChanged()),this.subStream=g,g&&(this.streamReady=!1,g.requestSource(this.msi).then((()=>{this.streamReady=!0,this.notifyStreamChanged()})).catch((g=>{this.notifyError(g)})))}catch(g){this.event("onFailed").raise(this,g)}}notifyError(g){this.clients.forEach((f=>{f.notifyError(g)})),this.event("onFailed").raise(this,g)}dispose(g,f){f?(remove2(this.clients,(g=>g===f)),this.isInactive&&(this.disposeTimeout=window.setTimeout((()=>{this.disposeTimeout=null,this.unsubscribeIfInactive()}),this.disposeDelay))):(this.clients=[],this.unsubscribe())}unsubscribeIfInactive(){this.isInactive&&(this.disposeTimeout&&clearTimeout(this.disposeTimeout),this.unsubscribe())}unsubscribe(g=!0){this.subStream&&(this.subStream.requestSource(-1).catch((()=>{})),this.streamReady=!1,this.subStream=null),g&&this.event("onDisposed").raise(this)}notifyStreamChanged(){this.clients.forEach((g=>g.notifyMediaStreamChanged())),this.event("onStreamChanged").raise()}},qy=class extends Ht{constructor(g,f,S,v){super(g),this.configProvider=f,this.diagnostics=v,this.videoSubscriptions=[],this.isMcpSrAvailable=!1,this.subscriptionEvents=new Map,this.setLogger(g),this.diagnostics??(this.diagnostics=new Wy(this.configProvider,(()=>{}))),this.setStreamProvider(S),this.logger.safe.info("created")}getSubscriptionsCount(){return this.videoSubscriptions.filter((g=>g.isStreamReady)).length}setStreamProvider(g){this.streamProvider=g,this.streamProvider.setOnStreamsChangedHandler((()=>this.streamsChanged()))}setLogger(g){this.logger=g}subscribeVideo(g,f=-2){let S=this.videoSubscriptions.find((S=>S.msi===f&&S.modality===g)),v=this.getAvailableStream(g);if(S)!S.stream&&v?this.assignStream(S,v):this.logger.safe.info(`subscription #${f} for modality ${g} already exists, stream assigned: ${!!S.stream}`);else{const C=Date.now();this.disposeInactiveSubscriptionIfNeeded(g),v=this.getAvailableStream(g);const _=v?.getSourceStreamId();this.logger.safe.info(`creating new subscription #${f} for modality ${g}`),this.event("onSubscriptionChanged").raise(1,g,f,_,null),this.diagnostics.addSubscribe(g,f,_),S=new Gy(g,f,this.configProvider.config.webrtcVideoSubscriptionDisposeTimeout);const T=[];T.push(S.on("onDisposed",(g=>this.onSubscriptionDisposed(g)))),T.push(S.on("onStreamChanged",(()=>{const v=S.stream?.getId(),_=S.localMsi;if(this.updateTrackIds(),S.isStreamReady){const S=Date.now();this.event("onSubscriptionChanged").raise(2,g,f,_,S-C,v),this.diagnostics.addSubscribed(g,f,_,S-C)}}))),T.push(S.on("onFailed",((g,f)=>this.onSubscriptionFailed(g,f)))),this.subscriptionEvents.set(S,T),this.videoSubscriptions.push(S),v?this.assignStream(S,v):this.logger.safe.info(`waiting for available stream for subscription #${f}`)}return S.createClient()}dispose(){const g=generateCauseId();this.videoSubscriptions.concat().forEach((f=>f.dispose(g))),this.streamProvider.setOnStreamsChangedHandler(null),super.dispose(),this.logger.safe.info("disposed")}reriseSubscribeEvents(){this.logger.safe.info(`rerising subscription events: ${this.videoSubscriptions.length}`);const g=[];this.videoSubscriptions.forEach((f=>{const S=f.modality,v=f.msi,C=f.localMsi;this.event("onSubscriptionChanged").raise(1,S,v,C),this.diagnostics.addSubscribe(S,v,C),g.push(...this.getSubscriptionVideoTrackIds(f))})),this.diagnostics.subscribedTrackIds=g}setDiagnostics(g){this.diagnostics=g??new Wy(this.configProvider,(g=>{this.logger.safe.warn(`Unhandled stats error from inactive subscription manager: ${g}`)}))}streamChangedByMsi(g){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`);const f=this.videoSubscriptions.find((f=>f.msi===g));f?this.assignSubscriptionToStream(f):this.logger.safe.error(`Subscription for msi ${g} not found`)}mcpSourceRequestsAvailable(){this.isMcpSrAvailable=!0}streamsChanged(){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`),this.videoSubscriptions.forEach((g=>{this.assignSubscriptionToStream(g)}))}assignSubscriptionToStream(g){const f=!g.stream||this.isStreamRemoved(g.stream);if(this.logger.safe.info(`Subscription for ${g.modality} #${g.msi} needs new stream: ${f}`),!f)return;const S=this.getAvailableStream(g.modality);S?this.assignStream(g,S):this.resignStream(g)}getAvailableStream(g){let f=this.streamProvider.getStreams();return"video"===g&&!this.isMcpSrAvailable&&this.configProvider.config.multiStreamSupported&&(f=f.filter((g=>void 0===g.getSubstreamIndex()))),f.find((f=>g===f.getModality()&&-1===f.getMsi()))}isStreamRemoved(g){return!this.streamProvider.getStreams().some((f=>f===g))}assignStream(g,f){this.logger.safe.info(`assigning stream #${f.getId()} to subscription #${g.msi}`),g.stream=f}resignStream(g){if(g.stream)this.logger.safe.info(`removing stream from subscription #${g.msi}`),g.stream=null;else{const f=this.streamProvider.getStreams().filter((f=>g.modality===f.getModality()&&-1!==f.getMsi())).length;this.logger.safe.warn(`no stream available for ${g.modality} #${g.msi}, ${g.modality} used stream count: ${f}`)}}disposeInactiveSubscriptionIfNeeded(g){this.getAvailableStream(g)||this.videoSubscriptions.find((f=>f.modality===g&&f.isInactive))?.unsubscribeIfInactive()}onSubscriptionDisposed(g){const f=generateCauseId(),S=g.modality,v=g.msi,C=g.localMsi;this.event("onSubscriptionChanged").raise(3,S,v,C),this.diagnostics.addUnsubscribe(S,v,C),this.logger.safe.info(`disposing subscription for ${S} #${v}`),remove2(this.videoSubscriptions,(f=>f===g)),this.streamsChanged(),this.updateTrackIds(),this.subscriptionEvents.has(g)&&(this.subscriptionEvents.get(g).forEach((g=>g.dispose(f))),this.subscriptionEvents.delete(g))}updateTrackIds(){const g=[],f=[];this.videoSubscriptions.forEach((S=>{if(!S.isStreamReady)return;const v=S.stream?.getId().split("-")[1];f.push(v),g.push(...this.getSubscriptionVideoTrackIds(S))})),this.event("onTrackIdsChanged").raise(g),this.diagnostics.subscribedTrackIds=g,this.configProvider.config.subscribeToSsrcForVideo&&this.event("onTrackSsrcChanged").raise(f)}getSubscriptionVideoTrackIds(g){return g?.stream?.getMediaStream()?.getVideoTracks().map((g=>g.id))??[]}onSubscriptionFailed(g,f){this.event("onSubscriptionFailed").raise(-1,g.modality,g.msi,g.localMsi,f),this.diagnostics.addFailed(g.modality,g.msi,g.localMsi,stringifyObject(f))}},Wy=class{constructor(g,f){this.configProvider=g,this.addStatsError=f,this.data={video:{events:[],counters:{attempted:0,subscribed:0,unsubscribed:0,failed:0}},sharing:{events:[],counters:{attempted:0,subscribed:0,unsubscribed:0,failed:0}},subscribedTrackIds:[]}}set subscribedTrackIds(g){this.data.subscribedTrackIds=g}addSubscribe(g,f,S){const v=this.getModalityData(g);if(v){const g={evt:1,msi:f,localMsi:S,ts:Date.now()};arrayLimitedPush2(v.events,g,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),v.counters.attempted++}}addSubscribed(g,f,S,v){const C=this.getModalityData(g);if(C){const g={evt:2,msi:f,localMsi:S,ts:Date.now(),duration:v};arrayLimitedPush2(C.events,g,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),C.counters.subscribed++}}addUnsubscribe(g,f,S){const v=this.getModalityData(g);if(v){const g={evt:3,msi:f,localMsi:S,ts:Date.now()};arrayLimitedPush2(v.events,g,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),v.counters.unsubscribed++}}addFailed(g,f,S,v){const C=this.getModalityData(g);if(C){const g={evt:-1,msi:f,localMsi:S,ts:Date.now(),error:v};arrayLimitedPush2(C.events,g,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),C.counters.failed++}}getObjectRef(){return this.data}getModalityData(g){switch(g){case qt.MEDIA_TYPE.video:return this.data.video;case qt.MEDIA_TYPE.sharing:return this.data.sharing;default:return void this.addStatsError(`Unsupported modality ${g}`)}}},zy=class{constructor(g,f){this.configProvider=g,this.addStatsError=f,this.data={videoMaxCapabilitiesEvents:[],videoMaxCapabilitiesErrors:[],sharingMaxCapabilitiesEvents:[],sharingMaxCapabilitiesErrors:[],currentVideoSsrcRequestedCapabilities:{},currentVideoSsrcAppliedCapabilities:{},currentSharingSsrcRequestedCapabilities:{},currentSharingSsrcAppliedCapabilities:{},numVideoControlMessages:0,numOutOfOrderVideoControlMessages:0,numWebcamFreezeIntervals:0,numProcessedStreamFreezeIntervals:0}}onMaxCapabilitiesRequested(g){const f={causeId:g.causeId,events:[{eventType:"req",timestamp:Date.now(),capabilities:g.capabilities,isSimulcast:g.isSimulcastEnabled}]};try{if(g.modality===qt.MODALITY.video){arrayLimitedPush2(this.data.videoMaxCapabilitiesEvents,f,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested),this.data.currentVideoSsrcRequestedCapabilities={};for(const f of g.capabilities)this.data.currentVideoSsrcRequestedCapabilities[`${f.ssrc??0}`]=f}else if(g.modality===qt.MODALITY.sharing){arrayLimitedPush2(this.data.sharingMaxCapabilitiesEvents,f,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested),this.data.currentSharingSsrcRequestedCapabilities={};for(const f of g.capabilities)this.data.currentSharingSsrcRequestedCapabilities[`${f.ssrc??0}`]=f}}catch(g){this.addStatsError?.("onMaxCapabilitiesRequested",stringifyObject(g))}}onMaxCapabilitiesApplied(g){try{const f=this.getEventForCause(g.modality,g.causeId),S={eventType:"app",timestamp:Date.now(),capabilities:g.capabilities,error:`${g.error}`||"none"};if(f&&(arrayLimitedPush2(f.events,S,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1),g.error&&(g.modality===qt.MODALITY.video?arrayLimitedPush2(this.data.videoMaxCapabilitiesErrors,f,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1):g.modality===qt.MODALITY.sharing&&arrayLimitedPush2(this.data.sharingMaxCapabilitiesErrors,f,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1))),g.modality===qt.MODALITY.video){this.data.currentVideoSsrcAppliedCapabilities={};for(const f of g.capabilities)this.data.currentVideoSsrcAppliedCapabilities[`${f.ssrc??0}`]=f}else if(g.modality===qt.MODALITY.sharing){this.data.currentSharingSsrcAppliedCapabilities={};for(const f of g.capabilities)this.data.currentSharingSsrcAppliedCapabilities[`${f.ssrc??0}`]=f}}catch(g){this.addStatsError?.("onMaxCapabilitiesApplied",stringifyObject(g))}}addVideoControlMessage(g=!1){this.data.numVideoControlMessages++,g&&this.data.numOutOfOrderVideoControlMessages++}getObjectRef(){return this.data}registerWebcamFreeze(){this.data.numWebcamFreezeIntervals++}registerProcessedStreamFreeze(){this.data.numProcessedStreamFreezeIntervals++}getEventForCause(g,f){return(g===qt.MODALITY.video?this.data.videoMaxCapabilitiesEvents:this.data.sharingMaxCapabilitiesEvents).find((g=>g.causeId===f))}},Ky=class{constructor(g){this.configProvider=g,this.data={renderers:[],firstTimeToFirstFrameVideo:-1,firstTimeToFirstFrameSharing:-1,timeToFirstFrameSinceSubscriptionStartVideo:-1,timeToFirstFrameSinceSubscriptionStartSharing:-1,isRenderingEvents:{video:[],sharing:[]},preferredResolution:{video:void 0,sharing:void 0}}}setTimeToFirstFrame(g,f){-1!==g&&(f===qt.MODALITY.video&&-1===this.data.firstTimeToFirstFrameVideo?this.data.firstTimeToFirstFrameVideo=g:f===qt.MODALITY.sharing&&-1===this.data.firstTimeToFirstFrameSharing&&(this.data.firstTimeToFirstFrameSharing=g))}setTimeToFirstFrameSinceSubscriptionStart(g,f){-1!==g&&(f===qt.MODALITY.video&&-1===this.data.timeToFirstFrameSinceSubscriptionStartVideo?this.data.timeToFirstFrameSinceSubscriptionStartVideo=g:f===qt.MODALITY.sharing&&-1===this.data.timeToFirstFrameSinceSubscriptionStartSharing&&(this.data.timeToFirstFrameSinceSubscriptionStartSharing=g))}setIsRendering(g,f){this.data.isRenderingEvents[f]&&arrayLimitedPush2(this.data.isRenderingEvents[f],{isRendering:g,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents)}setPreferredResolution(g,f){(g.width||g.height)&&(this.data.preferredResolution[f]=g)}newRendererDiagnostics(){const g=new Jy(this,this.configProvider),f=g.on("onDisposed",(()=>{this.removeDeadRenderers(),f.dispose()}));return this.data.renderers.push(g.getObjectRef()),g}getObjectRef(){return this.data}removeDeadRenderers(){this.data.renderers=this.data.renderers.filter((g=>g.alive))}},Jy=class extends Ht{constructor(g,f){super(),this.managerDiagnostics=g,this.configProvider=f,this.isAlive=!0,this.data={alive:!0,totalFreezeDuration:0,isRendering:!1,timeToFirstFrame:-1,timeToFirstFrameSinceSubscriptionStart:-1,rendererStates:[]},delete this.data.alive,Object.defineProperty(this.data,"alive",{get:()=>this.isAlive,enumerable:!1,configurable:!1})}set trackId(g){this.data.trackId=g}set rendererSize(g){this.data.rendererSize=g,g.toString=()=>`${g.width}x${g.height}`,this.managerDiagnostics.setPreferredResolution(g,this.data.modality)}set msi(g){this.data.msi=g}set modality(g){this.data.modality=g}set isRendering(g){this.data.isRendering=g,this.managerDiagnostics.setIsRendering(g,this.data.modality)}set timeToFirstFrame(g){this.data.timeToFirstFrame=g,this.managerDiagnostics.setTimeToFirstFrame(g,this.data.modality)}set timeToFirstFrameSinceSubscriptionStart(g){this.data.timeToFirstFrameSinceSubscriptionStart=g,this.managerDiagnostics.setTimeToFirstFrameSinceSubscriptionStart(g,this.data.modality)}addFreezeDuration(g){this.data.totalFreezeDuration+=g}addStateChange(g){arrayLimitedPush2(this.data.rendererStates,g,this.configProvider.config.diagnostics.telemetryLimits.numRendererStateChangedEvents)}dispose(){this.isAlive=!1,this.event("onDisposed").raise()}getObjectRef(){return this.data}},Yy=M,Qy=__toESM(we()),Xy=M;function fmtParamsToString(g){let f="";return forOwn(g,((g,S)=>{f+=(f?";":"")+S,void 0!==g&&(f+=`=${g}`)})),f}var Zy=class{constructor(g){this.parameters={},g&&g.split(";").forEach((g=>{const f=g.split("=");this.parameters[f[0]]=f[1]}))}setIfMissing(g,f){this.contains(g)||(this.parameters[g]=f)}removeIfPresent(g){this.contains(g)&&delete this.parameters[g]}get(g){return this.parameters[g]}names(){return Object.keys(this.parameters)}contains(g){return this.parameters.hasOwnProperty(g)}toString(){return fmtParamsToString(this.parameters)}};function updatePayload(g,f,S){if(!g.rtp)return;const v=g.rtp.filter((g=>g.payload===f))[0];v&&forOneCodec(g,{codec:v.codec,rate:v.rate,payload:v.payload,encoding:v.encoding},(g=>(g.rtp.payload=S,g)))}function findAvailablePayload(g){const f=new Set;for(const S of g.media)for(const g of S.rtp??[])f.add(g.payload);const S=[96,127];for(let g=S[0];g<=S[1];g++)if(!f.has(g))return g;const v=[35,64];for(let g=v[0];g<=v[1];g++)if(!f.has(g))return g;return-1}function findAllAvailablePayloads(g,f){const S=new Set,v=[];for(const f of g.media)for(const g of f.rtp??[])S.add(g.payload);for(let g=f[0];g<=f[1];g++)S.has(g)||v.push(g);return v}function forOneCodec(g,f,S,v){forCodec(g,f,!0,v,S)}function forAllCodecs(g,f,S,v){forCodec(g,f,!1,v,S)}function forCodec(g,f,S,v=!0,C){if(g.rtp){for(let _=0;_<g.rtp.length;_++){const T=g.rtp[_],I=T.payload;if(f.codec.toLowerCase()!==T.codec.toLowerCase()||f.rate!==T.rate||f.encoding!==T.encoding||f.payload&&f.payload!==T.payload)continue;const b={rtp:T};g.fmtp||(g.fmtp=[]);const A=g.fmtp.find((g=>T.payload===g.payload));b.fmtp=A,g.rtcpFb||(g.rtcpFb=[]),b.rtcpFb=g.rtcpFb.filter((g=>g.payload===T.payload));const P=b.rtcpFb.length>0;if(null===C(b))g.payloads=g.payloads.toString().split(" ").filter((g=>T.payload!==+g)).join(" "),g.fmtp=g.fmtp.filter((g=>T.payload!==g.payload)),g.rtcpFb=g.rtcpFb.filter((g=>T.payload!==g.payload)),g.rtp[_]=null;else{if(b.rtp.payload!==I){const f=b.rtp.payload;g.payloads=g.payloads.toString().split(" ").map((g=>+g===I?f:+g)).join(" "),b.fmtp&&(b.fmtp.payload=f),b.rtcpFb&&b.rtcpFb.forEach((g=>g.payload=f)),v&&g.fmtp.filter((g=>g.config&&g.config.indexOf(`apt=${I}`)>-1)).forEach((g=>g.config=g.config.replace(`apt=${I}`,`apt=${f}`)))}!A&&b.fmtp&&g.fmtp.push(b.fmtp),!P&&b.rtcpFb&&b.rtcpFb.forEach((f=>g.rtcpFb.push(f)))}if(S)break}g.rtp=g.rtp.filter((g=>!!g))}}function removeCodec(g,f){if(!g.rtp)return;let S=-1;if(g.rtp.forEach((function(g,v){f.codec.toLowerCase()!==g.codec.toLowerCase()||f.rate!==g.rate||f.encoding!==g.encoding||f.payload&&f.payload!==g.payload||(S=v)})),S>=0&&g.rtp.length>1){const f=g.rtp[S].payload;g.rtp.splice(S,1),g.payloads=g.payloads.split(" ").filter((g=>f!==+g)).join(" "),g.fmtp=g.fmtp?.filter((g=>f!==g.payload))}}function addCodec(g,f){g.rtp.unshift({payload:f.payload,codec:f.codec,rate:f.rate,encoding:f.encoding}),g.payloads=`${f.payload} ${g.payloads}`}function isCodecsMatch2(g,f,S){if(!(0,Xy.isUndefined)(g.rate)&&g.rate!==f.rate)return!1;if(!(0,Xy.isUndefined)(g.codec)&&g.codec.toLowerCase()!==f.codec.toLowerCase())return!1;if(!(0,Xy.isUndefined)(g.encoding)){if(!(0,Xy.isUndefined)(f.encoding)&&g.encoding!==f.encoding)return!1;if((0,Xy.isUndefined)(f.encoding)&&1!==g.encoding)return!1}if(!(0,Xy.isUndefined)(g.fmtpLine)){const v=S?.find((S=>S.payload===f.payload&&-1!==S.config.toLowerCase().indexOf(g.fmtpLine.toLowerCase())));return!!v}return!0}function isPayloadMatch(g,f){return f===g||"*"===f}function filterCodecs(g,f,S,v){if(!g.rtp?.length)return;let C=g.rtp.filter((S=>f.some((f=>isCodecsMatch2(f,S,g.fmtp)))));g.type===qt.MEDIA_TYPE.video&&(C=C.filter((f=>{const S=g.fmtp?.find((g=>g.payload===f.payload&&g.config.startsWith("apt=")));if(S){const g=+S.config.split(";")[0].split("=")[1];return C.some((f=>f.payload===g))}return!0}))),C.length?(g.rtp=C,S&&(g.rtp=(0,Xy.flatten)(f.map((f=>g.rtp.filter((S=>isCodecsMatch2(f,S,g.fmtp))))))),g.payloads=g.rtp.map((g=>g.payload)).join(" "),g.fmtp=g.fmtp?.filter((f=>g.rtp.some((g=>isPayloadMatch(g.payload,f.payload))))),g.rtcpFb=g.rtcpFb?.filter((f=>g.rtp.some((g=>isPayloadMatch(g.payload,f.payload)))))):v&&v.warn("Empty rtp list after filtering")}function getModalityForMedia(g){if(g.label)switch(g.label){case qt.MEDIA_LABEL.audio:return"Audio";case qt.MEDIA_LABEL.video:return"Video";case qt.MEDIA_LABEL.sharing:return"ScreenShare";case qt.MEDIA_LABEL.data:return"Data"}else switch(g.type){case qt.MEDIA_TYPE.audio:return"Audio";case qt.MEDIA_TYPE.video:return"Video";case qt.MEDIA_TYPE.data:case qt.MEDIA_TYPE.dataChannel:return"Data"}return null}function getModality(g){if(g.label)switch(g.label){case qt.MEDIA_LABEL.audio:return qt.MODALITY.audio;case qt.MEDIA_LABEL.video:return qt.MODALITY.video;case qt.MEDIA_LABEL.sharing:return qt.MODALITY.sharing;case qt.MEDIA_LABEL.data:return qt.MODALITY.data}else switch(g.type){case qt.MEDIA_TYPE.audio:return qt.MODALITY.audio;case qt.MEDIA_TYPE.video:return qt.MODALITY.video;case qt.MEDIA_TYPE.data:case qt.MEDIA_TYPE.dataChannel:return qt.MODALITY.data}return null}function getLabelForModality(g){switch(g){case qt.MODALITY.audio:return qt.MEDIA_LABEL.audio;case qt.MODALITY.video:return qt.MEDIA_LABEL.video;case qt.MODALITY.sharing:return qt.MEDIA_LABEL.sharing;case qt.MODALITY.data:return qt.MEDIA_LABEL.data;default:return null}}function getModalities(g){return g.media.reduce(((g,f)=>{if(0!==f.port){const S=getModality(f);if(!(S in g)){const v=f.direction?f.direction.toLowerCase():qt.MEDIA_STATE.sendReceive;g[S]=v}}return g}),{})}function getTypeFromModality(g){switch(g){case qt.MODALITY.audio:return qt.MEDIA_TYPE.audio;case qt.MODALITY.video:case qt.MODALITY.sharing:return qt.MEDIA_TYPE.video;case qt.MODALITY.data:return qt.MEDIA_TYPE.data;default:return null}}function getBundle(g){const f=g.groups?.find((g=>"BUNDLE"===g.type));if(f){const S=f.mids?.toString().split(" ")[0];return g.media.find((g=>{const f="number"==typeof g.mid?g.mid.toString():g.mid;return S===f}))||null}return null}function isMediaDisabled(g){return 0===g.port}function getRecvCapabilitiesForMedia(g){let f;return g&&forOneCodec(g,{codec:"h264",rate:9e4},(g=>{g.fmtp?.config&&(f=parseVideoCapabilitiesFromFmtpConfig(g.fmtp.config))})),f}function getNextAvailableMid(g){const f=g.media.map((g=>parseFloat(g.mid||"0")));for(let g=1;g<=Math.max(...f)+1;g++)if(!f.includes(g))return g.toString();return"-1"}function parseVideoCapabilitiesFromFmtpConfig(g){const f=new Zy(g);return{maxFs:+f.get(qt.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+f.get(qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+f.get(qt.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+f.get(qt.VIDEO_CAPABILITIES.MAX_BR_PATH)}}function getMultiStreamCountFromSdp(g){const f=/a=x-multi-stream:(\d+)/,S=g.match(f);if(S)return parseInt(S[1])}var eE=M;function CandidateTransform(){const g=[{jsep:"active",msSdp:"tcp-act"},{jsep:"passive",msSdp:"tcp-pass"},{jsep:"so",msSdp:"tcp-so"}];function transformBundle(g,f){if(g.port&&!g.candidates.length){const S=getBundle(f);S&&(g.port=S.port,g.connection=S.connection)}}function transformCandidate(g,f){delete g.generation,delete g["network-id"],delete g["network-cost"],g.transport.match(/tcp/i)&&transformTcpCandidate(g,f)}function transformTcpCandidate(f,S){g.some((function(g){if(S){if(g.msSdp===f.transport.toLowerCase())return f.transport="tcp",f.tcptype=g.jsep,!0}else if(f.tcptype&&g.jsep===f.tcptype.toLowerCase())return f.transport=g.msSdp,delete f.tcptype,!0;return!1}))}function isDefault(g,f,S){const v=f.connection||S.connection,isSame=function(g,f,S){return g.port===S&&g.ip===f};return!!v&&(1===g.component?isSame(g,v.ip,f.port):!!f.rtcp&&isSame(g,f.rtcp.ip||v.ip,f.rtcp.port))}this.fromMsSdp=function(g){g.candidates=g.candidates||[],g.xCandidatesIpv6&&(g.xCandidatesIpv6.forEach((function(f){g.candidates.push(f)})),delete g.xCandidatesIpv6),g.candidates.forEach((function(g){transformCandidate(g,!0)}))},this.toMsSdp=function(g,f){g.candidates=g.candidates||[],g.candidates.sort((function(S,v){return S.foundation!==v.foundation?S.foundation-v.foundation:S.component!==v.component?S.component-v.component:+isDefault(v,g,f)-+isDefault(S,g,f)})),g.candidates=g.candidates.filter((function(f,S){transformCandidate(f,!1);const v=g.candidates[S-1];return!v||v.component!==f.component||v.foundation!==f.foundation})),transformBundle(g,f)}}var tE={build:()=>new CandidateTransform},iE=class{toMsSdp(g,f){"offer"===f?g.rtcp&&(g.rtcp={port:g.port}):delete g.rtcp}},nE={build:()=>new iE},rE={STREAM_ID:{audio:"mainAudio",video:"mainVideo",sharing:"applicationsharingVideo"},STREAM_ID_DELIMITER:"-"},sE=[{label:qt.MEDIA_LABEL.audio,id:rE.STREAM_ID.audio},{label:qt.MEDIA_LABEL.video,id:rE.STREAM_ID.video},{label:qt.MEDIA_LABEL.sharing,id:rE.STREAM_ID.sharing}].reduce(((g,f)=>(g[f.label]=f.id,g)),{}),aE=uniqueId(),oE=class{constructor(g){this.configuration=g}fromMsSdp(g){if(0===g.port)return;const f="-";if(!this.isRecvOnly(g)||this.configuration.unifiedPlanEnabled){if(g.msid){g.ssrcs&&1===g.ssrcs.length&&(this.addStream(g,g.ssrcs[0].id,g.ssrcs[0].value,g.msid),g.ssrcs.shift());const S=g.msid.split(" ");(this.configuration.addPrefixForMsid||S[0]===f)&&(g.msid=this.getMsidValue(S[0],S[1]||S[0],g.label))}if(g.ssrcs)this.updateMsids(g.ssrcs,((S,v)=>this.configuration.addPrefixForMsid||S===f?this.getMsidValue(S,v,g.label):`${S} ${v}`));else{const f=this.getFlowSsrcs(g);f.length>0?f.forEach((S=>{this.addStream(g,S,aE,this.getMsidValue(f[0],f[0],g.label))})):g.xSsrcRange&&this.addStream(g,g.xSsrcRange.ssrcMin,aE,this.getMsidValue(g.xSsrcRange.ssrcMin,g.xSsrcRange.ssrcMin,g.label))}}delete g.xSsrcRange}toMsSdp(g,f){if(0===g.port)return;let S;g.ssrcs?.[0]&&(S=g.ssrcs[0].id),void 0!==S&&(g.xMultiStream||(g.xSsrcRange={ssrcMin:S,ssrcMax:S+f}))}getFlowSsrcs(g){if(g.ssrcGroups&&g.type===qt.MEDIA_TYPE.video){let f;if(g.ssrcGroups.some((g=>"FID"===g.semantics&&(f=g,!0))),f)return f.ssrcs.split(" ").map((g=>+g))}return[]}addStream(g,f,S,v){g.ssrcs=g.ssrcs||[],g.ssrcs.push({attribute:"cname",id:f,value:S}),g.ssrcs.push({attribute:"msid",id:f,value:v})}updateMsids(g,f){g.filter((g=>"msid"===g.attribute)).forEach((g=>{const S=g.value.split(" ");g.value=f(S[0],S[1]||S[0])}))}getMsidValue(g,f,S){const v=this.getMsidPrefix(S);return v+g+" "+v+f}getMsidPrefix(g){return sE[g]?sE[g]+rE.STREAM_ID_DELIMITER:""}isRecvOnly(g){return"recvonly"===g.direction}},lE={audio:"main-audio",video:"main-video"},cE=class{constructor(g,f){this.context=g,this.mediaManager=f,this.logger=this.context.logger,this.candidateTransform=tE.build(),this.streamTransform=new oE(this.context.configuration),this.rtcpTransform=nE.build()}toMsSdp(g,f){return g.msidSemantic={semantic:"WMS",token:"*"},g.media.forEach(((S,v)=>{if(S.protocol=qt.PROFILES.rtpSavp,S.label=S.label||this.getLabel(S.type),isMediaDisabled(S)){for(const g in S)S.hasOwnProperty(g)&&["type","port","protocol","payloads"].indexOf(g)<0&&delete S[g];S.payloads="34"}const C=this.getSsrcRangeForIndex(S.direction,v);this.streamTransform.toMsSdp(S,C),S.crypto&&S.crypto.forEach((function(g){g.config+="|2^31"})),0!==S.port&&g.fingerprint&&(S.fingerprint=g.fingerprint),this.candidateTransform.toMsSdp(S,g),this.rtcpTransform.toMsSdp(S,f),S.invalid&&(this.logger.unsafe.error(`Unknown SDP attributes! ${JSON.stringify(S.invalid)}`),delete S.invalid),this.transformExtensions(S,!1),0!==S.port&&(S.type===qt.MEDIA_TYPE.audio&&this.context.configProvider.config.webrtcAudioChannelSignalingFeedback?S.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcAudioChannelSignalingFeedback}:S.type===qt.MEDIA_TYPE.video&&this.context.configProvider.config.webrtcVideoChannelSignalingFeedback&&(S.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcVideoChannelSignalingFeedback}))})),delete g.fingerprint,g}fromMsSdp(g,f){for(let S=g.media.length-1;S>=0;--S){const v=g.media[S];if((v.ssrcs?.[0]||v.xSsrcRange)&&(g.msidSemantic={semantic:"WMS",token:"*"}),isMediaDisabled(v))v.direction||(v.direction="inactive");else{if(this.streamTransform.fromMsSdp(v),delete v.cryptoscale,v.fingerprint&&(!this.isOffer(f)||this.context.configProvider.config.disableIncomingDtlsRoleOverride&&v.setup||(v.setup="actpass")),v.crypto)for(let g=v.crypto.length-1;g>=0;--g){const f=v.crypto[g];f.config.match(/.*\|\d+:\d+/)?v.crypto.splice(g,1):f.config=f.config.replace(/(.*)\|2\^\d+/,"$1")}v.remoteCandidates&&(delete v.candidates,delete v.xCandidatesIpv6,delete v.remoteCandidates),this.candidateTransform.fromMsSdp(v),v.rtcpFbXMessage&&delete v.rtcpFbXMessage,v.invalid&&this.logger.unsafe.info(`Unknown SDP attributes! ${JSON.stringify(v.invalid)}`),this.transformExtensions(v,!0)}}return g}transformExtensions(g,f){const S=[{name:qt.ABS_SEND_TIME.EXT_URI,encoded:qt.ABS_SEND_TIME.MSSDP_ENCODED_URI},{name:qt.TRANSPORT_CC.EXT_URI,encoded:qt.TRANSPORT_CC.MSSDP_ENCODED_URI}];g.ext&&g.ext.forEach((function(g){S.some((function(S){const v=f?S.encoded:S.name,C=f?S.name:S.encoded;return v===g.uri&&(g.uri=C,!0)}))}))}isOffer(g){return"offer"===g}getLabel(g){return lE.hasOwnProperty(g)&&lE[g]||"undefined"}getSsrcRangeForIndex(g,f){const S=this.mediaManager.getMediaEntities()[f],v=S?.getSimulcastContext();return hasSendDirectionality(g)&&v?v.getSsrcRange():0}},dE=4294967040,hE=class{constructor(){this.ssrc=Math.floor(Math.random()*(dE-1))+1}nextAudioStreamSsrc(){return this.nextSsrc(0)}nextVideoStreamSsrc(){return this.nextSsrc(99)}nextSsrc(g){let f=this.ssrc;do{f=this.ssrc,this.ssrc=(this.ssrc+g+1)%dE,0===this.ssrc&&(this.ssrc=1)}while(f+g>dE);return{min:f,max:f+g}}},uE=M,gE=class{constructor(g,f,S){this.mediaEntity=g,this.logger=f,this.configProvider=S,this.activeRids=[],this.isLocalDescSet=!1,this.enabledLocally=!1,this.enabledRemotely=!1;const v=modalityToMediaType(this.mediaEntity.getModality());this.config=getSimulcastConfigForMediaType(v,this.configProvider),this.config?this.logger.safe.debug(`Adding simulcast info to ${g.getModality()} with mid: ${g.getMid()}, config: ${JSON.stringify(this.config)}`):this.logger.safe.debug(`Simulcast is disabled for ${g.getModality()}`)}get ridList(){return this.config?(0,uE.times)(this.config.layerScaleFactors.length,(g=>g+1)):[]}localDescriptionIsApplied(){this.isLocalDescSet=!0}enableInLocalDesc(){this.enabledLocally=!0}shouldBeEnabledInLocalDesc(){return!!this.config&&(this.config.enableLocally||this.enabledRemotely)}enableInRemoteDesc(){this.enabledRemotely=!0}shouldBeEnabledInRemoteDesc(){return!!this.config&&(this.enabledLocally||this.config.allowEnableRemotely&&this.isMidRidHeaderExtPresented()&&!this.isLocalDescSet)}shouldUseSimulcast(){return this.shouldBeEnabledInLocalDesc()}getSsrcRange(){return this.shouldUseSimulcast()?99:0}isMidRidHeaderExtPresented(){const g=this.mediaEntity.getRtpHeaderExtensions();return g?.some((g=>"mid"===g.headerType||"rid"===g.headerType||"rrid"===g.headerType))}};function getSimulcastConfigForMediaType(g,f){return"Video"===g?f.config.specCompliantSimulcast?.video:"ScreenShare"===g?f.config.specCompliantSimulcast?.sharing:null}var pE=M,mE=[2812,4218,8437,16875,33750,67500,108e3,135e3,198e3,244800,27e4,352500,52e4],fE=class{constructor(g,f,S,v){this.initialMaxFS=g,this.initialMaxFPS=f,this.isAv1Allowed=S,this.h264SubscribeProfile=v,this.maxFS=g,this.maxFPS=f}setMaxFS(g,f){return!(this.maxFS===g||(this.maxFS=g,!f))&&(f(this),!0)}getMaxFS(){return this.maxFS}getMaxFPS(){return this.maxFPS}getMaxMBPS(){return this.calculateMbps(this.maxFS,this.maxFPS)}calculateMbps(g,f){return getClosestValue(mE,g*f/100,!0)}resetToInitial(){this.maxFS=this.initialMaxFS,this.maxFPS=this.initialMaxFPS}fmtpParams(){return{"max-fs":this.getMaxFS(),"max-mbps":this.getMaxMBPS(),"max-fps":this.getMaxFPS()}}buildFmtp(){const g=[];let f=this.fmtpParams();return this.h264SubscribeProfile&&(f["profile-level-id"]=this.h264SubscribeProfile),g.push(f),this.isAv1Allowed&&(f=this.fmtpParams(),f.codec="AV1",g.push(f)),g}},SE=class _MediaEntity{constructor(g,f){this.entity=g,this.configProvider=f,this.supportedSendProfiles={}}toString(){return`MediaEntity: ${this.entity.modality} \nmid: ${this.entity.mid} localRecvCaps: ${JSON.stringify(this.localRecvCapabilities?.buildFmtp())}  remoteRecvCaps: ${JSON.stringify(this.remoteRecvCapabilities)}  localSsrc: ${this.getLocalSsrc()} remoteSsrc: ${this.getRemoteSsrc()} localTrackId: ${this.getLocalTrackId()} remoteStreamId: ${this.getRemoteStreamId()} remoteTrackId: ${this.getRemoteTrackId()} xSourceStreamId: ${this.getXSourceStreamId()} subStreamIndex: ${this.getSubstreamIndex()} extensions: ${JSON.stringify(this.entity.extensions)} rtpExt: ${JSON.stringify(this.entity.rtpExt)}         `}static getVideoCababilities(g,f,S){if(g!==qt.MEDIA_TYPE.video)return null;let v,C;f===qt.MODALITY.sharing?(v=S.config.webrtcScreensharingCapabilityMaxFS,C=S.config.webrtcScreensharingCapabilityMaxFPS):(v=S.config.webrtcVideoCapabilityMaxFS,C=S.config.webrtcVideoCapabilityMaxFPS,S.config.useMultiviewLimitsOnInitialRequest&&S.config.multiviewResolutionLimits[1]&&(v=ei.Send.getMaxFsForHeight(S.config.multiviewResolutionLimits[1])));const _=S.config.isAv1Allowed&&f===qt.MODALITY.sharing;return new fE(v,C,_,S.config.h264SubscribeProfile)}static create(g,f,S){const v=getTypeFromModality(f),C=new _MediaEntity({modality:f,mid:S,mtype:v,extensions:{}},g);return C.localRecvCapabilities=_MediaEntity.getVideoCababilities(v,f,g),C}clone(){const g=new _MediaEntity((0,pE.cloneDeep)(this.entity),this.configProvider);return g.setSimulcastContext(this.simulcastContext),g.localRecvCapabilities=this.localRecvCapabilities,g.remoteRecvCapabilities=this.remoteRecvCapabilities,g.supportedSendProfiles=this.supportedSendProfiles,g}getModality(){return this.entity.modality}getType(){return this.entity.mtype}getMid(){return this.entity.mid}disable(){this.entity.mid=null}update(g,f){this.entity.modality!==g&&(this.localRecvCapabilities=_MediaEntity.getVideoCababilities(this.entity.mtype,g,this.configProvider)),this.entity.modality=g,this.entity.mid=f,this.isEnabled()&&this.setExtension("rollback",!1)}isDisabled(){return!this.entity.mid}isEnabled(){return!!this.entity.mid}getLocalRecvCapabilities(){return this.localRecvCapabilities}getRemoteRecvCapabilities(){return{sourceId:this.getXSourceStreamId(),capabilities:this.remoteRecvCapabilities?[this.remoteRecvCapabilities]:[]}}setRemoteRecvCapabilities(g){this.remoteRecvCapabilities=g}getRemoteStreamId(){return this.entity.remoteStreamId}setRemoteStreamId(g){this.entity.remoteStreamId=g}setRemoteSsrc(g){this.entity.remoteSsrc=g}getRemoteSsrc(){return this.entity.remoteSsrc}setLocalSsrc(g){this.entity.localSsrc=g}getLocalSsrc(){return this.entity.localSsrc}getRemoteTrackId(){return this.entity.remoteTrackId}setRemoteTrackId(g){this.entity.remoteTrackId=g}getXSourceStreamId(){return this.entity.xSourceStreamId}setXSourceStreamId(g){this.entity.xSourceStreamId=g}setLocalTrackId(g){this.entity.localTrackId=g}getLocalTrackId(){return this.entity.localTrackId}setSubStreamIndex(g){this.entity.subStreamIndex=g}getSubstreamIndex(){return this.entity.subStreamIndex}getExtension(g){return this.entity.extensions[g]}setExtension(g,f){this.entity.extensions[g]=f}getRtpHeaderExtensions(){return this.entity.rtpExt}setRtpHeaderExtensions(g){this.entity.rtpExt=g}setSimulcastContext(g){this.simulcastContext=g}getSimulcastContext(){return this.simulcastContext}addSupportedSendProfile(g,f){void 0===this.supportedSendProfiles[g]&&(this.supportedSendProfiles[g]=new Set),this.supportedSendProfiles[g].add(f)}isSendProfileSupported(g,f){const S=this.supportedSendProfiles[g];if(void 0!==S){const g=f.slice(0,2);for(const f of S)if(f.startsWith(g))return!0}return!1}serialize(){return deepClone(this.entity)}},vE={toffset:"toffset","abs-send-time":"abs-send-time","video-orientation":"video-orientation","draft-holmer-rmcat-transport-wide-cc-extensions-01":"transport-cc","video-content-type":"video-content-type","video-timing":"video-timing","color-space":"color-space","video-layers-allocation00":"vla","video-layers-allocation00-non-advertised":"non-adv-vla",mid:"mid","rtp-stream-id":"rid","repaired-rtp-stream-id":"rrid","fast_bandwidth_feedback#version_3":"fast_bandwidth_feedback#version_3","frame-counters-gvc":"frame-counters-gvc"},CE=class{constructor(g){this.context=g,this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.ssrcGenerator=new hE,this.rollbackHandlers=[],this.logger=g.logger.createChild("MM2"),this.configProvider=g.configProvider}fromOffer(g,f,S=!1){this.logger.safe.debug(`fromOffer, modalities: ${JSON.stringify(f)} disableOnly: ${S}`),this.updateMediaEntitiesFromModel(g,S),this.updateSharingEntity(!!f.sharing),g.media.forEach((g=>{this.logger.safe.debug(`Media entity for mid: ${g.mid}, ${this.getMediaEntityByMid(g.mid)}`);const f=this.getMediaEntityByMid(g.mid);f&&this.saveLocalSsrc(f,g)}))}fromRemote(g,f){const S=0===this.mediaEntities.length;this.updateMediaEntitiesFromModel(g,!1,f),g.media.forEach(((g,f)=>{const S=this.getMediaEntityByMid(g.mid);S&&(this.saveRemoteMsid(S,g),this.saveRemoteSsrc(S,g),this.saveRtpHeaderExtensions(S,g),S.setXSourceStreamId(g.xSourceStreamId||this.generateSourceStreamId(f)),S.setRemoteRecvCapabilities(getRecvCapabilitiesForMedia(g)),S.setSubStreamIndex(g.subStreamIndex)),this.logger.safe.debug(`Media entity for mid: ${g.mid}, ${S}`)})),S&&this.updateReinvitelessState(g)}isEmpty(){return 0===this.mediaEntities.length}createMediaEntity(g,f){const S=SE.create(this.configProvider,g,f);return this.logger.safe.debug(`Creating media entity for modality: ${g}, mid: ${f}`),this.context.useSimulcast&&!this.mediaEntities.find((f=>f.getModality()===g))&&this.setSimulcastContext(S),S.setExtension("reinviteless",!1),this.mediaEntities.push(S),S}getMediaEntities(){return this.mediaEntities}getMediaEntity(g){return this.mediaEntities[g]}getMediaEntityByMid(g){return this.mediaEntities.find((f=>f.getMid()===g))}getMediaEntitiesByModality(g){return this.mediaEntities.filter((f=>f.getModality()===g))}getMediaEntitiesByMediaType(g){const f=modalityToMediaType(g);return this.getMediaEntitiesByModality(f)}getMediaEntityByRemoteStreamId(g){return this.mediaEntities.find((f=>f.getRemoteStreamId()===g))}getMediaEntityByLocalTrackId(g){return this.mediaEntities.find((f=>f.getLocalTrackId()===g))}getMediaEntityByXSourceStreamId(g){return this.mediaEntities.find((f=>f.getXSourceStreamId()===g))}reset(){this.mediaEntities=[],this.rollbackHandlers=[]}syncModalities(g,f,S=!1){this.logger.safe.debug(`syncModalities, modalities: ${JSON.stringify(f)}, disableOnly: ${S},`),this.fromOffer(g,f,S)}setLocalTracksInfo(g){this.mediaTracks=g}getLocalTracksInfo(){return this.mediaTracks}backup(){this.logger.safe.debug("backup"),this.mediaEntitiesBackup=[],this.mediaEntities.forEach((g=>{this.mediaEntitiesBackup.push(g.clone())}))}commit(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((g=>{g.setExtension("unnegotiatedModality",!1)}))}rollback(){this.logger.safe.debug(`rollback, if backup exists: ${!!this.mediaEntitiesBackup.length}`),this.mediaEntitiesBackup.length&&(this.rollbackHandlers.forEach((g=>g(this.mediaEntities,this.mediaEntitiesBackup))),this.mediaEntities.forEach(((g,f)=>{this.mediaEntitiesBackup[f]?this.mediaEntities[f]=this.mediaEntitiesBackup[f]:(g.disable(),g.setExtension("rollback",!0))})))}updateMediaEntitiesWithLocalTracks(){this.mediaTracks?(this.mediaEntities.forEach((g=>g.setLocalTrackId(null))),this.mediaTracks.forEach((g=>{const f=this.getMediaEntitiesByModality(g.modality)[0];f?(this.logger.safe.debug(`Setting local track id ${g.trackId} for modality ${g.modality}`),f.setLocalTrackId(g.trackId)):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(g.modality)}`)}))):this.logger.safe.debug("No mediaTracks, not updating local tracks for media entities")}updateMediaEntitiesWithActivityState(g,f){this.logger.safe.debug(`Updating activity indexes for ${g} to ${JSON.stringify(f)}`);const S=mediaTypeToModality(g),v=this.getMediaEntitiesByModality(S)[0];if(!v)return void this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(S)}`);const C=v.getSimulcastContext();C&&(C.activeRids=f)}setRollbackUpdateHandler(g){this.rollbackHandlers.push(g)}saveRtpHeaderExtensions(g,f){if(g.isDisabled())return void g.setRtpHeaderExtensions(void 0);const S=f.ext?.map((g=>this.getHeaderExtension(g)));this.logger.safe.debug(`RTP header ext for mid=${f.mid}, modality=${g.getModality()}: ${JSON.stringify(S)}`),g.setRtpHeaderExtensions(S)}getHeaderExtension(g){let f="unknown";for(const[S,v]of Object.entries(vE))if(g.uri.endsWith(S)){f=v;break}return{headerType:f,value:g.value}}saveRemoteMsid(g,f){if(isMediaDisabled(f))g.setRemoteStreamId(null);else if(f.msid)g.setRemoteStreamId(f.msid.split(" ")[0]);else if(f.ssrcs){const S=f.ssrcs.find((g=>"msid"===g.attribute));S?g.setRemoteStreamId(S.value.split(" ")[0]):this.logger.safe.warn(`No ssrc msid for media of type ${f.type} with mid ${f.mid}`)}}saveRemoteSsrc(g,f){if(f.ssrcs?.length){const S=f.ssrcs[0];g.setRemoteSsrc(+S.id)}}saveLocalSsrc(g,f){const S=f.ssrcs?.[0]?.id;if(!hasSendDirectionality(f.direction))return this.logger.safe.debug(`set local SSRC to ${S}`),void g.setLocalSsrc(+S);this.logger.safe.debug("has no send direction");const v=S||g.getLocalSsrc()||this.ssrcGenerator.nextVideoStreamSsrc().min;g.setLocalSsrc(+v)}updateMediaEntitiesFromModel(g,f,S){g.media.forEach(((g,v)=>{if(this.mediaEntities[v])if(isMediaDisabled(g))this.logger.safe.debug(`Disabling media entity for mid: ${g.mid}`),this.mediaEntities[v].disable();else{const f=g.mid||this.mediaEntities[v].getMid(),S=this.mediaEntities[v].getModality();this.logger.safe.debug(`Updating media entity for mid: ${f}, modality: ${S}`),this.mediaEntities[v].update(S,f),this.logger.safe.debug(`updated entity: ${this.mediaEntities[v]}`)}else f||this.createMediaEntity(getModality(g),g.mid||v.toString());this.mediaEntities[v]&&S&&!(this.mediaEntities[v].getModality()in S)&&(this.logger.safe.debug(`Disabling media entity for mid: ${g.mid} as it is not found in modalities ${JSON.stringify(S)}`),this.mediaEntities[v].disable())}))}updateSharingEntity(g){if(g&&!this.getMediaEntitiesByModality(qt.MODALITY.sharing).length){const g=this.getMediaEntitiesByModality(qt.MODALITY.video).pop();g.update(qt.MODALITY.sharing,g.getMid())}}setSimulcastContext(g){if(!g||g.getSimulcastContext())return;const f=new gE(g,this.logger.createChild(`SimContext:${g.getModality()}`),this.configProvider);g.setSimulcastContext(f)}generateSourceStreamId(g){return g+10}updateReinvitelessState(g){const f={[qt.MODALITY.audio]:0,[qt.MODALITY.video]:0,[qt.MODALITY.sharing]:0};for(const S of g.media){const g=getModality(S);void 0!==f[g]&&f[g]++;const v=this.getMediaEntityByMid(S.mid);if(v){const C=this.context.reinviteltessContext?.maxStreamsForModality[g]>=f?.[g]&&(!S.direction||"sendrecv"===S.direction);v.setExtension("reinviteless",C)}}}},yE=class{constructor(g){this.modifierList=g}modify(g){for(const f of this.modifierList)f.modify(g)}},EE=class{constructor(g,f,S,v){this.context=g,this.mediaManager=f,this.modalities=S,this.cname=v}build(g){switch(g.sdpSource){case 0:return new yE([new g_(this.context.configProvider),new qE(this.context.configProvider),new b_(this.mediaManager,this.context.configProvider),new I_(this.mediaManager),new t_(this.context.configProvider),new QE(this.context.configProvider),new u_(this.context.configProvider,this.mediaManager,g.sdpType,!1,this.context.getLogger().createChild("OverrideH264SendProfile")),new KE(this.mediaManager,this.context.configProvider,g.sdpType),new zE(this.mediaManager,this.context.configProvider,this.context.config.isConference,!1),new L_(this.context.configProvider,g.sdpType),new l_(this.context.configProvider)]);case 2:return new yE([new PE(this.mediaManager,this.modalities),new WE,new RE(this.mediaManager,!0),new S_(this.context.configProvider,this.mediaManager),new LE(this.modalities,this.mediaManager),new r_,new e_,new i_,new n_(this.context.configProvider),new ZE(this.context.configProvider),new h_(this.context.configProvider),new u_(this.context.configProvider,this.mediaManager,g.sdpType,!0,this.context.getLogger().createChild("OverrideH264SendProfile")),new xE,new IE(this.context),new E_(this.mediaManager,this.context.configProvider),new GE(this.context.configProvider),new w_,new M_(this.context.configProvider),new A_(this.context.configProvider),new BE(this.mediaManager,this.modalities,this.context.configProvider),new kE(this.context),new O_(this.context.configProvider),new DE(this.context.configProvider),new KE(this.mediaManager,this.context.configProvider,g.sdpType),new JE(this.mediaManager,this.context.configProvider,g.sdpType),new zE(this.mediaManager,this.context.configProvider,this.context.config.isConference,!0),new a_(this.context.configProvider,this.context.getLogger()),new VE,new N_(this.context.configProvider),new l_(this.context.configProvider),new F_(g,this.context),new C_(this.context.configProvider),new m_(this.context.configProvider)]);case 1:return new yE([new wE(this.context,this.modalities.data),new RE(this.mediaManager,!1),new HE(this.context.configProvider),new PE(this.mediaManager,this.modalities),new UE(this.mediaManager),new e_,new XE(this.context.configProvider),new bE(this.mediaManager,"offer"===g.sdpType,this.context.configProvider),new T_(this.mediaManager,this.context.getLogger()),new R_(this.context.configProvider,this.mediaManager),new FE(this.context.config.isConference,this.cname),new $E(this.mediaManager),new jE,new p_(this.context.configProvider),new NE(this.context.configProvider),new D_(this.context.configProvider),new k_(this.context.configProvider),new JE(this.mediaManager,this.context.configProvider,g.sdpType),new d_(this.mediaManager,this.context.configProvider,g.sdpType),new m_(this.context.configProvider)])}}},_E=class{constructor(g,f,S){this.context=g,this.mediaManager=f,this.sessionType=S,this.msSdpT=new cE(this.context,this.mediaManager)}modify(g){this.msSdpT.toMsSdp(g,this.sessionType)}},TE=class{constructor(g,f,S){this.context=g,this.mediaManager=f,this.sessionType=S,this.msSdpT=new cE(this.context,this.mediaManager)}modify(g){this.msSdpT.fromMsSdp(g,this.sessionType)}},IE=class{constructor(g){this.context=g}modify(g){const f=preferSdesSrtp(this.context.configProvider,this.context.config.isPstnCall),S=getSrtpInfo(g),v=g.media.find((g=>!!g.crypto));g.media.forEach((g=>{g.type!==qt.MEDIA_TYPE.dataChannel&&(!f&&g.fingerprint&&g.crypto&&delete g.crypto,g.protocol=!S.dtls||S.sdes&&f?qt.PROFILES.rtpSavpf:qt.PROFILES.udpTlsRtpSavpf,isMediaDisabled(g)&&g.protocol===qt.PROFILES.rtpSavpf&&v&&(g.crypto=v.crypto))}))}},bE=class{constructor(g,f,S){this.mediaManager=g,this.isOffer=f,this.configProvider=S}modify(g){g.media.forEach(((g,f)=>{const S=g.setup,v=this.mediaManager.getMediaEntities()[f],C=v.getExtension("setup");S&&v.isEnabled()&&("actpass"!==S?v.setExtension("setup",S):this.isOffer&&void 0!==C&&"actpass"!==C&&!this.configProvider.config.disableOutgoingDtlsRoleOverride&&(g.setup=C))}))}},AE=class{modify(g){g.media.forEach((g=>{g.direction===qt.MEDIA_STATE.sendReceive&&(g.direction=qt.MEDIA_STATE.receive),g.direction===qt.MEDIA_STATE.send&&(g.direction=qt.MEDIA_STATE.inactive)}))}},PE=class{constructor(g,f){this.mediaManager=g,this.modalities=f}modify(g){let f=0;g.media.forEach(((g,S)=>{const v=parseInt(g.mid,10);!isNaN(v)&&v>=f&&(f=v+1)})),g.media.forEach(((S,v)=>{const C=this.mediaManager.getMediaEntities()[v];if(isMediaDisabled(S)||C.isDisabled()||!(C.getModality()in this.modalities)){const _=C.getExtension("midApplied")?void 0:S.mid||""+f++;0===v?S.direction=qt.MEDIA_STATE.inactive:g.media[v]=disabledMedia(S.type,void 0,S.protocol,_)}}))}},RE=class{constructor(g,f){this.mediaManager=g,this.remote=f}modify(g){const f=this.mediaManager.getMediaEntities();for(let S=0;S<f.length;S++){const v=f[S],C=g.media[S];if(v.getExtension("rollback"))if(C&&!this.remote)g.media[S]=null;else if(!C&&this.remote){const f=v.getType()===qt.MEDIA_TYPE.data?qt.MEDIA_TYPE.dataChannel:v.getType(),S=f===qt.MEDIA_TYPE.dataChannel?qt.PROFILES.udpDtlsSctp:qt.PROFILES.udpTlsRtpSavpf;g.media.push(disabledMedia(f,void 0,S,void 0))}}g.media=g.media.filter((g=>g))}},ME=class{constructor(g){this.mediaManager=g}modify(g){this.mediaManager.getMediaEntities().forEach(((f,S)=>{const v=g.media[S];f.getModality()!==qt.MODALITY.data||v&&v.type===qt.MEDIA_TYPE.dataChannel||g.media.splice(S,0,disabledMedia(qt.MEDIA_TYPE.data,qt.MEDIA_LABEL.data,qt.PROFILES.rtpSavp,void 0))}))}},wE=class{constructor(g,f){this.context=g,this.direction=f}modify(g){g.media.forEach((g=>{g.type===qt.MEDIA_TYPE.dataChannel&&(g.type=qt.MEDIA_TYPE.data,g.payloads=qt.PAYLOAD_TYPE.X_DATA)})),allowDataChannel(this.context)&&getEnabledMedia(g,qt.MEDIA_TYPE.data).forEach((f=>{f.rtp=f.rtp||[],f.fmtp=f.fmtp||[],f.rtp.push({codec:"x-data",payload:127,rate:9e4}),f.rtp.push({codec:"rtx",payload:126,rate:9e4}),f.fmtp.push({payload:126,config:"apt=127"});const S=this.getNonOverlappingSsrc(g);f.xSsrcRange={ssrcMin:S,ssrcMax:S},f.rtcpMux="rtcp-mux",f.xDataProtocol="sctp",f.direction=this.direction}))}getNonOverlappingSsrc(g){let f,S=!0;do{f=Math.floor(4294967293*Math.random())+2,getEnabledMedia(g).forEach((g=>{g?.ssrcs?.[0]?.id===f&&(S=!1)}))}while(!S);return f}},OE=class{constructor(g){this.configProvider=g,this.uri="urn:3gpp:video-orientation",this.value=13}modify(g){if(this.configProvider.config.enableVideoOrientationExtension)for(const f of getEnabledMedia(g,qt.MEDIA_TYPE.video))this.modifyMedia(f)}},DE=class extends OE{modifyMedia(g){g.ext??(g.ext=[]);g.ext.some((g=>g.uri===this.uri))||g.ext.push({value:this.getAvailableValue(g.ext),uri:this.uri})}getAvailableValue(g){const f=g.map((g=>g.value));return f.includes(this.value)?Math.max(...f)+1:this.value}},NE=class extends OE{modifyMedia(g){g.ext=g.ext?.filter((g=>g.uri!==this.uri))}},kE=class{constructor(g){this.context=g}modify(g){const f=g.groups?.find((g=>"BUNDLE"===g.type));for(let S=g.media.length-1;S>=0;S--){const v=g.media[S];if(v.type===qt.MEDIA_TYPE.data){const C=this.context.configProvider.config.rejectUnbundledDataModality&&!this.context.configProvider.mediaConfig.isTransportUnbundled&&!f?.mids?.toString().includes(v.mid),_=allowDataChannel(this.context);_||this.context.configProvider.config.acceptDisabledDataModality?(v.port=_&&!C?v.port:0,v.payloads=qt.PAYLOAD_TYPE.DATA_CHANNEL,v.type=qt.MEDIA_TYPE.dataChannel,v.protocol=qt.PROFILES.udpDtlsSctp,v.sctpPort??(v.sctpPort=this.context.configProvider.config.sctpPort),delete v.xDataProtocol,delete v.rtp,delete v.fmtp,delete v.rtcp,delete v.rtcpMux,delete v.ext,delete v.ssrcs,delete v.ssrcGroups,delete v.xSsrcRange):g.media.splice(S,1)}}}},LE=class{constructor(g,f){this.modalities=g,this.mediaManager=f}modify(g){getEnabledMedia(g).forEach((g=>{const f=getModality(g),S=this.mediaManager.getMediaEntityByMid(g.mid);!(this.modalities[f]!==qt.MEDIA_STATE.send||S.getExtension("reinviteless")||g.direction&&g.direction.toLowerCase()===qt.MEDIA_STATE.receive)&&(g.direction=qt.MEDIA_STATE.receive)}))}},FE=class{constructor(g,f){this.isMultiparty=g,this.cname=f}modify(g){this.isMultiparty&&getEnabledMedia(g).forEach((g=>{const f=g.direction;f!==qt.MEDIA_STATE.receive&&f!==qt.MEDIA_STATE.inactive||(g.ssrcs?.[0]?g.ssrcs=[{id:g.ssrcs[0].id,attribute:"cname",value:this.cname}]:g.type===qt.MEDIA_TYPE.audio?g.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:g.type===qt.MEDIA_TYPE.video&&(g.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}))}},xE=class{modify(g){const f=new Set;getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{g.ssrcs&&g.ssrcs.length>1&&f.add(+g.ssrcs[0].id)}));const S=getEnabledMedia(g,qt.MEDIA_TYPE.video).find((g=>g.direction===qt.MEDIA_STATE.sendReceive||g.direction===qt.MEDIA_STATE.send));getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{const v=g.direction;if((v===qt.MEDIA_STATE.receive||v===qt.MEDIA_STATE.inactive)&&g.ssrcs&&1===g.ssrcs.length){const v=g.ssrcs[0].id;(1===v||S&&S.ssrcs[0].id===v||!S&&f.has(v))&&(delete g.ssrcs,delete g.ssrcGroups)}}))}},UE=class{constructor(g){this.mediaManager=g}modify(g){g.media.forEach(((g,f)=>{const S=this.mediaManager.getMediaEntities()[f];g.label=getLabelForModality(S.getModality())}))}},VE=class{modify(g){g.media.forEach((g=>{delete g.label}))}},BE=class{constructor(g,f,S){this.mediaManager=g,this.modalities=f,this.configProvider=S}modify(g){let f=this.configProvider.mediaConfig.maxBandwidthInKbps;const S=g.bandwidth?.find((g=>"CT"===g.type));S&&(!f||f>+S.limit)&&(f=+S.limit);const v=this.configProvider.config.audioBandwidthInKbps||0,C=Math.max(f-v,0),_=this.configProvider.config.videoBandwidthAllocation&&hasSendDirectionality(this.modalities.video)&&hasSendDirectionality(this.modalities.sharing);getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{if(delete g.bandwidth,C){let f=C;if(_){const S=this.mediaManager.getMediaEntityByMid(g.mid).getModality()===qt.MODALITY.video?this.configProvider.config.videoBandwidthAllocation:1-this.configProvider.config.videoBandwidthAllocation;f=Math.round(C*S)}g.bandwidth=[{limit:f,type:"AS"}]}}))}},HE=class{constructor(g){this.configProvider=g}modify(g){const f=this.configProvider.mediaConfig.maxBandwidthInKbps;f&&(g.bandwidth=[{limit:f,type:"CT"}])}},$E=class{constructor(g){this.mediaManager=g}modify(g){g.media.forEach(((g,f)=>{const S=this.mediaManager.getMediaEntities()[f],v=S.getExtension("iceUfrag");S.setExtension("iceRestart",!!g.iceUfrag&&!!v&&v!==g.iceUfrag),S.setExtension("iceUfrag",g.iceUfrag)}))}},jE=class{modify(g){const f=new Set(["urn:ietf:params:rtp-hdrext:csrc-audio-level","http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"]);getEnabledMedia(g).forEach((g=>{g.ext&&(g.ext=g.ext.filter((g=>!f.has(g.uri))))}))}},GE=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.extmapAllowMixed&&(g.extmapAllowMixed="extmap-allow-mixed")}},qE=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.extmapAllowMixed||delete g.extmapAllowMixed}},WE=class{modify(g){getEnabledMedia(g).forEach((g=>{delete g.signalingFbXMessage}))}},zE=class{constructor(g,f,S,v){this.mediaManager=g,this.configProvider=f,this.isConference=S,this.remote=v}modify(g){if(this.configProvider.config.isAv1Allowed&&this.isConference){const f=findAllAvailablePayloads(g,[96,127]);this.mediaManager.getMediaEntities().forEach(((S,v)=>{let C=0;const _=g.media[v];if(S.getModality()!==qt.MODALITY.audio){if(!this.remote){const g=changeCodecPayload(_,{codec:"AV1",rate:9e4},f,!0,C);C=f.length-1,g.forEach((g=>{changeCodecPayload(_,{codec:"rtx",rate:9e4,payload:g+1},f,!1,C),C--}))}this.remote&&this.configProvider.config.av1LevelIndex&&forAllCodecs(_,{codec:"AV1",rate:9e4},(g=>{const replaceLevelIdx=(g,f)=>g.replace(/level-idx=\d+((\.\d+)+)?/g,`level-idx=${f}`);g.fmtp.config=replaceLevelIdx(g.fmtp.config,this.configProvider.config.av1LevelIndex)}))}}))}}},KE=class{constructor(g,f,S){this.mediaManager=g,this.configProvider=f,this.sdpType=S,this.baseModifier=new YE(this.mediaManager,this.configProvider,this.sdpType,!1)}modify(g){this.configProvider.config.filterCodecsInSdpV2||this.baseModifier.modify(g)}},JE=class{constructor(g,f,S){this.mediaManager=g,this.configProvider=f,this.sdpType=S,this.baseModifier=new YE(this.mediaManager,this.configProvider,this.sdpType,!0)}modify(g){this.configProvider.config.filterCodecsInSdpV2&&this.baseModifier.modify(g)}},YE=class{constructor(g,f,S,v=!1){this.mediaManager=g,this.configProvider=f,this.sdpType=S,this.alwaysReorder=v}modify(g){this.configProvider.config.filterCodecsInSdp&&"offer"===this.sdpType&&this.mediaManager.getMediaEntities().forEach(((f,S)=>{const v=g.media[S];if(!v)return;const C=getAllowedCodecs(this.configProvider,v.type);if(!C.length)return;filterCodecs(v,convertToCodecInfo(C),!!f.getExtension("unnegotiatedModality")||this.alwaysReorder,null)}))}},QE=class{constructor(g){this.configProvider=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(!f)return;const S=this.configProvider.mediaConfig.audioCodecContext;if(!S?.enabledLocally)return this.removeSubstitutionCodec(f,"SatinFB"),void this.removeSubstitutionCodec(f,"MUCHv2");S.codec!==S.lastUsedCodec&&"None"!==S.lastUsedCodec&&this.removeSubstitutionCodec(f,S.lastUsedCodec),S.enabledLocally&&!S.disabledRemotely&&this.addSubstitutionCodecIfNeeded(f,S.codec,g)}addSubstitutionCodecIfNeeded(g,f,S){if(this.isSubstitutionCodecAdded(g,f))return;const v=findAvailablePayload(S);if(-1===v)return;const C=getCustomCodecParams(f,"SUBSTITUTION");changePayloadType(S,C.payload,v),addCodec(g,C)}removeSubstitutionCodec(g,f){removeCodec(g,getCustomCodecParams(f,"SUBSTITUTION"))}isSubstitutionCodecAdded(g,f){let S=!1;return forOneCodec(g,getCustomCodecParams(f,"SUBSTITUTION"),(()=>{S=!0})),S}},XE=class{constructor(g){this.configProvider=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(!f)return;const S=this.configProvider.mediaConfig.audioCodecContext;if(!S?.enabledLocally||S.disabledRemotely)return this.removeSubstitutionCodec(f,"SatinFB"),void this.removeSubstitutionCodec(f,"MUCHv2");const v=getCustomCodecParams(S.codec,"SUBSTITUTION"),C=getCustomCodecParams(S.codec,"CODEC");forOneCodec(f,v,(g=>{g.rtp.codec=C.codec,g.rtp.rate=C.rate,g.rtp.encoding=C.encoding,"SatinFB"===S.codec&&(g.fmtp={payload:C.payload,config:"decoderversion=1"})}))}removeSubstitutionCodec(g,f){removeCodec(g,getCustomCodecParams(f,"SUBSTITUTION"))}},ZE=class{constructor(g){this.configProvider=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(!f)return;const S=this.configProvider.mediaConfig.audioCodecContext;if(!S?.enabledLocally)return this.removeCodec(f,"SatinFB"),void this.removeCodec(f,"MUCHv2");const v=getCustomCodecParams(S.codec,"CODEC"),C=getCustomCodecParams(S.codec,"SUBSTITUTION");let _=!1;forOneCodec(f,v,(g=>{S.enabledForSend&&(g.rtp.codec=C.codec,g.rtp.rate=C.rate,g.rtp.encoding=C.encoding,g.fmtp={payload:v.payload,config:"ptime=20"}),_=!0})),S.disabledRemotely=!_}removeCodec(g,f){removeCodec(g,getCustomCodecParams(f,"CODEC"));removeCodec(g,getCustomCodecParams(f,"SUBSTITUTION"))}},e_=class{modify(g){removeCodec(g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),{codec:"CN",rate:16e3})}},t_=class{constructor(g){this.configProvider=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),S=this.configProvider.mediaConfig.audioCodecContext;if(this.configProvider.config.fixOpusComfortNoise){if(!f||S&&(!S.enabledLocally||S.disabledRemotely))return}else if(!f||!S?.enabledLocally||S.disabledRemotely)return;let v=!1;const C={codec:"CN",rate:48e3};if(forOneCodec(f,C,(()=>{v=!0})),v)return;const _=findAvailablePayload(g);-1!==_&&(this.configProvider.config.fixOpusComfortNoise?C.payload=_:(changePayloadType(g,qt.PAYLOAD_TYPE.MSRTC_CNFB,_),C.payload=qt.PAYLOAD_TYPE.MSRTC_CNFB),addCodec(f,C))}},i_=class{modify(g){removeCodec(g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),{codec:"g722",rate:8e3,encoding:2})}},n_=class{constructor(g){this.configProvider=g}modify(g){const f=this.configProvider.config.enforceOpusFmtp;if(f){forOneCodec(g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),{codec:"opus",rate:48e3,encoding:2},(g=>{g.fmtp||(g.fmtp={payload:g.rtp.payload});const S=new Zy(g.fmtp.config);Object.keys(f).forEach((g=>{S.removeIfPresent(g),S.setIfMissing(g,`${f[g]}`)})),g.fmtp.config=S.toString()}))}}},r_=class{modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(f&&isMediaDisabled(f)){const S=g.media.find((g=>!!g.iceUfrag));S&&(f.port=9,f.direction="inactive",f.iceUfrag=S.iceUfrag,f.icePwd=S.icePwd,f.rtcpMux="rtcp-mux",S.crypto&&(f.crypto=S.crypto),S.fingerprint&&(f.fingerprint=S.fingerprint,f.setup=S.setup),f.rtp=[{payload:0,codec:"PCMU",rate:8e3}],f.payloads="0")}}},s_=class{constructor(g){this.otherPartyCodecs=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),S=["cn","telephone-event"],v=f.rtp.filter((g=>-1!==this.otherPartyCodecs.indexOf(g.codec.toLowerCase())&&-1===S.indexOf(g.codec.toLowerCase())));if(0===v.length)throw new Error("there is no matching primary audio codec");f.rtp.filter((g=>g!==v[0]&&-1===S.indexOf(g.codec.toLowerCase()))).forEach((g=>{removeCodec(f,g)}))}},a_=class{constructor(g,f){this.configProvider=g,this.logger=f}modify(g){this.configProvider.config.webrtcInjectTransportCCAudio&&getEnabledMedia(g,qt.MEDIA_TYPE.audio).forEach((g=>{const f=g.ext?.find((g=>g.uri===qt.TRANSPORT_CC.EXT_URI));if(!f)return void this.logger.safe.info("transport-cc ext not present in sdp, skipping injecting transport-cc attribute for audio");const S=g.rtp?.find((g=>"opus"===g.codec.toLowerCase()));if(!S)return void this.logger.safe.info("opus codec not found, skipping injecting transport-cc attribute for audio");const v=S.payload,C=g.rtcpFb?.find((g=>g.type===qt.TRANSPORT_CC.ATTRIBUTE&&g.payload===v));C?this.logger.safe.info("opus codec already has transport-cc attribute"):(g.rtcpFb=g.rtcpFb||[],g.rtcpFb.push({payload:v,type:qt.TRANSPORT_CC.ATTRIBUTE}),this.logger.safe.info("injected transport-cc attribute"))}))}},o_=class{constructor(g,f){this.mediaManager=g,this.configProvider=f}modify(g){g.media.forEach(((g,f)=>{if(isMediaDisabled(g)||g.type!==qt.MEDIA_TYPE.video)return;const S=this.mediaManager.getMediaEntities()[f];forOneCodec(g,{codec:"h264",rate:9e4},(g=>{const f=S.getLocalRecvCapabilities();if(!f)return;g.fmtp||(g.fmtp={payload:g.rtp.payload});const v=new Zy(g.fmtp.config);this.configProvider.config.h264SdpProfile?(v.removeIfPresent("profile-level-id"),v.setIfMissing("profile-level-id",this.configProvider.config.h264SdpProfile)):v.setIfMissing("profile-level-id","42C02A"),v.setIfMissing("max-fs",f.getMaxFS().toString()),v.setIfMissing("max-mbps",f.getMaxMBPS().toString()),v.setIfMissing("max-fps",f.getMaxFPS().toString()),g.fmtp.config=v.toString()}))}))}},l_=class{constructor(g){this.configProvider=g}modify(g){if(!this.configProvider.config.removeRtcpRsizeFromLocalSdp)return;const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));f?.rtcpRsize&&delete f.rtcpRsize}},c_=class{constructor(g){this.configProvider=g}modify(g){if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<this.configProvider.config.nonMultiStreamChannels)return;let f=0;for(let S=0;S<g.media.length;S++)if("Video"===getModalityForMedia(g.media[S])){if(g.media[S].xMultiStream)break;f++}const S=g.media.findIndex((g=>g.xMultiStream)),v=g.media[S];if(!v)return;const C=v.xMultiStream.startSsrc,_=v.xMultiStream.ssrcGroupRange,T=v.xMultiStream.ssrcRange;delete v.xMultiStream;const I=this.configProvider.config.numVideoChannelsGvc-f-1;v.subStreamIndex=I;const b=[];for(let f=0;f<I;f++){const I=(0,eE.cloneDeep)(v);I.mid=getNextAvailableMid(g),I.xSourceStreamId=v.xSourceStreamId,I.subStreamIndex=f,b.push(I.mid);const A=C+f*T;I.ssrcGroups=[{ssrcs:`${A} ${A+_}`,semantics:"FID"}],I.xSsrcRange={ssrcMin:A,ssrcMax:A+T-1},g.media.splice(S+f,0,I)}const A=C+I*T;v.ssrcGroups=[{ssrcs:`${A} ${A+_}`,semantics:"FID"}],v.xSsrcRange={ssrcMin:A,ssrcMax:A+T-1};const P=g.groups.find((g=>g.mids.includes(v.mid)));P.mids=`${P.mids} ${b.join(" ")}`}},d_=class{constructor(g,f,S){this.mediaManager=g,this.configProvider=f,this.type=S}modify(g){const f=1;if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<=this.configProvider.config.nonMultiStreamChannels+f)return;const S=this.mediaManager.getMediaEntitiesByModality(qt.MODALITY.video);let v=-1,C=-1;if(S.forEach(((f,S)=>{const _=g.media.findIndex((g=>g.mid===f.getMid()));S===this.configProvider.config.nonMultiStreamChannels-1&&(C=_),v=_})),-1===v||-1===C)return;const _=g.media[v];g.media.splice(C+1,v-C-1);const T=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;_.xMultiStream={numberOfStreams:T,startSsrc:1,ssrcRange:1,ssrcGroupRange:1},"answer"===this.type&&(_.xMultiStream.numberOfStreams=Math.min(T,this.configProvider.mediaConfig.multiStreamChannelsOffered),_.ssrcGroups&&delete _.ssrcGroups,_.xSsrcRange&&delete _.xSsrcRange)}},h_=class{constructor(g){this.configProvider=g}modify(g){getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{forOneCodec(g,{codec:"h264",rate:9e4},(g=>{if(g.fmtp){const f=new Zy,S=new Zy(g.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((g=>{if(S.contains(g)){let v=S.get(g);"profile-level-id"===g&&(v=this.configProvider.config.h264SendProfileOverride||v),f.setIfMissing(g,v)}})),g.fmtp.config=f.toString()}}))}))}},u_=class{constructor(g,f,S,v,C){this.configProvider=g,this.mediaManager=f,this.sdpType=S,this.remote=v,this.log=C}process(g,f,S){getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{getModalityForMedia(g)===f&&forOneCodec(g,{codec:"h264",rate:9e4},(f=>{if(f.fmtp){const v=new Zy(f.fmtp.config),C=new Zy;let _=!1;for(const f of v.names()){let T=v.get(f);if("profile-level-id"===f){const f=this.mediaManager.getMediaEntities().filter((f=>f.getModality()===getModality(g))).filter((g=>g.isEnabled())),v=S(f,T);typeof v==typeof T&&v!==T&&(T=v,_=!0)}C.setIfMissing(f,T)}_&&(f.fmtp.config=C.toString())}}))}))}modify(g){const f=this.configProvider.config.preferredH264SendProfileFallback,S=this.configProvider.config.preferredH264SharingSendProfile,v=this.configProvider.config.preferredH264VideoSendProfile;if(this.remote){const override=g=>(S,v)=>S.some((f=>f.isSendProfileSupported("H264",g)))?(this.log.safe.info(`Overriding H264 send profile: ${v} => ${g}`),g):(this.log.safe.info(`Applying fallback H264 profile: ${v} => ${f}`),f);v&&this.process(g,"Video",override(v)),S&&this.process(g,"ScreenShare",override(S))}else"answer"===this.sdpType&&(v||S)&&this.configProvider.config.enableFallbackH264SendProfileForLocalAnswer&&this.process(g,"Video",((g,C)=>C===v||C===S?(this.log.safe.info(`Restoring fallback profile in local answer: ${C} => ${f}`),f):C))}},g_=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{forAllCodecs(g,{codec:"h264",rate:9e4},(g=>{if(g.fmtp){const f=new Zy(g.fmtp.config);f.setIfMissing("sps-pps-idr-in-keyframe","1"),g.fmtp.config=f.toString()}}))}))}},p_=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{forAllCodecs(g,{codec:"h264",rate:9e4},(g=>{if(g.fmtp){const f=new Zy(g.fmtp.config);f.removeIfPresent("sps-pps-idr-in-keyframe"),g.fmtp.config=f.toString()}}))}))}},m_=class{constructor(g){this.configProvider=g}modify(g){const f=(g.groups||[]).findIndex((g=>"BUNDLE"===g.type)),S=g.groups?g.groups[f]:void 0;S&&(this.configProvider.mediaConfig.isTransportUnbundled?(S.mids=this.createBundleFromMedia(getEnabledMedia(g,qt.MEDIA_TYPE.video)),S.mids||g.groups.splice(f,1)):S.mids=this.createBundleFromMedia(getEnabledMedia(g)))}createBundleFromMedia(g){return g.map((g=>g.mid?.toString())).filter((g=>g)).join(" ")}},f_=class{modify(g){g.media.forEach((g=>{isMediaDisabled(g)&&g.bundleOnly&&(g.port=9,delete g.invalid)}))}},S_=class{constructor(g,f){this.configProvider=g,this.mediaManager=f}modify(g){if(!this.configProvider.mediaConfig.isTransportUnbundled&&!g.groups?.find((g=>"BUNDLE"===g.type))){let f=!1;if(g.media.forEach(((g,S)=>{const v=this.mediaManager.getMediaEntities()[S];!f&&v.isEnabled()?(g.mid=v.getMid(),f=!0):(v.disable(),g.port=0)})),f){g.groups||(g.groups=[]);const f={type:"BUNDLE"};g.groups.push(f)}}}},v_=class{constructor(g,f){this.configProvider=g,this.logger=f}modify(g){g.media.forEach((g=>{const f=!!g.candidates;if(g.candidates&&(g.candidates=g.candidates.filter((g=>{let f=!0,S=!0,v=!0;return this.configProvider.config.iceCandidateType&&(f=!!g.type.match(new RegExp(this.configProvider.config.iceCandidateType,"i"))),this.configProvider.config.iceCandidateTransport&&(S=!!g.transport.match(new RegExp(this.configProvider.config.iceCandidateTransport,"i"))),this.configProvider.config.iceCandidateFilterMDns&&(v=!this.isMdns(g.ip),v||this.logger.safe.info(`Filtering out mDNS candidate ${scrubMriOrOmit(g.ip)}:${scrubMriOrOmit(g.port)}`)),f&&S&&v}))),f&&g.connection&&this.configProvider.config.iceCandidateFilterMDns&&(g.candidates&&0!==g.candidates.length||(g.candidates=[getDummyCandidate(g.port)]),this.isMdns(g.connection.ip)||!this.hasMatchingCandidate(g))){const f=this.getDefaultCandidate(g);g.connection.ip=f.ip,g.port=f.port}}))}hasMatchingCandidate(g){const f=g.connection;return f&&!!g.candidates.find(this.createIpAndPortMatcher(f.ip,g.port))}getDefaultCandidate(g){return g.candidates.slice().sort(((g,f)=>g.type===f.type?0:"host"===g.type||"relay"===f.type?1:"relay"===g.type||"host"===f.type?-1:0))[0]}isMdns(g){return g.indexOf(".local")>-1||g.indexOf(".encrypted")>-1}createIpAndPortMatcher(g,f){return S=>S.ip===g&&S.port===f}},C_=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.useOneRelayCandidateForRemoteSDP&&g.media.forEach((g=>{if(g.candidates){const f=g.candidates.filter((g=>!!g.type.match(new RegExp("relay","i"))));f.length>0&&(g.candidates=f.slice(0,1))}}))}},y_=class{modify(g){const f=getEnabledMedia(g)[0];f&&(f.candidates=[getDummyCandidate()])}},E_=class{constructor(g,f){this.mediaManager=g,this.configProvider=f}modify(g){g.media.forEach(((g,f)=>{this.fromMsSdp(g,f)}))}fromMsSdp(g,f){if(isMediaDisabled(g)||g.rids&&g.simulcast)return;const S=this.mediaManager.getMediaEntities()[f],v=S?.getSimulcastContext();v?.shouldBeEnabledInRemoteDesc()&&(v.enableInRemoteDesc(),g.simulcast={dir1:"recv",list1:this.configProvider.config.specCompliantSimulcast?.disableTilde?v.ridList.map((g=>`${g}`)).join(";"):v.ridList.map((g=>`${v.activeRids.includes(g)?"":"~"}${g}`)).join(";")},g.rids=v.ridList.map((g=>({id:g,direction:"recv"}))))}},T_=class{constructor(g,f){this.mediaManager=g,this.logger=f}modify(g){g.media.forEach(((g,f)=>{this.toMsSdp(g,f)}))}toMsSdp(g,f){const S=this.mediaManager.getMediaEntities()[f],v=S?.getSimulcastContext();v&&(v.localDescriptionIsApplied(),v.shouldBeEnabledInLocalDesc()&&(v.enableInLocalDesc(),this.removeSimulcastEnvelope(g),this.addStreamSsrc(g,S.getLocalSsrc())))}removeSimulcastEnvelope(g){g.rids&&delete g.rids,g.simulcast&&delete g.simulcast}addStreamSsrc(g,f){if(!f)return;if(g.ssrcs)return void this.logger.safe.debug(`Media mid: ${g.mid} already contains ssrc: ${JSON.stringify(g.ssrcs)}`);const S=f;this.setSsrc(g,S)}setSsrc(g,f){g.ssrcs=[{id:f,attribute:"fake_attribute",value:"fake_value"}]}},I_=class{constructor(g){this.mediaManager=g}modify(g){g.media.forEach(((g,f)=>{const S=this.mediaManager.getMediaEntities()[f],v=S?.getLocalTrackId();(!g.msid&&S?.getSimulcastContext()?.shouldUseSimulcast()&&v||S?.getExtension("reinviteless"))&&(g.msid=`- ${v??f}`)}))}},b_=class{constructor(g,f){this.mediaManager=g,this.configProvider=f}modify(g){const f=this.mediaManager.getMediaEntities(),S=(0,eE.flatMap)(f,(g=>g.getRtpHeaderExtensions())),v=S.find((g=>"vla"===g?.headerType))?.value,C=S.find((g=>"non-adv-vla"===g?.headerType))?.value,_=v??C??(0,eE.flatMap)(g.media,(g=>g.ext||[])).find((g=>g.uri===qt.VLA.EXT_URI))?.value,T=getFreeValueForExt(g,this.configProvider.config.extmapAllowMixed,qt.VLA.DEFAULT_VALUE);g.media.forEach(((g,S)=>{const v=getModalityForMedia(g);if(!(this.configProvider.config.enableVla&&("Video"===v||"ScreenShare"===v)))return;if(g.ext?.find((g=>g.uri===qt.VLA.EXT_URI)))return;const C=f[S]?.getRtpHeaderExtensions(),I=C?C.find((g=>"vla"===g.headerType))?.value??C.find((g=>"non-adv-vla"===g.headerType))?.value:_??T;I&&(g.ext=g.ext||[],g.ext.push({value:I,uri:qt.VLA.EXT_URI}))}))}},A_=class{constructor(g){this.configProvider=g}modify(g){g.media.forEach((g=>{const f=getModalityForMedia(g);if(this.configProvider.config.allowRemoteVla&&("Video"===f||"ScreenShare"===f))return;const S=g.ext?.findIndex((g=>g.uri===qt.VLA.EXT_URI));S>-1&&g.ext.splice(S,1)}))}},P_=class{constructor(g){this.configProvider=g}modify(g,f,S){g.media.forEach((g=>{const v=getModalityForMedia(g);if(!(this.configProvider.config.enableNonAdvVla&&("Video"===v||"ScreenShare"===v))||g.ext?.find((g=>g.uri===S)))return;const C=g.ext?.find((g=>g.uri===f));C&&(C.uri=S)}))}},R_=class extends P_{constructor(g,f){super(g),this.mediaManager=f}modify(g){const f=this.mediaManager.getMediaEntities();(0,eE.flatMap)(f,(g=>g.getRtpHeaderExtensions())).some((g=>"vla"===g?.headerType))||super.modify(g,qt.VLA.EXT_URI,qt.VLA.EXT_URI_NON_ADV)}},M_=class extends P_{constructor(g){super(g)}modify(g){super.modify(g,qt.VLA.EXT_URI_NON_ADV,qt.VLA.EXT_URI)}},w_=class{modify(g){g.media.forEach((g=>{g.ext?.forEach((g=>g.uri=this.normalizeSlashesInUri(g.uri)))}))}normalizeSlashesInUri(g){return g.replace(/\\/g,"/")}},O_=class{constructor(g){this.configProvider=g}modify(g){if(this.configProvider.config.fixSdpForPartialIceRestart){const[{iceUfrag:f,icePwd:S}={}]=g.media;void 0!==f&&void 0!==S&&g.media.forEach((g=>{g.iceUfrag=f,g.icePwd=S}))}}},D_=class{constructor(g){this.configProvider=g}modify(g){if(this.configProvider.config.reduceRtcpFbInSdp?.length)for(const f of getEnabledMedia(g,qt.MEDIA_TYPE.video))f.rtcpFb=f.rtcpFb&&this.getFbList(f.rtcpFb)}getFbList(g){const f=[],S=[];for(const v of g){const g=v.subtype?`${v.type}/${v.subtype}`:`${v.type}`;f.includes(g)||(this.configProvider.config.reduceRtcpFbInSdp.includes(g)?(f.push(g),S.push({...v,payload:"*"})):S.push(v))}return S}},N_=class{constructor(g){this.configProvider=g}modify(g){if(!this.configProvider.config.redReceiveEnabled)return;const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));let S=0;forOneCodec(f,{codec:"opus",rate:48e3,encoding:2},(g=>{S=g.rtp.payload}));const v={codec:"RED",rate:8e3};forOneCodec(f,v,(g=>{g.rtp.rate=48e3,g.rtp.encoding=2,S&&(g.fmtp={payload:g.rtp.payload,config:`${S}/${S}`})})),removeCodec(f,v)}},k_=class{constructor(g){this.configProvider=g}modify(g){if(!this.configProvider.config.redReceiveEnabled)return;forOneCodec(g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),{codec:"red",rate:48e3,encoding:2},(g=>{g.rtp.codec="RED",g.rtp.rate=8e3,delete g.rtp.encoding}))}},L_=class{constructor(g,f){this.configProvider=g,this.sdpType=f}modify(g){if(!this.configProvider.config.redReceiveEnabled||"offer"!==this.sdpType)return;const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),S={codec:"red",rate:48e3,encoding:2};let v=0;if(forOneCodec(f,S,(g=>{v=g.rtp.payload})),v===qt.PAYLOAD_TYPE.MSRTC_RED)return;const C=findAvailablePayload(g);-1!==C&&(changePayloadType(g,qt.PAYLOAD_TYPE.MSRTC_RED,C),forOneCodec(f,S,(g=>{g.rtp.payload=qt.PAYLOAD_TYPE.MSRTC_RED})))}},F_=class{constructor(g,f){this.modification=g,this.context=f,this.logger=f.getLogger().createChild("IncomingDtlsRoleModifier")}modify(g){if("answer"!==this.modification.sdpType)if("offer"===this.modification.sdpType&&2===this.modification.sdpSource){if(this.modification.isOrWasProvisional){const f=this.context.config.isPstnCall?this.context.configProvider.config.createProvisionalAnswer.dtlsRolePstn:this.context.configProvider.config.createProvisionalAnswer.dtlsRole;if(!f)return;this.logger.debug(`Configured DTLS role override: ${f}`),g.media.forEach(((g,S)=>{const v=g.setup;"inactive"!==g.direction&&(v&&"actpass"!==v?this.logger.warn(`Remote DTLS role is ${v}, cannot change`):(g.setup=f,this.logger.debug(`Remote DTLS role changed from ${v} to ${g.setup} for mid=${g.mid}`)))}))}}else this.logger.error(`Tried to apply invalid change to DTLS role: ${this.modification.sdpType} ${this.modification.sdpSource}`)}};function disabledMedia(g,f,S,v){const C={type:g,port:0,label:f,payloads:g===qt.MEDIA_TYPE.dataChannel||g===qt.MEDIA_TYPE.data?qt.PAYLOAD_TYPE.DATA_CHANNEL:"36",protocol:S,connection:{ip:"10.10.10.10",version:4}};return v&&(C.mid=v),C}function getEnabledMedia(g,f=null){return g.media.filter((g=>!(isMediaDisabled(g)||f&&g.type!==f)))}function getDummyCandidate(g=1234){return{component:1,ip:"10.10.10.10",foundation:"1755259772",priority:2122197247,port:g!==9?g:1234,transport:"UDP",type:"host"}}function getFreeValueForExt(g,f,S,v=!1){const C=(0,eE.flatMap)(g.media,(g=>g.ext||[])).map((g=>g.value));if(0===C.length)return S;const _=2,T=14;if(v&&!C.includes(S))return S;let I;for(let g=_;g<=T;g++)if(!C.includes(g)){I=g;break}return!I&&f&&(I=Math.max(...C)+1),I}function getCustomCodecParams(g,f){if(!Ra[g]?.[f])throw`unsupported codec ${g} or type ${f}`;const S=Ra[g][f];return{codec:S.NAME,rate:S.RATE,encoding:S.ENCODING,payload:Ra[g].PT}}function changePayloadType(g,f,S){for(const v of g.media)updatePayload(v,f,S)}function changeCodecPayload(g,f,S,v,C){const _=new Set;return forAllCodecs(g,f,(g=>{g.rtp.payload<96&&(_.add(g.rtp.payload),g.rtp.payload=S[C]??g.rtp.payload,C++)}),v),_}var x_=class _SessionDescription{constructor(g,f,S,v){this.context=g,this.sessionType=f,this.sdp=S,this.remote=v,this.mediaManager=this.context.mediaManager,this.sdpTransform=this.context.sdpTransform,this.logger=this.context.logger.createChild("SessionDescr"),this.sdpModel=Qy.parse(this.sdp),v&&new c_(this.context.configProvider).modify(this.sdpModel),this.sdpModel.media.forEach((g=>{(0,Yy.isUndefined)(g.mid)||(g.mid=g.mid.toString())})),this.remote&&!this.context.configProvider.config.disableMsSdp&&new TE(g,this.mediaManager,f).modify(this.sdpModel)}getSdp(){return Qy.write(this.sdpModel)}clone(){return new _SessionDescription(this.context,this.sessionType,this.sdp,this.remote)}getModalities(){return this.modalities||getModalities(this.sdpModel)}updateModalities(g){this.logger.debug("updateModalities",g),this.modalities=g}getSrtpInfo(){return getSrtpInfo(this.sdpModel)}getVideoCodecs(){const g={};return this.sdpModel.media.forEach((f=>{"video"===f.type&&f.rtp.map((g=>g.codec.toLowerCase())).forEach((f=>g[f]=!0))})),Object.keys(g)}usePrimaryAudioCodecOnly(g){new s_(g).modify(this.sdpModel)}isCodecSwitchSupported(){return!this.sdpModel.media.some((g=>g.type===qt.MEDIA_TYPE.audio&&g.xMediaSettings&&this.containsMediaSetting(g.xMediaSettings,"codecswitchunsupported")))}toLocal(){return this.sdpModel=this.sdpTransform.toLocal(this.sdpModel,this.mediaManager,this.sessionType),this.getSdp()}toOffer(){return this.toOfferAnswer()}toAnswer(){return this.toOfferAnswer()}toOfferAnswer(){const g="offer"===this.sessionType;return new v_(this.context.configProvider,this.logger).modify(this.sdpModel),(new f_).modify(this.sdpModel),g&&this.mediaManager.isEmpty()&&this.mediaManager.fromOffer(this.sdpModel,this.modalities),this.mediaManager.syncModalities(this.sdpModel,this.modalities,!g),this.sdpModel=g?this.sdpTransform.toOffer(this.sdpModel,this.mediaManager,this.modalities):this.sdpTransform.toAnswer(this.sdpModel,this.mediaManager,this.modalities),this.context.configProvider.config.disableMsSdp||new _E(this.context,this.mediaManager,this.sessionType).modify(this.sdpModel),new o_(this.mediaManager,this.context.configProvider).modify(this.sdpModel),this.modalities=getModalities(this.sdpModel),this.getSdp()}setModalities(g){this.modalities=g,this.mediaManager.fromRemote(this.sdpModel,this.modalities)}toRemote(g=!1){return this.sdpModel=this.sdpTransform.toRemote(this.sdpModel,this.mediaManager,this.modalities,this.sessionType,g),this.getSdp()}getVideoRecvCapabilities(){return getRecvCapabilitiesForMedia(this.getMediaByLabel(qt.MEDIA_LABEL.video))}getSharingRecvCapabilities(){return getRecvCapabilitiesForMedia(this.getMediaByLabel(qt.MEDIA_LABEL.sharing))}getMediaByType(g){return this.sdpModel.media.find((f=>f.type===g))}isUnbundled(){const g=this.sdpModel.groups?.find((g=>"BUNDLE"===g.type)),f=this.sdpModel.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),S=this.sdpModel.media.find((g=>g.type===qt.MEDIA_TYPE.video));return g?!g.mids.toString().split(" ").find((g=>g===f.mid)):!!S}couldBeUnbundled(){return!this.sdpModel.groups?.find((g=>"BUNDLE"===g.type))||this.hasUnbundledIceCandidates()}containsMediaSetting(g,f){return g.some((g=>-1!==g.settings.indexOf(f)))}getMediaByLabel(g){return this.sdpModel.media.find((f=>f.label===g))}hasIceCandidatesForMediaType(g,f=""){const S=this.sdpModel.media?this.sdpModel.media.filter((f=>f.type===g&&!!f.candidates&&0!==f.candidates.length)):[];return f?S.some((g=>!!g.candidates&&g.candidates.some((g=>g.type===f)))):!!S.length}hasIceCandidates(){return this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.audio)||this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.video)}hasRelayIceCandidates(){return this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.audio,"relay")||this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.video,"relay")}hasUnbundledIceCandidates(){const g=this.sdpModel.media.filter((g=>g.type===qt.MEDIA_TYPE.video&&0!==g.port));return this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.audio)&&(!g.length||this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.video))}hasUnbundledRelayIceCandidates(){const g=this.sdpModel.media.filter((g=>g.type===qt.MEDIA_TYPE.video&&0!==g.port));return this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.audio,"relay")&&(!g.length||this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.video,"relay"))}isIceRestart(){return this.mediaManager.getMediaEntities().some((g=>g.getExtension("iceRestart")))}isMSRTC(){return!!this.sdpModel.xMediaBw}insertFakeCandidateIfNeeded(){return!this.hasIceCandidates()&&((new y_).modify(this.sdpModel),!0)}forceRecvonly(){(new AE).modify(this.sdpModel)}getBweType(){const g=this.sdpModel.media.find((g=>0!==g.port&&g.type===qt.MEDIA_TYPE.video));if(!g)return"Unknown";const f=g.ext?.find((g=>g.uri===qt.TRANSPORT_CC.EXT_URI||g.uri===qt.TRANSPORT_CC.MSSDP_ENCODED_URI));return f?"SSBWE":"REMB"}fixDataModality(){new ME(this.mediaManager).modify(this.sdpModel)}getPayloadsForMedia(g){const f=this.sdpModel.media.find((f=>f.type===g&&0!==f.port));return f?.rtp??[]}},U_=class{constructor(g){this.context=g}createLocalOffer(g){return new x_(this.context,"offer",g)}createRemoteOffer(g){return new x_(this.context,"offer",g,!0)}createLocalAnswer(g){return new x_(this.context,"answer",g)}createRemoteAnswer(g){return new x_(this.context,"answer",g,!0)}},V_=class{static build(g){return new U_(g=g||{})}};function getSrtpReport(g){let f="";return g.dtls&&(f+="dtls"),g.sdes&&(f+="sdes"),f}var B_=class{constructor(){this.info={OfferedSrtp:"none",NegotiatedSrtp:"none",IceConnectionState:"none",IceConnectionStatePrevious:"none",SignalingState:"none",SignalingStatePrevious:"none",RelayCandidate:"none",IceTransportPolicy:"none",IceServers:"none",FakeIceCandidate:!1,BweType:"none",SdpSemantics:"none",BundlePolicy:"none",IPAddress:"none",ReflexiveLocalIP:"none",NumberOfInterfaces:0,EncodedStreamWorker:!1,AudioCodecEvents:"none"}}setCandidateDetails(g){"host"===g.type&&"udp"===g.protocol?this.setIPAddressInfo(g.ip):"srflx"===g.type&&this.setReflexiveLocalIP(g.ip)}setOfferedModalities(g){this.offeredModalities=g,this.activeModalities=g}setNegotiatedModalities(g){this.negotiatedModalities=g,this.activeModalities=g}setNegotiatedSrtpInfo(g){this.info.NegotiatedSrtp=getSrtpReport(g)}setOfferedSrtpInfo(g){this.info.OfferedSrtp=getSrtpReport(g)}setIceConnectionState(g){this.info.IceConnectionStatePrevious=this.info.IceConnectionState,this.info.IceConnectionState=g}setSignalingConnectionState(g){this.info.SignalingStatePrevious=this.info.SignalingState,this.info.SignalingState=g}setRelayCandidateInfo(g){this.info.RelayCandidate=JSON.stringify(g)}fillExtensionInfo(g){assign(g,this.info)}setIceTransportPolicy(g){this.info.IceTransportPolicy=g}setIceServers(g){const f=g.map((g=>{const f={...g};return f.username&&(f.username="true"),f.credential&&(f.credential="true"),f}));this.info.IceServers=JSON.stringify(f)}setFakeIceCandidate(g){this.info.FakeIceCandidate=g}setBweType(g){"Unknown"!==g&&(this.info.BweType=g)}setSdpSemantics(g){this.info.SdpSemantics=g}setBundlePolicy(g){this.info.BundlePolicy=g}setEncodedStreamWorkerLoaded(g){this.info.EncodedStreamWorker=g}setAudioCodecEvents(g){this.info.AudioCodecEvents=JSON.stringify(g)}setIPAddressInfo(g){this.info.NumberOfInterfaces+=1,"none"===this.info.IPAddress&&(this.info.IPAddress=g)}setReflexiveLocalIP(g){"none"===this.info.ReflexiveLocalIP&&(this.info.ReflexiveLocalIP=g)}},H_=class{constructor(){this.presentationAPIUserDuration=0,this.presentationAudioDuration=0,this.isActiveScreenSharing=!1}handleInputLevel(g,f){this.isActiveScreenSharing&&("ScreenShare"===g&&f>0&&(this.presentationAPIUserDuration+=qt.TIME_INTERVAL.SEC_1),"Audio"===g&&f>0&&(this.presentationAudioDuration+=qt.TIME_INTERVAL.SEC_1))}updateScreenSharingStream(g,f){"ScreenShare"===f&&(this.isActiveScreenSharing=!!g)}getPresentationAudioDuration(){return this.presentationAudioDuration}getPresentationAudioAPIUserDuration(){return this.presentationAPIUserDuration}},$_=class _TimerTracker{constructor(g){this.name=g,this.sharedState={mark:new Map,measure:[]}}mark(g,f){const S=Jt();this.sharedState.mark.set(g,{name:g,ts:S,startTime:round(Yt+S),details:f})}measure(g,f){const S=this.sharedState.mark.get(f.start),v=this.sharedState.mark.get(f.end);if(S&&v){const C={...f,parentName:this.name===g?"":this.name};this.sharedState.measure.push({name:g,details:C,duration:round(v.ts-S.ts),startTime:S.startTime})}}markAndMeasure(g,f,S,v){!1===this.sharedState.mark.has(f)&&this.mark(f,S);const C=this.sharedState.mark.get(g),_=this.sharedState.mark.get(f);if(C&&_){const g={...v,parentName:this.name===f?"":this.name};this.sharedState.measure.push({name:f,details:g,duration:round(_.ts-C.ts),startTime:C.startTime})}}clone(g){const f=new _TimerTracker(`${this.name}|${g}`);return f.setSharedState(this.sharedState),f}setSharedState(g){this.sharedState=g}getReport(){return this.sharedState.measure.map((g=>({name:g.name,duration:g.duration,ts:g.startTime,parentName:g.details.parentName})))}},j_=class _NoopTracker{mark(){}measure(){}markAndMeasure(){}clone(){return new _NoopTracker}getReport(){return[]}},G_=class{constructor(g){this.enableTimerTracker=g,this.timerTrackers={},this.timerTrackerOptions={}}getTimerTracker(g,f){if(!this.enableTimerTracker)return new j_;const S=new $_(g);if(this.timerTrackers[g]){const f=this.timerTrackerOptions[g];if(f?.first)return new j_;f?.last&&(this.timerTrackers[g]=[S]),f?.all&&this.timerTrackers[g].push(S)}else this.timerTrackers[g]=[S],this.timerTrackerOptions[g]=f;return S}getReport(){if(this.enableTimerTracker)return Object.keys(this.timerTrackers).reduce(((g,f)=>{const S=this.timerTrackerOptions[f];return(S.first||S.last)&&(g[f]=[this.timerTrackers[f][0]?.getReport()]),S.all&&(g[f]=Object.values(this.timerTrackers[f]).map((g=>g?.getReport()))),g}),{})}},q_=class{constructor(g,f){this.configProvider=g,this.sessionInfo=f,this.data={fakeCandidate:!1,bweType:"Unknown",offeredSrtp:"unknown",negotiatedSrtp:"unknown",callSetupTimeReport:{}},this.timerTrackerManager=new G_(this.configProvider.config.enableTimerTracker),addGetterFields(this.data,{callSetupTimeReport:()=>this.timerTrackerManager.getReport()})}getTimerTracker(g,f){return this.timerTrackerManager.getTimerTracker(g,f)}set offeredModalities(g){this.data.offeredModalities=g,this.data.activeModalities=g,this.sessionInfo.setOfferedModalities(g)}set negotiatedModalities(g){this.data.negotiatedModalities=g,this.data.activeModalities=g,this.sessionInfo.setNegotiatedModalities(g)}set fakeCandidate(g){var f;(f=this.data).fakeCandidate||(f.fakeCandidate=g),this.sessionInfo.setFakeIceCandidate(g)}set bweType(g){this.data.bweType=g,this.sessionInfo.setBweType(g)}set negotiatedSrtp(g){this.data.negotiatedSrtp=getSrtpReport2(g),this.sessionInfo.setNegotiatedSrtpInfo(g)}set offeredSrtp(g){this.data.offeredSrtp=getSrtpReport2(g),this.sessionInfo.setOfferedSrtpInfo(g)}set meetingScenario(g){this.data.meetingScenario=g}set isTownHall(g){this.data.isTownHall=g}getObjectRef(){return this.data}};function getSrtpReport2(g){let f="";return g.dtls&&(f+="dtls"),g.sdes&&(f+="sdes"),f}var W_=class{constructor(g){this.data=g,this.reopenRequestDeviceIds=new Set}registerReopenRequest(g){this.reopenRequestDeviceIds.has(g)||(this.data.sinkNumOfReopenRequests++,this.reopenRequestDeviceIds.add(g))}registerSuccessfullReopen(g){this.reopenRequestDeviceIds.has(g)&&(this.data.sinkNumOfSuccessfulReopens++,this.reopenRequestDeviceIds.delete(g))}getObjectRef(){return this.data}},z_=class{constructor(g){this.configProvider=g,this.data={signalingState:"none",signalingStatePrevious:"none",iceConnectionState:"none",iceConnectionStatePrevious:"none",numCallbacksScheduled:0,numCallbacksExecuted:0,numCallbacksExecutedImmediately:0,scheduledCallbacks:[],events:[],timers:{}},this.scheduledCallbacks=new Map,this.stateTrackers={},addGetterFields(this.data,{scheduledCallbacks:()=>this.scheduledCallbacks.values(),timers:()=>{const g={};for(const f of Object.keys(this.stateTrackers))g[f]=this.stateTrackers[f].durations;return g}})}dispose(){for(const g of Object.values(this.stateTrackers))g.dispose()}set hasConnectionState(g){this.data.hasConnectionState=g}set transportState(g){this.data.transportStatePrevious=this.data.transportState,this.data.transportState=g,this.addStateEvent("transport",this.data.transportStatePrevious,this.data.transportState)}set signalingState(g){this.data.signalingStatePrevious=this.data.signalingState,this.data.signalingState=g,this.addStateEvent("signaling",this.data.signalingStatePrevious,this.data.signalingState)}set iceConnectionState(g){this.data.iceConnectionStatePrevious=this.data.iceConnectionState,this.data.iceConnectionState=g,this.addStateEvent("ice",this.data.iceConnectionStatePrevious,this.data.iceConnectionState)}set connectionState(g){this.data.connectionStatePrevious=this.data.connectionState,this.data.connectionState=g,this.addStateEvent("connection",this.data.connectionStatePrevious,this.data.connectionState)}set dtlsTransportState(g){this.data.dtlsTtransportStatePrevious=this.data.dtlsTransportState,this.data.dtlsTransportState=g,this.addStateEvent("dtlsTransport",this.data.dtlsTtransportStatePrevious,this.data.dtlsTransportState)}set provisional(g){this.addStateEvent("provisional",`${this.data.isProvisional}`,`${g}`),this.data.isProvisional=g}scheduleDoOnConnected(g,f,S,v){this.scheduledCallbacks.set(g,`${f}: ${S?"p":""}${v?"n":""}`),this.addCallbackEvent(f,S,v),this.data.numCallbacksScheduled++}runDoOnConnected(g,f=!1){this.scheduledCallbacks.get(g)&&this.scheduledCallbacks.delete(g),this.data.numCallbacksExecuted++,f&&this.data.numCallbacksExecutedImmediately++}getObjectRef(){return this.data}addCallbackEvent(g,f,S){arrayLimitedPush(this.data.events,{evType:"callback",timestamp:Date.now(),logName:g,allowProvisional:f,mayRunImmediately:S},this.configProvider.config.diagnostics.collectionLimits.numTransportStateEvents)}addStateEvent(g,f,S){arrayLimitedPush(this.data.events,{evType:"stateChanged",timestamp:Date.now(),changedState:g,previous:f,current:S},this.configProvider.config.diagnostics.collectionLimits.numTransportStateEvents);const v=this.stateTrackers[g]??new K_;v.state=S,this.stateTrackers[g]=v}},K_=class{constructor(){this.stopwatches={}}set state(g){if(this.stateInternal===g)return;this.running?.stop();const f=this.stopwatches[g]??new eT;this.stopwatches[g]=f,f.start(),this.running=f,this.stateInternal=g}get durations(){const g={};for(const f in this.stopwatches){const S=this.stopwatches[f];g[f]=S.elapsed}return g}dispose(){this.running?.stop(),this.running=void 0}},J_=/profile-level-id=(.{6})/,Y_=class{constructor(g,f,S=(()=>{}),v=(()=>this),C=(()=>{}),_=new Hy,T){this.configProvider=g,this.dmDiagnostics=f,this.addSessionStatsError=S,this.newNativeSession=v,this.commitNativeSession=C,this.dshDiagnostics=_,this.getSessionRef=T,this.data={startTime:Date.now(),duration:0,relayCandidate:"none",iceTransportPolicy:"none",iceServers:"none",sdpSemantics:"none",bundlePolicy:"none",iceCandidateErrors:[],H264Profiles:[],h264CodecCapabilities:{sendProfiles:[],receiveProfiles:[]},numInterfaces:0,statsReports:[],aggregatedModalityStats:{},multiViewStats:[],networkInfo:[],statsErrors:[],statsOnSubscribed:{},negotiation:{},recvVideoStreamCount:{min:0,max:0,mode:0},reportedReceiveBandwidth:[],reportedSendBandwidthLayouts:[],encodedStreamWorker:!1,audioCodecEvents:"none",totalVideoRecvMblocksRates:{macroblockRateReceivedMax:0,macroblockRateReceivedAvg:0,macroblockRateDecodedMax:0,macroblockRateDecodedAvg:0,macroblockRateMaxDecoderLossPercent:0,macroblockRateDecoderLossPercent:0},loopIntervalMax:-1,loopIntervalMedian:-1,fetchTimeMax:-1,fetchTimeMedian:-1,videoPerformanceEvent:[],localVideoPerformanceEvents:[],ovcToSubscriptionEvents:[],presentationAPIUserDuration:0,presentationAudioDuration:0,earlyMediaNumStatsPolls:0,audioRenderer:null},this.presentationAudioTelemetry=new H_,addGetterFields(this.data,{duration:()=>this.data.endTime?this.data.endTime-this.data.startTime:Date.now()-this.data.startTime,bandwidthReport:()=>this.bandwidthStatsRef?.getBandwidthReport(),presentationAPIUserDuration:()=>this.presentationAudioTelemetry.getPresentationAudioAPIUserDuration(),presentationAudioDuration:()=>this.presentationAudioTelemetry.getPresentationAudioDuration()}),Object.defineProperty(this.data,"IPAddress",{enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(this.data,"reflexiveLocalIP",{enumerable:!1,writable:!0,configurable:!0})}get deviceManager(){return this.dmDiagnostics}get audioLevel(){return this.analyzer?.getInputLevelNormalized()}get reflexiveLocalIP(){return this.data.reflexiveLocalIP}set bandwidthDiagnostic(g){this.bandwidthStatsRef=g}get callIsMuted(){return this.getSessionRef?.().callIsMuted}get sharingAudioLevel(){return this.analyzerSharing?.getInputLevelNormalized()}set relayCandidateInfo(g){this.data.relayCandidate=JSON.stringify(g)}set iceTransportPolicy(g){this.data.iceTransportPolicy=g}set reinvitelessContext(g){this.data.reinvitelessContext=g}set iceServers(g){const f=g.map((g=>{const f={...g};return f.username&&(f.username="true"),f.credential&&(f.credential="true"),f}));this.data.iceServers=JSON.stringify(f)}set sdpSemantics(g){this.data.sdpSemantics=g}set isCodecsSupported(g){this.data.codecSupport=g}set bundlePolicy(g){this.data.bundlePolicy=g}set latestRawReport(g){this.data.latestRawReport=g}set recvVideoStreamsCount(g){this.data.recvVideoStreamCount=g}set aggregatedStatsRef(g){this.data.aggregatedModalityStats=g}set multiViewStats(g){this.data.multiViewStats=g}set videoCapabilities(g){if(!g?.codecs)return;const f=[];g.codecs.forEach((g=>{if("h264"===g.mimeType&&g.sdpFmtpLine){const S=J_.exec(g.sdpFmtpLine)?.[1];S&&f.push(S)}})),this.data.H264Profiles=[...new Set(this.data.H264Profiles.concat(f))]}setSupportedH264Profiles(g,f){if(!g?.codecs&&!f?.codecs)return;const extractProfiles=g=>{const f=[];return g.codecs?.forEach((g=>{if("h264"===g.mimeType&&g.sdpFmtpLine){const S=J_.exec(g.sdpFmtpLine)?.[1];S&&!f.includes(S)&&f.push(S)}})),f};this.data.h264CodecCapabilities.sendProfiles=extractProfiles(g),this.data.h264CodecCapabilities.receiveProfiles=extractProfiles(f)}set sentBWSeed(g){var f;(f=this.data).initialBWSeed??(f.initialBWSeed=g),this.data.sentBWSeed=g}reportedSendBandwidthLayouts(g){arrayLimitedPush(this.data.reportedSendBandwidthLayouts,g,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}set maxSessionBandwidth(g){this.data.maxSessionBandwidth=g}set bwStabilizationTime(g){this.data.bwStabilizationTime=g}set bwDownlinkStabilizationTime(g){this.data.bwDownlinkStabilizationTime=g}set statsOnSubscribed(g){this.data.statsOnSubscribed=g}set loopIntervalMax(g){this.data.loopIntervalMax=g}set loopIntervalMedian(g){this.data.loopIntervalMedian=g}set fetchTimeMax(g){this.data.fetchTimeMax=g}set fetchTimeMedian(g){this.data.fetchTimeMedian=g}set simulcastReport(g){this.data.simulcast=g}setTotalVideoRecvMblocksRates(g){this.data.totalVideoRecvMblocksRates=g}set dataChannelSessionState(g){this.data.dataChannelSessionState=g}set createChannelFailReason(g){this.data.dataChannelCreationError=g}setCandidateDetails(g){"host"===g.type&&"udp"===g.protocol?(this.data.numInterfaces++,this.data.IPAddress||(this.data.IPAddress=g.ip)):"srflx"!==g.type||this.data.reflexiveLocalIP||(this.data.reflexiveLocalIP=g.ip)}setAudioSendStream(g,f){if(this.configProvider.config.useAudioAnalyzer){const S=new My(g.rawStream);"ScreenShare"===f&&g.hasAudio()?(this.analyzerSharing?.dispose(),this.analyzerSharing=S):"Audio"===f&&(this.analyzer?.dispose(),this.analyzer=S)}}addNetworkInfo(g){arrayLimitedPush(this.data.networkInfo,g,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addIceCandidateError(g){this.data.iceCandidateErrors.push(g)}clearIceCandidateErrors(){this.data.iceCandidateErrors=[]}registerEarlyMediaPoll(){this.data.earlyMediaNumStatsPolls++}addReportedReceiveBandwidth(g){arrayLimitedPush(this.data.reportedReceiveBandwidth,g,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addOvcSubscriptionReport(g,f,S){const v=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];v?.ovc.count!==g&&arrayLimitedPush(this.data.ovcToSubscriptionEvents,{ovc:{ts:Date.now(),count:g,subsCount:f,...S},subs:[]},this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents)}addSubscriptionToOvcEvent(g){const f=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];f&&arrayLimitedPush(f.subs,{ts:Date.now(),count:g},this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents)}addStatsReport(g){arrayLimitedPush(this.data.statsReports,g,this.configProvider.config.diagnostics.collectionLimits.numStatsReports)}addStatsError(g,f){const S=this.data.statsErrors.find((S=>S.error===f&&S.origin===g));S?S.count++:arrayLimitedPush(this.data.statsErrors,{origin:g,error:f,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors),this.addSessionStatsError(`nativeSession:${g}`,f)}setPresentationAudioOnScreenSharing(g,f){this.presentationAudioTelemetry.updateScreenSharingStream(g,f)}handlePresentationAudioInputLevel(){this.presentationAudioTelemetry.handleInputLevel("Audio",this.audioLevel),this.presentationAudioTelemetry.handleInputLevel("ScreenShare",this.sharingAudioLevel)}terminate(){this.data.endTime=Date.now(),this.analyzer?.dispose(),this.analyzer=null,this.analyzerSharing?.dispose(),this.analyzerSharing=null}newQualityManagerDiagnostics(){const g=new zy(this.configProvider,((g,f)=>this.addStatsError(`qualityManagerDiagnostics:${g}`,f)));return this.data.qualityManager=g.getObjectRef(),g}newRemoteVideoManagerDiagnostics(){const g=new Ky(this.configProvider);return this.data.remoteVideoManager=g.getObjectRef(),g}newNegotiationDiagnostics(g){const f=new q_(this.configProvider,g);return this.data.negotiation=f.getObjectRef(),f}newSubscriptionManagerDiagnostics(){const g=new Wy(this.configProvider,(g=>this.addStatsError("subscriptionManagerDiagnostics",g)));return this.data.subscriptionManager=g.getObjectRef(),g}newDataChannelDiagnostics(g){const f=new _s(g);return this.data.dataChannel=f.getObjectRef(),f}newTransportStateDiagnostics(){const g=new z_(this.configProvider);return this.data.transportState=g.getObjectRef(),g}set encodedStreamWorker(g){this.data.encodedStreamWorker=g}set audioCodecEvents(g){this.data.audioCodecEvents=g}getObjectRef(){return this.data}registerVideoPerformanceEvent(g,f,S){const v={type:f,perfEvent:g,resRequestEvent:null,resChangedEvent:[],perfConstrainedOvc:S};arrayLimitedPush(this.data.videoPerformanceEvent,v,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}registerLocalVideoPerformanceEvent(g){arrayLimitedPush(this.data.localVideoPerformanceEvents,{timestamp:Date.now(),description:g.description,activeModalities:g.activeModalities,isTransient:g.isTransient},this.configProvider.config.diagnostics.collectionLimits.numPerformanceEvents)}registerResolutionChangeRequest(g){const f=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];f&&(f.resRequestEvent=g)}registerResolutionChangeEvent(g){const f=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];g.ts-f?.resRequestEvent?.ts<this.configProvider.config.diagnostics.performanceMonitoring.telemetryResolutionRequestSpanMs&&f.resChangedEvent.push(g)}set contributingSourcesError(g){this.data.contributingSourcesError=g}newAudioRendererDiagnostics(){return this.data.audioRenderer=this.getSessionRef?.().audioRenderer,this.data.audioRenderer?new W_(this.data.audioRenderer):null}},Q_=Symbol("sessionDiagnosticsRef"),X_=class{constructor(g,f,S,v,C,_){this.logger=g,this.configProvider=f,this.diagnosticsReport=S,this.dmDiagnostics=v,this.dshDiagnostics=new Hy,this.data={creationTime:Date.now(),callNumber:0,sessionId:"unknown",isMultiParty:!1,dtmfSuccessCount:0,dtmfFailureCount:0,iceInitTime:0,iceConnectedStateTime:0,negotiationCount:0,rejectedNegotiationCount:0,initialNegotiationCompleted:!1,finalAnswerTime:0,transportReconnectedCount:0,rollbackNegotiation:[],activeModalities:{},allowedAudioSend:!0,allowedVideoSend:!0,allowedScreensharingSend:!0,noIceCandidatesEventCount:{good:0,bad:0},noRelayIceCandidatesEventCount:{good:0,bad:0},microphoneInUseEventCount:{good:0,bad:0},cameraInUseEventCount:{good:0,bad:0},cameraFreezeEventCount:{start:0,end:0},rawMedia:{audio:{recv:{numAttempts:0,durationRatio:0},send:{numAttempts:0,durationRatio:0}}},ufds:[],remoteUfds:[],statsErrors:[],webrtcSessions:[],isOngoing:!1,duration:0,callMutedRatio:0,callOsMuted:0,callHwSilent:0,callSwMuted:0,callIsMuted:!1,callSpeakerMuted:0,callIsSpeaking:0,networkRecvUFD:void 0,networkSendUFD:void 0,zeroCaptureDevicesRatio:0,zeroRenderDevicesRatio:0,deviceRenderFailuresRatio:0,deviceCaptureFailuresRatio:0,deviceManager:void 0,relayTimers:void 0,authTokenFetcherStats:void 0,dominantSpeaker:this.dshDiagnostics.getObjectRef(),[Q_]:this,callConstraints:[],audioRenderer:{sinkNumOfReopenRequests:0,sinkNumOfSuccessfulReopens:0},elevation:[],batteryLevel:void 0},this.transportDisconnected=!1,this.commonMuteTracker=new eT,this.swMuteTracker=new eT,this.osMuteTracker=new eT,this.speakerMuteTracker=new eT,this.hwSilentTracker=new eT,this.isSpeakingTracker=new eT,this.networkRecvTracker=new tT,this.networkSendTracker=new tT,this.zeroCaptureTracker=new tT,this.zeroRenderTracker=new tT,this.deviceRenderTracker=new tT,this.deviceCaptureTracker=new tT,this.rawMediaTimers={audio:{send:new eT,recv:new eT}},this.dmFragmenter=new Z_(this.dmDiagnostics),this.durationTimer=new eT,this.data.callNumber=C,this.data.sessionId=_,this.durationTimer.start(),addGetterFields(this.data,{isOngoing:()=>void 0===this.data.terminationTime,duration:()=>this.durationTimer.elapsed,callMutedRatio:()=>getDurationRatio(this.commonMuteTracker.elapsed,this.data.duration),callOsMuted:()=>this.osMuteTracker.elapsed,callHwSilent:()=>this.hwSilentTracker.elapsed,callSwMuted:()=>this.swMuteTracker.elapsed,callIsMuted:()=>this.swMuteTracker.isRunning,callSpeakerMuted:()=>this.speakerMuteTracker.elapsed,callIsSpeaking:()=>this.isSpeakingTracker.elapsed,zeroCaptureDevicesRatio:()=>this.zeroCaptureTracker.getRatio("Bad"),zeroRenderDevicesRatio:()=>this.zeroRenderTracker.getRatio("Bad"),deviceRenderFailuresRatio:()=>this.deviceRenderTracker.getRatio("Bad"),deviceCaptureFailuresRatio:()=>this.deviceCaptureTracker.getRatio("Bad"),networkRecvUFD:()=>({good:this.networkRecvTracker.getCount("Good"),poor:this.networkRecvTracker.getCount("Poor"),bad:this.networkRecvTracker.getCount("Bad"),goodRatio:this.networkRecvTracker.getRatio("Good"),poorRatio:this.networkRecvTracker.getRatio("Poor"),badRatio:this.networkRecvTracker.getRatio("Bad")}),networkSendUFD:()=>({good:this.networkSendTracker.getCount("Good"),poor:this.networkSendTracker.getCount("Poor"),bad:this.networkSendTracker.getCount("Bad"),goodRatio:this.networkSendTracker.getRatio("Good"),poorRatio:this.networkSendTracker.getRatio("Poor"),badRatio:this.networkSendTracker.getRatio("Bad")}),deviceManager:()=>this.dmFragmenter.getFragment(this.dmDiagnostics),relayTimers:()=>this._relayManager?.getStats(),authTokenFetcherStats:()=>this._relayManager?.getAuthTokenStats(),callConstraints:()=>this.configProvider.getCallConstraintsTelemetry()}),addGetterFields(this.data.rawMedia.audio.recv,{durationRatio:()=>getDurationRatio(this.rawMediaTimers.audio.recv.elapsed,this.data.duration)}),addGetterFields(this.data.rawMedia.audio.send,{durationRatio:()=>getDurationRatio(this.rawMediaTimers.audio.send.elapsed,this.data.duration)})}get telemetryReport(){const g={type:"WebRtcMediaStats",data:this.diagnosticsReport.getSessionTelemetry(this.data.sessionId)},f={};return forOwnRec(g.data,((g,S,v)=>{let C=0;la.test(g)?(C=13,f[S]="IPv4"):ca.test(g)&&(C=4,f[S]="IPv6"),v[S]={type:C,value:g,__VALUE__:!0}})),g.data.metrics.piiFields={type:0,value:JSON.stringify(f),__VALUE__:!0},g}get mediaStatsReport(){return this.diagnosticsReport.getMediaSessionStats(this.data.sessionId)}get realtimeTelemetryReport(){return this.diagnosticsReport.getTeamsRealtimeTelemetry(this.data.sessionId)}get e2eDiagnostics(){return this.diagnosticsReport.getDiagnosticsForE2eTests(this.data.sessionId)}set relayManager(g){this._relayManager=g}set isMultiParty(g){this.data.isMultiParty=g}set mediaLegId(g){this.data.mediaLegId=g.process()}set ETag(g){this.data.ETag=g}set configIds(g){this.data.configIds=g}set reconnect(g){this.data.reconnect=g}set relay(g){this.data.relay={address:g.addresses.join(),expires:g.expires,realm:g.realm,credentials:!(!g.username||!g.password),ports:[g.udpPort?`udp:${g.udpPort}`:"",g.tcpPort?`tcp:${g.tcpPort}`:"",g.tlsPort?`tls:${g.tlsPort}`:""].join(","),fqdns:g.fqdns?g.fqdns.join():"none"}}set sessionError(g){this.data.error=g}set dtmfResult(g){g?this.data.dtmfSuccessCount++:this.data.dtmfFailureCount++}set swMute(g){g?this.swMuteTracker.start():this.swMuteTracker.stop(),this.updateCommonMute()}set speakerMute(g){g?this.speakerMuteTracker.start():this.speakerMuteTracker.stop()}set hwSilent(g){g?this.hwSilentTracker.start():this.hwSilentTracker.stop()}set isSpeaking(g){g?this.isSpeakingTracker.start():this.isSpeakingTracker.stop()}set iceInitTime(g){this.data.iceInitTime||(this.data.iceInitTime=g)}set finalAnswerTime(g){this.data.finalAnswerTime||(this.data.finalAnswerTime=g)}set iceConnectedStateTimestamp(g){this.data.iceConnectedStateTime||(this.data.iceConnectedStateTime=g)}set allowedModalities(g){this.data.allowedAudioSend=g.audio.some((g=>hasSendDirectionality(g))),this.data.allowedVideoSend=g.video.some((g=>hasSendDirectionality(g))),this.data.allowedScreensharingSend=g.sharing.some((g=>hasSendDirectionality(g)))}negotiationStart(g){var f;(f=this.data).initialNegotiationType??(f.initialNegotiationType=g),this.data.negotiationCount++}negotiationCompleted(g){this.data.initialNegotiationCompleted=!0,this.data.activeModalities=g,this.data.error=void 0}negotiationRejected(){this.data.rejectedNegotiationCount++}registerRollbackEvent(g){this.data.rollbackNegotiation.push({type:g.type,attempt:this.data.rollbackNegotiation.length+1,error:g.error})}registerRawMediaAccess(g,f,S){const v=this.data.rawMedia[g]?.[f];if(v){v.numAttempts++;const C=this.rawMediaTimers[g]?.[f];S?C?.start():C?.stop()}}registerQualityStateChangedEvent(g){switch(g.type){case"NoNetwork":"Good"===g.value?this.data.noIceCandidatesEventCount.good++:this.data.noIceCandidatesEventCount.bad++;break;case"NetworkRelaysNotReachable":"Good"===g.value?this.data.noRelayIceCandidatesEventCount.good++:this.data.noRelayIceCandidatesEventCount.bad++;break;case"DeviceCaptureNotFunctioning":this.deviceCaptureTracker.updateLevel(g.value),"Good"===g.value?this.data.microphoneInUseEventCount.good++:this.data.microphoneInUseEventCount.bad++;break;case"DeviceRenderNotFunctioning":this.deviceRenderTracker.updateLevel(g.value);break;case"VideoCapturerDeviceStartFailed":"Good"===g.value?this.data.cameraInUseEventCount.good++:this.data.cameraInUseEventCount.bad++;break;case"DeviceCaptureMute":"Bad"===g.value?this.osMuteTracker.start():this.osMuteTracker.stop(),this.updateCommonMute();break;case"NetworkRecvQuality":this.networkRecvTracker.updateLevel(g.value);break;case"NetworkSendQuality":this.networkSendTracker.updateLevel(g.value);break;case"ZeroCaptureDevicesEnumerated":this.zeroCaptureTracker.updateLevel(g.value);break;case"ZeroRenderDevicesEnumerated":this.zeroRenderTracker.updateLevel(g.value);break;case"VideoCaptureDeviceFreeze":"Good"===g.value?this.data.cameraFreezeEventCount.end++:this.data.cameraFreezeEventCount.start++}"DeviceSpeakWhileMuted"!==g.type&&arrayLimitedPush2(this.data.ufds,{...g,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numUFDs)}registerRemoteQualityStateChangedEvent(g,f){arrayLimitedPush2(this.data.remoteUfds,{...g,participantId:f,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numUFDs)}registerTransportConnected(){this.transportDisconnected&&(this.transportDisconnected=!1,this.data.transportReconnectedCount++)}registerTransportDisconnected(){this.transportDisconnected=!0}registerTransportFailed(){this.transportDisconnected=!1}terminated(g){this.commonMuteTracker.stop(),this.swMuteTracker.stop(),this.osMuteTracker.stop(),this.speakerMuteTracker.stop(),this.hwSilentTracker.stop(),this.isSpeakingTracker.stop(),this.rawMediaTimers.audio.recv.stop(),this.rawMediaTimers.audio.send.stop(),this.networkSendTracker.dispose(),this.networkRecvTracker.dispose(),this.zeroCaptureTracker.dispose(),this.zeroRenderTracker.dispose(),this.deviceCaptureTracker.dispose(),this.data.terminationReason=deepClone(g),this.data.terminationTime=Date.now(),this.durationTimer.stop(),this.dmFragmenter.terminated(this.dmDiagnostics)}addStatsError(g,f){const S=this.data.statsErrors.find((S=>S.error===f&&S.origin===g));this.logger.safe.error(`Stats error from '${g}': ${f} (${S?.count??1})`),S?S.count++:arrayLimitedPush2(this.data.statsErrors,{origin:g,error:f,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors)}newNativeSessionDiag(g=!0){let f;return f=new Y_(this.configProvider,this.dmDiagnostics,((g,f)=>this.addStatsError(g,f)),(g=>this.newNativeSessionDiag(g)),(()=>this.pushNativeSessionDiag(f.getObjectRef())),this.dshDiagnostics.resetState(),(()=>this.getObjectRef())),g&&arrayLimitedPush2(this.data.webrtcSessions,f.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numNativeSessions),f}pushNativeSessionDiag(g){arrayLimitedPush2(this.data.webrtcSessions,g,this.configProvider.config.diagnostics.collectionLimits.numNativeSessions)}getObjectRef(){return this.data}setBatteryLevel(g){this.data.batteryLevel=g}updateCommonMute(){this.swMuteTracker.isRunning||this.osMuteTracker.isRunning?this.commonMuteTracker.start():this.swMuteTracker.isRunning||this.osMuteTracker.isRunning||this.commonMuteTracker.stop()}registerElevation(g){arrayLimitedPush(this.data.elevation,{event:g,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numElevation)}},Z_=class{constructor(g){this.initTimestamp=Number.MIN_SAFE_INTEGER,this.terminatedTimestamp=Number.MAX_SAFE_INTEGER,this.fragmentBase=this.sanitizeDiagnostics(g),this.initTimestamp=Date.now()}getFragment(g){const f=this.fragmentTerminated??g;return{devicesChangeCount:f.devicesChangeCount-this.fragmentBase.devicesChangeCount,deviceSelectionChangeCount:f.deviceSelectionChangeCount-this.fragmentBase.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:f.deviceSelectionChangeCountFromInterface-this.fragmentBase.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:f.devicesPollChangeCount-this.fragmentBase.devicesPollChangeCount,audioSourceNumOfSuccessfulReopens:f.audioSourceNumOfSuccessfulReopens-this.fragmentBase.audioSourceNumOfSuccessfulReopens||void 0,audioSourceNumOfReopenRequests:f.audioSourceNumOfReopenRequests-this.fragmentBase.audioSourceNumOfReopenRequests||void 0,audioCaptureDeviceErrorFlag:g.audioCaptureDeviceErrorFlags.filter((g=>g.timestamp>this.initTimestamp&&g.timestamp<this.terminatedTimestamp)).reduce(((g,f)=>Number(BigInt(g)|BigInt(f.audioDeviceErrorFlag))),0),audioRenderDeviceErrorFlag:g.audioRenderDeviceErrorFlags.filter((g=>g.timestamp>this.initTimestamp&&g.timestamp<this.terminatedTimestamp)).reduce(((g,f)=>Number(BigInt(g)|BigInt(f.audioDeviceErrorFlag))),0)}}terminated(g){this.fragmentTerminated=this.sanitizeDiagnostics(g),this.terminatedTimestamp=Date.now()}sanitizeDiagnostics(g){return{devicesChangeCount:g.devicesChangeCount,deviceSelectionChangeCount:g.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:g.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:g.devicesPollChangeCount,audioSourceNumOfSuccessfulReopens:g.audioSourceNumOfSuccessfulReopens,audioSourceNumOfReopenRequests:g.audioSourceNumOfReopenRequests,audioCaptureDeviceErrorFlag:0,audioRenderDeviceErrorFlag:0}}},eT=class{constructor(){this.startTime=0,this.elapsedInternal=0,this.countInternal=0}get isRunning(){return!!this.startTime}get elapsed(){return Math.round(this.startTime?this.elapsedInternal+Jt()-this.startTime:this.elapsedInternal)}get count(){return this.countInternal}start(){this.startTime||(this.startTime=Jt(),this.countInternal++)}stop(){this.startTime&&(this.elapsedInternal+=Jt()-this.startTime,this.startTime=0)}},tT=class{constructor(){this.currentLevel="Good",this.stopWatches={},this.startTime=Jt(),this.getStopWatch(this.currentLevel).start()}updateLevel(g){this.currentLevel!==g&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=g,this.getStopWatch(this.currentLevel).start())}getCount(g){const f=this.stopWatches[g];return f?f.count:0}getRatio(g){return getDurationRatio(this.getStopWatch(g).elapsed,Math.round((this.endTime||Jt())-this.startTime))}dispose(g){this.getStopWatch(this.currentLevel).stop(),this.endTime=Jt()}getStopWatch(g){let f=this.stopWatches[g];return f||(f=new eT,this.stopWatches[g]=f),f}};function getDurationRatio(g,f){return g/(f||1)}function compileAudioReport(g,f,S){return removeUndefinedFields({recv:removeUndefinedFields({id:f?.inboundRTP.id,ssrc:f?.inboundRTP.ssrc,mediaType:f?.inboundRTP.mediaType??f?.inboundRTP.kind,bytesReceived:sampleseries(g.audio?.recv,(g=>g.inboundRTP.bytesReceived)),packetsReceived:sampleseries(g.audio?.recv,(g=>g.inboundRTP.packetsReceived)),packetsLost:sampleseries(g.audio?.recv,(g=>g.inboundRTP.packetsLost)),googCodecName:f?.codec?.mimeType.split("/").pop(),googTrackId:f?.track?.trackIdentifier,transport_id:f?.transport?.id,transportId:f?.inboundRTP.transportId,transport_selectedCandidatePairId:f?.transport?.selectedCandidatePairId,transport_dtlsCipher:f?.transport?.dtlsCipher,transport_srtpCipher:f?.transport?.srtpCipher,pair_id:f?.transport?.selectedCandidatePair?.id,pair_responsesSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:f?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:f?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:f?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:f?.transport?.selectedCandidatePair?.writable,pair_requestsSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:sampleseries(g.audio?.recv,(g=>1e3*g.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:f?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:f?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:f?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:f?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:f?.transport?.selectedCandidatePair?.localCandidate?.ip??f?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:f?.transport?.selectedCandidatePair?.remoteCandidate?.ip??f?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:f?.transport?.selectedCandidatePair?.nominated}),send:removeUndefinedFields({id:S?.outboundRTP.id,ssrc:S?.outboundRTP.ssrc,mediaType:S?.outboundRTP.mediaType??S?.outboundRTP.kind,bytesSent:sampleseries(g.audio?.send,(g=>g.outboundRTP.bytesSent)),packetsSent:sampleseries(g.audio?.send,(g=>g.outboundRTP.packetsSent)),packetsLost:sampleseries(g.audio?.send,(g=>g.remoteInboundRTP?.packetsLost)),googCodecName:S?.codec?.mimeType.split("/").pop(),googTrackId:S?.track?.trackIdentifier,transport_id:S?.transport?.id,transportId:S?.outboundRTP.transportId,transport_selectedCandidatePairId:S?.transport?.selectedCandidatePairId,transport_dtlsCipher:S?.transport?.dtlsCipher,transport_srtpCipher:S?.transport?.srtpCipher,pair_id:S?.transport?.selectedCandidatePair?.id,pair_responsesSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:S?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:S?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:S?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:S?.transport?.selectedCandidatePair?.writable,pair_requestsSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:sampleseries(g.audio?.send,(g=>1e3*g.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:S?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:S?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:S?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:S?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:S?.transport?.selectedCandidatePair?.localCandidate?.ip??S?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:S?.transport?.selectedCandidatePair?.remoteCandidate?.ip??S?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:S?.transport?.selectedCandidatePair?.nominated})})}function compileVideoTelemetryReport(g,f,S,v){return removeUndefinedFields({recv:removeUndefinedFields({id:S?.inboundRTP.id,ssrc:S?.inboundRTP.ssrc,mediaType:S?.inboundRTP.mediaType??S?.inboundRTP.kind,bytesReceived:sampleseries(f[g]?.recv,(g=>g.inboundRTP.bytesReceived)),packetsReceived:sampleseries(f[g]?.recv,(g=>g.inboundRTP.packetsReceived)),packetsLost:sampleseries(f[g]?.recv,(g=>g.inboundRTP.packetsLost)),googCodecName:S?.codec?.mimeType.split("/").pop(),codecImplementationName:S?.inboundRTP.decoderImplementation,googTrackId:S?.track?.trackIdentifier,transport_id:S?.transport?.id,transportId:S?.inboundRTP.transportId,transport_selectedCandidatePairId:S?.transport?.selectedCandidatePairId,transport_dtlsCipher:S?.transport?.dtlsCipher,transport_srtpCipher:S?.transport?.srtpCipher,pair_id:S?.transport?.selectedCandidatePair?.id,pair_responsesSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:S?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:S?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:S?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:S?.transport?.selectedCandidatePair?.writable,pair_requestsSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:sampleseries(f[g]?.recv,(g=>1e3*g.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:S?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:S?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:S?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:S?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:S?.transport?.selectedCandidatePair?.localCandidate?.ip??S?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:S?.transport?.selectedCandidatePair?.remoteCandidate?.ip??S?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:S?.transport?.selectedCandidatePair?.nominated,framesDecoded:sampleseries(f[g]?.recv,(g=>g.inboundRTP.framesDecoded)),googFrameHeightReceived:sampleseries(f[g]?.recv,(g=>g.inboundRTP.frameHeight)),googFrameWidthReceived:sampleseries(f[g]?.recv,(g=>g.inboundRTP.frameWidth)),googFrameRateReceived:sampleseries(f[g]?.recv,(g=>g.extensions?.frameRateReceived||0)),googNacksSent:sampleseries(f[g]?.recv,(g=>g.inboundRTP.nackCount)),googPlisSent:sampleseries(f[g]?.recv,(g=>g.inboundRTP.pliCount)),keyFramesDecoded:sampleseries(f[g]?.recv,(g=>g.inboundRTP.keyFramesDecoded)),googFirsSent:sampleseries(f[g]?.recv,(g=>g.inboundRTP.firCount)),googJitterBufferMs:sampleseries(f[g]?.recv,(g=>g.extensions?.jitterBufferMs)),googFrameRateDecoded:sampleseries(f[g]?.recv,(g=>g.extensions?.frameRateDecoded||0)),googFrameRateOutput:S?.extensions?.trackRecvFps,jitter:S?.inboundRTP.jitter}),send:removeUndefinedFields({id:v?.outboundRTP.id,ssrc:v?.outboundRTP.ssrc,mediaType:v?.outboundRTP.mediaType??v?.outboundRTP.kind,bytesSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.bytesSent)),packetsSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.packetsSent)),packetsLost:sampleseries(f[g]?.send,(g=>g.remoteInboundRTP?.packetsLost)),googCodecName:v?.codec?.mimeType.split("/").pop(),codecImplementationName:v?.outboundRTP.encoderImplementation,googTrackId:v?.track?.trackIdentifier,transport_id:v?.transport?.id,transportId:v?.outboundRTP.transportId,transport_selectedCandidatePairId:v?.transport?.selectedCandidatePairId,transport_dtlsCipher:v?.transport?.dtlsCipher,transport_srtpCipher:v?.transport?.srtpCipher,pair_id:v?.transport?.selectedCandidatePair?.id,pair_responsesSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:v?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:v?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:v?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:v?.transport?.selectedCandidatePair?.writable,pair_requestsSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:sampleseries(f[g]?.send,(g=>1e3*g.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:v?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:v?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:v?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:v?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:v?.transport?.selectedCandidatePair?.localCandidate?.ip??v?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:v?.transport?.selectedCandidatePair?.remoteCandidate?.ip??v?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:v?.transport?.selectedCandidatePair?.nominated,framesEncoded:sampleseries(f[g]?.send,(g=>g.outboundRTP.framesEncoded)),googNacksReceived:sampleseries(f[g]?.send,(g=>g.outboundRTP.nackCount)),googPlisReceived:sampleseries(f[g]?.send,(g=>g.outboundRTP.pliCount)),googFirsReceived:sampleseries(f[g]?.send,(g=>g.outboundRTP.firCount)),keyFramesEncoded:sampleseries(f[g]?.send,(g=>g.outboundRTP.keyFramesEncoded)),googFrameHeightInput:v?.mediaSource?.height,googFrameWidthInput:v?.mediaSource?.width,googFrameRateInput:sampleseries(f[g]?.send,(g=>g.mediaSource?.framesPerSecond)),googFrameHeightSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.frameHeight)),googFrameWidthSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.frameWidth)),googFrameRateSent:sampleseries(f[g]?.send,(g=>g.extensions?.frameRateSent)),googRtt:sampleseries(f[g]?.send,(g=>1e3*(g.remoteInboundRTP?.roundTripTime??0)),!0),hugeFramesSent:v?.outboundRTP.hugeFramesSent,qpSum:sampleseries(f[g]?.send,(g=>g.outboundRTP.qpSum)),qualityLimitationDurations:v?JSON.stringify(v?.outboundRTP.qualityLimitationDurations):void 0,qualityLimitationReason:v?.outboundRTP.qualityLimitationReason,qualityLimitationResolutionChanges:v?.outboundRTP.qualityLimitationResolutionChanges,jitter:v?.remoteInboundRTP?.jitter,retransmittedPacketsSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.retransmittedPacketsSent))})})}function compileExtensionsTelemetryReport(g,f,S){const v=f.config.diagnostics.telemetryLimits,C=g.aggregatedModalityStats,_=getLast(C.audio?.recv),T=getLast(C.audio?.send),I=getLast(C.video?.recv),b=getLast(C.video?.send),A=getLast(C.sharing?.recv),P=getLast(C.sharing?.send),getMaxCapsEvents=S=>S&&limitArraySize2(deepClone(S).map((f=>rebaseTime(limitArraySize2(f.events,v.numCapabilitiesApplied,1),"timestamp",g.startTime))),f.config.diagnostics.telemetryLimits.numCapabilitiesRequested),R=getMaxCapsEvents(g.qualityManager?.videoMaxCapabilitiesEvents),M=getMaxCapsEvents(g.qualityManager?.videoMaxCapabilitiesErrors),w=getMaxCapsEvents(g.qualityManager?.sharingMaxCapabilitiesEvents),O=getMaxCapsEvents(g.qualityManager?.sharingMaxCapabilitiesErrors),D="REMB"!==g.negotiation.bweType?g.bandwidthReport:void 0,N="REMB"===g.negotiation.bweType?g.bandwidthReport:void 0;return removeUndefinedFields({BundlePolicy:g.bundlePolicy,FakeIceCandidate:g.negotiation.fakeCandidate,h264AvailableProfiles:JSON.stringify(g.H264Profiles),h264CodecCapabilities:JSON.stringify(g.h264CodecCapabilities),IceConnectionState:g.transportState?.iceConnectionState,IceConnectionStatePrevious:g.transportState?.iceConnectionStatePrevious,IceServers:g.iceServers,IceTransportPolicy:g.iceTransportPolicy,NegotiatedSrtp:JSON.stringify(g.negotiation.negotiatedSrtp),OfferedSrtp:JSON.stringify(g.negotiation.offeredSrtp),RelayCandidate:g.relayCandidate,SdpSemantics:g.sdpSemantics,iceCandidateErrors:JSON.stringify(g.iceCandidateErrors),SignalingState:g.transportState?.signalingState,SignalingStatePrevious:g.transportState?.signalingStatePrevious,WebRTCStats_statsErrors:JSON.stringify(S),MaxSessionBandwidth:g.maxSessionBandwidth,Bandwidth_uplinkStabilizationTime:JSON.stringify(g.bwStabilizationTime),Bandwidth_downlinkStabilizationTime:JSON.stringify(g.bwDownlinkStabilizationTime),totalVideoControlMessages:g.qualityManager?.numVideoControlMessages,outOfOrderVideoControlMessages:g.qualityManager?.numOutOfOrderVideoControlMessages,webcamFreezeIntervals:g.qualityManager?.numWebcamFreezeIntervals,processedStreamFreezeIntervals:g.qualityManager?.numProcessedStreamFreezeIntervals,IPAddress:g.IPAddress??"none",ReflexiveLocalIP:g.reflexiveLocalIP??"none",NumberOfInterfaces:g.numInterfaces,StartTime:g.startTime,EndTime:g.endTime,AudioTransportRecvBitrate:_?.transport?.extensions?.recvBWAvg,AudioTransportSendBitrate:_?.transport?.extensions?.sendBWAvg,AudioPayloadRecvBitrate:_?.aggregated?.bitrateAvg,AudioPayloadSendBitrate:T?.aggregated?.bitrateAvg,VideoPayloadRecvBitrate:I?.aggregated?.bitrateAvg,VideoPayloadSendBitrate:b?.aggregated?.bitrateAvg,WebRTCStats_bweStat_googAvailableReceiveBandwidth:sampleseries(C.video?.recv,(g=>g.transport?.selectedCandidatePair?.availableIncomingBitrate))??sampleseries(C.video?.send,(g=>g.transport?.selectedCandidatePair?.availableIncomingBitrate)),WebRTCStats_bweStat_googAvailableSendBandwidth:sampleseries(C.video?.send,(g=>g.transport?.selectedCandidatePair?.availableOutgoingBitrate))??sampleseries(C.video?.recv,(g=>g.transport?.selectedCandidatePair?.availableOutgoingBitrate)),Bandwidth_jumpsHistogram:JSON.stringify(b?.transport?.extensions?.bwJumpsHistogram),StartCallBWESendSide:JSON.stringify(D?.startOfTheCall),EndCallBWESendSide:JSON.stringify(D?.endOfTheCall),BWEStdSendSide:JSON.stringify(D?.std),BwPercentilesSendSide:JSON.stringify(D?.bwPercentiles),AvgBwSendSide:JSON.stringify(D?.avgBwe),StartCallBWE:JSON.stringify(N?.startOfTheCall),EndCallBWE:JSON.stringify(N?.endOfTheCall),BWEStd:JSON.stringify(N?.std),BwPercentiles:JSON.stringify(N?.bwPercentiles),AvgBw:JSON.stringify(N?.avgBwe),WebRTCStats_ssrc:removeUndefinedFields({audio:compileAudioReport(C,_,T),video:compileVideoTelemetryReport("video",C,I,b),sharing:compileVideoTelemetryReport("sharing",C,A,P)}),Audio_recv_jitterBufferAvgSize:_?.aggregated?.avgJitterBufferSize,Audio_recv_packetsLostRateMax:round(_?.aggregated?.lossRateMax,6),Audio_recv_jitterAvg:_?.aggregated?.jitterAvg,Audio_recv_jitterMax:_?.aggregated?.jitterMax,Audio_recv_networkAvgLossRate:round(_?.aggregated?.networkAvgLossRate,6),Audio_recv_packetsLostAvg:_?.aggregated?.packetsLostAvg,Audio_recv_healedRatioAvg:_?.aggregated?.healedRatioAvg,Audio_recv_healedRatioMax:_?.aggregated?.healedRatioMax,Audio_send_rttAvg:T?.aggregated?.rttAvg&&round(1e3*T.aggregated.rttAvg),Audio_send_rttMax:T?.aggregated?.rttMax&&round(1e3*T.aggregated.rttMax),Audio_send_RawInputVolume:sampleseries(C.audio?.send,(g=>g.aggregated?.rawInputVolume)),Audio_send_packetsLostRateMax:round(T?.aggregated?.lossRateMax,6),Audio_send_presentationAPIUserDuration:g.presentationAPIUserDuration,Audio_send_presentationDuration:g.presentationAudioDuration,Video_recv_DurationSeconds:I?.aggregated?.duration,Video_recv_FreezeHistogram:JSON.stringify(I?.aggregated?.freezeCountHistogram),Video_recv_FreezeTimestamps:JSON.stringify(rebaseAndLimitHistogramTimestamps(I?.aggregated?.freezeTimestampsHistogram,g.startTime,v.numOfHistogramSamples)),Video_recv_LongestFreezeDuration:I?.aggregated?.longestFreeze,Video_recv_OngoingFreeze:I?.extensions?.isFrozen,Video_recv_OngoingFreezeDuration:I?.aggregated?.ongoingFreezeDuration,Video_recv_TotalFreezeDuration:I?.aggregated?.totalFreezeDuration,Video_recv_RecvAvgFreezeDuration:I?.aggregated?.avgFreezeDuration,Video_recv_NumResolutionSwitches:I?.aggregated?.numResolutionSwitches,Video_recv_ResolutionDurations:JSON.stringify(I?.aggregated?.resolutionDurations),Video_recv_StreamsMax:g.recvVideoStreamCount.max,Video_recv_StreamsMin:g.recvVideoStreamCount.min,Video_recv_StreamsMode:g.recvVideoStreamCount.mode,Video_recv_TimeToFirstFrame:g.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_TimeToFirstFrameSinceSubscriptionStart:g.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_bitrateAvg:I?.aggregated?.bitrateAvg,Video_recv_bitrateMax:I?.aggregated?.bitrateMax,Video_recv_frameRateAvg:I?.aggregated?.avgFrameRate,Video_recv_jitterBufferAvgSize:I?.aggregated?.avgJitterBufferSize,Video_recv_packetsLostRateMax:round(I?.aggregated?.lossRateMax,6),Video_recv_isRenderingEvents:JSON.stringify(limitArraySize2(g.remoteVideoManager?.isRenderingEvents.video,v.numIsRenderingEvents)),Video_recv_FpsHarmonicAverage:I?.aggregated?.fpsHarmonicAverage,Video_recv_PreferredResolution:g.remoteVideoManager?.preferredResolution.video?.toString(),Video_recv_statsOnSubscribed:JSON.stringify(g.statsOnSubscribed.video),Video_SubscriptionEvents:JSON.stringify(rebaseTime(g.subscriptionManager?.video.events,"ts",g.startTime)),Video_SubscriptionCounters:JSON.stringify(g.subscriptionManager?.video.counters),Video_send_CaptureFramerateAvg:b?.aggregated?.captureFramerateAvg,Video_send_DurationSeconds:b?.aggregated?.duration,Video_send_FreezeIntervals:b?.extensions?.captureFreezeIntervalsCount,Video_send_MaxCapabilities:JSON.stringify(R),Video_send_MaxCapabilitiesErrors:JSON.stringify(M),Video_send_OvershootDurations:JSON.stringify({fs:b?.aggregated?.totalFsOvershootDuration,fps:b?.aggregated?.totalFpsOvershootDuration,br:b?.aggregated?.totalBrOvershootDuration}),Video_send_OvershootEvents:limitRebaseAndStringifyEvents(b?.aggregated?.overshootEvents,v.numOvershootEvents,"timestamp",g.startTime),Video_send_QpAvg:b?.aggregated?.qpAvg,Video_send_bitrateAvg:b?.aggregated?.bitrateAvg,Video_send_bitrateMax:b?.aggregated?.bitrateMax,Video_send_frameRateAvg:b?.aggregated?.frameRateAvg,Video_send_AllocateBWAvg:b?.aggregated?.bweAvg,Video_send_CameraOpenWidth:b?.extensions?.cameraOpenResolution?.width,Video_send_CameraOpenHeight:b?.extensions?.cameraOpenResolution?.height,Video_send_packetsLostRateMax:round(b?.aggregated?.lossRateMax,6),Video_send_resolutionSwitches:JSON.stringify(b?.aggregated?.resolutionSwitches),Video_send_performanceEvents:limitRebaseAndStringifyEvents(g.localVideoPerformanceEvents,v.numPerformanceEvents,"timestamp",g.startTime),Video_send_Simulcast:JSON.stringify(g.simulcast?.video),Video_send_powerEfficientEncoderEvents:limitRebaseAndStringifyEvents(b?.extensions?.powerEfficientEncoderEvents,v.numPowerEfficientEncoderEvents,"timestamp",g.startTime),Video_send_powerEfficientEncoderEventOnCount:b?.extensions?.powerEfficientEncoderEventOnCount,Video_send_powerEfficientEncoderEventOffCount:b?.extensions?.powerEfficientEncoderEventOffCount,Sharing_recv_DurationSeconds:A?.aggregated?.duration,Sharing_recv_FreezeHistogram:JSON.stringify(A?.aggregated?.freezeCountHistogram),Sharing_recv_FreezeTimestamps:JSON.stringify(rebaseAndLimitHistogramTimestamps(A?.aggregated?.freezeTimestampsHistogram,g.startTime,v.numOfHistogramSamples)),Sharing_recv_LongestFreezeDuration:A?.aggregated?.longestFreeze,Sharing_recv_OngoingFreeze:A?.extensions?.isFrozen,Sharing_recv_TotalFreezeDuration:A?.aggregated?.totalFreezeDuration,Sharing_recv_RecvAvgFreezeDuration:A?.aggregated?.avgFreezeDuration,Sharing_recv_NumResolutionSwitches:A?.aggregated?.numResolutionSwitches,Sharing_recv_ResolutionDurations:JSON.stringify(A?.aggregated?.resolutionDurations),Sharing_recv_StreamsMax:g.recvVideoStreamCount.max,Sharing_recv_StreamsMin:g.recvVideoStreamCount.min,Sharing_recv_StreamsMode:g.recvVideoStreamCount.mode,Sharing_recv_TimeToFirstFrame:g.remoteVideoManager?.firstTimeToFirstFrameSharing,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:g.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_bitrateAvg:A?.aggregated?.bitrateAvg,Sharing_recv_bitrateMax:A?.aggregated?.bitrateMax,Sharing_recv_frameRateAvg:A?.aggregated?.avgFrameRate,Sharing_recv_jitterBufferAvgSize:A?.aggregated?.avgJitterBufferSize,Sharing_recv_packetsLostRateMax:round(A?.aggregated?.lossRateMax,6),Sharing_recv_FpsHarmonicAverage:A?.aggregated?.fpsHarmonicAverage,Sharing_recv_isRenderingEvents:JSON.stringify(limitArraySize2(g.remoteVideoManager?.isRenderingEvents.sharing,v.numIsRenderingEvents)),Sharing_recv_PreferredResolution:g.remoteVideoManager?.preferredResolution.sharing?.toString(),Sharing_recv_statsOnSubscribed:JSON.stringify(g.statsOnSubscribed.sharing),Sharing_SubscriptionEvents:JSON.stringify(rebaseTime(g.subscriptionManager?.sharing.events,"ts",g.startTime)),Sharing_SubscriptionCounters:JSON.stringify(g.subscriptionManager?.sharing.counters),Sharing_send_CaptureFramerateAvg:P?.aggregated?.captureFramerateAvg,Sharing_send_DurationSeconds:P?.aggregated?.duration,Sharing_send_MaxCapabilities:JSON.stringify(w),Sharing_send_MaxCapabilitiesErrors:JSON.stringify(O),Sharing_send_OvershootDurations:JSON.stringify({fs:P?.aggregated?.totalFsOvershootDuration,fps:P?.aggregated?.totalFpsOvershootDuration,br:P?.aggregated?.totalBrOvershootDuration}),Sharing_send_resolutionSwitches:P?.aggregated?.resolutionSwitches,Sharing_send_OvershootEvents:limitRebaseAndStringifyEvents(P?.aggregated?.overshootEvents,v.numOvershootEvents,"timestamp",g.startTime),Sharing_send_QpAvg:P?.aggregated?.qpAvg,Sharing_send_bitrateAvg:P?.aggregated?.bitrateAvg,Sharing_send_bitrateMax:P?.aggregated?.bitrateMax,Sharing_send_frameRateAvg:P?.aggregated?.frameRateAvg,Sharing_send_AllocateBWAvg:P?.aggregated?.bweAvg,Sharing_send_packetsLostRateMax:round(P?.aggregated?.lossRateMax,6),Sharing_send_Simulcast:JSON.stringify(g.simulcast?.sharing),Data_ProtocolCounters:JSON.stringify(g.dataChannel?.protocolCounters),Data_Error:g.dataChannel?.error,Data_SessionState:g.dataChannelSessionState?.toString(),Data_CreateChannelError:g.dataChannelCreationError,multipleVideoStreams:JSON.stringify(rebaseTime(g.multiViewStats,"startTime",g.startTime)),ReportedReceiveBandwidth:JSON.stringify(g.reportedReceiveBandwidth),ReportedSendBandwidth:JSON.stringify(g.reportedSendBandwidthLayouts),OvcToSubscriptions:JSON.stringify(g.ovcToSubscriptionEvents),EncodedStreamWorker:g.encodedStreamWorker,AudioCodecEvents:JSON.stringify(g.audioCodecEvents),HevcCodecSupport:JSON.stringify(g.codecSupport),MeetingScenario:JSON.stringify(g.negotiation.meetingScenario),IsTownHall:g.negotiation.isTownHall,InitialBWSeed:g.initialBWSeed,SentBWSeed:g.sentBWSeed,videoPerformanceEvent:JSON.stringify(g.videoPerformanceEvent),EarlyMedia_NumStatsPolls:g.earlyMediaNumStatsPolls})}var videoSendStatsFieldConverter=g=>removeUndefinedFields({id:g.outboundRTP.ssrc.toString(),codecName:g.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:g.extensions?.bitrate,jitter:g.remoteInboundRTP?.jitter,packets:g.outboundRTP.packetsSent,packetsPerSecond:g.extensions?.packetsPerSecond,packetsLost:g.remoteInboundRTP?.packetsLost,packetsLostPerSecond:g.extensions?.packetsLostPerSecond,rtt:g.remoteInboundRTP?.roundTripTime,frameRateInput:g.mediaSource?.framesPerSecond,frameWidthInput:g.mediaSource?.width,frameHeightInput:g.mediaSource?.height,framesEncoded:g.outboundRTP.framesEncoded,frameRateEncoded:g.extensions?.frameRateEncoded,framesSent:g.outboundRTP.framesSent,frameRateSent:g.extensions?.frameRateSent,frameWidthSent:g.outboundRTP.frameWidth,frameHeightSent:g.outboundRTP.frameHeight,keyFramesEncoded:g.outboundRTP.keyFramesEncoded,nackCount:g.outboundRTP.nackCount,firCount:g.outboundRTP.firCount,pliCount:g.outboundRTP.pliCount,transportId:g.outboundRTP.transportId,altLayouts:g.altLayouts?.map(videoSendStatsFieldConverter)}),videoRecvStatsFieldConverter=g=>removeUndefinedFields({id:g.inboundRTP.ssrc.toString(),codecName:g.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:g.extensions?.bitrate,jitter:g.inboundRTP.jitter,packets:g.inboundRTP.packetsReceived,packetsPerSecond:g.extensions?.packetsPerSecond,packetsLost:g.inboundRTP.packetsLost,packetsLostPerSecond:g.extensions?.packetsLostPerSecond,packetsDiscarded:g.inboundRTP.packetsDiscarded,rtt:g.remoteOutboundRTP?.roundTripTime,msi:g.renderer?.msi,jitterBufferMs:g.extensions?.jitterBufferMs,frameRateOutput:g.extensions?.frameRateDecoded,frameRateDecoded:g.extensions?.frameRateDecoded,frameRateReceived:g.extensions?.frameRateReceived,frameWidthReceived:g.inboundRTP.frameWidth,frameHeightReceived:g.inboundRTP.frameHeight,longestFreezeDuration:g.extensions?.longestFreeze,totalFreezeDuration:g.extensions?.totalFreezeDuration,framesReceived:g.inboundRTP.framesReceived,framesDropped:g.inboundRTP.framesDropped,framesDecoded:g.inboundRTP.framesDecoded,keyFramesDecoded:g.inboundRTP.keyFramesDecoded,nackCount:g.inboundRTP.nackCount,firCount:g.inboundRTP.firCount,pliCount:g.inboundRTP.pliCount,transportId:g.inboundRTP.transportId}),audioSendStatsFieldConverter=g=>removeUndefinedFields({id:g.outboundRTP.ssrc.toString(),codecName:g.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:g.extensions?.bitrate,jitter:g.remoteInboundRTP?.jitter,packets:g.outboundRTP.packetsSent,packetsPerSecond:g.extensions?.packetsPerSecond,packetsLost:g.remoteInboundRTP?.packetsLost,packetsLostPerSecond:g.extensions?.packetsLostPerSecond,packetsDiscarded:g.remoteInboundRTP?.packetsDiscarded,rtt:g.remoteInboundRTP?.roundTripTime,audioLevel:g.mediaSource?.audioLevel,transportId:g.outboundRTP.transportId}),audioRecvStatsFieldConverter=g=>removeUndefinedFields({id:g.inboundRTP.ssrc.toString(),codecName:g.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:g.extensions?.bitrate,jitter:g.inboundRTP.jitter,packets:g.inboundRTP.packetsReceived,packetsPerSecond:g.extensions?.packetsPerSecond,packetsLost:g.inboundRTP.packetsLost,packetsLostPerSecond:g.extensions?.packetsLostPerSecond,packetsDiscarded:g.inboundRTP.packetsDiscarded,rtt:g.remoteOutboundRTP?.roundTripTime,jitterBufferMs:g.extensions?.jitterBufferMs,audioLevel:g.inboundRTP.audioLevel,healedRatio:g.extensions?.healedRatio,transportId:g.inboundRTP.transportId}),dataChannelStatsFieldConverter=g=>removeUndefinedFields({id:g.id,state:g.state,dataChannelIdentifier:g.dataChannelIdentifier,messagesSent:g.messagesSent,bytesSent:g.bytesSent,messagesReceived:g.messagesReceived,bytesReceived:g.bytesReceived,sendBitrate:g.extensions?.sendBitrate,recvBitrate:g.extensions?.recvBitrate,messagesSentPerSecond:g.extensions?.sendMessageRate,messagesReceivedPerSecond:g.extensions?.recvMessageRate}),transportStatsFieldConverter=g=>removeUndefinedFields({id:g.id,rtt:g.selectedCandidatePair?.currentRoundTripTime,availableIncomingBitrate:g.selectedCandidatePair?.availableIncomingBitrate,availableOutgoingBitrate:g.selectedCandidatePair?.availableOutgoingBitrate,relayProtocol:g.selectedCandidatePair?.localCandidate?.relayProtocol,candidateType:`${g.selectedCandidatePair?.localCandidate?.candidateType??""}:${g.selectedCandidatePair?.remoteCandidate?.candidateType??""}`});function compileAudioSendReport(g){return(g.audio?.send??[]).map(audioSendStatsFieldConverter)}function compileAudioRecvReport(g){return(g.audio?.recv??[]).map(audioRecvStatsFieldConverter)}function compileVideoSendReport(g){if(!g.video?.send?.length)return[];return g.video.send.map(videoSendStatsFieldConverter)}function compileVideoRecvReport(g){return(g.video?.recv??[]).map(videoRecvStatsFieldConverter)}function compileScreenShareSendReport(g){if(!g.sharing?.send?.length)return[];return g.sharing.send.map(videoSendStatsFieldConverter)}function compileScreenShareRecvReport(g){return(g.sharing?.recv??[]).map(videoRecvStatsFieldConverter)}function compileDataChannelReport(g){return(g.data??[]).map(dataChannelStatsFieldConverter)}function compileTransportReport(g){return Object.values(g.transports??{}).map(transportStatsFieldConverter)}function compileMediaStatsReport(g){return{audio:{send:compileAudioSendReport(g),recv:compileAudioRecvReport(g)},video:{send:compileVideoSendReport(g),recv:compileVideoRecvReport(g)},screenShare:{send:compileScreenShareSendReport(g),recv:compileScreenShareRecvReport(g)},data:compileDataChannelReport(g),transports:compileTransportReport(g)}}function compileMediaStatsReportExtensions(g,f){const S=g.qualityManager&&limitArraySize2(deepClone(g.qualityManager.videoMaxCapabilitiesEvents),f.config.diagnostics.telemetryLimits.numCapabilitiesRequested),v=g.qualityManager&&limitArraySize2(deepClone(g.qualityManager.sharingMaxCapabilitiesEvents),f.config.diagnostics.telemetryLimits.numCapabilitiesRequested);return removeUndefinedFields({Video_SubscriptionEvents:JSON.stringify(g.subscriptionManager?.video.events),Sharing_SubscriptionEvents:JSON.stringify(g.subscriptionManager?.sharing.events),Video_send_MaxCapabilities:JSON.stringify(S),Sharing_send_MaxCapabilities:JSON.stringify(v),RelayCandidate:g.relayCandidate,Video_recv_TimeToFirstFrame:g.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_TimeToFirstFrame:g.remoteVideoManager?.firstTimeToFirstFrameSharing,Video_recv_TimeToFirstFrameSinceSubscriptionStart:g.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartVideo,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:g.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartSharing,IceServers:g.iceServers})}function compileMediaStatsReportMetrics(g,f,S){return removeUndefinedFields({DeviceEvents:JSON.stringify(rebaseTime(S.deviceManager.deviceTelemetryEvents.filter((g=>g.timestamp>f)),"timestamp",g.creationTime)),IceConnectedStateTime:1e4*g.iceConnectedStateTime})}function compileMetricsTelemetryReport(g,f,S,v){const C=v.config.diagnostics.telemetryLimits,_=g.webrtcSessions[g.webrtcSessions.length-1];return removeUndefinedFields({MediaLegId:g.mediaLegId,CreationTime:getHpTimeFromMillis(g.creationTime),CallNumber:g.callNumber,SessionId:g.sessionId,MultiParty:g.isMultiParty,ErrorType:g.error?.type??"none",ErrorDetail:g.error?.detail??"none",IncompatibleOffer:g.error?.type===qt.MEDIA_ERROR.incompatibleOffer,TerminationTime:getHpTimeFromMillis(g.terminationTime),TerminationReason_code:g.terminationReason?.code,TerminationReason_subCode:g.terminationReason?.subCode,TerminationReason_phrase:g.terminationReason?.phrase,TerminationReason_remoteTerminated:g.terminationReason?.remoteTerminated,TerminationReason_clientReasonPhrase:g.terminationReason?.clientReasonPhrase,TerminationReason_clientReasonSubCode:g.terminationReason?.clientReasonSubCode,TerminationReason_resultCategories:g.terminationReason?.resultCategories,CallDuration:getHpTimeFromMillis(g.duration),IceInitTime:getHpTimeFromMillis(g.iceInitTime),IceConnectedStateTime:getHpTimeFromMillis(g.iceConnectedStateTime),NegotiationCount:g.negotiationCount,RejectedNegotiationCount:g.rejectedNegotiationCount,InitialNegotiationCompleted:g.initialNegotiationCompleted,InitialNegotiationType:g.initialNegotiationType,FinalAnswerTime:getHpTimeFromMillis(g.finalAnswerTime),TransportReconnectedCount:g.transportReconnectedCount,RollbackNegotiation:JSON.stringify(g.rollbackNegotiation),Relay:g.relay?JSON.stringify(g.relay):void 0,ActiveModalities:JSON.stringify(g.activeModalities),AllowedAudioSend:g.allowedAudioSend,AllowedVideoSend:g.allowedVideoSend,AllowedScreensharingSend:g.allowedScreensharingSend,RelayManager:JSON.stringify(g.relayTimers),AuthTokenStats:JSON.stringify(g.authTokenFetcherStats),CallMutedRatio:g.callMutedRatio,CallOsMuted:getHpTimeFromMillis(g.callOsMuted),CallHwSilent:getHpTimeFromMillis(g.callHwSilent),CallSwMuted:getHpTimeFromMillis(g.callSwMuted),CallSpeakerMuted:getHpTimeFromMillis(g.callSpeakerMuted),CallIsSpeaking:getHpTimeFromMillis(g.callIsSpeaking),DtmfSuccess:g.dtmfSuccessCount,DtmfFailure:g.dtmfFailureCount,ContributingSourcesError:_.contributingSourcesError,ReconnectInProgress:g.reconnect?.isReconnecting,RetargetIncomingCount:g.reconnect?.retargetCount.incoming,RetargetOutgoingCount:g.reconnect?.retargetCount.outgoing,RetargetCompletedCount:g.reconnect?.retargetCount.completed,RetargetRejectedCount:g.reconnect?.retargetCount.rejected,EscalationAttemptedCount:g.reconnect?.escalationCount.attempted,EscalationCompletedCount:g.reconnect?.escalationCount.completed,EscalationRejectedCount:g.reconnect?.escalationCount.rejected,Elevation:JSON.stringify(g.elevation),ReconnectAttemptedCount:g.reconnect?.reconnectCount.attempted,ReconnectConnectedCount:g.reconnect?.reconnectCount.connected,ReconnectAttempts:limitRebaseAndStringifyEvents(g.reconnect?.records,C.numReconnects,"startTime",g.creationTime),NetworkEvents:limitRebaseAndStringifyEvents(g.reconnect?.tmpRecords,C.numNetworkEvents,"startTime",g.creationTime),NoIceCandidatesGoodEventCount:g.noIceCandidatesEventCount.good,NoIceCandidatesBadEventCount:g.noIceCandidatesEventCount.bad,NoRelayIceCandidatesGoodEventCount:g.noRelayIceCandidatesEventCount.good,NoRelayIceCandidatesBadEventCount:g.noRelayIceCandidatesEventCount.bad,MicrophoneInUseGoodEventCount:g.microphoneInUseEventCount.good,MicrophoneInUseBadEventCount:g.microphoneInUseEventCount.bad,CameraInUseGoodEventCount:g.cameraInUseEventCount.good,CameraInUseBadEventCount:g.cameraInUseEventCount.bad,CameraFreezeStartEventCount:g.cameraFreezeEventCount.start,CameraFreezeEndEventCount:g.cameraFreezeEventCount.end,NetworkRecvGood:g.networkRecvUFD.good,NetworkRecvGoodRatio:g.networkRecvUFD.goodRatio,NetworkRecvPoor:g.networkRecvUFD.poor,NetworkRecvPoorRatio:g.networkRecvUFD.poorRatio,NetworkRecvBad:g.networkRecvUFD.bad,NetworkRecvBadRatio:g.networkRecvUFD.badRatio,NetworkSendGood:g.networkSendUFD.good,NetworkSendGoodRatio:g.networkSendUFD.goodRatio,NetworkSendPoor:g.networkSendUFD.poor,NetworkSendPoorRatio:g.networkSendUFD.poorRatio,NetworkSendBad:g.networkSendUFD.bad,NetworkSendBadRatio:g.networkSendUFD.badRatio,Connection_Downlink:sampleseries(_.networkInfo,(g=>g.downlink)),Connection_EffectiveType:_.networkInfo.map((g=>g.effectiveType)).filter((g=>g)).join(","),Connection_Rtt:sampleseries(_.networkInfo,(g=>g.rtt)),Connection_SaveData:getLast(_.networkInfo)?.saveData,RawOutputAudioAccessAttempted:g.rawMedia.audio.recv.numAttempts,RawOutputAudioAccessDurationRatio:g.rawMedia.audio.recv.durationRatio,RawInputAudioOverrideAttempted:g.rawMedia.audio.send.numAttempts,RawInputAudioOverrideDurationRatio:g.rawMedia.audio.send.durationRatio,ZeroCaptureDevicesEnumeratedEventRatio:g.zeroCaptureDevicesRatio,ZeroRenderDevicesEnumeratedEventRatio:g.zeroRenderDevicesRatio,DeviceCaptureNotFunctioningEventRatio:g.deviceCaptureFailuresRatio,DeviceRenderNotFunctioningEventRatio:g.deviceRenderFailuresRatio,UFDs:limitRebaseAndStringifyEvents(g.ufds,C.numUFDs,"timestamp",g.creationTime),remoteUFDs:limitRebaseAndStringifyEvents(g.remoteUfds,C.numUFDs,"timestamp",g.creationTime),MediaQosEnabled:S.configuration.mediaConfig?.enableMediaQoS??!1,PortRangeConfigured:!!S.configuration.mediaConfig?.mediaPortRanges,hardwareConcurrency:S.configuration.userAgentConfig.hardwareConcurrency,ETag:g.ETag,ConfigIds:g.configIds,GPUName:S.configuration.userAgentConfig.unmaskedGlRenderer,PermissionStates:JSON.stringify(S.deviceManager.permissionStates),DeviceList:JSON.stringify(S.deviceManager.deviceList),DeviceListDebug:JSON.stringify(S.deviceManager.deviceDebugStrings),DevicesChangeCount:g.deviceManager.devicesChangeCount,DevicesPollChangeCount:g.deviceManager.devicesPollChangeCount,DeviceSelectionChangeCount:g.deviceManager.deviceSelectionChangeCount,DeviceSelectionChangeFromInterfaceCount:g.deviceManager.deviceSelectionChangeCountFromInterface,DevicesCount:JSON.stringify(S.deviceManager.devicesCount),UsedMicrophone:S.deviceManager.usedDevices?.microphone,UsedSpeaker:S.deviceManager.usedDevices?.speaker,UsedCamera:S.deviceManager.usedDevices?.camera,DeviceEvents:limitRebaseAndStringifyEvents(S.deviceManager.deviceTelemetryEvents.filter((g=>g.timestamp>f)),C.numDeviceEvents,"timestamp",g.creationTime),VideoEffects:limitRebaseAndStringifyEvents(S.deviceManager.videoEffectsEvents.filter((g=>g.timestamp>f)),C.numVideoEffectsEvents,"timestamp",g.creationTime),AudioEffects:limitRebaseAndStringifyEvents(S.deviceManager.audioEffectsEvents.filter((g=>g.timestamp>f)),C.numAudioEffectsEvents,"timestamp",g.creationTime),WorkerEvents:limitRebaseAndStringifyEvents(S.deviceManager.workerEvents.filter((g=>g.timestamp>f)),C.numWorkerEvents,"timestamp",g.creationTime),MediaByPassEnabled:!!S.configuration.mediaConfig.enableMediaBypass,CallConstraints:JSON.stringify(g.callConstraints),DominantSpeaker:JSON.stringify(generateDominantSpeakerReport(g.dominantSpeaker,g.terminationTime)),AudioSourceNumOfReopenRequests:g.deviceManager.audioSourceNumOfReopenRequests||void 0,AudioSourceNumOfSuccessfulReopens:g.deviceManager.audioSourceNumOfSuccessfulReopens||void 0,AudioCaptureErrorCodeFlagsInit:g.deviceManager.audioCaptureDeviceErrorFlag,AudioRenderErrorCodeFlagsInit:g.deviceManager.audioRenderDeviceErrorFlag,AudioSinkNumOfReopenRequests:g.audioRenderer.sinkNumOfReopenRequests,AudioSinkNumOfSuccessfulReopens:g.audioRenderer.sinkNumOfSuccessfulReopens,CallSetupTimeTracker:JSON.stringify(g.webrtcSessions[0].negotiation.callSetupTimeReport),LastSessionSetupTimeTracker:g.webrtcSessions.length>1?JSON.stringify(_.negotiation.callSetupTimeReport):void 0,BatteryLevel:g.batteryLevel})}function getHpTimeFromMillis(g){return 1e4*g}function generateDominantSpeakerReport(g,f=Number(new Date)){if(!g)return;const S=deepClone(g);return g.lastMsgDate&&(g.timeSinceLastMsg=g.lastMsgDate-f),delete S.lastMsgDate,delete S.lastHistory,removeUndefinedFields(S)}function getValue(g,f,S=0){const v=f.filter((g=>void 0!==g));let C;switch(g){case"Difference":C=v[v.length-1]-v[0];break;case"Average":C=v.reduce(((g,f)=>g+f),0)/v.length;break;case"LastValue":C=v[v.length-1]}return C||0===C?`${"number"==typeof C?+C.toFixed(S):C}`:void 0}function filterStats(g,f,S){return(S?g.map((g=>g?.[f]?.[S])):g.map((g=>g?.[f]))).filter((g=>void 0!==g)).reduce(((g,f)=>g.concat(f)),[])}function findTransportStats(g){const f=g.find((g=>g?.transports));return f?f.transports[Object.keys(f.transports)[0]]:void 0}function getVideoProcessing(g){const f=g[g.length-1]?.extensions?.powerEfficient;return void 0===f?"":f?"hw":"sw"}function getMediaDirection(g,f){return g&f?"Bidirectional":g?"ReceiveFromPeer":f?"SendToPeer":"Inactive"}function getSendActivityState(g){const f=g[g.length-1]?.extensions?.callIsMuted,S=g[g.length-1]?.extensions?.rawInputVolume;return f?"0":!f&&S>0?"2":f||0!==S?void 0:"1"}function compileAudioReport2(g,f){const S=filterStats(g,"audio","send"),v=filterStats(g,"audio","recv"),C=findTransportStats(g);if(S.length||v.length)return removeUndefinedFields({mediaType:"Audio",mediaDirection:getMediaDirection(v.length,S.length),"Received BW estimate":getValue("Average",v.map((g=>g?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Recv Loss Rate (Avg)":getValue("LastValue",v.map((g=>g?.extensions?.lossRate/100)),3),"Rtp Packets Received":getValue("Difference",v.map((g=>g?.inboundRTP.packetsReceived))),"Rtp Packet Sent":getValue("Difference",S.map((g=>g?.outboundRTP.packetsSent))),"Sent BW estimate":getValue("Average",S.map((g=>g?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Audio Codec":getValue("LastValue",S.map((g=>g?.codec?.mimeType)))?.split("/").pop(),"Send RTT (Avg)":getValue("LastValue",S.map((g=>g?.extensions?.rttAvg))),"Audio NW jitter avg":getValue("LastValue",v.map((g=>g?.extensions?.jitterAvg)),3),"Audio send bps":getValue("Average",S.map((g=>g?.extensions?.bitrate))),"JB delay (ms)":getValue("LastValue",v.map((g=>g?.extensions?.jitterBufferDelayMs))),"Recv Audio Codec":getValue("LastValue",v.map((g=>g?.codec?.mimeType)))?.split("/").pop(),"Current Render Device Name":f?.speaker,"Current Capture Device Name":f?.microphone,"Latest Network Type":C?.selectedCandidatePair?.localCandidate?.networkType,"Latest Transport Protocol":C?.selectedCandidatePair?.localCandidate?.protocol,"Latest Reflexive Address":ipAddressConverter(C?.extensions?.reflexiveLocalIP),"Local Address":ipAddressConverter(C?.selectedCandidatePair?.localCandidate?.ip),"Local short-term Healed Data Ratio":getValue("LastValue",v.map((g=>g?.extensions?.healedRatio))),"Send activity (0=muted; 1=inactive; 2=active)":getSendActivityState(S)})}function formatVideoStats(g){const f={},formatStats=S=>{g.map((g=>g?.video?.[S])).forEach((g=>{g?.forEach((g=>{var v;const C=g?.mediaEntity?.remoteSsrc;f[C]??(f[C]={}),(v=f[C])[S]??(v[S]=[]),f[C][S].push(g)}))}))};return formatStats("recv"),formatStats("send"),f}function compileVideoReport(g,f){const S=[],v=formatVideoStats(g);for(const{send:g,recv:C}of Object.values(v)){let v={mediaType:"Camera",mediaDirection:getMediaDirection(C?.length,g?.length)};C&&(v={...v,...compileVideoRecvReport2(C)}),g&&(v={...v,...compileVideoSendReport2(g,f)}),S.push(removeUndefinedFields(v))}return S}function compileVideoSendReport2(g,f){const S=getValue("LastValue",g.map((g=>g?.codec?.mimeType)))?.split("/").pop(),v=S?S+` ${getVideoProcessing(g)}`:void 0;return{"Rtp Packet Sent":getValue("Difference",g.map((g=>g?.outboundRTP.packetsSent))),"Sent BW estimate":getValue("Average",g.map((g=>g?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Current Bitrate":getValue("Average",g.map((g=>g?.extensions?.bitrate))),"Allocated Send Bandwidth Average":getValue("LastValue",g.map((g=>g?.extensions?.bitrateAvg))),"Send Actual Height":getValue("LastValue",g.map((g=>g?.outboundRTP.frameHeight))),"Send Actual Width":getValue("LastValue",g.map((g=>g?.outboundRTP.frameWidth))),"Send Current Frame Rate":getValue("Average",g.map((g=>g?.extensions?.frameRateSent))),"Send RTT (Avg)":getValue("LastValue",g.map((g=>g?.extensions?.rttAvg))),"Sent Codec Name":v,"Webcam Freeze Intervals":getValue("LastValue",g.map((g=>g?.extensions?.captureFreezeIntervalsCount))),"Current Capture Device Name":f?.camera,"Number of Sync Frame Request per Minute":getValue("LastValue",g.map((g=>g?.extensions?.pliRate)))}}function compileVideoRecvReport2(g){const f=getValue("LastValue",g.map((g=>g?.mediaEntity?.xSourceStreamId))),S=getValue("LastValue",g.map((g=>g?.codec?.mimeType)))?.split("/").pop(),v=S?S+` ${getVideoProcessing(g)}`:void 0;return{"Recv Loss Rate (Avg)":getValue("LastValue",g.map((g=>g?.extensions?.lossRate)),3),"Received BW estimate":getValue("Average",g.map((g=>g?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Receive Current Bitrate":getValue("Average",g.map((g=>g?.extensions?.bitrate))),"Rtp Packets Received":getValue("Difference",g.map((g=>g?.inboundRTP.packetsReceived))),"Receive Actual Height":getValue("LastValue",g.map((g=>g?.inboundRTP.frameHeight))),"Receive Actual Width":getValue("LastValue",g.map((g=>g?.inboundRTP.frameWidth))),"Receive Current Frame Rate":getValue("Average",g.map((g=>g?.extensions?.frameRateReceived))),"Received Codec Name":v,"Received Total Freeze Fraction (ms per min)":getValue("LastValue",g.map((g=>g?.extensions?.totalFreezeFraction))),videoSourceId:f?parseInt(f):void 0,"Received Fps Time Weighted Harmonic Average":getValue("LastValue",g.map((g=>g?.extensions?.fpsHarmonicAverage)))}}function compileSharingReport(g){const f=filterStats(g,"sharing","send"),S=filterStats(g,"sharing","recv");if(!S.length&&!f.length)return;let v={mediaType:"AppSharing",mediaDirection:"Bidirectional","Render Device Name":""};return S.length&&(v={...v,...compileVideoRecvReport2(S)}),f.length&&(v={...v,...compileVideoSendReport2(f,{microphone:void 0,camera:"Screen sharing",speaker:void 0})}),removeUndefinedFields(v)}function compileReports(g,f,S){const v=compileAudioReport2(g,f);v&&S.channels.push(v);const C=compileVideoReport(g,f);C.length&&S.channels.push(...C);const _=compileSharingReport(g);_&&S.channels.push(_)}function compileTeamsRealtimeTelemetryReport(g,f){const S=filterStats(g,"inactiveTracks"),v={channels:[]};return compileReports(g,f,v),S.length&&compileReports(S,void 0,v),v}function compileVideoReportForE2E(g,f,S,v,C){return removeUndefinedFields({recv:removeUndefinedFields({id:S?.inboundRTP.id,ssrc:S?.inboundRTP.ssrc,mediaType:S?.inboundRTP.mediaType??S?.inboundRTP.kind,bytes:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.bytesReceived),C),packets:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.packetsReceived),C),packetsLost:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.packetsLost),C),codec:S?.codec?.mimeType.split("/").pop(),codecReport:S?.aggregated?.codecReport,framesDecoded:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.framesDecoded),C),height:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.frameHeight),C),width:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.frameWidth),C),frameRate:sampleseriesArr(f[g]?.recv,(g=>g.extensions?.frameRateReceived),C)}),send:removeUndefinedFields({id:v?.outboundRTP.id,ssrc:v?.outboundRTP.ssrc,mediaType:v?.outboundRTP.mediaType??v?.outboundRTP.kind,bytes:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.bytesSent),C),packets:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.packetsSent),C),packetsLost:sampleseriesArr(f[g]?.send,(g=>g.remoteInboundRTP?.packetsLost),C),codec:v?.codec?.mimeType.split("/").pop(),framesEncoded:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.framesEncoded),C),heightInput:v?.mediaSource?.height,widthInput:v?.mediaSource?.width,height:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.frameHeight),C),width:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.frameWidth),C),frameRate:sampleseriesArr(f[g]?.send,(g=>g.extensions?.frameRateSent),C)})})}function compileAudioReportForE2E(g,f,S,v){return removeUndefinedFields({recv:removeUndefinedFields({id:f?.inboundRTP.id,ssrc:f?.inboundRTP.ssrc,mediaType:f?.inboundRTP.mediaType??f?.inboundRTP.kind,bytes:sampleseriesArr(g.audio?.recv,(g=>g.inboundRTP.bytesReceived),v),packets:sampleseriesArr(g.audio?.recv,(g=>g.inboundRTP.packetsReceived),v),packetsLost:sampleseriesArr(g.audio?.recv,(g=>g.inboundRTP.packetsLost),v),codec:f?.codec?.mimeType.split("/").pop(),audioLevel:sampleseriesArr(g.audio?.recv,(g=>Math.floor(65535*g.inboundRTP.audioLevel)),v)}),send:removeUndefinedFields({id:S?.outboundRTP.id,ssrc:S?.outboundRTP.ssrc,mediaType:S?.outboundRTP.mediaType??S?.outboundRTP.kind,bytes:sampleseriesArr(g.audio?.send,(g=>g.outboundRTP.bytesSent),v),packets:sampleseriesArr(g.audio?.send,(g=>g.outboundRTP.packetsSent),v),packetsLost:sampleseriesArr(g.audio?.send,(g=>g.remoteInboundRTP?.packetsLost),v),codec:S?.codec?.mimeType.split("/").pop(),audioLevel:sampleseriesArr(g.audio?.send,(g=>Math.floor(65535*g.aggregated.audioLevel)),v)})})}function compileE2EDiagReport(g,f,S,v,C){const _=g.aggregatedModalityStats,T=getLast(_.audio?.recv),I=getLast(_.audio?.send),b=getLast(_.video?.recv),A=getLast(_.video?.send),P=getLast(_.sharing?.recv),R=getLast(_.sharing?.send),M=[],w=[];return g.statsOnSubscribed.video?.forEach((g=>M.push(g))),g.statsOnSubscribed.sharing?.forEach((g=>w.push(g))),removeUndefinedFields({multipleVideoStreams:g.multiViewStats,WebRTCStats_ssrc:removeUndefinedFields({audio:compileAudioReportForE2E(_,T,I,C),video:compileVideoReportForE2E("video",_,b,A,C),sharing:compileVideoReportForE2E("sharing",_,P,R,C)}),CallSwMuted:1e3*f.callSwMuted,DeviceEvents:rebaseTime(S.deviceManager.deviceTelemetryEvents.filter((g=>g.timestamp>v)),"timestamp",f.creationTime),VideoEffects:rebaseTime(S.deviceManager.videoEffectsEvents.filter((g=>g.timestamp>v)),"timestamp",f.creationTime),AudioEffects:rebaseTime(S.deviceManager.audioEffectsEvents.filter((g=>g.timestamp>v)),"timestamp",f.creationTime),statsErrors:f.statsErrors,WorkerEvents:rebaseTime(S.deviceManager.workerEvents.filter((g=>g.timestamp>v)),"timestamp",f.creationTime)})}var iT=class{constructor(g,f){this.rootRef=g,this.configProvider=f}get rawRootRef(){return this.rootRef}getSessionTelemetry(g){const f=this.getLatestSession(g);if(!f)return;const S={metrics:{},Extensions:{}},v=Jt();try{const g=f.callNumber>1?this.rootRef.sessions.find((g=>f.callNumber-1===g.callNumber)):void 0,v=g?.terminationTime??0,C=f.webrtcSessions[f.webrtcSessions.length-1];S.metrics=compileMetricsTelemetryReport(f,v,this.rootRef,this.configProvider),S.Extensions=compileExtensionsTelemetryReport(C,this.configProvider,f.statsErrors)}catch(g){f[Q_].addStatsError("DiagnosticsReport:getSessionTelemetry",stringifyObject(g)),S.Extensions.WebRTCStats_statsErrors=JSON.stringify(f.statsErrors)}return S.metrics.ReportGenerationTimeMs=round(Jt()-v),S}getTeamsRealtimeTelemetry(g){const f=this.getLatestSession(g);if(f)try{const g=f.webrtcSessions[f.webrtcSessions.length-1],S=this.configProvider.config.diagnostics.teamsRealtimeTelemetry.pollingInterval;return compileTeamsRealtimeTelemetryReport(g.statsReports.slice(g.statsReports.length-S),this.rootRef.deviceManager.rawUsedDevices)}catch(g){throw f[Q_].addStatsError("DiagnosticsReport:getRealTimeTelemetry",stringifyObject(g)),g}}getMediaSessionStats(g){const f=this.getLatestSession(g);if(f)try{const g=f.callNumber>1?this.rootRef.sessions.find((g=>f.callNumber-1===g.callNumber)):void 0,S=g?.terminationTime??0,v=f.webrtcSessions[f.webrtcSessions.length-1],C=v?.statsReports.length?v.statsReports[v.statsReports.length-1]:void 0,_=C?compileMediaStatsReport(C):void 0;return _&&(_.extensions=compileMediaStatsReportExtensions(v,this.configProvider),_.metrics=compileMediaStatsReportMetrics(f,S,this.rootRef)),_}catch(g){throw f[Q_].addStatsError("DiagnosticsReport:getMediaSessionStats",stringifyObject(g)),g}}getDiagnosticsForE2eTests(g){const f=this.getLatestSession(g);let S={statsErrors:[]};if(f){try{const g=f.webrtcSessions[f.webrtcSessions.length-1],v=f.callNumber>1?this.rootRef.sessions.find((g=>f.callNumber-1===g.callNumber)):void 0,C=v?.terminationTime??0;S=compileE2EDiagReport(g,f,this.rootRef,C,this.configProvider.config.diagnostics.collectionLimits.numSamplesForE2E)}catch(g){const v="DiagnosticsReport:getDiagnosticsForE2eTests",C=stringifyObject(g);f[Q_].addStatsError(v,C),arrayLimitedPush2(S.statsErrors,{origin:v,error:C,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors)}return S}}getLatestSession(g){return this.rootRef.sessions.filter((f=>f.sessionId===g)).sort(((g,f)=>g.callNumber-f.callNumber)).pop()}},nT=class{constructor(g,f){this.configProvider=g,this.deviceManagerDiagnostics=f,this.root={creationTime:Date.now(),numTotalSessions:0,deviceManager:this.deviceManagerDiagnostics.getObjectRef(),configuration:{stackConfig:this.configProvider.stackConfig,defaultConfig:this.configProvider.defaultConfig,mediaConfig:{},userAgentConfig:{isAudioOutputSelectionSupported:this.configProvider.userAgentConfig.isAudioOutputSelectionSupported,isBrowserRollbackSupported:this.configProvider.userAgentConfig.isBrowserRollbackSupported,hardwareConcurrency:oa.hardwareConcurrency,unmaskedGlRenderer:oa.unmaskedGlRenderer,hasMediaApi:oa.hasMediaApi(),hasCapabilitiesApi:oa.hasCapabilitiesApi(),hasUnifiedPlanSupport:void 0},consoleOverrides:this.configProvider.consoleOverrides,fullConfig:deepClone(this.configProvider.config),ecsConfigUpdates:[]},browserInfo:et.getBrowserInfo(),sessions:[]},this.diagnosticsReport=new iT(this.root,this.configProvider),this.configProvider.on("newConfigReceived",((g,f,S)=>{this.root.configuration.ecsConfigUpdates.push({timestamp:Date.now(),etag:f,configIds:S,config:g})})),this.configProvider.on("configUpdated",(()=>{this.root.configuration.consoleOverrides=this.configProvider.consoleOverrides,this.root.configuration.fullConfig=deepClone(this.configProvider.config)}))}get reportGenerator(){return this.diagnosticsReport}get rootRef(){return this.root}set mediaConfig(g){this.root.configuration.mediaConfig=g}newSession(g,f,S){this.root.configuration.userAgentConfig.hasUnifiedPlanSupport=this.configProvider.mediaConfig.simulcastSessionEnabled;const v=new X_(S,g,this.diagnosticsReport,this.root.deviceManager,++this.root.numTotalSessions,f);return arrayLimitedPush2(this.root.sessions,v.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numSessions),v}},rT=class _JamaLogger{constructor(g,f){this.safe=g,this.unsafe=f,this.safe||(this.safe=this.unsafe)}warn(...g){this.unsafe.warn(...g)}error(...g){this.unsafe.error(...g)}debug(...g){this.unsafe.debug(...g)}info(...g){this.unsafe.info(...g)}createChild(g){return new _JamaLogger(this.safe.createChild(g),this.unsafe.createChild(g))}},sT=M,aT=class{constructor(g){this.logger=g,this.extensionId="nkeimhogjdpnpccoofpliimaahmaaome",this.editorExtensionId="ncbjelpjchkpbikbpkcchkhkblodoama",this.logId="TeamsWebRTCLogs",this.loggingState="unknown",this.connectionCount=0;window.webRtcInternalsCollector=this}get isExtensionAvailable(){return"unavailable"!==this.loggingState}async updateSessionCount(g){this.isExtensionAvailable&&(0===this.connectionCount&&1===g?("stopped"===this.loggingState&&await this.discardLogs(),await this.initialStartLogging()):0===g&&await this.stopLogging(),this.connectionCount=g)}async collect(){return this.isExtensionAvailable?this.collectPromise?this.collectPromise:this.collectPromise=new Promise((async g=>{try{this.connectionCount>0&&(this.logger.safe.info(`Stopping logger for gathering, open connections: ${this.connectionCount}`),await this.stopLogging()),await this.storeLogs();const f=await this.gatherFromStorage();this.connectionCount>0&&await this.continueLogging(),g(f.length>0?f.join("\r\n"):"")}catch(f){this.logger.safe.error("Error while collecting logs",f),g(JSON.stringify(f))}this.collectPromise=void 0})):""}async initialStartLogging(){try{await this.startLogging()}catch(g){if(g?.includes("A log is already open"))try{const f=g.match(/State=(\w+)/);await this.cleanState(f?.[1]),await this.startLogging()}catch(g){this.logger.safe.error("Error while starting logging at cleanup phase",g),this.loggingState="unknown"}else this.logger.safe.error("Error while starting logging",g),this.loggingState="unavailable"}}async continueLogging(){try{await this.startLogging()}catch(g){this.logger.safe.error("Error while continuing logging",g),this.loggingState="stopped"}}async startLogging(){await this.sendMessage(this.extensionId,{method:"logging.start"}),this.logger.safe.info("Logging started"),this.loggingState="started"}async cleanState(g){try{if("started"===g)await this.stopLogging(),await this.discardLogs();else{if("stopped"!==g)throw new Error(`Unexpected logging state: ${g}`);await this.discardLogs()}}catch(g){this.logger.safe.error("Error while cleaning state",g)}}async stopLogging(){try{await this.sendMessage(this.extensionId,{method:"logging.stop"}),this.logger.safe.info("Logging stopped"),this.loggingState="stopped"}catch(g){this.logger.safe.error("Error while stopping logging",g)}}async discardLogs(){try{await this.sendMessage(this.extensionId,{method:"logging.discard"}),this.logger.safe.info("Logs discarded"),this.loggingState="closed"}catch(g){this.logger.safe.error("Error while discarding logs",g)}}async storeLogs(){try{await this.sendMessage(this.extensionId,{method:"logging.store",logId:this.logId}),this.logger.safe.info(`Logs stored to ${this.logId}`),this.loggingState="closed"}catch(g){this.logger.safe.error("Error while storing logs",g)}}async gatherFromStorage(){const g=[];let f={offset:0};do{f=await this.sendMessage(this.editorExtensionId,{api:"getWebRtcLog",logId:this.logId,offset:f.offset}),g.push(f.data),this.logger.safe.info(`Batch gathered with offset: ${f.offset}, moreData: ${f.moreData}`)}while(f.moreData);return this.logger.safe.info("Finished gathering"),g}sendMessage(g,f){return new Promise(((S,v)=>{const C=chrome.runtime;C.sendMessage(g,f,(g=>{if(!g||g?.error){const S=g?JSON.stringify(g.error):C.lastError;v(`sendMessage ${JSON.stringify(f)} failed with error: ${S}`)}S(g)}))}))}},oT=(()=>{let g;function getInstance(f,S){return S.config.enableWebRtcInternalsLogs&&et.isBrowser("EdgeAnaheim")&&!!chrome?.runtime?(g||(g=new aT(f)),g):(f.safe.info("WebRTC internal logging is disabled"),{collect:()=>Promise.resolve(""),updateSessionCount:()=>Promise.resolve()})}return{getInstance:getInstance}})(),lT=oT,cT=class{getId(){return 0}getDeviceId(){return qt.EMPTY_DEVICE_ID}getPreviewAsync(g,f){return Promise.resolve(null)}getDescription(){return"display"}getType(){return 1}getIcon(g,f){return Promise.resolve(null)}},dT=class{constructor(g){this.descr=g}getId(){return 0}getDeviceId(){return this.descr.browserId}getPreviewAsync(g,f){return Promise.resolve(null)}getDescription(){return this.descr.label}getType(){return 3}getIcon(g,f){return Promise.resolve(null)}},hT=class{constructor(g){this.deviceManager=g,this.sharingSource=new cT}onScreensChanged(g){return{dispose:()=>{}}}enumerateScreensAsync(){return Promise.resolve([this.sharingSource])}enumerateWindowsAsync(){return Promise.resolve([])}async enumerateCamerasAsync(){return(await this.deviceManager.enumerateDevicesAsync()).filter((g=>"camera"===g.kind)).map((g=>new dT(g)))}},uT=class{constructor(g){this.configProvider=g,this.data={records:[],tmpRecords:[],isReconnecting:!1,networkRecoveredCount:0,disconnectedRecoveredCount:0,reconnectCount:{attempted:0,connected:0},retargetCount:{incoming:0,outgoing:0,completed:0,rejected:0},escalationCount:{attempted:0,completed:0,rejected:0}}}registerState(g){const f="connected"===g?this.activeTmpRecord:this.getTmpRecord();f&&f.events[f.events.length-1]?.type!==g&&(f.events.push({type:g,time:Date.now()-f.startTime}),"networkOnline"===g?this.data.networkRecoveredCount++:"connected"===g&&this.data.disconnectedRecoveredCount++,"reconnect"!==g&&"connected"!==g||(f.endTime=Date.now()-f.startTime,this.activeTmpRecord=null))}registerReconnectAttempt(g){this.activeRecord&&(this.activeAttempt={direction:g,startTime:Date.now()-this.activeRecord.startTime,status:!1},this.data.isReconnecting=!0,arrayLimitedPush(this.activeRecord.attempts,this.activeAttempt,this.configProvider.config.diagnostics.collectionLimits.numReconnectRecords))}registerReconnectAttemptStatus(g){"completed"===g&&(this.data.isReconnecting=!1),this.activeAttempt&&this.activeRecord&&(this.activeAttempt.endTime=Date.now()-this.activeRecord.startTime,this.activeAttempt.status="completed"===g)}registerReconnect(g){if(this.data.reconnectCount[g]++,this.data.isReconnecting="attempted"===g,"attempted"===g){if(this.activeRecord)return;this.activeRecord={startTime:Date.now(),attempts:[]},arrayLimitedPush(this.data.records,this.activeRecord,this.configProvider.config.diagnostics.collectionLimits.numReconnects)}else if("connected"===g){if(!this.activeRecord)return;this.activeTmpRecord&&this.registerState("connected"),this.activeRecord.endTime=Date.now()-this.activeRecord.startTime,this.activeRecord=void 0,this.activeAttempt=void 0}}registerRetarget(g){this.data.retargetCount[g]++}registerEscalation(g){this.data.escalationCount[g]++}getObject(){return this.data}getTmpRecord(){return(!this.activeTmpRecord||this.activeTmpRecord.endTime>0)&&(this.activeTmpRecord={startTime:Date.now(),events:[]},this.data.tmpRecords.push(this.activeTmpRecord)),this.activeTmpRecord}},gT=class{constructor(){}process(g){return this.mediaLegId=g||this.mediaLegId||uniqueId().toUpperCase(),this.mediaLegId}},pT=class{constructor(g,f){this.relayManager=g,this.diagnostics=f}initialize(){}setRelayOverride(){}async queryRelaysAsync(g){const f=await this.relayManager.queryRelaysAsync(g);return f.length>0&&(this.diagnostics.relay=f[0]),f}getStats(){return this.relayManager.getStats?.()??{stats:{unavailable:"1"}}}getAuthTokenStats(){return this.relayManager.getAuthTokenStats()}},mT=class{constructor(g,f,S){this.stats=g,this.diag=f,S&&f&&(S.reconnect=f.getObject())}registerState(g){this.diag?.registerState(g)}registerReconnectAttempt(g){this.stats.registerReconnectAttempt(g),this.diag?.registerReconnectAttempt(g)}registerReconnectAttemptStatus(g){switch(g){case"completed":this.stats.registerReconnectAttemptCompleted();break;case"rejected":this.stats.registerReconnectAttemptRejected()}this.diag?.registerReconnectAttemptStatus(g)}registerReconnect(g){switch(g){case"attempted":this.stats.registerReconnectAttempted();break;case"connected":this.stats.registerReconnectConnected()}this.diag?.registerReconnect(g)}registerRetarget(g){switch(g){case"completed":this.stats.registerRetargetCompleted();break;case"rejected":this.stats.registerRetargetRejected();break;case"incoming":this.stats.registerRetargetIncoming();break;case"outgoing":this.stats.registerRetargetOutgoing()}this.diag?.registerRetarget(g)}registerEscalation(g){switch(g){case"attempted":this.stats.registerEscalationStart();break;case"completed":this.stats.registerEscalationCompleted();break;case"rejected":this.stats.registerEscalationRejected()}this.diag?.registerEscalation(g)}},fT=class{constructor(g){this.initialCallbacks=g,this.queueCallbacks={onTerminated:this.genCallback(this.initialCallbacks.onTerminated),onSessionErrorOccurred:this.genCallback(this.initialCallbacks.onSessionErrorOccurred),onNegotiationRequired:this.genCallback(this.initialCallbacks.onNegotiationRequired),onAudioStateChanged:this.genCallback(this.initialCallbacks.onAudioStateChanged),onAudioHwSilentChanged:this.genCallback(this.initialCallbacks.onAudioHwSilentChanged),onTransportDisconnected:this.genCallback(this.initialCallbacks.onTransportDisconnected),onTransportConnected:this.genCallback(this.initialCallbacks.onTransportConnected),onTransportInitialized:this.genCallback(this.initialCallbacks.onTransportInitialized),onTransportFailed:this.genCallback(this.initialCallbacks.onTransportFailed),onUpdateMediaDescriptionsRequired:this.genCallback(this.initialCallbacks.onUpdateMediaDescriptionsRequired),onTeamsRealtimeTelemetryReport:this.genCallback(this.initialCallbacks.onTeamsRealtimeTelemetryReport)},this.queue=[]}flush(){this.queue.forEach((g=>{g.method.apply(null,g.args)})),this.clear()}clear(){this.queue=[]}genCallback(g){return(...f)=>this.queue.push({method:g,args:f})}},ST=class{constructor(g,f){this.relayConfig=g,this.logger=f}async ensureOnline(){if(0===this.relayConfig.length)return this.logger.safe.warn("No TURN servers defined"),0;if(this.probeDeferred)return this.probeDeferred.promise;this.logger.safe.info(`Starting TURN probes with ${JSON.stringify(this.relayConfig[0].urls)}`),this.checkStart=Date.now();let g=0;this.probeDeferred=new dt;const check=async()=>{await this.performCheck()&&this.finalize()},spawnCheckAndScheduleNext=()=>{check(),g<3e3&&(g+=1e3),this.probeTimer=setTimeout(spawnCheckAndScheduleNext,g)};return spawnCheckAndScheduleNext(),this.probeDeferred.promise}finalize(){this.probeTimer&&(clearTimeout(this.probeTimer),this.probeTimer=0),this.probeDeferred&&(this.probeDeferred.resolve(Date.now()-this.checkStart),this.probeDeferred=null)}dispose(){this.finalize()}async performCheck(){this.logger.safe.info("Probing...");const g=this.tryCreatePc();if(!g)return!1;g.createDataChannel("probe");const f=new dt;function finalize(S){g.onicecandidate=void 0,g.close(),f.resolve(S)}let S=!1;return g.onicecandidate=g=>{const f=g.candidate;if(!f)return S||this.logger.safe.info("still offline"),void finalize(S);const v=f.type??parseCandidateString(f.candidate).type;"srflx"!==v&&"relay"!==v||(this.logger.safe.info(`Back online through ${v} candidate`),S=!0,"srflx"===v&&(this.ipFromRelay=f.address,finalize(!0)))},await g.setLocalDescription(await g.createOffer()),f.promise}tryCreatePc(){try{return new Xs.window.RTCPeerConnection({iceServers:this.relayConfig})}catch(g){return this.logger.safe.info(`Failed to create PC, errCode=${g.code}`),null}}},createIceServers=(g,f)=>g.reduce(((g,S)=>{const v=[],C=S.addresses&&S.addresses[0],_=S.fqdns&&S.fqdns.length>0,T=f.iceUdpAddressType,I=f.iceTcpAddressType,b=f.iceServerTransport;if(!C&&!_)return g;if(b.includes("udp")&&S.udpPort){const g=!_||"fqdn"!==T&&C?C:S.fqdns[0];v.push(`turn:${g}:${S.udpPort}?transport=udp`)}if(b.includes("tcp")&&S.tcpPort){const g=!_||"fqdn"!==I&&C?C:S.fqdns[0];v.push(`turn:${g}:${S.tcpPort}?transport=tcp`)}return b.includes("tls")&&S.tlsPort&&_&&v.push(`turns:${S.fqdns[0]}:${S.tlsPort}`),g.concat({urls:v,credential:S.password,username:S.username})}),[]),createProbeIceServers=(g,f)=>g.reduce(((g,S)=>{const v=[],C=S.addresses&&S.addresses[0],_=S.fqdns&&S.fqdns.length>0,T=f.iceUdpAddressType,I=f.iceServerTransport;if(!C&&!_)return g;if(I.includes("udp")&&S.udpPort){const g=!_||"fqdn"!==T&&C?C:S.fqdns[0];v.push(`stun:${g}:${S.udpPort}`)}return I.includes("tls")&&S.tlsPort&&_&&v.push(`turns:${S.fqdns[0]}:${S.tlsPort}`),g.concat({urls:v,credential:S.password,username:S.username})}),[]),vT=class{constructor(g,f,S,v,C,_,T,I){this.session=g,this.context=f,this.diagnostics=S,this.sessionOperationQueue=v,this.callback=C,this.sessionCallbacks=_,this.configProvider=T,this.relayManager=I,this.wasConnected=!1,this.isDisconnected=!1,this.isReconnectConference=!1,this.escalationType=0,this._isSignalingStable=!0,this.reconnectDelayTime=0,this._isReconnectScheduled=!1,this.isDisposing=!1,this.isWaitingForNetwork=!1,this.onOnline=()=>{this.logger.safe.info("onOnline: Network is up"),this.diagnostics.registerState("networkOnline"),this.isOnlineDeferred?.resolve(),this.isOnlineDeferred=null},this.onOffline=()=>{this.logger.safe.info("onOffline: Network is down"),this.diagnostics.registerState("networkOffline"),this.isOnlineDeferred=new dt},this.logger=f.getLogger().createChild("ReconnectManagerV2"),this.ufdManager=f.getUfdManager(),this.session.callbacks=_,this.reconnectManagerMessageQueue=new fT(_),window.addEventListener("online",this.onOnline),window.addEventListener("offline",this.onOffline)}get isOnline(){return!this.isOnlineDeferred}async createRelayProber(){if(!this._relayProber){const g=Date.now(),f=createProbeIceServers(await this.relayManager.queryRelaysAsync({relayType:"turn"}),this.configProvider.config),S=Date.now()-g;this.logger.safe.info(`RelayProber configuration fetched in ${S} ms`),S>5e3&&this.diagnostics.registerState("relayConfigFetched"),this._relayProber=new ST(f,this.logger.createChild("RelayProber"))}return this._relayProber}dispose(){this.isDisposing=!0,window.removeEventListener("online",this.onOnline),window.removeEventListener("offline",this.onOffline),this._relayProber?.dispose(),this.isOnlineDeferred?.reject(new Error("dispose")),this.reconnectTimer&&this.resetReconnectTimer()}get settings(){return(this.reconnectSession||this.session).getSessionConfig().config}getCurrentSession(){return this.reconnectSession||this.session}getMainSession(){return this.session||this.reconnectSession}getReconnectSession(){return this.reconnectSession}async onIceDisconnect(g){if(this.wasConnected)this.raiseReconnectEvent("Bad",g);else if(!this.settings.reconnectWithNoRelays&&!this.session.hasRelayCandidates())return void this.onReconnectFailed("no relays",g);if(this.isDisconnected=!0,!this.isReconnecting()&&!this.isWaitingForNetwork)return this.logger.safe.info(`[${g}] reconnect attempt after iceDisconnect error`),this.session.transportStateProvider?.isFailed&&this.diagnostics.registerState("failed"),this.diagnostics.registerReconnect("attempted"),this.reconnectAsync(g)}onTransportDisconnect(g){this.isDisconnected=!0,this.wasConnected&&(this.diagnostics.registerState("disconnected"),this.handleTmpConnectivityLoss(g))}onConnected(g){this.isDisconnected=!1,this.logger.safe.info(`[${g}] set allow UFD`),this.diagnostics.registerState("connected"),this.raiseReconnectEvent("Good",g),this.wasConnected=!0,this._relayProber?.finalize()}onNegotiationCompletedAsync(g){return this.logger.safe.info(`[${g}] handle negotiation completed`),this.setSignalingState(!0),this.isReconnecting()&&(this.diagnostics.registerRetarget("completed"),2===this.escalationType&&this.blockCurrentSession(g)),Promise.resolve()}async onSessionErrorOccurred(g,f){this.logger.safe.info(`[${f}] handle session error`,stringifyObject(g)),await this.rejectReconnect(f),this.isReconnectAllowed()?await this.scheduleReconnectRetry(f,!1,!1):this.callback.onSessionErrorOccurred(g,f,this.wasConnected)}onNegotiationRejection(g,f){this.logger.safe.info(`[${f}] handle negotiation rejection`),this.diagnostics.registerRetarget("rejected");const S=1===this.escalationType;return this.rejectReconnect(f).then((()=>{const v=g.type===qt.RENEGOTIATION_ERROR.glare&&S;(g.type!==qt.RENEGOTIATION_ERROR.glare||S)&&(this.isRecoverableError(g.type)||v?this.scheduleReconnectRetry(f,v,S):this.onReconnectFailed(stringifyObject(g),f))}))}async ensureNetwork(g){const f=this.isOnline;if(!this.isOnline){this.logger.safe.info(`[${g}] waiting for network...`);try{await this.isOnlineDeferred.promise}catch(f){return void this.logger.safe.info(`${g} call disposed while waiting for network`)}this.logger.safe.info(`[${g}] network seems up`)}if(this.isDisconnected){const S=await this.createRelayProber(),v=await S.ensureOnline();this.logger.safe.info(`[${g}] probing complete in ${v} ms`),this.diagnostics.registerState("relaysUp"),f&&v<1e3&&this.logger.safe.info(`[${g}] looks like network failed on remote side, recovery was quick`)}}oldSessionIsOnline(g){return!!this.session?.transportStateProvider?.isConnected&&(this.logger.safe.info(`[${g}] old session recovered`),this.isReconnecting()||this.diagnostics.registerReconnect("connected"),!0)}async waitForNetworkAndTryLightweightRecovery(g){const f=this.oldSessionIsOnline(g);if(f||!this.settings.reconnectWithProbes)return f;this.setReconnectTimer(),this.isWaitingForNetwork=!0;const S=this.getMaxNetworkWaitTime();return this.logger.safe.info(`[${g}] can wait up to ${S} ms`),await Promise.race([this.ensureNetwork(g),delay(S)]),this.isWaitingForNetwork=!1,this.session&&(this.session.transportStateProvider?.isConnected||this.session.transportStateProvider?.isFailed||(this.logger.safe.info(`[${g}] giving session a moment to recover`),await delay(this.settings.reconnectWaitTimeAfterProbe)),this.oldSessionIsOnline(g))?(this.resetReconnectTimer(),!0):this.checkIfTimerFailed(g)?(this.logger.safe.info(`[${g}] session reconnect timer reached during network checks`),!0):!!this.isDisposing&&(this.logger.safe.info(`[${g}] session is disposed`),!0)}reconnectAsync(g,f=!1,S=!1,v){return this.logger.safe.info(`[${g}] queueing reconnect, force=${f}, escalation=${S}`),this.diagnostics.registerReconnectAttempt(S?"local escalation":"out"),this.context.getSmallCallTelemetry()?.setEventType("reconnect"),this._isReconnectScheduled=!0,S&&(this.escalationType=1,this.onReconnectCompleted=v),this.sessionOperationQueue.queueOperation((async()=>{if(this._isReconnectScheduled=!1,!f){if(await this.waitForNetworkAndTryLightweightRecovery(g))return void this.sessionOperationQueue.completeCurrentOperation()}if(this.isReconnecting())return this.logger.safe.info(`[${g}] ongoing reconnect is in progress`),void this.sessionOperationQueue.completeCurrentOperation();this.diagnostics.registerState("reconnect"),await this.initReconnect(g),await this.reconnectSession.configureModalitiesAsync(this.getConfiguredModalities(),g),this.sessionOperationQueue.completeCurrentOperation()}),g)}async acceptReconnectStartAsync(g,f){return this.logger.safe.info(`[${f}] accepting reconnect`),this.diagnostics.registerRetarget("incoming"),g?(this.escalationType=2,this.diagnostics.registerEscalation("attempted")):(!this.isReconnecting()&&this.isDisconnected?this.diagnostics.registerReconnect("attempted"):this.isReconnecting()&&await this.rejectReconnect(f),this.diagnostics.registerState("reconnect"),this.diagnostics.registerReconnectAttempt("in")),this.initReconnect(f)}acceptReconnectFinish(g){const f=this.getConfiguredModalities();return this.reconnectSession.configureModalitiesAsync(f,g).then((()=>f))}isReconnecting(){return!!this.reconnectSession}isReconnectScheduled(){return this._isReconnectScheduled}cleanUp(){this.sessionCallbacks=null,this.reconnectSession=null}async terminateAsync(g){try{await(this.session?.terminate(g,{}))}catch{}try{await this.terminateReconnectSessionAsync(g,!0)}catch{}this.cleanUp()}completeReconnect(g){return this.logger.safe.info(`[${g}] completing reconnect`),2===this.escalationType&&(this.unblockCurrentSession(g),this.diagnostics.registerEscalation("completed")),this.escalationType=0,this.reconnectSession&&(this.context.config.isConference=this.isReconnectConference,this.disposeActiveSession(g),this.session=this.reconnectSession,this.reconnectManagerMessageQueue.clear(),this.diagnostics.registerReconnectAttemptStatus("completed"),this._isSignalingStable||this.diagnostics.registerRetarget("completed"),this.isDisconnected&&this.diagnostics.registerReconnect("connected"),this.resetReconnectTimer(),this.reconnectDelayTime=0,this.reconnectSession=null,this.negotiationPausePromise=null,this.session.callbacks=this.sessionCallbacks||{}),Promise.resolve()}async rejectReconnect(g){this.logger.safe.info(`[${g}] rejecting reconnect`),this.setSignalingState(!1),2===this.escalationType&&this.diagnostics.registerEscalation("rejected"),this.escalationType=0,this.reconnectSession&&(await this.terminateReconnectSessionAsync(g,!1),this.diagnostics.registerReconnectAttemptStatus("rejected")),this.session&&(this.reconnectManagerMessageQueue.flush(),this.session.callbacks=this.sessionCallbacks,this.unblockCurrentSession(g))}configureModalitiesAsync(g,f,S){this.lastKnownConfiguredModalities=g;const v=[];return this.session&&v.push(this.session.configureModalitiesAsync(g,f,S)),this.reconnectSession&&v.push(this.reconnectSession.configureModalitiesAsync(g,f,S)),Promise.all(v).then((()=>Promise.resolve()))}canSendDtmf(){return this.getMainSession().canSendDtmf()}muteHold(g,f){this.getMainSession().muteHold(g,f)}muteInputAsync(g){return this.getMainSession().muteInputAsync(g)}unmuteInputAsync(g){return this.getMainSession().unmuteInputAsync(g)}muteOutputAsync(g){return this.getMainSession().muteOutputAsync(g)}unmuteOutputAsync(g){return this.getMainSession().unmuteOutputAsync(g)}async getSpeakerVolume(g){return this.getMainSession().getSpeakerVolume(g)}async setSpeakerVolume(g,f){return this.getMainSession().setSpeakerVolume(g,f)}_deviceSelectionChanged(){this.session&&this.session.deviceSelectionChanged(),this.reconnectSession&&this.reconnectSession.deviceSelectionChanged()}disposeActiveSession(g){if(this.session&&this.isReconnecting()){this.logger.safe.info(`[${g}] About to dispose current session...`);const f=this.session;return this.lastKnownConfiguredModalities=this.session.getConfiguredModalities(),f.callbacks=this.reconnectManagerMessageQueue.queueCallbacks,f.move(this.reconnectSession,g),this.session=null,f.terminate(g,{},!1)}return Promise.resolve()}registerRetargetOutgoing(){this.diagnostics.registerRetarget("outgoing")}isSignalingStable(){return this._isSignalingStable}getConfiguredModalities(){return this.getMainSession().getConfiguredModalities()||this.lastKnownConfiguredModalities}checkIfTimerFailed(g){return!(this.isReconnectAllowed()||this.session&&!this.session.transportStateProvider?.isFailed)&&(this.onReconnectFailed("the time limit was reached",g),!0)}async scheduleReconnectRetry(g,f,S){const v=this.getReconnectDelayTime();if(this.logger.safe.info(`[${g}] scheduling reconnect retry attempt in ${v}`),await delay(v),f||!this.checkIfTimerFailed(g))return this.reconnectAsync(g,S,S,this.onReconnectCompleted)}isRecoverableError(g){return qt.RENEGOTIATION_ERROR.media===g||qt.RENEGOTIATION_ERROR.signaling===g}async resetReconnectSession(g){this.logger.safe.info(`[${g}] Resetting reconnect session. Session exists: old: ${!!this.session}, new: ${!!this.reconnectSession}`),this.isReconnectConference=0!==this.escalationType||this.context.config.isConference;const f=0!==this.escalationType||this.context.config.isConference&&this.wasConnected&&!this.isDisconnected,S=this.getMainSession(),v=this.configProvider.getConfigView(this.isReconnectConference,S.getSessionConfig()),C=S.clone(f,v);C.callbacks={...this.sessionCallbacks,onTransportConnected:g=>{2!==this.escalationType&&this.completeReconnect(g),this.onReconnectCompleted?.(),this.raiseReconnectEvent("Good",g),this.sessionCallbacks.onTransportConnected(g)}},this.session&&(this.session.callbacks={...this.reconnectManagerMessageQueue.queueCallbacks,onSessionErrorOccurred:(g,f)=>(g.type!==qt.MEDIA_ERROR.iceConnectionError&&this.reconnectManagerMessageQueue.queueCallbacks.onSessionErrorOccurred(g,f),Promise.resolve())}),this.reconnectSession&&(this.reconnectSession.move(C,g),this.logger.safe.info(`[${g}] reconnect session still exists during reconnect clone operation`),await this.terminateReconnectSessionAsync(g,!1)),this.logger.safe.info(`[${g}] New session reset.`),this.reconnectSession=C}async initReconnect(g){this.logger.safe.info(`[${g}] initiate reconnect`),this.setReconnectTimer(),await this.resetReconnectSession(g),this.setSignalingState(!1),this.session&&(this.blockCurrentSession(g),await Promise.all([this.reconnectSession.muteInputAsync(g),this.reconnectSession.muteOutputAsync(g)]))}blockCurrentSession(g){this.logger.safe.debug(`[${g}] blocking current session negotiations`),this.negotiationPausePromise=this.session.pauseNegotiations(g)}unblockCurrentSession(g){this.negotiationPausePromise&&(this.logger.safe.debug(`[${g}] unblocking current session negotiations`),this.negotiationPausePromise.resolve(),this.negotiationPausePromise=null)}raiseReconnectEvent(g,f){this.ufdManager.signalEvent("NetworkReconnect",g,"Audio",!0,f)}async terminateReconnectSessionAsync(g,f){if(this.reconnectSession){const S=new fT(this.sessionCallbacks);this.reconnectSession.callbacks={...S.queueCallbacks,onTerminated:f?this.sessionCallbacks.onTerminated:S.queueCallbacks.onTerminated},await this.reconnectSession.terminate(g,{},!1),S.clear(),this.reconnectSession=null}}setReconnectTimer(){const g=this.wasConnected?this.settings.reconnectTimeLimit:this.settings.initialReconnectTimeLimit;g>0&&!this.reconnectTimer&&(this.reconnectTimerStart=Date.now(),this.reconnectTimer=window.setTimeout((()=>this.resetReconnectTimer()),g))}resetReconnectTimer(){clearTimeout(this.reconnectTimer),this.reconnectTimer=null}isReconnectAllowed(){return!!this.reconnectTimer&&!this.isDisposing}getReconnectDelayTime(){return 1e3*Math.min(++this.reconnectDelayTime,this.settings.maxReconnectDelayTime)}getMaxNetworkWaitTime(){const g=this.reconnectTimerStart>0?Date.now()-this.reconnectTimerStart:0;return Math.max(this.settings.reconnectTimeLimit-g,0)}onReconnectFailed(g,f){this.callback.onSessionErrorOccurred({type:qt.MEDIA_ERROR.iceConnectionError,detail:`Reconnect failed, error - ${stringifyObject(g)}`},f,this.wasConnected)}setSignalingState(g){this._isSignalingStable=g}async handleTmpConnectivityLoss(g){this.logger.safe.info(`[${g}] Session went into disconnected state, giving it ${this.settings.losingConnectivityTimeoutMs}ms to recover`),-1!==this.settings.losingConnectivityTimeoutMs&&(await delay(this.settings.losingConnectivityTimeoutMs),this.isDisconnected&&this.raiseReconnectEvent("Poor",g)),this.isDisconnected&&this.settings.reconnectOnDisconnect&&(this.logger.safe.info(`[${g}] Session is still down, triggering reconnect`),this.onIceDisconnect(g))}},CT=class{constructor(g,f){this.stats=g,this.diagnostics=f}set mediaLegId(g){this.stats.setMediaLegId(g.process()),this.diagnostics&&(this.diagnostics.mediaLegId=g)}set isMultiParty(g){g&&this.stats.setMultiParty(),this.diagnostics&&(this.diagnostics.isMultiParty=g)}set allowedModalities(g){this.stats.setSendModalities(g),this.diagnostics&&(this.diagnostics.allowedModalities=g)}set sessionError(g){this.stats.setError(g),this.diagnostics&&(this.diagnostics.sessionError=g)}set finalAnswerTime(g){this.stats.setFinalAnswerTimestamp(g),this.diagnostics&&(this.diagnostics.finalAnswerTime=g)}set dtmfResult(g){this.stats.dtmfResult(g),this.diagnostics&&(this.diagnostics.dtmfResult=g)}set swMute(g){this.stats.setSwMute(g),this.diagnostics&&(this.diagnostics.swMute=g)}set speakerMute(g){this.stats.setSpeakerMute(g),this.diagnostics&&(this.diagnostics.speakerMute=g)}set hwSilent(g){this.stats.setHwSilent(g),this.diagnostics&&(this.diagnostics.hwSilent=g)}set isSpeaking(g){this.stats.setSpeakingState(g),this.diagnostics&&(this.diagnostics.isSpeaking=g)}set iceConnectedStateTimestamp(g){this.stats.setIceConnectedStateTimestamp(g),this.diagnostics&&(this.diagnostics.iceConnectedStateTimestamp=g)}set iceInitTime(g){this.stats.setIceInitTimestamp(g),this.diagnostics&&(this.diagnostics.iceInitTime=g)}set ETag(g){this.stats.setETag(g),this.diagnostics&&(this.diagnostics.ETag=g)}set configIds(g){this.stats.setConfigIds(g),this.diagnostics&&(this.diagnostics.configIds=g)}set relay(g){this.stats.setRelay(g),this.diagnostics&&(this.diagnostics.relay=g)}negotiationStart(g){switch(this.diagnostics?.negotiationStart(g),g){case"Offering":this.stats.negotiation.offering.started();break;case"Answering":this.stats.negotiation.answering.started()}}negotiationCompleted(g){this.stats.negotiation.current.completed(g),this.diagnostics?.negotiationCompleted(g)}negotiationRejected(){this.stats.negotiation.current.rejected(),this.diagnostics?.negotiationRejected()}registerTransportConnected(){this.stats.registerTransportConnected(),this.diagnostics?.registerTransportConnected()}registerTransportDisconnected(){this.stats.registerTransportDisconnected(),this.diagnostics?.registerTransportDisconnected()}registerTransportFailed(){this.stats.registerTransportFailed(),this.diagnostics?.registerTransportFailed()}registerRollbackEvent(g){this.stats.registerRollbackEvent(g),this.diagnostics?.registerRollbackEvent(g)}registerRawMediaAccess(g,f,S){"send"===f?this.stats.registerSetInputRawMedia(S):this.stats.registerOutputRawMediaAccess(),this.diagnostics?.registerRawMediaAccess(g,f,S)}registerQualityStateChangedEvent(g){this.stats.registerQualityStateChangedEvent(g),this.diagnostics?.registerQualityStateChangedEvent(g)}terminated(g){this.stats.terminated(g),this.diagnostics?.terminated(g)}registerRemoteQualityStateChangedEvent(g,f){this.stats.registerRemoteQualityStateChangedEvent(g,f),this.diagnostics?.registerRemoteQualityStateChangedEvent(g,f)}},yT=class{constructor(g){this.logger=g,this.operationQueue=null,this.currentOperationDeferred=null,this.operationQueue=new zC(this.logger)}queueOperation(g,f=generateCauseId()){this.logger.safe.info(`[${f}] queueing operation`);const S=new dt,v=this.operationQueue.add((()=>(this.currentOperationDeferred=S,g())),f);return this.operationQueue.add(S,f),v}completeCurrentOperation(){this.currentOperationDeferred&&(this.logger.safe.info("completing operation"),this.currentOperationDeferred.resolve())}},ET=class extends Ht{constructor(g,f,S,v,C,_,T,I=S.getLogger().createChild("SessionV2",f)){super(I),this.context=S,this.callback=v,this.statistics=C,this.configProvider=_,this.diagnostics=T,this.logger=I,this.audioStreamStates={[qt.STREAMING_STATE.inactive]:[qt.STREAMING_STATE.started,qt.STREAMING_STATE.active,qt.STREAMING_STATE.failed],[qt.STREAMING_STATE.started]:[qt.STREAMING_STATE.active,qt.STREAMING_STATE.removed,qt.STREAMING_STATE.stopped,qt.STREAMING_STATE.failed],[qt.STREAMING_STATE.active]:[qt.STREAMING_STATE.removed,qt.STREAMING_STATE.stopped,qt.STREAMING_STATE.failed]},this.mediaLegId=new gT,this.rejectedNegotiations=0,this.negotiationState=null,this.audioStreamState=qt.STREAMING_STATE.inactive,this.deviceManagerDisposables=[],this.visibilityChangedHandler=()=>{if(this.logger.safe.debug(`document.visibilityState changed: ${document.visibilityState}`),"visible"===document.visibilityState&&this.pcClosedInfo){const g=this.pcClosedInfo;this.pcClosedInfo=null,Date.now()<g.timestamp+this.configProvider.config.reconnectWakeupTimeLimit?(this.logger.safe.info(`[${g.causeId}] start reconnect after wakeup`),this.startReconnect(g.causeId)):(this.logger.safe.info(`[${g.causeId}] terminate a call after wakeup because allowed time limit for reconnect exceeded`),this.endCallOnFailure(g.mediaError,g.causeId))}"hidden"===document.visibilityState&&this.context.getSmallCallTelemetry()?.setEventType("visibilityHidden")},this.ufdManager=S.getUfdManager(),this.ufdManagerDisposable=this.ufdManager.on("onQualityChanged",(g=>this.qualityChanged(g))),this.sessionOperationQueue=new yT(this.logger),this.mediaLegId=new gT,this.diagnosticsWrapper=new CT(this.statistics,this.diagnostics),this.statistics.setId(f),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.diagnosticsWrapper.ETag=this.configProvider.ETag,this.diagnosticsWrapper.configIds=this.configProvider.ecsConfigIds,this.diagnosticsWrapper.isMultiParty=!!S.config.isConference,this.recoverableErrors=this.configProvider.config.recoverableMediaErrors.split(","),this.forceReconnectErrors=this.configProvider.config.forceReconnectErrors.split(",");const b=this.getSessionCallbacks();g.callbacks=b,g.relayManagerProvider=this,this.reconnectManager=new vT(g,S,new mT(this.statistics,this.diagnostics?new uT(this.configProvider):void 0,this.diagnostics),this.sessionOperationQueue,this.getReconnectManagerCallbacks(),b,this.configProvider,this.getRelayManager()),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.deviceManagerDisposables.push(this.deviceManager.on("onDevicesPermissionChanged",(()=>this.diagnosticsWrapper.allowedModalities=this.getAllowedModalities()))),this.deviceManagerDisposables.push(this.deviceManager.on("onSelectedDevicesChanged",(()=>this.deviceSelectionChanged()))),this.deviceManagerDisposables.push(this.deviceManager.on("onDevicesChanged",((g,f)=>this.deviceListChanged(f)))),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount()),this.diagnostics&&(this.diagnostics.relayManager=this.getRelayManager()),this.ufdManager.applyCurrentState((g=>this.qualityChanged(g))),document.addEventListener("visibilitychange",this.visibilityChangedHandler),this.requestWakeLock()}async requestWakeLock(){if(oa.isWakeLockSupported()&&this.configProvider.config.useWakeLockApi)try{this.wakeLock=await window.navigator.wakeLock.request("screen")}catch(g){this.logger.safe.info(`Wakelock request failed - ${g.message}`)}}enableTeamsRealTimeTelemetry(){this.realtimeTelemetryInterval||(this.logger.safe.info("teams realtime telemetry is enabled"),this.getSessionCallbacks().onTeamsRealtimeTelemetryReport(),this.realtimeTelemetryInterval=window.setInterval((()=>{this.getSessionCallbacks().onTeamsRealtimeTelemetryReport()}),1e3*this.configProvider.config.diagnostics.teamsRealtimeTelemetry.pollingInterval))}getMediaStatsReport(){return this.diagnostics?.mediaStatsReport}createOfferAsync(g,f){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Offering");try{const S=await this.getCurrentSession().createOfferAsync(g,f);return this.updateSelectedDevices(),S.mediaLegId=this.mediaLegId.process(S.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.reconnectManager.isReconnecting()&&!this.reconnectManager.isSignalingStable()&&(this.reconnectManager.registerRetargetOutgoing(),S.newOffer=!0),S}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}),g)}registerRemoteQualityStateChangedEvent(g,f){this.diagnosticsWrapper.registerRemoteQualityStateChangedEvent(g,f)}setCallConstraints(g,f){return this.getCurrentSession().setCallConstraints(g,f)}processOfferAsync(g,f){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Answering"),g.mediaLegId=this.mediaLegId.process(g.mediaLegId);try{g.newOffer&&await this.reconnectManager.acceptReconnectStartAsync(g.escalationOccurring,f);const S=await this.getCurrentSession().processOfferAsync(g,f);if(g.newOffer){const g=await this.reconnectManager.acceptReconnectFinish(f);return S.sharing===qt.MEDIA_STATE.sendReceive&&(S.sharing=g.sharing===qt.MEDIA_STATE.send?qt.MEDIA_STATE.send:qt.MEDIA_STATE.receive),S}return S}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}),f)}async processAnswerAsync(g,f,S,v){try{return this.configProvider.config.muteDuringRemotePranswer&&(S&&!this.callMuteState&&(this.logger.safe.info(`[${f}] Muting input before processing full answer`),await this.muteInputAsync(f),this.lastMuteFromPranswer=!0),!S&&this.lastMuteFromPranswer&&(this.logger.safe.info(`[${f}] Unmuting input before processing full answer`),await this.unmuteInputAsync(f),this.lastMuteFromPranswer=!1)),await this.getCurrentSession().processAnswerAsync(g,f,S,v)}catch(g){throw this.lastMuteFromPranswer=!1,this.diagnosticsWrapper.sessionError=g,g}}async completeNegotiationAsync(g){this.rejectedNegotiations=0;try{const f=await this.getCurrentSession().completeNegotiationAsync(g);return this.negotiationState=f,this.diagnosticsWrapper.finalAnswerTime=Date.now(),this.diagnosticsWrapper.negotiationCompleted?.(f.activeModalities),await this.reconnectManager.onNegotiationCompletedAsync(g),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}ignoreNotReconnectError(g){return g.detail?.type!==qt.MEDIA_ERROR.incompatibleOriginator}async rejectNegotiationAsync(g,f){this.logger.safe.info(`[${f}] rejectNegotiationAsync`,g);try{if(this.reconnectManager.isReconnecting()&&this.ignoreNotReconnectError(g))return await this.reconnectManager.onNegotiationRejection(g,f),this.registerNegotiationRejection(this.negotiationState),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState;{const S=await this.getCurrentSession().rejectNegotiationAsync(g,f,this.isRenegotiationAllowed(g.type));return this.sessionOperationQueue.completeCurrentOperation(),this.registerNegotiationRejection(S),S}}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}completeEscalationAsync(g){return this.reconnectManager.completeReconnect(g)}rejectEscalationAsync(g){return this.reconnectManager.rejectReconnect(g)}async terminate(g,f){this.logger.safe.info(`terminate reject reason: ${JSON.stringify(f||"")}`),this.registerVideoEffectsTelemetryEvent(this.deviceManager.effectsManager.getStats("Video","StatsQuery")),this.registerAudioEffectsTelemetryEvent(this.deviceManager.effectsManager.getStats("Audio")),this.statistics.setPermissionStates(await this.deviceManager.getKnownPermissionStates()),this.diagnosticsWrapper.terminated(f);const always=()=>this.cleanUp();return this.reconnectManager.terminateAsync(g).then(always,always)}async getStatsAsync(g){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.getMainSession().getStatsAsync(g).then((g=>this.prepareStats(g)))}getLastKnownStats(g=!1){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.prepareStats(this.getMainSession().getLastKnownStats(g),g)}getCallTechnicalInfo(){return this.diagnostics?.realtimeTelemetryReport}async createAnswerAsync(g,f){try{const S=await this.getCurrentSession().createAnswerAsync(g,f);return this.updateSelectedDevices(),S.mediaLegId=this.mediaLegId.process(S.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,S}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}configureModalitiesAsync(g,f,S){return forOwn(g,((f,S)=>{f||delete g[S]})),this.reconnectManager.configureModalitiesAsync(g,f,S)}getAllowedModalities(){return this.deviceManager.getAllowedModalities()}createRemoteRenderer(g){return this.getMainSession().createRemoteRenderer(g)}async sendDtmf(g){try{const f=await this.getMainSession().sendDtmf(g);return this.diagnosticsWrapper.dtmfResult=!0,f}catch(g){throw this.diagnosticsWrapper.dtmfResult=!1,g}}canSendDtmf(){return this.reconnectManager.canSendDtmf()}muteHold(g,f){this.reconnectManager.muteHold(g,f)}muteInputAsync(g){return this.callMuteState=!0,this.diagnosticsWrapper.swMute=!0,this.lastMuteFromPranswer=!1,this.reconnectManager.muteInputAsync(g)}unmuteInputAsync(g){return this.callMuteState=!1,this.diagnosticsWrapper.swMute=!1,this.lastMuteFromPranswer=!1,this.reconnectManager.unmuteInputAsync(g)}muteOutputAsync(g){return this.diagnosticsWrapper.speakerMute=!0,this.reconnectManager.muteOutputAsync(g)}unmuteOutputAsync(g){return this.diagnosticsWrapper.speakerMute=!1,this.reconnectManager.unmuteOutputAsync(g)}async getSpeakerVolume(g){return this.reconnectManager.getSpeakerVolume(g)}async setSpeakerVolume(g,f){return this.reconnectManager.setSpeakerVolume(g,f)}getAcceptedTypes(){return this.reconnectManager.getCurrentSession().getAcceptedTypes()}useNullAudioStreamClient(){this.getCurrentSession().useNullAudioStreamClient()}createAudioElement(g){this.getCurrentSession().createAudioElement(g)}getIncomingRawAudioStream(g){return this.diagnosticsWrapper.registerRawMediaAccess("audio","recv",!0),this.getCurrentSession().getIncomingRawAudioStream(g)}getUnmixedAudioProvider(){return this.getCurrentSession().getUnmixedAudioProvider()}deviceSelectionChanged(){this.updateSelectedDevices(),this.reconnectManager._deviceSelectionChanged()}registerDeviceTelemetryEvent(g){this.getCurrentSession().onDeviceEvent(g),this.statistics.registerDeviceTelemetryEvent(g)}registerVideoEffectsTelemetryEvent(g){this.statistics.registerVideoEffectsTelemetryEvent(g)}registerAudioEffectsTelemetryEvent(g){this.statistics.registerAudioEffectsTelemetryEvent(g)}reconnectAsync(g,f=!1,S){return this.reconnectManager.reconnectAsync(g,!0,f,S)}isReconnecting(){return this.reconnectManager.isReconnecting()}getRelayManager(){return this.relayManager??(this.relayManager=new pT(this.context.maContext.getRelayManager(),this.diagnosticsWrapper))}getSessionConfig(){return this.reconnectManager.getCurrentSession().getSessionConfig()}getDiagnostics(){return this.diagnostics}getLocalMediaTrackId(g){return this.reconnectManager.getMainSession().getLocalMediaTrackId(g)}getSubscriptionManager(){return this.getCurrentSession().getSubscriptionManager()}getDisabledModalities(){return this.getCurrentSession().getDisabledModalities()}configureSpatialAudio(g,f){this.getCurrentSession().configureSpatialAudio(g,f)}setParticipantSpatialAudioPositions(g,f){this.getCurrentSession().setParticipantSpatialAudioPositions(g,f)}startMediaDescriptionsUpdateAsync(g,f){return this.getCurrentSession().startMediaDescriptionsUpdateAsync(g,f)}completeMediaDescriptionsUpdateAsync(g){return this.getCurrentSession().completeMediaDescriptionsUpdateAsync(g)}rejectMediaDescriptionsUpdateAsync(g,f){return this.getCurrentSession().rejectMediaDescriptionsUpdateAsync(g,f)}processNotification(g,f){this.getCurrentSession().processNotification(g,f)}getMediaControlPlaneInstance(){return this.getCurrentSession().getMediaControlPlaneInstance()}async cleanUp(){this.callback=null,this.deviceManagerDisposables.forEach((g=>g.dispose())),this.ufdManagerDisposable.dispose(),this.reconnectManager.dispose(),this.pcClosedInfo=null,document.removeEventListener("visibilitychange",this.visibilityChangedHandler),window.clearInterval(this.realtimeTelemetryInterval),this.wakeLock&&(await this.wakeLock.release(),this.wakeLock=null)}updateSelectedDevices(){const g=this.deviceManager.getSelectedDevices(),getDeviceName=g=>g?this.deviceManager.getDeviceNameAsync(g).then((g=>scrubDeviceLabelPii(g,this.configProvider.config.devices.piiSafeWords))):Promise.resolve("none");Promise.all([getDeviceName(g.microphone),getDeviceName(g.speaker),getDeviceName(g.camera)]).then((([g,f,S])=>{this.statistics.setUsedDevices({microphone:g,speaker:f,camera:S})}))}getCurrentSession(){return this.reconnectManager.getCurrentSession()}getMainSession(){return this.reconnectManager.getMainSession()}setAudioStreamState(g,f,S){this.isAudioStateValid(g)?this.raiseAudioStateChanged(g,f,S):this.logger.safe.error(`[${f}] audio state transition is invalid: ${this.audioStreamState} -> ${g}`)}isAudioStateValid(g){return this.audioStreamStates[this.audioStreamState].indexOf(g)>=-1}raiseAudioStateChanged(g,f,S){if(this.logger.safe.info(`[${f}] audio state changed to ${g}`),this.callback.onAudioStateChanged){const f={content:"audio",direction:"receive",stream:g};this.callback.onAudioStateChanged(f,S)}}getReconnectManagerCallbacks(){return{onSessionErrorOccurred:(g,f,S)=>{this.isNetworkMediaError(g)&&!S&&this.ufdManager.raisePendingWhitelistingUFD(),this.endCallOnFailure(g,f)}}}isNetworkMediaError(g){return g.type===qt.MEDIA_ERROR.iceConnectionError||g.type===qt.MEDIA_ERROR.noNetworkError}isRecoverableMediaError(g){return this.recoverableErrors.includes(g.type)}startReconnect(g=generateCauseId()){return this.reconnectManager.onIceDisconnect(g)}shouldForceReconnect(g){return this.forceReconnectErrors.includes(g.type)}isUnexpectedPcClose(g){return g.type===qt.MEDIA_ERROR.unexpectedClose}getSessionCallbacks(){return this.sessionCallbacks||(this.sessionCallbacks={onTerminated:()=>{this.logger.safe.warn("call onTerminated"),this.event("onTerminated").raise(this)},onSessionErrorOccurred:(g,f=generateCauseId())=>this.isUnexpectedPcClose(g)?this.handlePcClosed(g,f):this.shouldForceReconnect(g)?this.reconnectManager.reconnectAsync(f,!0):this.isRecoverableMediaError(g)?this.reconnectManager.isReconnecting()?this.reconnectManager.onSessionErrorOccurred(g,f):this.startReconnect(f):(this.endCallOnFailure(g,f),Promise.resolve()),onNegotiationRequired:(g,f)=>this.callback.onNegotiationRequired(g,f),onAudioHwSilentChanged:g=>{this.diagnosticsWrapper.hwSilent=g},onAudioStateChanged:(g,f)=>{this.setAudioStreamState(g,f)},onTransportConnected:(g=generateCauseId())=>{this.logger.safe.info(`[${g}] Transport connectivity established`),this.ufdManager.cancelPendingWhitelistingUFD(),this.reconnectManager.onConnected(g),this.diagnosticsWrapper.registerTransportConnected(),this.diagnosticsWrapper.iceConnectedStateTimestamp=Date.now(),this.callback?.onTransportConnected(g)},onTransportDisconnected:(g=generateCauseId())=>{this.logger.safe.warn(`[${g}] Transport connectivity lost`),this.reconnectManager.onTransportDisconnect(g),this.diagnosticsWrapper.registerTransportDisconnected(),this.callback?.onTransportDisconnected?.(g)},onTransportFailed:()=>{this.diagnosticsWrapper.registerTransportFailed(),this.callback?.onTransportFailed?.()},onTransportInitialized:()=>{this.diagnosticsWrapper.iceInitTime=Date.now()},onUpdateMediaDescriptionsRequired:(g,f)=>this.callback.onUpdateMediaDescriptionsRequired(g,f),onTeamsRealtimeTelemetryReport:()=>this.callback.onRealtimeTelemetryReport()}),this.sessionCallbacks}registerNegotiationRejection(g){this.rejectedNegotiations++,this.diagnosticsWrapper.negotiationRejected?.(),g.rollback&&this.diagnosticsWrapper.registerRollbackEvent(g.rollback)}isRenegotiationAllowed(g){return this.rejectedNegotiations<this.context.configProvider.config.renegotiationAttempts&&!this.reconnectManager.isReconnectScheduled&&(qt.RENEGOTIATION_ERROR.signaling===g||qt.RENEGOTIATION_ERROR.media===g)}prepareStats(g,f=!1){this.statistics.setDeviceList(this.deviceManager.getDeviceDescriptions(),this.deviceManager.getDeviceListDebugInfo()),this.statistics.setRelayManagerTimers(this.getRelayManager().getStats()),this.statistics.setVideoEffectStats(this.context.callDeviceManager.getDeviceManager("Video").effectsManager.getStats("Video","StatsQuery")),this.statistics.setAudioEffectStats(this.deviceManager.effectsManager.getStats("Audio"));const S=this.statistics.generateStatistics(g,this.mediaLegId,f);return this.configProvider.config.diagnostics.features.useNewerStatisticsMetrics&&(S.data.metrics=this.diagnostics?.telemetryReport?.data.metrics),!g.data.Extensions?.StartTime&&this.configProvider.config.diagnostics.features.useFallbackToNewExtensions&&(S.data.Extensions=this.diagnostics?.telemetryReport?.data.Extensions),S}deviceListChanged(g){g&&this.statistics.deviceChangedByPoll(),this.statistics.devicesChanged(),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount())}qualityChanged(g){const f=g.deviceManagerId;!f||this.context.callDeviceManager.hasDevice(f)?(this.context.getSmallCallTelemetry()?.setEventType(g.type),this.callback?.onQualityChanged&&(this.diagnosticsWrapper.registerQualityStateChangedEvent(g),"DeviceSpeakWhileMuted"===g.type&&(this.diagnosticsWrapper.isSpeaking="Good"!==g.value),this.callback.onQualityChanged(g))):this.logger.info(`${f} - is not added to Call, skipping UFD.`)}endCallOnFailure(g,f,S){this.callback&&(this.callback.onSessionErrorOccurred&&this.callback.onSessionErrorOccurred(g,f),this.diagnosticsWrapper.sessionError=g,this.setAudioStreamState(qt.STREAMING_STATE.failed,f,S))}async handlePcClosed(g,f){const S=this.configProvider.config.reconnectWakeupTimeLimit;return this.logger.safe.info(`[${f}] handle unexpected PC closed event`,`visibilityState=${document.visibilityState}, wakeupLimit=${this.configProvider.config.reconnectWakeupTimeLimit}`),"visible"===document.visibilityState?this.startReconnect(f):S?void(this.pcClosedInfo={timestamp:Date.now(),causeId:f,mediaError:g}):this.endCallOnFailure(g,f,"suspended")}},_T=class{constructor(g){this.creationTime=g,this.records=[],this.activeRecord=null,this.activeAttempt=null,this.reconnectState=!1}getReport(){return this.records.length?JSON.stringify(this.records):""}isReconnecting(){return this.reconnectState}onReconnectStart(){this.reconnectState=!0,this.activeRecord||(this.activeRecord={attempts:[],endTime:null,startTime:Date.now()-this.creationTime},this.records.push(this.activeRecord))}onReconnectAttempt(g){if(!this.activeRecord)return null;this.activeAttempt={direction:g,status:!1,endTime:null,startTime:this.getTimestamp()},this.reconnectState=!0,this.activeRecord.attempts.push(this.activeAttempt)}onReconnectConnected(){if(!this.activeRecord)return null;this.reconnectState=!1,this.activeRecord.endTime=this.getTimestamp(),this.activeRecord=this.activeAttempt=null}onReconnectCompleted(){this.reconnectState=!1,this.resolveReconnectAttempt(!0)}onReconnectRejected(){this.resolveReconnectAttempt(!1)}resolveReconnectAttempt(g){this.activeAttempt&&this.activeRecord&&(this.activeAttempt.status=g,this.activeAttempt.endTime=this.getTimestamp())}getTimestamp(){return Date.now()-this.creationTime-this.activeRecord.startTime}},TT=window.navigator,IT=class{constructor(g="Good"){this.stopWatches=[],this.currentLevel=g,this.getStopWatch(g).start()}updateLevel(g){this.currentLevel!==g&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=g,this.getStopWatch(this.currentLevel).start())}getCount(g){const f=this.stopWatches[g];return f?f.count:0}getElapsed(g){const f=this.stopWatches[g];return f?f.elapsed:0}getStopWatch(g){let f=this.stopWatches[g];return f||(f=new eT,this.stopWatches[g]=f),f}},bT=RegExp(/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\:[0-9]{2,5})?$/),AT=RegExp(/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(:[0-9]{2,5})?$/),PT=class{constructor(g,f,S){this.configProvider=g,this.callNumber=f,this.sessionDiagnostics=S,this.negotiation={offering:this.offering(),answering:this.answering(),current:this.current()},this.creationTime=Date.now(),this.negotiationCount=0,this.initialNegotiationCompleted=!1,this.activeModalities={},this.multiParty=!1,this.noIceCandidatesGoodEventCount=0,this.noIceCandidatesBadEventCount=0,this.noRelayIceCandidatesGoodEventCount=0,this.noRelayIceCandidatesBadEventCount=0,this.cameraInUseBadEventCount=0,this.cameraInUseGoodEventCount=0,this.microphoneInUseBadEventCount=0,this.microphoneInUseGoodEventCount=0,this.cameraFreezeStartEventCount=0,this.cameraFreezeEndEventCount=0,this.networkRecv=new IT,this.networkSend=new IT,this.retargetIncomingCount=0,this.retargetOutgoingCount=0,this.retargetCompletedCount=0,this.retargetRejectedCount=0,this.reconnectAttemptedCount=0,this.reconnectConnectedCount=0,this.escalationAttemptedCount=0,this.escalationCompletedCount=0,this.escalationRejectedCount=0,this.durationTimer=new eT,this.terminationReason={},this.terminationTime=0,this.sessionId="0",this.rejectedNegotiationCount=0,this.mediaError={type:"none",detail:"none"},this.incompatibleOffer=!1,this.dtmfSuccess=0,this.dtmfFailure=0,this.relay=null,this.relayManagerTimers=null,this.allowedAudioSend=!0,this.allowedVideoSend=!0,this.allowedScreensharingSend=!0,this.iceInitTime=0,this.finalAnswerTime=0,this.iceConnectedStateTime=0,this.usedDevices=null,this.deviceSelectionChangeCount=0,this.devicesChangeCount=0,this.devicesPollChangeCount=0,this.mute=new eT,this.osMute=new eT,this.hwSilent=new eT,this.isSpeaking=new eT,this.swMute=new eT,this.speakerMute=new eT,this.deviceTelemetryEvents=[],this.videoEffectsTelemetryEvents=new Uv(this.configProvider.config.effectsTelemetryBufferSize),this.audioEffectsTelemetryEvents=new Uv(this.configProvider.config.effectsTelemetryBufferSize),this.devicesCount=null,this.reconnectStats=new _T(this.creationTime),this.transportDisconnected=!1,this.transportReconnectedCount=0,this.ufds=[],this.remoteUfds=[],this.mediaQosEnabled=!1,this.portRangeConfigured=!1,this.rollbackNegotiation=[],this.rawOutputAudioAccess={attempt:0,timer:new eT},this.rawInputAudioOverride={attempt:0,timer:new eT},this.connectionEffectiveTypeSeries=new Uv(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionRttSeries=new Uv(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionDownlinkSeries=new Uv(this.configProvider.config.navConnectionNumSamplesToCollect),this.navigatorConnectionInterval=setInterval((()=>{const g=TT?.connection;g&&("number"==typeof g.downlink&&this.connectionDownlinkSeries.add(g.downlink),"number"==typeof g.rtt&&this.connectionRttSeries.add(g.rtt),"number"==typeof g.effectiveType&&this.connectionEffectiveTypeSeries.add(g.effectiveType))}),this.configProvider.config.navConnectionPollingInterval),this.durationTimer.start()}terminated(g){this.terminationReason=deepClone(g),this.terminationTime=Date.now(),this.durationTimer.stop(),this.osMute.stop(),this.swMute.stop(),this.hwSilent.stop(),this.isSpeaking.stop(),this.mute.stop(),this.speakerMute.stop(),this.rawInputAudioOverride.timer.stop(),this.rawOutputAudioAccess.timer.stop(),clearInterval(this.navigatorConnectionInterval)}setMultiParty(){this.multiParty=!0}updateCommonMute(){this.swMute.isRunning||this.osMute.isRunning?this.mute.start():this.mute.stop()}setDeviceList(g,f){this.deviceList=g.map((g=>({label:scrubDeviceLabelPii(g.label,this.configProvider.config.devices.piiSafeWords),kind:g.kind}))),f&&(this.deviceDebugStrings=deepClone(f))}setPermissionStates(g){this.permissionStates=g}setSwMute(g){g?this.swMute.start():this.swMute.stop(),this.updateCommonMute()}setSpeakerMute(g){g?this.speakerMute.start():this.speakerMute.stop()}setHwSilent(g){g?this.hwSilent.start():this.hwSilent.stop()}setSpeakingState(g){g?this.isSpeaking.start():this.isSpeaking.stop()}setETag(g){this.ETag=g}setConfigIds(g){this.configIds=g}setVideoEffectStats(g){g&&this.videoEffectsTelemetryEvents.add(g)}setAudioEffectStats(g){g&&this.audioEffectsTelemetryEvents.add(g)}registerQualityStateChangedEvent(g){switch(g.type){case"NoNetwork":"Good"===g.value?this.noIceCandidatesGoodEventCount++:this.noIceCandidatesBadEventCount++;break;case"NetworkRelaysNotReachable":"Good"===g.value?this.noRelayIceCandidatesGoodEventCount++:this.noRelayIceCandidatesBadEventCount++;break;case"DeviceCaptureNotFunctioning":"Good"===g.value?this.microphoneInUseGoodEventCount++:this.microphoneInUseBadEventCount++;break;case"VideoCapturerDeviceStartFailed":"Good"===g.value?this.cameraInUseGoodEventCount++:this.cameraInUseBadEventCount++;break;case"DeviceCaptureMute":"Audio"===g.mediaType&&("Bad"===g.value?this.osMute.start():this.osMute.stop(),this.updateCommonMute());break;case"NetworkRecvQuality":this.networkRecv.updateLevel(g.value);break;case"NetworkSendQuality":this.networkSend.updateLevel(g.value);break;case"VideoCaptureDeviceFreeze":"Good"===g.value?this.cameraFreezeEndEventCount++:this.cameraFreezeStartEventCount++}"DeviceSpeakWhileMuted"!==g.type&&this.ufds.push({...g,timestamp:Date.now()-this.creationTime}),this.ufds.length>this.configProvider.config.maxStoredUFDCount&&this.ufds.shift()}registerRemoteQualityStateChangedEvent(g,f){arrayLimitedPush2(this.remoteUfds,{...g,participantId:f,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numUFDs)}registerRetargetIncoming(){this.retargetIncomingCount++}registerRetargetOutgoing(){this.retargetOutgoingCount++}registerRetargetCompleted(){this.retargetCompletedCount++}registerRetargetRejected(){this.retargetRejectedCount++}registerEscalationStart(){this.escalationAttemptedCount++}registerEscalationCompleted(){this.escalationCompletedCount++}registerEscalationRejected(){this.escalationRejectedCount++}registerRollbackEvent(g){g&&this.rollbackNegotiation.push({type:g.type,attempt:this.rollbackNegotiation.length+1,error:g.error?g.error:""})}registerReconnectAttempted(){this.reconnectAttemptedCount++,this.reconnectStats.onReconnectStart()}registerReconnectConnected(){this.reconnectConnectedCount++,this.reconnectStats.onReconnectConnected()}registerDeviceTelemetryEvent(g){g.timestamp=g.timestamp-this.creationTime,this.deviceTelemetryEvents.push(g)}registerVideoEffectsTelemetryEvent(g){g&&(g.timestamp=g.timestamp-this.creationTime,this.videoEffectsTelemetryEvents.add(g))}registerAudioEffectsTelemetryEvent(g){if(g){g.timestamp=g.timestamp-this.creationTime;const f=this.audioEffectsTelemetryEvents.items.pop();f&&this.audioEffectsChanged(f,g)&&this.audioEffectsTelemetryEvents.add(f),this.audioEffectsTelemetryEvents.add(g)}}audioEffectsChanged(g,f){return g.payload.fallback!==f.payload.fallback||(void 0!==f.payload.userNoiseSuppressionMethod&&g.payload.userNoiseSuppressionMethod!==f.payload.userNoiseSuppressionMethod||void 0!==f.payload.userAudioEffect&&g.payload.userAudioEffect!==f.payload.userAudioEffect)}registerReconnectAttempt(g){this.reconnectStats.onReconnectAttempt(g)}registerReconnectAttemptCompleted(){this.reconnectStats.onReconnectCompleted()}registerReconnectAttemptRejected(){this.reconnectStats.onReconnectRejected()}setMediaLegId(g){this.mediaLegId=g}setId(g){this.sessionId=g}setError(g){g.type===qt.MEDIA_ERROR.incompatibleOffer&&(this.incompatibleOffer=!0),this.mediaError.type=g.type||qt.MEDIA_ERROR.internalError,this.mediaError.detail=g.detail||g.toString()}setRelay(g){this.relay={address:g.addresses.join(),expires:g.expires,realm:g.realm,credentials:!(!g.username||!g.password),ports:[g.udpPort?`udp:${g.udpPort}`:"",g.tcpPort?`tcp:${g.tcpPort}`:"",g.tlsPort?`tls:${g.tlsPort}`:""].join(","),fqdns:g.fqdns?g.fqdns.join():"none"}}setRelayManagerTimers(g){this.relayManagerTimers=g}setSendModalities(g){this.allowedAudioSend=g.audio.some((g=>hasSendDirectionality(g))),this.allowedVideoSend=g.video.some((g=>hasSendDirectionality(g))),this.allowedScreensharingSend=g.sharing.some((g=>hasSendDirectionality(g)))}setIceInitTimestamp(g){this.iceInitTime||(this.iceInitTime=g)}setFinalAnswerTimestamp(g){this.finalAnswerTime||(this.finalAnswerTime=g)}setIceConnectedStateTimestamp(g){this.iceConnectedStateTime||(this.iceConnectedStateTime=g)}dtmfResult(g){g?++this.dtmfSuccess:++this.dtmfFailure}setUsedDevices(g){this.usedDevices&&JSON.stringify(g)!==JSON.stringify(this.usedDevices)&&this.deviceSelectionChangeCount++,this.usedDevices=g}setDevicesCount(g){this.devicesCount=g}setMediaQosEnabled(g){this.mediaQosEnabled=g}setPortRangeConfigured(g){this.portRangeConfigured=g}devicesChanged(){this.devicesChangeCount++}deviceChangedByPoll(){this.devicesPollChangeCount++}registerOutputRawMediaAccess(){this.rawOutputAudioAccess.attempt++,this.rawOutputAudioAccess.timer.start()}registerSetInputRawMedia(g){this.rawInputAudioOverride.attempt++,g?this.rawInputAudioOverride.timer.start():this.rawInputAudioOverride.timer.stop()}getReport(){const g=this.usedDevices||{microphone:"none",speaker:"none",camera:"none"};return{RawOutputAudioAccessDurationRatio:this.getDurationRatio(this.rawOutputAudioAccess.timer.elapsed),RawOutputAudioAccessAttempted:this.rawOutputAudioAccess.attempt,RawInputAudioOverrideDurationRatio:this.getDurationRatio(this.rawInputAudioOverride.timer.elapsed),RawInputAudioOverrideAttempted:this.rawInputAudioOverride.attempt,SessionId:this.sessionId,CallNumber:this.callNumber,NoIceCandidatesBadEventCount:this.noIceCandidatesBadEventCount,NoIceCandidatesGoodEventCount:this.noIceCandidatesGoodEventCount,NoRelayIceCandidatesBadEventCount:this.noRelayIceCandidatesBadEventCount,NoRelayIceCandidatesGoodEventCount:this.noRelayIceCandidatesGoodEventCount,CameraInUseBadEventCount:this.cameraInUseBadEventCount,CameraInUseGoodEventCount:this.cameraInUseGoodEventCount,MicrophoneInUseBadEventCount:this.microphoneInUseBadEventCount,MicrophoneInUseGoodEventCount:this.microphoneInUseGoodEventCount,CameraFreezeStartEventCount:this.cameraFreezeStartEventCount,CameraFreezeEndEventCount:this.cameraFreezeEndEventCount,RetargetIncomingCount:this.retargetIncomingCount,RetargetOutgoingCount:this.retargetOutgoingCount,RetargetCompletedCount:this.retargetCompletedCount,RetargetRejectedCount:this.retargetRejectedCount,ReconnectAttemptedCount:this.reconnectAttemptedCount,ReconnectConnectedCount:this.reconnectConnectedCount,EscalationAttemptedCount:this.escalationAttemptedCount,EscalationCompletedCount:this.escalationCompletedCount,EscalationRejectedCount:this.escalationRejectedCount,CreationTime:this.getHpTimeFromMillis(this.creationTime),InitTime:this.getHpTimeFromMillis(this.creationTime),TerminationTime:this.getHpTimeFromMillis(this.terminationTime),CallDuration:this.getHpTimeFromMillis(this.getCurrentDuration()),InitialNegotiationType:this.initialNegotiationType||"none",InitialNegotiationCompleted:this.initialNegotiationCompleted,ActiveModalities:JSON.stringify(this.activeModalities),NegotiationCount:this.negotiationCount,RejectedNegotiationCount:this.rejectedNegotiationCount,MediaLegId:this.mediaLegId,MultiParty:this.multiParty,ErrorType:this.mediaError.type,ErrorDetail:this.mediaError.detail,TerminationReason:this.terminationReason,IncompatibleOffer:this.incompatibleOffer,DtmfSuccess:this.dtmfSuccess,DtmfFailure:this.dtmfFailure,Relay:this.relay?JSON.stringify(this.relay):"none",RelayManager:this.relayManagerTimers?JSON.stringify(this.relayManagerTimers):"none",AllowedAudioSend:this.allowedAudioSend,AllowedVideoSend:this.allowedVideoSend,AllowedScreensharingSend:this.allowedScreensharingSend,IceInitTime:this.getHpTimeFromMillis(this.iceInitTime),FinalAnswerTime:this.getHpTimeFromMillis(this.finalAnswerTime),IceConnectedStateTime:this.getHpTimeFromMillis(this.iceConnectedStateTime),UsedMicrophone:g.microphone,UsedSpeaker:g.speaker,UsedCamera:g.camera,DeviceSelectionChangeCount:this.deviceSelectionChangeCount,DevicesChangeCount:this.devicesChangeCount,DevicesPollChangeCount:this.devicesPollChangeCount,DevicesCount:this.devicesCount?JSON.stringify(this.devicesCount):"none",ETag:this.ETag||"",ConfigIds:this.configIds?Array.isArray(this.configIds)?this.configIds.join(","):this.configIds:"",CallMutedRatio:this.getDurationRatio(this.mute.elapsed),CallOsMuted:this.getHpTimeFromMillis(this.osMute.elapsed),CallHwSilent:this.getHpTimeFromMillis(this.hwSilent.elapsed),CallSwMuted:this.getHpTimeFromMillis(this.swMute.elapsed),CallSpeakerMuted:this.getHpTimeFromMillis(this.speakerMute.elapsed),CallIsSpeaking:this.getHpTimeFromMillis(this.isSpeaking.elapsed),NetworkRecvGood:this.networkRecv.getCount("Good")-1,NetworkRecvPoor:this.networkRecv.getCount("Poor"),NetworkRecvBad:this.networkRecv.getCount("Bad"),NetworkSendGood:this.networkSend.getCount("Good")-1,NetworkSendPoor:this.networkSend.getCount("Poor"),NetworkSendBad:this.networkSend.getCount("Bad"),NetworkRecvGoodRatio:this.getDurationRatio(this.networkRecv.getElapsed("Good")),NetworkRecvPoorRatio:this.getDurationRatio(this.networkRecv.getElapsed("Poor")),NetworkRecvBadRatio:this.getDurationRatio(this.networkRecv.getElapsed("Bad")),NetworkSendGoodRatio:this.getDurationRatio(this.networkSend.getElapsed("Good")),NetworkSendPoorRatio:this.getDurationRatio(this.networkSend.getElapsed("Poor")),NetworkSendBadRatio:this.getDurationRatio(this.networkSend.getElapsed("Bad")),DeviceEvents:JSON.stringify(this.deviceTelemetryEvents),DeviceList:JSON.stringify(this.deviceList),DeviceListDebug:JSON.stringify(this.deviceDebugStrings),VideoEffects:JSON.stringify(this.videoEffectsTelemetryEvents.items),AudioEffects:JSON.stringify(this.audioEffectsTelemetryEvents.items),PermissionStates:JSON.stringify(this.permissionStates),ReconnectAttempts:this.reconnectStats.getReport(),NetworkEvents:JSON.stringify(rebaseTime(limitArraySize2(this.sessionDiagnostics?.getObjectRef().reconnect?.tmpRecords,this.configProvider.config.diagnostics.telemetryLimits.numNetworkEvents),"startTime",this.creationTime)),ReconnectInProgress:this.reconnectStats.isReconnecting(),TransportReconnectedCount:this.transportReconnectedCount,UFDs:JSON.stringify(this.ufds),remoteUFDs:JSON.stringify(this.remoteUfds),MediaQosEnabled:this.mediaQosEnabled,PortRangeConfigured:this.portRangeConfigured,RollbackNegotiation:JSON.stringify(this.rollbackNegotiation),hardwareConcurrency:oa.hardwareConcurrency,GPUName:oa.unmaskedGlRenderer,Connection_Downlink:sampleseries(this.connectionDownlinkSeries.items,(g=>g)),Connection_EffectiveType:this.connectionEffectiveTypeSeries.items.filter((g=>g)).join(","),Connection_Rtt:sampleseries(this.connectionRttSeries.items,(g=>g)),Connection_SaveData:TT?.connection?.saveData,MediaByPassEnabled:!!this.configProvider.mediaConfig.mediaBypassEnabled,CallConstraints:JSON.stringify(this.configProvider.getCallConstraintsTelemetry()),DominantSpeaker:JSON.stringify(generateDominantSpeakerReport(this.sessionDiagnostics?.getObjectRef().dominantSpeaker,this.terminationTime))}}generateStatistics(g,f,S=!1){if(this.setMediaLegId(f.process()),"WebRtcMediaStats"!==g.type)throw new Error(`Unknown stats type - ${g.type}`);if(S){const g=this.deviceTelemetryEvents.length;this.deviceTelemetryEvents.splice(0,g-1),this.deviceDebugStrings=uy,this.audioEffectsTelemetryEvents.clear()}g.data.metrics=this.getReport();const v=this.sessionDiagnostics?.getObjectRef().statsErrors;if(v?.length)if(g.data.Extensions?.WebRTCStats?.statsErrors){const f=JSON.parse(g.data.Extensions.WebRTCStats.statsErrors);f.push(...v),g.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(f)}else g.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(v);const C={};return forOwnRec(g.data,((g,f,S)=>{let v=0;bT.test(g)?(v=13,C[f]="IPv4"):AT.test(g)&&(v=4,C[f]="IPv6"),S[f]={type:v,value:g,__VALUE__:!0}})),g.data.metrics.piiFields={type:0,value:JSON.stringify(C),__VALUE__:!0},g}registerTransportConnected(){this.transportDisconnected&&(this.transportDisconnected=!1,this.transportReconnectedCount++)}registerTransportDisconnected(){this.transportDisconnected=!0}registerTransportFailed(){this.transportDisconnected=!1}resetError(){this.setError({type:"none",detail:"none"})}offering(){return{started:()=>{this.currentNegotiationType="Offering",this.negotiationStarted()}}}answering(){return{started:()=>{this.currentNegotiationType="Answering",this.negotiationStarted()}}}negotiationStarted(){this.initialNegotiationType=this.initialNegotiationType||this.currentNegotiationType,++this.negotiationCount}current(){return{completed:g=>{this.initialNegotiationCompleted=!0,this.activeModalities=g,this.resetError()},rejected:()=>{++this.rejectedNegotiationCount}}}getDurationRatio(g){const f=this.getCurrentDuration();return g/(0!==f?f:1)}getCurrentDuration(){return this.durationTimer.elapsed}getHpTimeFromMillis(g){return 1e4*g}},RT=class{constructor(g,f,S,v){this.onActiveSpeakersChanged=g,this.onDominantSpeakersChanged=f,this.logger=S,this.diagnostics=v}setStrategy(g){this.disposeStrategy(),this.dshStrategy=g,this.dshStrategy?.setOnDominantSpeakerChanged(this.onDominantSpeakerHistoryChanged.bind(this)),this.diagnostics?.setCurrentActiveStrategy("client")}onContributingSourcesChanged(g){this.onActiveSpeakersChanged(g),this.diagnostics?.contributingSourcesChanged(),this.dshStrategy?.setSources(g)}onDominantSpeakerHistoryChanged(g,f){this.onDominantSpeakersChanged(g),this.diagnostics?.recordHistoryEvent(g,f),"client"!==f&&this.dshStrategy&&(this.logger.safe.info("Disposing client DSH strategy and switching to MP provided DSH"),this.disposeStrategy())}dispose(){this.disposeStrategy(),this.onActiveSpeakersChanged=null,this.onDominantSpeakersChanged=null}disposeStrategy(){this.dshStrategy?.dispose(),this.dshStrategy=null}},MT=class{constructor(g){this.listener=g,this.streams=[]}add(g){this.streams.some((f=>f.getId()===g.getId()))||(this.streams.push(g),this.listener.streamAdded(g))}remove(g){let f;remove2(this.streams,(S=>S.getId()===g&&(f=S,!0)))&&this.listener.streamRemoved(f)}getStreams(){return this.streams}clear(){this.streams.forEach((g=>g.dispose())),this.streams=[]}},wT=__toESM(we()),OT=class{constructor(g,f,S){this.logger=g,this.qualityManager=f,this.configProvider=S}getControlItem(){return this.controlItem}setControlItem(g){this.controlItem=g}dispose(){this.controlItem=null}setVideoControlMessage(g){this.controlItem=this.messageToControlItem(g),this.logger.safe.info(`BW limit requested to ${this.controlItem.bandwidth}`)}modifyDescriptor(g){if(!this.controlItem)return g;const f=wT.parse(g.sdp);if(!f.media[1])return this.logger.unsafe.warn("video modality is disabled, skipping sdp modification, ",g),g;const S=this.getCurrentResolutionBitrate();this.logger.safe.info(`Select the BW limit as min of requested ${this.controlItem.bandwidth} and Current Resolution Max BR ${S}`);const v=this.getSessionBitrate(f),C=Math.min(S,this.controlItem.bandwidth,v);if(f.media[1].bandwidth)f.media[1].bandwidth[0].limit=C;else{const g={limit:C,type:"AS"};f.media[1].bandwidth=[g]}return g.sdp=wT.write(f),g}messageToControlItem(g){const f=new Zy(g.controlVideoStreaming.controlInfo[0].fmtParams),S="max-br",v=1.2;if(!f.contains(S))return null;const C=Math.round(+f.get(S)*v);return{sourceId:g.controlVideoStreaming.controlInfo[0].sourceId,streamMsid:g.controlVideoStreaming.controlInfo[0].streamMsid,bandwidth:C}}getCurrentResolutionBitrate(){const g=this.qualityManager.getCurrentResolution(),f=ei.Send.getResolutionByFs(g);return g&&f?Math.floor(ei.Send.getBitrateForResolution(f.width,f.height).maxBitrate/1e3):Number.MAX_VALUE}getSessionBitrate(g){let f=Number.MAX_SAFE_INTEGER;return this.configProvider.mediaConfig.maxBandwidthInKbps&&(f=this.configProvider.mediaConfig.maxBandwidthInKbps),g.bandwidth&&(f=Math.min(+g.bandwidth[0].limit,f)),f-(this.configProvider.config.audioBandwidthInKbps||0)}},DT=class{constructor(g,f,S){this.pc=g,this.configProvider=f,this.logger=S.createChild("MediaRollbackModifier")}modifyDescriptor(g){const f=wT.parse(g.sdp);return wT.parse(this.pc.localDescription.sdp).media.forEach(((g,S)=>{const v=f.media[S];(isMediaDisabled(g)&&!g.bundleOnly||!v||isMediaDisabled(v))&&(this.logger.safe.info(`Adding disabled media ${g.type}, position ${S}`),f.media[S]=disabledMedia(g.type,void 0,g.protocol,void 0))})),new m_(this.configProvider).modify(f),g.sdp=wT.write(f),g}},NT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(g){if(!g)return;const f=new Set;if(g.send){this.diagnostics.handlePresentationAudioInputLevel();for(const S of g.send)try{f.add(S.outboundRTP.id);let g=this.sendExtenders.get(S.outboundRTP.id)??new FT(this.diagnostics,this.configProvider);S.outboundRTP.bytesSent<g.lastBytes&&(g=new FT(this.diagnostics,this.configProvider)),this.sendExtenders.set(S.outboundRTP.id,g),g.processSample(S)}catch(g){this.diagnostics.addStatsError("AudioStatsProcessor:send",stringifyObject(g))}}if(clearMap(this.sendExtenders,f),f.clear(),g.recv)for(const S of g.recv)try{f.add(S.inboundRTP.id);let g=this.recvExtenders.get(S.inboundRTP.id)??new kT(this.configProvider);S.inboundRTP.bytesReceived<g.lastBytes&&(g=new kT(this.configProvider)),this.recvExtenders.set(S.inboundRTP.id,g),g.processSample(S)}catch(g){this.diagnostics.addStatsError("AudioStatsProcessor:recv",stringifyObject(g))}clearMap(this.recvExtenders,f)}},kT=class{constructor(g){this.configProvider=g,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new Xv(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.bytesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.totalSamplesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.concealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.silentConcealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.concealedRatioAverager=new Hv,this.stretchedRatioAverager=new Hv,this.codecSwitchesTracker=new zv,this.packetDurationTracker=new zv,this.jitterAverager=new Hv,this.jitterBufferDelayAverager=new Hv,this.lastBytes=0}processSample(g){let f,S,v,C,_;const T=this.lossRateCalculator.calculate(g.inboundRTP.packetsReceived,g.inboundRTP.packetsLost)??0;this.lastBytes=g.inboundRTP.bytesReceived,this.bytesReceivedDiff.captureSample(g.inboundRTP.bytesReceived,g.inboundRTP.timestamp),this.totalSamplesReceivedDiff.captureSample(g.inboundRTP.totalSamplesReceived,g.inboundRTP.timestamp),this.concealedSamplesDiff.captureSample(g.inboundRTP.concealedSamples,g.inboundRTP.timestamp),this.silentConcealedSamplesDiff.captureSample(g.inboundRTP.silentConcealedSamples,g.inboundRTP.timestamp);const I=this.bytesReceivedDiff.delta&&8*this.bytesReceivedDiff.delta;this.packetsDelta.captureSample(g.inboundRTP.packetsReceived,g.inboundRTP.timestamp),this.packetsLostDelta.captureSample(g.inboundRTP.packetsLost,g.inboundRTP.timestamp);const b=g.inboundRTP.jitterBufferDelay&&g.inboundRTP.jitterBufferEmittedCount&&round(g.inboundRTP.jitterBufferDelay/g.inboundRTP.jitterBufferEmittedCount*1e3,0);if(this.jitterAverager.captureSample(1e3*g.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(g.inboundRTP.jitterBufferDelay),f=this.totalSamplesReceivedDiff.delta&&this.concealedSamplesDiff.delta&&this.silentConcealedSamplesDiff.delta&&round((this.concealedSamplesDiff.delta-this.silentConcealedSamplesDiff.delta)/this.totalSamplesReceivedDiff.delta),g.customHealerStats){g.customHealerStats.numSamplesPerFrame&&(C=g.customHealerStats.decodedSamples/g.customHealerStats.numSamplesPerFrame,_=g.customHealerStats.cngSamples/g.customHealerStats.numSamplesPerFrame),f=g.customHealerStats.healedSamples/(g.customHealerStats.decodedSamples+g.customHealerStats.healedSamples),v=g.customHealerStats.concealSamples&&g.customHealerStats.concealSamples/(g.customHealerStats.decodedSamples+g.customHealerStats.healedSamples),S=g.customHealerStats.stretchSamples&&g.customHealerStats.stretchSamples/(g.customHealerStats.decodedSamples+g.customHealerStats.healedSamples);const T=g.customHealerStats.packetDurationInMs&&g.customHealerStats.packetDurationInMs>100?100:g.customHealerStats.packetDurationInMs;this.concealedRatioAverager.captureSample(v),this.stretchedRatioAverager.captureSample(S),this.codecSwitchesTracker.captureSample(`${g.customHealerStats.pullAdspPayloadType}`),this.packetDurationTracker.captureSample(`${T}`)}g.extensions={lossRate:T,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,healedRatio:f,jitterBufferMs:b,bitrate:I||0,customHealerStats:g.customHealerStats&&{concealedDataRatio:v,concealedDataRatioMax:this.concealedRatioAverager.maxSample,stretchedDataRatio:S,stretchedDataRatioMax:this.stretchedRatioAverager.maxSample,numberOfDecodedFrames:C,usageMetricsCodecId:this.codecSwitchesTracker.sortedDurations,percentageOfPtime:this.packetDurationTracker.durationRatios,pushPacketProcessingTimes:g.customHealerStats.pushProcessingTimes,pullPacketProcessingTimes:g.customHealerStats.pullProcessingTimes,pullProcessingTimePerStreamNumber:g.customHealerStats.pullProcessingTimePerStreamNumber,pullTimings:g.customHealerStats.pullTimings,cnpPushCount:g.customHealerStats.cnpPushCount,cnpPullCount:g.customHealerStats.cnpPullCount,numberOfCNFrames:_,redPacketsCount:g.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:g.customHealerStats.pullNumOfStreamsCounter},jitterAvg:round(this.jitterAverager.avg),jitterBufferDelayMs:round(this.jitterBufferDelayAverager.avg)},this.duration++}},LT=class{constructor(){this.duration=0,this.lossRateAverager=new Hv,this.bitrateAverager=new Hv,this.jitterBufferAverager=new Hv,this.jitterAverager=new Hv,this.jitterBufferDelayAverager=new Hv,this.healedRatioAverager=new Hv}processSample(g,f,S){const v=g[0],C={inboundRTP:v.inboundRTP};if(v.transport&&Object.defineProperty(C,"transport",{value:v.transport,configurable:!1,enumerable:!1}),v.codec&&(C.codec=v.codec),v.track&&(C.track=v.track),v.remoteOutboundRTP&&(C.remoteOutboundRTP=v.remoteOutboundRTP),v.extensions){this.lossRateAverager.captureSample(v.extensions.lossRate),this.bitrateAverager.captureSample(v.extensions.bitrate),this.healedRatioAverager.captureSample(v.extensions.healedRatio),this.jitterBufferAverager.captureSample(v.extensions.jitterBufferMs),this.jitterAverager.captureSample(1e3*v.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(v.inboundRTP.jitterBufferDelay);const g=v.inboundRTP.packetsReceived+v.inboundRTP.packetsLost;C.aggregated={lossRateMax:this.lossRateAverager.maxSample,lossRateAvg:this.lossRateAverager.avg,networkAvgLossRate:g>0?v.inboundRTP.packetsLost/g:0,packetsLostAvg:this.duration>0?v.inboundRTP.packetsLost/this.duration:0,duration:this.duration,bitrateAvg:round(this.bitrateAverager.avg,0),bitrateMax:round(this.bitrateAverager.maxSample,0),jitterAvg:this.jitterAverager.avg,jitterMax:this.jitterAverager.maxSample,avgJitterBufferSize:this.jitterBufferAverager.avg,healedRatioAvg:this.healedRatioAverager.avg,healedRatioMax:this.healedRatioAverager.maxSample,customHealerStats:v.extensions.customHealerStats&&{concealedDataRatio:v.extensions.customHealerStats.concealedDataRatio,concealedDataRatioMax:v.extensions.customHealerStats.concealedDataRatioMax,stretchedDataRatio:v.extensions.customHealerStats.stretchedDataRatio,stretchedDataRatioMax:v.extensions.customHealerStats.stretchedDataRatioMax,numberOfDecodedFrames:v.extensions.customHealerStats.numberOfDecodedFrames,usageMetricsCodecId:v.extensions.customHealerStats.usageMetricsCodecId,percentageOfPtime:v.extensions.customHealerStats.percentageOfPtime,pushPacketProcessingTimes:v.extensions.customHealerStats.pushPacketProcessingTimes,pullPacketProcessingTimes:v.extensions.customHealerStats.pullPacketProcessingTimes,pullProcessingTimePerStreamNumber:v.extensions.customHealerStats.pullProcessingTimePerStreamNumber,pullTimings:v.extensions.customHealerStats.pullTimings,cnpPushCount:v.extensions.customHealerStats.cnpPushCount,cnpPullCount:v.extensions.customHealerStats.cnpPullCount,numberOfCNFrames:v.extensions.customHealerStats.numberOfCNFrames,redPacketsCount:v.extensions.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:v.extensions.customHealerStats.pullNumOfStreamsCounter}},this.duration++}arrayLimitedPush2(f,C,S)}},FT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new Xv(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.bytesSendDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.rttAverager=new Hv,this.lastBytes=0}processSample(g){const f=this.lossRateCalculator.calculate(g.remoteInboundRTP?.packetsReceived,g.remoteInboundRTP?.packetsLost)??0;this.packetsDelta.captureSample(g.outboundRTP.packetsSent,g.outboundRTP.timestamp),this.packetsLostDelta.captureSample(g.remoteInboundRTP?.packetsLost,g.remoteInboundRTP?.timestamp),this.lastBytes=g.outboundRTP.bytesSent,this.bytesSendDiff.captureSample(g.outboundRTP.bytesSent,g.outboundRTP.timestamp);const S=this.bytesSendDiff.delta;this.rttAverager.captureSample(1e3*(g.remoteInboundRTP?.roundTripTime??0)),g.extensions={lossRate:f,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,bitrate:S?8*S:0,rttAvg:round(this.rttAverager.avg),callIsMuted:this.diagnostics.callIsMuted,rawInputVolume:this.diagnostics.audioLevel},this.duration++}},xT=class{constructor(g){this.diagnostics=g,this.duration=0,this.lossRateAverager=new Hv,this.bitrateAverager=new Hv,this.rttAverager=new Hv}processSample(g,f,S){const v=g[0],C={outboundRTP:v.outboundRTP};v.transport&&Object.defineProperty(C,"transport",{value:v.transport,configurable:!1,enumerable:!1}),v.codec&&(C.codec=v.codec),v.track&&(C.track=v.track),v.mediaSource&&(C.mediaSource=v.mediaSource),v.remoteInboundRTP&&(C.remoteInboundRTP=v.remoteInboundRTP),v.extensions&&(this.lossRateAverager.captureSample(v.extensions.lossRate),this.bitrateAverager.captureSample(v.extensions.bitrate),this.rttAverager.captureSample(v.remoteInboundRTP?.roundTripTime),C.aggregated={duration:this.duration,lossRateMax:this.lossRateAverager.maxSample,bitrateAvg:round(this.bitrateAverager.avg,0),bitrateMax:round(this.bitrateAverager.maxSample,0),rttAvg:round(this.rttAverager.avg),rttMax:round(this.rttAverager.maxSample),rawInputVolume:this.diagnostics.audioLevel,audioLevel:v.track?.audioLevel??v.mediaSource?.audioLevel},this.duration++),arrayLimitedPush2(f,C,S)}},UT=M,VT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(g){if(!g)return;const f=new Set;if(g.send&&(0,UT.flatMap)(g.send,(g=>[g,...g.altLayouts??[]])).forEach((g=>{try{f.add(g.outboundRTP.id);let S=this.sendExtenders.get(g.outboundRTP.id)??new $T(this.diagnostics,this.configProvider);g.outboundRTP.bytesSent<S.lastBytes&&(S=new $T(this.diagnostics,this.configProvider)),this.sendExtenders.set(g.outboundRTP.id,S),S.processSample(g)}catch(g){this.diagnostics.addStatsError("VideoStatsProcessor:send",stringifyObject(g))}})),clearMap(this.sendExtenders,f),f.clear(),g.recv)for(const S of g.recv)try{f.add(S.inboundRTP.id);let g=this.recvExtenders.get(S.inboundRTP.id)??new BT(this.configProvider);S.inboundRTP.bytesReceived<g.lastBytes&&(g=new BT(this.configProvider)),this.recvExtenders.set(S.inboundRTP.id,g),g.processSample(S)}catch(g){this.diagnostics.addStatsError("VideoStatsProcessor:recv",stringifyObject(g))}clearMap(this.recvExtenders,f)}},BT=class{constructor(g){this.configProvider=g,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new Xv(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.bytesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.framesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.framesDecodedDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.trackFramesDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.decodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new Gv(2):new jv,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.freezeHistogram=new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.harmonicDecodedFps=new Kv(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.prevTimeToFirstFrame=-1,this.hasPrevFramerate=!1,this.lastBytes=0,this.macroblockStatsTracker=new iC}processSample(g){const f=this.lossRateCalculator.calculate(g.inboundRTP.packetsReceived,g.inboundRTP.packetsLost)??0;this.framesReceivedDelta.captureSample(g.inboundRTP.framesReceived,g.inboundRTP.timestamp),this.framesDecodedDelta.captureSample(g.inboundRTP.framesDecoded,g.inboundRTP.timestamp),this.trackFramesDelta.captureSample(g.inboundRTP.framesReceived??g.track?.framesReceived,g.inboundRTP.timestamp),this.packetsDelta.captureSample(g.inboundRTP.packetsReceived,g.inboundRTP.timestamp),this.packetsLostDelta.captureSample(g.inboundRTP.packetsLost,g.inboundRTP.timestamp);const S=this.framesReceivedDelta.delta,v=this.framesDecodedDelta.delta;this.harmonicDecodedFps.captureSample(v),this.decodeTimeDelta.captureSample(g.inboundRTP.totalDecodeTime,g.inboundRTP.timestamp);const C=this.decodeTimeDelta.delta&&v&&round(this.decodeTimeDelta.delta/v*1e3,2),_=v>0&&S>0,T=g.renderer?.timeToFirstFrame??(_?0:-1);this.freezeHistogram.active=-1!==T&&-1!==this.prevTimeToFirstFrame&&!_,"sharing"===g.mediaEntity?.modality&&this.configProvider.config.diagnostics.features.useTwoSampleVBSSFreezeDetection&&(this.freezeHistogram.active=this.freezeHistogram.active&&!this.hasPrevFramerate),this.prevTimeToFirstFrame=T,this.hasPrevFramerate=_,this.lastBytes=g.inboundRTP.bytesReceived,this.bytesReceivedDelta.captureSample(g.inboundRTP.bytesReceived,g.inboundRTP.timestamp);const I=this.bytesReceivedDelta.delta,b=g.inboundRTP.jitterBufferEmittedCount&&round((g.inboundRTP.jitterBufferDelay??0)/g.inboundRTP.jitterBufferEmittedCount*1e3),A=calcMacroblockRate(g.inboundRTP.frameWidth,g.inboundRTP.frameHeight,S||0),P=calcMacroblockRate(g.inboundRTP.frameWidth,g.inboundRTP.frameHeight,v||0);this.macroblockStatsTracker.captureSample(A,P),g.extensions={lossRate:f,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,frameRateReceived:S,frameRateDecoded:v,trackRecvFps:this.trackFramesDelta.delta,decodeTime:C||0,jitterBufferMs:b,bitrate:I?8*I:0,isFrozen:this.freezeHistogram.active,macroblockRateReceived:A,macroblockRateDecoded:P,macroblockRateStats:this.macroblockStatsTracker.getReport(),longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,powerEfficient:void 0!==g.inboundRTP.powerEfficientDecoder?g.inboundRTP.powerEfficientDecoder:isPowerEfficient(g.inboundRTP.decoderImplementation),totalFreezeFraction:this.duration?this.freezeHistogram.totalDuration/this.duration:0,fpsHarmonicAverage:round(this.harmonicDecodedFps.harmonicMean)},this.duration++}},HT=class{constructor(g){this.configProvider=g,this.duration=0,this.lossRateAverager=new Hv,this.bitrateAverager=new Hv,this.jitterAverager=new Hv,this.frameRateAverager=new Hv,this.freezeHistogram=new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.harmonicDecodedFps=new Kv(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.resolutionDurations=new zv,this.codecCalculator=new nC}processSample(g,f,S){const v=g.sort(((g,f)=>f.inboundRTP.frameHeight*f.inboundRTP.frameWidth-g.inboundRTP.frameHeight*g.inboundRTP.frameWidth))[0],C={inboundRTP:v.inboundRTP};v.transport&&Object.defineProperty(C,"transport",{value:v.transport,configurable:!1,enumerable:!1}),v.codec&&(C.codec=v.codec,this.configProvider.config.isAv1Allowed&&"sharing"===v.mediaEntity?.modality&&this.codecCalculator.captureSample(v.codec.mimeType,v.renderer?.msi)),v.track&&(C.track=v.track),v.remoteOutboundRTP&&(C.remoteOutboundRTP=v.remoteOutboundRTP),v.extensions&&(C.extensions=v.extensions),v.extensions&&(this.harmonicDecodedFps.captureSample(v.extensions.frameRateDecoded),this.lossRateAverager.captureSample(v.extensions.lossRate),this.bitrateAverager.captureSample(v.extensions.bitrate),this.jitterAverager.captureSample(1e3*(v.inboundRTP.jitter??0)),this.frameRateAverager.captureSample(v.extensions.frameRateReceived??v.extensions.frameRateDecoded),this.freezeHistogram.active=v.extensions.isFrozen,v.inboundRTP.frameWidth&&v.inboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${v.inboundRTP.frameWidth}x${v.inboundRTP.frameHeight}`),C.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,avgFrameRate:round(this.frameRateAverager.avg),fpsHarmonicAverage:round(this.harmonicDecodedFps.harmonicMean),avgJitterBufferSize:round(this.jitterAverager.avg),bitrateAvg:round(this.bitrateAverager.avg,0),bitrateMax:round(this.bitrateAverager.maxSample,0),bitrateMinNonZero:round(this.bitrateAverager.minNonZeroSample,0),ongoingFreezeDuration:this.freezeHistogram.ongoingDuration,numFreezes:this.freezeHistogram.numEvents,avgFreezeDuration:round(this.freezeHistogram.avgDuration),longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,freezeCountHistogram:this.freezeHistogram.counts,freezeTimestampsHistogram:this.freezeHistogram.timestamps,numResolutionSwitches:this.resolutionDurations.changeCount,resolutionDurations:this.resolutionDurations.durations,resolutionDurationRatios:this.resolutionDurations.durationRatios,macroblockRateStats:v.extensions.macroblockRateStats,codecReport:this.codecCalculator?.report},this.duration++),arrayLimitedPush(f,C,S)}},$T=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new Xv(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.lossRateAverager=new Hv,this.freezeHistogram=new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.hasPrevFramerate=!1,this.captureFreezeIntervalsCount=0,this.bytesSendDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.encodedFramesDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.sentFramesDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.harmonicEncodedFps=new Kv(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.encodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new Gv(2):new jv,this.qpDelta=this.useLastSampleDeltaPerSecondConverter?new Gv(3):new jv,this.fsOvershoot=new Qv("fs"),this.fpsOvershoot=new Qv("fps",1),this.brOvershoot=new Qv("br"),this.plisDelta=new jv,this.pliRate=new eC(60),this.resolutionSwitcherTracker=new tC(this.configProvider.config.diagnostics.collectionLimits.numResolutionSwitches),this.bitrateAverager=new Hv,this.rttAverager=new Hv,this.powerEfficientEncoderChangeTracker=new rC(this.configProvider.config.diagnostics.collectionLimits.numPowerEfficientEncoderEvents),this.lastBytes=0}processSample(g){const f=this.lossRateCalculator.calculate(g.remoteInboundRTP?.packetsReceived,g.remoteInboundRTP?.packetsLost);this.lossRateAverager.captureSample(f),this.plisDelta.captureSample(g.outboundRTP.pliCount),this.pliRate.captureSample(this.plisDelta.delta),this.packetsDelta.captureSample(g.outboundRTP.packetsSent,g.outboundRTP.timestamp),this.packetsLostDelta.captureSample(g.remoteInboundRTP?.packetsLost,g.remoteInboundRTP?.timestamp),this.lastBytes=g.outboundRTP.bytesSent,this.bytesSendDelta.captureSample(g.outboundRTP.bytesSent,g.outboundRTP.timestamp);const S=this.bytesSendDelta.delta,v=S?8*S:void 0;this.bitrateAverager.captureSample(v),this.rttAverager.captureSample(1e3*(g.remoteInboundRTP?.roundTripTime??0)),this.encodedFramesDelta.captureSample(g.outboundRTP.framesEncoded,g.outboundRTP.timestamp);const C=this.encodedFramesDelta.delta;this.sentFramesDelta.captureSample(g.outboundRTP.framesSent,g.outboundRTP.timestamp);const _=this.sentFramesDelta.delta||0;this.harmonicEncodedFps.captureSample(C);const T=g.mediaSource?.framesPerSecond;0===T&&void 0!==this.lastCaptureFramerate&&this.lastCaptureFramerate>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFramerate=T;const I=C>0&&_>0;this.freezeHistogram.active=!I,"sharing"===g.mediaEntity?.modality&&this.configProvider.config.diagnostics.features.useTwoSampleVBSSFreezeDetection&&(this.freezeHistogram.active=this.freezeHistogram.active&&!this.hasPrevFramerate),this.hasPrevFramerate=I,this.encodeTimeDelta.captureSample(g.outboundRTP.totalEncodeTime,g.outboundRTP.timestamp);const b=this.encodeTimeDelta.delta&&C&&round(this.encodeTimeDelta.delta/C*1e3,2);this.qpDelta.captureSample(g.outboundRTP.qpSum,g.outboundRTP.timestamp);const A=this.qpDelta.delta&&C&&round(this.qpDelta.delta/C,2);g.outboundRTP.frameWidth&&g.outboundRTP.frameHeight&&this.resolutionSwitcherTracker.captureSample(g.outboundRTP.frameWidth,g.outboundRTP.frameHeight);const P=this.diagnostics.deviceManager?.latestCameraOpenResolution,R=g.appliedCapabilities??g.requestedCapabilities;R&&(void 0!==g.outboundRTP.frameHeight&&void 0!==g.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(g.outboundRTP.frameHeight/16*(g.outboundRTP.frameWidth/16),R.maxFs),this.fpsOvershoot.captureSample(_,R.maxFps),R.maxBr&&this.brOvershoot.captureSample(v,R.maxBr));const M=[...this.fsOvershoot.events,...this.brOvershoot.events,...this.fpsOvershoot.events];if(M.sort(((g,f)=>g.timestamp-f.timestamp)),g.outboundRTP.frameHeight&&(g.outboundRTP.powerEfficientEncoder||g.outboundRTP.encoderImplementation)){const f=void 0!==g.outboundRTP.powerEfficientEncoder?g.outboundRTP.powerEfficientEncoder:isPowerEfficient(g.outboundRTP.encoderImplementation);this.powerEfficientEncoderChangeTracker.captureSample(f,g.outboundRTP.frameHeight)}g.extensions={cameraOpenResolution:P,lossRate:f,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,pliRate:this.pliRate.getRate(),frameRateEncoded:this.encodedFramesDelta.delta,frameRateSent:_,bitrate:v||0,encodeTime:b||0,qp:A||0,isFrozen:this.freezeHistogram.active,longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,ongoingFreezeDuration:this.freezeHistogram.ongoingDuration,freezeCountHistogram:this.freezeHistogram.counts,captureFreezeIntervalsCount:this.captureFreezeIntervalsCount,isFsOvershooting:this.fsOvershoot.isOvershooting,isFpsOvershooting:this.fpsOvershoot.isOvershooting,isBrOvershooting:this.brOvershoot.isOvershooting,totalFsOvershootDuration:this.fsOvershoot.totalDuration,totalFpsOvershootDuration:this.fpsOvershoot.totalDuration,totalBrOvershootDuration:this.brOvershoot.totalDuration,overshootEvents:M,powerEfficient:this.powerEfficientEncoderChangeTracker.curPowerEfficientEncoderState,powerEfficientEncoderEvents:this.powerEfficientEncoderChangeTracker.events,powerEfficientEncoderEventOnCount:this.powerEfficientEncoderChangeTracker.eventOnCount,powerEfficientEncoderEventOffCount:this.powerEfficientEncoderChangeTracker.eventOffCount,bitrateAvg:round(this.bitrateAverager.avg,0),rttAvg:round(this.rttAverager.avg)},this.duration++}},jT=class{constructor(g){this.configProvider=g,this.duration=0,this.lossRateAverager=new Hv,this.bitrateAverager=new Hv,this.sendBWEAverager=new Hv,this.rttAverager=new Hv,this.framerateAverager=new Hv,this.captureFpsAverager=new Hv,this.captureFreezeIntervalsCount=0,this.lastCaptureFps=void 0,this.resolutionDurations=new zv,this.fsOvershoot=new Qv("fs"),this.fpsOvershoot=new Qv("fps",1),this.brOvershoot=new Qv("br"),this.harmonicEncodedFps=new Kv(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax)}processSample(g,f,S){g.length>1&&g.sort(((g,f)=>{const S=g.appliedCapabilities??g.requestedCapabilities,v=f.appliedCapabilities??f.requestedCapabilities;return S?.maxMbps&&v?.maxMbps?v.maxMbps-S.maxMbps:0}));const v=g[0],C={outboundRTP:v.outboundRTP};if(v.transport&&Object.defineProperty(C,"transport",{value:v.transport,configurable:!1,enumerable:!1}),v.codec&&(C.codec=v.codec),v.track&&(C.track=v.track),v.mediaSource&&(C.mediaSource=v.mediaSource),v.remoteInboundRTP&&(C.remoteInboundRTP=v.remoteInboundRTP),v.extensions&&(C.extensions=v.extensions),v.extensions){this.lossRateAverager.captureSample(v.extensions.lossRate),this.bitrateAverager.captureSample(v.extensions.bitrate),this.sendBWEAverager.captureSample(v.transport?.selectedCandidatePair?.availableOutgoingBitrate),this.rttAverager.captureSample(v.remoteInboundRTP?.roundTripTime),this.framerateAverager.captureSample(v.extensions.frameRateSent);const g=v.mediaSource?.framesPerSecond;this.captureFpsAverager.captureSample(g),0===g&&void 0!==this.lastCaptureFps&&this.lastCaptureFps>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFps=g,v.outboundRTP.frameWidth&&v.outboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${v.outboundRTP.frameWidth}x${v.outboundRTP.frameHeight}`);const f=v.appliedCapabilities??v.requestedCapabilities;f&&(void 0!==v.outboundRTP.frameHeight&&void 0!==v.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(v.outboundRTP.frameHeight/16*(v.outboundRTP.frameWidth/16),f.maxFs),this.fpsOvershoot.captureSample(v.extensions.frameRateSent,f.maxFps),f.maxBr&&this.brOvershoot.captureSample(v.extensions?.bitrate,f.maxBr)),this.harmonicEncodedFps.captureSample(v.extensions.frameRateEncoded);const S=[...this.fsOvershoot.events,...this.fpsOvershoot.events,...this.brOvershoot.events];S.sort(((g,f)=>g.timestamp-f.timestamp)),C.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,frameRateAvg:round(this.framerateAverager.avg),captureFramerateAvg:round(this.captureFpsAverager.avg),fpsHarmonicAverage:round(this.harmonicEncodedFps.harmonicMean),qpAvg:round(v.outboundRTP.qpSum/v.outboundRTP.framesSent),rttAvg:round(this.rttAverager.avg),bitrateAvg:round(this.bitrateAverager.avg,0),bitrateMax:round(this.bitrateAverager.maxSample,0),bitrateMinNonZero:round(this.bitrateAverager.minNonZeroSample,0),bweAvg:round(this.sendBWEAverager.avg,0),captureFreezeIntervalsCount:this.captureFreezeIntervalsCount,numResolutionSwitches:this.resolutionDurations.changeCount,resolutionDurations:this.resolutionDurations.durations,resolutionDurationRatios:this.resolutionDurations.durationRatios,isFsOvershooting:this.fsOvershoot.isOvershooting,isFpsOvershooting:this.fpsOvershoot.isOvershooting,isBrOvershooting:this.brOvershoot.isOvershooting,totalFsOvershootDuration:this.fsOvershoot.totalDuration,totalFpsOvershootDuration:this.fpsOvershoot.totalDuration,totalBrOvershootDuration:this.brOvershoot.totalDuration,overshootEvents:S},this.duration++}arrayLimitedPush(f,C,S)}},GT=class{constructor(g){this.configProvider=g,this.samplesCountPerSubscription=0,this.data=new Uv(this.configProvider.config.diagnostics.collectionLimits.numVideoSubscriptionStats)}prepareCollectingStatsOnSubscribed(g){this.samplesCountPerSubscription=0,this.data.add({timestamp:Date.now(),framesDecoded:[],bytesReceived:[],height:[],msi:g})}captureStatsOnSubscribed(g,f,S){if(this.samplesCountPerSubscription>=this.configProvider.config.diagnostics.collectionLimits.numVideoStatsAfterSubscription)return;const v=getLast(this.data.items);v&&(g&&v.framesDecoded.push(g),f&&v.bytesReceived.push(f),S&&v.height.push(S)),this.samplesCountPerSubscription++}get videoStatsOnSubscribed(){return this.data.items}},qT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.extenders=new Map}processStats(g){const f=new Set;for(const S in g)try{f.add(S);const v=g[S],C=this.extenders.get(v.id)??new WT(this.configProvider,this.diagnostics);this.extenders.set(v.id,C),C.processSample(v)}catch(g){this.diagnostics.addStatsError("TransportStatsProcessor",stringifyObject(g))}clearMap(this.extenders,f)}},WT=class{constructor(g,f){this.configProvider=g,this.diagnostics=f,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.bwJumpsHistogramCollector=new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.sendBWEAverager=new Hv,this.recvBWEAverager=new Hv,this.sendBW=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.recvBW=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.sendBWAverager=new Hv,this.recvBWAverager=new Hv}processSample(g){this.sendBWEAverager.captureSample(g.selectedCandidatePair?.availableOutgoingBitrate),this.recvBWEAverager.captureSample(g.selectedCandidatePair?.availableIncomingBitrate),this.sendBW.captureSample(g.selectedCandidatePair?.bytesSent,g.selectedCandidatePair?.timestamp),this.recvBW.captureSample(g.selectedCandidatePair?.bytesReceived,g.selectedCandidatePair?.timestamp);const f=this.sendBW.delta,S=this.recvBW.delta,v=f?8*f:void 0,C=S?8*S:void 0;this.sendBWAverager.captureSample(v),this.recvBWAverager.captureSample(C);const _=g.selectedCandidatePair?.availableOutgoingBitrate;_&&(this.bwJumpsHistogramCollector.active=this.bwJumpsHistogramCollector.active&&_<this.configProvider.config.webrtcBWJumpUpperLimit||_<this.configProvider.config.webrtcBWJumpLowerLimit),g.extensions={sendBWEAvg:round(this.sendBWEAverager.avg,0),sendBWEMax:round(this.sendBWEAverager.maxSample,0),recvBWEAvg:round(this.recvBWEAverager.avg,0),recvBWEMax:round(this.recvBWEAverager.maxSample,0),sendBitrate:v,recvBitrate:C,sendBWAvg:round(this.sendBWAverager.avg,0),sendBWMax:round(this.sendBWAverager.maxSample,0),recvBWAvg:round(this.recvBWAverager.avg,0),recvBWMax:round(this.recvBWAverager.maxSample,0),bwJumpsHistogram:this.bwJumpsHistogramCollector.counts,reflexiveLocalIP:this.diagnostics.reflexiveLocalIP}}},zT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.extenders=new Map}processStats(g){if(!g)return;const f=new Set;for(const S of g)try{f.add(S.id);const g=this.extenders.get(S.id)??new KT(this.configProvider);this.extenders.set(S.id,g),g.processSample(S)}catch(g){this.diagnostics.addStatsError("DataChannelStatsProcessor",stringifyObject(g))}clearMap(this.extenders,f)}},KT=class{constructor(g){this.configProvider=g,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.sendBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.recvBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.sendMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.recvMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv}processSample(g){this.sendBytesDeltaCalculator.captureSample(g.bytesSent,g.timestamp),this.recvBytesDeltaCalculator.captureSample(g.bytesReceived,g.timestamp);const f=this.sendBytesDeltaCalculator.delta,S=this.recvBytesDeltaCalculator.delta,v=f?8*f:void 0,C=S?8*S:void 0;this.sendMessagesDeltaCalculator.captureSample(g.messagesSent,g.timestamp),this.recvMessagesDeltaCalculator.captureSample(g.messagesReceived,g.timestamp);const _=this.sendMessagesDeltaCalculator.delta,T=this.recvMessagesDeltaCalculator.delta;g.extensions={sendBitrate:v,recvBitrate:C,sendMessageRate:_,recvMessageRate:T}}},JT=class{constructor(g,f,S,v){this.slidingWindowSize=g,this.maxDeviation=f,this.minBandwidth=S,this.directionalityCheck=v,this.slidingWindow=new Uv(this.slidingWindowSize),this.currentModality=null,this.previousModality=null,this.inProcess=!1}processBandwidth(g,f,S){this.currentModality?this.handleStopEvent(f,S):this.handleStartEvent(f,S),this.inProcess&&(this.stabilizationTime++,this.slidingWindow.add(g),this.inProcess=!this.slidingWindow.isFull||!this.isBandwidthStable())}getReport(g=!1){if(void 0!==this.stabilizationTime){return{time:this.inProcess?this.stabilizationTime:Math.max(this.stabilizationTime-this.slidingWindowSize,0),bandwidth:g?round(this.averageBandwidth,2):this.averageBandwidth,finished:!this.inProcess,modality:this.previousModality}}}handleStartEvent(g,f){this.currentModality=this.GetModalityString(g),f&&this.currentModality&&!this.previousModality&&(this.previousModality=this.currentModality,this.stabilizationTime=0,this.slidingWindow.clear(),this.inProcess=!0)}handleStopEvent(g,f){f&&(this.directionalityCheck(g.audio)||this.directionalityCheck(g.video)||this.directionalityCheck(g.sharing))||(this.currentModality=null,this.inProcess=!1)}GetModalityString(g){return[this.directionalityCheck(g.audio)?qt.MODALITY.audio:null,this.directionalityCheck(g.video)?qt.MODALITY.video:null,this.directionalityCheck(g.sharing)?qt.MODALITY.sharing:null].filter(Boolean).join(", ")}isBandwidthStable(){if(this.averageBandwidth=average(this.slidingWindow.items),this.averageBandwidth<this.minBandwidth)return!1;{const g=this.averageBandwidth*this.maxDeviation,f=this.averageBandwidth-g,S=this.averageBandwidth+g;return this.slidingWindow.items.every((g=>isInRange(g,f,S)))}}},YT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.uplinkStabilizationTelemetry=new JT(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,hasSendDirectionality),this.downlinkStabilizationTelemetry=new JT(this.configProvider.config.downlinkBWStabilizationSlidingWindowSize,this.configProvider.config.downlinkBWStabilizationMaxDeviation,this.configProvider.config.downlinkBWStabilizationMinBandwidth,hasReceiveDirectionality),this.bandwidthCalculator=new Zv,this.bandwidthAvg=new Hv}processStats(g){const f=this.diagnostics.getObjectRef(),S=f?.negotiation.activeModalities;if(!S||!g.transports)return;const v=g.transports[Object.keys(g.transports)[0]],C=f?.reportedReceiveBandwidth?.[f.reportedReceiveBandwidth.length-1],_=v?.selectedCandidatePair?.availableOutgoingBitrate,T=g.audio?.send?.length>0||g.video?.send?.length>0||g.sharing?.send?.length>0,I=g.audio?.recv?.length>0||g.video?.recv?.length>0||g.sharing?.recv?.length>0;this.bweType!==f?.negotiation.bweType&&(this.bandwidthCalculator=new Zv,this.bandwidthAvg=new Hv,this.bweType=f?.negotiation.bweType);const b="REMB"===f?.negotiation.bweType?"availableIncomingBitrate":"availableOutgoingBitrate",A=v?.selectedCandidatePair?.[b];this.bandwidthCalculator.captureSample(A),this.bandwidthAvg.captureSample(A);try{this.uplinkStabilizationTelemetry.processBandwidth(_,S,T),this.downlinkStabilizationTelemetry.processBandwidth(C,S,I)}catch(g){this.diagnostics.addStatsError("BandwidthStatsProcessor",stringifyObject(g))}}getStabilizedReport(g=!1){return this.uplinkStabilizationTelemetry.getReport(g)}getDownlinkStabilizedReport(g=!1){return this.downlinkStabilizationTelemetry.getReport(g)}calculateBwPercentiles(){if(!this.bandwidthCalculator.getFirst())return;const g=this.configProvider.config.bwPercentiles,f={};return g.forEach((g=>{Object.defineProperty(f,g,{value:this.bandwidthCalculator.calculatePercentile(g/100),enumerable:!0})})),f}getBandwidthReport(){return{startOfTheCall:this.bandwidthCalculator.getFirst(),endOfTheCall:this.bandwidthCalculator.getLast(),std:this.bandwidthCalculator.calculateStd(),bwPercentiles:this.calculateBwPercentiles(),avgBwe:round(this.bandwidthAvg.avg,2)}}},QT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.videoSimulcastStreamsData={},this.videoLayoutProcessor=new XT(this.diagnostics,qt.MODALITY.video),this.sharingSimulcastStreamsData={},this.sharingLayoutProcessor=new XT(this.diagnostics,qt.MODALITY.sharing)}processStats(g){if(g.video?.send?.length){const f=g.video.send[0],S=[f,...f.altLayouts??[]];this.processSimulcastStream(S,this.videoSimulcastStreamsData),this.videoLayoutProcessor.processLayout(S)}if(g.sharing?.send?.length){const f=g.sharing.send[0],S=[f,...f.altLayouts??[]];this.processSimulcastStream(S,this.sharingSimulcastStreamsData),this.sharingLayoutProcessor.processLayout(S)}this.diagnostics.simulcastReport=this.getSimulcastDiagnostics()}processSimulcastStream(g,f){const{numAggregatedSamples:S}=this.configProvider.config.diagnostics.telemetryLimits;for(const v of g){const g=v.outboundRTP.rid;if(!g)continue;f[g]??(f[g]={sentLayerProcessor:new eI,appliedLayerProcessor:new eI,requestedLayerProcessor:new eI,encoderProcessor:new ZT,debugResolutionTracker:new zv,outboundStats:[],report:{ssrc:v.outboundRTP.ssrc,time:{requested:0,applied:0,sent:0},duration:{requested:0,applied:0,sent:0},restarts:{requested:0,applied:0,sent:0},resolution:{requested:{},applied:{},sent:{}},framerate:{requested:{},applied:{},sent:{}},bitrate:{requested:{},applied:{},sent:{}},encoder:{},stats:{},overshootEvents:[]}});const C=f[g],{sentLayer:_,requestedLayer:T,appliedLayer:I}=this.getLayers(v);C.sentLayerProcessor.processLayer(_),C.appliedLayerProcessor.processLayer(I),C.requestedLayerProcessor.processLayer(T),C.encoderProcessor.processVideo(v),I&&_&&C.debugResolutionTracker.captureSample(`${I.width}x${I.height}:${_.width}x${_.height}`),arrayLimitedPush(C.outboundStats,v.outboundRTP,S),C.report.time.sent=C.sentLayerProcessor.getTime(),C.report.time.applied=C.appliedLayerProcessor.getTime(),C.report.time.requested=C.requestedLayerProcessor.getTime(),C.report.duration.sent=C.sentLayerProcessor.getDuration(),C.report.duration.applied=C.appliedLayerProcessor.getDuration(),C.report.duration.requested=C.requestedLayerProcessor.getDuration(),C.report.restarts.sent=C.sentLayerProcessor.getRestarts(),C.report.restarts.applied=C.appliedLayerProcessor.getRestarts(),C.report.restarts.requested=C.requestedLayerProcessor.getRestarts(),C.report.resolution.sent=C.sentLayerProcessor.getResolutionDurations(),C.report.resolution.applied=C.appliedLayerProcessor.getResolutionDurations(),C.report.resolution.requested=C.requestedLayerProcessor.getResolutionDurations(),C.report.resolution.debug=C.debugResolutionTracker.durations,C.report.framerate.sent=C.sentLayerProcessor.getFpsDurations(),C.report.framerate.applied=C.appliedLayerProcessor.getFpsDurations(),C.report.framerate.requested=C.requestedLayerProcessor.getFpsDurations(),C.report.bitrate.sent=C.sentLayerProcessor.getBitrateDurations(),C.report.bitrate.applied=C.appliedLayerProcessor.getBitrateDurations(),C.report.bitrate.requested=C.requestedLayerProcessor.getBitrateDurations(),C.report.encoder=C.encoderProcessor.getEncoderReport(),C.report.stats.fir=sampleseries(C.outboundStats,(g=>g.firCount)),C.report.stats.nack=sampleseries(C.outboundStats,(g=>g.nackCount)),C.report.stats.pli=sampleseries(C.outboundStats,(g=>g.pliCount)),C.report.stats.packetsSent=sampleseries(C.outboundStats,(g=>g.packetsSent)),C.report.overshootEvents=v.extensions?.overshootEvents,C.report.totalBrOvershootDuration=v.extensions?.totalBrOvershootDuration,C.report.totalFpsOvershootDuration=v.extensions?.totalFpsOvershootDuration,C.report.totalFsOvershootDuration=v.extensions?.totalFsOvershootDuration,C.report.totalFreezeDuration=v.extensions?.totalFreezeDuration,C.report.ongoingFreezeDuration=v.extensions?.ongoingFreezeDuration,C.report.freezeHistogram=v.extensions?.freezeCountHistogram}}getSimulcastDiagnostics(){if(!isEmpty(this.videoSimulcastStreamsData)||!isEmpty(this.sharingSimulcastStreamsData))return{video:{streams:Object.fromEntries(Object.entries(this.videoSimulcastStreamsData).map((([g,{report:f}])=>[g,f]))),layouts:this.videoLayoutProcessor.getLayoutReport()},sharing:{streams:Object.fromEntries(Object.entries(this.sharingSimulcastStreamsData).map((([g,{report:f}])=>[g,f]))),layouts:this.sharingLayoutProcessor.getLayoutReport()}}}getLayers(g){const f=g.outboundRTP.rid,S=this.diagnostics.getObjectRef().qualityManager,findCurrentCapability=g=>Object.values(g).find((g=>g.rid===f)),v="sharing"===g.mediaEntity?.modality?findCurrentCapability(S.currentSharingSsrcAppliedCapabilities):findCurrentCapability(S.currentVideoSsrcAppliedCapabilities),C="sharing"===g.mediaEntity?.modality?findCurrentCapability(S.currentSharingSsrcRequestedCapabilities):findCurrentCapability(S.currentVideoSsrcRequestedCapabilities);return{sentLayer:g.outboundRTP.frameHeight&&{height:g.outboundRTP.frameHeight,width:g.outboundRTP.frameWidth,framerate:g.extensions?.frameRateSent,bitrate:g.extensions?.bitrate},appliedLayer:v&&convertStreamSenderParamsToLayer(v),requestedLayer:C&&convertStreamSenderParamsToLayer(C)}}},XT=class{constructor(g,f){this.diagnostics=g,this.modality=f,this.sentResolutionTracker=new zv,this.requestedResolutionTracker=new zv,this.appliedResolutionTracker=new zv,this.debugResolutionTracker=new zv}processLayout(g){const getLayoutResolution=g=>g.filter((g=>g.width&&g.height)).sort(((g,f)=>g.height-f.height)).map((g=>`${g.width}x${g.height}`)).join(":"),mapCapabilities=g=>Object.values(g).map(convertStreamSenderParamsToLayer),f=getLayoutResolution(g.map((g=>({height:g.outboundRTP.frameHeight,width:g.outboundRTP.frameWidth,framerate:g.extensions?.frameRateSent,bitrate:g.extensions?.bitrate})))),S=this.diagnostics.getObjectRef().qualityManager,v="sharing"===this.modality?S.currentSharingSsrcAppliedCapabilities:S.currentVideoSsrcAppliedCapabilities,C="sharing"===this.modality?S.currentSharingSsrcRequestedCapabilities:S.currentVideoSsrcRequestedCapabilities,_=getLayoutResolution(mapCapabilities(v)),T=getLayoutResolution(mapCapabilities(C));f&&this.sentResolutionTracker.captureSample(f),T&&this.requestedResolutionTracker.captureSample(T),_&&this.appliedResolutionTracker.captureSample(_),_&&f&&this.debugResolutionTracker.captureSample(`${_}->${f}`)}getLayoutReport(){return{requested:this.requestedResolutionTracker.durations,sent:this.sentResolutionTracker.durations,applied:this.appliedResolutionTracker.durations,debug:this.debugResolutionTracker.durations}}},ZT=class{constructor(){this.report={}}processVideo(g){var f,S;const{encoderImplementation:v,frameWidth:C,frameHeight:_,rid:T}=g.outboundRTP,{encodeTime:I}=g.extensions;if(!v||!_)return;const b=getEncoderName(v,T),A=`${C}x${_}`;(f=this.report)[b]??(f[b]={resolutionTracker:new zv,encodingHistograms:{},report:{resolution:{},encodeTime:{},restarts:0}});const P=this.report[b];P.resolutionTracker.captureSample(A),(S=P.encodingHistograms)[A]??(S[A]=new zv),P.encodingHistograms[A].captureSample(bucketizeEncodeTime(I)),P.report.resolution=P.resolutionTracker.durations,P.report.encodeTime[A]=P.encodingHistograms[A].durations,this.prevEncoder&&this.prevEncoder!==b&&P.report.restarts++,this.prevEncoder=b}getEncoderReport(){return Object.fromEntries(Object.entries(this.report).map((([g,{report:f}])=>[g,f])))}},eI=class{constructor(){this.resolutionTracker=new zv,this.fpsTracker=new zv,this.bitrateTracker=new zv,this.durationTracker=new eT,this.startedAt=0}processLayer(g){g?(this.startedAt||(this.startedAt=Jt()),this.durationTracker.start(),this.resolutionTracker.captureSample(`${g.width}x${g.height}`),this.fpsTracker.captureSample(bucketizeFramerate(g.framerate)),this.bitrateTracker.captureSample(bucketizeBitrate(g.bitrate))):this.durationTracker.stop()}getResolutionDurations(){return this.resolutionTracker.durations}getFpsDurations(){return this.fpsTracker.durations}getBitrateDurations(){return this.bitrateTracker.durations}getRestarts(){return Math.max(0,this.durationTracker.count-1)}getTime(){return this.startedAt}getDuration(){return this.durationTracker.elapsed}};function convertStreamSenderParamsToLayer(g){const f={...ei.Send.getResolutionByFs(g.maxFs)};if(405===g.maxFs)f.width=426,f.height=240;return{width:f.width,height:f.height,framerate:g.maxFps,bitrate:g.maxBr}}function getEncoderName(g,f){if(g.startsWith("SimulcastEncoderAdapter")){const S=g.indexOf("(")+1,v={},C=g.indexOf(")");g.substring(S,C).split(",").forEach(((g,f)=>{v[`${f+1}`]=g.trim()})),g=v[f]??"Unknown"}switch(g){case"OpenH264":return"H264:SW";case"ExternalEncoder":case"MediaFoundationVideoEncodeAccelerator":case"VideoToolbox":case"WMFVideoEncoder":case"VTVideoEncoder":case"VaapiVideoEncodeAccelerator":return"H264:HW";default:return"H264:Other"}}function bucketizeBitrate(g){return bucketize(g,[{limit:4e6,label:"4M+"},{limit:25e5,label:"2.5M-4M"},{limit:15e5,label:"1.5M-2.5M"},{limit:1e6,label:"1M-1.5M"},{limit:8e5,label:"800k-1M"},{limit:5e5,label:"500k-800k"},{limit:25e4,label:"250k-500k"},{limit:1e5,label:"100k-250k"},{limit:5e4,label:"50k-100k"},{limit:1e4,label:"10k-50k"},{limit:0,label:"0-10k"}])}function bucketizeFramerate(g){return bucketize(g,[{limit:60,label:"60+"},{limit:30,label:"31-60"},{limit:15,label:"16-30"},{limit:7,label:"8-15"},{limit:3,label:"4-7"},{limit:1,label:"1-3"}])}function bucketizeEncodeTime(g){return bucketize(g,[{limit:100,label:"100+ ms"},{limit:30,label:"30-100 ms"},{limit:10,label:"10-30 ms"},{limit:5,label:"5-10 ms"},{limit:2,label:"2-5 ms"},{limit:1,label:"1-2 ms"}])}function bucketize(g,f){for(const{limit:S,label:v}of f)if(g>S)return v;return`${g}`}var tI=class{constructor(g,f){this.configProvider=g,this.diagnostics=f,this.dataChannelStatsProcessor=new zT(this.diagnostics,this.configProvider),this.transportStatsProcessor=new qT(this.diagnostics,this.configProvider),this.audioStatsProcessor=new NT(this.diagnostics,this.configProvider),this.videoStatsProcessor=new VT(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new VT(this.diagnostics,this.configProvider),this.bandwidthStatsProcessor=new YT(this.diagnostics,this.configProvider),this.simulcastStatsProcessor=new QT(this.diagnostics,this.configProvider),this.macroblockStatsTracker=new iC,this.statsAggregators={audio:{recv:new LT,send:new xT(this.diagnostics)},video:{recv:new HT(this.configProvider),send:new jT(this.configProvider)},sharing:{recv:new HT(this.configProvider),send:new jT(this.configProvider)}},this.aggregatedModalityStats={},this.recvVideoStreamsCounter=new $v,this.multiviewData={},this.multiviewKeySet=new Set,this.statsOnSubscribedData={video:{},sharing:{}},this.statsOnSubscribed={video:[],sharing:[]},this.diagnostics.aggregatedStatsRef=this.aggregatedModalityStats,this.diagnostics.statsOnSubscribed=this.statsOnSubscribed,this.diagnostics.bandwidthDiagnostic=this.bandwidthStatsProcessor}processStats(g){this.dataChannelStatsProcessor.processStats(g.data),this.transportStatsProcessor.processStats(g.transports),this.audioStatsProcessor.processStats(g.audio),this.videoStatsProcessor.processStats(g.video),this.sharingStatsProcessor.processStats(g.sharing),this.bandwidthStatsProcessor.processStats(g),this.diagnostics.bwStabilizationTime=this.bandwidthStatsProcessor.getStabilizedReport(!0),this.diagnostics.bwDownlinkStabilizationTime=this.bandwidthStatsProcessor.getDownlinkStabilizedReport(!0),this.recvVideoStreamsCounter.captureSample(g.video?.recv?.length),this.diagnostics.recvVideoStreamsCount={min:this.recvVideoStreamsCounter.min,max:this.recvVideoStreamsCounter.max,mode:this.recvVideoStreamsCounter.mode};try{this.processAggregated(g)}catch(g){this.diagnostics.addStatsError("webrtcStatistics:processAggregated",stringifyObject(g))}try{this.processMultiview(g.video?.recv??[])}catch(g){this.diagnostics.addStatsError("webrtcStatistics:processMultiview",stringifyObject(g))}try{this.simulcastStatsProcessor.processStats(g)}catch(g){this.diagnostics.addStatsError("webrtcStatistics:processSimulcastStats",stringifyObject(g))}try{const g=navigator?.connection;g&&this.diagnostics.addNetworkInfo({downlink:g.downlink,rtt:g.rtt,effectiveType:g.effectiveType,saveData:g.saveData})}catch(g){this.diagnostics.addStatsError("webrtcStatistics:processStats(networkInfo)",stringifyObject(g))}try{this.processMacroblockRateStats(g.video?.recv)}catch(g){this.diagnostics.addStatsError("webrtcStatistics: processMacroblockRateStats",stringifyObject(g))}}signalNoConnection(){this.transportStatsProcessor=new qT(this.diagnostics,this.configProvider),this.audioStatsProcessor=new NT(this.diagnostics,this.configProvider),this.videoStatsProcessor=new VT(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new VT(this.diagnostics,this.configProvider)}processMultiview(g){const f=new Set;for(const S of g){const g=S.inboundRTP.id;f.add(g);let v=this.multiviewData[g];v&&this.multiviewKeySet.has(g)?v.stats.duration++:(v={bitrateAverager:new Hv,jitterAverager:new Hv,frameRateAverager:new Hv,freezeHistogram:new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),resolutionDurations:new zv,isRenderingEvents:[],statsOnSubscribed:new GT(this.configProvider),stats:{ssrc:S.inboundRTP.ssrc,startTime:Date.now(),duration:0,framesDecoded:[],bytesReceived:[],height:[],width:[]}},v.statsOnSubscribed.prepareCollectingStatsOnSubscribed(S.renderer?.msi),this.multiviewData[g]=v),v.statsOnSubscribed.captureStatsOnSubscribed(S.inboundRTP.framesDecoded,S.inboundRTP.bytesReceived,S.inboundRTP.frameHeight),v.bitrateAverager.captureSample(S.extensions?.bitrate),v.jitterAverager.captureSample(1e3*(S.inboundRTP.jitter??0)),v.frameRateAverager.captureSample(S.extensions.frameRateReceived),v.freezeHistogram.active=S.extensions?.isFrozen,S.inboundRTP.frameWidth&&S.inboundRTP.frameHeight&&v.resolutionDurations.captureSample(`${S.inboundRTP.frameWidth}x${S.inboundRTP.frameHeight}`);const C=S.renderer?.isRendering??!1;(!v.isRenderingEvents.length&&C||v.isRenderingEvents.length&&getLast(v.isRenderingEvents).isRendering!==C)&&arrayLimitedPush2(v.isRenderingEvents,{isRendering:C,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents),v.stats.frameRateAvg=round(v.frameRateAverager.avg),v.stats.bitrateAvg=round(v.bitrateAverager.avg,0),v.stats.bitrateMax=round(v.bitrateAverager.maxSample,0),v.stats.bitrateMinNonZero=round(v.bitrateAverager.minNonZeroSample),v.stats.freezeHistogram=v.freezeHistogram.counts,v.stats.freezeTimestamps=v.freezeHistogram.timestamps,v.stats.avgFreezeDuration=round(v.freezeHistogram.avgDuration),v.stats.totalFreezeDuration=v.freezeHistogram.totalDuration,v.stats.ongoingFreeze=v.freezeHistogram.active,v.stats.ongoingFreezeDuration=v.freezeHistogram.ongoingDuration,v.stats.numResolutionSwitches=v.resolutionDurations.changeCount,v.stats.rendererSize=`${S.renderer?.rendererSize?.width}x${S.renderer?.rendererSize?.height}`,v.stats.resolutionDurations=v.resolutionDurations.durations,v.stats.timeToFirstFrame=S.renderer?.timeToFirstFrame,v.stats.timeToFirstFrameSinceSubscriptionStart=S.renderer?.timeToFirstFrameSinceSubscriptionStart,v.stats.isRenderingEvents=v.isRenderingEvents,v.stats.statsOnSubscribed=v.statsOnSubscribed.videoStatsOnSubscribed,v.stats.msi=S.renderer?.msi,v.stats.rendererStates=S.renderer?.rendererStates,arrayLimitedPush2(v.stats.framesDecoded,S.inboundRTP.framesDecoded,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),arrayLimitedPush2(v.stats.bytesReceived,S.inboundRTP.bytesReceived,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),arrayLimitedPush2(v.stats.height,S.inboundRTP.frameHeight,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),arrayLimitedPush2(v.stats.width,S.inboundRTP.frameWidth,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples);const _=S.extensions?.macroblockRateStats??{};for(const g in _)v.stats[g]=round(_[g],0)}this.diagnostics.multiViewStats=Object.values(this.multiviewData).map((g=>g.stats)),this.multiviewKeySet=f}processAggregated(g){for(const f of["audio","video","sharing"])if(g[f])for(const S in g[f])this.processAggregatedModality(g,f,S)}processAggregatedModality(g,f,S){var v,C;const _=g[f]?.[S]?.length??0;_>0&&((v=this.aggregatedModalityStats)[f]??(v[f]={}),(C=this.aggregatedModalityStats[f])[S]??(C[S]=[]),_>1&&("audio"===f||"sharing"===f)&&this.diagnostics.addStatsError("webrtcStatistics:processAggregatedModality",`Multiple ${f} ${S} streams: ${_}`),this.statsAggregators[f][S].processSample(g[f][S],this.aggregatedModalityStats[f][S],this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),"sharing"!==f&&"video"!==f||"recv"!==S||this.processStatsOnSubscribed(g[f][S],f))}processStatsOnSubscribed(g,f){const S=new Set;for(const v of g)if(v.inboundRTP){const g=`${v.inboundRTP.id}x${v.renderer?.msi}`;let C=this.statsOnSubscribedData[f]?.[g];S.add(g),C||(C=new GT(this.configProvider),C.prepareCollectingStatsOnSubscribed(v.renderer?.msi),this.statsOnSubscribedData[f][g]=C,this.statsOnSubscribed[f].push(...C.videoStatsOnSubscribed)),C.captureStatsOnSubscribed(v.inboundRTP.framesDecoded,v.inboundRTP.bytesReceived)}clearObj(this.statsOnSubscribedData[f],S)}processMacroblockRateStats(g){if(!g?.length)return;let f=0,S=0;for(const v of g)f+=v.extensions?.macroblockRateReceived,S+=v.extensions?.macroblockRateDecoded;this.macroblockStatsTracker.captureSample(f,S),this.diagnostics.setTotalVideoRecvMblocksRates(this.macroblockStatsTracker.getReport())}},iI=M,nI=class{constructor(g,f,S,v){this.logger=g,this.configProvider=f,this.diagnostics=S,this.mediaManager=v,this.webrtcStats=new tI(this.configProvider,this.diagnostics),this.ssrcToRecvTrackMap=new Map,this.activeChannels={}}setAudioDecoderStatsProvider(g){this.audioDecoderStatsProvider=g}signalNoConnection(){this.webrtcStats.signalNoConnection()}processRawReport(g){this.diagnostics.latestRawReport=g;const f={loopTime:-1,fetchTime:-1,convertTime:-1,processingTime:-1,legacyProcessingTime:-1};try{let S=Jt(),v=S;const C=this.convertStatsReport(g);return C.perfCounters=f,S=Jt(),f.convertTime=S-v,v=S,this.webrtcStats.processStats(C),this.diagnostics.addStatsReport(C),S=Jt(),f.processingTime=S-v,C}catch(g){const f=stringifyObject(g);return this.logger.safe.error(`Error processing raw stats: ${f}`),void this.diagnostics.addStatsError("StatisticsGatherer:processRawReport",f)}}setSsrcTrackPair(g,f){null===f?this.ssrcToRecvTrackMap.delete(g):this.ssrcToRecvTrackMap.set(g,f)}convertStatsReport(g){const f={transports:this.processTransportStats(g)};return this.appendPcStats(g,f),this.appendSendMediaStats(g,f),this.appendRecvMediaStats(g,f),g["data-channel"]&&(f.data=Object.values(g["data-channel"])),f}processTransportStats(g){if(g.transport){const f={};for(const S in g.transport){const v=g.transport[S];if(f[S]=shallowClone(v),v.selectedCandidatePairId){const C=shallowClone(g["candidate-pair"][v.selectedCandidatePairId]);C.localCandidate=g["local-candidate"][C.localCandidateId],C.remoteCandidate=g["remote-candidate"][C.remoteCandidateId],f[S].selectedCandidatePair=C}v.localCertificateId&&g.certificate&&(f[S].localCertificate=g.certificate[v.localCertificateId]),v.remoteCertificateId&&g.certificate&&(f[S].remoteCertificate=g.certificate[v.remoteCertificateId])}return f}if(g["candidate-pair"]){const f={};for(const S in g["candidate-pair"]){const v=shallowClone(g["candidate-pair"][S]);v.selected&&(v.localCandidate=g["local-candidate"][v.localCandidateId],v.remoteCandidate=g["remote-candidate"][v.remoteCandidateId],f.faketransport={id:"faketransport",timestamp:v.timestamp,type:"transport",selectedCandidatePair:v,selectedCandidatePairId:v.id})}return f}}appendPcStats(g,f){let S="";g["peer-connection"]&&(Object.keys(g["peer-connection"]).forEach((g=>{""===S?S=g:(this.logger.safe.error(`Unexpected second peer connection stats id ${g}, also found ${S}`),this.diagnostics.addStatsError("StatisticsGatherer","Unexpected second peer connection stats"))})),f.peerConnection=g["peer-connection"][S])}appendSendMediaStats(g,f){var S,v,C,_;for(const T in g["outbound-rtp"]){const I=g["outbound-rtp"][T],b={outboundRTP:I};I.codecId&&g.codec&&(b.codec=g.codec[I.codecId]),Object.defineProperty(b,"transport",{value:f.transports[I.transportId??"faketransport"],configurable:!1,enumerable:!1}),I.remoteId&&g["remote-inbound-rtp"]&&(b.remoteInboundRTP=g["remote-inbound-rtp"][I.remoteId]),I.mediaSourceId&&g["media-source"]&&(b.mediaSource=g["media-source"][I.mediaSourceId]),I.trackId&&g.track&&(b.track=g.track[I.trackId]);const A=getEntityByLocalTrack(this.mediaManager,b.track?.trackIdentifier??b.mediaSource?.trackIdentifier,I.rid)??getEntityByLocalSSRC(this.mediaManager,I.ssrc,I.rid)??getMediaEntityByMid(this.mediaManager,b.outboundRTP.mid,I.rid);if(!A?.getLocalTrackId())continue;b.mediaEntity=A.serialize(),!b.mediaSource&&b.mediaEntity&&g["media-source"]&&(b.mediaSource=Object.values(g["media-source"]).find((g=>g.trackIdentifier===b.mediaEntity.localTrackId)));const P="video"===I.kind?"sharing"===A?.getModality()?"sharing":"video":I.kind;if((S=this.activeChannels)[P]??(S[P]={}),(v=this.activeChannels[P]).send??(v.send={}),hasSendDirectionality(this.diagnostics.getObjectRef().negotiation.activeModalities?.[P])){if(f[P]||(f[P]={}),f[P].send||(f[P].send=[]),"video"===I.kind){const g=getRequestedCapabilitiesBySsrc(this.diagnostics,P,I.ssrc)??getRequestedCapabilitiesBySsrc(this.diagnostics,P,0);g&&(b.requestedCapabilities=g);const S=getAppliedCapabilitiesBySsrc(this.diagnostics,P,I.ssrc)??getAppliedCapabilitiesBySsrc(this.diagnostics,P,0);S&&(b.appliedCapabilities=S);const v=f[P].send.find((g=>g.outboundRTP.trackId===b.outboundRTP.trackId));if(v){const g=parseInt(v.outboundRTP.rid,10)>parseInt(b.outboundRTP.rid,10);if(!v.altLayouts&&g&&(v.altLayouts=[]),g)v.altLayouts.push(b);else{b.altLayouts=[],b.altLayouts.push(v);const g=f[P].send.indexOf(v);f[P].send[g]=b}continue}}this.activeChannels[P].send[I.id]=b,f[P].send.push(b)}else this.activeChannels[P].send[I.id]&&"sharing"!==P&&(f.inactiveTracks??(f.inactiveTracks={}),(C=f.inactiveTracks)[P]??(C[P]={}),(_=f.inactiveTracks[P]).send??(_.send=[]),f.inactiveTracks[P].send.push(this.activeChannels[P].send[I.id]))}}appendRecvMediaStats(g,f){var S,v,C,_;const T=this.diagnostics.getObjectRef().subscriptionManager?.subscribedTrackIds;for(const I in g["inbound-rtp"]){const b=g["inbound-rtp"][I],A={inboundRTP:b};b.codecId&&g.codec&&(A.codec=g.codec[b.codecId]),"audio"===b.kind&&A.inboundRTP.ssrc===this.audioDecoderStatsProvider?.ssrc&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("replacing recv audio stats with custom audio decoder stats"),A.codec||(A.codec={transportId:b.transportId??"faketransport",id:"fakeCodec",payloadType:999,timestamp:b.timestamp,type:"codec",mimeType:"unk"}),A.codec.mimeType=this.audioDecoderStatsProvider.codecName,A.inboundRTP=(0,iI.merge)(A.inboundRTP,this.audioDecoderStatsProvider.getWebRtcCompatibleStats()),A.customHealerStats=this.audioDecoderStatsProvider.getWasmStats()),f.transports[b.transportId??"faketransport"]&&Object.defineProperty(A,"transport",{value:f.transports[b.transportId??"faketransport"],configurable:!1,enumerable:!1}),b.remoteId&&g["remote-outbound-rtp"]&&(A.remoteOutboundRTP=g["remote-outbound-rtp"][b.remoteId]);const P=A.inboundRTP.trackIdentifier??this.ssrcToRecvTrackMap.get(b.ssrc);if(b.trackId||P){b.trackId&&g.track?A.track=g.track[b.trackId]:P&&(A.track={id:"ssrcToTrackId",kind:b.kind,timestamp:b.timestamp,type:"track",trackIdentifier:P});const f=getRendererDiagnosticsByTrack(this.diagnostics,A.track?.trackIdentifier);f&&(A.renderer=f)}const R=getEntityByRemoteTrack(this.mediaManager,A.track?.trackIdentifier)??getEntityByRemoteSSRC(this.mediaManager,b.ssrc);if(!R)continue;A.mediaEntity=R.serialize();const M="video"===b.kind&&A.track?"sharing"===R?.getModality()?"sharing":"video":b.kind;(S=this.activeChannels)[M]??(S[M]={}),(v=this.activeChannels[M]).recv??(v.recv={}),"video"!==b.kind||T.some((g=>g&&g===A.track?.trackIdentifier))?hasReceiveDirectionality(this.diagnostics.getObjectRef().negotiation.activeModalities?.[M])&&(f[M]||(f[M]={}),f[M].recv||(f[M].recv=[]),this.activeChannels[M].recv[b.id]=A,f[M].recv.push(A)):this.activeChannels[M].recv[b.id]&&"sharing"!==M&&(f.inactiveTracks??(f.inactiveTracks={}),(C=f.inactiveTracks)[M]??(C[M]={}),(_=f.inactiveTracks[M]).recv??(_.recv=[]),f.inactiveTracks[M].recv.push(this.activeChannels[M].recv[b.id]))}}};function verifyRidIfPresent(g,f){return!f||g.getSimulcastContext()?.activeRids.map(String).some((g=>g===f))}function getEntityByRemoteSSRC(g,f){return g.getMediaEntities().find((g=>g.getRemoteSsrc()===f))}function getEntityByRemoteTrack(g,f){const S=g.getMediaEntities();return void 0!==f?S.find((g=>g.getRemoteTrackId()===f)):void 0}function getEntityByLocalSSRC(g,f,S){return g.getMediaEntities().find((g=>g.getLocalSsrc()===f&&verifyRidIfPresent(g,S)))}function getEntityByLocalTrack(g,f,S){const v=g.getMediaEntities();return f?v.find((g=>g.getLocalTrackId()===f&&verifyRidIfPresent(g,S))):void 0}function getRequestedCapabilitiesBySsrc(g,f,S){const v=g.getObjectRef().qualityManager;return"video"===f?v?.currentVideoSsrcRequestedCapabilities[`${S}`]:"sharing"===f?v?.currentSharingSsrcRequestedCapabilities[`${S}`]:void 0}function getAppliedCapabilitiesBySsrc(g,f,S){const v=g.getObjectRef().qualityManager;return"video"===f?v?.currentVideoSsrcAppliedCapabilities[`${S}`]:"sharing"===f?v?.currentSharingSsrcAppliedCapabilities[`${S}`]:void 0}function getRendererDiagnosticsByTrack(g,f){return g.getObjectRef().remoteVideoManager?.renderers.find((g=>g.trackId===f))}function getMediaEntityByMid(g,f,S){const v=g.getMediaEntities();return f?v.find((g=>g.getMid()===f&&verifyRidIfPresent(g,S))):void 0}var rI=class{constructor(){this.googCandidatePair={},this.ssrc={},this.googComponent={},this.VideoBwe={bweforvideo:{}}}},sI=class{constructor(){this.statistics=new rI,this.statsDiffMap=new Map,this.ssrcTrackMap=new Map}build(g){return this.statistics=new rI,this.constructGoogCandidatePair(g),this.constructGoogSsrc(g),this.constructGoogComponent(g),this.constructDataChannel(g),this.constructBwe(g),this.statistics}setSsrcTrackPair(g,f){null===f?this.ssrcTrackMap.delete(g):this.ssrcTrackMap.set(g,f)}setAudioDecoderStatsProvider(g){this.audioDecoderStatsProvider=g}constructGoogSsrc(g){const f={};if(g.hasOwnProperty("outbound-rtp")){const S=g["outbound-rtp"];Object.keys(S).forEach((v=>{const C=`ssrc_${S[v].ssrc}_send`,_=this.constructSendSsrc(g,S[v]);f[C]=_}))}if(g.hasOwnProperty("inbound-rtp")){const S=g["inbound-rtp"];Object.keys(S).forEach((v=>{const C=`ssrc_${S[v].ssrc}_recv`,_=this.constructRecvSsrc(g,S[v]);f[C]=_}))}this.statistics.ssrc=f}constructSendSsrc(g,f){const S=f.trackId?g.track[f.trackId]:null,v=f.mediaSourceId?g["media-source"][f.mediaSourceId]:null,C=g["remote-inbound-rtp"]?.[f.remoteId],_=`ssrc_${f.ssrc}_send`,T=v?.trackIdentifier??S?.trackIdentifier??this.ssrcTrackMap.get(f.ssrc);let I={id:_,ssrc:f.ssrc,mediaType:f.mediaType??f.kind,bytesSent:f.bytesSent,bytesSentDiff:this.calculateDiff(_,f.bytesSent,4),packetsSent:f.packetsSent,packetsLost:C?.packetsLost,jitter:C?.jitter,googRtt:this.getRtt(C),googCodecName:this.getCodec(g,f.codecId),transportId:f.transportId,googTrackId:T};return"audio"===I.mediaType&&(I={...I,...this.constructAudioSendSsrc(f,v)}),"video"===I.mediaType&&(I={...I,...this.constructVideoSendSsrc(f,v,_,S)}),removeUndefinedFields(I)}constructAudioSendSsrc(g,f){return{audioInputLevel:f?.audioLevel,totalAudioEnergy:f?.totalAudioEnergy,fecPacketsSent:g.fecPacketsSent}}constructVideoSendSsrc(g,f,S,v){return{framesEncoded:g.framesEncoded,googFrameRateEncoded:this.calculateDiff(S,g.framesEncoded,2),googFrameRateSent:this.calculateDiff(S,g.framesSent??v?.framesSent,1),googFrameRateInput:f?.framesPerSecond,googFrameHeightSent:g.frameHeight??v?.frameHeight,googFrameWidthSent:g.frameWidth??v?.frameWidth,googFrameHeightInput:f?.height,googFrameWidthInput:f?.width,hugeFramesSent:g.hugeFramesSent??v?.hugeFramesSent,keyFramesEncoded:g.keyFramesEncoded,qpSum:g.qpSum,qp:this.calculateDiff(S,g.qpSum,8),googPlisReceived:g.pliCount,googFirsReceived:g.firCount,googNacksReceived:g.nackCount,qualityLimitationDurations:g.qualityLimitationDurations,qualityLimitationReason:g.qualityLimitationReason,qualityLimitationResolutionChanges:g.qualityLimitationResolutionChanges,codecImplementationName:g.encoderImplementation,rid:g.rid,encodeTime:g.totalEncodeTime&&Math.round(1e3*this.calculateDiff(S,g.totalEncodeTime,6))}}constructRecvSsrc(g,f){const S=f.trackId?g.track[f.trackId]:null,v=`ssrc_${f.ssrc}_recv`,C=f.trackIdentifier??S?.trackIdentifier??this.ssrcTrackMap.get(f.ssrc);let _={id:v,ssrc:f.ssrc,mediaType:f.mediaType??f.kind,bytesReceived:f.bytesReceived,bytesReceivedDiff:this.calculateDiff(v,f.bytesReceived,5),packetsReceived:f.packetsReceived,packetsLost:f.packetsLost,jitter:f.jitter,googJitterBufferMs:f.jitterBufferEmittedCount&&Math.round(f.jitterBufferDelay/f.jitterBufferEmittedCount*1e3),googCodecName:this.getCodec(g,f.codecId),googTrackId:C,transportId:f.transportId};return"audio"===_.mediaType&&(_={..._,...this.constructAudioRecvSsrc(f,S)}),"video"===_.mediaType&&(_={..._,...this.constructVideoRecvSsrc(f,v,S)}),removeUndefinedFields(_)}constructAudioRecvSsrc(g,f){const S=this.audioDecoderStatsProvider?.ssrc===g.ssrc?this.audioDecoderStatsProvider?.getWebRtcCompatibleStats():g,v={audioOutputLevel:S.audioLevel??f?.audioLevel,totalAudioEnergy:S.totalAudioEnergy??f?.totalAudioEnergy,concealedSamples:S.concealedSamples,silentConcealedSamples:S.silentConcealedSamples,totalSamplesReceived:S.totalSamplesReceived,healedRatio:S.totalSamplesReceived&&(S.concealedSamples-S.silentConcealedSamples)/S.totalSamplesReceived,fecPacketsReceived:S.fecPacketsReceived,fecPacketsDiscarded:S.fecPacketsDiscarded,packetsDiscarded:S.packetsDiscarded};if(this.audioDecoderStatsProvider?.ssrc===g.ssrc){v.googJitterBufferMs=S.jitterBufferEmittedCount&&Math.round(S.jitterBufferDelay/S.jitterBufferEmittedCount*1e3),v.googCodecName=this.audioDecoderStatsProvider.codecName;const g=this.audioDecoderStatsProvider.getDecoderStats();v.pushCount=g.pushCount,v.pushErrCount=g.pushErrCount,v.pullCount=g.pullCount,v.pullErrCount=g.pullErrCount}return v}constructVideoRecvSsrc(g,f,S){return{framesDecoded:g.framesDecoded,googFrameRateDecoded:this.calculateDiff(f,g.framesDecoded,3),googFrameRateReceived:this.calculateDiff(f,g.framesReceived??S?.framesReceived,0),googFrameHeightReceived:g.frameHeight??S?.frameHeight,googFrameWidthReceived:g.frameWidth??S?.frameWidth,keyFramesDecoded:g.keyFramesDecoded,googPlisSent:g.pliCount,googFirsSent:g.firCount,googNacksSent:g.nackCount,codecImplementationName:g.decoderImplementation,decodeTime:g.totalDecodeTime&&Math.round(1e3*this.calculateDiff(f,g.totalDecodeTime,7))}}constructGoogCandidatePair(g){const f=g["candidate-pair"];f&&Object.keys(f).forEach((S=>{const v=this.constructPair(g,f[S]);this.statistics.googCandidatePair[v.id]=v}))}constructPair(g,f){const S=g["local-candidate"][f.localCandidateId],v=g["remote-candidate"][f.remoteCandidateId];return removeUndefinedFields({bytesReceived:f.bytesReceived,bytesSent:f.bytesSent,googTransportType:S.protocol,googRtt:f.currentRoundTripTime?Math.round(1e3*f.currentRoundTripTime):void 0,googLocalAddress:`${S.ip?S.ip:S.address}:${S.port}`,googLocalCandidateType:S.candidateType,localRelayProtocol:S.relayProtocol,localNetworkType:S.networkType,googRemoteAddress:`${v.ip?v.ip:v.address}:${v.port}`,googRemoteCandidateType:v.candidateType,googActiveConnection:f.nominated,requestsReceived:f.requestsReceived,requestsSent:f.requestsSent,responsesReceived:f.responsesReceived,responsesSent:f.responsesSent,consentRequestsSent:f.consentRequestsSent,id:f.id,remoteCandidateId:f.remoteCandidateId,localCandidateId:f.localCandidateId,googWritable:f.writable,selected:f.selected,packetsDiscardedOnSend:f.packetsDiscardedOnSend})}constructGoogComponent(g){g.transport&&Object.keys(g.transport).forEach((f=>{this.statistics.googComponent[f]={id:f,selectedCandidatePairId:g.transport[f].selectedCandidatePairId}}))}constructDataChannel(g){if(!g.hasOwnProperty("data-channel"))return;const f=g["data-channel"];this.statistics.data=Object.keys(f).map((g=>{const S=f[g];return{bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,dataChannelIdentifier:S.dataChannelIdentifier,label:S.label,messagesReceived:S.messagesReceived,messagesSent:S.messagesSent,protocol:S.protocol,state:S.state,timestamp:S.timestamp,type:S.type}}))}constructBwe(g){const f=Object.values(g["outbound-rtp"]??{})?.find((g=>{const f=g.mediaType??g.kind;return"audio"===f||"video"===f}));if(!f)return;const S=g.transport?.[f.transportId];if(!S)return;const v=g["candidate-pair"]?.[S.selectedCandidatePairId];if(!v)return;const C={googAvailableSendBandwidth:v.availableOutgoingBitrate,googAvailableReceiveBandwidth:v.availableIncomingBitrate};this.statistics.VideoBwe.bweforvideo=removeUndefinedFields(C)}getRtt(g){const f=g?.roundTripTime;return f?Math.round(1e3*f):void 0}getCodec(g,f){if(f&&g.codec&&g.codec[f])return g.codec[f].mimeType.split("/").pop()}calculateDiff(g,f,S){if(void 0===f)return;let v=f;const C=this.statsDiffMap.has(g)?this.statsDiffMap.get(g):new Map;if(C.has(S)){const g=C.get(S);g<=f&&(v=f-g)}return C.set(S,f),this.statsDiffMap.set(g,C),isNaN(v)?void 0:v}},aI=M,oI=M,lI=class{constructor(g){this.healedRatio=0,this.healedRatioMax=0,this.healedRatioDuration=0,this.healedRatioTotal=0,this.totalSamplesReceivedDiff=0;const f=g.config;this.networkDetectionDuration=f.webrtcStatNetworkDetectionDuration,this.networkRecvQualityDiagnostics=f.networkRecvQualityDiagnostics,this.networkRecvQualityDiagnostics&&(this.healedRatioAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesDiffAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesDiffAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedDiffAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize))}captureHealedRatioSamples(g,f,S){!g||!f||!S||g.length<=this.networkDetectionDuration||f.length<=this.networkDetectionDuration||S.length<=this.networkDetectionDuration||this.setHealedRatioPerDuration(g,f,S)}getHealedRatioMax(){return this.healedRatioMax}getHealedRatioAvg(){return this.healedRatioDuration?this.healedRatioTotal/this.healedRatioDuration:0}getHealedRatio(){return this.healedRatio}getTotalSamplesReceivedDiff(){return this.totalSamplesReceivedDiff}setHealedRatioPerDuration(g,f,S){const v=-1-this.networkDetectionDuration,C=Math.max((0,oI.last)(g)-(0,oI.nth)(g,v),0),_=Math.max((0,oI.last)(f)-(0,oI.nth)(f,v),0);this.totalSamplesReceivedDiff=Math.max((0,oI.last)(S)-(0,oI.nth)(S,v),0),0!==this.totalSamplesReceivedDiff&&(this.healedRatio=(C-_)/this.totalSamplesReceivedDiff,this.healedRatioDuration++,this.healedRatioTotal+=this.healedRatio,this.healedRatioMax=Math.max(this.healedRatioMax,this.healedRatio),this.networkRecvQualityDiagnostics&&(this.concealedSamplesAccumulator.add((0,oI.last)(g)),this.silentConcealedSamplesAccumulator.add((0,oI.last)(f)),this.totalSamplesReceivedAccumulator.add((0,oI.last)(S)),this.concealedSamplesDiffAccumulator.add(C),this.silentConcealedSamplesDiffAccumulator.add(_),this.totalSamplesReceivedDiffAccumulator.add(this.totalSamplesReceivedDiff),this.healedRatioAccumulator.add(this.healedRatio)))}getDiagnostics(g){return{quality:(0,oI.last)(g),qualityLevels:g,concealedSamples:this.concealedSamplesAccumulator.items,silentConcealedSamples:this.silentConcealedSamplesAccumulator.items,totalSamplesReceived:this.totalSamplesReceivedAccumulator.items,concealedSamplesDiff:this.concealedSamplesDiffAccumulator.items,silentConcealedSamplesDiff:this.silentConcealedSamplesDiffAccumulator.items,totalSamplesReceivedDiff:this.totalSamplesReceivedDiffAccumulator.items,healedRatio:this.healedRatioAccumulator.items.map((g=>round(g)))}}},cI=class{constructor(g){this.configProvider=g,this.audioAnalyzers=new Map,this.jitterBufferDuration=0,this.jitterBufferTotal=0,this.jitterTotal=0,this.jitterDuration=0,this.rttDuration=0,this.rttTotal=0,this.rttMax=0,this.jitterMax=0}captureJitterBuffer(g){this.jitterBufferDuration+=qt.TIME_INTERVAL.SEC_1,this.jitterBufferTotal+=g}captureJitter(g){const f=1e3*g;this.jitterTotal+=f,this.jitterMax=Math.max(f,this.jitterMax),this.jitterDuration+=qt.TIME_INTERVAL.SEC_1}getJitterAvg(){return this.jitterDuration?round(this.jitterTotal/this.jitterDuration):0}getAvgJitterBuffer(){return this.jitterBufferDuration?Math.round(this.jitterBufferTotal/this.jitterBufferDuration):0}captureRtt(g){if(null!==g){const f=parseInt(g);this.rttDuration+=qt.TIME_INTERVAL.SEC_1,this.rttTotal+=f,this.rttMax=Math.max(this.rttMax,f)}}getAvgRtt(){return this.rttDuration?round(this.rttTotal/this.rttDuration):0}getMaxRtt(){return this.rttMax}getJitterMax(){return this.jitterMax}updateSendStream(g,f){if(!this.configProvider.config.useAudioAnalyzer)return;const S=this.audioAnalyzers.get(f);S&&(S.dispose(),this.audioAnalyzers.delete(f)),g?.rawStream?.getAudioTracks().length&&this.audioAnalyzers.set(f,new My(g.rawStream))}getInputLevel(g){const f=this.audioAnalyzers.get(g);return f?.getInputLevelNormalized()}},dI=class{constructor(g,f){this.dropBadBandwidth=g,this.dropGoodBandwidth=f,this.dropDurationCounts={},Object.keys(qt.HISTOGRAM_BATCH).forEach((g=>{this.dropDurationCounts[g]=0}))}recordSendBandwidth(g){this.currentDropDuration&&g<this.dropGoodBandwidth||g<this.dropBadBandwidth?this.initiateDrop():this.currentDropDuration&&g>this.dropGoodBandwidth&&this.recoverDrop()}getReport(){const g=shallowClone(this.dropDurationCounts);return this.currentDropDuration&&(g.ongoingDuration=this.currentDropDuration),g}initiateDrop(){this.currentDropDuration?this.currentDropDuration++:this.currentDropDuration=1}recoverDrop(){for(const g of Object.keys(qt.HISTOGRAM_BATCH))if(this.currentDropDuration<=qt.HISTOGRAM_BATCH[g]){this.dropDurationCounts[g]+=1,this.currentDropDuration=0;break}}},hI=M,uI=class{constructor(g,f,S,v){this.lowThreshold=g,this.highThreshold=f,this.isLowerBetter=S,this.curInLowerRange=S,this.stateTracker=new gI(v)}onSample(g,f){let S=this.curInLowerRange;this.curInLowerRange?g>this.highThreshold&&(S=!1):g<this.lowThreshold&&(S=!0);const v=this.stateTracker.onNewState(this.getQuality(S),f);return v!==this.getQuality(this.curInLowerRange)&&(this.curInLowerRange=S),v}getQuality(g){return g===this.isLowerBetter?"Good":"Bad"}},gI=class{constructor(g){this.stickinessTime=g}onNewState(g,f){return"Good"!==g&&"Bad"!==g?this.curState:0===this.stickinessTime?g:g===this.curState?(this.stickTimerStarted=0,this.curState):("Bad"===this.curState?0===this.stickTimerStarted?this.stickTimerStarted=f:f-this.stickTimerStarted>this.stickinessTime&&(this.curState=g,this.stickTimerStarted=0):(this.curState=g,this.stickTimerStarted=0),this.curState)}},pI=class{constructor(g,f,S,v){this.stateProcessor=g,this.windowSize=f,this.extendedWindowSize=S,this.addDiagnosticData=v,this.dataAccumulator=new Uv(S),this.avgAccumulator=new Uv(S)}getLatestSendQuality(g,f,S){if(this.dataAccumulator.add(g),this.dataAccumulator.items.length>=this.windowSize){const g=this.dataAccumulator.items.slice(-this.windowSize),S=(0,hI.mean)(g);return this.addDiagnosticData&&this.avgAccumulator.add(S),this.stateProcessor.onSample(S,f)}return S}getData(){return this.dataAccumulator.items.map((g=>round(g)))}getAggregatedData(){return this.avgAccumulator.items.map((g=>round(g)))}},mI=class{constructor(g,f,S){this.configProvider=g,this.newStatsApi=f,this.webrtcHealedRatio=S,this.sendAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiffAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostDiffAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.totalAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendQualityAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiagnosticsEnabled=this.configProvider.config.networkSendQualityDiagnostics,this.recvDiagnosticsEnabled=this.configProvider.config.networkRecvQualityDiagnostics,this.recvQualityAccumulator=new Uv(this.configProvider.config.webrtcHealedRatioExtendedWindowSize);const v=Number(this.configProvider.config.webrtcStatNetworkDetectionHysteresis);this.networkDetectionBadLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionBadLevel)+v/2,this.networkDetectionBadLevelLow=this.networkDetectionBadLevelHigh-v,this.networkDetectionGoodLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionGoodLevel)+v/2,this.networkDetectionGoodLevelLow=this.networkDetectionGoodLevelHigh-v;const C=new uI(g.config.webrtcJitterLowThreshold,g.config.webrtcJitterHighThreshold,!0,g.config.webrtcJitterSticknessTime),_=new uI(g.config.webrtcLossRateLowThreshold,g.config.webrtcLossRateHighThreshold,!0,g.config.webrtcLossRateSticknessTime);this.jitterCalculator=new pI(C,g.config.webrtcJitterWindowSize,g.config.webrtcJitterExtendedWindowSize,this.sendDiagnosticsEnabled),this.lossRateCalculator=new pI(_,g.config.webrtcLossRateWindowSize,g.config.webrtcLossRateExtendedWindowSize,this.sendDiagnosticsEnabled)}calculateNetworkSendQualityLevel(g,f,S,v){if(!g||!f)return{quality:v};if(g.length<2||f.length<2||(0,hI.last)(g)<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return{quality:v};const C=Date.now(),_=(0,hI.last)(S),T=this.jitterCalculator.getLatestSendQuality(_,C,v),[I,b]=g.slice(-2),[A,P]=f.slice(-2),R=this.getLossRate(b,I,P,A),M=this.lossRateCalculator.getLatestSendQuality(R,C,v),w="Good"===T&&"Good"===M?"Good":"Bad";return this.sendDiagnosticsEnabled&&(this.sendAccumulator.add(b),this.lostAccumulator.add(P),this.sendQualityAccumulator.add(w)),this.sendDiagnosticsEnabled?{quality:w,packetsSend:this.sendAccumulator.items,packetsLost:this.lostAccumulator.items,packetsSendDiff:this.sendDiffAccumulator.items,packetsLostDiff:this.lostDiffAccumulator.items,lossRates:this.lossRateCalculator.getData(),lossRatesAggregated:this.lossRateCalculator.getAggregatedData(),jitter:this.jitterCalculator.getData(),jitterAggregated:this.jitterCalculator.getAggregatedData(),qualityLevels:this.sendQualityAccumulator.items}:{quality:w}}calculateNetworkRecvQualityLevel(g){if(this.newStatsApi){const f=g;return this.calculateNetworkRecvQualityLevelNewStatsApi(f.concealedSamples,f.silentConcealedSamples,f.totalSamplesReceived,f.oldNetworkLevel)}{const f=g;return this.calculateNetworkRecvQualityLevelLegacyStatsApi(f.googDecodingCTN,f.googDecodingPLC,f.oldNetworkLevel)}}calculateNetworkRecvQualityLevelLegacyStatsApi(g,f,S){const v=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!g||!f||g.length<2*v)return{quality:S};let C=g.length-1-v;const _=g[g.length-1];for(;C>=0&&_-g[C]<100*v;)C--;if(C<0)return{quality:S};const T=_-g[C],I=f[f.length-1]-f[C];if(T<=0)return{quality:S};const b=I/T;return{quality:this.getRecvQuality(b,S)}}calculateNetworkRecvQualityLevelNewStatsApi(g,f,S,v){const C=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!g||g.length<=C||!f||f.length<=C||!S||S.length<=C)return{quality:v};if((0,hI.last)(S)<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality)return{quality:v};if(0===this.webrtcHealedRatio.getTotalSamplesReceivedDiff())return{quality:v};const _=this.webrtcHealedRatio.getHealedRatio(),T=this.getRecvQuality(_,v);if(this.recvDiagnosticsEnabled){this.recvQualityAccumulator.add(T);return this.webrtcHealedRatio.getDiagnostics(this.recvQualityAccumulator.items)}return{quality:T}}getRecvQuality(g,f){return g<this.networkDetectionGoodLevelLow?"Good":g<this.networkDetectionGoodLevelHigh?"Good"===f?"Good":"Poor":g<this.networkDetectionBadLevelLow?"Poor":g<this.networkDetectionBadLevelHigh?"Bad"===f?"Bad":"Poor":"Bad"}getLossRate(g,f,S,v){const C=g-f,_=S-v,T=C+_;return this.sendDiagnosticsEnabled&&(this.sendDiffAccumulator.add(C),this.lostDiffAccumulator.add(_),this.totalAccumulator.add(T)),T>0?_/T:0}},fI=class{constructor(g){this.configProvider=g,this.qualityLimitationReasonEvents=[]}setQualityLimitationReason(g){this.lastQualityLimitationReason!==g&&this.qualityLimitationReasonEvents.push({event:g,startTime:Date.now(),endTime:Date.now()}),this.qualityLimitationReasonEvents.length>this.configProvider.config.maxStoredQualityLimitationReasonEvents&&this.qualityLimitationReasonEvents.shift(),this.lastQualityLimitationReason=g}getQualityLimitationReasonEvents(){return this.qualityLimitationReasonEvents.reduce(((g,f,S)=>"none"===f.event?g:[...g,{...f,endTime:this.qualityLimitationReasonEvents[S+1]?.startTime??Date.now()}]),[])}},SI=class{constructor(){this.bitrateData={[qt.MEDIA_DIRECTION.SEND]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0,allocateBW:0,allocateBWSamples:0},[qt.MEDIA_DIRECTION.RECV]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0}}}captureSample(g,f){const S=Date.now()/1e3;if(0!==this.bitrateData[g].lastTimestamp&&f>this.bitrateData[g].lastBytes){const v=S-this.bitrateData[g].lastTimestamp,C=8*(f-this.bitrateData[g].lastBytes)/v;this.onBitrateSample(g,C)}this.bitrateData[g].lastTimestamp=S,this.bitrateData[g].lastBytes=f}getMax(g){return Math.round(this.bitrateData[g].maxSample)}getAvg(g){return 0===this.bitrateData[g].nSamples?0:Math.round(this.bitrateData[g].bitrateTotal/this.bitrateData[g].nSamples)}stopCapture(g){this.bitrateData[g].lastBytes=0,this.bitrateData[g].lastTimestamp=0}onBitrateSample(g,f){f>this.bitrateData[g].maxSample&&(this.bitrateData[g].maxSample=f),this.bitrateData[g].bitrateTotal+=f,this.bitrateData[g].nSamples++}captureAllocateBandwidth(g){if(g){const f=parseInt(g[g.length-1]);this.bitrateData[qt.MEDIA_DIRECTION.SEND].allocateBW+=f,this.bitrateData[qt.MEDIA_DIRECTION.SEND].allocateBWSamples+=1}}getAllocateBandwidthAvg(){const g=this.bitrateData[qt.MEDIA_DIRECTION.SEND].allocateBW,f=this.bitrateData[qt.MEDIA_DIRECTION.SEND].allocateBWSamples;if(g>0&&f>0)return Math.floor(g/f)}},vI=class{constructor(g,f){this.maxAppliedCapabilitiesCount=f,this.events=[],this.events.push({eventType:"req",timestamp:Date.now(),capabilities:g.capabilities,isSimulcast:g.isSimulcastEnabled})}setMaxCapabilitiesApplied(g){this.events.push({eventType:"app",timestamp:Date.now(),capabilities:g.capabilities,error:g.error?`${g.error}`:"none"}),this.maxAppliedCapabilitiesCount&&this.events.length>this.maxAppliedCapabilitiesCount+1&&this.events.splice(1,1)}getEvents(){return this.events}},CI=class{constructor(g,f){this.configProvider=g,this.logger=f,this.resolutionChangeRequestRecords={},this.currentResolutionsByRid={},this.resolutionChangeCounterByRid={},this.events=[],this.errors=[]}setMaxCapabilitesRequested(g){const f=new vI(g,this.configProvider.config.webrtcLastAppliedVideoCapabilitiesCount);this.events.push({causeId:g.causeId,seq:f}),this.recordResolutionChange(g),this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.length>this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.shift()}setMaxCapabilitesApplied(g){const f=this.events.find((f=>f.causeId===g.causeId));f?(f.seq.setMaxCapabilitiesApplied(g),g.error&&this.errors.push(f)):this.logger.safe.warn(`Requested capabilities with id ${g.causeId} not found`)}getEvents(){return this.events.map((g=>({causeId:g.causeId,events:g.seq.getEvents()})))}getErrors(){return this.errors.map((g=>({causeId:g.causeId,events:g.seq.getEvents()})))}getResolutionRecords(){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo)return{req:this.resolutionChangeRequestRecords,count:this.resolutionChangeCounterByRid}}recordResolutionChange(g){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo){const f=Object.keys(this.currentResolutionsByRid),getRid=g=>g.rid||"default";[...f,...g.capabilities.map((g=>getRid(g)))].forEach((f=>{const S=g.capabilities.find((g=>getRid(g)===f)),v=this.currentResolutionsByRid[f]||0,C=S?.maxFs||0;if(v===C)return;this.resolutionChangeRequestRecords[f]||(this.resolutionChangeRequestRecords[f]=[],this.resolutionChangeCounterByRid[f]=0);const _=this.resolutionChangeRequestRecords[f].find((g=>g.from===v&&g.to===C));_?_.counter++:this.resolutionChangeRequestRecords[f].push({from:v,to:C,counter:1}),this.currentResolutionsByRid[f]=C,this.resolutionChangeCounterByRid[f]++}))}}},yI=class{constructor(){this.delayCur=[],this.delayTotal=0,this.delayEventCount=0}analyzeDelay(g,f){if(f&&""!==f){this.delayCur.length===g&&this.delayCur.shift();const S=parseInt(f);this.delayCur.push(S),this.delayTotal+=S,this.delayEventCount+=qt.TIME_INTERVAL.SEC_1}}getDelayCur(){if(this.delayCur.length>0){const g=this.delayCur.reduce(((g,f)=>g+f))/this.delayCur.length;return g<0?0:g}}getDelayAvg(){if(this.delayEventCount>0&&this.delayTotal>0){const g=this.delayTotal/this.delayEventCount;return g<0?0:g}}},EI=class{constructor(g,f){this.configProvider=g,this.startTime=f,this.recvTotalFreezeDuration=-1,this.recvFreezeDurations=[],this.recvFreezeIsOngoing=!1,this.recvCurrentFreezeDuration=0,this.recvFreezeCount=0,this.receiveFreezeDurationCounts={},this.longestRecvFreezeDuration=0,this.sendCameraFreezeIntervalsCount=0,this.previousInputFrame=0,this.recvCurrentFreezeStartTimestamp=0,this.receiveFreezeDurationTimestamps={},this.finalFreezeIsOngoing=!1,this.finalRecvCurrentFreezeDuration=0,this.mediaStarted=!1,this.lastBytesRecv=0,this.currentLowBitrateDuration=0,Object.keys(qt.HISTOGRAM_BATCH).forEach((g=>{this.receiveFreezeDurationCounts[g]=0,this.receiveFreezeDurationTimestamps[g]=[]}))}gatherFreezeData({frameRateDecoded:g,frameRateRecv:f,bytesReceived:S,mediaType:v}){if(g){const C=parseInt(g[g.length-1],10),_=f?.length>0?parseInt(f[f.length-1],10):void 0;void 0!==S&&"ScreenShare"!==v&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&!this.configProvider.config.isRenderingBasedOnRawStatistics&&this.calculateBitrate(S,C),-1===this.recvTotalFreezeDuration&&(this.recvTotalFreezeDuration=0),C>0&&(this.mediaStarted=!0),0!==C&&0!==_||!this.mediaStarted?C>0&&(void 0===_||_>0)&&this.recvFreezeIsOngoing&&this.stopRecvDataGathering(!1):(this.recvFreezeIsOngoing||(this.recvCurrentFreezeStartTimestamp=Date.now()-this.startTime),this.recvFreezeIsOngoing=!0,this.recvCurrentFreezeDuration+=qt.TIME_INTERVAL.SEC_1,this.recvTotalFreezeDuration+=qt.TIME_INTERVAL.SEC_1)}}getIsRendering(g){return this.recvCurrentFreezeDuration<g&&this.currentLowBitrateDuration<g&&this.mediaStarted}detectCaptureFreeze(g){if(g){const f=parseInt(g[g.length-1],10);this.previousInputFrame>0&&0===f&&(this.sendCameraFreezeIntervalsCount+=1),this.previousInputFrame=f}}getSendCameraFreezeIntervals(){return this.sendCameraFreezeIntervalsCount>0?this.sendCameraFreezeIntervalsCount:void 0}stopRecvDataGathering(g=!0){this.finalFreezeIsOngoing=this.recvFreezeIsOngoing,this.recvFreezeIsOngoing=!1,g&&(this.mediaStarted=!1),this.recvCurrentFreezeDuration>0&&(this.populateLongestRecvFreezeDuration(),this.populateRecvFreezeDurationCounts(),this.recvFreezeDurations.push(this.recvCurrentFreezeDuration),this.recvFreezeCount+=1),this.finalRecvCurrentFreezeDuration=this.recvCurrentFreezeDuration,this.recvCurrentFreezeDuration=0}getRecvFreezeDurationCounts(){return this.recvFreezeCount>0?JSON.stringify(this.receiveFreezeDurationCounts):void 0}getRecvFreezeDurationTimestamps(g){if(0===this.recvFreezeCount)return;const f={};return Object.keys(this.receiveFreezeDurationTimestamps).forEach((S=>{const v=this.receiveFreezeDurationTimestamps[S].length;f[S]=v>g?this.receiveFreezeDurationTimestamps[S].slice(v-g):this.receiveFreezeDurationTimestamps[S]})),JSON.stringify(f)}getRecvFreezeIsOngoing(g){return this.finalRecvCurrentFreezeDuration>=g&&this.finalFreezeIsOngoing}getRecvTotalFreezeDuration(){return this.recvTotalFreezeDuration>=0?this.recvTotalFreezeDuration:void 0}getRecvAvgFreezeDuration(){if(this.recvTotalFreezeDuration>0&&this.recvFreezeCount>0)return this.recvTotalFreezeDuration/this.recvFreezeCount}getLongestRecvFreezeDuration(){return this.longestRecvFreezeDuration>0?this.longestRecvFreezeDuration:void 0}populateRecvFreezeDurationCounts(){for(const g of Object.keys(qt.HISTOGRAM_BATCH))if(this.recvCurrentFreezeDuration<=qt.HISTOGRAM_BATCH[g]){this.receiveFreezeDurationCounts[g]+=1,this.receiveFreezeDurationTimestamps[g].push(this.recvCurrentFreezeStartTimestamp);break}this.recvCurrentFreezeStartTimestamp=0}populateLongestRecvFreezeDuration(){this.recvCurrentFreezeDuration>this.longestRecvFreezeDuration&&(this.longestRecvFreezeDuration=this.recvCurrentFreezeDuration)}calculateBitrate(g,f){const S=125,v=(g-this.lastBytesRecv)/S;this.lastBytesRecv=g,v<this.configProvider.config.notRenderingLowBitrateThreshold&&f<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}},_I=class{constructor(){this.mediaData={[qt.MEDIA_DIRECTION.SEND]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0},[qt.MEDIA_DIRECTION.RECV]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0}},this.gatheringSendData=!1}captureMediaData(g,f,S){const v=this.mediaData[g];if(g===qt.MEDIA_DIRECTION.SEND&&(this.gatheringSendData=!0),f){const g=parseInt(f[f.length-1],10);v.totalFrameCount+=g}if(S){-1===v.totalMediaDuration&&(v.totalMediaDuration=0);const g=parseInt(S[S.length-1],10);v.mediaStarted||g>0&&(v.mediaStarted=!0,v.mediaStartTimestamp=new Date)}v.mediaStarted&&(v.totalMediaDuration+=qt.TIME_INTERVAL.SEC_1)}captureFrameRate(g){const f=this.mediaData[qt.MEDIA_DIRECTION.SEND];if(g){const S=parseInt(g[g.length-1],10);f.cameraFrameRate+=S}}stopRecvDataGathering(){const g=this.mediaData[qt.MEDIA_DIRECTION.RECV],f=(new Date).getTime();g.timeSinceLastDecode=g.totalMediaDuration>0?Math.round((f-g.mediaStartTimestamp.getTime())/1e3):0,g.mediaStarted=!1}isGatheringSendData(){return this.gatheringSendData}stopSendDataGathering(){const g=this.mediaData[qt.MEDIA_DIRECTION.SEND],f=new Date;g.timeSinceLastDecode=g.totalMediaDuration>0?Math.round((f.getTime()-g.mediaStartTimestamp.getTime())/1e3):0,this.gatheringSendData=!1,g.mediaStarted=!1}getAvgFrameRate(g){const f=this.mediaData[g];if(f.totalMediaDuration>0&&f.totalFrameCount>0)return f.totalFrameCount/f.totalMediaDuration}getTotalDuration(g){const f=this.mediaData[g];return f.totalMediaDuration>=0?f.totalMediaDuration:void 0}getTimeSinceLastDecode(g){const f=this.mediaData[g];return f.timeSinceLastDecode>0?f.timeSinceLastDecode:void 0}getSendCameraFramerate(){const g=this.mediaData[qt.MEDIA_DIRECTION.SEND];if(g.totalMediaDuration>0)return g.cameraFrameRate/g.totalMediaDuration}},TI={fs:0,fps:1},II=class{constructor(g){this.logger=g,this.allowed=new Map,this.lastParams=new Map,this.currentEvents=new Map,this.finishedEvents=[]}setMaxCapabilities(g){g.forEach((g=>{if(g.ssrc||0===g.ssrc){this.finishIfActive(g.ssrc),this.allowed.set(g.ssrc,{fs:g.maxFs+TI.fs,fps:g.maxFps+TI.fps});const f=this.lastParams.get(g.ssrc);f&&this.setCurrentParams(g.ssrc,f.fs,f.fps)}}))}setCurrentParams(g,f,S){this.lastParams.set(g,{fs:f,fps:S});const v=this.getAllowedParams(g);v&&(f>v.fs||S>v.fps)?(this.captureOvershoot(g,S,v.fps,"fps"),this.captureOvershoot(g,f,v.fs,"fs")):v&&this.finishIfActive(g)}flush(){this.currentEvents.forEach(((g,f)=>this.finishIfActive(f)))}getEvents(){const g=[...deepClone(this.finishedEvents)],f=Date.now();return this.currentEvents.forEach((S=>S.forEach((S=>g.push({ssrc:S.ssrc,timestamp:S.timestamp,duration:f-S.timestamp,overshootType:S.overshootType,amount:S.amount}))))),g}captureOvershoot(g,f,S,v){const C=this.currentEvents.get(g)||[],_=C.findIndex((g=>g.overshootType===v)),T=C[_],I=f-S,b=TI[v];I<=b&&T?(T.duration=Date.now()-T.timestamp,this.finishedEvents.push(T),this.logger.debug(`stopped overshooting ${v} by ${T.amount}`),C.splice(_,1)):I>b&&!T?(this.logger.safe.info(`overshooting ${v} by ${f-S}`),C.push({ssrc:g,timestamp:Date.now(),duration:-1,overshootType:v,amount:{min:I,max:I}})):I>b&&T&&(T.amount={min:Math.min(T.amount.min,I),max:Math.max(T.amount.max,I)}),C.length?this.currentEvents.set(g,C):this.currentEvents.has(g)&&this.currentEvents.delete(g)}getAllowedParams(g){const f=this.allowed.get(g);return f||this.allowed.get(0)}finishIfActive(g){const f=this.currentEvents.get(g);if(f){const S=Date.now();f.forEach((f=>{f.duration=S-f.timestamp,this.finishedEvents.push(f),this.logger.debug(`finished overshooting ${f.overshootType} by min:${f.amount.min} max:${f.amount.max} for ${f.duration}ms for ssrc ${g}`)})),this.currentEvents.delete(g)}}},bI=class{constructor(){this.qpData={[qt.MEDIA_DIRECTION.SEND]:{frames:0,qpSum:0},[qt.MEDIA_DIRECTION.RECV]:{frames:0,qpSum:0}}}captureQpData(g,f,S){const v=this.qpData[g];if(S&&S.length>0){const g=parseInt(S[S.length-1],10);g>0&&(v.frames=g)}if(f){const g=parseInt(f,10);g>0&&(v.qpSum=g)}}getQpAverage(g){const f=this.qpData[g];if(f.qpSum>0&&f.frames>0)return f.qpSum/f.frames}},AI=class{constructor(){this.resolutionChangedCount=0,this.resDurations={},this.preferredResolutionDurations={},this.preferredResolutions=[]}get resolutionSwitchCount(){return this.resolutionChangedCount}get resolutionDurationRatios(){return this.countResolutionDurationRatio(this.resDurations)}get preferredResolutionDurationRatios(){return this.countResolutionDurationRatio(this.preferredResolutionDurations)}get preferredResolution(){return this.preferredResolutions}captureSample(g){g&&g.width&&g.height&&(this.isResolutionChanged(this.lastResolution,g)&&this.resolutionChanged(g),this.updateResolutionDuration(this.getResolutionKey(g),this.resDurations)),this.lastPreferredResolution&&this.updatePreferredResolutionDurations()}capturePreferredResolution(g,f){const S=this.getResolutionKey(g);this.preferredResolution.includes(S)||(this.preferredResolutions.length>=f&&this.preferredResolutions.shift(),this.preferredResolutions.push(S)),this.isResolutionChanged(this.lastPreferredResolution,g)&&(this.preferredResolutionChanged(g),this.updatePreferredResolutionDurations())}getResolutionKey(g){return`${g.width}x${g.height}`}isResolutionChanged(g,f){return!g||g.width!==f.width||g.height!==f.height}countResolutionDurationRatio(g){const f={};let S=0;for(const f in g)S+=g[f];for(const v in g)f[v]=round(g[v]/S*100,2);return f}updatePreferredResolutionDurations(){this.updateResolutionDuration(this.getResolutionKey(this.lastPreferredResolution),this.preferredResolutionDurations)}updateResolutionDuration(g,f){f[g]||(f[g]=0),f[g]++}preferredResolutionChanged(g){this.lastPreferredResolution=g}resolutionChanged(g){this.lastResolution=g,this.resolutionChangedCount++}},PI=class{constructor(){this.streamsTimers={}}countRecvStreams(g){const f=`${g}`;this.streamsTimers.hasOwnProperty(f)||(this.streamsTimers[f]=0),this.streamsTimers[f]++}getStreamCounts(){const g={min:void 0,max:void 0,mode:void 0},f=Object.keys(this.streamsTimers).map(Number);return 0===f.length||1===f.length&&0===f[0]||(g.min=Math.min(...f.filter((g=>g>0))),g.max=Math.max(...f),g.mode=f.reduce(((g,f)=>this.streamsTimers[f]>this.streamsTimers[g]?f:g),f[0])),g}},RI=class{constructor(g){this.configProvider=g,this.subscriptionEvents=[],this.subscriptionCounters={attempted:0,subscribed:0,unsubscribed:0,failed:0}}addSubscriptionEvent(g){switch(this.subscriptionEvents.length>this.configProvider.config.webrtcSubscriptionEventLimit&&this.subscriptionEvents.shift(),this.subscriptionEvents.push(g),g.evt){case 1:this.subscriptionCounters.attempted++;break;case 2:this.subscriptionCounters.subscribed++;break;case 3:this.subscriptionCounters.unsubscribed++;break;case-1:this.subscriptionCounters.failed++}}getSubscriptionEvents(){return this.subscriptionEvents.length>0?{events:this.subscriptionEvents}:void 0}getSubscriptionCounters(){return this.subscriptionEvents.length>0?this.subscriptionCounters:void 0}},MI=class{constructor(g,f,S,v="Video"){this.startTime=g,this.configProvider=f,this.logger=S,this.mediaType=v,this.subscriptionCounter=0,this.videoFreezeTelemetry=new EI(this.configProvider,this.startTime),this.videoDelayTelemetry=new yI,this.videoSubscriptionEvents=new RI(this.configProvider),this.videoQPEvents=new bI,this.videoResolutionTelemetry=new AI,this.videoGeneralTelemetry=new _I,this.videoStreamsCounters=new PI,this.videoBitrate=new SI,this.videoMaxCapabilities=new CI(this.configProvider,this.logger),this.videoOvershoot=new II(this.logger),this.videoQualityLimitations=new fI(this.configProvider),this.videoStatsOnSubscribed=new GT(this.configProvider),this.videoResolutionSwitchTracker=new tC(this.configProvider.config.diagnostics?.collectionLimits?.numResolutionSwitches),this.timeToFirstFrame=-1,this.timeToFirstFrameSinceSubscriptionStart=-1,this.currentTrackId="",this.recvTotalFreezeDurationMs=0,this.isRenderingEvents=[]}get trackId(){return this.currentTrackId}set trackId(g){this.currentTrackId=g}get isRecvDataGatheringEnabled(){return this.subscriptionCounter>0}startStopRecvDataGathering(g){this.logger.safe.info("Receive data gathering is "+(g?"enabled":"disabled")),g?this.subscriptionCounter++:this.subscriptionCounter--,this.subscriptionCounter<0&&this.logger.safe.error(`Subscription counter should not be less than 0. Actual value is ${this.subscriptionCounter}`),0===this.subscriptionCounter&&this.stopRecvGathering()}stopDataGathering(){this.stopRecvGathering(),this.stopSendGathering()}stopRecvGathering(){this.videoFreezeTelemetry.stopRecvDataGathering(),this.videoGeneralTelemetry.stopRecvDataGathering(),this.videoBitrate.stopCapture(qt.MEDIA_DIRECTION.RECV)}isSendGathering(){return this.videoGeneralTelemetry.isGatheringSendData()}stopSendGathering(){this.videoGeneralTelemetry.stopSendDataGathering(),this.videoBitrate.stopCapture(qt.MEDIA_DIRECTION.SEND),this.videoOvershoot.flush()}gatherRecvFreezeData(g,f,S){this.videoFreezeTelemetry.gatherFreezeData({frameRateDecoded:g,frameRateRecv:f,bytesReceived:S,mediaType:this.mediaType})}detectCaptureFreeze(g){this.videoFreezeTelemetry.detectCaptureFreeze(g)}getRecvFreezeDurationCounts(){return this.videoFreezeTelemetry.getRecvFreezeDurationCounts()}getRecvFreezeDurationTimestamps(){return this.videoFreezeTelemetry.getRecvFreezeDurationTimestamps(this.configProvider.config.maxVideoFreezeTimestampsInBucket)}getRecvTotalFreezeDuration(){return this.videoFreezeTelemetry.getRecvTotalFreezeDuration()}setRecvTotalFreezeDurationMs(g){this.recvTotalFreezeDurationMs=void 0!==g?this.recvTotalFreezeDurationMs+=g:void 0}analyzeDelay(g,f){this.videoDelayTelemetry.analyzeDelay(g,f)}getDelayCur(){return this.videoDelayTelemetry.getDelayCur()}getDelayAvg(){return this.videoDelayTelemetry.getDelayAvg()}addSubscriptionEvent(g){this.videoSubscriptionEvents.addSubscriptionEvent(g)}getSubscriptionEvents(){return this.videoSubscriptionEvents.getSubscriptionEvents()}getSubscriptionCounters(){return this.videoSubscriptionEvents.getSubscriptionCounters()}captureQpData(g,f,S){this.videoQPEvents.captureQpData(g,f,S)}getQpAverage(g){return this.videoQPEvents.getQpAverage(g)}captureMediaData(g,f,S){this.videoGeneralTelemetry.captureMediaData(g,f,S)}getIsRendering(){const g=this.configProvider.config.notRenderingTimeInterval["Video"===this.mediaType?"video":"sharing"];return this.videoFreezeTelemetry.getIsRendering(g)}captureFrameRate(g){this.videoGeneralTelemetry.captureFrameRate(g)}getTotalDuration(g){return this.videoGeneralTelemetry.getTotalDuration(g)}captureResolutionSample(g){this.videoResolutionTelemetry.captureSample(g)}countRecvStreams(g){this.videoStreamsCounters.countRecvStreams(g)}captureBitrateSample(g,f){this.videoBitrate.captureSample(g,f)}captureAllocateBandwidth(g){this.videoBitrate.captureAllocateBandwidth(g)}capturePreferredResolution(g,f){this.videoResolutionTelemetry.capturePreferredResolution(g,f)}setMaxCapabilitesRequested(g,f=!1){this.videoMaxCapabilities.setMaxCapabilitesRequested(g),f||1===g.capabilities.length&&!g.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(g.capabilities)}setMaxCapabilitesApplied(g,f=!1){this.videoMaxCapabilities.setMaxCapabilitesApplied(g),f||1===g.capabilities.length&&!g.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(g.capabilities)}getMaxCapabilitiesEvents(){const g=this.videoMaxCapabilities.getEvents();return JSON.stringify(g)}getMaxCapabilitiesResolutionChanges(){const g=this.videoMaxCapabilities.getResolutionRecords();return g?JSON.stringify(g):""}getMaxCapabilitiesErrors(){const g=this.videoMaxCapabilities.getErrors();return g?JSON.stringify(g):""}setCurrentParameters(g,f,S){this.videoOvershoot.setCurrentParams(g,f.height/16*(f.width/16),S)}setMaxCapabilitiesOvershoot(g){this.videoOvershoot.setMaxCapabilities(g)}getOvershootEvents(){let g=this.videoOvershoot.getEvents();return g=g.slice(Math.max(0,g.length-(this.configProvider.config.maxReportedOvershootingEvents+1)),g.length),g.forEach((g=>g.timestamp=g.timestamp-this.startTime)),JSON.stringify(g)}getOvershootTotalDurations(){const g=this.videoOvershoot.getEvents();return g.forEach((g=>g.timestamp=g.timestamp-this.startTime)),JSON.stringify({fs:g.reduce(((g,f)=>"fs"===f.overshootType?g+f.duration:g),0),fps:g.reduce(((g,f)=>"fps"===f.overshootType?g+f.duration:g),0)})}setQualityLimitationReason(g){this.videoQualityLimitations.setQualityLimitationReason(g)}getQualityLimitationReasonEvents(){return this.videoQualityLimitations.getQualityLimitationReasonEvents()}captureTimeToFirstFrame(g,f){-1!==g&&(this.timeToFirstFrame=g,this.timeToFirstFrameSinceSubscriptionStart=f)}getTimeToFirstFrame(){return this.timeToFirstFrame}setIsRendering(g){arrayLimitedPush2(this.isRenderingEvents,{isRendering:g,ts:Date.now()},this.configProvider.config.diagnostics.telemetryLimits.numIsRenderingEvents)}setMsi(g){this.msi=g}setLocalMsi(g){this.localMsi=g}prepareCollectingStatsOnSubscribed(g){this.videoStatsOnSubscribed.prepareCollectingStatsOnSubscribed(g)}captureStatsOnSubscribed(g,f){this.videoStatsOnSubscribed.captureStatsOnSubscribed(g,f)}calculateResolutinSwitches(g,f){this.videoResolutionSwitchTracker.captureSample(g,f)}getReport(g,f,S=!1){const v={};if(v[f+"DurationSeconds"]=this.getTotalDuration(g),v[f+"QpAvg"]=this.getQpAverage(g),v[f+"frameRateAvg"]=this.videoGeneralTelemetry.getAvgFrameRate(g),v[f+"bitrateAvg"]=this.videoBitrate.getAvg(g),v[f+"bitrateMax"]=this.videoBitrate.getMax(g),g===qt.MEDIA_DIRECTION.SEND)v[f+"DelayCur"]=this.getDelayCur(),v[f+"DelayAvg"]=this.getDelayAvg(),v[f+"TimeSinceLastEncodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(g),v[f+"AllocateBWAvg"]=this.videoBitrate.getAllocateBandwidthAvg(),v[f+"CaptureFramerateAvg"]=this.videoGeneralTelemetry.getSendCameraFramerate(),v[f+"FreezeIntervals"]=this.videoFreezeTelemetry.getSendCameraFreezeIntervals(),v[f+"MaxCapabilities"]=S?"":this.getMaxCapabilitiesEvents(),v[f+"MaxCapabilitiesErrors"]=S?"":this.getMaxCapabilitiesErrors(),v[f+"OvershootEvents"]=this.getOvershootEvents(),v[f+"OvershootDurations"]=this.getOvershootTotalDurations(),v[f+"qualityLimitationReasonEvents"]=JSON.stringify(this.getQualityLimitationReasonEvents()),v[f+"MaxCapabilitiesResolutions"]=this.getMaxCapabilitiesResolutionChanges(),v[f+"ResolutionsSwitches"]=this.videoResolutionSwitchTracker.switches?JSON.stringify(this.videoResolutionSwitchTracker.switches):"";else if(g===qt.MEDIA_DIRECTION.RECV){v[f+"TimeSinceLastDecodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(g),v[f+"FreezeHistogram"]=this.getRecvFreezeDurationCounts(),v[f+"FreezeTimestamps"]=this.getRecvFreezeDurationTimestamps(),v[f+"LongestFreezeDuration"]=this.videoFreezeTelemetry.getLongestRecvFreezeDuration(),v[f+"RecvAvgFreezeDuration"]=this.videoFreezeTelemetry.getRecvAvgFreezeDuration(),v[f+"TotalFreezeDuration"]=this.getRecvTotalFreezeDuration(),v[f+"TotalFreezeDurationMs"]=this.recvTotalFreezeDurationMs,v[f+"OngoingFreeze"]=this.videoFreezeTelemetry.getRecvFreezeIsOngoing(this.configProvider.config.webrtcEndOfCallFreezeThreshold),v[f+"NumResolutionSwitches"]=this.videoResolutionTelemetry.resolutionSwitchCount,v[f+"PreferredResolution"]=this.videoResolutionTelemetry.preferredResolution,v[f+"PreferredResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.preferredResolutionDurationRatios),v[f+"ResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.resolutionDurationRatios);const S=this.videoStreamsCounters.getStreamCounts();v[f+"StreamsMin"]=S.min,v[f+"StreamsMax"]=S.max,v[f+"StreamsMode"]=S.mode,v[f+"TimeToFirstFrame"]=this.timeToFirstFrame,v[f+"TimeToFirstFrameSinceSubscriptionStart"]=this.timeToFirstFrameSinceSubscriptionStart,v[f+"LocalMsi"]=this.localMsi,v[f+"Msi"]=this.msi,v[f+"isRenderingEvents"]=JSON.stringify(this.isRenderingEvents),v[f+"statsOnSubscribed"]=JSON.stringify(this.videoStatsOnSubscribed.videoStatsOnSubscribed)}return v}},wI=Symbol("mslbase"),OI=Symbol("mslsamples"),DI=class{constructor(g,f){this.logger=g,this.configProvider=f,this.currentLayouts={},this.collectedModalitySessions=[],this.startTimestamp=Date.now()}get collectedSessions(){return this.collectedModalitySessions}get highestFidelitySSRC(){if(!this.currentModalitySession)return;let g;for(const f in this.currentLayouts)g=this.getHigherFidelitySSRC(f,g);return parseInt(g)}processStats(g){const f=Object.values(g.ssrc??{}).filter((g=>g.rid&&g.ssrc&&g.googFrameHeightInput&&this.lastMaxCapabilitiesEvent?.capabilities.some((f=>f.rid===g.rid)))),S=new Map(f.map((g=>[`${g.ssrc}`,g.rid])));for(const g in this.currentLayouts)S.has(g)||this.collectLayout(g);!this.currentModalitySession&&S.size>0&&(this.currentModalitySession={timestamp:Date.now()-this.startTimestamp,duration:0,numLayouts:0,layouts:[]},this.logger.safe.info("Modality session started")),f.forEach((g=>{this.currentLayouts[`${g.ssrc}`]||this.addLayout(g)})),0===S.size&&this.currentModalitySession&&this.collectSession(),f.forEach((g=>this.processLayoutData(g)))}setMaxCapabilities(g,f){if(this.lastMaxCapabilitiesEvent=g,Object.keys(this.currentLayouts).length)for(const S of g.capabilities){const v=Object.values(this.currentLayouts).find((g=>g.rid===S.rid));v&&(f?(arrayLimitedPush2(v.fmtp,{...S,timestamp:Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-v.timestamp,causeId:g.causeId},this.configProvider.config.simulcastTelemetryNumFMTP),v.gatherer.setMaxCapabilitesApplied(g)):v.gatherer.setMaxCapabilitesRequested(g),v.gatherer.setMaxCapabilitiesOvershoot([S]))}}finish(){this.logger.safe.info("Finishing statistics gathering");for(const g in this.currentLayouts)this.collectLayout(g);this.currentModalitySession&&this.collectSession()}addLayout(g){const f=`${g.ssrc}`,S=g.rid,v=this.lastMaxCapabilitiesEvent?.capabilities.find((g=>g.rid===S));this.logger.safe.info(`Adding layout for ssrc ${f} rid ${S}`);const C=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,_=new MI(C,this.configProvider,this.logger.createChild(`Telemetry#${f}`));this.currentLayouts[f]={ssrc:g.ssrc,rid:S,fmtp:[{...v,timestamp:C,causeId:this.lastMaxCapabilitiesEvent?.causeId}],timestamp:C,duration:0,gatherer:_,[wI]:{firCount:g.googFirsReceived,nackCount:g.googNacksReceived,pliCount:g.googPlisReceived,framesEncoded:g.framesEncoded,bytesSent:g.bytesSent,packetsSent:g.packetsSent,packetsLost:g.packetsLost,qpSum:g.qpSum},[OI]:{firCount:[],nackCount:[],pliCount:[],framesEncoded:[],bytesSent:[],packetsSent:[],packetsLost:[],qpSum:[],frameHeightInput:[],frameHeightSent:[],frameRateInput:[],frameRateSent:[]}},_.setMaxCapabilitiesOvershoot([v]),this.currentModalitySession.numLayouts++}processLayoutData(g){const f=`${g.ssrc}`,S=this.currentLayouts[f];this.processMediaStats(S,g),S.gatherer.captureMediaData(qt.MEDIA_DIRECTION.SEND,[String(g.googFrameRateSent)],[String(g.framesEncoded)]),S.gatherer.captureFrameRate([String(g.googFrameRateInput)]),S.gatherer.captureQpData(qt.MEDIA_DIRECTION.SEND,String(g.qpSum),[String(g.framesEncoded)]),S.gatherer.captureBitrateSample(qt.MEDIA_DIRECTION.SEND,g.bytesSent),S.gatherer.detectCaptureFreeze([String(g.googFrameRateInput)]),S.gatherer.setCurrentParameters(g.ssrc,{width:g.googFrameWidthSent,height:g.googFrameHeightSent},g.googFrameRateSent)}processMediaStats(g,f){const S=g[wI],v=f.googFirsReceived-S.firCount,C=f.googNacksReceived-S.nackCount,_=f.googPlisReceived-S.pliCount,T=f.framesEncoded-S.framesEncoded,I=f.bytesSent-S.bytesSent,b=f.packetsSent-S.packetsSent,A=f.packetsLost-S.packetsLost,P=f.qpSum-S.qpSum,R=g[OI],M=this.configProvider.config.webrtcStatStoredRecordsNumber;arrayLimitedPush2(R.firCount,v,M),arrayLimitedPush2(R.nackCount,C,M),arrayLimitedPush2(R.pliCount,_,M),arrayLimitedPush2(R.framesEncoded,T,M),arrayLimitedPush2(R.bytesSent,I,M),arrayLimitedPush2(R.packetsSent,b,M),arrayLimitedPush2(R.packetsLost,A,M),arrayLimitedPush2(R.qpSum,P,M),arrayLimitedPush2(R.frameHeightInput,f.googFrameHeightInput,M),arrayLimitedPush2(R.frameHeightSent,f.googFrameHeightSent,M),arrayLimitedPush2(R.frameRateInput,f.googFrameRateInput,M),arrayLimitedPush2(R.frameRateSent,f.googFrameRateSent,M)}collectLayout(g){this.logger.safe.info(`Collecting layout for ssrc ${g}`),this.currentLayouts[g].duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-this.currentLayouts[g].timestamp,this.currentLayouts[g].gatherer.isSendGathering()&&this.currentLayouts[g].gatherer.stopSendGathering();const f=this.currentLayouts[g].gatherer.getReport(qt.MEDIA_DIRECTION.SEND,"",!1);for(const S in f)this.currentLayouts[g][S]=f[S];for(const f in this.currentLayouts[g][OI])this.currentLayouts[g][f]=sampleseries(this.currentLayouts[g][OI][f],(g=>g));delete this.currentLayouts[g].gatherer,arrayLimitedPush2(this.currentModalitySession.layouts,this.currentLayouts[g],this.configProvider.config.simulcastTelemetryLayoutsPerSession),delete this.currentLayouts[g]}collectSession(){this.logger.safe.info("Collecting session");for(const g in this.currentLayouts)this.collectLayout(g);this.currentModalitySession.duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,arrayLimitedPush2(this.collectedModalitySessions,this.currentModalitySession,this.configProvider.config.simulcastTelemetryNumModalitySessions),this.currentModalitySession=void 0,this.lastMaxCapabilitiesEvent=void 0}getHigherFidelitySSRC(g,f){if(!g||!f)return g||f;const[S]=this.currentLayouts[g].fmtp.slice(-1),[v]=this.currentLayouts[f].fmtp.slice(-1);return(S?.maxMbps??0)>0&&(v?.maxMbps??0)>0?S.maxMbps>v.maxMbps?g:f:g||f}},NI=["googFrameHeightReceived","googFrameWidthReceived","googFrameHeightSent","googFrameWidthSent","googFrameRateInput","googFrameRateSent","googNacksSent","googNacksReceived","googPlisSent","googPlisReceived","googFirsSent","googFirsReceived","framesDecoded","googFrameRateDecoded","googFrameRateReceived","framesEncoded","packetsLost","packetsSent","packetsReceived","bytesReceived","bytesSent","googEncodeUsagePercent","audioInputLevel","audioOutputLevel","googDecodingCTN","googDecodingPLC","keyFramesEncoded","keyFramesDecoded","googRtt","concealedSamples","silentConcealedSamples","totalSamplesReceived","healedRatio","jitter","googJitterBufferMs","qpSum","fecPacketsReceived","fecPacketsDiscarded","fecPacketsSent","packetsDiscarded","pushCount","pushErrCount","pullCount","pullErrCount"],kI=["bytesSent","bytesReceived","googRtt","packetsSent","requestsSent","consentRequestsSent","responsesSent","requestsReceived","responsesReceived"],LI=["googAvailableReceiveBandwidth","googAvailableSendBandwidth","googTransmitBitrate"];function catchStatsErrors(g,f,S){const v=S.value;S.value=function(...g){try{return v.apply(this,g)}catch(g){this.processStatsError(f,g)}}}var FI=10,xI=class{constructor(g,f,S,v,C,_){this.logger=g,this.sessionInfo=f,this.configProvider=S,this.mediaManager=v,this.multiparty=C,this.newStatsApi=_,this.statsErrors=[],this.subscribedTrackIds=[],this.iceCandidateErrors=[],this.terminated=!1,this.hwSilent=!1,this.isSpeaking=!1,this.networkSendLevel={quality:"Good"},this.networkRecvLevel={quality:"Good"},this.audioTelemetry=new cI(this.configProvider),this.cameraOpenResolution={width:0,height:0},this.streamSenderStarted={},this.totalVideoControlMessages=0,this.outOfOrderVideoControlMessages=0,this.subscribedTrackSsrc=[],this.multiViewVideoTelemetry={},this.h264AvailableProfiles=[],this.h264CodecCapabilities={sendProfiles:[],receiveProfiles:[]},this.timeToFirstFrame={},this.timeToFirstFrameSinceSubscriptionStart={},this.missedInitialPreferredResolution={},this.MSIDs=new Set,this.MSIDsPairs={},this.timerTrackerManager=new G_(this.configProvider.config.enableTimerTracker),this.extensions={WebRTCStats:{},AudioTransportRecvBitrate:0,AudioTransportSendBitrate:0,AudioPayloadSendBitrate:0,AudioPayloadRecvBitrate:0,VideoPayloadSendBitrate:0,VideoPayloadRecvBitrate:0,TimerAudioTransportRecvBitrate:0,TimerAudioTransportSendBitrate:0,TimerAudioPayloadRecvBitrate:0,TimerAudioPayloadSendBitrate:0,TimerVideoPayloadRecvBitrate:0,TimerVideoPayloadSendBitrate:0,StartTime:Date.now(),EndTime:Date.now(),Audio_recv_jitterBufferAvgSize:0,Audio_recv_jitterMax:0,Audio_recv_jitterAvg:0,Audio_send_rttAvg:0,Audio_send_rttMax:0,MaxSessionBandwidth:0,Video_recv_MSIDs:[],Audio_send_presentationUserAPIDuration:"",Audio_send_presentationDuration:""},this.report={type:"WebRtcMediaStats",data:{Extensions:this.extensions}},this.lastSSRCs=new Map,this.videoTelemetry=new MI(this.extensions.StartTime,this.configProvider,this.logger.createChild("Video"),"Video"),this.sharingTelemetry=new MI(this.extensions.StartTime,this.configProvider,this.logger.createChild("Sharing"),"ScreenShare"),this.bandwidthTelemetry=new dI(this.configProvider.config.webrtcBWJumpLowerLimit,this.configProvider.config.webrtcBWJumpUpperLimit),this.stabilizationTelemetry=new JT(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,hasSendDirectionality),this.storedRecordsNumber=Number(this.configProvider.config.webrtcStatStoredRecordsNumber),this.hwSilentDetectionDuration=Number(this.configProvider.config.webrtcStatHwSilentDetectionDuration),this.hwSilentDetectionLevel=Number(this.configProvider.config.webrtcStatHwSilentDetectionLevel),this.audioHealedRatioTelemetry=new lI(this.configProvider),this.networkQualityTelemetry=new mI(this.configProvider,this.newStatsApi,this.audioHealedRatioTelemetry),this.speakingWhileMutedBadDuration=Number(this.configProvider.config.webrtcSpeakingWhileMutedBadDuration),this.speakingWhileMutedDetectionLevel=Number(this.configProvider.config.webrtcSpeakingWhileMutedDetectionLevel),this.videoDelayTimePeriod=this.configProvider.config.webrtcVideoDelayThreshold,this.maxStoredPreferredResolutions=this.configProvider.config.maxStoredPreferredResolutionCount,this.simulcastVideo=new DI(this.logger.createChild("simulcastVideo"),this.configProvider),this.simulcastSharing=new DI(this.logger.createChild("simulcastSharing"),this.configProvider)}get currentVideoRecvTrackId(){return this.extensions.WebRTCStats.ssrc_video_recv?.googTrackId}get currentSharingRecvTrackId(){return this.extensions.WebRTCStats.ssrc_sharing_recv?.googTrackId}get isMultiViewVideoTelemetry(){return Object.getOwnPropertyNames(this.multiViewVideoTelemetry).length>0}onDeviceEvent(g){if("stream_acquired"===g.eventType){const f=g.payload;"Video"===f.mediaType&&(this.cameraOpenResolution=f.resolution)}}onMaxCapabilitiesRequested(g){(g.modality===qt.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesRequested(g);(g.modality===qt.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(g,!1)}onMaxCapabilitiesApplied(g){(g.modality===qt.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesApplied(g);(g.modality===qt.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(g,!0)}setSubscribedTrackIds(g){this.subscribedTrackIds=g||[]}setSubscribedTrackSsrc(g){this.subscribedTrackSsrc=g||[]}addSubscriptionEvent(g,f,S,v,C,_,T){const I={evt:g,ts:Date.now()-this.extensions.StartTime,msi:S,localMsi:v,duration:_};C&&(I.error=stringifyObject(C));const b=this.getHandlerForModality(f);if(b.addSubscriptionEvent(I),T&&this.setMSIDsPair(S,v,T),1===g||3===g){const f=1===g;b.startStopRecvDataGathering(f)}2===g&&b.prepareCollectingStatsOnSubscribed(S)}setMSIDsPair(g,f,S){const v=`ssrc_${S.replace(/\D/g,"")}_recv`;this.MSIDsPairs[v]={msi:g,localMsi:f}}getHandlerForModality(g){switch(g){case qt.MODALITY.video:return this.videoTelemetry;case qt.MODALITY.sharing:return this.sharingTelemetry;default:throw new Error(`Handler not found for modality: ${g}`)}}setTerminated(){this.extensions.EndTime=(new Date).getTime(),this.terminated=!0}startWaitingForStreamStart(g){this.streamStartDetection||this.sessionInfo.setOfferedModalities(g),this.streamStartDetection=!0}processStatsDict(g){if(this.processSimulcastStats(g),this.constructWebRtcReportForSingleStream(this.extensions.WebRTCStats,g),this.streamStartDetection&&(this.setStartTime(this.sessionInfo.offeredModalities)||this.terminated)&&(this.streamStartDetection=!1),Object.keys(this.missedInitialPreferredResolution).length>0&&(this.currentVideoRecvTrackId||this.currentSharingRecvTrackId)&&this.setMissedInitialPreferredResolution(),this.constructWebRTCDataReport(this.extensions.WebRTCStats,g),this.calculateHwSilentState(),this.calculateSpeakingState(),this.setHealedRatioSamples(),this.calculateNetworkRecvQualityLevel(),this.calculateNetworkSendQualityLevel(),this.sessionInfo.activeModalities&&(this.processBandwidthStats(),this.processAudioStats(),this.processVideoStatsRecv(this.videoTelemetry,this.extensions.WebRTCStats.ssrc_video_recv,!0),this.processVideoStatsSend(this.videoTelemetry,this.extensions.WebRTCStats.ssrc_video_send),this.processSharingStats(),this.processStreamsCounters()),this.configProvider.config.enableMultiViewStats){const f=this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS]?this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS]:{};this.constructWebRtcReportForMultipleStreams(f,g);for(const g of Object.keys(f)){const S=f[g];this.processVideoStatsRecv(this.multiViewVideoTelemetry[g],S)}this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS]=f}this.extensions.WebRTCStats.statsErrors=JSON.stringify(this.statsErrors)}setTimeToFirstFrame(g,f,S){S in this.timeToFirstFrame||(this.timeToFirstFrame[S]=g,this.timeToFirstFrameSinceSubscriptionStart[S]=f)}getCurrentTimeToFirstFrame(g){return this.timeToFirstFrame[g]?this.timeToFirstFrame[g]:-1}getCurrentTimeToFirstFrameSinceSubscriptionStart(g){return this.timeToFirstFrameSinceSubscriptionStart[g]?this.timeToFirstFrameSinceSubscriptionStart[g]:-1}getVideoTelemetryBySsrc(g){let f;return this.extensions.WebRTCStats.ssrc_video_recv&&this.extensions.WebRTCStats.ssrc_video_recv.id===g?f=this.videoTelemetry:this.extensions.WebRTCStats.ssrc_sharing_recv&&this.extensions.WebRTCStats.ssrc_sharing_recv.id===g?f=this.sharingTelemetry:this.isMultiViewVideoTelemetry&&(f=this.multiViewVideoTelemetry[g]),f}getIsRendering(g){const f=this.getVideoTelemetryBySsrc(g);return f?f.getIsRendering():void 0}setFreezeDuration(g,f){for(const S of Object.keys(this.multiViewVideoTelemetry))this.multiViewVideoTelemetry[S].trackId===f&&this.isSubscribed(f)&&this.multiViewVideoTelemetry[S].setRecvTotalFreezeDurationMs(g);this.currentSharingRecvTrackId===f&&this.isSubscribed(f)&&this.sharingTelemetry.setRecvTotalFreezeDurationMs(g),this.currentVideoRecvTrackId===f&&this.isSubscribed(f)&&this.videoTelemetry.setRecvTotalFreezeDurationMs(g)}addVideoControlMessage(g){this.totalVideoControlMessages++,g&&this.outOfOrderVideoControlMessages++}setStreamSenderStarted(g,f){this.streamSenderStarted[g]=f}addReportedReceiveBandwidth(g){this.limitCaptureAmount(this.extensions,"ReportedReceiveBandwidth",g)}setHealedRatioSamples(){this.audioHealedRatioTelemetry.captureHealedRatioSamples(this.extensions?.WebRTCStats?.ssrc_audio_recv?.concealedSamples,this.extensions?.WebRTCStats?.ssrc_audio_recv?.silentConcealedSamples,this.extensions?.WebRTCStats?.ssrc_audio_recv?.totalSamplesReceived)}processSimulcastStats(g){this.simulcastVideo.processStats(g),this.simulcastSharing.processStats(g)}processBandwidthStats(){const g=this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth;if(g){const f=this.streamSenderStarted.Video||this.streamSenderStarted.ScreenShare;this.bandwidthTelemetry.recordSendBandwidth(g[g.length-1]),this.stabilizationTelemetry.processBandwidth(parseInt(g[g.length-1]),this.sessionInfo.activeModalities,f)}}processAudioStats(){if(this.extensions.WebRTCStats.ssrc_audio_send&&this.limitCaptureAmount(this.extensions,"Audio_send_RawInputVolume",this.audioTelemetry.getInputLevel("Audio")),void 0!==this.extensions.WebRTCStats.ssrc_audio_recv?.googJitterBufferMs&&this.audioTelemetry.captureJitterBuffer((0,aI.last)(this.extensions.WebRTCStats.ssrc_audio_recv.googJitterBufferMs)),void 0!==this.extensions.WebRTCStats.ssrc_audio_recv?.jitter&&this.audioTelemetry.captureJitter((0,aI.last)(this.extensions.WebRTCStats.ssrc_audio_recv.jitter)),this.extensions.WebRTCStats.ssrc_audio_send?.googRtt){const g=this.extensions.WebRTCStats.ssrc_audio_send.googRtt;this.audioTelemetry.captureRtt(g[g.length-1])}}stopGatheringIfNeeded(g,f,S,v){const C=`${f}${S}`;v!==this.lastSSRCs.get(C)&&(this.lastSSRCs.set(C,v),f===qt.MEDIA_DIRECTION.SEND?g.stopSendGathering():g.stopRecvGathering())}processVideoStatsSend(g,f){f&&hasSendDirectionality(this.sessionInfo.activeModalities.video)?(this.stopGatheringIfNeeded(g,qt.MEDIA_DIRECTION.SEND,"Video",f.ssrc),g.captureMediaData(qt.MEDIA_DIRECTION.SEND,f.googFrameRateSent,f.framesEncoded),g.captureFrameRate(f.googFrameRateInput),g.analyzeDelay(this.videoDelayTimePeriod,f.googAvgEncodeMs),g.captureQpData(qt.MEDIA_DIRECTION.SEND,f.qpSum,f.framesEncoded),g.captureBitrateSample(qt.MEDIA_DIRECTION.SEND,this.getLastSampleInt(f.bytesSent)),g.detectCaptureFreeze(f.googFrameRateInput),g.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),g.setCurrentParameters(parseInt(f.ssrc),{width:this.getLastSampleInt(f.googFrameWidthSent),height:this.getLastSampleInt(f.googFrameHeightSent)},this.getLastSampleInt(f.googFrameRateSent)),g.setQualityLimitationReason(f.qualityLimitationReason),this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo&&g.calculateResolutinSwitches(this.getLastSampleInt(f.googFrameWidthSent),this.getLastSampleInt(f.googFrameHeightSent))):g.isSendGathering()&&(g.stopSendGathering(),this.lastSSRCs.delete(`${qt.MEDIA_DIRECTION.SEND}Video`))}processVideoStatsRecv(g,f,S=!1){f&&hasReceiveDirectionality(this.sessionInfo.activeModalities.video)&&this.videoTelemetry.isRecvDataGatheringEnabled?(S&&this.stopGatheringIfNeeded(g,qt.MEDIA_DIRECTION.RECV,"Video",f.ssrc),g.trackId=f.googTrackId,g.gatherRecvFreezeData(f.googFrameRateDecoded,f.googFrameRateReceived,this.getLastSampleInt(f.bytesReceived)),g.captureMediaData(qt.MEDIA_DIRECTION.RECV,f.googFrameRateReceived,f.googFrameRateDecoded),g.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(f.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(f.googTrackId)),g.captureQpData(qt.MEDIA_DIRECTION.RECV,f.qpSum,f.framesDecoded),g.captureBitrateSample(qt.MEDIA_DIRECTION.RECV,this.getLastSampleInt(f.bytesReceived)),g.captureResolutionSample({width:this.getLastSampleInt(f.googFrameWidthReceived),height:this.getLastSampleInt(f.googFrameHeightReceived)}),g.captureStatsOnSubscribed(this.getLastSampleInt(f.framesDecoded),this.getLastSampleInt(f.bytesReceived))):S&&this.lastSSRCs.delete(`${qt.MEDIA_DIRECTION.RECV}Video`)}processSharingStats(){const g=this.extensions.WebRTCStats.ssrc_sharing_send,f=this.extensions.WebRTCStats.ssrc_sharing_recv;g&&hasSendDirectionality(this.sessionInfo.activeModalities.sharing)?(this.stopGatheringIfNeeded(this.sharingTelemetry,qt.MEDIA_DIRECTION.SEND,"Sharing",g.ssrc),this.sharingTelemetry.captureMediaData(qt.MEDIA_DIRECTION.SEND,g.googFrameRateSent,g.framesEncoded),this.sharingTelemetry.captureFrameRate(g.googFrameRateInput),this.sharingTelemetry.analyzeDelay(this.videoDelayTimePeriod,g.googAvgEncodeMs),this.sharingTelemetry.captureQpData(qt.MEDIA_DIRECTION.SEND,g.qpSum,g.framesEncoded),this.sharingTelemetry.captureBitrateSample(qt.MEDIA_DIRECTION.SEND,this.getLastSampleInt(g.bytesSent)),this.sharingTelemetry.detectCaptureFreeze(g.googFrameRateInput),this.sharingTelemetry.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),this.sharingTelemetry.setCurrentParameters(parseInt(g.ssrc),{width:this.getLastSampleInt(g.googFrameWidthSent),height:this.getLastSampleInt(g.googFrameHeightSent)},this.getLastSampleInt(g.googFrameRateSent)),this.limitCaptureAmount(this.extensions,"Sharing_send_RawInputVolume",this.audioTelemetry.getInputLevel("ScreenShare"))):this.sharingTelemetry.isSendGathering()&&(this.sharingTelemetry.stopSendGathering(),this.lastSSRCs.delete(`${qt.MEDIA_DIRECTION.SEND}Sharing`)),f&&hasReceiveDirectionality(this.sessionInfo.activeModalities.sharing)&&this.sharingTelemetry.isRecvDataGatheringEnabled?(this.stopGatheringIfNeeded(this.sharingTelemetry,qt.MEDIA_DIRECTION.RECV,"Sharing",f.ssrc),this.sharingTelemetry.trackId=f.googTrackId,this.sharingTelemetry.gatherRecvFreezeData(f.googFrameRateDecoded,f.googFrameRateReceived),this.sharingTelemetry.captureMediaData(qt.MEDIA_DIRECTION.RECV,f.googFrameRateReceived,f.googFrameRateDecoded),this.sharingTelemetry.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(f.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(f.googTrackId)),this.sharingTelemetry.captureQpData(qt.MEDIA_DIRECTION.RECV,f.qpSum,f.framesDecoded),this.sharingTelemetry.captureBitrateSample(qt.MEDIA_DIRECTION.RECV,this.getLastSampleInt(f.bytesReceived)),this.sharingTelemetry.captureResolutionSample({width:this.getLastSampleInt(f.googFrameWidthReceived),height:this.getLastSampleInt(f.googFrameHeightReceived)}),this.sharingTelemetry.captureStatsOnSubscribed(this.getLastSampleInt(f.framesDecoded),this.getLastSampleInt(f.bytesReceived))):this.lastSSRCs.delete(`${qt.MEDIA_DIRECTION.RECV}Sharing`)}processStreamsCounters(){const g=this.extensions.WebRTCStats.recvCounters;g&&(this.videoTelemetry.countRecvStreams(g[qt.MODALITY.video]),this.sharingTelemetry.countRecvStreams(g[qt.MODALITY.sharing]))}setMissedInitialPreferredResolution(){forOwn(this.missedInitialPreferredResolution,((g,f)=>{this.setPreferredResolution(f,g)})),this.missedInitialPreferredResolution={}}setPreferredResolution(g,f,S){if((S===qt.MEDIA_TYPE.video&&!this.currentVideoRecvTrackId||S===qt.MEDIA_TYPE.sharing&&!this.currentSharingRecvTrackId)&&(this.missedInitialPreferredResolution[g]=f),this.currentVideoRecvTrackId===g&&this.videoTelemetry.capturePreferredResolution(f,this.maxStoredPreferredResolutions),this.currentSharingRecvTrackId===g&&this.sharingTelemetry.capturePreferredResolution(f,this.maxStoredPreferredResolutions),this.isMultiViewVideoTelemetry){const S=this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(g)];S&&S.capturePreferredResolution(f,this.maxStoredPreferredResolutions)}}setIsRendering(g,f,S){f===qt.MEDIA_TYPE.video&&this.videoTelemetry.setIsRendering(g),f===qt.MEDIA_TYPE.sharing&&this.sharingTelemetry.setIsRendering(g),this.isMultiViewVideoTelemetry&&this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(S)]?.setIsRendering(g)}setMaxSessionBandwidth(g){this.extensions.MaxSessionBandwidth=g}isSubscribed(g,f){let S=this.subscribedTrackIds.some((f=>f===g));return!S&&this.configProvider.config.subscribeToSsrcForVideo&&(S=this.subscribedTrackSsrc.some((g=>g===`${f}`))),S||!this.multiparty&&this.configProvider.config.subscribeToSsrcForVideo}getReport(g=!1,f=!1){try{f&&this.resetPairValues(),g||(this.videoTelemetry.stopDataGathering(),this.sharingTelemetry.stopDataGathering());const S=this.videoTelemetry.getTotalDuration(qt.MEDIA_DIRECTION.RECV),v=this.videoTelemetry.getTotalDuration(qt.MEDIA_DIRECTION.SEND),C=this.sharingTelemetry.getTotalDuration(qt.MEDIA_DIRECTION.RECV),_=this.sharingTelemetry.getTotalDuration(qt.MEDIA_DIRECTION.SEND);if(S>=0&&(forOwn(this.videoTelemetry.getReport(qt.MEDIA_DIRECTION.RECV,"Video_recv_",f),((g,f)=>this.extensions[f]=g)),!isEmpty(this.multiViewVideoTelemetry))){const g=[];for(const S of Object.keys(this.multiViewVideoTelemetry)){const v={id:S};forOwn(this.multiViewVideoTelemetry[S].getReport(qt.MEDIA_DIRECTION.RECV,"Video",f),((g,f)=>{void 0!==g&&(v[f]=g)})),g.push(v)}this.extensions[qt.MULTIPLE_RECV_STREAMS]=JSON.stringify(g)}C>=0&&forOwn(this.sharingTelemetry.getReport(qt.MEDIA_DIRECTION.RECV,"Sharing_recv_",f),((g,f)=>this.extensions[f]=g)),v>=0&&(forOwn(this.videoTelemetry.getReport(qt.MEDIA_DIRECTION.SEND,"Video_send_",f),((g,f)=>this.extensions[f]=g)),this.extensions.Bandwidth_jumpsHistogram=JSON.stringify(this.bandwidthTelemetry.getReport()),this.extensions.Bandwidth_uplinkStabilizationTime=JSON.stringify(this.stabilizationTelemetry.getReport(!0)),this.extensions.Video_send_CameraOpenWidth=this.cameraOpenResolution.width,this.extensions.Video_send_CameraOpenHeight=this.cameraOpenResolution.height),_>=0&&forOwn(this.sharingTelemetry.getReport(qt.MEDIA_DIRECTION.SEND,"Sharing_send_",f),((g,f)=>this.extensions[f]=g)),g||f||(this.simulcastVideo.finish(),this.extensions.Video_send_Simulcast=JSON.stringify(this.simulcastVideo.collectedSessions),this.simulcastSharing.finish(),this.extensions.Sharing_send_Simulcast=JSON.stringify(this.simulcastSharing.collectedSessions)),this.iceCandidateErrors.length>0&&(this.extensions.iceCandidateErrors=JSON.stringify(this.iceCandidateErrors)),this.extensions.Audio_recv_jitterBufferAvgSize=this.audioTelemetry.getAvgJitterBuffer(),this.extensions.Audio_recv_jitterMax=this.audioTelemetry.getJitterMax(),this.extensions.Audio_recv_jitterAvg=this.audioTelemetry.getJitterAvg(),this.extensions.Video_SubscriptionEvents=f?"":JSON.stringify(this.videoTelemetry.getSubscriptionEvents()),this.extensions.Video_SubscriptionCounters=f?"":JSON.stringify(this.videoTelemetry.getSubscriptionCounters()),this.extensions.Sharing_SubscriptionEvents=f?"":JSON.stringify(this.sharingTelemetry.getSubscriptionEvents()),this.extensions.Sharing_SubscriptionCounters=f?"":JSON.stringify(this.sharingTelemetry.getSubscriptionCounters()),this.extensions.Audio_recv_healedRatioMax=this.audioHealedRatioTelemetry.getHealedRatioMax(),this.extensions.Audio_recv_healedRatioAvg=this.audioHealedRatioTelemetry.getHealedRatioAvg(),this.extensions.Audio_send_rttAvg=this.audioTelemetry.getAvgRtt(),this.extensions.Audio_send_rttMax=this.audioTelemetry.getMaxRtt();for(const g of Object.keys(this.extensions))void 0===this.extensions[g]&&delete this.extensions[g];delete this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS],this.sessionInfo.fillExtensionInfo(this.extensions);return Object.keys(this.extensions.WebRTCStats).length>0&&!this.extensions.WebRTCStats.hasStatsError&&this.calculateAverages(),this.extensions.H264_available_profiles=this.h264AvailableProfiles.join(),this.extensions.H264_codec_capabilities=JSON.stringify(this.h264CodecCapabilities),this.extensions.Video_recv_MSIDs=Array.from(this.MSIDs),this.totalVideoControlMessages>0&&(this.extensions.totalVideoControlMessages=this.totalVideoControlMessages,this.extensions.outOfOrderVideoControlMessages=this.outOfOrderVideoControlMessages),deepClone(this.report)}catch(g){throw this.processStatsError("Report",g),{error:g,partialReport:deepClone(this.report)}}}getAudioHwSilent(){return this.hwSilent}getSpeakingState(){return this.isSpeaking}getNetworkSendLevel(){return this.networkSendLevel}getNetworkRecvLevel(){return this.networkRecvLevel}addIceCandidateError(g){this.iceCandidateErrors.push(g)}clearIceCandidateErrors(){this.iceCandidateErrors=[]}addH264AvailableProfiles(g){this.h264AvailableProfiles=[...new Set(this.h264AvailableProfiles.concat(g))]}setSupportedH264Profiles(g,f){this.h264CodecCapabilities.sendProfiles=g,this.h264CodecCapabilities.receiveProfiles=f}updateSendStream(g,f){this.audioTelemetry.updateSendStream(g,f)}getTimerTracker(g,f){return this.timerTrackerManager.getTimerTracker(g,f)}resetPairValues(){Object.keys(this.extensions.WebRTCStats).forEach((g=>{delete this.extensions.WebRTCStats[g].pair}))}limitCaptureAmount(g,f,S){void 0!==S&&(g[f]=Array.isArray(g[f])?g[f]:[],g[f].push(S),g[f].length>this.storedRecordsNumber&&g[f].shift())}setStartTime(g){const f=this.extensions.WebRTCStats;if(!f.ssrc_audio_send||!f.ssrc_audio_recv)return!1;const setupCounter=(g,f)=>!g||f&&-1===f?f:(new Date).getTime();return this.extensions.TimerAudioPayloadRecvBitrate=hasReceiveDirectionality(g.audio)?setupCounter(f.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioPayloadRecvBitrate):-1,this.extensions.TimerAudioPayloadSendBitrate=hasSendDirectionality(g.audio)?setupCounter(f.ssrc_audio_send.bytesSent,this.extensions.TimerAudioPayloadSendBitrate):-1,this.extensions.TimerAudioTransportRecvBitrate=hasReceiveDirectionality(g.audio)?setupCounter(f.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioTransportRecvBitrate):-1,this.extensions.TimerAudioTransportSendBitrate=hasSendDirectionality(g.audio)?setupCounter(f.ssrc_audio_send.bytesSent,this.extensions.TimerAudioTransportSendBitrate):-1,!(!f.ssrc_video_send||!f.ssrc_video_recv)&&(this.extensions.TimerVideoPayloadRecvBitrate=hasReceiveDirectionality(g.video)?setupCounter(f.ssrc_video_recv.bytesReceived,this.extensions.TimerVideoPayloadRecvBitrate):-1,this.extensions.TimerVideoPayloadSendBitrate=hasSendDirectionality(g.video)?setupCounter(f.ssrc_video_send.bytesSent,this.extensions.TimerVideoSendBitrate):-1,!!(this.extensions.TimerVideoPayloadRecvBitrate&&this.extensions.TimerVideoPayloadSendBitrate&&this.extensions.TimerAudioPayloadRecvBitrate&&this.extensions.TimerAudioPayloadSendBitrate&&this.extensions.TimerAudioTransportRecvBitrate&&this.extensions.TimerAudioTransportSendBitrate))}calculateAverages(){const g=this.extensions.EndTime,doTheCalc=(f,S)=>f&&g-S>0&&0!==S&&-1!==S?Math.round(8*f/(g-S)):0,getCounter=g=>{const f=g.split(".").reduce(((g,f)=>null==g?g:g[f]),this.extensions.WebRTCStats);return Array.isArray(f)?f[f.length-1]:f};this.extensions.AudioPayloadRecvBitrate=doTheCalc(getCounter("ssrc_audio_recv.bytesReceived"),this.extensions.TimerAudioPayloadRecvBitrate),this.extensions.AudioPayloadSendBitrate=doTheCalc(getCounter("ssrc_audio_send.bytesSent"),this.extensions.TimerAudioPayloadSendBitrate),this.extensions.VideoPayloadRecvBitrate=doTheCalc(getCounter("ssrc_video_recv.bytesReceived"),this.extensions.TimerVideoPayloadRecvBitrate),this.extensions.VideoPayloadSendBitrate=doTheCalc(getCounter("ssrc_video_send.bytesSent"),this.extensions.TimerVideoPayloadSendBitrate),this.extensions.AudioTransportRecvBitrate=doTheCalc(getCounter("ssrc_audio_send.pair.bytesReceived"),this.extensions.TimerAudioTransportRecvBitrate),this.extensions.AudioTransportSendBitrate=doTheCalc(getCounter("ssrc_audio_send.pair.bytesSent"),this.extensions.TimerAudioTransportSendBitrate)}addFilteredFields(g,f,S=[]){for(const v in f)if(f.hasOwnProperty(v)&&"type"!==v)if(-1!==S.indexOf(v)){const S=g[v]||[];S.push(this.formatFields(f,v)),S.length>this.storedRecordsNumber&&S.shift(),g[v]||(g[v]=S)}else g[v]=f[v]}formatFields(g,f){const S=g[f];switch(f){case"audioInputLevel":case"audioOutputLevel":return this.newStatsApi?Math.floor(65535*S):2*S;case"googJitterBufferMs":return parseInt(S);case"healedRatio":return round(parseFloat(S),this.configProvider.config.healedRatioPrecision);case"jitter":return round(parseFloat(S),this.configProvider.config.jitterPrecision);default:return S}}processSource(g,f,S){let v;if(this.addFilteredFields(g,f,NI),f.transportId){const C=S.googComponent?.[f.transportId];g.transport||(g.transport={}),C&&(this.addFilteredFields(g.transport,C),C.selectedCandidatePairId&&(v=S.googCandidatePair?.[C.selectedCandidatePairId]))}else v=Object.values(S.googCandidatePair).find((g=>g.selected));v&&(g.pair||(g.pair={}),this.addFilteredFields(g.pair,v,kI))}getWebrtcReport(g,f,S,v){const C=g.ssrc[S],_=v?C.id.replace(/[0-9]+/,v):C.id;f[_]?C.ssrc!==f[_].ssrc&&(_.endsWith("video_send")?this.videoTelemetry.stopSendGathering():_.endsWith("video_recv")?this.videoTelemetry.stopRecvGathering():_.endsWith("sharing_send")?this.sharingTelemetry.stopSendGathering():_.endsWith("sharing_recv")&&this.sharingTelemetry.stopRecvGathering()):f[_]={},this.processSource(f[_],C,g)}constructWebRTCDataReport(g,f){if(!f.data?.length)return;const S=f.data.sort(((g,f)=>f.timestamp-g.timestamp)),v=S.find((g=>"open"===g.state));g.data=v||S[0]}constructWebRtcReportForSingleStream(g,f){if(!f.ssrc)return;const S=this.selectSsrcsToCollect(f.ssrc);g.recvCounters=S.recvCounters,delete S.recvCounters,delete S.multiRecv,forOwn(S,(S=>{forOwn(S,((S,v)=>{this.getWebrtcReport(f,g,S,v)}))})),f.VideoBwe?.bweforvideo&&(g.bweStat||(g.bweStat={}),this.addFilteredFields(g.bweStat,f.VideoBwe.bweforvideo,LI))}constructWebRtcReportForMultipleStreams(g,f){if(!f.ssrc)return;this.selectSsrcsToCollect(f.ssrc).multiRecv.forEach((S=>this.getWebrtcReport(f,g,S)))}getMediaType(g,f){let S=f?f.getModality():g.mediaType;return g.googTrackId?.match("applicationsharing")&&S!==qt.MEDIA_TYPE.sharing&&(S=qt.MEDIA_TYPE.sharing),S}selectSsrcsToCollect(g){const f={send:{},recv:{},recvCounters:{video:0,sharing:0},multiRecv:[]};if(!this.sessionInfo.activeModalities)return f;let S=[];for(const v of Object.keys(g)){const C=g[v],_=C.googTrackId;if(!_&&C.mediaType!==qt.MEDIA_TYPE.audio)continue;const T=this.getMediaEntity(_,C),I=this.getMediaType(C,T),b=T?.getXSourceStreamId();if(v.endsWith("send"))switch(I){case qt.MEDIA_TYPE.audio:hasSendDirectionality(this.sessionInfo.activeModalities.audio)&&(f.send.audio=v);break;case qt.MEDIA_TYPE.video:if(this.extensions.Video_send_SourceId=b,this.simulcastVideo.highestFidelitySSRC){this.simulcastVideo.highestFidelitySSRC===C.ssrc&&(f.send.video=v);break}this.streamSenderStarted.Video&&hasSendDirectionality(this.sessionInfo.activeModalities.video)&&T?.getLocalTrackId()&&(T?.getLocalTrackId()===C.googTrackId||this.configProvider.config.statsAllowAnyVideoSendTrack&&!f.send.video)&&(!C.rid||"1"===C.rid)&&(f.send.video=v);break;case qt.MEDIA_TYPE.sharing:if(this.simulcastSharing.highestFidelitySSRC){this.simulcastSharing.highestFidelitySSRC===C.ssrc&&(f.send.sharing=v);break}this.streamSenderStarted.ScreenShare&&hasSendDirectionality(this.sessionInfo.activeModalities.sharing)&&T?.getLocalTrackId()===C.googTrackId&&(f.send.sharing=v);break;default:this.logger.warn(`Unknown media type '${I}'`)}else if(v.endsWith("recv"))switch(I){case qt.MEDIA_TYPE.audio:hasReceiveDirectionality(this.sessionInfo.activeModalities.audio)&&(f.recv.audio=v);break;case qt.MEDIA_TYPE.video:void 0!==b&&this.MSIDs.add(b),this.isSubscribed(C.googTrackId,C.ssrc)&&hasReceiveDirectionality(this.sessionInfo.activeModalities.video)&&(S.push(C),+C.googFrameRateReceived>0&&f.recvCounters[qt.MODALITY.video]++);break;case qt.MEDIA_TYPE.sharing:this.isSubscribed(C.googTrackId,C.ssrc)&&hasReceiveDirectionality(this.sessionInfo.activeModalities.sharing)&&(f.recv.sharing=v,+C.googFrameRateReceived>0&&f.recvCounters[qt.MODALITY.sharing]++);break;default:this.logger.warn(`Unknown media type '${I}'`)}}if(S.length>0){S=S.sort(((g,f)=>+f.googFrameHeightReceived-+g.googFrameHeightReceived));const g=S.find((g=>g.mediaType===qt.MEDIA_TYPE.video));g&&(f.recv.video=g.id),this.multiparty&&this.configProvider.config.enableMultiViewStats&&(f.multiRecv=S.map((g=>g.id)),f.multiRecv.forEach((g=>{this.multiViewVideoTelemetry[g]||(this.multiViewVideoTelemetry[g]=new MI(this.extensions.StartTime,this.configProvider,this.logger.createChild(`Video[${g}]`,"Video")),this.multiViewVideoTelemetry[g].setMsi(this.MSIDsPairs[g]?.msi),this.multiViewVideoTelemetry[g].setLocalMsi(this.MSIDsPairs[g]?.localMsi),this.multiViewVideoTelemetry[g].prepareCollectingStatsOnSubscribed(this.MSIDsPairs[g]?.msi))})))}return f}getMediaEntityForTrack(g){if(g)return this.mediaManager.getMediaEntities().find((f=>f.getLocalTrackId()===g||f.getRemoteTrackId()===g))}getMediaEntityByRemoteSsrc(g){if(g)return this.mediaManager.getMediaEntities().find((f=>f.getRemoteSsrc()===+g))}getMediaEntity(g,f){const S=`${f.ssrc}`,v=f.id;let C=this.getMediaEntityForTrack(g);return!C&&this.configProvider.config.subscribeToSsrcForVideo&&v.endsWith("recv")&&(C=this.getMediaEntityByRemoteSsrc(S)),C}calculateHwSilentState(){const g=this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!g||g.length<2*this.hwSilentDetectionDuration)return;let f=!0;for(let S=g.length-this.hwSilentDetectionDuration-1;S<g.length;S++)if(g[S]>this.hwSilentDetectionLevel){f=!1;break}this.hwSilent!==f&&(this.hwSilent=f,this.logger.safe.info(`HW silent changed to ${this.hwSilent}`))}calculateSpeakingState(){const g=this.newStatsApi&&this.configProvider.config.useAudioAnalyzer?this.extensions.Audio_send_RawInputVolume:this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!g||g.length<=this.speakingWhileMutedBadDuration)return;let f=!1;for(let S=g.length-this.speakingWhileMutedBadDuration;S<g.length;S++)if(g[S]>this.speakingWhileMutedDetectionLevel){f=!0;break}this.isSpeaking=f}calculateNetworkRecvQualityLevel(){this.configProvider.config.enableNetworkRecvQualityUFD&&this.extensions.WebRTCStats.ssrc_audio_recv&&(this.networkRecvLevel=this.networkQualityTelemetry.calculateNetworkRecvQualityLevel({googDecodingCTN:this.extensions.WebRTCStats.ssrc_audio_recv.googDecodingCTN??[],googDecodingPLC:this.extensions.WebRTCStats.ssrc_audio_recv.googDecodingPLC??[],concealedSamples:this.extensions.WebRTCStats.ssrc_audio_recv.concealedSamples??[],silentConcealedSamples:this.extensions.WebRTCStats.ssrc_audio_recv.silentConcealedSamples??[],totalSamplesReceived:this.extensions.WebRTCStats.ssrc_audio_recv.totalSamplesReceived??[],oldNetworkLevel:this.networkRecvLevel.quality}))}calculateNetworkSendQualityLevel(){this.extensions.WebRTCStats.ssrc_audio_send&&(this.networkSendLevel=this.networkQualityTelemetry.calculateNetworkSendQualityLevel(this.extensions.WebRTCStats.ssrc_audio_send.packetsSent,this.extensions.WebRTCStats.ssrc_audio_send.packetsLost,this.extensions.WebRTCStats.ssrc_audio_send.jitter,this.networkSendLevel.quality))}processStatsError(g,f){const S=stringifyObject(f);this.logger.safe.error(`webrtcStatistics error [${g}]: ${S}`);const v=this.statsErrors.find((f=>f.error===S&&f.origin===g));v?v.count++:this.statsErrors.push({origin:g,error:S,count:1}),this.statsErrors.length>FI&&this.statsErrors.splice(1)}getLastSampleInt(g){return"number"==typeof g?g:g&&parseInt(g[g.length-1])||0}getSsrcIdFromMultipleVideoStream(g){let f;const S=this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS]||{};for(const v in S){const C=S[v];if(C&&C.googTrackId===g){f=v;break}}return f}};__decorateClass([catchStatsErrors],xI.prototype,"onDeviceEvent",1),__decorateClass([catchStatsErrors],xI.prototype,"onMaxCapabilitiesRequested",1),__decorateClass([catchStatsErrors],xI.prototype,"onMaxCapabilitiesApplied",1),__decorateClass([catchStatsErrors],xI.prototype,"addSubscriptionEvent",1),__decorateClass([catchStatsErrors],xI.prototype,"processSimulcastStats",1),__decorateClass([catchStatsErrors],xI.prototype,"processBandwidthStats",1),__decorateClass([catchStatsErrors],xI.prototype,"processAudioStats",1),__decorateClass([catchStatsErrors],xI.prototype,"processVideoStatsSend",1),__decorateClass([catchStatsErrors],xI.prototype,"processVideoStatsRecv",1),__decorateClass([catchStatsErrors],xI.prototype,"processSharingStats",1),__decorateClass([catchStatsErrors],xI.prototype,"processStreamsCounters",1),__decorateClass([catchStatsErrors],xI.prototype,"setMissedInitialPreferredResolution",1),__decorateClass([catchStatsErrors],xI.prototype,"setPreferredResolution",1),__decorateClass([catchStatsErrors],xI.prototype,"setIsRendering",1),__decorateClass([catchStatsErrors],xI.prototype,"setMaxSessionBandwidth",1),__decorateClass([catchStatsErrors],xI.prototype,"setStartTime",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateAverages",1),__decorateClass([catchStatsErrors],xI.prototype,"addFilteredFields",1),__decorateClass([catchStatsErrors],xI.prototype,"formatFields",1),__decorateClass([catchStatsErrors],xI.prototype,"processSource",1),__decorateClass([catchStatsErrors],xI.prototype,"getWebrtcReport",1),__decorateClass([catchStatsErrors],xI.prototype,"constructWebRTCDataReport",1),__decorateClass([catchStatsErrors],xI.prototype,"constructWebRtcReportForSingleStream",1),__decorateClass([catchStatsErrors],xI.prototype,"constructWebRtcReportForMultipleStreams",1),__decorateClass([catchStatsErrors],xI.prototype,"selectSsrcsToCollect",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateHwSilentState",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateSpeakingState",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateNetworkRecvQualityLevel",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateNetworkSendQualityLevel",1);var UI="VideoBwe",VI="bweforvideo",BI="googAvailableReceiveBandwidth",HI="googAvailableSendBandwidth",$I="mediaType",jI="framesDecoded",GI="googFrameRateDecoded",qI="googFrameRateReceived",WI="googFrameRateInput",zI="googTrackId";function unwrapResults(g){const f={};return g.result().forEach((g=>{g.names().forEach((S=>{f[g.type]=f[g.type]||{},f[g.type][g.id]=f[g.type][g.id]||{},f[g.type][g.id][S]=g.stat(S)})),f[g.type][g.id].id=g.id})),f}var KI=class extends Ht{constructor(g,f,S,v){super(),this.logger=g,this.configProvider=f,this.mediaManager=S,this.window=Xs.window,this._sessionInfo=new B_,this.statisticsMapper=new sI,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.webRtcStatistics=new xI(this.logger.createChild("WebrtcStatistics"),this._sessionInfo,this.configProvider,S,v,this.useNewStatsApi)}setAudioDecoderStatsProvider(g){this.statisticsMapper?.setAudioDecoderStatsProvider(g)}get sessionInfo(){return this._sessionInfo}get isDisposed(){return null===this.pc&&0===this.interval}initialize(g){this.pc=g}startWaitingForStreamStart(g){this.webRtcStatistics.startWaitingForStreamStart(g)}onDeviceEvent(g){this.webRtcStatistics.onDeviceEvent(g)}onMaxCapabilitiesRequested(g){this.webRtcStatistics.onMaxCapabilitiesRequested(g)}onMaxCapabilitiesApplied(g){this.webRtcStatistics.onMaxCapabilitiesApplied(g)}onSendersChanged(g,f){this.webRtcStatistics.setStreamSenderStarted(g,f)}addSubscriptionEvent(g,f,S,v,C,_,T){this.webRtcStatistics.addSubscriptionEvent(g,f,S,v,C,_,T)}setSubscribedTrackIds(g){this.webRtcStatistics.setSubscribedTrackIds(g)}setSubscribedTrackSsrc(g){this.webRtcStatistics.setSubscribedTrackSsrc(g)}setPreferredResolution(g,f,S){this.webRtcStatistics.setPreferredResolution(g,f,S)}setIsRendering(g,f,S){this.webRtcStatistics.setIsRendering(g,f,S)}setMaxSessionBandwidth(g){this.webRtcStatistics.setMaxSessionBandwidth(g)}setTerminated(){this.webRtcStatistics.setTerminated()}addIceCandidateError(g){this.webRtcStatistics.addIceCandidateError(g)}clearIceCandidateErrors(){this.webRtcStatistics.clearIceCandidateErrors()}updateSendStream(g,f){this.webRtcStatistics.updateSendStream(g,f)}getTimerTracker(g,f){return this.webRtcStatistics.getTimerTracker(g,f)}setH264AvailableProfiles(g){if(!g?.codecs)return;let f=[];g.codecs.forEach((g=>{if("h264"===g.mimeType&&g.sdpFmtpLine){const S=/profile-level-id=(.{6})/.exec(g.sdpFmtpLine);S?.[1]&&(f=f.concat(S[1]))}})),this.webRtcStatistics.addH264AvailableProfiles(f)}setSupportedH264Profiles(g,f){if(!g?.codecs&&!f?.codecs)return;const extractProfiles=g=>{const f=[];return g.codecs?.forEach((g=>{if("h264"===g.mimeType&&g.sdpFmtpLine){const S=/profile-level-id=(.{6})/.exec(g.sdpFmtpLine)?.[1];S&&!f.includes(S)&&f.push(S)}})),f},S=extractProfiles(g),v=extractProfiles(f);this.webRtcStatistics.setSupportedH264Profiles(S,v)}processRawReport(g){this.processStatsDict(this.statisticsMapper.build(g))}processLegacyReport(g){this.processStatsDict(unwrapResults(g))}getReport(g,f=!1){const S=this.webRtcStatistics.getReport(g,f);return this.addStreamInfoForE2ETests(S),S}dispose(){this.interval&&(this.window.clearInterval(this.interval),this.interval=0),this.pc=null}getLastStatistics(){return this.statistics}setTimeToFirstFrame(g,f,S){this.webRtcStatistics.setTimeToFirstFrame(g,f,S)}setFreezeDuration(g,f){this.webRtcStatistics.setFreezeDuration(g,f)}addVideoControlMessage(g=!1){this.webRtcStatistics.addVideoControlMessage(g)}setSsrcTrackPair(g,f){this.statisticsMapper.setSsrcTrackPair(g,f)}updateStatsWithLocalSsrcTrackInfo(){for(const g of this.mediaManager.getMediaEntities()){const f=g.getLocalSsrc();f&&this.statisticsMapper.setSsrcTrackPair(f,g.getLocalTrackId())}}addReportedReceiveBandwidth(g){this.webRtcStatistics.addReportedReceiveBandwidth(g)}addStreamInfoForE2ETests(g){const f=this._sessionInfo.negotiatedModalities;if(f&&!this.isDisposed)try{g.localStreams=this.getSendersReport(this.pc.getSenders(),{audio:hasSendDirectionality(f.audio),video:hasSendDirectionality(f.video)}),g.remoteStreams=this.getReceiversReport(this.pc.getReceivers(),{audio:hasReceiveDirectionality(f.audio),video:hasReceiveDirectionality(f.video)})}catch(g){this.logger.safe.warn(`addStreamInfoForE2ETests failed: ${stringifyObject(g)}`)}}getReceiversReport(g,f){const S=[];return g.forEach((g=>{const v={tracks:[]};S.push(v),g.track&&("audio"===g.track.kind&&f.audio||"video"===g.track.kind&&f.video)&&v.tracks.push({stream:void 0,track:g.track})})),S}getSendersReport(g,f){const S=[],v={tracks:[]};return S.push(v),g.forEach((g=>{g.track&&("audio"===g.track.kind&&f.audio||"video"===g.track.kind&&f.video)&&v.tracks.push({stream:void 0,track:g.track})})),S}processStatsDict(g){this.webRtcStatistics.processStatsDict(g);let f=0,S=0;const v=g[UI]?.[VI];v&&(f=Number(v[BI]),S=Number(v[HI]));const C=1e3*((this.configProvider.mediaConfig.maxBandwidthInKbps||Math.floor(Number.MAX_SAFE_INTEGER/1e3))-(this.configProvider.config.audioBandwidthInKbps||0)),_=isNaN(f)?0:f,T=isNaN(S)?0:S,I={estimatedReceiveBandwidth:Math.min(_,C),estimatedSendBandwidth:Math.min(T,C),remoteVideoStreams:{},localVideoStreams:{},isSpeaking:this.webRtcStatistics.getSpeakingState(),audioHwSilent:this.webRtcStatistics.getAudioHwSilent(),networkSendLevel:this.webRtcStatistics.getNetworkSendLevel(),networkRecvLevel:this.webRtcStatistics.getNetworkRecvLevel()};forOwn(g.ssrc,(g=>{if("video"!==g[$I])return;const f=g[zI],S=g.id;-1!==S.indexOf("_recv")?(I.remoteVideoStreams[f]={trackId:f,frameRateReceived:Number(g[qI]),frameRateDecoded:Number(g[GI]),framesDecoded:Number(g[jI])},this.configProvider.config.isRenderingBasedOnRawStatistics||(I.remoteVideoStreams[f].isRendering=this.webRtcStatistics.getIsRendering(S))):f&&-1!==S.indexOf("_send")&&(I.localVideoStreams[f]={trackId:f,ssrc:Number(g.ssrc),frameRateInput:Number(g[WI])})})),deepEqual(this.statistics,I)||(this.statistics=I,this.notifyStatisticsChanged())}notifyStatisticsChanged(){this.event("onStatisticsChanged").raise(this.statistics)}},JI=class extends Ht{constructor(g,f,S,v,C){super(),this.logger=g,this.configProvider=f,this.diagnostics=S,this.mediaManager=v,this.window=Xs.window,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.loopIntervalTracker=new Jv(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.loopIntervalAggregator=new Yv,this.fetchTimeTracker=new Jv(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.fetchTimeAggregator=new Yv,this.gathererV1=new KI(this.logger.createChild("V1"),this.configProvider,this.mediaManager,C),this.gathererV1.on("onStatisticsChanged",(g=>this.event("onStatisticsChanged").raise(g))),this.useNewStatsApi&&f.config.diagnostics.sideBySide&&(this.gathererV2=new nI(this.logger.createChild("V2"),this.configProvider,this.diagnostics,this.mediaManager))}initialize(g){this.pc=g,this.gathererV1.initialize(g),this.interval??(this.interval=this.window.setInterval((()=>this.processStats()),this.configProvider.config.webrtcStatPollInterval))}setAudioDecoderStatsProvider(g){this.gathererV1.setAudioDecoderStatsProvider(g),this.gathererV2?.setAudioDecoderStatsProvider(g)}dispose(){super.dispose(),this.interval&&(this.window.clearInterval(this.interval),this.interval=void 0),this.gathererV1.dispose(),this.pc=void 0}get isDisposed(){return!this.pc&&void 0===this.interval}async processStats(){if(this.configProvider.config.diagnostics.collectWhileNotConnected){if(!this.pc||"closed"===this.pc.iceConnectionState)return}else if(!this.pc||"connected"!==this.pc.iceConnectionState&&"completed"!==this.pc.iceConnectionState)return void this.gathererV2?.signalNoConnection();if(this.useNewStatsApi){const g=Jt(),f=void 0===this.loopTimer?-1:g-this.loopTimer;this.loopTimer=g,this.loopIntervalTracker.captureSample(f),this.loopIntervalAggregator.captureSample(this.loopIntervalTracker.getReport());const S=this.loopIntervalAggregator.getReport();S&&(this.diagnostics.loopIntervalMax=S.max,this.diagnostics.loopIntervalMedian=S.median);const v={};(await this.pc.getStats()).forEach((g=>{this.cleanupPii(g);const f=g.type;delete g.type,v[f]??(v[f]={}),v[f][g.id]=g}));const C=Jt()-g;this.fetchTimeTracker.captureSample(C),this.fetchTimeAggregator.captureSample(this.fetchTimeTracker.getReport());const _=this.fetchTimeAggregator.getReport();_&&(this.diagnostics.fetchTimeMax=_.max,this.diagnostics.fetchTimeMedian=_.median);const T=this.gathererV2?.processRawReport(v);let I=Jt();this.gathererV1.processRawReport(v),I=Jt()-I,T&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Raising onDiagnosticUpdated event"),this.event("onDiagnosticUpdated").raise(T)),T?.perfCounters&&(T.perfCounters.loopTime=f,T.perfCounters.fetchTime=C,T.perfCounters.legacyProcessingTime=I)}else this.pc.getStats((g=>{g.result&&this.gathererV1.processLegacyReport(g)}))}cleanupPii(g){switch(g.type){case"local-candidate":case"remote-candidate":{const f=g;Object.defineProperty(f,"address",{enumerable:!1}),Object.defineProperty(f,"url",{enumerable:!1}),Object.defineProperty(f,"relatedAddress",{enumerable:!1}),Object.defineProperty(f,"ip",{enumerable:!1}),Object.defineProperty(f,"usernameFragment",{enumerable:!1});break}case"certificate":{const f=g;Object.defineProperty(f,"fingerprint",{enumerable:!1}),Object.defineProperty(f,"base64Certificate",{enumerable:!1});break}}}get sessionInfo(){return this.gathererV1.sessionInfo}onMaxCapabilitiesApplied(g){this.gathererV1.onMaxCapabilitiesApplied(g)}clearIceCandidateErrors(){this.gathererV1.clearIceCandidateErrors()}setSsrcTrackPair(g,f){this.gathererV1.setSsrcTrackPair(g,f),this.gathererV2?.setSsrcTrackPair(g,f)}addSubscriptionEvent(g,f,S,v,C,_,T){this.gathererV1.addSubscriptionEvent(g,f,S,v,C,_,T)}setSubscribedTrackSsrc(g){this.gathererV1.setSubscribedTrackSsrc(g)}addIceCandidateError(g){this.gathererV1.addIceCandidateError(g)}setH264AvailableProfiles(g){this.gathererV1.setH264AvailableProfiles(g)}setSupportedH264Profiles(g,f){this.gathererV1.setSupportedH264Profiles(g,f)}setTerminated(){this.gathererV1.setTerminated()}onDeviceEvent(g){this.gathererV1.onDeviceEvent(g)}getReport(g,f=!1){const S=this.gathererV1.getReport(g,f);if(this.gathererV2&&this.configProvider.config.diagnostics.sideBySide){const g=this.loopIntervalAggregator.getReport();g&&(S.data.Extensions.LoopIntervalMax=`${round(g.max,1)}`,S.data.Extensions.LoopIntervalMedian=`${round(g.median,1)}`);const f=this.fetchTimeAggregator.getReport();f&&(S.data.Extensions.FetchTimeMax=`${round(f.max,1)}`,S.data.Extensions.FetchTimeMedian=`${round(f.median,1)}`);const v=this.diagnostics.getObjectRef();S.data.Extensions.multipleVideoStreams=JSON.stringify(rebaseTime(v.multiViewStats,"startTime",v.startTime)),S.data.Extensions.OvcToSubscriptions=JSON.stringify(v.ovcToSubscriptionEvents),S.data.Extensions.videoPerformanceEvent=JSON.stringify(v.videoPerformanceEvent);const C=v.bandwidthReport;"REMB"===v.negotiation.bweType?(S.data.Extensions.StartCallBWE=JSON.stringify(C?.startOfTheCall),S.data.Extensions.EndCallBWE=JSON.stringify(C?.endOfTheCall),S.data.Extensions.BWEStd=JSON.stringify(C?.std),S.data.Extensions.BwPercentiles=JSON.stringify(C?.bwPercentiles),S.data.Extensions.AvgBwe=JSON.stringify(C?.avgBwe)):(S.data.Extensions.StartCallBWESendSide=JSON.stringify(C?.startOfTheCall),S.data.Extensions.EndCallBWESendSide=JSON.stringify(C?.endOfTheCall),S.data.Extensions.BWEStdSendSide=JSON.stringify(C?.std),S.data.Extensions.BwPercentilesSendSide=JSON.stringify(C?.bwPercentiles),S.data.Extensions.AvgBwSendSide=JSON.stringify(C?.avgBwe)),S.data.Extensions.InitialBWSeed=JSON.stringify(v.initialBWSeed),S.data.Extensions.SentBWSeed=JSON.stringify(v.sentBWSeed),S.data.Extensions.Bandwidth_downlinkStabilizationTime=JSON.stringify(v.bwDownlinkStabilizationTime),S.data.Extensions.ReinvitelessContext=JSON.stringify(v.reinvitelessContext),S.data.Extensions.ReportedSendBandwidth=JSON.stringify(v.reportedSendBandwidthLayouts),S.data.Extensions.Data_ProtocolCounters=JSON.stringify(v.dataChannel?.protocolCounters),S.data.Extensions.Data_Error=v.dataChannel?.error,S.data.Extensions.Data_SessionState=v.dataChannelSessionState?.toString(),S.data.Extensions.Data_CreateChannelError=v.dataChannelCreationError;const _=v.aggregatedModalityStats?.video?.recv||[],T=v.aggregatedModalityStats?.audio?.recv||[],I=v.aggregatedModalityStats?.sharing?.recv||[],b=v.aggregatedModalityStats?.video?.send||[],A=v.aggregatedModalityStats?.sharing?.send||[],P=S.data.Extensions.WebRTCStats,R=_[_.length-1],M=I[I.length-1],w=T[T.length-1],O=b[b.length-1],D=A[A.length-1],N=R?.aggregated?.macroblockRateStats??{},k=w?.aggregated?.customHealerStats??{};if(k?.pullPacketProcessingTimes){const g=getPercentilesProviderFromSampleFreqs(k.pullPacketProcessingTimes);k.pullPacketProcessingTimeP50=g.getPercentile(.5),k.pullPacketProcessingTimeP95=g.getPercentile(.95)}if(k?.pushPacketProcessingTimes){const g=getPercentilesProviderFromSampleFreqs(k.pushPacketProcessingTimes);k.pushPacketProcessingTimeP50=g.getPercentile(.5),k.pushPacketProcessingTimeP95=g.getPercentile(.95)}for(const g in N)S.data.Extensions[`Video_recv_${g}`]=`${round(N[g],0)}`;for(const g in v.totalVideoRecvMblocksRates)S.data.Extensions[`totalVideoRecv_${g}`]=`${round(v.totalVideoRecvMblocksRates[g],0)}`;for(const g in k)if(void 0!==k[g]){const f="number"!=typeof k[g]?JSON.stringify(k[g]):k[g];S.data.Extensions[`Audio_recv_customHealer_${g}`]=f}S.data.Extensions.MeetingScenario=JSON.stringify(v.negotiation.meetingScenario),S.data.Extensions.IsTownHall=JSON.stringify(v.negotiation.isTownHall),S.data.Extensions.Audio_send_presentationAPIUserDuration=JSON.stringify(v.presentationAPIUserDuration),S.data.Extensions.Audio_send_presentationDuration=JSON.stringify(v.presentationAudioDuration),S.data.Extensions.CodecSupport=JSON.stringify(v.codecSupport),S.data.Extensions.Video_recv_FpsHarmonicAverage=R?.extensions.fpsHarmonicAverage?.toString(),S.data.Extensions.Sharing_recv_FpsHarmonicAverage=M?.extensions.fpsHarmonicAverage?.toString(),S.data.Extensions.Sharing_recv_CodecReport=JSON.stringify(M?.aggregated?.codecReport),S.data.Extensions.Video_send_performanceEvents=JSON.stringify(limitArraySize2(rebaseTime(v.localVideoPerformanceEvents,"timestamp",v.startTime),this.configProvider.config.diagnostics.telemetryLimits.numPerformanceEvents)),P?.ssrc_sharing_send&&((P?.ssrc_sharing_send).retransmittedPacketsSent=sampleseries(v.aggregatedModalityStats?.sharing?.send,(g=>g.outboundRTP.retransmittedPacketsSent))),this.configProvider.config.diagnostics.features.takeFreezeTelemetryFromGathererV2&&(_.length&&(S.data.Extensions.Video_recv_FreezeHistogram=JSON.stringify(R.aggregated?.freezeCountHistogram),S.data.Extensions.Video_recv_LongestFreezeDuration=JSON.stringify(R?.aggregated?.longestFreeze),S.data.Extensions.Video_recv_OngoingFreeze=JSON.stringify(R?.extensions?.isFrozen),S.data.Extensions.Video_recv_OngoingFreezeDuration=JSON.stringify(R?.aggregated?.ongoingFreezeDuration),S.data.Extensions.Video_recv_TotalFreezeDuration=JSON.stringify(R?.aggregated?.totalFreezeDuration),S.data.Extensions.Video_recv_RecvAvgFreezeDuration=JSON.stringify(R?.aggregated?.avgFreezeDuration),S.data.Extensions.Video_recv_FreezeTimestamps=JSON.stringify(rebaseAndLimitHistogramTimestamps(R?.aggregated?.freezeTimestampsHistogram,v.startTime,this.configProvider.config.diagnostics.telemetryLimits.numOfHistogramSamples))),I.length&&(S.data.Extensions.Sharing_recv_FreezeHistogram=JSON.stringify(M.aggregated?.freezeCountHistogram),S.data.Extensions.Sharing_recv_LongestFreezeDuration=JSON.stringify(M?.aggregated?.longestFreeze),S.data.Extensions.Sharing_recv_OngoingFreeze=JSON.stringify(M?.extensions?.isFrozen),S.data.Extensions.Sharing_recv_OngoingFreezeDuration=JSON.stringify(M?.aggregated?.ongoingFreezeDuration),S.data.Extensions.Sharing_recv_TotalFreezeDuration=JSON.stringify(M?.aggregated?.totalFreezeDuration),S.data.Extensions.Sharing_recv_RecvAvgFreezeDuration=JSON.stringify(M?.aggregated?.avgFreezeDuration),S.data.Extensions.Sharing_recv_FreezeTimestamps=JSON.stringify(rebaseAndLimitHistogramTimestamps(M?.aggregated?.freezeTimestampsHistogram,v.startTime,this.configProvider.config.diagnostics.telemetryLimits.numOfHistogramSamples)))),S.data.Extensions.EarlyMedia={NumStatsPolls:`${v.earlyMediaNumStatsPolls}`},S.data.Extensions.Audio_recv_packetsLostRateMax=`${round(w?.aggregated?.lossRateMax,6)||0}`,S.data.Extensions.Audio_recv_networkAvgLossRate=`${round(w?.aggregated?.networkAvgLossRate,6)||0}`,S.data.Extensions.Video_recv_packetsLostRateMax=`${round(R?.aggregated?.lossRateMax,6)||0}`,S.data.Extensions.Sharing_recv_packetsLostRateMax=`${round(M?.aggregated?.lossRateMax,6)||0}`,S.data.Extensions.Video_send_packetsLostRateMax=`${round(O?.aggregated?.lossRateMax,6)||0}`,S.data.Extensions.Sharing_send_packetsLostRateMax=`${round(D?.aggregated?.lossRateMax,6)||0}`,this.configProvider.config.diagnostics.features.useNewSimulcastTelemetryExtension&&(S.data.Extensions.Video_send_Simulcast=JSON.stringify(v.simulcast?.video),S.data.Extensions.Sharing_send_Simulcast=JSON.stringify(v.simulcast?.sharing)),S.data.Extensions.Video_send_powerEfficientEncoderEvents=limitRebaseAndStringifyEvents(O?.extensions?.powerEfficientEncoderEvents,this.configProvider.config.diagnostics.telemetryLimits.numPowerEfficientEncoderEvents,"timestamp",v.startTime),S.data.Extensions.Video_send_powerEfficientEncoderEventOnCount=JSON.stringify(O?.extensions?.powerEfficientEncoderEventOnCount),S.data.Extensions.Video_send_powerEfficientEncoderEventOffCount=JSON.stringify(O?.extensions?.powerEfficientEncoderEventOffCount)}return removeUndefinedFields(S)}startWaitingForStreamStart(g){this.gathererV1.startWaitingForStreamStart(g)}getTimerTracker(g,f){return this.gathererV1.getTimerTracker(g,f)}getLastStatistics(){return this.gathererV1.getLastStatistics()}updateSendStream(g,f){this.gathererV1.updateSendStream(g,f)}setSubscribedTrackIds(g){this.gathererV1.setSubscribedTrackIds(g)}setMaxSessionBandwidth(g){this.gathererV1.setMaxSessionBandwidth(g)}updateStatsWithLocalSsrcTrackInfo(){this.gathererV1.updateStatsWithLocalSsrcTrackInfo()}onSendersChanged(g,f){this.gathererV1.onSendersChanged(g,f)}setPreferredResolution(g,f,S){this.gathererV1.setPreferredResolution(g,f,S)}setIsRendering(g,f,S){this.gathererV1.setIsRendering(g,f,S)}setTimeToFirstFrame(g,f,S){this.gathererV1.setTimeToFirstFrame(g,f,S)}setFreezeDuration(g,f){this.gathererV1.setFreezeDuration(g,f)}addVideoControlMessage(g){this.gathererV1.addVideoControlMessage(g)}onMaxCapabilitiesRequested(g){this.gathererV1.onMaxCapabilitiesRequested(g)}addReportedReceiveBandwidth(g){this.gathererV1.addReportedReceiveBandwidth(g)}},YI=101,QI=[48e3,32e3,24e3,16e3,12e3],XI=class{constructor(g){this.context=g,this.cname=uniqueId(),this.dataMedia={type:qt.MEDIA_TYPE.data,protocol:qt.PROFILES.rtpSavp,port:0},this.configProvider=g.configProvider,this.logger=g.getLogger().createChild("WebkitSdpTrans")}fixTelephoneEvent(g){let f;return QI.forEach((f=>{removeCodec(g,{codec:"telephone-event",rate:f})})),updatePayload(g,YI,999),forOneCodec(g,{codec:"telephone-event",rate:8e3},(g=>(f=g.rtp.payload,g.rtp.payload=YI,g))),updatePayload(g,999,f||YI),f}toLocal(g,f,S){const v=f.isEmpty(),C=deepClone(g);let _;return C.media.forEach((g=>{if("audio"===g.type)v&&(_=this.fixTelephoneEvent(g)),fixComfortNoise(g);else{_&&updatePayload(g,YI,_);const S=f.getLocalSsrcs().get(getModality(g));this.enforceFixedSsrc(g,S)}const C=getAllowedCodecs(this.configProvider,g.type);"offer"===S&&filterCodecs2(g,C,v,this.logger)})),new g_(this.configProvider).modify(C),delete C.extmapAllowMixed,C}toOffer(g,f,S){return this.fromNative(g,f,S,!0)}toAnswer(g,f,S){return this.fromNative(g,f,S,!1)}toRemote(g,f,S,v){const C=deepClone(g);let _,T,I=this.configProvider.mediaConfig.maxBandwidthInKbps;C.bandwidth&&(!I||I>+g.bandwidth[0].limit)&&(I=+g.bandwidth[0].limit),C.media.forEach(((g,S)=>{f.getMediaEntity(S).isDisabled()&&g.type!==qt.MEDIA_TYPE.audio&&(g.port=0)}));let b=getBundle2(C);if(!b){let g=!1;C.media.forEach(((S,v)=>{const C=f.getMediaEntity(v);!g&&C.isEnabled()?(S.mid=C.getMid(),g=!0):(C.disable(),S.port=0)})),g&&(C.groups||(C.groups=[]),b={type:"BUNDLE"},C.groups.push(b))}C.media.forEach((g=>{const f=getModality(g);S[f]===qt.MEDIA_STATE.send&&(g.direction&&g.direction.toLowerCase()===qt.MEDIA_STATE.receive||(g.direction=qt.MEDIA_STATE.receive))}));const A=C.media.filter((g=>g.type===qt.MEDIA_TYPE.video));if(A.length>0){const g=A.filter((g=>0!==g.port));if(g.length>0){T=deepClone(g[0]),T.bandwidth&&delete T.bandwidth;const f=this.configProvider.config.audioBandwidthInKbps?this.configProvider.config.audioBandwidthInKbps:0;I&&I-f>0&&(T.bandwidth=[{limit:I-f,type:"AS"}]),T.mid="video",T.direction=null,delete T.label,T.ssrcs=[],T.ssrcGroups=[],delete T.msid,g.forEach((g=>{g.ssrcs&&(T.ssrcs=T.ssrcs.concat(g.ssrcs)),g.ssrcGroups&&(T.ssrcGroups=T.ssrcGroups.concat(g.ssrcGroups)),T.direction=mergeDirections(T.direction,g.direction||qt.MEDIA_STATE.sendReceive)})),removeUnifiedPlanExtensions(T)}else T=disabledMedia2(qt.MEDIA_TYPE.video,void 0,A[0].protocol,A[0].payloads)}const P=C.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(P)if(0!==P.port)_=deepClone(P),_.mid="audio",delete _.label,removeG722Codec(_),fixComfortNoise(_),removeUnifiedPlanExtensions(_);else{_=disabledMedia2(qt.MEDIA_TYPE.audio,void 0,P.protocol,P.payloads);const g=C.media.find((g=>!!g.iceUfrag));g&&(_.port=9,_.direction="inactive",_.mid="audio",_.iceUfrag=g.iceUfrag,_.icePwd=g.icePwd,_.rtcpMux="rtcp-mux",g.crypto&&(_.crypto=g.crypto),g.fingerprint&&(_.fingerprint=g.fingerprint,_.setup=g.setup),_.rtp=[{payload:0,codec:"PCMU",rate:8e3}],_.payloads="0")}C.media.forEach(((g,f)=>{g.type===qt.MEDIA_TYPE.data&&(g.type=qt.MEDIA_TYPE.dataChannel,g.payloads=qt.PAYLOAD_TYPE.DATA_CHANNEL,g.protocol=qt.PROFILES.udpDtlsSctp,g.mid="data",delete g.xDataProtocol,delete g.direction,isMediaDisabled(g)&&(C.media[f]=disabledMedia2(g.type,void 0,g.protocol,g.payloads)))}));const R=allowDataChannel(this.context)?C.media.find((g=>g.type===qt.MEDIA_TYPE.dataChannel)):null;C.media=[_,T,R].filter((g=>g)),f.getMediaEntities()[0].getModality()!==qt.MODALITY.audio&&C.media.reverse();const M=preferSdesSrtp(this.context.configProvider,this.context.config.isPstnCall),w=getSrtpInfo(g);return C.media.forEach((g=>{g.type!==qt.MEDIA_TYPE.dataChannel&&(!M&&g.fingerprint&&g.crypto&&delete g.crypto,g.protocol=!w.dtls||w.sdes&&M?qt.PROFILES.rtpSavpf:qt.PROFILES.udpTlsRtpSavpf)})),"offer"===v&&(filterCodecs2(_,this.configProvider.config.allowedAudioCodecs,!1,this.logger),filterCodecs2(T,this.configProvider.config.allowedVideoCodecs,!1,this.logger)),fixBundling(C,this.configProvider.mediaConfig.isTransportUnbundled),C}splitMedia(g,f,S,v,C){const _=g.getMid(),T=g.getModality(),I=deepClone(f);if(I.label=getLabelForModality(T),I.direction=v,I.mid=_,I.ssrcs=[],I.ssrcGroups=[],g.getModality()===qt.MODALITY.data)return I.type=qt.MEDIA_TYPE.data,I.payloads=qt.PAYLOAD_TYPE.X_DATA,I;const b=S.filter((g=>g.modality===T));if(b&&b.length){const g=[];f.ssrcs&&(b.forEach((S=>{const v=f.ssrcs.filter((g=>"msid"===g.attribute&&S.trackId===getTrackId(g.value))).map((g=>g.id));g.push(...v)})),I.ssrcs=f.ssrcs.filter((f=>g.indexOf(+f.id)>-1)),I.ssrcs.forEach((g=>{"cname"===g.attribute&&(g.value=this.cname)}))),f.ssrcGroups&&(I.ssrcGroups=f.ssrcGroups.filter((f=>f.ssrcs.split(" ").find((f=>g.indexOf(+f)>-1)))))}else{if(v===qt.MEDIA_STATE.send||v===qt.MEDIA_STATE.sendReceive)return disabledMedia2(f.type,getLabelForModality(T),f.protocol,f.payloads);v!==qt.MEDIA_STATE.receive&&v!==qt.MEDIA_STATE.inactive||(C[f.type].ssrcs?.[0]?I.ssrcs=[{id:C[f.type].ssrcs[0].id,attribute:"cname",value:this.cname}]:f.type===qt.MEDIA_TYPE.audio?I.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:f.type===qt.MEDIA_TYPE.video&&(I.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}return I}fromNative(g,f,S,v){const C=deepClone(g),_=this.configProvider.mediaConfig.maxBandwidthInKbps;_&&(C.bandwidth=[{limit:_,type:"CT"}]),new p_(this.configProvider).modify(C);const T=C.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),I=C.media.find((g=>g.type===qt.MEDIA_TYPE.video)),b=C.media.find((g=>g.type===qt.MEDIA_TYPE.dataChannel)),A={};A[qt.MODALITY.audio]=T,A[qt.MODALITY.video]=I,A[qt.MODALITY.sharing]=I,A[qt.MODALITY.data]=b||this.dataMedia;const P={};P[qt.MEDIA_TYPE.audio]=T,P[qt.MEDIA_TYPE.video]=I,P[qt.MEDIA_TYPE.data]=b||this.dataMedia;const R={};return R[qt.MODALITY.audio]=f.getMediaEntitiesByModality(qt.MODALITY.audio)[0],R[qt.MODALITY.video]=f.getMediaEntitiesByModality(qt.MODALITY.video)[0],R[qt.MODALITY.sharing]=f.getMediaEntitiesByModality(qt.MODALITY.sharing)[0],R[qt.MODALITY.data]=f.getMediaEntitiesByModality(qt.MODALITY.data)[0],C.media=[],f.getMediaEntities().forEach((g=>{let _,T=S[g.getModality()];!g.isEnabled()||0===A[g.getModality()].port||g!==R[g.getModality()]&&T===qt.MEDIA_STATE.send?(_=disabledMedia2(g.getType(),getLabelForModality(g.getModality()),A[g.getModality()].protocol,A[g.getModality()].payloads),A[g.getModality()].payloads===qt.PAYLOAD_TYPE.DATA_CHANNEL&&(_.payloads=qt.PAYLOAD_TYPE.DATA_CHANNEL)):(T!==qt.MEDIA_STATE.inactive&&g!==R[g.getModality()]&&(T=qt.MEDIA_STATE.receive),_=this.splitMedia(g,A[g.getModality()],f.getLocalTracksInfo(),T,P),g!==R[g.getModality()]&&(_.candidates=[]));const I=A[g.getModality()].setup;I&&("actpass"!==I?g.setExtension("setup",I):v&&void 0!==g.getExtension("setup")&&(_.setup="actpass"!==g.getExtension("setup")?g.getExtension("setup"):I));const b=A[g.getModality()].iceUfrag,M=g.getExtension("iceUfrag");g.setExtension("iceRestart",!!b&&!!M&&M!==b),g.setExtension("iceUfrag",b),isMediaDisabled(_)&&g.disable(),C.media.push(_)})),new wE(this.context,S.data).modify(C),fixBundling(C,this.configProvider.mediaConfig.isTransportUnbundled),C}enforceFixedSsrc(g,f){let S=-1;if(!g.ssrcs)return;const v=[];if(g.ssrcs.forEach((g=>{"msid"===g.attribute&&v.push({ssrc:g.id,trackId:getTrackId(g.value)})})),g.ssrcs.forEach((g=>{"cname"===g.attribute&&S++,f&&(g.id=this.getVideoSSRC(S,f))})),g.ssrcGroups){const f=g.ssrcs.filter((g=>"cname"===g.attribute)).map((g=>g.id));g.ssrcGroups.forEach(((g,S)=>{g.ssrcs=[f[2*S],f[2*S+1]].join(" ")}))}}getVideoSSRC(g,f){return g%2==1?f+50:f}};function removeG722Codec(g){removeCodec(g,{codec:"g722",rate:8e3,encoding:2})}function removeUnifiedPlanExtensions(g){const f=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);g.ext&&(g.ext=g.ext.filter((g=>!f.has(g.uri))))}function fixComfortNoise(g){removeCodec(g,{codec:"CN",rate:16e3})}function getBundle2(g){return g.groups?g.groups.find((g=>"BUNDLE"===g.type)):null}function fixBundling(g,f){const S=g.groups?.findIndex((g=>"BUNDLE"===g.type)),v=g.groups?g.groups[S]:void 0;v&&(f?(v.mids=g.media.filter((g=>g.type===qt.MEDIA_TYPE.video)).map((g=>g.mid)).filter((g=>g)).join(" "),v.mids||delete g.groups[S]):v.mids=g.media.map((g=>g.mid)).filter((g=>g)).join(" "))}function disabledMedia2(g,f,S,v){return{type:g,port:0,label:f,payloads:v,protocol:S}}function getTrackId(g){return g.split(" ")[1]}function mergeDirections(g,f){return g===qt.MEDIA_STATE.sendReceive||f===qt.MEDIA_STATE.sendReceive?qt.MEDIA_STATE.sendReceive:g===f?g:g&&f&&g!==f?qt.MEDIA_STATE.sendReceive:g||f}function filterCodecs2(g,f,S,v){if(!f.length||!g?.port)return;filterCodecs(g,convertToCodecInfo(f),S,v)}var ZI=__toESM(we()),eb=class{getCapabilities(g){const f=RTCRtpReceiver.getCapabilities(g);return f.codecs.forEach((g=>{g.mimeType=g.mimeType.toLowerCase().split("/").pop()})),Promise.resolve(f)}},tb=class{getCapabilities(g){const f=RTCRtpSender.getCapabilities(g);return f.codecs.forEach((g=>{g.mimeType=g.mimeType.toLowerCase().split("/").pop()})),Promise.resolve(f)}},ib=class{constructor(g,f){this.noRequiredCodecsWorkaround=f,this.selfGlobal=g.global.capabilityGatherer=g.global.capabilityGatherer||{},this.getCapabilities("video")}async getCapabilities(g){if("video"!==g&&"audio"!==g)return Promise.reject(new Error(`capabilities for ${g} are not supported`));if(!this.selfGlobal.gatherTask){const g=new dt;this.selfGlobal.gatherTask=g.promise;const f=void 0!==Xs.window.webkitRTCPeerConnection,S=f?new Xs.window.webkitRTCPeerConnection(null):new Xs.window.RTCPeerConnection(null),createOfferWrapper=g=>f?new Promise(((f,v)=>{S.createOffer(f,v,g)})):(this.noRequiredCodecsWorkaround&&S.addTrack(S.addTransceiver("video").receiver.track),S.createOffer(g));try{const f=await createOfferWrapper({offerToReceiveVideo:1,offerToReceiveAudio:1}),v={};ZI.parse(f.sdp).media.forEach((g=>{v[g.type]=g.rtp.map((f=>{const S={mimeType:f.codec.toLowerCase()};if("video"===g.type){const v=g.fmtp?.find((g=>g.payload===f.payload));S.sdpFmtpLine=v?.config}return S}))})),S.close(),g.resolve(v)}catch(f){this.selfGlobal.gatherTask=null,S.close(),g.reject(f)}}return this.selfGlobal.gatherTask.then((f=>({codecs:f[g]})))}},nb={build:(g,f,S=!1,v=!1)=>v?new tb:!f&&oa.hasCapabilitiesApi()?new eb:new ib(g,S)},rb=__toESM(we()),sb="rollback";function SessionDescription2(){const g=[].slice.apply(arguments);let f=g[0]&&isRollback(g[0].type);g.splice(0,f?1:0,null);const S=new(Function.prototype.bind.apply(Xs.window.RTCSessionDescription,g)),v=Object.getOwnPropertyDescriptor(Xs.window.RTCSessionDescription.prototype,"type");return Object.defineProperty(S,"type",{get:()=>f?sb:v.get.call(S),set(g){f=isRollback(g),f||v.set.call(S,g)}}),S}function isRollback(g){return sb===g}var ab={build:()=>SessionDescription2},ob=[{codec:"telephone-event",rate:8e3},{codec:"cn",rate:16e3}];function PeerConnection(g){const f=[],S=ab.build(),v=[].slice.apply(arguments);v.splice(0,1,null),overrideSetting("iceTransportPolicy","iceTransports");const C=new(Function.prototype.bind.apply(Xs.window.webkitRTCPeerConnection,v));function overrideSetting(g,f){v[1]?.[g]&&(v[1][f]=v[1][g])}function shim(){shimPromises(),shimSetRemoteDescription(),shimCreateAnswer(),shimCreateOffer(),shimSenders()}function shimPromises(){[{name:"createOffer",reverseArgs:!0},"createAnswer","setRemoteDescription","setLocalDescription"].forEach((function(g){const f=g.name||g,S=C[f];C[f]=function(){const f=arguments;return new Promise((function(v,_){const T=[v,_];f.length>0&&T.splice(g.reverseArgs?T.length:0,0,f[0]),S.apply(C,T)}))}}))}function Sender(g,f){let S;Object.defineProperty(this,"dtmf",{get:()=>"audio"===g.kind?(S=S||C.createDTMFSender(g),S):null}),this.track=g,this._stream=f}function shimSenders(){C.getSenders&&C.addTrack&&C.removeTrack||(C.getSenders=function(){return f.slice()},C.addTrack=function(g,S){if(!g||!S)throw new Error("both media track and stream need to be provided");C.getLocalStreams().some((function(g){return g.id===S.id}))||C.addStream(S);let v=f.find((function(f){return f.track.id===g.id}));return v||(v=new Sender(g,S),f.push(v)),v},C.removeTrack=function(g){C.getLocalStreams().filter((function(f){return f.id===g._stream.id})).forEach((function(g){C.removeStream(g)})),remove2(f,(f=>f===g))})}function shimCreateOffer(){const g=C.createOffer;C.createOffer=function(f){const S=arguments;return f&&f.offerToReceiveVideo>1&&(f.offerToReceiveVideo=1),g.apply(C,S)}}function shimSetRemoteDescription(){["createOffer","createAnswer","setLocalDescription"].forEach((function(f){const S=C[f];C[f]=function(){const f=arguments;return g.getCapabilities("video").then((function(){return S.apply(S,f)}))}}));const f=C.setRemoteDescription;C.setRemoteDescription=function(S){return g.getCapabilities("video").then((function(g){const v=g.codecs,C=rb.parse(S.sdp);return C.media.forEach((function(g){if("video"===g.type){g.rtp.some((function(g){return v.some((function(f){return g.codec.toLowerCase()===f.mimeType}))}))?suppressH264FormatParameters(g):g.port=0}if(!hasDtls(g)){const f=getBundle(C);f?g.crypto=f.crypto:g.port||C.media.some((function(f){return!!f.port&&(g.crypto=f.crypto,!0)}))}})),S.sdp=rb.write(C),f(S)}))}}function shimCreateAnswer(){const g=C.createAnswer;C.createAnswer=function(){const f=arguments;return g.apply(C,f).then((function(g){if(!C.localDescription?.sdp)return g;const f=rb.parse(C.localDescription.sdp),v=[];if(f.media.forEach((function(g){ob.forEach((function(f){forOneCodec(g,f,(function(g){v.push(g)}))}))})),v.length){const f=rb.parse(g.sdp);let C=!1;f.media.forEach((function(g){v.forEach((function(f){forOneCodec(g,{codec:f.rtp.codec,rate:f.rtp.rate},(function(g){g.rtp.payload!==f.rtp.payload&&(g.rtp.payload=f.rtp.payload,C=!0)}))}))})),C&&(g=new S({type:g.type,sdp:rb.write(f)}))}return g}))}}function suppressH264FormatParameters(g){forOneCodec(g,{codec:"h264",rate:9e4},(function(g){if(g.fmtp){const f=new Zy,S=new Zy(g.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((function(g){if(S.contains(g)){let v=S.get(g);"profile-level-id"===g&&(v="42C02A"),f.setIfMissing(g,v)}})),g.fmtp.config=f.toString()}}))}function hasDtls(g){return"RTP/SAVPF"!==g.protocol}return shim(),C}var lb={build:g=>PeerConnection.bind(null,g)},cb=class{constructor(g){const f=g.configProvider.config.useSdpCapabilitiesLegacySession,S=g.configProvider.config.noRequiredCodecsWorkaround;this.RTCRtpReceiver=nb.build(g,f,S),this.SdpTransform=XI,this.RTCPeerConnection=lb.build(this.RTCRtpReceiver),this.RTCSessionDescription=ab.build()}};function UnsupportedAdapter(){function throwUnsupported(){throw new Error("unsupported platform")}this.SdpTransform=throwUnsupported,this.RTCPeerConnection=throwUnsupported,this.RTCSessionDescription=throwUnsupported,this.RTCRtpReceiver=throwUnsupported,this.RTCRtpSender=throwUnsupported}function isWebkitRtc(){return void 0!==Xs.window.webkitRTCPeerConnection}var db={build:g=>isWebkitRtc()?new cb(g):new UnsupportedAdapter},hb=class{constructor(g,f,S,v){this.logger=g,this.configProvider=f,this.activeSpeakerManager=S,this.contributingSourcesProvider=v,this.lastSources=[],this.emptySourcesCount=0,this.poll=()=>{const g=this.contributingSourcesProvider?.getContributingSources();if(!g)return this.logger.safe.info(`Contributing sources are not supported on this client. Retries attempts: ${this.emptySourcesCount}`),void(this.emptySourcesCount>0?(this.emptySourcesCount--,this.timer=window.setTimeout(this.poll,this.configProvider.config.webrtcContributingSourcesPollingInterval)):this.dispose());this.activeSpeakerManager.onContributingSourcesChanged(g.filter((g=>{const f=this.lastSources.find((f=>f.source===g.source));return!f||f.timestamp!==g.timestamp})).map((g=>g.source))),this.updateLastSources(g),this.timer=window.setTimeout(this.poll,this.configProvider.config.webrtcContributingSourcesPollingInterval)},this.emptySourcesCount=this.configProvider.config.webrtcContributingSourcesPollingEmptySources,this.startPolling(this.configProvider.config.webrtcContributingSourcesPollingStartDelay)}dispose(){this.stopPolling(),this.contributingSourcesProvider=void 0}useCustomCodec(g){g?this.stopPolling():this.startPolling()}updateContributingSources(g){this.activeSpeakerManager.onContributingSourcesChanged(g)}startPolling(g=this.configProvider.config.webrtcContributingSourcesPollingInterval){!this.timer&&this.contributingSourcesProvider&&(this.logger.safe.info("Polling started"),this.timer=window.setTimeout(this.poll,g))}stopPolling(){this.timer&&(this.logger.safe.info("Polling stopped"),window.clearTimeout(this.timer),this.timer=void 0)}updateLastSources(g){this.lastSources=g.map((g=>({source:g.source,timestamp:g.timestamp})))}},ub=class{constructor(g,f,S,v){this.logger=g,this.peerConnection=f,this.logDiagnosticsError=S,this.sessionDiagnostics=v}getContributingSources(){try{if(!this.peerConnection?.getReceivers)return;const g=this.peerConnection.getReceivers().find((g=>"audio"===g.track.kind));return g?g.getContributingSources?.():[]}catch(g){return this.logger.safe.error("Failed to get contributing sources",g),void(this.logDiagnosticsError&&this.sessionDiagnostics&&(this.sessionDiagnostics.contributingSourcesError=`${g}`))}}},gb=class{constructor(g){this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.localSsrcs=new Map,this.ssrcGenerator=new hE,this.logger=g.logger.createChild("MM"),this.configProvider=g.configProvider,this.numVideoChannels=g.numVideoChannels}fromOffer(g,f){g.media.forEach((g=>{if(g.type===qt.MEDIA_TYPE.audio)qt.MODALITY.audio in f&&this.addMediaEntity(qt.MODALITY.audio);else if(g.type===qt.MEDIA_TYPE.video){if(qt.MODALITY.video in f)for(let g=0;g<this.numVideoChannels;g++)this.addMediaEntity(qt.MODALITY.video);qt.MODALITY.sharing in f&&this.addMediaEntity(qt.MODALITY.sharing)}else g.type===qt.MEDIA_TYPE.data&&qt.MODALITY.data in f&&this.addMediaEntity(qt.MODALITY.data)}))}fromRemote(g,f){g.media.forEach(((g,S)=>{const v=getModality(g);if(isMediaDisabled(g)||!(v in f))this.mediaEntities[S]?this.mediaEntities[S].disable():this.addDisabledMediaEntity(v),this.mediaEntities[S].setRemoteStreamId(null),this.mediaEntities[S].setRemoteTrackId(null);else{if(this.mediaEntities[S]?this.mediaEntities[S].update(v,g.mid||this.generateMid(S)):this.addMediaEntity(v,g.mid||this.generateMid(S)),g.msid)this.mediaEntities[S].setRemoteStreamId(g.msid.split(" ")[0]),this.mediaEntities[S].setRemoteTrackId(g.msid.split(" ")[1]);else if(g.ssrcs){const f=g.ssrcs.find((g=>"msid"===g.attribute));f?(this.mediaEntities[S].setRemoteStreamId(f.value.split(" ")[0]),this.mediaEntities[S].setRemoteTrackId(f.value.split(" ")[1])):this.logger.safe.warn(`No ssrc msid for media of type ${g.type} with mid ${g.mid}`)}const f=g.xSourceStreamId||this.generateSourceStreamId(S);this.mediaEntities[S].setXSourceStreamId(f)}}))}isEmpty(){return 0===this.mediaEntities.length}addMediaEntity(g,f){this.createMediaEntity(g,f||this.generateMid(this.mediaEntities.length))}addDisabledMediaEntity(g){this.createMediaEntity(g)}getMediaEntities(){return this.mediaEntities}createMediaEntity(g,f){const S=SE.create(this.configProvider,g,f);return this.mediaEntities.push(S),S}getMediaEntity(g){return this.mediaEntities[g]}getMediaEntityByMid(g){return this.mediaEntities.find((f=>f.getMid()===g))}getMediaEntitiesByModality(g){return this.mediaEntities.filter((f=>f.getModality()===g))}getMediaEntityByRemoteStreamId(g){return this.mediaEntities.find((f=>f.getRemoteStreamId()===g))}getMediaEntityByLocalTrackId(g){return this.mediaEntities.find((f=>f.getLocalTrackId()===g))}getMediaEntityByXSourceStreamId(g){return this.mediaEntities.find((f=>f.getXSourceStreamId()===g))}reset(){this.mediaEntities=[]}syncModalities(g,f,S){this.disableModalities(f),S||(this.enableModalities(f),this.addModalities(f))}enableModalities(g){this.mediaEntities.forEach(((f,S)=>{f.getModality()in g&&f.isDisabled()&&f.update(f.getModality(),this.generateMid(S))}))}disableModalities(g){this.mediaEntities.forEach((f=>{f.getModality()in g||f.disable()}))}setRollbackUpdateHandler(g){}addModalities(g){const f={};this.mediaEntities.map((g=>g.getModality())).forEach((g=>{f[g]=!0}));for(const S in g)S in f||this.addMediaEntity(S)}setLocalTracksInfo(g){this.mediaTracks=g,this.updateLocalSsrc(this.mediaTracks)}getLocalTracksInfo(){return this.mediaTracks}getLocalSsrcs(){return this.localSsrcs}updateMediaEntitiesWithLocalTracks(){this.mediaTracks&&(this.mediaEntities.forEach((g=>g.setLocalTrackId(null))),this.mediaTracks.forEach((g=>{const f=this.getMediaEntitiesByModality(g.modality)[0];f?f.setLocalTrackId(g.trackId):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(g.modality)}`)})))}updateMediaEntitiesWithActivityState(g,f){}backup(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((g=>{this.mediaEntitiesBackup.push(g.clone())}))}commit(){this.mediaEntitiesBackup=[]}rollback(){this.mediaEntities=this.mediaEntitiesBackup}generateSourceStreamId(g){return g+10}generateMid(g){return`media_${g}`}updateLocalSsrc(g){g.forEach((g=>{if(!this.localSsrcs.get(g.modality)){const f=this.ssrcGenerator.nextVideoStreamSsrc().min;this.logger.safe.debug(`Ssrc updated for modality: ${g.modality}: ${f}`),this.localSsrcs.set(g.modality,f)}}))}},pb=__toESM(we()),mb=class{constructor(g,f,S,v,C){this.logger=g,this.RtcDescType=f,this.sessionDescription=S,this.negotiationQueue=v,this.mediaManager=C}configure(g){this.peerConnection=g}renegotiateNow(){return this.renegotiate(null,!0)}renegotiate(g,f=!1,S="local"){if(!this.peerConnection)throw new Error("trying to renegotiate without a peerConnection");const v="local"===S?this.createNegotiationTaskForHaveLocalOffer(g):this.createNegotiationTaskForHaveRemoteOffer();return f?(this.logger.safe.info(`forced ${S} renegotiation starting`),Promise.resolve(v())):this.negotiationQueue.add(v)}normalizeRemoteSdpSDES(g,f){if(f.media[0].crypto)g.media.forEach((g=>{delete g.fingerprint,delete g.setup,g.crypto=g.crypto.filter((g=>f.media[0].crypto.some((f=>f.id===g.id)))).slice(0,1)})),g.fingerprint&&delete g.fingerprint;else{const f=this.mediaManager.getMediaEntities().find((g=>void 0!==g.getExtension("setup")));g.media.forEach((g=>{const S=f?.getExtension("setup")||"actpass";"actpass"===g.setup&&(g.setup="active"===S?"passive":"active")}))}}normalizeRemoteSdpExtensions(g,f){g.media.forEach(((g,S)=>{const v=new Set(f.media[S].ext?.map((g=>g.value))||[]);g.ext=g.ext?.filter((g=>v.has(g.value)))}))}createNegotiationTaskForHaveLocalOffer(g){return async()=>{let f=this.peerConnection.remoteDescription.sdp;const S=this.peerConnection.localDescription.sdp;this.logger.safe.info(`local renegotiation starting remoteSdp=${!!f} localSdp=${!!S}`);const v=pb.parse(f),C=pb.parse(S);this.normalizeRemoteSdpSDES(v,C),this.normalizeRemoteSdpExtensions(v,C),f=pb.write(v);let _=new this.RtcDescType({sdp:f,type:"answer"});g&&g.forEach((g=>{_=g.modifyDescriptor(_)}));try{this.logger.safe.info("creating offer");const g=await this.peerConnection.createOffer(),f=this.sessionDescription.createLocalOffer(g.sdp),S=new this.RtcDescType({sdp:f.toLocal(),type:"offer"});this.logger.safe.info("setting local description"),this.logger.unsafe.debug(`local description, sdp: ${S.sdp}`),await this.peerConnection.setLocalDescription(S),this.logger.safe.info("setting remote description"),this.logger.unsafe.debug(`remote description, sdp: ${_.sdp}`),await this.peerConnection.setRemoteDescription(_),this.logger.safe.debug("local renegotiation done")}catch(g){throw this.logger.safe.error("local renegotiation failed: ",g.toString()),g}}}createNegotiationTaskForHaveRemoteOffer(){return this.logger.safe.info("createNegotiationTaskForRemote"),async()=>{this.logger.safe.info("proceed with setting local sdp start");try{this.logger.safe.info("creating answer");const g=await this.peerConnection.createAnswer();this.logger.safe.info("applying answer");const f=this.sessionDescription.createLocalAnswer(g.sdp),S=new this.RtcDescType({sdp:f.toLocal(),type:"answer"});this.logger.safe.info("setting [answer] local description"),this.logger.unsafe.debug(`[answer] local description, sdp: ${S.sdp}`),await this.peerConnection.setLocalDescription(S),this.logger.safe.info("local answer for renegotiation is done")}catch(g){throw this.logger.safe.error("local answer for renegotiation failed: ",g.toString()),g}}}},fb=15e3,Sb=5e3,vb=class{constructor(g,f,S){this.settings=g,this.listener=f,this.logger=S,this.lastSendBW=0,this.coolingDown=!1,this.cooldownTimer=null,this.cooldownEnd=0,this.active=!1,this.maxResolution=this.settings.maxResolution,this.settings.scalingEnabled?this.active=!0:this.logger.safe.info("Resolution management disabled: no resolution management for 1x1 calls")}dispose(){this.currentResolution=null,this.pendingResolution=null,this.maxResolution=null,this.listener=null,this.active=!1,clearTimeout(this.cooldownTimer),this.cooldownTimer=null,this.listener=null}setMaxResolution(g){const f=ei.Send.getResolutionByFs(g);f!==this.maxResolution&&(this.logger.safe.info(`Setting max resolution: ${f}`),this.maxResolution=f,this.lastSendBW&&this.processEstimatedBandwidth(this.lastSendBW))}updateEstimatedSendBandwidth(g){g!==this.lastSendBW&&(this.logger.safe.debug(`Send BW: ${g}`),this.processEstimatedBandwidth(g))}resetCurrentResolution(){this.currentResolution=null}getCurrentResolution(){return this.currentResolution?.fs}setCurrentResolution(g){this.currentResolution=g}applyRes(g){this.pendingResolution=g,this.coolingDown&&(!this.currentResolution||g.fs>this.currentResolution.fs)||(this.coolingDown=!0,this.logger.safe.info(`Changing resolution to ${g}`),this.listener&&this.listener.onResolutionChanged(g.fs).then((f=>{f?(g===this.pendingResolution&&(this.pendingResolution=null),this.coolingDown&&!this.currentResolution&&(this.coolingDown=!1),this.currentResolution=g,this.cooldown()):(this.logger.safe.info("Unable to apply resolution at the moment"),this.cooldown(Sb))})).catch((g=>{this.logger.safe.error(`Error while applying new resolution: ${JSON.stringify(g)}`),this.pendingResolution=null})))}cooldown(g=fb){!this.active||this.coolingDown&&this.cooldownEnd-Date.now()>fb||(this.cooldownTimer&&clearTimeout(this.cooldownTimer),this.coolingDown=!0,this.cooldownEnd=Date.now()+fb,this.cooldownTimer=setTimeout((()=>{this.logger.safe.debug("Resolution changer cooled down"),this.coolingDown=!1,this.cooldownTimer=null,this.pendingResolution?this.proposeResolution(this.pendingResolution):this.processEstimatedBandwidth(this.lastSendBW)}),g))}proposeResolution(g){let f=g;this.maxResolution&&this.maxResolution.fs<f.fs&&(f=this.maxResolution),this.currentResolution&&f.fs===this.currentResolution.fs||this.applyRes(f)}processEstimatedBandwidth(g){const{lowRes:f,highRes:S}=ei.Send.getResolutionForBitrate(g),v=g<this.lastSendBW?S:f;g<this.lastSendBW&&v&&this.currentResolution&&this.currentResolution.fs<v.fs||(v&&this.proposeResolution(v),this.lastSendBW=g)}};function calculateEstimatedSendBandwidth(g,f){const S=f.config.maxBandwidthInKbpsFallback>0?f.config.maxBandwidthInKbpsFallback:Math.floor(Number.MAX_SAFE_INTEGER/1e3),v=1e3*((f.mediaConfig.maxBandwidthInKbps||S)-(f.config.audioBandwidthInKbps||0)),C=g.transport?.selectedCandidatePair?.availableOutgoingBitrate??0;return Math.min(v,C)}var Cb=class extends Ht{constructor(g,f){super(f),this.configProvider=g,this.logger=f,this.lastReportedAgo=1/0,this._forceUpdate=!1}forceUpdate(){this._forceUpdate=!0}onBandwidthChanged(g){this._forceUpdate?this.updateBandwidth(g,"forceUpdate"):this.processEstimatedBandwidth(g)}processEstimatedBandwidth(g){if(this.lastReportedAgo++,!g||this.bandwidth===g)return;const f=this.configProvider.config.webrtcSendBandwidthIgnoredUpdateLimit,S=this.configProvider.config.webrtcSendBandwidthThreshold,v=this.lastReportedAgo===1/0,C=!f&&!S,_=f&&this.lastReportedAgo>=f,T=S&&Math.abs((g-this.bandwidth)/this.bandwidth)>=S;if(v||C||_||T){const f=+v|+C<<1|+_<<2|+T<<3,S=this.getUpdateReason(f);this.updateBandwidth(g,S)}}updateBandwidth(g,f){this.bandwidth=g,this.logger.safe.debug(`Updating send bandwidth: ${this.bandwidth}, reason: ${f}`),this.notifySendBandwidthChanged()}notifySendBandwidthChanged(){this._forceUpdate=!1,this.event("onSendBandwidthChanged").raise(this.bandwidth),this.lastReportedAgo=0}getUpdateReason(g){return 1&g?"firstReport":2&g?"throttlingDisabled":4&g?"noReportsForTooLong":8&g?"bigMovement":"none"}},yb=class{constructor(g,f,S,v,C,_,T){this.listener=g,this.statisticsGatherer=f,this.diagnostics=S,this.logger=v,this.configProvider=C,this.isSimulcastEnabled=T,this.serialQueue=new zC(this.logger),this.modality=qt.MODALITY.video;const I=_.maxResolution?{maxFs:_.maxResolution.fs}:null;this.validator=new gC(this.logger.createChild("CapsValidator"),I),this.resolutionManager=new vb(_,this,this.logger.createChild("rm")),this.statisticsGatherer.on("onStatisticsChanged",(g=>this.onStatisticsChanged(g))),this.statisticsGatherer.on("onDiagnosticUpdated",(g=>this.onDiagnosticUpdated(g)))}async setMaxCapabilities(g,f){const S={modality:this.modality,causeId:g,capabilities:f,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(S),this.diagnostics?.onMaxCapabilitiesRequested(S),this.causeId=g;const v=this.validator.ensureValidity(f[0]);this.streamSenderParams={...f[0],...v},this.resolutionManager.setMaxResolution(this.streamSenderParams.maxFs),this.configProvider.mediaConfig.simulcastSessionEnabled&&await this.applyCapabilities(this.getParamsToApply())}resetCurrentResolution(){this.resolutionManager.resetCurrentResolution()}getCurrentResolution(){return this.resolutionManager.getCurrentResolution()}setCurrentResolution(g){this.resolutionManager.setCurrentResolution(g)}async onResolutionChanged(g){return this.applyCapabilities(this.getParamsToApply(g))}dispose(){this.resolutionManager.dispose(),this.resolutionManager=null}async applyCapabilities(g){return g?this.lastAppliedSenderParams===g?(this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(g)}`),!0):(this.logger.safe.info(`Capabilities to apply: ${JSON.stringify(g)}`),this.lastAppliedSenderParams=g,this.listener.onReceiveCapabilitiesChanged(this.modality,this.causeId,[g])):(this.logger.safe.error("Send capabilities are not set. Cannot apply constraints"),!1)}getParamsToApply(g){if(!this.streamSenderParams)return null;const f=g||this.resolutionManager.getCurrentResolution();if(!f||this.streamSenderParams.maxFs<=f)return this.streamSenderParams;const S=shallowClone(this.streamSenderParams);return S.maxFs=f,S}onStatisticsChanged(g){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.resolutionManager.updateEstimatedSendBandwidth(g.estimatedSendBandwidth)}onDiagnosticUpdated(g){try{if(this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation){if(!g.video?.send?.length||!g.video.send[0])return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Estimating send bandwidth");const f=calculateEstimatedSendBandwidth(g.video.send[0],this.configProvider);this.resolutionManager.updateEstimatedSendBandwidth(f)}}catch(g){this.logger.error("Failed to processes diagnostics update: "+g)}}};__decorateClass([sequentialize()],yb.prototype,"applyCapabilities",1);var Eb=class{constructor(g,f,S,v,C){this.modality=g,this.listener=f,this.statisticsGatherer=S,this.diagnostics=v,this.isSimulcastEnabled=C}setMaxCapabilities(g,f){const S={modality:this.modality,causeId:g,capabilities:f,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(S),this.diagnostics?.onMaxCapabilitiesRequested(S),this.listener.onReceiveCapabilitiesChanged(this.modality,g,f)}dispose(){}resetCurrentResolution(){}getCurrentResolution(){return null}setCurrentResolution(g){}},_b=class{constructor(g,f,S,v,C,_){this.logger=g,this.settings=f,this.listener=S,this.statsGatherer=v,this.diagnostics=C,this.configProvider=_,this.mediaSourceModels=[],this.pendingCapabilities=new Map}dispose(){this.mediaSourceModels.forEach((g=>{g.handler&&(g.handler.dispose(),g.handler=null)})),this.mediaSourceModels=null}updateRegisteredSources(g){this.logger.safe.info(`Local media params updated: ${JSON.stringify(g)}`);const f=[];this.mediaSourceModels.forEach((g=>f.push(g.sourceId)));const S=g.map((g=>g.sourceId)),v=subtractFrom(f,S);this.removeSourcesWithIds(v);const C=subtractFrom(S,f);this.addSourcesWithIds(C,g)}setMaxCapabilities(g,f){for(const S of g){if(!S.capabilities.length)continue;if(!S.sourceId){this.logger.safe.info(`SourceId is not defined to apply recv capabilities: ${JSON.stringify(S)}`);continue}const g=this.getModelWithSourceId(S.sourceId);if(!g){this.logger.safe.info(`Model is not registered for sourceId: ${S.sourceId}`),this.configProvider.config.enableCachingFMTP&&this.pendingCapabilities.set(S.sourceId,S);continue}this.logger.safe.info(`Capabilities handler found for sourceId: ${S.sourceId}`);const v=this.getOrCreateHandlerForModel(g,S.isSimulcast);v?v.setMaxCapabilities(S.causeId||f,S.capabilities):this.logger.safe.info(`Handler is not found for sourceId: ${S.sourceId}`)}this.logger.safe.debug("Max capabilities application completed")}setPendingCapabilities(){if(!this.configProvider.config.enableCachingFMTP)return;this.logger.safe.info(`Apply pending capabilities for sources [${Array.from(this.pendingCapabilities.keys())}]`);const g=Array.from(this.pendingCapabilities.values());this.setMaxCapabilities(g),this.pendingCapabilities.clear()}clearPendingCapabilities(){this.pendingCapabilities.clear()}resetCurrentResolution(){const g=this.mediaSourceModels.find((g=>g.modality===qt.MODALITY.video));g?.handler&&g.handler.resetCurrentResolution()}getCurrentResolution(){const g=this.mediaSourceModels.find((g=>g.modality===qt.MODALITY.video));return g?.handler?g.handler.getCurrentResolution():this.currentResolution?.fs}setCurrentResolution(g){const f=this.mediaSourceModels.find((g=>g.modality===qt.MODALITY.video));f?.handler?f.handler.setCurrentResolution(g):this.currentResolution=g}getOrCreateHandlerForModel(g,f){return g.handler||(g.handler=this.getCapabilitiesHandler(g.modality,f)),g.handler}addSourcesWithIds(g,f){g.forEach((g=>{const S=f.find((f=>f.sourceId===g));this.registerSource(g,S.modality)}))}removeSourcesWithIds(g){g.forEach((g=>this.unregisterSource(g)))}registerSource(g,f){this.logger.safe.info(`SourceId ${g} registered with mediaType: ${f}`),this.mediaSourceModels.push({modality:f,sourceId:g})}unregisterSource(g){const f=this.mediaSourceModels.find((f=>f.sourceId===g));f?(f.handler&&f.handler.dispose(),this.mediaSourceModels.splice(this.mediaSourceModels.indexOf(f),1),this.logger.safe.info(`SourceId ${g} unregistered`)):this.logger.safe.info(`Model doesn't exist with sourceId ${g}`)}getModelWithSourceId(g){return this.mediaSourceModels.find((f=>f.sourceId===g))}getCapabilitiesHandler(g,f){if(g===qt.MODALITY.audio)return null;if(g===qt.MODALITY.video&&!f&&this.settings.customBwEstimationEnabled){const g=new yb(this.listener,this.statsGatherer,this.diagnostics,this.logger.createChild("ach"),this.configProvider,this.settings,f);return this.currentResolution&&g.setCurrentResolution(this.currentResolution),g}return new Eb(g,this.listener,this.statsGatherer,this.diagnostics,f)}},Tb=class extends Ht{constructor(g,f,S,v,C,_){super(g),this.logger=g,this.multiParty=f,this.configProvider=S,this.mediaManager=v,this.statsGatherer=C,this.diagnostics=_,this.rendererResolutions=new Map,this.rendererResolutionsApplied=new Map,this.rendererResolutionMax=new Map,this.hasPendingLimitResolutionUpdate=!1,this.spotlightedRenderers=[]}addRenderer(g){this.rendererResolutions.set(g,{width:0,height:0}),g.on("onRendererSizeChanged",((g,f)=>{this.onRendererSizeChanged(g,f)})),this.scheduleUpdateLimitedResolutions()}removeRenderer(g){this.rendererResolutions.delete(g),this.rendererResolutionsApplied.delete(g),this.rendererResolutionMax.delete(g),this.scheduleUpdateLimitedResolutions()}clearRenderers(){this.rendererResolutions.clear(),this.rendererResolutionsApplied.clear(),this.rendererResolutionMax.clear()}getMaxAllowedVideoFS(){const g=this.getMaxHeightFromConfig(this.sizedRenderersCount);return this.getMaxFSForHeight(g)}limitResolutionOnPoorPerformance(g){const f=this.getRendererByMsi(g);if(!f)return;const S=f.resolution.height>f.resolution.width,v=ei.Recv.getNextLowerResolution(f.resolution.width,f.resolution.height);if(!v)return;const C={width:S?v.height:v.width,height:S?v.width:v.height};this.rendererResolutionMax.set(f.renderer,C),this.diagnostics?.registerResolutionChangeRequest({ts:Date.now(),msi:f.renderer.getMsi(),res:C}),this.logger.safe.info(`Poor perf. Limiting resolution for renderer msi: ${f.renderer.getMsi()} from ${f.resolution.height}p to ${C.height}p`),this.onRendererSizeChanged(f.renderer,C)}get renderersCount(){return this.rendererResolutions.size}get sizedRenderersCount(){return this.configProvider.config.excludeUnsizedRenderersFromMultiviewResolutionLimits?[...this.rendererResolutions.values()].filter((g=>g.height>0)).length:this.renderersCount}getMaxFSForHeight(g){return this.limitMaxFS(ei.Recv.getMaxFsForHeight(g))}getRendererByMsi(g){for(const[f,S]of this.rendererResolutions.entries())if(f.getMsi()===g)return{renderer:f,resolution:S};return null}applyRendererResolution(g,f){this.setMaxFSCapabilities(g,f),this.rendererResolutionsApplied.set(g,f);const S=g.getMediaStream()&&g.getMediaStream().getVideoTracks();S?.[0]&&this.statsGatherer.setPreferredResolution(S[0].id,f,g.getModality())}onRendererSizeChanged(g,f){this.rendererResolutions.set(g,f),this.scheduleUpdateLimitedResolutions()}scheduleUpdateLimitedResolutions(){this.hasPendingLimitResolutionUpdate||(this.hasPendingLimitResolutionUpdate=!0,window.setTimeout((()=>{this.hasPendingLimitResolutionUpdate=!1;const g=this.groupMaxRenderersResolutionsByMsi();this.logger.safe.info(`Updating resolution limits: renderers count ${this.renderersCount}, with size: ${this.sizedRenderersCount}, resolution limits: ${JSON.stringify(this.configProvider.config.multiviewResolutionLimits)}`),this.spotlightedRenderers=this.findSpotlightedRenderers(),this.spotlightedRenderers.length>0&&this.logger.safe.info(`Spotlighted renderers: ${this.spotlightedRenderers.map((g=>g.getMsi()))}, max spotlight height: ${this.configProvider.config.maxSpotlightResolution}`);for(const[f,S]of this.rendererResolutions.entries()){if(!S.height)continue;const v=g.get(f.getMsi()),C=this.limitRendererResolution(f,v||S),_=this.rendererResolutionsApplied.get(f);(!_||_.height!==C.height||_.width!==C.width)&&this.applyRendererResolution(f,C)}}),this.configProvider.config.multiviewResolutionLimitUpdateThrottleDelay))}findSpotlightedRenderers(){if(this.sizedRenderersCount<=1||!this.configProvider.config.isSpotlightEnabled)return[];let g=!1,f=0;for(const[S,v]of this.rendererResolutions.entries())v.height&&v.height!==f&&(f&&(g=!0),f=v.height);if(!g)return[];const S=new Ss(((g,f)=>g.resolution.width>f.resolution.width));for(const[g,f]of this.rendererResolutions.entries())S.enqueue({renderer:g,resolution:f});const v=[];let C=this.configProvider.config.maxNumberOfPinnedVideos;for(;C;){const g=S.peek()?.resolution?.width,f=[];for(;S.peek()?.resolution?.width===g;)f.push(S.dequeue().renderer);if(!(C-f.length>=0))break;C-=f.length,v.push(...f)}return v}getMaxHeightFromConfig(g,f=!1){return f?this.configProvider.config.maxSpotlightResolution:this.configProvider.config.multiviewResolutionLimits[`${g}`]||this.configProvider.config.multiviewResolutionLimits.more}getMaxHeight(g){const f=this.spotlightedRenderers.some((f=>f.getMsi()===g.getMsi()));let S=this.getMaxHeightFromConfig(this.sizedRenderersCount,f);const v=this.rendererResolutionMax.get(g);return v&&(S=Math.min(S,Math.min(v.height,v.width))),S}limitRendererResolution(g,f){const S=this.getMaxHeight(g);if(!S)return f;if(f.height>f.width&&f.width>S){const g=S/f.width;return{height:Math.ceil(f.height*g),width:S,limited:!0}}if(f.width>f.height&&f.height>S){const g=S/f.height;return{height:S,width:Math.ceil(f.width*g),limited:!0}}return f}setMaxFSCapabilities(g,f){const S=g.getMediaStream();if(!S)return void this.logger.safe.warn("renderer has no stream attached");const v=this.mediaManager.getMediaEntityByRemoteStreamId(S.id);if(!v?.getLocalRecvCapabilities())return void this.logger.safe.warn(`no capabilities for provided modality: ${g.getModality()}`);const C=f.limited?this.getMaxFSForHeight(f.height):this.getMaxFS(f.width,f.height),_=v.getLocalRecvCapabilities();_.setMaxFS(C,(()=>{if(this.logger.safe.info(`updated max-fs video capability to ${C} for renderer msi: ${g.getMsi()}`),this.multiParty&&this.configProvider.config.webrtcMultiPartyRecvVideoSignaling){const f=g.getMsi(),v=_.buildFmtp();this.event("onSourceRequestRequired").raise(S.id,f,v)}else this.event("onNegotiationRequired").raise()}))}getMaxFS(g,f){return this.limitMaxFS(ei.Recv.getMaxFsForHeight(f))}limitMaxFS(g){return this.multiParty?Math.min(g,this.configProvider.config.webrtcMultiPartyRecvVideoMaxFS):Math.min(g,this.configProvider.config.webrtcRecvVideoMaxFS)}groupMaxRenderersResolutionsByMsi(){const g=new Map;return this.rendererResolutions.forEach(((f,S)=>{const v=S.getMsi(),C=g.get(v);(!C||f.width>C.width&&f.height>C.height)&&g.set(v,f)})),g}},Ib=class extends Ht{constructor(g,f){super(),this.configProvider=g,this.getModality=f,this.isRendering=!1,this.currentFreezeDuration=0,this.mediaStarted=!1,this.lastBytesRecv=0,this.currentLowBitrateDuration=0}captureRawStatistics(g){const f=g.googFrameRateDecoded,S=g.googFrameRateReceived,v=g.bytesReceived;void 0!==v&&this.getModality()!==qt.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateBitrate(v,f),f>0&&(this.mediaStarted=!0),0===f||0===S?this.currentFreezeDuration+=qt.TIME_INTERVAL.SEC_1:f>0&&(void 0===S||S>0)&&(this.currentFreezeDuration=0);const C=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(C)}updateRenderingTracker(g){const f=g.extensions.frameRateDecoded||0,S=g.extensions.frameRateReceived||0,v=g.extensions.bitrate;void 0!==v&&this.getModality()!==qt.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateLowBitrateDuration(v,f),f>0&&(this.mediaStarted=!0),0===f||0===S?this.currentFreezeDuration+=qt.TIME_INTERVAL.SEC_1:f>0&&(void 0===S||S>0)&&(this.currentFreezeDuration=0);const C=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(C)}calculateLowBitrateDuration(g,f){g/1e3<this.configProvider.config.notRenderingLowBitrateThreshold&&f<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}calculateBitrate(g,f){const S=8*(g-this.lastBytesRecv);this.lastBytesRecv=g,this.calculateLowBitrateDuration(S,f)}setIsRendering(g){const f=this.currentFreezeDuration<g&&this.currentLowBitrateDuration<g&&this.mediaStarted;f!==this.isRendering&&(this.isRendering=f,this.event("onIsRenderingChanged").raise(this.isRendering))}},bb=class extends Ht{constructor(g,f,S){super(),this.videoElement=g,this.configProvider=f,this.getTimeToFirstFrame=S,this.prevCurrentTime=0,this.prevDecodedFrameCount=0,this.prevTimestamp=Date.now(),this.currentFreezeDuration=0,this.freezeDurationTimer=window.setInterval((()=>{this.calcFreezeDurationMs()}),this.configProvider.config.freezeIntervalFrequency)}calcFreezeDurationMs(){const g=this.videoElement.currentTime,f=g===this.prevCurrentTime,S=this.videoElement.webkitDecodedFrameCount,v=void 0===S||S===this.prevDecodedFrameCount;this.prevCurrentTime=g,this.prevDecodedFrameCount=S;if(-1!==this.getTimeToFirstFrame())if(f&&v){const g=Date.now();this.currentFreezeDuration+=g-this.prevTimestamp,this.prevTimestamp=g}else{if(this.currentFreezeDuration>this.configProvider.config.freezeMinDuration){const g=this.calcFreeze();this.event("onFreezeEnded").raise(g)}this.currentFreezeDuration=0}this.prevTimestamp=Date.now()}getEndOfTheFreeze(){let g=0;return this.currentFreezeDuration>0&&(g=this.calcFreeze(),this.currentFreezeDuration=0),g}dispose(){const g=this.getEndOfTheFreeze();this.event("onFreezeEnded").raise(g),clearInterval(this.freezeDurationTimer)}calcFreeze(){const g=Date.now()-this.prevTimestamp;return this.currentFreezeDuration+g}},Ab=class extends Ht{constructor(g,f,S,v){super(),this.videoElement=g,this.minInterval=f,this.maxInterval=S,this.window=Xs.window,this.devicePixelRatio=v&&window.devicePixelRatio||1,this.originalVideoElementSize={width:g.offsetWidth,height:g.offsetHeight},this.initializeSizeTracking()}get width(){return this.originalVideoElementSize.width*this.devicePixelRatio}get height(){return this.originalVideoElementSize.height*this.devicePixelRatio}initializeSizeTracking(){const g=Math.floor(Math.random()*Math.abs(this.maxInterval-this.minInterval))+this.minInterval;this.elementSizeTrackingRef=this.window.setInterval((()=>{this.videoElementSizeChanged()&&(this.saveCurrentVideoElementSize(),this.raiseChanged())}),g)}triggerVideoElementSizeChange(){this.originalVideoElementSize.height&&this.originalVideoElementSize.width&&this.raiseChanged()}dispose(){this.elementSizeTrackingRef&&this.window.clearInterval(this.elementSizeTrackingRef)}videoElementSizeChanged(){return this.originalVideoElementSize.width!==this.videoElement.offsetWidth||this.originalVideoElementSize.height!==this.videoElement.offsetHeight}saveCurrentVideoElementSize(){this.originalVideoElementSize.width=this.videoElement.offsetWidth,this.originalVideoElementSize.height=this.videoElement.offsetHeight}},Pb=class extends ey{constructor(g,f,S,v,C,_){super(C,g.createChild("remote"),f),this.diagnostics=S,this.subscriptionManager=v,this.sessionDiagnostics=_,this.disposed=!1,this.currentIsRendering=!1,this.startTimeTTFF=0,this.timeToFirstFrame=-1,this.isTimeToFirstFrameReported=!1,this.configProvider.config.freezeIntervalFrequency&&(this.freezeTracker=new bb(this.getVideoElement(),this.configProvider,(()=>this.timeToFirstFrame)),this.freezeTracker.on("onFreezeEnded",(g=>{this.diagnostics?.addFreezeDuration(g),this.event("onFreezeEnded").raise(g)}))),this.configProvider.config.isRenderingBasedOnRawStatistics&&(this.isRenderingTracker=new Ib(this.configProvider,this.getModality.bind(this)),this.isRenderingChangedSubscription=this.isRenderingTracker.on("onIsRenderingChanged",(g=>{this.setIsRendering(g)}))),this.overlayStats=new QC(this.configProvider.config.showStatsInCall,C,this)}getEndOfTheFreeze(){return this.freezeTracker?.getEndOfTheFreeze()}resetTimeToFirstFrameFlag(){this.isTimeToFirstFrameReported=!1}setIsRendering(g){this.currentIsRendering!==g&&(this.currentIsRendering=g,this.captureIsRenderingEvent(g))}updateStatsOverlay(g,f){this.overlayStats.setStats(g,f)}updateIsRenderingTracker(g){this.isRenderingTracker?.updateRenderingTracker(g)}subscribeVideoAsync(g,f){return this.timeToFirstFrameSinceSubscriptionStart=Date.now(),new Promise(((S,v)=>{this.modality=f?qt.MODALITY.sharing:qt.MODALITY.video,this.diagnostics&&(this.diagnostics.msi=g,this.diagnostics.modality=this.modality),this.trackElementSizeChange(),this.unsubscribe(),this.on("onVideoSizeChanged",((f,S)=>{if(this.modality===qt.MODALITY.video&&this.sessionDiagnostics?.registerResolutionChangeEvent({ts:Date.now(),msi:g,res:{width:f,height:S}}),this.isTimeToFirstFrameReported)return;if(-1===this.timeToFirstFrame){const g=Date.now();this.timeToFirstFrame=g-this.startTimeTTFF,this.timeToFirstFrameSinceSubscriptionStart=Date.now()-this.timeToFirstFrameSinceSubscriptionStart}const v=this.getTrackId();v&&(this.diagnostics.timeToFirstFrameSinceSubscriptionStart=this.timeToFirstFrameSinceSubscriptionStart,this.diagnostics.timeToFirstFrame=this.timeToFirstFrame,this.sizeTracker?.triggerVideoElementSizeChange(),this.event("onVideoStarted").raise(this.timeToFirstFrame,this.timeToFirstFrameSinceSubscriptionStart,v),this.isTimeToFirstFrameReported=!0)})),this.on("onVideoRendererStateChanged",(g=>{this.diagnostics.addStateChange(g)}));const C=this.subscriptionManager.subscribeVideo(this.modality,g);this.subscription=C,this.logger.safe.info(`subscribing renderer to type: ${C.modality} msi: ${C.msi}`),C.setOnMediaStreamChangedHandler((g=>{const f=this.getMediaStream();this.attachMediaStream(g),g&&(this.startTimeTTFF=Date.now());const v=this.getTrackId();v&&this.diagnostics&&(this.diagnostics.trackId=v),this.logger.safe.info(`subscribed renderer to type: ${C.modality} msi: ${C.msi} on stream #${g?g.id:"none"}`),g&&f!==g&&this.sizeTracker?.triggerVideoElementSizeChange(),S()})),C.setOnErrorHandler((f=>{this.logger.safe.error(`failed to subscribe renderer ${stringifyObject(f)}`),"webRtcSession cleanup"===JSON.stringify(f)&&(this.logger.safe.info(`Retry to subscribe to video stream with msi: ${g}. Previous session was cleaned up`),this.subscriptionManager.streamChangedByMsi(g),S()),v(f)}))}))}dispose(){this.disposed?this.logger.safe.warn("renderer already disposed"):(this.disposed=!0,this.logger.safe.info("disposing"),this.unsubscribe(),this.captureIsRenderingEvent(!1),this.freezeTracker?.dispose(),this.sizeTracker?.dispose(),this.isRenderingChangedSubscription?.dispose(),this.overlayStats.dispose(),this.diagnostics?.dispose(),this.event("onRendererDisposed").raise(this),super.dispose())}getModality(){return this.modality}getMsi(){return this.subscription?.msi??-1}getLocalMsi(){return this.subscription?.localMsi}getCurrentResolution(){return this.resolution??{width:0,height:0}}unsubscribeNow(){this.subscription?.unsubscribe(),this.subscription=null}trackElementSizeChange(){const g=this.modality===qt.MODALITY.sharing,f=g?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMin:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMin,S=g?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMax:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMax;f&&S?(this.sizeTracker=new Ab(this.getVideoElement(),f,S,this.configProvider.config.enableDevicePixelRatio),this.sizeTracker.changed((()=>this.onSizeTrackerChanged()))):this.logger.safe.info("skipping video size tracking")}onSizeTrackerChanged(){this.resolution={width:this.sizeTracker.width,height:this.sizeTracker.height},this.logger.safe.info(`video renderer size changed to ${this.resolution.width}x${this.resolution.height}`),this.diagnostics&&(this.diagnostics.rendererSize=this.resolution),this.event("onRendererSizeChanged").raise(this,this.resolution)}unsubscribe(){this.subscription?.dispose(),this.subscription=null}captureIsRenderingEvent(g){this.diagnostics&&(this.diagnostics.isRendering=g),this.event("onIsRenderingChanged").raise(g,this.getModality(),this.getTrackId())}},Rb=class{constructor(g,f,S,v,C,_){this.logger=g,this.configProvider=f,this.statsGatherer=S,this.sessionDiagnostics=v,this.remoteVideoResolutionManager=C,this.domOverrides=_,this.remoteRendererSubscriptions=new Map,this.diagnostics=v?.newRemoteVideoManagerDiagnostics()}createRenderer(g,f,S){const v=new Pb((S??this.logger).createChild("videorenderer"),this.configProvider,this.diagnostics?.newRendererDiagnostics(),f,g,this.sessionDiagnostics);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(v.getVideoElement()),this.addRenderer(v),v}moveRenderers(g){this.renderers.forEach((f=>{f.resetTimeToFirstFrameFlag(),g.addRenderer(f),this.removeRenderer(f)}))}getMaxAllowedVideoFS(){return this.remoteVideoResolutionManager.getMaxAllowedVideoFS()}dispose(){this.renderers.forEach((g=>g.resetTimeToFirstFrameFlag())),this.renderers.forEach((g=>{const f=g.getTrackId(),S=g.getEndOfTheFreeze();this.statsGatherer.setFreezeDuration(S,f)})),this.remoteRendererSubscriptions.forEach(((g,f)=>{f.dispose(),g.forEach((g=>g.dispose()))})),this.remoteRendererSubscriptions.clear(),this.remoteVideoResolutionManager.clearRenderers()}processStatsReport(g){this.configProvider.config.isRenderingBasedOnRawStatistics&&this.onDiagnosticUpdated(g),this.updateOverlayStats(g)}processLegacyStats(g){this.configProvider.config.isRenderingBasedOnRawStatistics||this.renderers.forEach((f=>{const S=f.getTrackId();if(g.remoteVideoStreams[S]){const v=g.remoteVideoStreams[S].isRendering;void 0!==v&&f.setIsRendering(v)}}))}playVideo(){this.renderers.forEach((g=>g.playVideo()))}get renderers(){return Array.from(this.remoteRendererSubscriptions,(([g])=>g))}addRenderer(g){this.remoteRendererSubscriptions.set(g,this.subscribeOnEvents(g)),this.logger.safe.info("Added renderer to manager"),this.remoteVideoResolutionManager.addRenderer(g)}generateVideoRecvStats(g){const f=new Map,processRecvStats=g=>{g?.forEach((g=>{const S=g.track?.trackIdentifier??g.inboundRTP.trackIdentifier;f.set(S,g)}))};return processRecvStats(g.sharing?.recv),processRecvStats(g.video?.recv),f}updateOverlayStats(g){const f=this.generateVideoRecvStats(g);this.renderers.forEach((S=>{const v=S.getTrackId();f.has(v)&&g.audio?.recv?.length&&S.updateStatsOverlay(f.get(v),g.audio.recv[0])}))}onDiagnosticUpdated(g){const f=[...g.video?.recv??[],...g.sharing?.recv??[]];if(f.length){const g=new Map;f.forEach((f=>{g.set(f.track?.trackIdentifier,f)})),this.renderers.forEach((f=>{const S=f.getTrackId();g.has(S)&&f.updateIsRenderingTracker(g.get(S))}))}}subscribeOnEvents(g){return[g.on("onRendererDisposed",(g=>this.onRendererDisposed(g))),g.on("onVideoStarted",((g,f,S)=>this.onVideoStarted(g,f,S))),g.on("onFreezeEnded",(f=>{const S=g.getTrackId();this.statsGatherer.setFreezeDuration(f,S)})),g.on("onIsRenderingChanged",((g,f,S)=>this.statsGatherer.setIsRendering(g,f,S)))]}onRendererDisposed(g){this.logger.safe.debug("Renderer removed from manager"),this.removeRenderer(g),this.domOverrides.onMediaElementRemoved&&this.domOverrides.onMediaElementRemoved(g.getVideoElement())}removeRenderer(g){this.remoteRendererSubscriptions.get(g).forEach((g=>g.dispose())),this.remoteRendererSubscriptions.delete(g),this.remoteVideoResolutionManager.removeRenderer(g)}onVideoStarted(g,f,S){this.statsGatherer.setTimeToFirstFrame(g,f,S)}},Mb=class extends Ht{constructor(g,f,S){super(),this.configProvider=f,this.callDeviceManager=S,this.lastFramerateInput=-1,this.trackInfo=[],this.timeoutId=null,this.logger=g.createChild("localStreamWatcher"),this.callDeviceManagerSub=S.on("onSelectedVirtualDevicesChanged",(()=>{this.logger.info("VirtualDevice changed, updating subscriptions"),this.handleDeviceManagerChange()}))}get effectsManager(){return this.callDeviceManager.getDeviceManager("Video").effectsManager}startWatching(g,f){(this.configProvider.config.videoCaptureFreezeTimeout||f)&&(this.trackInfo=g,this.performanceMonitor=f,this.configProvider.config.videoCaptureFreezeTimeout&&(this.videoEffectManagerSubscription||(this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(g=>this.onVideoFreezeDetected(g))))))}stopWatching(){this.trackInfo=[],this.videoEffectManagerSubscription?.dispose(),this.videoEffectManagerSubscription=null,this.performanceMonitor=void 0,0!==this.lastFramerateInput||this.timeoutId||this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")),this.disposeTimer(),this.lastFramerateInput=-1}dispose(g){this.callDeviceManagerSub?.dispose(),super.dispose(g),this.stopWatching()}onDiagnosticUpdated(g){if(!this.trackInfo.length||!g.video?.send?.length)return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Updating local video stream watcher");const f=g.video?.send[0],S=[];let v,C=0;[f,...f.altLayouts??[]].forEach((g=>{const f=g.mediaSource,_=f?.framesPerSecond??0;this.trackInfo.some((g=>g.trackId===f.trackIdentifier))&&((!v||C<_)&&(v=f,C=_),this.performanceMonitor&&S.push(g.outboundRTP))})),this.performanceMonitor?.monitor(S),this.configProvider.config.videoCaptureFreezeTimeout&&(v?C!==this.lastFramerateInput&&(0===C?this.scheduleCaptureFreezeStart(v.trackIdentifier,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${v.trackIdentifier}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=C):this.logger.safe.warn("WebRTC Stats for send video not found"))}onStatisticsChanged(g){if(!this.trackInfo.length||!this.configProvider.config.videoCaptureFreezeTimeout)return;let f;Object.keys(g.localVideoStreams).forEach((S=>{const v=g.localVideoStreams[S];this.trackInfo.some((g=>g.trackId===v.trackId))&&(!f||f.frameRateInput<v.frameRateInput)&&(f=v)})),f?f.frameRateInput!==this.lastFramerateInput&&(0===f.frameRateInput?this.scheduleCaptureFreezeStart(f.trackId,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${f.trackId}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=f.frameRateInput):this.logger.safe.warn("WebRTC Stats for send video not found")}onVideoFreezeDetected(g){this.logger.info(`onVideoCaptureFreeze, webcam freeze detected trackId: ${g}`),this.event("onVideoCaptureFreeze").raise(!1,!0)}scheduleCaptureFreezeStart(g,f){this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,this.logger.safe.info(`onVideoCaptureFreeze start for trackId: ${g} (isWebcamStream: ${f})`),this.event("onVideoCaptureFreeze").raise(!0,f)}),this.configProvider.config.videoCaptureFreezeTimeout)}disposeTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handleDeviceManagerChange(){this.videoEffectManagerSubscription?.dispose(),this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(g=>this.onVideoFreezeDetected(g)))}},wb=class{constructor(g){this.queue=[],this.logger=g}cleanup(){this.queue.forEach((g=>{g.reject({notSent:g.tones})})),this.queue=[]}waitForNotification(g){return g?(this.logger.unsafe.info("sending dtmf tones: ",g),new Promise(((f,S)=>{this.queue.push({tones:g,resolve:f,reject:S})}))):Promise.reject(new Error("invalid input"))}toneSent(g){this.queue[0]&&(g===this.queue[0].tones[0]?(this.queue[0].tones=this.queue[0].tones.substr(1),""===this.queue[0].tones&&(this.queue[0].resolve(),this.queue.shift())):(this.queue[0].reject(new Error(`sent tone does not match: expected '${this.queue[0].tones[0]}' got '${g}'`)),this.queue.shift(),this.toneSent(g)))}},Ob=class{constructor(g){this.webRtcSender=null,this.configProvider=g.configProvider,this.queue=new wb(g.logger)}sendDtmf(g,f){return g?.getSenders?(this.syncSender(g),this.webRtcSender?(this.webRtcSender.ontonechange=this.onToneChange.bind(this),this.webRtcSender.insertDTMF(this.webRtcSender.toneBuffer+f,this.configProvider.config.dtmf.toneDuration,this.configProvider.config.dtmf.toneGap),this.queue.waitForNotification(f)):Promise.reject(new Error("not available"))):Promise.reject(new Error("bad peerConnection"))}canSendDtmf(g){return!!g?.getSenders&&(this.syncSender(g),!!this.webRtcSender&&this.webRtcSender.canInsertDTMF)}dispose(){this.queue.cleanup()}syncSender(g){const f=g.getSenders().filter((g=>g.track&&"audio"===g.track.kind)).filter((g=>g.dtmf?.canInsertDTMF))[0];this.webRtcSender&&f&&f.dtmf!==this.webRtcSender&&(this.webRtcSender.ontonechange=null,this.queue.cleanup()),this.webRtcSender=f?f.dtmf:null}onToneChange(g){g.tone&&this.queue.toneSent(g.tone)}},Db={build:g=>new Ob(g)},Nb=class extends Ht{constructor(g,f,S,v,C){super(S),this.pc=g,this.cryptoMethod=f,this.logger=S,this.configProvider=v,this.diagnostics=C,this.iceConnectionStateInternal="new",this.isWaitingAcceptProvisionalInternal=!1,this.state="new",this.toBeCalledOnConnected=[],this.toBeCalledOnProvisionalConnected=[],this.handleSignalingStateChange=()=>{const g=this.pc.signalingState,f=this.signalingStateInternal;if(this.logger.safe.info(`RTCPeerConnection onsignalingstatechange signalingState: ${this.signalingStateInternal} -> ${g}`),this.signalingStateInternal=g,this.diagnostics.signalingState=g,this.event("signalingStateChanged").raise(this.signalingStateInternal,f,generateCauseId()),!this.configProvider.config.useDtlsTrasportConnectionCheck||this.transport||1!==this.cryptoMethod||this.hasPcConnectionState)return;const S=this.pc.getReceivers().find((g=>!!g.transport));this.transport=S?.transport,this.transport&&(this.transport.onstatechange=this.handleDtlsTransportStateChange)},this.handleIceConnectionStateChange=()=>{const g=this.pc.iceConnectionState;this.logger.safe.info(`RTCPeerConnection oniceconnectionstatechange iceConnectionState: ${g} pc.signalingState: ${this.pc.signalingState}`),this.iceConnectionStateInternal=g,this.diagnostics.iceConnectionState=g,this.event("iceConnectionStateChanged").raise(this.iceConnectionStateInternal,generateCauseId()),this.shouldRaise(0)&&this.updateState(g)},this.handleConnectionStateChange=()=>{const g=this.pc.connectionState;this.logger.safe.info(`RTCPeerConnection onconnectionStatechange connectionState: ${g} pc.signalingState: ${this.pc.signalingState}`),this.connectionStateInternal=g,this.diagnostics.connectionState=g,this.event("connectionStateChanged").raise(this.connectionStateInternal,generateCauseId()),this.shouldRaise(1)&&this.updateState(g)},this.handleDtlsTransportStateChange=()=>{const g=this.transport.state;this.logger.safe.info(`RTCDtlsTransport onstatechange state: ${g} pc.signalingState: ${this.pc.signalingState}`),this.dtlsStateInternal=g,this.diagnostics.dtlsTransportState=g,this.event("dtlsTransportStateChanged").raise(this.dtlsStateInternal,generateCauseId()),this.shouldRaise(3)&&this.updateState(g)},this.iceConnectionStateInternal=this.pc.iceConnectionState,this.connectionStateInternal=this.pc.connectionState,this.signalingStateInternal=this.pc.signalingState,this.pc.oniceconnectionstatechange=this.handleIceConnectionStateChange,this.pc.onsignalingstatechange=this.handleSignalingStateChange,this.logger.safe.debug(`ctor ctryptoMethod ${1===this.cryptoMethod?"dtls":"sdes"}, hasPcConnectionState ${this.hasPcConnectionState}`),1===this.cryptoMethod&&this.hasPcConnectionState&&(this.pc.onconnectionstatechange=this.handleConnectionStateChange),this.diagnostics.hasConnectionState=this.hasPcConnectionState}get hasPcConnectionState(){return"connectionState"in this.pc&&this.configProvider.config.useConnectionState}get isWaitingAcceptProvisional(){return this.isWaitingAcceptProvisionalInternal}set isWaitingAcceptProvisional(g){this.isWaitingAcceptProvisionalInternal!==g&&(this.logger.safe.debug(`isProvisional set ${this.isWaitingAcceptProvisionalInternal} -> ${g}`),this.isWaitingAcceptProvisionalInternal=g,this.diagnostics.provisional=g,this.updateState(this.state,!1))}get iceConnectionState(){return this.iceConnectionStateInternal}get signalingState(){return this.signalingStateInternal}get isIceConnected(){return"connected"===this.iceConnectionStateInternal||"completed"===this.iceConnectionStateInternal}get isTransportConnected(){return"connected"===this.state||"completed"===this.state}get isFailed(){return this.configProvider.config.transportStateFailedFix?"failed"===this.state:"failed"===this.state||"closed"===this.state}get isConnected(){return this.isTransportConnected&&"closed"!==this.signalingStateInternal}doOnConnected(g,f="unknown",S=!1,v=!0){return this.diagnostics.scheduleDoOnConnected(g,f,S,v),v&&this.isConnected&&(S||!this.isWaitingAcceptProvisionalInternal)?(this.logger.safe.info(`Running callback immediately ${f}`),this.diagnostics.runDoOnConnected(g,!0),void g()):S?(this.logger.safe.info(`Queuing provisional connected callback '${f}'`),void this.toBeCalledOnProvisionalConnected.push(g)):(this.logger.safe.info(`Queuing connected callback '${f}'`),void this.toBeCalledOnConnected.push(g))}dispose(){this.pc.oniceconnectionstatechange=void 0,this.pc.onsignalingstatechange=void 0,this.transport&&(this.transport.onstatechange=void 0),this.pc.onconnectionstatechange&&(this.pc.onconnectionstatechange=void 0),this.diagnostics.dispose()}updateState(g,f=!0){if(f&&(this.statePrevious=this.state),this.state=g,this.event("stateChanged").raise(this.state,this.statePrevious,generateCauseId()),this.diagnostics.transportState=g,this.isConnected){if(!this.isWaitingAcceptProvisionalInternal&&this.toBeCalledOnConnected.length)for(this.logger.safe.info(`Running ${this.toBeCalledOnConnected.length} callbacks on connected`);this.toBeCalledOnConnected.length;){const g=this.toBeCalledOnConnected.shift();this.diagnostics.runDoOnConnected(g),g()}if(this.toBeCalledOnProvisionalConnected.length)for(this.logger.safe.info(`Running ${this.toBeCalledOnProvisionalConnected.length} callbacks on provisional connected`);this.toBeCalledOnProvisionalConnected.length;){const g=this.toBeCalledOnProvisionalConnected.shift();this.diagnostics.runDoOnConnected(g),g()}}}shouldRaise(g){switch(g){case 3:if(1!==this.cryptoMethod)throw new Error(`DTLS transport is used with cryptoMethod=${this.cryptoMethod}`);return!this.configProvider.config.ignoreClosedDtlsTransportState||"closed"!==this.transport.state;case 1:return 1===this.cryptoMethod&&!this.transport;case 0:return!(!this.configProvider.config.ignoreClosedDtlsTransportState||!this.transport||"closed"!==this.pc.iceConnectionState)||(0===this.cryptoMethod||!this.transport&&!this.hasPcConnectionState||this.transport&&"disconnected"===this.pc.iceConnectionState||"connected"===this.transport?.state&&"connected"===this.pc.iceConnectionState);default:return this.logger.safe.error(`unknown StateMethod=${g}`),!1}}},kb=class{constructor(g,f,S,v,C,_){this.logger=g,this.emulator=f,this.qualityManager=S,this.diagnostics=v,this.configProvider=C,this.statsGatherer=_,this.previousSequenceNumber=new Map,this.modifiers=this.configProvider.mediaConfig.simulcastSessionEnabled?[]:[new OT(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider)]}dispose(){this.cleanupDevToolsInjector(),this.modifiers&&(this.modifiers.forEach((g=>g.dispose())),this.modifiers=null),this.emulator=null,this.logger=this.logger.createChild("DISPOSED")}handleMessage(g){const f=g.controlInfo[0].sourceId;if(this.previousSequenceNumber.has(f)&&g.sequenceNumber<this.previousSequenceNumber.get(f))return this.statsGatherer.addVideoControlMessage(!0),this.diagnostics?.addVideoControlMessage(!0),this.logger.safe.info(`Discarded old media stream control message for sourceId ${f}: (${JSON.stringify(g)})`),Promise.resolve();this.previousSequenceNumber.set(f,g.sequenceNumber),this.statsGatherer.addVideoControlMessage(),this.diagnostics?.addVideoControlMessage(),this.configProvider.config.enableDevtoolsAPI&&this.injectFmtpHandler(g);const S={controlVideoStreaming:g};return this.configureResolution(S),this.modifiers.length?(this.modifiers.forEach((g=>g.setVideoControlMessage(S))),this.emulator.renegotiate(this.modifiers)):Promise.resolve()}configureResolution(g){this.logger.safe.info(`Signaling FMTP: ${JSON.stringify(g.controlVideoStreaming)}`);const f=String(g.controlVideoStreaming.sequenceNumber),S=g.controlVideoStreaming.controlInfo[0].fmtParamsList,v=g.controlVideoStreaming.controlInfo[0].fmtParams,C=S&&this.configProvider.config.webrtcFmtParamListSupported?this.parseFmtParamsList(S):[this.parseFmtParams(v)],_=+g.controlVideoStreaming.controlInfo[0].sourceId,T=[{causeId:f,isSimulcast:C.some((g=>void 0!==g.rid))||C.length>1,capabilities:C,sourceId:_}];this.qualityManager.setMaxCapabilities(T)}parseFmtParamsList(g){return g.map((g=>this.parseFmtParams(g)))}parseFmtParams(g){const f=new Zy(g);return{maxFs:+f.get(qt.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+f.get(qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+f.get(qt.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+f.get(qt.VIDEO_CAPABILITIES.MAX_BR_PATH),ssrc:+f.get(qt.VIDEO_CAPABILITIES.SSRC_PATH),rid:f.get(qt.VIDEO_CAPABILITIES.RID_PATH),keyframe:this.shouldGenerateKeyFrame(f),vlaDebug:f.get(qt.VIDEO_CAPABILITIES.VLA_DEBUG)}}shouldGenerateKeyFrame(g){return g.get(qt.VIDEO_CAPABILITIES.KEYFRAME_PATH)?!!+g.get(qt.VIDEO_CAPABILITIES.KEYFRAME_PATH):this.configProvider.config.webrtcAllowRestoreKeyframe}injectFmtpHandler(g){const f=window;f?.webMA&&(f.webMA.fmtp||(f.webMA.fmtp={handleMessage:this.handleMessage.bind(this)}),f.webMA.fmtp.lastFmtp=g)}cleanupDevToolsInjector(){const g=window;g?.webMA&&delete g.webMA.fmtp}},Lb=(g=>(g[g.ThreeStreamSimulcast=0]="ThreeStreamSimulcast",g[g.HardwareEncoder=1]="HardwareEncoder",g[g.Encode1080P=2]="Encode1080P",g[g.BroadcastMode=3]="BroadcastMode",g))(Lb||{}),Fb=class extends Ht{constructor(g,f){super(f),this.mediaType=g,this.logger=f,this.features={}}notify(){super.raiseChanged()}find(g){var f;return(f=this.features)[g]??(f[g]={})}set(g,f,S){const v=this.find(g);let C=!1;return void 0!==f&&v.server!==f&&(this.logger.safe.info(`Server support for [${this.mediaType}][${Lb[g]}] changed from ${v.server} to ${f}`),v.server=f,C=!0),void 0!==S&&v.client!==S&&(this.logger.safe.info(`Client support for [${this.mediaType}][${Lb[g]}] changed from ${v.client} to ${S}`),v.client=S,C=!0),C}toggleServer(g,f){return!!this.set(g,f,void 0)&&(this.notify(),!0)}toggleClient(g,f){return!!this.set(g,void 0,f)&&(this.notify(),!0)}toggle(g,f){return!!this.set(g,f,f)&&(this.notify(),!0)}hasAnySupport(g){const f=this.find(g);return!0===f.client||!0===f.server}hasFullSupport(g){const f=this.find(g);return!0===f.client&&!0===f.server}hasClientSupport(g){return!0===this.find(g).client}hasServerSupport(g){return!0===this.find(g).server}},xb=class extends Ht{constructor(g){super(g),this.logger=g,this.modalities={Video:new Fb("Video",this.logger),ScreenShare:new Fb("ScreenShare",this.logger)},this.blocked=new Set;for(const g of Object.keys(this.modalities))this.modalities[g].changed((()=>{this.notify(this.modalities[g],!1)}))}notify(g,f){this.blocked.has(g.mediaType)&&!0!==f||(this.blocked.add(g.mediaType),this.logger.safe.info(`Notify: ${g.mediaType}`),this.event("onVideoFeaturesChanged").raise(g),this.blocked.delete(g.mediaType))}manageFeatureSupport(g){for(const g of Object.values(this.modalities))this.blocked.add(g.mediaType);g();for(const g of[...this.blocked])this.notify(this.modalities[g],!0)}get(g){if(!this.modalities[g])throw this.logger.safe.error(`Unsupported media type: ${g}`),new Error(`Unsupported media type: ${g}`);return this.modalities[g]}},Ub=class _MediaMessageGenerator{constructor(g){this.configProvider=g}getVideoControlMessage(g,f,S){const v={controlVideoStreaming:{sequenceNumber:++_MediaMessageGenerator.sequence,globalTimeStamp:(new Date).toString(),controlInfo:[{control:"start",sourceId:f,streamMsid:g}]}};return S&&(v.controlVideoStreaming.controlInfo[0].fmtParams=fmtParamsToString(S)),v}getSourceRequestMessage(g,f,S,v){if(!S)throw new Error("Failed to construct SourceRequestMessage, missing fmtParams");const C={sourceId:f,streamMsid:g,fmtParams:S};return C.subStreamIndex=v,{type:"sr",controlVideoStreaming:{sequenceNumber:++_MediaMessageGenerator.sequence,controlInfo:C}}}getSignalingSourceRequestMessage(g,f,S,v,C){if(!v)throw new Error("Failed to construct SourceRequestMessage, missing fmtParams");const _={sourceId:f,streamMsid:g,fmtParams:v};return _.subStreamIndex=C,{applyChannelParameters:{multiChannelParameter:{mids:[S],mediaParameter:JSON.stringify({controlVideoStreaming:{sequenceNumber:++_MediaMessageGenerator.sequence,controlInfo:_}})}}}}getBandwidthInfoMessage(g){return{type:"ssbwe",BwMessage:g}}getMaxVideoSendCapabilitiesMessage(g){const{streamMIDs:f,capabilities:S,useMax:v,sendMaxFs:C,sendMaxMbps:_}=g;let T=ceilToMacroblock(S.maxWidth),I=ceilToMacroblock(S.maxHeight);v&&(T=I=Math.max(T,I));const b={[qt.VIDEO_CAPABILITIES.MAX_FPS_PATH]:S.maxFps,[qt.VIDEO_CAPABILITIES.MAX_WIDTH]:T,[qt.VIDEO_CAPABILITIES.MAX_HEIGHT]:I};return C&&(b[qt.VIDEO_CAPABILITIES.MAX_FS_PATH]=S.maxFs),_&&(b[qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH]=S.maxMbps),{applyChannelParameters:{multiChannelParameter:{mids:f,mediaParameter:JSON.stringify({maxVideoSendCapabilities:{caps:b}})}}}}getMaxVideoSendCapabilitiesContent(g,f,S,v){const C={};if(S){let g=ceilToMacroblock(S.maxWidth),f=ceilToMacroblock(S.maxHeight);this.configProvider.config.maxSendVideoCapabilities.useMaximumWidthHeight&&(g=f=Math.max(g,f)),C[qt.VIDEO_CAPABILITIES.MAX_WIDTH]=g,C[qt.VIDEO_CAPABILITIES.MAX_HEIGHT]=f,C[qt.VIDEO_CAPABILITIES.MAX_FPS_PATH]=S.maxFps,this.configProvider.config.maxSendVideoCapabilities.sendMaxFs&&(C[qt.VIDEO_CAPABILITIES.MAX_FS_PATH]=S.maxFs),this.configProvider.config.maxSendVideoCapabilities.sendMaxMbps&&(C[qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH]=S.maxMbps)}else v&&[qt.VIDEO_CAPABILITIES.MAX_WIDTH,qt.VIDEO_CAPABILITIES.MAX_HEIGHT,qt.VIDEO_CAPABILITIES.MAX_FPS_PATH,qt.VIDEO_CAPABILITIES.MAX_FS_PATH,qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH].forEach((g=>{v[g]&&(C[g]=v[g])}));const _=g.getSimulcastContext();let T,I,b,A;if(_&&_.config.layerScaleFactors.length>2&&(T=_.config.layerScaleFactors.length,I=_.config.layerScaleFactors.length,f.hasClientSupport(0)||(I=2),this.configProvider.config.minFrameSizeForThreeStreamSimulcast&&S&&S.maxFs<this.configProvider.config.minFrameSizeForThreeStreamSimulcast&&(I=2)),void 0!==T&&(C[qt.VIDEO_CAPABILITIES.MAX_STREAMS]=T),void 0!==I&&(C[qt.VIDEO_CAPABILITIES.MAX_LAYERS]=I),f.hasClientSupport(3)&&this.configProvider.config.broadcastMode?.prioritizeLayoutOnServer){const g=this.configProvider.config.broadcastMode;g.priorityLayoutMinFS&&g.priorityLayoutMinFPS&&(A=g.priorityLayoutMinFS,A*=g.priorityLayoutMinFPS),g.priorityLayoutMinBitrate&&(b=g.priorityLayoutMinBitrate)}return b&&(C[qt.VIDEO_CAPABILITIES.PRIORITY_LAYOUT_MIN_BITRATE]=b),A&&(C[qt.VIDEO_CAPABILITIES.PRIORITY_LAYOUT_MIN_MBPR]=A),f.hasClientSupport(1)&&this.configProvider.config.preferredHardwareLadderType&&(C[qt.VIDEO_CAPABILITIES.LADDER_TYPE]=this.configProvider.config.preferredHardwareLadderType),C}getMultiChannelParametersMessage(g,f){return{applyChannelParameters:{multiChannelParameter:{mids:g,mediaParameter:JSON.stringify(f)}}}}};Ub.sequence=0;var Vb=Ub,Bb=class{constructor(g,f,S,v){this.logger=g,this.configProvider=f,this.sender=S,this.mediaControlPlane=v,this.messageGenerator=new Vb(this.configProvider),this.lastVideoSendMaxCapabilities={}}sendSourceRequest(g,f,S,v,C){if(this.configProvider.config.useApplyChannelParametersForSourceRequests){const _=this.messageGenerator.getSourceRequestMessage(g,f,v,C),T=this.messageGenerator.getSignalingSourceRequestMessage(g,f,S,v,C);return this.sendMessage("ApplyChannelParametersSourceRequest",_,T)}const _=this.messageGenerator.getVideoControlMessage(g,f,v?.[0]);return this.sendMessage("ControlVideoStreaming",_)}sendMaxVideoSendCapabilities(g,f){const S=this.messageGenerator.getMaxVideoSendCapabilitiesMessage({streamMIDs:g,capabilities:f,sendMaxFs:this.configProvider.config.maxSendVideoCapabilities.sendMaxFs,sendMaxMbps:this.configProvider.config.maxSendVideoCapabilities.sendMaxMbps,useMax:this.configProvider.config.maxSendVideoCapabilities.useMaximumWidthHeight});return this.sendMessage("ApplyChannelParametersVideoCapabilities",S)}async sendBandwidthInfo(g){const f=this.messageGenerator.getBandwidthInfoMessage(g);return this.mediaControlPlane?.sendMsg(f)}sendMaxVideoSendCapabilitiesV2(g,f,S){if(void 0===this.lastVideoSendMaxCapabilities[g.getMid()]){if(!S)return this.logger.safe.info("Skip sending empty max-capabilities message"),Promise.resolve();this.lastVideoSendMaxCapabilities[g.getMid()]={}}const v=this.messageGenerator.getMaxVideoSendCapabilitiesContent(g,f,S,this.lastVideoSendMaxCapabilities[g.getMid()]);if(S||!deepEqual(this.lastVideoSendMaxCapabilities[g.getMid()],v)){this.lastVideoSendMaxCapabilities[g.getMid()]=v;const f=this.messageGenerator.getMultiChannelParametersMessage([g.getMid()],{maxVideoSendCapabilities:{caps:v}});return this.sendMessage("ApplyChannelParametersVideoCapabilities",f)}return this.logger.safe.info("Skip sending duplicate max-capabilties message"),Promise.resolve()}async sendMessage(g,f,S){let v;return"ApplyChannelParametersSourceRequest"===g&&(v=f.controlVideoStreaming.sequenceNumber),this.logger.safe.info(`sending video control message: ${JSON.stringify(f)}`),this.sender.send(g,f,v,S)}},Hb=0,$b=class _WebRtcSession{constructor(g,f,S){this.context=g,this.callId=f,this.callback=S,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc-"+ ++Hb),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.webrtcAdapter=db.build({global:this.context.maContext,configProvider:this.configProvider}),this.iceHostCandidateOnly=this.multiParty&&getFrom("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new gb({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:!1}),this.sessionDescription=V_.build({sdpTransform:new this.webrtcAdapter.SdpTransform(this.context),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:this.getStreamTransformConfiguration()}),this.allowedMediaContentType=getFrom("webrtcAllowedMediaContentType",this.context.config,this.configProvider.config).concat(),this.receiveStreamCollection=new MT({streamAdded:g=>this.streamAdded(g),streamRemoved:g=>this.streamRemoved(g)}),this.stats=new JI(this.logger.createChild("stats"),this.configProvider,void 0,this.mediaManager,this.multiParty),this.maxResolution=this.multiParty?ei.Send.getResolutionByFs(this.configProvider.config.webrtcMultipartyMaxScalingFs):ei.Send.getResolutionByFs(this.configProvider.config.webrtcMaxScalingFs),this.qualityManager=new _b(this.logger.createChild("qm"),{scalingEnabled:this.configProvider.config.webrtcVideoScaling,cooldownTimeout:this.configProvider.config.webrtcResolutionManagerCooldownTimeout,retryDelay:this.configProvider.config.webrtcResolutionManagerRetryDelay,maxResolution:this.maxResolution,customBwEstimationEnabled:!0},{onReceiveCapabilitiesChanged:(g,f,S)=>this.applyCapabilitiesForModality(g,f,S)},this.stats,void 0,this.configProvider),this.localVideoStreamWatcher=new Mb(this.logger,this.configProvider,this.context.callDeviceManager),this.activeSpeakerManager=new RT(this.callback.onContributingSourcesChanged,this.callback.onDominantSpeakerChanged,this.logger.createChild("ActiveSpeakerManager")),this.senders={},this.negotiationQueue=new zC(this.logger),this.negotiationEmulator=new mb(this.logger.createChild("negotiationEmulator"),this.webrtcAdapter.RTCSessionDescription,this.sessionDescription,this.negotiationQueue,this.mediaManager),this.streamConfigurationHandler=new kb(this.logger,this.negotiationEmulator,this.qualityManager,null,this.configProvider,this.stats),this.mediaMessageController=new Bb(this.logger,this.configProvider,{send:this.context.sendWebRtcMediaNotificationAsyncCallback}),this.toBeCalledAfterConnected=[],this.iceTransportPolicy=this.configProvider.config.iceTransportPolicyForced||this.context.config.iceTransportPolicy||qt.ICE_TRANSPORT_POLICY.all,this.isMuteHold=!1,this.peerConnection=null,this.mediaStreams=new Map,this.doAudioMute=this.context.config.muted,this.iceCandidatesDeferred=new dt,this.relayCandidateGathered=!1,this.iceCandidatesTimer=null,this.triggerRenegotiationFlag=!1,this.canTriggerRenegotiation=!0,this.noIceCandidates=!1,this.noRelayIceCandidates=!1,this.forceMediaStreamUpdate=!1,this.negotiatedModalities={},this.disabledModalities={},this.iceDisconnectedTimer=null,this.statisticsReport=Promise.resolve({}),this.terminated=!1,this.initiator=!1,this.streamsChangedListener=null,this.dtmfSender=Db.build({logger:this.logger,configProvider:this.configProvider}),this.mediaContentType=getFrom("webrtcMediaContentType",this.context.config,this.configProvider.config),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new qy(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:g=>this.onStreamsChanged(g)}),this.remoteVideoResolutionManager=new Tb(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.stats),this.remoteVideoManager=new Rb(this.logger.createChild("RemoteVideoManager"),this.configProvider,this.stats,void 0,this.remoteVideoResolutionManager,this.context.maContext.domOverrides),this.hwSilent=!1,this.configuredModalitiesPromise=Promise.resolve(),this.negotiationCompletedPromise=new dt,this.ssrcGenerator=new hE,this.ssrcs={Audio:this.getSsrcRangeForMediaType("Audio"),Video:this.getSsrcRangeForMediaType("Video"),ScreenShare:this.getSsrcRangeForMediaType("ScreenShare")},this.forceKeyFramePromise=null,this.transportStateProvider={isFailed:this.isFailed.bind(this),isConnected:this.isConnected.bind(this)},this.ufdManager=g.getUfdManager(),this.stats.on("onStatisticsChanged",(g=>{this.remoteVideoManager.processLegacyStats(g),this.localVideoStreamWatcher?.onStatisticsChanged(g),this.updateQualityLevels(g)})),this.negotiationCompletedPromise.promise.catch((()=>{})),this.negotiationCompletedPromise.reject("placeholder"),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((g,f,S)=>this.requestSource(g,f,S))),this.setSubsForSubscriptionManager(),this.localVideoStreamWatcher.on("onVideoCaptureFreeze",(g=>{this.isConnected()&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",g?"Bad":"Good","Video")})),this.configProvider.mediaConfig.maxBandwidthInKbps&&this.stats.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.createAudioRenderer(),this.configProvider.config.webrtcVideoScaling&&this.onOptimalVideoReceiversCountChanged(this.configProvider.config.nonEstimatedDefaultVideoReceiversCount)}get audioStream(){return this.mediaStreams.get("Audio")}get videoStream(){return this.mediaStreams.get("Video")}get displayStream(){return this.mediaStreams.get("ScreenShare")}useNullAudioStreamClient(){}getIncomingRawAudioStream(){return null}configureSpatialAudio(g,f){}setParticipantSpatialAudioPositions(g,f){}getAcceptedTypes(){return this.allowedMediaContentType}clone(g=!1){const f=shallowClone(this.context);f.config=shallowClone(this.context.config),f.config.webrtcMediaContentType=this.mediaContentType,f.config.webrtcAllowedMediaContentType=this.allowedMediaContentType,g?f.config.isConference=!0:(f.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(f.config.webrtcIceGatheringTimeoutIncreased=!0));const S=new _WebRtcSession(f,this.callId,this.callback);return this.relayManagerProvider&&(S.relayManagerProvider=this.relayManagerProvider),S.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,S}setInternals(g){g.subscriptionManager&&(this.subscriptionManager&&this.subscriptionManager.dispose(),this.subscriptionManager=g.subscriptionManager,this.subscriptionManager.setStreamProvider({getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:g=>this.onStreamsChanged(g)}),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),g.audioRenderer&&(g.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=g.audioRenderer),g.remoteVideoManager&&g.remoteVideoManager.moveRenderers(this.remoteVideoManager)}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(g=>this.stats.setSubscribedTrackIds(g))),this.subscriptionManager.on("onTrackSsrcChanged",(g=>this.stats.setSubscribedTrackSsrc(g))),this.subscriptionManager.on("onSubscriptionChanged",((g,f,S,v,C,_)=>this.stats.addSubscriptionEvent(g,f,S,v,null,C,_))),this.subscriptionManager.on("onSubscriptionFailed",((g,f,S,v,C)=>this.stats.addSubscriptionEvent(g,f,S,v,C)))]}move(g,f){g.setInternals({subscriptionManager:this.subscriptionManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager}),g.muteHold(this.isMuteHold,f),this.doAudioMute?g.muteInputAsync(f):g.unmuteInputAsync(f),this.subscriptionManager=null,this.audioRenderer=null,this.callbacks.onTerminated=null}setMute(g,f,S){this.logger.safe.info(`[${S}] call setMuteAsync with mute state ${f}, audio stream exists: ${!!this.audioStream}`),"Audio"===g&&this.audioStream?this.audioStream.setMuted(f,S):"Video"===g&&this.videoStream?this.videoStream.setMuted(f,S):"ScreenShare"===g&&this.displayStream&&this.displayStream.setMuted(f,S),this.updateQualityLevels(this.stats.getLastStatistics())}setCallConstraints(g,f){return Promise.reject(new Error("Not supported"))}configureModalitiesAsync(g,f){const S=this.configuredModalitiesPromise.then((()=>{if(!g||!g.audio&&!g.video&&!g.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(g)}`);const S=!this.configuredModalities||!areNegotiatedDirectionsFulfilled(g,this.negotiatedModalities);return this.configuredModalities=g,this.logger.safe.info(`[${f}] configure modalities`,`audio: ${g.audio}`,`video: ${g.video}`,`sharing: ${g.sharing}`,`peerconnection: ${!!this.peerConnection}`,`pc.signalingState: ${this.peerConnection?this.peerConnection.signalingState:"-"}`,`needNewRenegotiation: ${S}`),S&&this.triggerRenegotiation(!1,f),this.configuredModalities}));return this.configuredModalitiesPromise=S.catch((g=>{this.logger.safe.warn(`[${f}] Error during configuring modalities: ${stringifyObject(g)}`)})).then((()=>{})),S.then((()=>{}))}getConfiguredModalities(){return this.configuredModalities}getDisabledModalities(){return this.disabledModalities}getSubscriptionManager(){return null}createAudioElement(g){}createOfferAsync(g){const f=this.negotiationQueue.add((()=>new Promise((f=>{this.logger.safe.info(`[${g}] create [offer] configured: ${JSON.stringify(this.configuredModalities)}`),this.initiator=!0,this.throwIfModalitiesNotConfigured("no configured modalities to create offer for"),this.canTriggerRenegotiation=!1,this.negotiatingModalities=this.configuredModalities,this.offeredModalities=this.negotiatingModalities,this.configProvider.config.webrtcNegotiateDisabledDataModality&&!this.offeredModalities[qt.MODALITY.data]&&this.multiParty&&(this.offeredModalities[qt.MODALITY.data]=qt.MEDIA_STATE.inactive),isOnHold(this.offeredModalities)&&!isEmpty(this.negotiatedModalities)&&Object.keys(this.offeredModalities).forEach((g=>{void 0===this.negotiatedModalities[g]&&delete this.offeredModalities[g]})),f(this.updatePeerConnectionStreamsAsync(this.offeredModalities,!0,!0,g).then((()=>{const f=this.createNegotiationConstraints(this.offeredModalities);return this.logger.safe.info(`[${g}] create [offer] offered: ${JSON.stringify(this.offeredModalities)} constraints: ${JSON.stringify(f)}`),this.peerConnection.createOffer(f)})).then((f=>{this.logger.unsafe.debug(`[${g}] create [offer] offer from peer connection`,"sdp:",f.sdp);const S=this.sessionDescription.createLocalOffer(f.sdp);this.hasIceCandidates(S)||this.resetCandidateGathering(g),this.stats.startWaitingForStreamStart(this.offeredModalities);const v=new this.webrtcAdapter.RTCSessionDescription({sdp:S.toLocal(),type:"offer"});return this.setupIceGatheringTimeout(g),Promise.all([this.peerConnection.setLocalDescription(v),this.iceCandidatesDeferred.promise])})).then((()=>{const f=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp);f.updateModalities(this.offeredModalities),this.checkIceCandidates(f);const S=f.toOffer();this.logger.unsafe.debug("CREATE OFFER","sdp:",S);const v={blob:S,contentType:this.mediaContentType};return""===this.configProvider.config.webrtcRequiredFeatures||this.multiParty||(v.requiredFeatures=this.configProvider.config.webrtcRequiredFeatures),this.configProvider.countryCode&&(v.clientLocation=this.configProvider.countryCode),this.doRetargetIfNeeded(v,f,g),v})))}))),g);return this.resetNegotiationQueue(g),f}processOfferAsync(g,f){const S=this.negotiationQueue.add((()=>new Promise((S=>{const v=g.blob;if(this.logger.unsafe.debug(`[${f}] process [offer]`,"sdp:",v),this.configProvider.config.webrtcCompareContentTypeInOffer&&(assertContentTypeSupported(g.contentType,this.allowedMediaContentType),this.mediaContentType=g.contentType),g.requiredFeatures){const f=this.configProvider.config.webrtcRejectedFeatures.split(",");throwIfFeatureNotSupported(g.requiredFeatures.split(","),f)}this.initiator=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(v),this.canTriggerRenegotiation=!1,this.offeredModalities=invertModalities(this.offeredDescription.getModalities()),this.peerConnection||(this.context.configProvider.mediaConfig.isTransportUnbundled?this.context.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.couldBeUnbundled():this.context.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.isUnbundled());let C=Promise.resolve(this.offeredModalities);if(hasSendDirectionality(this.offeredModalities.video)||hasReceiveDirectionality(this.offeredModalities.video)||hasSendDirectionality(this.offeredModalities.sharing)||hasReceiveDirectionality(this.offeredModalities.sharing)){const g=this.offeredDescription.getVideoCodecs();C=this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video").then((S=>{if(!S.codecs.some((f=>g.some((g=>f.mimeType===g))))){this.logger.safe.warn(`[${f}] offer doesn't contain any supported video codecs`);const g=shallowClone(this.offeredModalities);return this.disabledModalities.video=g.video,this.disabledModalities.sharing=g.sharing,g.video=void 0,g.sharing=void 0,g}return this.offeredModalities})).catch((g=>(this.logger.safe.error(`[${f}] failed to get video capability ${stringifyObject(g)}`),this.offeredModalities)))}S(C.then((g=>(this.logger.safe.info(`[${f}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(g)}`),g))))}))),f);return this.resetNegotiationQueue(f),S}createAnswerAsync(g,f){return new Promise((S=>{if(g)return void S({blob:"",contentType:this.mediaContentType});this.logger.safe.info(`[${f}] create [answer] offered: ${JSON.stringify(this.offeredModalities)} configured: ${JSON.stringify(this.configuredModalities)}`),this.throwIfModalitiesNotConfigured("no configured modalities to create answer for"),this.negotiatingModalities=this.configuredModalities;let v=negotiateModalities(this.offeredModalities,this.negotiatingModalities);const C=this.offeredDescription.clone();S(this.updatePeerConnectionStreamsAsync(v,!0,!1,f).then((()=>this.handleCodecSwitchUnsupported(f))).then((()=>{this.offeredDescription.setModalities(v);const g=this.offeredDescription.toRemote();this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources();const S=new this.webrtcAdapter.RTCSessionDescription({sdp:g,type:"offer"});return this.updateDescriptor(S,C),this.logger.unsafe.info(`[${f}] create [answer] set remote description`,"negotiated:",v,"sdp:",S.sdp),this.peerConnection.setRemoteDescription(S)})).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.updatePeerConnectionStreamsAsync(v,!1,!0,f)))).then((()=>(this.handleSharingRecvCapabilities(C),this.handleVideoRecvCapabilities(C)))).then((()=>this.peerConnection.createAnswer())).then((g=>{this.logger.unsafe.debug(`[${f}] create [answer] answer from peer connection`,"sdp:",g.sdp);const S=this.sessionDescription.createLocalAnswer(g.sdp);this.hasIceCandidates(S)||this.resetCandidateGathering(f),this.stats.startWaitingForStreamStart(v);const C=new this.webrtcAdapter.RTCSessionDescription({sdp:S.toLocal(),type:"answer"});return this.setupIceGatheringTimeout(f),Promise.all([this.peerConnection.setLocalDescription(C),this.iceCandidatesDeferred.promise])})).then((()=>{const g=this.sessionDescription.createLocalAnswer(this.peerConnection.localDescription.sdp);g.updateModalities(v),this.checkIceCandidates(g);const S=g.toAnswer();v=g.getModalities(),areNegotiatedDirectionsAcceptable(this.configuredModalities,this.negotiatingModalities,v)||this.triggerRenegotiation(!0,f),this.setNegotiatedModalities(v),this.stats.sessionInfo.setBweType(g.getBweType()),this.logger.unsafe.debug("CREATE ANSWER","sdp:",S);const C={blob:S,contentType:this.mediaContentType};return this.configProvider.countryCode&&(C.clientLocation=this.configProvider.countryCode),C})))}))}processAnswerAsync(g,f,S){const v=g.blob;if(this.logger.unsafe.debug(S?"PROCESS PRANSWER":"PROCESS ANSWER","sdp:",v),S)return this.logger.safe.info(`[${f}] process [pranswer] ignored`),Promise.resolve();this.mediaContentType=g.contentType,-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType);const C=this.sessionDescription.createRemoteAnswer(v),_=C.clone(),T=invertModalities(C.getModalities());this.setNegotiatedModalities(T),C.setModalities(this.negotiatedModalities);const I=C.toRemote();this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources(),this.stats.sessionInfo.setBweType(C.getBweType());const b=new this.webrtcAdapter.RTCSessionDescription({sdp:I,type:"answer"});return this.updateDescriptor(b,_),this.logger.unsafe.info(`[${f}] process [answer] set remote description`,"negotiated:",this.negotiatedModalities,"sdp:",b.sdp),this.peerConnection.setRemoteDescription(b).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.negotiatedModalities))).then((()=>(this.handleSharingRecvCapabilities(_),this.handleVideoRecvCapabilities(_)))).then((g=>{g&&this.triggerRenegotiation(!0,f)}))}completeNegotiationAsync(g){return new Promise((f=>{this.mediaManager.commit();const S=this.configuredModalities,v=this.forceMediaStreamUpdate&&!isOnHold(this.negotiatedModalities)||!areNegotiatedDirectionsAcceptable(S,this.negotiatingModalities,this.negotiatedModalities)||this.triggerRenegotiationFlag,C=!v;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${g}] negotiation completed isComplete: ${C} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),v&&this.triggerRenegotiation(!1,g),this.negotiationCompletedPromise.resolve();f({isComplete:C,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})}))}rejectNegotiationAsync(g,f,S=!1){return Promise.resolve().then((()=>{if(this.mediaManager.rollback(),this.logger.safe.warn(`[${f}] negotiation rejected isComplete: ${!S} error: ${stringifyObject(g)} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),this.peerConnection){if("have-local-offer"===this.peerConnection.signalingState)return this.logger.safe.info(`[${f}] rolling back local description`),this.configProvider.config.webrtcHandleRollback?(this.logger.safe.info(`[${f}] rolling back using local renegotiation`),this.negotiationEmulator.renegotiateNow().then((()=>{this.logger.safe.info(`[${f}] rolling back using local complete`)}))):this.peerConnection.setLocalDescription(new this.webrtcAdapter.RTCSessionDescription({type:"rollback"}));this.logger.safe.error(`[${f}] cannot rollback local description in currrent state: ${this.peerConnection.signalingState}`)}})).then((()=>{this.canTriggerRenegotiation=!0,this.negotiationCompletedPromise.reject("negotiation rejected");this.getAddedMediaTypes(this.negotiatedModalities,this.negotiatingModalities).forEach((g=>{this.removeTrackByMediaType(g),this.disposeStreamByMediaType(g)})),this.registerLocalStreams()})).then((()=>(S&&(this.logger.safe.info(`[${f}] retrying failed negotiation`),this.triggerRenegotiation(!1,f)),{isComplete:!S,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})))}startMediaDescriptionsUpdateAsync(g){return Promise.reject(new Error("Not supported"))}completeMediaDescriptionsUpdateAsync(g){return Promise.reject(new Error("Not supported"))}rejectMediaDescriptionsUpdateAsync(g,f){return Promise.reject(new Error("Not supported"))}createRemoteRenderer(g){return this.remoteVideoManager.createRenderer(g,this.subscriptionManager,this.logger)}getStatsAsync(g){return this.terminated||(this.statisticsReport=this.statisticsReport.then((()=>this.stats.getReport(g))).catch((g=>(this.logger.safe.error(`getting statistics should never fail: ${g.error}`),g.partialReport)))),this.statisticsReport}getLastKnownStats(g=!1){return this.stats.getReport(!1,g)}muteHold(g,f){this.isMuteHold=g;const S=[qt.MODALITY.audio,qt.MODALITY.video,qt.MODALITY.sharing].filter((g=>hasSendDirectionality(this.negotiatedModalities[g])&&(g!==qt.MODALITY.audio||!this.doAudioMute)));for(const v of S)this.setMute(modalityToMediaType(v),g,f)}async muteInputAsync(g){this.doAudioMute=!0,this.setMute("Audio",!0,g)}async unmuteInputAsync(g){this.doAudioMute=!1,this.setMute("Audio",!1,g)}muteOutputAsync(g){return this.audioRenderer.setMuted(!0,g),Promise.resolve()}unmuteOutputAsync(g){return this.audioRenderer.setMuted(!1,g),Promise.resolve()}async getSpeakerVolume(g){return this.audioRenderer.getSpeakerVolume(g)}async setSpeakerVolume(g,f){return this.audioRenderer.setSpeakerVolume(g,f)}sendDtmf(g){return this.dtmfSender.sendDtmf(this.peerConnection,g)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}pauseNegotiations(g=generateCauseId()){const f=new dt;return this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(f,g)})),f}onDeviceEvent(g){this.stats.onDeviceEvent(g)}deviceSelectionChanged(){this.peerConnection&&(this.audioRenderer&&this.audioRenderer.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),isOnHold(this.negotiatedModalities)||(this.forceMediaStreamUpdate=!0,this.triggerRenegotiation(!0)))}async terminate(g,f,S=!0){this.logger.safe.info(`[${g}] terminate`),this.stats.setTerminated(),this.canTriggerRenegotiation=!1,this.cleanUp(g);try{S&&await this.getStatsAsync(!1)}catch(f){this.logger.safe.error(`[${g}] Error while gathering stats ${stringifyObject(f)}`)}finally{this.stats.dispose(),this.terminated=!0}}processNotification(g,f){"DominantSpeakerInfo"===g&&this.activeSpeakerManager.onDominantSpeakerHistoryChanged(f.previousDominantSpeakerHistory,"signaling"),"ControlVideoStreaming"===g&&this.streamConfigurationHandler.handleMessage(f)}cleanUp(g){this.negotiationQueue.dispose(),this.localVideoStreamWatcher.dispose(),this.remoteVideoManager.dispose(),this.resetPeerConnection(g),this.subscriptionManagerSubs.forEach((g=>g.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.clearIceDisconnectedTimer(),this.callbacks.onTerminated&&this.callbacks.onTerminated(),this.negotiationCompletedPromise.reject("webRtcSession cleanup")}resetPeerConnection(g){this.logger.safe.info(`[${g}] reset peer connection`),this.audioRenderer&&this.audioRenderer.dispose(),this.dtmfSender&&(this.dtmfSender.dispose(),this.dtmfSender=null),this.peerConnection&&this.peerConnection.close(),this.toBeCalledAfterConnected=[],this.disposeStreams(),this.peerConnection=null,this.contributingSources?.dispose(),this.activeSpeakerManager.dispose(),this.negotiationEmulator.configure(null),this.peerConnectionPromise=null,this.resetCandidateGathering(g),this.canTriggerRenegotiation=!0,this.negotiatedModalities={}}resetNegotiationQueue(g=generateCauseId()){this.negotiationCompletedPromise.reject("promise expired"),this.setNegotiationPromise(new dt,g)}setNegotiationPromise(g,f=generateCauseId()){this.terminated||(this.negotiationCompletedPromise=g,this.negotiationQueue.add(this.negotiationCompletedPromise,f))}updateQualityLevels(g){if(!g)return;this.hwSilent!==g.audioHwSilent&&(this.hwSilent=g.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.ufdManager.signalEvent("NetworkRecvQuality",g.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:g.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",g.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:g.networkSendLevel});const f=!(!g.isSpeaking||!this.doAudioMute);this.ufdManager.signalEvent("DeviceSpeakWhileMuted",f?"Bad":"Good")}triggerRenegotiation(g,f=generateCauseId()){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${f}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired&&this.callbacks.onNegotiationRequired(f)):g&&(this.logger.safe.info(`[${f}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}throwIfModalitiesNotConfigured(g){if(!this.configuredModalities)throw new Error(g)}addTrack(g,f,S){if(!g)return;const v=this.modalityByMediaType(S);if(this.logger.safe.info(`add media track kind: ${g.kind} id: ${g.id}`),this.senders[v])throw new Error("track already created, modality:"+v+", kind:"+g.kind+", id:"+g.id);"closed"!==this.peerConnection.iceConnectionState&&(this.senders[v]=this.peerConnection.addTrack(g,f))}registerMediaSources(){const g=[];if(this.mediaStreams.forEach(((f,S)=>{const v={sourceId:this.getSourceIdForStream(f),defaultSSRC:this.ssrcs[S].min,modality:this.modalityByMediaType(S)};g.push(v)})),this.qualityManager.updateRegisteredSources(g),this.videoStream){const g=this.videoStream.getResolution();this.qualityManager.setCurrentResolution(new Xt(g.width,g.height))}}updateStream(g,f){return g.start().then((()=>{try{const S=this.mediaStreams.get(f);if(S&&g.isSameStream(S))return g.dispose(),null;if(this.updateSsrcRangeForMediaType(f),this.removeTrackByMediaType(f),this.disposeStreamByMediaType(f),!this.peerConnection)return g.dispose(),null;if(this.addTrack(g.rawTrack,g.rawStream,f),g.onApplyConstraints=S=>{this.removeTrackByMediaType(f),S.then((()=>{this.addTrack(g.rawTrack,g.rawStream,f),this.registerLocalStreams(),this.mediaManager.updateMediaEntitiesWithLocalTracks()}))},this.mediaStreams.set(f,g),"Video"===f){const g=[this.getMediaTrackInfo(f)];this.localVideoStreamWatcher.startWatching(g)}}catch(S){throw this.removeTrackByMediaType(f),this.disposeStreamByMediaType(f),g.dispose(),S}}))}getSourceIdForStream(g){const f=g.rawStream.getTracks()[0].id,S=this.mediaManager.getMediaEntityByLocalTrackId(f);return S?(this.logger.safe.info(`Media entity found: ${JSON.stringify(S.getXSourceStreamId())}`),S.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(f)}`),0)}updatePeerConnectionStreamsAsync(g,f,S,v){const C=hasSendDirectionality(this.negotiatedModalities.audio),_=hasSendDirectionality(this.negotiatedModalities.video),T=hasSendDirectionality(this.negotiatedModalities.sharing),I=isOnHold(this.negotiatedModalities),b=hasSendDirectionality(g.audio),A=hasSendDirectionality(g.video),P=hasSendDirectionality(g.sharing),R=isOnHold(g);return I||R||(this.stats.onSendersChanged("Audio",b),this.stats.onSendersChanged("Video",A),this.stats.onSendersChanged("ScreenShare",P)),this.assurePeerConnectionAsync(v).then((async()=>{if(this.logger.safe.info("updatePeerConnectionStreamsAsync","pc state",this.peerConnection.signalingState,"hold","[",I,"->",R,"]","audio","[",C,"->",b,"]","video","[",_,"->",A,"]","sharing","[",T,"->",P,"]"),I!==R){if(this.videoStream&&this.videoStream.setHold(R),this.audioStream&&this.audioStream.setHold(R),this.displayStream&&this.displayStream.setHold(R),R)return;if(!R&&this.audioStream){this.removeTrackByMediaType("Audio");const g=this.audioStream.clone();this.audioStream.dispose(),this.mediaStreams.set("Audio",g),this.addTrack(this.audioStream.rawStream.getAudioTracks()[0],this.audioStream.rawStream,"Audio")}}if((C!==b||_!==A||T!==P||this.forceMediaStreamUpdate)&&(S&&(this.forceMediaStreamUpdate=!1),f&&(this.logger.safe.info("not using any media(track api) track, remove all senders"),b||(this.removeTrackByMediaType("Audio"),this.disposeStreamByMediaType("Audio")),S&&A||(this.removeTrackByMediaType("Video"),this.disposeStreamByMediaType("Video")),S&&P||(this.removeTrackByMediaType("ScreenShare"),this.disposeStreamByMediaType("ScreenShare"))),S)){const g=[];if(A){const f=await this.deviceManager.getVideoStream(!1);g.push(this.updateStream(f,"Video"))}if(P){const f=this.deviceManager.getDisplayStream();g.push(this.updateStream(f,"ScreenShare"))}if(b){const f=await this.deviceManager.getAudioStream(!1);g.push(this.updateStream(f,"Audio").then((()=>{this.audioStream.setMuted(this.doAudioMute)})))}return Promise.all(g).then((()=>this.registerLocalStreams()))}}))}getMediaTrackInfo(g){const f=this.modalityByMediaType(g),S=this.mediaStreams.get(g).rawStream.getTracks()[0].id;return S||this.logger.safe.error(`No media track for modality found: ${f}`),{trackId:S,modality:f}}getSsrcRangeForMediaType(g){const f={min:1,max:1};switch(g){case"Audio":return this.ssrcGenerator.nextAudioStreamSsrc();case"Video":case"ScreenShare":return this.ssrcGenerator.nextVideoStreamSsrc();default:return f}}updateSsrcRangeForMediaType(g){"Video"!==g&&"ScreenShare"!==g||(this.ssrcs[g]=this.ssrcGenerator.nextVideoStreamSsrc())}getStreamTransformConfiguration(){return{unifiedPlanEnabled:!1,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}registerLocalStreams(){const g=[];this.mediaStreams.forEach(((f,S)=>{g.push(this.getMediaTrackInfo(S))})),this.mediaManager.setLocalTracksInfo(g)}handleVideoRecvCapabilities(g){if(this.configProvider.config.enableLocalVideoConstraints&&hasReceiveDirectionality(g.getModalities().video)){if(this.videoStream){const f=g.getVideoRecvCapabilities();if(!f)return this.logger.safe.error("No fmt params found for video modality"),Promise.resolve(!1);const S=this.generateReceiveCapabilities(f,this.videoStream);this.qualityManager.setMaxCapabilities([S])}this.logger.safe.error("remote endpoint didn't specify video receive capability")}return Promise.resolve(!1)}handleSharingRecvCapabilities(g){if(this.configProvider.config.enableLocalVideoConstraints&&hasReceiveDirectionality(g.getModalities().sharing)&&this.displayStream){const f=g.getSharingRecvCapabilities();if(!f)return void this.logger.safe.error("No fmt params found for sharing modality");const S=this.generateReceiveCapabilities(f,this.displayStream);this.qualityManager.setMaxCapabilities([S])}}generateReceiveCapabilities(g,f){const S={ssrc:0,rid:"0",keyframe:!1,...g},v={causeId:generateCauseId(),isSimulcast:!1,sourceId:this.getSourceIdForStream(f),capabilities:[S]};return this.logger.safe.info(`Generated receive capabilities for stream ${f.id}: ${JSON.stringify(v)}`),v}updateDescriptor(g,f){const S=f.getVideoRecvCapabilities(),v={sourceId:0,streamMsid:0,bandwidth:0};if(S&&this.videoStream&&!this.displayStream&&(v.sourceId=this.getSourceIdForStream(this.videoStream),v.streamMsid=this.videoStream.id,v.bandwidth=S.maxBr?S.maxBr:Number.MAX_VALUE),v.bandwidth>0){v.bandwidth=Math.floor(v.bandwidth/1200);const f=new OT(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider);f.setControlItem(v),f.modifyDescriptor(g)}}removeTrackByMediaType(g){return this.removeTracksByModality(this.modalityByMediaType(g))}modalityByMediaType(g){switch(g){case"Audio":return qt.MODALITY.audio;case"Video":return qt.MODALITY.video;case"ScreenShare":return qt.MODALITY.sharing;default:throw new Error(`Modality is not defined for media type: ${g}`)}}removeTracksByModality(g){this.forceKeyFramePromise&&"sharing"===g?this.forceKeyFramePromise.then((()=>{this.removeTracksByModality(g)})):g in this.senders&&(this.logger.safe.info(`remove sender track kind: ${this.senders[g].track.kind} track id: ${this.senders[g].track.id}`),"closed"!==this.peerConnection.iceConnectionState&&this.peerConnection.removeTrack(this.senders[g]),delete this.senders[g])}handleCodecSwitchUnsupported(g){return this.offeredDescription.isCodecSwitchSupported()?Promise.resolve():this.webrtcAdapter.RTCRtpReceiver.getCapabilities(qt.MEDIA_TYPE.audio).then((g=>{const f=g.codecs.map((g=>g.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(f)})).catch((f=>{this.logger.safe.error(`[${g}] failed to set primary codec based on audio capability ${stringifyObject(f)}`)}))}disposeStreamByMediaType(g){const f=this.mediaStreams.get(g);f&&(this.mediaStreams.delete(g),f.dispose(),"Video"===g&&this.localVideoStreamWatcher.stopWatching())}disposeStreams(){this.mediaStreams.forEach(((g,f)=>this.disposeStreamByMediaType(f)))}assurePeerConnectionAsync(g){if(!this.peerConnectionPromise){if(!this.relayManagerProvider)throw new Error("relay manager provider is not set!");this.logger.safe.info("fetching relay details from RelayManager...");const f={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};this.peerConnectionPromise=this.relayManagerProvider.getRelayManager().queryRelaysAsync(f).then((f=>{if(this.terminated)throw new Error("session already disposed");const S={optional:[]},v=createIceServers(f,this.configProvider.config),C=this.configureCrypto(S);this.configureCpuThreshold(S),this.logger.safe.info("create peer connection");const _=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle",T=this.peerConnection=new this.webrtcAdapter.RTCPeerConnection({iceServers:v,rtcpMuxPolicy:"require",iceTransportPolicy:this.iceTransportPolicy,bundlePolicy:_,sdpSemantics:"plan-b",audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===C,offerExtmapAllowMixed:!1},S);this.negotiationEmulator.configure(T),this.stats.initialize(T),this.stats.sessionInfo.setIceServers(v),this.stats.sessionInfo.setIceTransportPolicy(this.iceTransportPolicy),this.stats.sessionInfo.setBundlePolicy(_);const I=this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video"),b=this.webrtcAdapter.RTCRtpSender.getCapabilities("video");this.stats.setH264AvailableProfiles(I),this.stats.setSupportedH264Profiles(b,I),T.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${T.signalingState}`)},T.onsignalingstatechange=()=>{this.stats.sessionInfo.setSignalingConnectionState(T.signalingState),this.logger.safe.info(`onsignalingstatechange signalingState: ${T.signalingState}`)},T.onicecandidateerror=g=>{const[f,S]=[g.address,g.port];this.logger.safe.warn(`On ICE candidate error ${g.url} | ${f}:${S}: code ${g.errorCode}: ${g.errorText}`),this.isConnected()&&!this.iceCandidatesDeferred.isPending||this.stats.addIceCandidateError({address:f,port:+S,url:g.url,errorCode:g.errorCode,errorText:g.errorText})};const onAddStream=g=>{if(!this.isConnected())return this.logger.safe.info("onaddstream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>onAddStream(g)));const f=g.stream;this.logger.safe.info(`onaddstream stream: ${f.id}`);let S=this.mediaManager.getMediaEntityByRemoteStreamId(f.id);if(S||(this.logger.safe.info(`cannot find media entity with stream id ${f.id} trying to fallback`),f.getAudioTracks()[0]&&(S=this.mediaManager.getMediaEntitiesByModality(qt.MODALITY.audio)[0])),S){const g=this.createReceiveStream(f,S);this.receiveStreamCollection.add(g)}else this.logger.safe.error(`could not find media entity for an added stream: ${f.id}`)};T.onaddstream=onAddStream,T.ontrack=g=>{this.logger.safe.info(`ontrack track: ${g.track}`)};const onRemoveStream=g=>{if(!this.isConnected())return this.logger.safe.info("onremovestream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>onRemoveStream(g)));this.logger.safe.info(`onremovestream stream: ${g.stream.id}`),this.receiveStreamCollection.remove(g.stream.id)};T.onremovestream=onRemoveStream,T.onicecandidate=f=>{const S=f.candidate;if(S){const f=parseCandidateString(S.candidate);this.logger.safe.info(`[${g}] onicecandidate candidate: prio:${f.priority} type:${f.type} port:${f.port}`),this.logger.unsafe.info(`[${g}] candidate details: ${S.candidate}`),!this.relayCandidateGathered&&S.candidate.indexOf("typ relay")>-1&&(this.stats.sessionInfo.setRelayCandidateInfo({priority:S.priority||S.candidate.split(" ")[3],time:Date.now()-this.iceRelayCandidatesGatherStartTime}),this.relayCandidateGathered=!0)}else this.logger.safe.info(`[${g}] onicecandidate candidate: null`);if(!this.iceCandidatesDeferred.isPending)return;const C=!this.initiator||!this.context.config.webrtcIceGatheringTimeoutIncreased,_=this.iceHostCandidateOnly||0===v.length;if(!S&&C||_){S&&this.logger.safe.info(`[${g}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${g}] Is connected:`,this.isConnected(),T.iceConnectionState,T.signalingState);let f=!0;if(this.context.configProvider.mediaConfig.isTransportUnbundled&&S){f=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledIceCandidates()}f&&this.completeCandidateGathering(g)}else if(this.relayCandidateGathered){let f=!0;if(this.context.configProvider.mediaConfig.isTransportUnbundled){f=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledRelayIceCandidates()}f&&(this.stats.clearIceCandidateErrors(),this.completeCandidateGathering(g))}},T.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${T.iceGatheringState}`)},T.oniceconnectionstatechange=()=>{const g=generateCauseId();if(!this.terminated){if(this.stats.sessionInfo.setIceConnectionState(T.iceConnectionState),this.logger.safe.info(`[${g}] oniceconnectionstatechange iceConnectionState: ${T.iceConnectionState} pc.signalingState: ${T.signalingState}`),"connected"===T.iceConnectionState||"completed"===T.iceConnectionState)this.onTransportConnected(g);else if("failed"===T.iceConnectionState){if(this.iceCandidatesDeferred.isPending)return this.logger.safe.info(`[${g}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(g);this.raiseError({type:qt.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},g),this.configProvider.config.webrtcCloseAfterIceFailure&&T.close(),this.onTransportFailed()}"disconnected"===T.iceConnectionState?(this.onTransportDisconnected(g),this.startIceDisconnectedTimer(g)):this.clearIceDisconnectedTimer()}},this.multiParty&&(this.contributingSources=new hb(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new ub(this.logger.createChild("ContributingSourcesProvider"),T)))}))}return this.peerConnectionPromise}configureCrypto(g){let f=!1;const S=preferSdesSrtp(this.context.configProvider,this.context.config.isPstnCall);if(this.offeredDescription){const g=this.offeredDescription.getSrtpInfo();this.stats.sessionInfo.setOfferedSrtpInfo(g),f=!g.dtls||g.sdes&&S}else f=S;return f&&(this.logger.safe.info("configuring peer connection to use sdes"),g.optional.push({DtlsSrtpKeyAgreement:!1})),this.stats.sessionInfo.setNegotiatedSrtpInfo({dtls:!f,sdes:!!f}),f?0:1}configureCpuThreshold(g){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&g.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(g){this.iceCandidatesDeferred.isPending&&(this.logger.safe.info(`[${g}] ICE candidates gathered completely`),this.iceCandidatesDeferred.resolve())}onTransportConnected(g){if(this.logger.safe.info(`[${g}] audio transport connected`),this.stats.clearIceCandidateErrors(),!this.terminated)for(this.callbacks.onAudioStateChanged(qt.STREAMING_STATE.active,g),this.callbacks.onTransportConnected&&this.callbacks.onTransportConnected(g);this.toBeCalledAfterConnected.length;)this.toBeCalledAfterConnected.shift()()}onTransportDisconnected(g){this.callbacks.onTransportDisconnected&&this.callbacks.onTransportDisconnected(g)}onTransportFailed(){this.callbacks.onTransportFailed&&this.callbacks.onTransportFailed()}startIceDisconnectedTimer(g){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${g}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise CONSTANTS.MEDIAthis._ERROR.iceConnectionError`),this.raiseError({type:qt.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},g)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(g,f=generateCauseId()){this.logger.safe.error(`[${f}] Media error occurred type: ${g.type} detail: ${g.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(g,f)}createNegotiationConstraints(g){function canReceive(g){return!!g&&(hasReceiveDirectionality(g)||"inactive"===g)}return{offerToReceiveAudio:canReceive(g.audio),offerToReceiveVideo:canReceive(g.video)||canReceive(g.sharing)}}resetCandidateGathering(g){this.logger.safe.info(`[${g}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new dt}checkIceCandidates(g){const f=this.hasIceCandidates(g);if(f===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:qt.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(f){const f=this.hasRelayIceCandidates(g);if(f===this.noRelayIceCandidates){if(!f&&("connected"===this.peerConnection.iceConnectionState||"completed"===this.peerConnection.iceConnectionState))return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasIceCandidates(g){return this.configProvider.mediaConfig.isTransportUnbundled?g.hasUnbundledIceCandidates():g.hasIceCandidates()}hasRelayIceCandidates(g){return this.configProvider.mediaConfig.isTransportUnbundled?g.hasUnbundledRelayIceCandidates():g.hasRelayIceCandidates()}doRetargetIfNeeded(g,f,S){const v=f.isIceRestart();this.logger.safe.info(`[${S}] ICE restart: ${v}`),this.context.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription?.isMSRTC()&&v&&!this.multiParty&&f.getSrtpInfo().sdes&&(g.newOffer=!0)}getAddedMediaTypes(g,f){g||(g={}),f||(f={});const S=[];return isModalityAdded(g.audio,f.audio)&&S.push("Audio"),isModalityAdded(g.video,f.video)&&S.push("Video"),isModalityAdded(g.sharing,f.sharing)&&S.push("ScreenShare"),S}applyCapabilitiesForModality(g,f,S){return g===qt.MODALITY.video?this.applyCapabilitiesForVideo(f,S[0]):g===qt.MODALITY.sharing?this.applyCapabilitiesForSharing(f,S[0]):Promise.resolve(!1)}applyCapabilitiesForSharing(g,f){return this.displayStream?this.applyCapabilities(this.displayStream,f).then((S=>(this.stats.onMaxCapabilitiesApplied({causeId:g,modality:qt.MODALITY.sharing,capabilities:[f]}),this.configProvider.config.webrtcAllowRestoreKeyframe?this.forceKeyframe(this.senders[qt.MODALITY.sharing]).then((()=>S)):Promise.resolve(S)))):(this.logger.safe.info(`${JSON.stringify(f)} is ignored as no sharing stream is sent, no renegotiation`),Promise.resolve(!1))}forceKeyframe(g){if(!g)return this.logger.safe.error("forceKeyframe: No sender available for sharing"),null;if(this.forceKeyFramePromise)return this.logger.safe.warn("forceKeyframe: already in progress"),this.forceKeyFramePromise;this.logger.safe.info("Restoring keyframe");const f=g.track;return this.forceKeyFramePromise=g.replaceTrack(null).then((()=>g.replaceTrack(f))).then((()=>{this.forceKeyFramePromise=null,this.logger.safe.info("Restoring keyframe finished")})).catch((g=>{this.forceKeyFramePromise=null,this.logger.safe.error(`Restoring keyframe failed: ${g}`),delete this.senders[qt.MODALITY.sharing]})),this.forceKeyFramePromise}applyCapabilitiesForVideo(g,f){return this.negotiationCompletedPromise.isPending?(this.logger.safe.info("##### Renegotiation is in progress, no local resolution switch for now #####"),this.negotiationCompletedPromise.promise.then((()=>Promise.resolve(!1)))):this.videoStream?this.scheduleApplyCapabilities(this.videoStream,g,f):(this.logger.safe.info(`${JSON.stringify(f)} is ignored as no video is sent, no renegotiation`),Promise.resolve(!0))}scheduleApplyCapabilities(g,f,S){this.logger.safe.info("Queueing local renegotiation...");let v=!1;return this.negotiationQueue.add((()=>(this.logger.safe.info("############# LOCAL RENEGOTIATION START #############"),this.applyCapabilities(g,S).then((()=>{this.stats.onMaxCapabilitiesApplied({causeId:f,modality:qt.MODALITY.video,capabilities:[S]}),v=!0})))),f),this.negotiationEmulator.renegotiate().then((()=>(this.logger.safe.info(`############# LOCAL RENEGOTIATION END. RESULT: ${v}  #############`),v)))}applyCapabilities(g,f){return g?(this.logger.safe.info(`Changing resolution to ${JSON.stringify(f)}`),g.applyCapabilities(f)):(this.logger.safe.info(`Resolution ${JSON.stringify(f)} ignored, no stream is being sent`),Promise.resolve(!1))}onOptimalVideoReceiversCountChanged(g){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(g)}getStreams(){return this.receiveStreamCollection.getStreams()}onStreamsChanged(g){this.streamsChangedListener=g}notifyStreamsChanged(){this.logger.safe.info(`Scheduling stream changed notification: ${this.streamsChangedNotificationScheduled}`),this.streamsChangedNotificationScheduled||this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.streamsChangedNotificationScheduled=!1,this.streamsChangedListener&&this.streamsChangedListener()}))}streamAdded(g){qt.MODALITY.audio===g.getModality()&&(this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),this.audioRenderer.play(g.getMediaStream())),this.notifyStreamsChanged()}streamRemoved(g){qt.MODALITY.audio===g.getModality()&&this.audioRenderer.getStream()===g.getMediaStream()&&this.audioRenderer.stop(),this.notifyStreamsChanged()}setNegotiatedModalities(g){this.negotiatedModalities=g,this.stats.sessionInfo.setNegotiatedModalities(g)}setupIceGatheringTimeout(g){this.iceRelayCandidatesGatherStartTime=Date.now();const f=this.context.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!f)return;this.iceCandidatesTimer>0&&clearTimeout(this.iceCandidatesTimer);const S=this.iceCandidatesDeferred;this.iceCandidatesTimer=setTimeout((()=>{this.iceCandidatesTimer=0,S.isPending&&(this.logger.safe.warn(`[${g}] ICE candidates gathering terminated due to timeout ${f}`),S.resolve())}),f)}createAudioRenderer(){this.audioRenderer=new WC(this.logger.createChild("AudioRenderer"),this.configProvider),this.context.maContext.domOverrides.onMediaElementAdded&&this.audioRenderer.on("onAudioElementAdded",this.context.maContext.domOverrides.onMediaElementAdded),this.context.maContext.domOverrides.onMediaElementRemoved&&this.audioRenderer.on("onAudioElementRemoved",this.context.maContext.domOverrides.onMediaElementRemoved)}isConnected(){const g=this.peerConnection;return g&&("connected"===g.iceConnectionState||"completed"===g.iceConnectionState)}isFailed(){return this.peerConnection&&("failed"===this.peerConnection.iceConnectionState||"closed"===this.peerConnection.iceConnectionState)}hasRelayCandidates(){return this.relayCandidateGathered}createReceiveStream(g,f){const S=this.configProvider.config.addFmtpToInitialSubscription?f.getLocalRecvCapabilities():null,v=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&f.getModality()!==qt.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null;return new $y(g,null,f.getModality(),+f.getXSourceStreamId(),this,S,v)}requestSource(g,f,S){if(!this.multiParty)return Promise.resolve();const v=this.mediaManager.getMediaEntityByRemoteStreamId(g);return!this.isMuteHold&&this.negotiatedModalities[v.getModality()]!==qt.MEDIA_STATE.inactive||-1===f?this.negotiationCompletedPromise.isPending?this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>this.requestSource(g,f,S))):Promise.resolve().then((()=>this.mediaMessageController.sendSourceRequest(v.getXSourceStreamId(),f,v?.getMid(),S,v.getSubstreamIndex()))):delay(10).then((()=>this.requestSource(g,f,S)))}getSessionConfig(){return this.configProvider}getUnmixedAudioProvider(){return null}};function isModalityAdded(g,f){return!hasSendDirectionality(g)&&hasSendDirectionality(f)}var jb={build:(g,f,S)=>new $b(g,f,S)},Gb=M,qb=class extends Ht{constructor(g,f){super(f),this.logger=f,this.id=-1,this.parentId=-1,this.rawStream=null,this.rawTrack=null,this.deviceId=null,this.mediaType=g}start(){return this.logger.safe.debug("start"),Promise.resolve()}clone(){return this.logger.safe.debug("clone"),this}setMuted(g,f){this.logger.safe.debug("setMuted")}setHold(g){this.logger.safe.debug("setHold")}getResolution(){return this.logger.safe.debug("getResolution"),{width:240,height:180}}getFrameRate(){return this.logger.safe.debug("getFrameRate"),1}hasAudio(){return this.logger.safe.debug("hasAudio"),!1}hasVideo(){return this.logger.safe.debug("hasVideo"),!1}isSameStream(g){return this.logger.safe.debug("isSameStream"),g===this}applyCapabilities(g){return this.logger.safe.debug("applyCapabilities"),Promise.resolve(!1)}onApplyConstraints(g){this.logger.safe.debug("onApplyConstraints")}update(g){this.logger.safe.debug("update")}isActive(){return!1}isDisposed(){return!1}},Wb=class _SessionStreamsProvider extends Ht{constructor(g,f,S,v,C){super(C),this.callDeviceManager=g,this.configProvider=f,this.sessionConfig=S,this.serialQueue=v,this.logger=C,this.mediaStreams={Audio:null,Video:null,ScreenShare:null},this.streamSubscriptions=new Map,this.deviceManagerSubscriptions=[],this.isNullAudioStream=!1}get currentMediaTypes(){return keys(this.mediaStreams).filter((g=>!!this.mediaStreams[g]))}async getStreams(){return this.mediaStreams}useNullAudioStreamClient(){this.isNullAudioStream=!0}async update(g,f){const S=keys(g).filter((f=>g[f]));return deepEqual(S,this.currentMediaTypes)?(this.logger.safe.info("Requested modalities have not changed. Do nothing"),sendStreamsToModalities(this.mediaStreams)):(this.logger.safe.info(`Starting media session with modalities: ${JSON.stringify(g)}`),await this.updateStreams(S,f),this.subscribeOnDeviceManagerEvents(),sendStreamsToModalities(this.mediaStreams))}async stopAsync(){this.logger.safe.info("Stopping streams async"),this.stop()}stop(){this.logger.safe.info("Stopping streams"),this.unsubscribeFromDeviceManagerEvents(),keys(this.mediaStreams).forEach((g=>this.removeStreamByType(g)))}dispose(){this.stop(),super.dispose()}async updateStreams(g,f){const S=this.getAvailableMediaTypes(),v=(0,Gb.intersection)(g,S),C=keys(this.mediaStreams).filter((g=>this.mediaStreams[g])),_=f?[]:subtractFrom(v,C),T=subtractFrom(C,v);_.length&&this.logger.safe.info(`Adding media streams for types: ${JSON.stringify(_)}`),await Promise.all(_.map((async g=>{await this.addStream(g,!1),this.mediaStreams[g]&&this.event("onStreamAdded").raise(g)}))),T.length&&this.logger.safe.info(`Removing media streams for types: ${JSON.stringify(T)}`),T.forEach((g=>{this.event("onStreamRemoving").raise(g),this.removeStreamByType(g)}))}getAvailableMediaTypes(){const g=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices(),f=[];return g.microphone&&f.push("Audio"),g.camera&&f.push("Video"),f.push("ScreenShare"),f}async addStream(g,f){if(this.mediaStreams[g])return void this.logger.safe.warn(`Stream with type: ${g} is already registered`);const S=await this.getStream(g,f);this.subscribeOnMediaStreamEvents(S);try{await S.start()}catch(f){return this.logger.safe.error(`Media stream request error: ${JSON.stringify(f)}`),void this.event("onStreamError").raise(g,f)}this.mediaStreams[g]=S}removeStreamByType(g){const f=this.mediaStreams[g];f?(this.unsubscribeFromMediaStreamEvents(f),f.dispose(),this.mediaStreams[g]=null):this.logger.safe.warn(`Stream with type: ${g} is not registered`)}async updateStream(g,f,S=!1){S&&"Audio"===g?await this.updateStreamWithEffect(g):(this.removeStreamByType(g),await this.addStream(g,f)),this.event("onStreamUpdated").raise(g)}async updateStreamWithEffect(g){const f=this.mediaStreams[g];f&&this.unsubscribeFromMediaStreamEvents(f);const S=await this.getStreamByMediaType(g,!0);this.subscribeOnMediaStreamEvents(S);try{await S.start()}catch(f){return this.logger.safe.error(`updateStreamWithEffect. Media stream request error: ${JSON.stringify(f)}`),void this.event("onStreamError").raise(g,f)}this.mediaStreams[g]=S,f?.dispose()}subscribeOnMediaStreamEvents(g){if(this.streamSubscriptions.has(g))return;const f=[];f.push(g.on("onStreamClientError",((g,f)=>this.onStreamError(g,f)))),f.push(g.on("onStreamClientDisposing",(g=>this.onStreamDisposing(g)))),this.streamSubscriptions.set(g,f)}unsubscribeFromMediaStreamEvents(g){this.streamSubscriptions.has(g)&&(this.streamSubscriptions.get(g).forEach((g=>g.dispose())),this.streamSubscriptions.delete(g))}async getStream(g,f){const S=this.mediaStreams[g];return S?(this.logger.safe.info(`Stream exists with id: ${S.id}, type: ${g}`),S):this.getStreamByMediaType(g,f)}async getStreamByMediaType(g,f){switch(g){case"Audio":return this.isNullAudioStream?new qb("Audio",this.logger.createChild("NullStreamClient")):this.getDeviceManagerByType("Audio").getAudioStream(f,"sessionStream");case"Video":return this.getDeviceManagerByType("Video").getVideoStream(f,"sessionStream",!1,this.sessionConfig.outgoingVideoMaxFS);case"ScreenShare":return this.getDeviceManagerByType("ScreenShare").getDisplayStream("sessionStream");default:throw new Error(`Media type is not supported: ${g}`)}}getMediaTypeForStream(g){const f=Object.keys(this.mediaStreams).find((f=>this.mediaStreams[f]===g));return f||this.logger.safe.error(`Media type is not found for stream: ${stringifyObject(g)}`),f}subscribeOnDeviceManagerEvents(){if(0!==this.deviceManagerSubscriptions.length)return;if(this.callDeviceManager.isVirtualDeviceEnabled){const g=this.callDeviceManager.on("onSelectedVirtualDevicesChanged",((g,f)=>{const S=g;if(!g.camera){this.logger.info("Virtual DeviceID for camera is undefined, falling back to default device");const{camera:g}=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices();S.camera=g}this.callDeviceManager.isModalityEnabled("Video")&&f.camera!==S.camera&&(this.logger.info("Updating stream for camera"),this.updateStreamForVirtualDeviceChange("Video")),this.callDeviceManager.isModalityEnabled("ScreenShare")&&f.screenshare!==S.screenshare&&(this.logger.info("Updating stream for screenshare"),this.updateStreamForVirtualDeviceChange("ScreenShare"))}));this.deviceManagerSubscriptions.push(g)}const g=this.callDeviceManager.getDefaultDeviceManager();this.deviceManagerSubscriptions.push(g.on("onSelectedDevicesChanged",((g,f)=>this.onSelectedDevicesChanged(g,f))),g.on("onStreamUpdateRequested",((g,f)=>this.requestStreamUpdate(g,!1,f))),g.on("onAudioSharingToggled",(g=>this.onAudioSharingToggled(g))))}unsubscribeFromDeviceManagerEvents(){0!==this.deviceManagerSubscriptions.length&&(this.deviceManagerSubscriptions.forEach((g=>g.dispose())),this.deviceManagerSubscriptions=[])}getMediaTypesToUpdate(g,f){const S=[];return this.currentMediaTypes.some((g=>"Audio"===g))&&g.microphone&&g.microphone!==f.microphone&&S.push("Audio"),!this.callDeviceManager.getSelectedDevices().camera&&this.currentMediaTypes.some((g=>"Video"===g))&&g.camera&&g.camera!==f.camera&&S.push("Video"),S}removeStream(g){const f=this.getMediaTypeForStream(g);this.removeStreamByType(f)}async onSelectedDevicesChanged(g,f){if(this.configProvider.config.enablePermissionsWorkaround&&_SessionStreamsProvider.isDeviceListEmpty(g,f))return void this.logger.safe.info("Device list is empty, permission workaround enabled");const S=this.getMediaTypesToUpdate(g,f);this.logger.safe.info(`Media types to update: ${JSON.stringify(S)}`),await Promise.all(S.map((g=>this.updateStream(g,!1))))}async onAudioSharingToggled(g){if(this.configProvider.config.postponeAudioMixerForAudioSharing&&g)return this.updateStream("ScreenShare",!0)}async requestStreamUpdate(g,f,S=!1){if(this.currentMediaTypes.some((f=>f===g))||f)return this.logger.safe.debug(`UpdateStream with media type: ${g}, force: ${f}`),this.updateStream(g,f,S);this.logger.safe.debug(`Stream with media type: ${g} is not active. Do nothing`)}onStreamError(g,f){this.removeStream(g)}onStreamDisposing(g){this.removeStream(g)}static isDeviceListEmpty(g,f){return!g.camera&&!g.microphone||!f.microphone&&!f.camera}getDeviceManagerByType(g){return this.callDeviceManager.getDeviceManager(g)}async updateStreamForVirtualDeviceChange(g){return this.updateStream(g,!1)}};__decorateClass([sequentialize()],Wb.prototype,"getStreams",1),__decorateClass([sequentialize()],Wb.prototype,"update",1),__decorateClass([sequentialize()],Wb.prototype,"stopAsync",1),__decorateClass([sequentialize()],Wb.prototype,"onSelectedDevicesChanged",1),__decorateClass([sequentialize()],Wb.prototype,"onAudioSharingToggled",1),__decorateClass([sequentialize()],Wb.prototype,"requestStreamUpdate",1),__decorateClass([sequentialize()],Wb.prototype,"updateStreamForVirtualDeviceChange",1);var zb=Wb,Kb=M,Jb=[5e4,1e6,15e5,2e6,25e5,375e4,4e6],Yb=[7e4,2e5,4e5,8e5,15e5,2499990,25e5];function createBandwidthAllocatorPerMediaType(g,f){const S=new Qb(g.createChild("BandwidthAllocator"));return S.setLadder("ScreenShare",f.config.sharingBitrateLadderOverride||Jb),S.setLadder("Video",f.config.videoBitrateLadderOverride||Yb),S}var Qb=class{constructor(g){this.logger=g,this.availableBandwidth=0,this.receivers=new Map,this.currentLayout={},this.ladders={}}setAvailableBandwidth(g){this.availableBandwidth=g,this.logger.safe.debug(`Total available bandwidth updated: ${g}`),this.updateLayouts()}getAvailableBandwidth(){return this.availableBandwidth}addReceiverCapability(g,f){this.logger.safe.debug(`Receiver maxBr set: ${g}/${f}`),this.receivers.set(g,f),this.updateLayouts()}getReceiverCapabilities(){const g={};for(const f of Object.keys(this.receivers)){const S=this.receivers.get(f);S&&(g[f]=S)}return g}removeReceiver(g){this.logger.safe.debug(`Receiver maxBr removed: ${g}`),this.receivers.delete(g),this.updateLayouts()}getLayouts(){return this.currentLayout}setLadder(g,f){this.ladders[g]=f}updateLayouts(){const g=this.generateLayouts();(0,Kb.isEqual)(g,this.currentLayout)||(this.currentLayout=g,this.logger.safe.debug(`Bandwidth distribution updated: ${stringifyObject(g)}`))}generateLayouts(){const g={},f={};for(const S of Object.keys(this.ladders)){const v=this.receivers.get(S);v&&(f[S]=v||Number.MAX_SAFE_INTEGER,g[S]=0)}let S=this.availableBandwidth,v=0;const runLoop=()=>{if(!S)return!1;for(const g of Object.values(f))if(g)return!0;return!1};for(;runLoop();){for(const C of Object.keys(g)){const _=this.ladders[C];let T=_[v]||_[_.length-1];T=Math.min(T,S,f[C]),g[C]+=T,S-=T,f[C]-=T}v++}return g}};function getVideoBandwidthLadder(g,f){const S=g.config.bandwidthAllocatorV2;let v=[],C=-1;for(const g of S.videoLadders)(f>=g.maxFS&&C<g.maxFS||-1===C)&&(v=g.ladder,C=g.maxFS);return v}function createBandwidthAllocatorV2(g,f){const S=new Xb(g.createChild("BandwidthAllocator2"));return S.setPriority("ScreenShare","Video"),S.setLadder("ScreenShare",f.config.bandwidthAllocatorV2.sharingLadder),S.setLadder("Video",getVideoBandwidthLadder(f,f.config.bandwidthAllocatorV2.defaultVideoMaxFS)),S}var Xb=class{constructor(g){this.logger=g,this.availableBandwidth=0,this.receivers=new Map,this.currentLayout={},this.ladder=[],this.priority=[]}getReceiverCapabilities(){const g={};for(const f of Object.keys(this.receivers)){const S=this.receivers.get(f);S&&(g[f]=S)}return g}setAvailableBandwidth(g){this.availableBandwidth=g,this.logger.safe.debug(`Total available bandwidth updated: ${g}`),this.updateLayouts()}getAvailableBandwidth(){return this.availableBandwidth}addReceiverCapability(g,f){this.logger.safe.debug(`Receiver maxBr set: ${g}/${f}`),this.receivers.set(g,f),this.updateLayouts()}removeReceiver(g){this.logger.safe.debug(`Receiver maxBr removed: ${g}`),this.receivers.delete(g),this.updateLayouts()}getLayouts(){return this.currentLayout}setPriority(...g){this.priority=g}setLadder(g,f){this.logger.safe.info(`Set ladder for ${g}: ${JSON.stringify(f)}`);for(const f of this.ladder)delete f[g];-1===this.priority.indexOf(g)&&this.priority.push(g);for(let S=0;S<f.length;++S)S>=this.ladder.length&&this.ladder.push({}),this.ladder[S][g]=f[S]}updateLayouts(){const g=this.generateLayouts();(0,Kb.isEqual)(g,this.currentLayout)||(this.currentLayout=g,this.logger.safe.debug(`Bandwidth distribution updated: ${stringifyObject(g)}`))}generateLayouts(){const g={};let f=this.availableBandwidth;for(const f of this.priority)this.receivers.get(f)&&(g[f]=0);for(let S=0;S<this.ladder.length&&f;++S){const v=this.ladder[S];for(const S of this.priority){const C=v[S];if(C&&this.receivers.get(S)){const v=Math.max(0,Math.min(C-g[S],f));f-=v,g[S]+=v}}}if(f){const S=f;let v=0;for(const g of this.priority)v+=this.receivers.get(g)??0;for(const C of this.priority){const _=this.receivers.get(C);if(_){const T=Math.min(f,Math.ceil(_*S/v));T&&this.logger.safe.info(`[AllocateSurplus][${C}] ${g[C]} + ${_} | ${f}`),f-=T,g[C]+=T}}}return g}},Zb=class{constructor(g,f,S){this.timeout=f,this.logger=S,this.isFirstTimeDeferred=!0,this.internalCallback=f=>{this.logger.safe.debug(`Trigger reason: ${f}`),g()}}invoke(g){this.logger.safe.debug(`Schedule shouldDefer: ${g}`),this.isFirstTimeDeferred?g?(this.isFirstTimeDeferred=!1,this.startTimer()):(this.stopTimer(),this.internalCallback("request")):this.timeoutId&&g||this.internalCallback("request")}dispose(){this.stopTimer()}startTimer(){this.timeoutId||(this.timeoutId=setTimeout((()=>{this.internalCallback("timeout"),this.timeoutId=void 0}),this.timeout),this.logger.safe.debug(`Timer started for : ${this.timeout}ms`))}stopTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0,this.logger.safe.debug("Timer stopped"))}},eA=class{constructor(g){this.logger=g,this.currentFrameSize=ei.Send.initialResolution.fs}setAvailableBandwidth(g){g!==this.lastSendBW&&(this.logger.safe.debug(`Available bandwidth updated ${g}`),this.processEstimatedBandwidth(g))}setMaxFrameSize(g){this.logger.safe.debug(`SetMaxFrameSize ${g}`),g!==this.maxFrameSize?(this.maxFrameSize=g,this.lastSendBW?(this.logger.safe.debug(`Setting max frame size: ${g}`),this.processEstimatedBandwidth(this.lastSendBW)):this.logger.safe.debug("Last send bwe is not defined. Do nothing")):this.logger.safe.debug(`Max frame size did not change. Do nothing, maxFs: ${g}`)}getFrameSize(){return this.currentFrameSize}processEstimatedBandwidth(g){if(this.logger.safe.debug(`Process estimated bandwidth ${g}`),0===g)return this.lastSendBW=0,void this.proposeResolution(0);const{lowRes:f,highRes:S}=ei.Send.getResolutionForBitrate(g);this.logger.safe.debug("low",f,"hi",S);const v=g<this.lastSendBW?S.fs:f.fs;g<this.lastSendBW&&this.currentFrameSize<v?this.logger.safe.debug(`proposed resolution is above the existing one, so we should stay on the current resolution, last bw: ${g}`):(v&&this.proposeResolution(v),this.logger.safe.debug(`Updating last bw: ${g}`),this.lastSendBW=g)}proposeResolution(g){this.logger.safe.debug(`Propose resolution ${g}`);const f=this.maxFrameSize?Math.min(g,this.maxFrameSize):g;f!==this.currentFrameSize&&(this.currentFrameSize=f,this.logger.safe.debug(`Proposed new frame size: ${f} based on bandwidth: ${this.lastSendBW}`))}},tA=1e8,iA=[{bwe:2e5,param:5e5},{bwe:5e5,param:12e5},{bwe:8e5,param:25e5},{bwe:12e5,param:4e6}],nA=[{bwe:2e5,param:240},{bwe:3e5,param:405},{bwe:5e5,param:920},{bwe:9e5,param:2040}],limitParamByBwe=(g,f,S)=>{for(const v of S)if(f<v.bwe)return Math.min(g,v.param);return g},limitStreamMaxBitrate=(g,f,S=iA)=>limitParamByBwe(g,f,S),limitStreamMaxResolution=(g,f,S=nA)=>limitParamByBwe(g,f,S),rA=class extends Ht{constructor(g,f,S){super(f),this.configProvider=g,this.logger=f,this.layoutsNumber=S,this.totalBandwidth=tA,this.totalBandwidthMax=0,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),this.outputLayouts=null,super.dispose()}setAvailableBandwidth(g){this.storeAvailableBandwidth(g),this.inputLayouts?(this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.debug("Layouts are not set. Skip update")}setLayouts(g,f){this.storeAvailableBandwidth(f),g.length===this.layoutsNumber?(this.logger.safe.debug(`Set layouts: ${JSON.stringify(g)}`),this.inputLayouts=this.getPrioritizedLayouts(g),this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.warn(`Incorrect number of layouts! ${JSON.stringify(g)}, expected ${this.layoutsNumber}`)}getLayouts(){return this.inputLayouts}getPrioritizedLayouts(g){return g}checkForChangesAndNotify(){const g=this.getLayouts();deepEqual(this.outputLayouts,g)?this.logger.safe.debug("Layout has not changed, skip update"):(this.outputLayouts=g.slice(),this.event("onLayoutsChanged").raise())}storeAvailableBandwidth(g){this.logger.safe.debug(`Set available bandwidth: ${g}`),this.totalBandwidth=g,this.totalBandwidthMax=Math.max(this.totalBandwidthMax,this.totalBandwidth)}},sA=class extends rA{constructor(g,f){super(g,f,2),this.resolutionManager=new eA(this.logger.createChild("BWEControlledResolutionManager"))}getLayouts(){return this.hiFiLayout?[this.loFiLayout,this.hiFiLayout]:[this.loFiLayout]}dispose(){super.dispose(),this.resolutionManager=null}getHighLayoutBandwidth(g){const f=this.inputLayouts?.[0].maxBr||0,S=Math.max(g-f,0);this.logger.safe.debug(`Setting available bandwidth for layouts. High: ${S}, low: ${f||"not set"}, total: ${g}`);const v=this.configProvider.config.specCompliantSimulcast?.allowedBweOvershootRatio||1;return Math.floor(S*v)}recalculateLayouts(){const g=this.hiFiLayout,f=this.getHighLayoutBandwidth(this.totalBandwidth);this.resolutionManager.setAvailableBandwidth(f),this.resolutionManager.setMaxFrameSize(this.inputLayouts[1].maxFs),this.loFiLayout=this.getMinimalLayoutParams(this.inputLayouts),this.hiFiLayout=this.getHighLayoutParams(this.inputLayouts,f,this.loFiLayout),this.loFiLayout=this.adjustLowLayoutBasedOnHighLayout(this.hiFiLayout,this.loFiLayout,g)}adjustLowLayoutBasedOnHighLayout(g,f,S){return this.configProvider.config.useMediaQualityControllerForceKeyFrame&&!g&&S&&(this.logger.safe.debug("Forcing kayframe on low layout due to disabling high layout"),f.keyframe=!0),g?(f.maxBr===g.maxBr&&f.maxBr--,f):f}getPrioritizedLayouts(g){return g.sort(((g,f)=>g.maxFs-f.maxFs?g.maxFs-f.maxFs:g.maxFps-f.maxFps))}getHighLayoutParams(g,f,S){const v=g[1];if(v.maxBr<=f)return this.logger.safe.debug(`High layout bandwidth suits requested caps. Applying as-is: ${JSON.stringify(v)}`),v;const C={...g[1],maxFs:this.resolutionManager.getFrameSize(),maxBr:Math.min(f,g[1].maxBr),maxFps:g[1].maxFps},_=C.maxBr<S.maxBr||C.maxFs<S.maxFs||C.maxFs===S.maxFs&&C.maxFps<=S.maxFps,T=`Potential high layout: ${JSON.stringify(C)}`;return!this.hiFiLayout&&_?(this.logger.safe.debug(`High layout is already disabled. Do nothing. ${T}`),null):this.hiFiLayout&&_?(this.logger.safe.debug(`High layout gets disabled. ${T}`),null):(this.hiFiLayout&&deepEqual(C,this.hiFiLayout)?this.logger.safe.debug(`High layout has not been changed. Do nothing. ${T}`):this.hiFiLayout?this.logger.safe.debug(`High layout updated. ${T}`):this.logger.safe.debug(`High layout enabled. ${T}`),C)}getMinimalLayoutParams(g){const f=Math.min(g[0].maxBr,g[1].maxBr),S=this.configProvider.config.specCompliantSimulcast.maxBrControlEnabled?limitStreamMaxBitrate(f,this.totalBandwidth,this.configProvider.config.specCompliantSimulcast.bitrateToBweTable):f;return{...g[0],maxBr:S,maxFps:Math.min(g[0].maxFps,g[1].maxFps),maxFs:Math.min(g[0].maxFs,g[1].maxFs)}}},aA=class extends rA{constructor(g,f,S){super(f,S,1),this.couldLimitFs=g}getLayouts(){return[this.layout]}recalculateLayouts(){let g=this.inputLayouts[0].maxFs;if(this.configProvider.config.specCompliantSimulcast.allowResLimit&&this.couldLimitFs&&this.totalBandwidthMax){const f=this.configProvider.config.specCompliantSimulcast.fsToBweTable;g=limitStreamMaxResolution(this.inputLayouts[0].maxFs,this.totalBandwidthMax,f)}const f=this.configProvider.config.specCompliantSimulcast.bitrateToBweTable,S=limitStreamMaxBitrate(this.inputLayouts[0].maxBr,this.totalBandwidth,f);this.layout={...this.inputLayouts[0],maxFs:g,maxBr:S}}},oA=class extends Ht{constructor(g){super(g),this.logger=g,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),super.dispose()}setAvailableBandwidth(g){this.logger.safe.debug(`Available bandwidth updated ${g}`)}setLayouts(g,f){this.layouts=g,this.setAvailableBandwidth(f)}getLayouts(){return this.layouts}},compareQuality=(g,f)=>g.maxFs===f.maxFs?g.maxFps===f.maxFps?g.maxBr-f.maxBr:g.maxFps-f.maxFps:g.maxFs-f.maxFs,compareMBPR=(g,f)=>g.maxFs===f.maxFs?g.maxFps-f.maxFps:g.maxFs-f.maxFs,lA=class extends Ht{constructor(g,f,S){super(S),this.settings=g,this.configProvider=f,this.logger=S,this.totalBandwidthMax=0,this.totalBandwidth=tA,this.inputLayouts=null,this.outputLayouts=null,this.maxOutputLayers=0,this.ladder=[],this.settings.ladder?this.ladder.push(...this.settings.ladder):this.ladder.push(...ei.Send.getResolutions())}dispose(){this.logger.safe.debug("Disposed"),super.dispose()}setAvailableBandwidth(g){this.updateAvailableBandwidth(g),this.update()}setLayouts(g,f){this.inputLayouts=g,this.updateAvailableBandwidth(f),this.update()}getLayouts(){return this.outputLayouts??[]}updateAvailableBandwidth(g){this.totalBandwidth!==Math.max(1,g)&&(this.logger.safe.debug(`Available bandwidth updated ${g}`),this.totalBandwidth=Math.max(1,g),this.totalBandwidthMax=Math.max(this.totalBandwidthMax,this.totalBandwidth))}debug(g,f,...S){let v;const format=g=>({FS:g.maxFs,FPS:g.maxFps,BR:g.maxBr,KF:g.keyframe?"1":"0",id:`rid:${g.rid}`??`0x${g.ssrc.toString(16).padStart(8,"0")}`});v=Array.isArray(f)?f.map(format):format(f),this.logger.safe.info(`${g}: <${S.map((g=>JSON.stringify(g))).join("><")}> ${JSON.stringify(v)}`)}update(){const g=this.settings.allowedOvershoot||1,f=this.adjustLayout(this.inputLayouts,this.totalBandwidth*g);if(deepEqual(this.outputLayouts,f))this.logger.safe.debug("Layout has not changed, skip update");else{if(this.settings.allowLayerBitrateOverlap&&f.length&&f.length<this.inputLayouts.length&&(this.setMinimumQuality(f[0],this.inputLayouts),this.debug("SetMinimumQuality",f[0])),this.outputLayouts&&this.settings.forceKeyFrameWhenLayerIsRemoved&&this.outputLayouts.length>f.length)for(const g of f)this.logger.safe.debug(`Force key frame for rid:${g.rid}`),g.keyframe=!0;this.outputLayouts=f,this.maxOutputLayers=Math.max(this.maxOutputLayers,this.outputLayouts.length),this.event("onLayoutsChanged").raise()}}adjustLayout(g,f){const S=[];if(g.length){if(g=g.map((g=>Object.assign({},g))).sort(compareQuality),this.debug("OriginalLayout",g),this.settings.minFrameSizeForSimulcast?.length>1){const f=this.settings.minFrameSizeForSimulcast;3===g.length&&2===f?.length&&g[g.length-1].maxFs<f[1]&&this.debug("DisableLowResStream",g.pop())}if(this.settings.highPriorityLayoutMinFS&&g.length>1){g[g.length-1].maxFs>=this.settings.highPriorityLayoutMinFS&&this.settings.lowPriorityLayoutMaxFS?.length&&this.limitResolutionOnLowerSimulcastStreams(g)}for(;g.length>0&&f>0;){const v=g.shift();this.debug("Next",v,f),this.settings.allowLayerBitrateOverlap||this.setMinimumQuality(v,g);let C=f-v.maxBr;if(S.length>0){if(C<0&&this.degradeBitrateOrResolution(v,f)&&(this.debug("DegradeBitrateOrResolution",v),C=f-v.maxBr),C>=0){let g=!1;for(const f of S){if(g=compareMBPR(f,v)>=0,this.settings.allowLayerBitrateOverlap||v.maxBr<f.maxBr&&(g=!0),g){this.debug("Drop",v,S.length);break}}g||(S.push(v),this.debug("Accept",v,S.length))}}else S.push(v),this.debug("Accept",v,S.length);f=C}this.debug("AdjustedLayout",S,f)}if(1===S.length)if(this.settings.minSinglecastBitrate||this.settings.singlecastLadder){const g=Math.max(this.settings.minSinglecastBitrate??this.totalBandwidth,this.totalBandwidth);S[0].maxBr>g&&this.degradeBitrateOrResolution(S[0],g,this.settings.singlecastLadder)&&this.debug("DegradeSinglecast",S[0],g)}else{if(this.settings.limitMaxResolution&&this.maxOutputLayers<=1){const g=this.configProvider.config.specCompliantSimulcast?.fsToBweTable;S[0].maxFs=limitStreamMaxResolution(S[0].maxFs,this.totalBandwidthMax,g),this.debug("LimitMaxFS",S[0],this.totalBandwidthMax)}if(this.settings.limitMaxBitrate){const g=this.configProvider.config.specCompliantSimulcast?.bitrateToBweTable;S[0].maxBr=limitStreamMaxBitrate(S[0].maxBr,this.totalBandwidth,g),this.debug("LimitMaxBitrate",S[0],this.totalBandwidth)}}return S}limitResolutionOnLowerSimulcastStreams(g){const f=g.pop();if(1===g.length){const f=this.settings.lowPriorityLayoutMaxFS[0];this.degradeResolutionTo(g[0],f)&&this.debug("DegradeResolutionTo",g[0],0,f)}else{const f=[...this.settings.lowPriorityLayoutMaxFS];f.sort(),g.splice(Math.min(2,f.length));for(let S=0;S<g.length;++S)this.degradeResolutionTo(g[S],f[S])&&this.debug("DegradeResolutionTo",g[S],S,f[S])}g.push(f)}setMinimumQuality(g,f){for(const S of f)g.maxBr=Math.min(S.maxBr,g.maxBr),g.maxFs=Math.min(S.maxFs,g.maxFs),g.maxFps=Math.min(S.maxFps,g.maxFps),g.maxMbps=g.maxFs*g.maxFps}degradeResolutionTo(g,f){for(;g.maxFs>f;)if(!this.degradeResolution(g))return!1;return!0}degradeResolution(g){const f=this.mapLayoutToLadder(g);if(f>=this.ladder.length)return!1;if(f>0){const S=this.ladder[f-1];return g.maxBr=Math.min(g.maxBr,S.maxBitrate),g.maxMbps=S.fs*S.fps,g.maxFps=S.fps,g.maxFs=S.fs,!0}return!1}degradeBitrateOrResolution(g,f,S){S??(S=this.ladder);const v=this.mapLayoutToLadder(g,S);if(v>=S.length)return!1;if(f>=S[v].minBitrate)return g.maxBr=f,!0;let C=v;for(;C>0;){const v=S[--C];if(f>=v.minBitrate)return g.maxMbps=v.fs*v.fps,g.maxFps=v.fps,g.maxFs=v.fs,g.maxBr=Math.min(f,v.maxBitrate),!0}return!1}mapLayoutToLadder(g,f){let S=0;for(f??(f=this.ladder);S<f.length&&!(f[S].fs>=g.maxFs&&f[S].fps>=g.maxFps);)++S;return S}},cA=class extends Ht{constructor(g,f,S,v){super(v),this.supportSingleBwControl=g,this.firstTime=f,this.configProvider=S,this.logger=v,this.multiStream=!1,this.wasMultistream=!0,this.deferredOperation=new Zb((()=>this.updateStrategy()),this.configProvider.config.layoutControlTimeout,this.logger.createChild("DeferredOperation")),this.simulcastStrategySettings=void 0,this.wasMultistream=!1,this.createStrategy(this.multiStream,this.firstTime)}configure(g){const f=this.isMultiStream(g);this.multiStream!==f&&(this.multiStream=f,this.simulcastStrategySettings||this.deferredOperation.invoke(this.multiStream&&!this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled))}onFeaturesChanged(g){const f={},S=this.configProvider.config.specCompliantSimulcast;let v=!1;g.hasServerSupport(0)&&(v=!0),g.hasClientSupport(2)&&this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy&&(v=!0),g.hasClientSupport(3)&&this.configProvider.config.broadcastMode?.prioritizeLayoutOnClient&&(v=!0),f.limitMaxBitrate=S?.maxBrControlEnabled,f.limitMaxResolution=S?.allowResLimit,f.allowedOvershoot=S?.allowedBweOvershootRatio,f.forceKeyFrameWhenLayerIsRemoved=this.configProvider.config.useMediaQualityControllerForceKeyFrame,v&&f.limitMaxResolution&&(f.limitMaxResolution=this.firstTime&&!this.wasMultistream),g.hasClientSupport(2)&&(g.hasClientSupport(1)||(f.highPriorityLayoutMinFS=this.configProvider.config.video1080p?.software?.highPriorityLayoutMinFS,f.lowPriorityLayoutMaxFS=this.configProvider.config.video1080p?.software?.lowPriorityLayoutMaxFS),f.minSinglecastBitrate=this.configProvider.config.video1080p?.minSinglecastBitrate,this.configProvider.config.video1080p?.singlecastLayoutLadder&&(f.singlecastLadder=createResolutionTable(this.configProvider.config.video1080p.singlecastLayoutLadder))),g.hasClientSupport(3)&&(f.highPriorityLayoutMinFS=this.configProvider.config.broadcastMode?.priorityLayoutMinFS,f.lowPriorityLayoutMaxFS=this.configProvider.config.broadcastMode?.lowPriorityLayoutMaxFS),g.hasServerSupport(0)&&(f.minSinglecastBitrate=f.minSinglecastBitrate??S?.minSinglecastBitrate,f.allowLayerBitrateOverlap=S?.allowLayerBitrateOverlap,S?.singlecastLadder&&(f.singlecastLadder=f.singlecastLadder??createResolutionTable(S?.singlecastLadder)),S.dropLowResolutionHigherStreams&&(f.minFrameSizeForSimulcast=S.video?.minFsForSimulcast)),!!this.simulcastStrategySettings===v&&deepEqual(f,this.simulcastStrategySettings)||(v?(this.logger.safe.info(`[SLCS] Configure [${this.simulcastStrategySettings?"existing":"initial"}][${this.wasMultistream}]: ${JSON.stringify(f)}`),this.simulcastStrategySettings=f):(this.simulcastStrategySettings&&this.logger.safe.info("[SLCS] Disable"),this.simulcastStrategySettings=void 0),this.deferredOperation.invoke(!1))}setLayouts(g,f){deepEqual(this.latestLayouts,g)&&this.latestBandwidth===f?this.logger.safe.debug("Layouts and bandwidth are not changed. Skipping update"):(this.latestLayouts=g,this.latestBandwidth=f,this.strategy.setLayouts(this.latestLayouts,f))}setAvailableBandwidth(g){this.latestBandwidth!==g?(this.strategy.setAvailableBandwidth(g),this.latestBandwidth=g):this.logger.safe.debug("Bandwidth is not changed. Skipping update")}getLayouts(){return this.strategy.getLayouts()}dispose(){this.strategy.dispose(),this.strategy=null,this.deferredOperation.dispose(),this.deferredOperation=null,super.dispose()}updateStrategy(){this.strategy.dispose(),this.createStrategy(this.multiStream),this.latestLayouts&&this.strategy.setLayouts(this.latestLayouts,this.latestBandwidth)}isMultiStream(g){return g>1}createStrategy(g,f=!1){this.strategy=this.getNewStrategy(g,f),this.strategy.on("onLayoutsChanged",(()=>{this.wasMultistream=this.wasMultistream||this.isMultiStream(this.strategy.getLayouts().length),this.event("onLayoutsChanged").raise()}))}getNewStrategy(g,f){return this.simulcastStrategySettings?new lA(this.simulcastStrategySettings,this.configProvider,this.logger.createChild("SimulcastLayoutControlStrategy")):g?new sA(this.configProvider,this.logger.createChild("BWEControlledStrategy")):this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled&&this.supportSingleBwControl?new aA(f,this.configProvider,this.logger.createChild("BWEControlledStrategySingle")):new oA(this.logger.createChild("NoControlStrategy"))}},dA=class extends Ht{constructor(g,f,S){super(f),this.configProvider=g,this.logger=f,this.videoFeatures=S,this.bandwidthAllocator=null,this.sendBandwidthCalculator=new Cb(this.configProvider,this.logger.createChild("SendBandwidthCalculator")),this.layoutProviders=new Map,this.hadLayoutProvider=new Set,this.useNewBandwidthAllocator=!1,this.highestVideoMaxFsWithSharingEnabled=0,this.bandwidthAllocator=createBandwidthAllocatorPerMediaType(this.logger,this.configProvider),this.sendBandwidthCalculator.on("onSendBandwidthChanged",(g=>this.onAvailableBandwidthChanged(g))),this.configProvider.config.sendBandwidthSeedValue&&this.bandwidthAllocator.setAvailableBandwidth(this.configProvider.config.sendBandwidthSeedValue),this.useVideoFeatures("Video")&&this.videoFeatures.on("onVideoFeaturesChanged",(g=>{if(this.useVideoFeatures(g.mediaType)){const f=this.layoutProviders.get(g.mediaType);f&&f.onFeaturesChanged(g)}if(!this.useNewBandwidthAllocator&&this.configProvider.config.bandwidthAllocatorV2.enableAllocator){let f=!1;g.hasServerSupport(0)&&(f=!0),g.hasClientSupport(2)&&this.configProvider.config.video1080p?.useNewBandwidthAllocator&&(f=!0),f&&this.switchBandwidthAllocator()}}))}dispose(){this.bandwidthAllocator=null,this.layoutProviders.forEach((g=>g.dispose())),this.layoutProviders.clear(),this.layoutProviders=null,super.dispose()}addReceiver(g,f){this.logger.safe.debug(`Set receiver max capabilities for ${g}: ${JSON.stringify(f)}`),this.configureProviders(g,f.length);const S=f.map((g=>g.maxBr)).reduce(((g,f)=>g+f));if(this.useNewBandwidthAllocator&&"Video"===g&&this.layoutProviders.has("ScreenShare")&&this.configProvider.config.bandwidthAllocatorV2.enableDynamicVideoLadder){const g=Math.max(...f.map((g=>g.maxFs)));g>this.highestVideoMaxFsWithSharingEnabled&&(this.highestVideoMaxFsWithSharingEnabled=g,this.bandwidthAllocator.setLadder("Video",getVideoBandwidthLadder(this.configProvider,g)))}this.bandwidthAllocator.addReceiverCapability(g,S);const v=this.bandwidthAllocator.getLayouts();this.layoutProviders.get(g).setLayouts(f,v[g]),this.updateBandwidthDistribution()}removeReceiver(g){this.logger.safe.debug(`Removing receiver for ${g}`),this.layoutProviders.get(g)?.dispose(),this.layoutProviders.delete(g),this.highestVideoMaxFsWithSharingEnabled=0,this.bandwidthAllocator.removeReceiver(g),this.updateBandwidthDistribution()}getLayouts(g){return this.layoutProviders.get(g).getLayouts()}onStatisticsChanged(g){this.sendBandwidthCalculator.onBandwidthChanged(g.estimatedSendBandwidth)}onDiagnosticUpdated(g){g.video?.send?.length&&g.video?.send[0]&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Estimating send bandwidth"),this.sendBandwidthCalculator.onBandwidthChanged(calculateEstimatedSendBandwidth(g.video.send[0],this.configProvider)))}useVideoFeatures(g){return"Video"===g&&(!!this.configProvider.config.specCompliantSimulcast?.enableSimulcastLayoutControlStrategy||!!this.configProvider.config.broadcastMode?.prioritizeLayoutOnClient||!!this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy)}switchBandwidthAllocator(){const g=createBandwidthAllocatorV2(this.logger,this.configProvider);g.setAvailableBandwidth(this.bandwidthAllocator.getAvailableBandwidth());const f=this.bandwidthAllocator.getReceiverCapabilities();for(const S of Object.keys(f))g.addReceiverCapability(S,f[S]);this.useNewBandwidthAllocator=!0,this.bandwidthAllocator=g,this.updateBandwidthDistribution()}configureProviders(g,f){if(!this.layoutProviders.has(g)){const f=this.createProvider(g);this.layoutProviders.set(g,f)}this.useVideoFeatures(g)&&f>2&&this.videoFeatures.get(g).toggleServer(0,!0),this.layoutProviders.get(g).configure(f)}createProvider(g){const f=new cA("Video"===g,!this.hadLayoutProvider.has(g),this.configProvider,this.logger.createChild(`LG:${g}`));return f.on("onLayoutsChanged",(()=>{const S=f.getLayouts();this.logger.safe.debug(`New layouts generated: ${JSON.stringify(S)}`),this.event("onLayoutsUpdated").raise(g)})),this.hadLayoutProvider.add(g),this.useVideoFeatures(g)&&f.onFeaturesChanged(this.videoFeatures.get(g)),f}onAvailableBandwidthChanged(g){this.bandwidthAllocator.setAvailableBandwidth(g),this.updateBandwidthDistribution()}updateBandwidthDistribution(){const g=this.bandwidthAllocator.getLayouts();for(const[f,S]of Object.entries(g))this.layoutProviders.get(f)?.setAvailableBandwidth(S);this.configProvider.config.mediaControlPlaneConfig?.enableSendBandwidthNotificationsEnabled&&this.event("onBandwidthAllocationUpdated").raise(g)}},hA=M;function mergeCapabilitiesWithCallConstraints(g,f,S){if("Video"!==g||!S)return S;const{maxBitrate:v,maxResolution:C,maxFramerate:_}=f.config.outgoingVideoLimit??{},T=v??1/0;let I=C?convertResolutionToFramesize(C):1/0,b=_??1/0;return f.config.sendVideoCapabilityManager?.isEnabled&&(I=1/0,b=1/0),T===1/0&&I===1/0&&b===1/0?S:S.map((g=>({...g,maxFs:getMinDefined(g.maxFs,I),maxBr:getMinDefined(g.maxBr,T),maxFps:getMinDefined(g.maxFps,b)})))}var uA=new Set(["maintain-framerate","maintain-resolution","balanced"]),gA=class{constructor(g,f){this.configProvider=g,this.logger=f}async setActive(g,f){const S=this.getSenderParameters(g);return S.encodings[0].active=f,this.setSenderParameters(g,S,"setActive")}getScaleFactor(g,f){if(!f.width||!f.height)return this.logger.safe.warn("Stream resolution is not set yet. Cannot calculate scale factor. Returning 1"),1;const S=ei.Send.getResolutionByFs(g);let v=Math.min(f.width,f.height)/S.height;return this.logger.safe.debug(`Scale factor is taken from resolution: ${JSON.stringify(f)} and new Fs: ${g} as ${v}`),v<1&&(this.logger.safe.warn("Scale factor cannot be less than 1! Limiting to 1"),v=1),v}async generateKeyFrameIfNeeded(g,f){if(!f.track)return void this.logger.safe.info("No track attached. Skipping");const S=this.getSenderParameters(f),v=g.filter((g=>g.keyframe)).map((g=>g.rid));if(0!==v.length&&S.encodings.some((g=>g.active)))if(this.configProvider.config.useKeyFrameApi){const g=[];S.encodings.forEach((f=>{!f.active||f.rid&&!v.includes(f.rid)?g.push({keyFrame:!1}):g.push({keyFrame:!0})})),await this.setSenderParameters(f,S,"generateKeyFrameAPI",!0,{encodingOptions:g})}else{const g=S.encodings.map(((g,f)=>g.active?g.rid&&!v.includes(g.rid)?null:{idx:f,factor:g.scaleResolutionDownBy||1}:null)).filter((g=>g));for(const f of g)S.encodings[f.idx].scaleResolutionDownBy=f.factor*this.configProvider.config.forceKeyFrameV2ScaleFactor;this.logger.safe.debug(`Restoring keyframe starting. Update scaleResolutionDownBy for encodings: ${JSON.stringify(S.encodings)}`),await this.setSenderParameters(f,S,"generateKeyFrameStart");const C=this.getSenderParameters(f);for(const f of g)C.encodings[f.idx].scaleResolutionDownBy=f.factor;await this.setSenderParameters(f,C,"generateKeyFrameEnd"),this.logger.safe.debug(`Restoring keyframe completed. Set scaleResolutionDownBy back for encodings: ${JSON.stringify(C.encodings)}`)}else this.logger.safe.info("No keyframes needed. Skipping")}getSenderParameters(g){const f=g.getParameters();if(f.encodings?.length||(f.encodings=[{}]),this.configProvider.config.reuseLastSetParameters&&this.lastSetEncodings){this.logger.safe.info(`Override returned encodings ${JSON.stringify(f.encodings)}`);const g=(0,hA.merge)((0,hA.cloneDeep)(f.encodings),this.lastSetEncodings);this.logger.safe.info(`Overrided encodings ${JSON.stringify(g)}`),f.encodings=g}return f}async setSenderParameters(g,f,S,v=!0,C){try{await g.setParameters(f,C),this.logger.safe.info(`${S}: Parameters applied for sender: encodings: ${JSON.stringify(f.encodings)}, degradationPreference: ${f.degradationPreference}`),this.lastSetEncodings=f.encodings}catch(g){const C=`${S}: setParameters failed. Parameters: ${JSON.stringify(f.encodings)}, error:  ${stringifyObject(g)}`;if(this.logger.safe.error(C),v)throw new Error(C)}}getAdjustedBitrate(g,f){let S=g||0;const{maxBitrate:v}=ei.Send.getBitrateForResolution(f.width,f.height);return S=Math.min(S||v,v),S}async updateStreamParameters(g,f,S){if(g.getCurrentConstraints().withEffect&&f?.maxFs){const S=ei.Send.getResolutionByFs(f.maxFs),v={width:S.width,height:S.height};this.logger.safe.info(`Applying video constrains for video effetcs ${JSON.stringify(v)}`),g.resetEffectsOutputConstraints(v)}S&&await g.applyCapabilities(f)}augmentDegradationPreference(g,f){uA.has(f)&&g.degradationPreference!==f&&(g.degradationPreference=f,this.logger.safe.info(`degradationPreference changed to: ${g.degradationPreference}`))}async setEncodingsActiveState(g,f,S){this.logger.safe.info(S);const v=this.getSenderParameters(g);return v.encodings.forEach((g=>g.active=f)),this.setSenderParameters(g,v,S)}},pA=class{constructor(g,f,S){this.config=g,this.configProvider=f,this.logger=S,this.capabilitiesHelper=new gA(this.configProvider,this.logger)}get streamResolution(){return this.stream?.getCurrentConstraints().withEffect?this._streamResolutionFromCapabilities:this._streamResolution}setSender(g){this.rtpSender=g}updateStream(g){this.stream=g,this._streamResolution=g.getResolution(),this._streamResolutionFromCapabilities=this._streamResolution}setActive(g){return this.capabilitiesHelper.setActive(this.rtpSender,g)}async setCapabilities(g){(0,hA.isEqual)(this.currentCapabilities,g)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(g)}. Do nothing`):(this.defaultCapabilities=(0,hA.cloneDeep)(g),this.currentCapabilities=(0,hA.cloneDeep)(g),await this.applyLastCapabilities(),await this.capabilitiesHelper.generateKeyFrameIfNeeded(g,this.rtpSender))}async updateStreamQualityParams(g,f,S){if(g&&!(0,hA.isEqual)(this.streamResolution,g))return this._streamResolution=g,this._streamResolutionFromCapabilities=g,this.logger.safe.info(`Stream params changed: ${JSON.stringify(g)}@${f}@${S} id: ${this.rtpSender.track?.id}`),this.applyLastCapabilities();this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(g)}@${f}`)}async startSender(){return shouldDisableVideoSendersTroughSetParams(this.configProvider,this.stream)||shouldDisableAudioSendersTroughSetParams(this.configProvider,this.stream)?this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!0,"Starting senders."):void 0}async stopSender(){return this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!1,"Stopping senders.")}async applyLastCapabilities(){if(!this.currentCapabilities)return void this.logger.safe.info("Capabilities are not set. Do nothing");this.currentCapabilities=mergeCapabilitiesWithCallConstraints(this.stream.mediaType,this.configProvider,this.defaultCapabilities),await this.applyStreamCapabilities(this.currentCapabilities);const g=this.capabilitiesHelper.getSenderParameters(this.rtpSender),f=(0,hA.cloneDeep)(g);return this.currentCapabilities.forEach((f=>{const S=this.getEncondingIndexForRid(f.rid,g.encodings);this.updateEncodingsWithCaps(g.encodings[S],f)})),this.capabilitiesHelper.augmentDegradationPreference(g,this.configProvider.config.degradationPreference),this.updateActiveStates(g,this.currentCapabilities),this.logger.safe.info(`Encoding params new: ${JSON.stringify(g.encodings)}, old: ${JSON.stringify(f.encodings)}`),this.capabilitiesHelper.setSenderParameters(this.rtpSender,g,"applyCapabilities")}async applyCallConstraints(g){return this.logger.safe.info(`[${g}] Applying call constraints`),this.applyLastCapabilities()}async applyStreamCapabilities(g){if("Video"!==this.stream.mediaType||!g.length)return;let f=g[0];for(const S of g)f.maxFs<S.maxFs&&(f=S);if(g.length>1){const S=this.configProvider.config.specCompliantSimulcast.video.minFsForSimulcast;if(f=(0,hA.cloneDeep)(f),S?.length>0)for(let v=0;v<S.length;++v)g.length>v+1&&(f.maxFs=Math.max(S[v]||0,f.maxFs),f.maxFps=Math.max(...g.map((g=>g.maxFps))))}const S=this.configProvider.config.specCompliantSimulcast.video.useApplyConstraints;await this.capabilitiesHelper.updateStreamParameters(this.stream,f,S),S&&(this._streamResolution=this.stream.getResolution())}getEncondingIndexForRid(g,f){if(!g)return this.logger.safe.error("No RID found in incoming params. Returning index 0"),0;const S=f.findIndex((f=>f.rid===g));return S<0||S-1>this.config.layerScaleFactors.length?(this.logger.safe.error("Incorrect index deduced from requested RID. Returning index 0"),0):S}updateEncodingsWithCaps(g,f){g?(g.maxBitrate=f.maxBr,g.scaleResolutionDownBy=this.capabilitiesHelper.getScaleFactor(f.maxFs,this.streamResolution),g.maxFramerate=f.maxFps,this.config.defaultScalabilityMode&&(g.scalabilityMode=this.config.defaultScalabilityMode)):this.logger.safe.error(`SenderParams does not exist for caps: ${JSON.stringify(f)}`)}updateActiveStates(g,f){const S=g.encodings.map((g=>g.rid)),v=S.filter((g=>f.some((f=>g===f.rid)))),C=subtractFrom(S,v);v.forEach((f=>this.changeEncodingState(g,f,!0))),C.forEach((f=>this.changeEncodingState(g,f,!1)))}changeEncodingState(g,f,S){const v=g.encodings.find((g=>g.rid===f));v?v.active=S:this.logger.safe.error(`Encoding not found for RID: ${f}`)}},mA=class{constructor(g,f){this.configProvider=g,this.logger=f,this.capabilitiesHelper=new gA(this.configProvider,this.logger)}get params(){return this.currentCapabilities?.find((g=>"1"===g.rid))??this.currentCapabilities?.[0]}get useSetParameter(){if("ScreenShare"===this.stream.mediaType){if(this.configProvider.config.useSetParametersToApplySSCapabilities)return this.logger.safe.info("useSetParametersToApplySSCapabilities: true"),!0;if(!1===this.configProvider.config.useSetParametersToApplySSCapabilities)return this.logger.safe.info("useSetParametersToApplySSCapabilities: false"),!1}return!!this.configProvider.config.useSetParametersToApplyCapabilities&&(this.logger.safe.info("useSetParametersToApplyCapabilities"),!0)}async applyCallConstraints(g){return this.logger.safe.info(`[${g}] Applying call constraints`),this.applyLastCapabilities(3)}setSender(g){this.rtpSender=g}updateStream(g){this.stream=g,this.streamResolution=g.getResolution()}setActive(g){return this.capabilitiesHelper.setActive(this.rtpSender,g)}async setCapabilities(g){(0,hA.isEqual)(this.currentCapabilities,g)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(g)}. Do nothing`):1===g.length?(this.defaultCapabilities=(0,hA.cloneDeep)(g),this.currentCapabilities=(0,hA.cloneDeep)(g),await this.applyLastCapabilities(0),await this.capabilitiesHelper.generateKeyFrameIfNeeded(g,this.rtpSender)):this.logger.safe.error("Incorrect number of sender params!")}async updateStreamQualityParams(g,f,S){if(g&&!(0,hA.isEqual)(this.streamResolution,g))return this.streamResolution=g,this.logger.safe.debug(`Stream params changed: ${JSON.stringify(g)}@${f}`),this.applyLastCapabilities(S);this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(g)}@${f}`)}async startSender(g){this.logger.safe.info(`Replace sender with track: ${g.id}`),await this.rtpSender.replaceTrack(g),this.logger.safe.info("replaceTrack completed"),shouldDisableVideoSendersTroughSetParams(this.configProvider,this.stream)&&await this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!0,"Starting senders."),shouldDisableAudioSendersTroughSetParams(this.configProvider,this.stream)&&await this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!0,"Starting senders."),this.configProvider.config.applySenderParamsBeforeStart&&this.currentCapabilities&&await this.capabilitiesHelper.generateKeyFrameIfNeeded(this.currentCapabilities,this.rtpSender)}async stopSender(){return shouldDisableVideoSendersTroughSetParams(this.configProvider,this.stream)||shouldDisableAudioSendersTroughSetParams(this.configProvider,this.stream)?this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!1,"Stopping senders."):(this.logger.safe.info("Replace sender with track: null"),await this.rtpSender.replaceTrack(null),void this.logger.safe.info("replaceTrack completed"))}async applyLastCapabilities(g){this.currentCapabilities?(this.currentCapabilities=mergeCapabilitiesWithCallConstraints(this.stream.mediaType,this.configProvider,this.defaultCapabilities),this.logger.safe.info(`Applying params: ${JSON.stringify(this.params)}`),await this.applyParams(this.params,g),await this.applyBitrate(this.params.maxBr)):this.logger.safe.debug("Capabilities are not yet set, nothing to apply")}applyBitrate(g){let f=g||0;return"Video"===this.stream.mediaType&&(f=this.capabilitiesHelper.getAdjustedBitrate(f,this.streamResolution)),this.setSingleEncodingParameters(this.rtpSender,{maxBitrate:f},"applyBitrate",!1)}async applyParams(g,f){if(this.useSetParameter)return this.setSingleEncodingParameters(this.rtpSender,{scaleResolutionDownBy:this.capabilitiesHelper.getScaleFactor(g.maxFs,this.streamResolution),maxFramerate:g.maxFps},"applyParams");2!==f&&await this.capabilitiesHelper.updateStreamParameters(this.stream,g,!0)}async setSingleEncodingParameters(g,f,S,v=!0){const C=this.capabilitiesHelper.getSenderParameters(g);return(0,hA.merge)(C.encodings[0],f),0===C.encodings[0].maxBitrate&&(this.configProvider.config.setParametersMaxBitrateUndefined?C.encodings[0].maxBitrate=void 0:delete C.encodings[0].maxBitrate),this.capabilitiesHelper.augmentDegradationPreference(C,this.configProvider.config.degradationPreference),this.capabilitiesHelper.setSenderParameters(this.rtpSender,C,S,v)}},fA=class{constructor(g,f,S){this.transitionStates=g,this.logger=S,this.stateCurrent=f}get state(){return this.stateCurrent}isDestinationStateValid(g){return this.transitionStates[this.stateCurrent].indexOf(g)>-1}setState(g){return this.isDestinationStateValid(g)?(this.stateCurrent=g,!0):(g!==this.stateCurrent&&this.logger.safe.info(`Invalid state transition ${this.stateCurrent} -> ${g}`),!1)}isCurrentStateMatchedWith(g){return this.stateCurrent===g||(this.logger.safe.info(`State does not match. Current: ${this.stateCurrent} required: ${g}`),!1)}},SA=class extends Ht{constructor(g,f){super(g),this.logger=g,this.configProvider=f,this.audioContext=new Xs.window.AudioContext(this.configProvider.config.audioSharingContextOptions),this.destination=this.audioContext.createMediaStreamDestination(),this.streamNodeMap=new Map,this.logger.safe.info(`Destination stream: ${this.destination.stream.id}, track: ${this.getDestinationTrack().id}`),this.subscribeOnMediaTrackEvents(this.getDestinationTrack())}get numberOfStreams(){return this.streamNodeMap.size}addSourceStream(g){if(!g.rawStream)return;if(this.streamNodeMap.has(g.rawStream))return;const f=g.on("onStreamClientDisposing",(()=>{this.removeSourceStream(g.rawStream),f.dispose()}));this.logger.safe.info(`Add stream: ${g.rawStream.id}, track: ${getTrack(g.rawStream).id}`),this.addStream(g.rawStream,g.mediaType)}getDestinationTrack(){return getTrack(this.destination.stream)}dispose(){super.dispose(),this.unsubscribeFromMediaTrackEvents(this.getDestinationTrack());for(const g of this.streamNodeMap.keys())this.removeSourceStream(g);this.audioContext.close(),this.audioContext=null}addStream(g,f="Audio"){const S=this.audioContext.createMediaStreamSource(g);S.connect(this.destination),this.streamNodeMap.set(g,{mediaType:f,sourceNode:S})}removeSourceStream(g){const f=this.streamNodeMap.get(g);f&&(this.logger.safe.info(`Remove stream: ${g.id}, track: ${getTrack(g).id}`),f.sourceNode.disconnect(),this.streamNodeMap.delete(g))}subscribeOnMediaTrackEvents(g){g.onended=f=>{this.logger.safe.info(`Track ${g.id} ended: ${JSON.stringify(f)}`)},g.onmute=()=>{this.logger.safe.info(`Track ${g.id} muted`)},g.onunmute=()=>{this.logger.safe.info(`Track ${g.id} unmuted`)}}unsubscribeFromMediaTrackEvents(g){g.onended=null,g.onmute=null,g.onunmute=null}};function getTrack(g){return g.getAudioTracks()[0]}var vA=class extends Ht{constructor(g,f,S,v,C,_,T){super(),this.mediaConnection=g,this.contextStream=S,this.logger=v,this.configProvider=C,this.encStreamsManager=_,this.capabilitiesManager=T,this.isMuted=!1,this.isActiveInternal=!1,this.stream=f.clone("streamSender ctor"),this.subscribeOnStreamClientMuted(),this.capabilitiesManager.updateStream(this.stream)}get rawTrack(){return this.audioMixer?.getDestinationTrack()||this.stream.rawTrack}get trackId(){return this.rawTrack?.id}applyCallConstraints(g){return this.capabilitiesManager.applyCallConstraints(g)}async init(){this.sender=await this.createSender(),this.isActiveInternal=!0,this.addStreamTransforms(),this.capabilitiesManager.setSender(this.sender)}async start(){this.isActive()?this.logger.safe.info("Already active. Do nothing"):(this.logger.safe.info("Starting"),this.isActiveInternal=!0,await this.capabilitiesManager.startSender(this.rawTrack),this.logger.safe.info("Started"))}async stop(){this.isActive()?(this.logger.safe.info("Stopping"),this.isActiveInternal=!1,await this.capabilitiesManager.stopSender(),this.logger.safe.info("Stopped")):this.logger.safe.info("Already stopped. Do nothing")}async setCapabilities(g){this.configProvider.config.applySenderParamsBeforeStart||await this.start();try{await this.capabilitiesManager.setCapabilities(g)}catch(g){this.logger.safe.error(`Error setting capabilities: ${stringifyObject(g)}`)}await this.start()}updateStreamQualityParams(g,f,S){return this.capabilitiesManager.updateStreamQualityParams(g,f,S)}setMuted(g,f,S){this.isMuted=g,this.stream.setMuted(g,f),g&&this.audioMixer&&1!==this.audioMixer.numberOfStreams||this.audioMuteTransform?.mute(g),!this.configProvider.config.requestNewStreamOnUnmute||g||S||this.stream.isActive()||this.event("onNewStreamNeeded").raise()}async setHold(g,f){if(this.configProvider.config.holdSkipActivation)return;const S=!g;this.logger.safe.info(`[${f}] change isActive state to ${S}`);try{return this.capabilitiesManager.setActive(S)}catch(g){const v=this.configProvider.config.holdRetryActivationDelay;if(v>=0)return this.logger.safe.info(`[${f}] retrying after delay of ${v}`),await delay(v),this.logger.safe.info(`[${f}] change isActive state to ${S}, second attempt`),this.capabilitiesManager.setActive(S);throw g}}async setMainStream(g){return this.stream.dispose(),this.onStreamClientMutedSubscription?.dispose(),this.stream=g.clone("streamSender setMainStream"),this.stream.setMuted(this.isMuted),this.audioMixer?.addSourceStream(this.stream),this.isActive()&&(this.logger.safe.info(`Replace sender with track: ${this.rawTrack?.id}`),await this.sender.replaceTrack(this.rawTrack),this.logger.safe.info("Replace completed")),this.capabilitiesManager.updateStream(this.stream),this.subscribeOnStreamClientMuted(),this.capabilitiesManager.applyLastCapabilities(1)}async addAdditionalStream(g){if("Audio"===this.stream.mediaType){if(this.configProvider.config.postponeAudioMixerForAudioSharing&&this.setupAudioMixer(),this.audioMixer||this.logger.safe.error(`addAdditionalStream is called when audioMixer is not created. Main stream type is ${this.stream.mediaType}.`),this.audioMixer?.addSourceStream(g),this.audioMuteTransform?.mute(!1),this.configProvider.config.postponeAudioMixerForAudioSharing){if(!this.sender)return void this.logger.safe.error("Sender not created, cannot replace track");this.logger.safe.info(`addAdditionalStream replace sender with track: ${this.rawTrack?.id}`),await this.sender.replaceTrack(this.rawTrack),this.logger.safe.info("addAdditionalStream replace completed")}}else this.logger.safe.error("Not adding additional stream for non-audio stream")}dispose(){this.removeSender(),this.cleanUp()}async terminateAsync(){await this.removeSenderAsync(),this.cleanUp()}getActiveStreamIndexes(){return this.getSenderParameters().encodings.filter((g=>g.active)).map((g=>+g.rid))}isActive(){if(!this.sender)return this.isActiveInternal;if(shouldDisableVideoSendersTroughSetParams(this.configProvider,this.stream)||shouldDisableAudioSendersTroughSetParams(this.configProvider,this.stream)){return this.getSenderParameters().encodings[0].active}return this.isActiveInternal}removeSender(){this.logger.safe.info("Removing sender from pc");try{this.mediaConnection.removeSender(this.sender)}catch(g){this.logger.safe.warn(`Error removing sender: ${stringifyObject(g)}`)}}async removeSenderAsync(){this.logger.safe.info("Removing sender from pc");try{await this.mediaConnection.removeSenderAsync(this.sender)}catch(g){this.logger.safe.warn(`Error removing sender: ${stringifyObject(g)}`)}}async createSender(){return this.configProvider.config.postponeAudioMixerForAudioSharing||this.setupAudioMixer(),this.mediaConnection.createSender(this.rawTrack,this.contextStream,mediaTypeToModality(this.stream.mediaType))}addStreamTransforms(){const g=this.encStreamsManager.initTransformsCollection(this.sender,"Sender",this.stream.mediaType);g&&("Audio"===this.stream.mediaType?this.configProvider.config.useInsertableStreams?.audioExtendedMute&&(this.audioMuteTransform=new Ja(this.logger.createChild("SendAudioPayload")),g.addTransform(this.audioMuteTransform)):this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&g.addTransform(new Wa(this.logger.createChild(`SendStreamAnalyzer [${this.stream.mediaType}]`))))}setupAudioMixer(){this.configProvider.config.enableAudioSharing?"Audio"===this.stream.mediaType?this.configProvider.config.audioSharingMemoryLeakFix&&this.audioMixer?this.logger.safe.debug("Audio mixer already created, not creating new one"):(this.audioMixer=new SA(this.logger.createChild("AudioMixer"),this.configProvider),this.audioMixer.addSourceStream(this.stream)):this.logger.safe.error("Not setting up audio mixer for non-audio stream"):this.logger.safe.info("Audio sharing is disabled, not setting up audio mixer")}getSenderParameters(){const g=this.sender.getParameters();return g.encodings?.length||(g.encodings=[{}]),g}subscribeOnStreamClientMuted(){this.configProvider.config.recoverOnStreamUnmute&&(this.onStreamClientMutedSubscription=this.stream.on("onStreamClientMuted",(async(g,f)=>{f||await this.capabilitiesManager.applyLastCapabilities(1)})))}cleanUp(){super.dispose(),this.encStreamsManager.clearTransformsCollection(this.sender),this.sender=null,this.audioMixer?.dispose(),this.stream.dispose(),this.onStreamClientMutedSubscription?.dispose(),this.stream=null,this.isActiveInternal=!1}},CA=class _SimulcastStreamSender extends Ht{constructor(g,f,S,v,C,_,T,I,b,A,P){super(),this.mediaConnection=g,this.mainStream=f,this.contextStream=S,this.mediaType=v,this.serialQueue=C,this.logger=_,this.configProvider=T,this.isAlwaysActive=I,this.encStreamsManager=b,this.simulcastContext=A,this.sendVideoCapabilityManager=P,this.isMuted=!1,this.isHold=!1,this.previousParameters=[],this.state=new fA(_SimulcastStreamSender.transitionStates,"NotStarted",this.logger.createChild("state")),this.pendingStream=null,this.pendingParams=null,this.lastAppliedParams=null,this.subscribeOnQualityUpdates(this.mainStream),P&&this.sendVideoCapabilityManager.on("onCapabilitiesChanged",(g=>{this.event("onMaxVideoSendCapabilitiesChanged").raise(g),this.configProvider.config.applyMaxCapabilitiesToSenderParamsDirectly&&this.lastAppliedParams&&!this.pendingParams&&this.updateParameters(this.lastAppliedParams)}))}async start(){this.state.setState("Started")&&(this.sender=new vA(this.mediaConnection,this.mainStream,this.contextStream,this.logger.createChild("Sender"),this.configProvider,this.encStreamsManager,this.getCapabilitiesManager(this.simulcastContext)),await this.sender.init(),this.notifyMaxVideoSendCapabilitiesChanged(),this.configProvider.config.deactiveAudioSender&&"Audio"===this.mediaType&&(this.logger.safe.info("start(): Deactivating audio sender"),await this.sender.stop()),this.sender.on("onNewStreamNeeded",(()=>{this.logger.safe.info("onNewStreamNeeded"),this.event("onNewStreamNeeded").raise()})))}async activate(){if(this.state.setState("Active")&&(this.pendingStream&&(this.logger.safe.info("activate(): updating from pendingStream"),await this.updateStreamInternal(this.pendingStream),this.pendingStream=null),this.isAlwaysActive&&!this.isMuted&&"Audio"===this.mediaType&&(this.logger.safe.info("activate(): starting sender"),await this.sender.start()),this.isAlwaysActive?(this.event("onSendersChanged").raise(this,!0),this.logger.safe.info("Sender set to always active")):await this.sender.stop(),this.configProvider.config.enableCachingFMTP&&this.pendingParams)){const updateParams=async()=>{this.configProvider.config.enableCachingFMTPDelay>0&&(this.logger.safe.info("Applying delay before applying pending parameters"),await delay(this.configProvider.config.enableCachingFMTPDelay)),this.logger.safe.info("Apply pending parameters");const g=this.updateParametersInternal(this.pendingParams);return this.pendingParams=null,g};this.configProvider.config.enableCachingFMTPAwait?(this.logger.safe.info("Apply pending parameters"),await updateParams()):(this.logger.safe.info("Apply pending parameters in background"),updateParams().catch((g=>this.logger.safe.error("Error applying pending parameters",g))))}}updateStream(g){return this.updateStreamInternal(g)}async addAdditionalStream(g){return this.sender.addAdditionalStream(g)}async updateParameters(g){if(this.state.isCurrentStateMatchedWith("Active"))return this.updateParametersInternal(g);this.configProvider.config.enableCachingFMTP?(this.logger.safe.info("Postpone params update until sender is activated"),this.pendingParams=g):this.logger.safe.warn("Ignore params update as sender is not activated")}async terminateAsync(){this.state.setState("Disposed")&&(this.logger.safe.info("Terminating async"),await this.sender.terminateAsync(),this.cleanUp())}dispose(){this.state.setState("Disposed")&&(this.logger.safe.info("Disposing"),this.sender.dispose(),this.cleanUp())}async setHold(g,f){if(this.isHold!==g)return this.logger.safe.info(`[${f}] Setting hold to: ${g}`),this.isHold=g,this.sender.setHold(g,f);this.logger.safe.info(`[${f}] Already in hold=${g} state`)}setMuted(g,f,S){this.logger.safe.info(`[${f}] Setting muted to: ${g}`),this.isMuted=g,this.sender.setMuted(this.isMuted,f,S),!this.isMuted&&"Audio"===this.mediaType&&this.state.isCurrentStateMatchedWith("Active")&&this.sender.start()}getActiveStreamIndexes(){return this.sender?this.sender.getActiveStreamIndexes():[]}getTrackInfo(){return{modality:mediaTypeToModality(this.mediaType),trackId:this.sender.trackId}}applyCallConstraints(g){return this.sendVideoCapabilityManager?.applyCallConstraints(g),this.sender.applyCallConstraints(g)}getCapabilitiesManager(g){return g?.shouldUseSimulcast()?new pA(g.config,this.configProvider,this.logger.createChild("SimCapMgrV2")):new mA(this.configProvider,this.logger.createChild("SnglCapMgrV2"))}async updateStreamInternal(g){return this.logger.info(`updateStreamInternal(): id: ${g.id}, parentId: ${g.parentId}), mediaType: ${this.mediaType}`),this.state.isCurrentStateMatchedWith("Active")?this.mainStream!==g?(this.logger.safe.debug(`Switching streams: ${this.mainStream.parentId}:${this.mainStream.id} -> ${g.parentId}:${g.id}`),this.unsubscribeFromQualityEvents(),this.mainStream.dispose(),this.mainStream=g,this.subscribeOnQualityUpdates(this.mainStream),this.notifyMaxVideoSendCapabilitiesChanged(),await this.sender.setMainStream(this.mainStream),this.logger.debug(`track info after stream update: ${JSON.stringify(this.getTrackInfo())}`),this.sender.updateStreamQualityParams(this.mainStream.getResolution(),this.mainStream.getFrameRate(),1)):void this.logger.safe.info("Stream has not been changed. Skipping update"):(this.logger.safe.info("Postponing stream update until sender is activated"),void this.setPendingStream(g))}async updateParametersInternal(g){if(this.configProvider.config.applyMaxCapabilitiesToSenderParamsDirectly){this.lastAppliedParams=g;const f=this.sendVideoCapabilityManager?.getCapabilities();f&&(g=g.map((g=>{const S={...g};return S.maxFs>f.maxFs&&(this.logger.safe.info(`Reducing SSRC:${S.ssrc} video FS from ${S.maxFs} to ${f.maxFs}`),S.maxFs=f.maxFs),S.maxFps>f.maxFps&&(this.logger.safe.info(`Reducing SSRC:${S.ssrc} video FPS from ${S.maxFps} to ${f.maxFps}`),S.maxFps=f.maxFps),S})))}await this.sender.setCapabilities(g),compareArraysBy(this.previousParameters,g,((g,f)=>g.ssrc===f.ssrc))||(this.previousParameters=g,this.event("onSendersChanged").raise(this,!0))}setPendingStream(g){this.pendingStream=g;const f=g.on("onStreamClientDisposing",(()=>{this.pendingStream===g&&(this.pendingStream=null,f.dispose())}))}subscribeOnQualityUpdates(g){this.sub=g.on("onStreamQualityChanged",((g,f,S,v)=>this.updateStreamQualityParams(f,S,v)))}updateStreamQualityParams(g,f,S){return S===lr.EffectQualityChangeReason.Performance&&this.notifyMaxVideoSendCapabilitiesChanged({resolution:g,fps:f}),this.sender.updateStreamQualityParams(g,f,2)}unsubscribeFromQualityEvents(){this.sub?.dispose(),this.sub=null}notifyMaxVideoSendCapabilitiesChanged(g){if(!["Video","ScreenShare"].includes(this.mediaType))return;const{width:f,height:S}=g?.resolution??this.mainStream.getResolution(),v=g?.fps??this.mainStream.getFrameRate();if(!f||!S||!v)return;const C=new Xt(f,S),_={maxFs:C.fs,maxMbps:C.fs*v,maxFps:v,maxWidth:C.width,maxHeight:C.height};this.logger.safe.info(`Capabilities for ${this.mediaType} stream: ${JSON.stringify(_)}`),this.sendVideoCapabilityManager?this.sendVideoCapabilityManager.manage(_,!g):this.event("onMaxVideoSendCapabilitiesChanged").raise(_)}cleanUp(){this.sendVideoCapabilityManager?.dispose(),this.sendVideoCapabilityManager=null,this.unsubscribeFromQualityEvents(),this.mainStream.dispose(),this.mainStream=null,this.pendingStream&&this.pendingStream.dispose(),this.pendingStream=null,this.sender=null,this.contextStream=null,this.event("onSendersChanged").raise(this,!1),super.dispose()}};CA.transitionStates={NotStarted:["Started","Disposed"],Started:["Active","Disposed"],Active:["NotStarted","Disposed"],Disposed:[]},__decorateClass([sequentialize()],CA.prototype,"start",1),__decorateClass([sequentialize()],CA.prototype,"activate",1),__decorateClass([sequentialize()],CA.prototype,"updateStream",1),__decorateClass([sequentialize()],CA.prototype,"addAdditionalStream",1),__decorateClass([sequentialize()],CA.prototype,"updateParameters",1),__decorateClass([sequentialize()],CA.prototype,"terminateAsync",1),__decorateClass([sequentialize()],CA.prototype,"setHold",1),__decorateClass([sequentialize()],CA.prototype,"updateStreamQualityParams",1);var yA=CA,EA=class{constructor(g){this.durationThreshold=g,this.signals={}}track(g,f){void 0===this.signals[g]&&(this.signals[g]={wasNotified:!1}),this.signals[g].currentTime=Jt(),!!this.signals[g].currentState!=!!f&&(this.signals[g].currentState=f,this.signals[g].lastChanged=this.signals[g].currentTime,this.signals[g].wasNotified=!1)}update(g){const f=[];for(const f of Object.keys(g))void 0===this.signals[f]&&(this.signals[f]={wasNotified:!1});for(const f of Object.keys(this.signals))this.track(f,g[f]);for(const g in this.signals){const S=this.signals[g];if(void 0!==S.currentState){if(S.wasNotified)continue;S.currentTime-S.lastChanged>=this.durationThreshold&&(S.wasNotified=!0,f.push(S.currentState))}}return f}},_A=class extends Ht{constructor(g,f){super(),this.logger=g,this.timeout=-1,this.signals=new EA(f.performanceMonitor.durationThreshold??3e3),this.config={monitorQualityLimitationReasons:f.performanceMonitor?.monitorQualityLimitationReasons,monitorMaxFS:f.performanceMonitor?.monitorMaxFS,mitigationTimeout:f.performanceMonitor?.mitigation?.timeout,startupDelay:f.performanceMonitor?.startupDelay}}key(g,f){return`${g.rid}:${f}`}suspend(g){g>0&&(this.logger.safe.info(`Suspending for ${(g/1e3).toFixed(1)} seconds`),this.timeout=Jt()+g)}acceptLayout(g){if(g.some((g=>void 0===g.rid)))return this.logger.safe.info("Ignore layout with missing RID"),!1;if(this.caps){if(Math.max(0,...g.map((g=>g.maxFs)))>this.caps.maxFs)return this.logger.safe.info("Ignore layout update while waiting for maxCapabilities to propagate to server"),!1}return!0}resetLayout(){this.signals.update({}),this.layout=void 0}updateMaxCapabilities(g){this.logger.safe.info(`Max capabilities updated: ${JSON.stringify(g)}`),this.caps&&g.maxFs<this.caps.maxFs&&this.layout?.length>0&&(this.logger.safe.info("Stop monitoring current layout as maxFS will be reduced"),this.resetLayout()),this.caps=g}updateLayout(g){if((g||this.layout)&&this.logger.safe.info(`New layout: ${JSON.stringify(g)}`),g&&this.acceptLayout(g)){if((g=g.map((g=>Object.assign({},g)))).sort(((g,f)=>g.maxFs===f.maxFs?g.maxFps===f.maxFps?g.maxBr-f.maxBr:g.maxFps-f.maxFps:g.maxFs-f.maxFs)),this.layout?.length)for(let f=0;f<g?.length;++f){const S=g[f],v=this.layout.find((g=>g.rid===S.rid));v&&v.maxFs!==S.maxFs&&(this.logger.safe.info(`Reset '${this.key(v,"FS")}'`),this.signals.track(this.key(v,"FS"),void 0))}this.layout=g,-1===this.timeout&&(this.timeout=0,this.logger.safe.info("Starting performance monitor"),this.suspend(this.config.startupDelay))}else this.resetLayout(),this.timeout=-1}onMitigationApplied(){this.logger.safe.info("Mitigation was applied - resetting current layout"),this.resetLayout(),this.suspend(this.config.mitigationTimeout)}monitor(g){const f={};let S=0;if(!this.layout||this.layout.length<1||g.length<this.layout.length||this.timeout>Jt())return void this.signals.update(f);for(this.timeout>0&&(this.logger.safe.info("Resuming"),this.timeout=0),S=0;S<this.layout.length;++S){const v=this.layout[S],C=g.find((g=>g.rid===v.rid));if(C){const g=Math.ceil(C.frameWidth/qt.MACROBLOCK_SIZE)*Math.ceil(C.frameHeight/qt.MACROBLOCK_SIZE);if(this.config.monitorQualityLimitationReasons){const g=C.qualityLimitationReason;-1!==this.config.monitorQualityLimitationReasons.indexOf(`${g}`)&&(f[this.key(v,"QL")]={layout:v,type:"QL",expected:"none",actual:g})}this.config.monitorMaxFS&&g<v.maxFs&&(f[this.key(v,"FS")]={layout:v,type:"FS",expected:v.maxFs,actual:g})}}const v=this.signals.update(f).map((g=>{const f=Object.assign({},g);return f.layout=this.layout?.find((g=>g.rid===f.layout.rid))??f.layout,f}));v.length&&(this.logger.safe.info(`Raise event: ${JSON.stringify(v)}`),this.event("onVideoQualityDegraded").raise(v))}},TA=class extends Ht{constructor(g,f,S,v){super(g),this.logger=g,this.configProvider=f,this.diagnostics=S,this.videoFeatureManager=v,this.activeModalities=new Set,this.callbacks=[];const C=this.configProvider.config.specCompliantSimulcast?.performanceMonitor?.mitigation??{};this.config={allowDisabling1080pSinglecast:C.enableFor1080pSinglecast,allowDisabling1080pSimulcast:C.enableFor1080pSimulcast,allowDisablingThreeStreamSimulcast:C.enableForThreeStreamSimulcast,allowReversals:C.enableReversals}}hasSoftwareEncodedVideoAndSharing(){return!this.videoFeatureManager.get("Video").hasClientSupport(1)&&(!this.videoFeatureManager.get("ScreenShare").hasClientSupport(1)&&this.hasActiveSenders("Video","ScreenShare"))}hasActiveSenders(...g){return g.every((g=>this.activeModalities.has(g)))}getAdaptationInfo(g,f){return{description:g,activeModalities:[...this.activeModalities],isTransient:f&&this.config.allowReversals}}notify(g){this.logger.safe.warn(`${g.description} activeModalities: ${g.activeModalities.join("/")} isTansient: ${g.isTransient}`),this.diagnostics.registerLocalVideoPerformanceEvent(g)}schedule(g,f,S){this.callbacks.push({mediaType:g,state:f,callback:S})}override(g,f,S){this.configProvider.config[g]=f,this.logger.safe.info(`Overwriting ${g} with ${this.configProvider.config[g]}. Reason: ${S}`)}disable1080pSoftwareEncode(g){const f=this.videoFeatureManager.get("Video");if(!g.find((g=>g.maxFs===qt.MAX_FS_1080P)))return!1;if(!f.hasClientSupport(2))return!1;if(f.hasClientSupport(1))return!1;if(1===g.length&&!this.config.allowDisabling1080pSinglecast)return this.logger.safe.info("Will not disable 1080p for singlecast"),!1;if(g.length>1&&!this.config.allowDisabling1080pSimulcast)return this.logger.safe.info("Will not disable 1080p for simulcast"),!1;const S=this.configProvider.config.performanceFallbackMaxFsFor1080pSend,v={},C={webrtcCameraOpenFs:this.configProvider.config.webrtcCameraOpenFs,maxCameraFsViaCallConstraints:this.configProvider.config.maxCameraFsViaCallConstraints,webrtcVideoCapabilityMaxFS:this.configProvider.config.webrtcVideoCapabilityMaxFS};for(const g in C)C[g]>0&&(v[g]=Math.min(S,C[g]));const _=Object.keys(v);if(_.some((g=>C[g]!==v[g]))){_.forEach((g=>{this.override(g,v[g],"mitigating 1080p performance issues")})),this.event("onNewStreamNeeded").raise(v.webrtcCameraOpenFs);const g=this.getAdaptationInfo("Disabled software 1080p",this.hasSoftwareEncodedVideoAndSharing());return g.isTransient&&this.schedule("ScreenShare",!1,(()=>{_.forEach((g=>{this.override(g,C[g],"removing mitigation for 1080p performance issues")})),this.event("onNewStreamNeeded").raise(),this.notify(this.getAdaptationInfo("Re-enabled software 1080p",!0))})),this.notify(g),!0}return!1}disableThreeStreamSimulcast(g){const f=this.videoFeatureManager.get("Video");if(3!==g.length)return!1;if(!this.config.allowDisablingThreeStreamSimulcast)return this.logger.safe.info("Will not disable 3-stream simulcast"),!1;if(f.hasClientSupport(1))return!1;if(f.hasFullSupport(0)){const g=this.getAdaptationInfo("Disabled 3-stream simulcast",this.hasSoftwareEncodedVideoAndSharing());return f.toggleClient(0,!1),g.isTransient&&this.schedule("ScreenShare",!1,(()=>{f.toggleClient(0,!0),this.notify(this.getAdaptationInfo("Re-enabled Three stream simulcast",!0))})),this.notify(g),!0}return!1}updateSenderState(g,f){if(f===this.activeModalities.has(g))return;f?this.activeModalities.add(g):this.activeModalities.delete(g);const S=this.callbacks.filter((S=>S.mediaType===g&&S.state===f));this.callbacks=this.callbacks.filter((S=>S.mediaType!==g||S.state!==f));for(const g of S)g.callback()}mitigatePerformanceIssue(g){return!!this.disable1080pSoftwareEncode(g)||!!this.disableThreeStreamSimulcast(g)}},IA=class{constructor(g,f,S){this.callback=g,this.logger=f,this.settings=S,this.triggers=0,this.budget=0,this.budget=this.burst}get interval(){return this.settings?.interval??0}get burst(){return this.settings?.burst??0}cancel(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}schedule(){this.timer||(this.timer=setTimeout((()=>{this.cancel(),this.commit()||(this.budget=Math.min(this.budget+1,this.burst)),this.budget<this.burst&&this.schedule()}),this.interval))}commit(){return this.triggers>0&&(this.callback.apply(this),this.triggers=0,!0)}dispose(){this.cancel()}trigger(){++this.triggers,0!==this.burst||0!==this.interval?this.burst?(this.budget>0&&(--this.budget,this.commit(),this.cancel(),this.budget||this.logger.safe.warn(`Max burst limit reached: ${this.burst}`)),this.triggers>0&&this.logger.safe.debug(`Triggered while out of budget: ${this.triggers} / ${this.burst}`),this.schedule()):this.timer||(this.commit(),this.schedule()):this.commit()}},bA=class extends Ht{constructor(g,f,S,v){super(g),this.logger=g,this.configProvider=f,this.frameSizeLimits={},this.initialMaxFS=this.configProvider.config.webrtcCameraOpenFs,this.subs=[],this.cadence=new IA(this.commitCallConstraints.bind(this),this.logger.createChild("Cadence"),this.configProvider.config.sendVideoCapabilityManager?.constraintsCadence),this.configProvider.config.enableVideoFeatureManager&&S&&(this.features=S.get("Video"),this.subs.push(S.on("onVideoFeaturesChanged",(g=>{"Video"===g.mediaType&&this.onFeaturesChanged(g)})))),v&&this.subs.push(v.on("onNewStreamNeeded",(g=>{this.limitFrameSize("Performance",g),this.updateConstraintsAndNotify()}))),this.configProvider.config.video1080p?.software?.isEnabled&&this.limitFrameSize("Software1080P",qt.MAX_FS_1080P),this.settings=this.configProvider.config.sendVideoCapabilityManager,this.settings.defaultFS&&(this.initialMaxFS=this.settings.defaultFS);const C=this.getCallConstraints().maxFS;C&&C!==this.initialMaxFS&&(this.logger.safe.info(`Detected initial resolution opt-in: ${this.initialMaxFS} => ${C}`),this.limitFrameSize("Opt-In",C))}getCapabilities(){if(this.appliedCapabilities)return{...this.appliedCapabilities}}applyCallConstraints(g){this.lastCauseId=g,this.cadence.trigger()}manage(g,f){f&&(this.streamConstraints={maxFPS:g.maxFps,maxFS:g.maxFs},this.features&&this.streamConstraints.maxFS>=qt.MAX_FS_1080P&&this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy&&this.features.toggleClient(2,!0)),this.requestedCapabilities={...g},this.updateConstraintsAndNotify()}dispose(g){for(const f of this.subs)f.dispose(g);this.subs=[],this.cadence.dispose(),super.dispose()}onFeaturesChanged(g){const checkClient=(f,S)=>{this.limitFrameSize(Lb[f],g.hasClientSupport(f)?S:void 0)};checkClient(1,this.configProvider.config.hardwareEncodedVideoMaxFS),checkClient(3,this.configProvider.config.broadcastMode?.maxVideoFS),this.updateConstraintsAndNotify()}getCallConstraints(){const g=this.configProvider.config.outgoingVideoLimit,f={},S="number"==typeof g?g:g?.maxResolution;return S&&(f.maxFS=convertResolutionToFramesize(S)),f.maxFPS="number"==typeof g?void 0:g?.maxFramerate,f}commitCallConstraints(){this.limitFrameSize("Opt-In",this.getCallConstraints().maxFS,this.lastCauseId),this.updateConstraintsAndNotify()}buildCapabilities(){const g={...this.requestedCapabilities};if(this.constraints?.maxFS<g.maxFs||this.constraints?.maxFPS<g.maxFps){g.maxFps=getMinDefined(this.constraints.maxFPS,g.maxFps),g.maxFs=getMinDefined(this.constraints.maxFS,g.maxFs);const f={...ei.Send.getResolutionByFs(g.maxFs)};g.maxMbps=f.fs*g.maxFps,g.maxWidth=f.width,g.maxHeight=f.height}return g}limitFrameSize(g,f,S){this.frameSizeLimits[g]!==f&&(S?this.logger.safe.info(`[${S}] FS limit for '${g}' changed from ${this.frameSizeLimits[g]} to ${f}`):this.logger.safe.info(`FS limit for '${g}' changed from ${this.frameSizeLimits[g]} to ${f}`),this.frameSizeLimits[g]=f)}notify(){this.appliedCapabilities=this.buildCapabilities(),this.requestedCapabilities.maxFs!==this.appliedCapabilities.maxFs&&this.logger.safe.debug(`Changed video send capability max-fs from ${this.requestedCapabilities.maxFs} to ${this.appliedCapabilities.maxFs}`),this.requestedCapabilities.maxFps!==this.appliedCapabilities.maxFps&&this.logger.safe.debug(`Changed video send capability max-fps from ${this.requestedCapabilities.maxFps} to ${this.appliedCapabilities.maxFps}`),this.logger.safe.info(`Reporting video capabilities: ${JSON.stringify(this.appliedCapabilities)}`),this.event("onCapabilitiesChanged").raise(this.appliedCapabilities)}updateConstraintsAndNotify(){this.updateConstraints()&&this.notify()}updateConstraints(){const g=this.getCallConstraints(),f={};let S=!1;for(const g of this.settings.priorityOrder)if(this.frameSizeLimits[g]>0){S=-1!==this.settings.allowOptIn.indexOf(g),f.maxFS=this.frameSizeLimits[g],this.logger.safe.info(`Using FS ${f.maxFS} from '${g}'. Opt-In is ${S?"allowed":"not allowed"}`);break}if(void 0===f.maxFS&&(f.maxFS=this.initialMaxFS,S=this.settings.maxFS>this.initialMaxFS),f.maxFPS=g.maxFPS,this.frameSizeLimits["Opt-In"]>0){const g=this.frameSizeLimits["Opt-In"];(g<f.maxFS||S)&&(this.logger.safe.info(`Applying opt-in: ${f.maxFS} => ${g}`),f.maxFS=g)}if(this.streamConstraints&&(this.logger.safe.debug(`Applying stream constraints: ${JSON.stringify(this.streamConstraints)} to ${JSON.stringify(f)}`),f.maxFS&&(f.maxFS=getMinDefined(f.maxFS,this.streamConstraints.maxFS)),f.maxFPS&&(f.maxFPS=getMinDefined(f.maxFPS,this.streamConstraints.maxFPS))),f.maxFS===this.constraints?.maxFS&&f.maxFPS===this.constraints?.maxFPS||(this.logger.safe.info(`Final constraints changed from ${JSON.stringify(this.constraints)} to ${JSON.stringify(f)}`),this.constraints=f),this.constraints&&this.requestedCapabilities){if(this.appliedCapabilities){const g=this.buildCapabilities();return g.maxFs!==this.appliedCapabilities.maxFs||g.maxFps!==this.appliedCapabilities.maxFps}return!0}return!1}},AA=class extends Ht{constructor(g,f,S,v,C,_,T,I,b,A,P){super(f),this.mediaManager=g,this.logger=f,this.callDeviceManager=S,this.configProvider=v,this.sessionConfig=C,this.statisticsGatherer=_,this.diagnostics=T,this.qmDiagnostics=I,this.isMultiparty=b,this.encStreamsManager=A,this.videoFeatureManager=P,this.senders=new Map,this.senderSubs=new Map,this.senderId=0,this.previousMediaModalities={Audio:!1,Video:!1,ScreenShare:!1},this.muted=new Map([["Audio",!1],["Video",!1]]),this.serialQueue=new zC(this.logger),this.streamsProvider=new zb(this.callDeviceManager,this.configProvider,this.sessionConfig,this.serialQueue,this.logger.createChild("StreamsProvider")),this.streamProviderSubscriptions=[this.streamsProvider.on("onStreamAdded",(g=>this.onStreamUpdated(g,!1))),this.streamsProvider.on("onStreamUpdated",(g=>this.onStreamUpdated(g,!0)))],this.localVideoStreamWatcher=new Mb(this.logger,this.configProvider,this.callDeviceManager),this.localVideoStreamWatcherSub=this.localVideoStreamWatcher.on("onVideoCaptureFreeze",((g,f)=>this.onVideoCaptureFreeze(g,f))),this.configProvider.config.useMediaQualityController&&(this.mediaQualityController=new dA(this.configProvider,this.logger.createChild("MQC"),this.videoFeatureManager),this.mediaQualityController.on("onLayoutsUpdated",(g=>{const f=this.mediaQualityController.getLayouts(g);return this.logger.safe.debug(`Update layouts for ${g}: ${JSON.stringify(f)}`),"Video"===g&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateLayout(f),this.updateParameters(this.lastCauseId,g,f)})),this.mediaQualityController.on("onBandwidthAllocationUpdated",(g=>{this.event("onBandwidthAllocationChanged").raise(g)}))),this.configProvider.config.specCompliantSimulcast?.performanceMonitor&&(this.simulcastPerformanceMonitor=new _A(this.logger.createChild("SPM"),this.configProvider.config.specCompliantSimulcast),this.simulcastPerformanceMonitor.on("onVideoQualityDegraded",(g=>this.onVideoQualityDegraded(g)))),this.configProvider.config.specCompliantSimulcast?.performanceMonitor?.mitigation&&(this.simulcastPerformanceAdaptationManager=new TA(this.logger.createChild("SPAM"),this.configProvider,this.diagnostics,this.videoFeatureManager),this.simulcastPerformanceAdaptationManager.on("onNewStreamNeeded",(g=>{this.configProvider.config.sendVideoCapabilityManager?.isEnabled||(this.sessionConfig.outgoingVideoMaxFS=g,this.streamsProvider.requestStreamUpdate("Video",!0))})))}dispose(){this.senders.forEach(((g,f)=>{this.event("onSendStreamChanged").raise(null,f),this.configProvider.config.disposeSendersSync?g.dispose():g.terminateAsync()})),this.senders.clear(),this.senderSubs.forEach((g=>g.forEach((g=>g.dispose())))),this.senderSubs.clear(),this.streamProviderSubscriptions.forEach((g=>g.dispose())),this.streamProviderSubscriptions=[],this.configProvider.config.disposeStreamsSync?this.streamsProvider.stop():this.streamsProvider.stopAsync(),this.localVideoStreamWatcherSub.dispose(),this.localVideoStreamWatcher.dispose(),this.logger=this.logger.createChild("DISPOSED"),this.mediaQualityController?.dispose(),super.dispose()}registerRtpSenderManager(g){this.logger.safe.debug(`Registering RTP sender manager ${g}`),this.mediaConnection=g}useNullAudioStreamClient(){this.logger.safe.debug("Using null audio stream client"),this.streamsProvider.useNullAudioStreamClient()}get pendingStreamsPromise(){return this.streamsPromise}clearStreamsPromise(){this.streamsPromise=void 0}async update(g,f,S,v){v?.mark("startUpdateStreams");let C=getSendStreamModalities(g,this.configProvider.config.streamModalitiesExcludeData);const _=0!=(1&f),T=0!=(2&f),I=0!=(4&f);I&&(C={Audio:!0,Video:!1,Data:!1,ScreenShare:!1});const b=I?Promise.resolve(C):this.streamsProvider.update(C,_);let A,P;return T||I?(delete C.Data,A=shallowClone(C),P=_?void 0:A):(A=await b,P=A),this.logger.safe.info(`[${S}] Streams updated, modalities requested: ${JSON.stringify(C)} (flags: ${f}), result: ${JSON.stringify(A)}`),v?.markAndMeasure("startUpdateStreams","updateStreamsWithModalities"),await this.updateSenders(P,S),v?.markAndMeasure("updateStreamsWithModalities","updateSenders"),T&&(this.streamsPromise=(async()=>{const f=await b;return this.streamsPromise=void 0,await this.updateSenders(f,S),this.setAndUpdateLocalTracksInfo(!1),this.mergeAndSaveModalities(f,g)})()),this.applyMuteState(S,!0),this.setAndUpdateLocalTracksInfo(!1),this.mergeAndSaveModalities(A,g)}mergeAndSaveModalities(g,f){this.previousMediaModalities=shallowClone(g);const S=shallowClone(f);return forOwn(f,((f,v)=>{const C=modalityToMediaType(v);hasSendDirectionality(f)&&!g[C]&&(S[v]=removeSendDirectionality(f))})),S}async activate(g){this.logger.safe.info(`[${g}] activate senders`),await Promise.all([...this.senders.values()].map((async g=>g.activate()))),this.setAndUpdateLocalTracksInfo(!1)}applyCallConstraints(g){const f=this.senders.get("Video");return f?f.applyCallConstraints(g):(this.logger.info(`[${g}] Caching call constraints until sender is created`),this.callConstraintsCauseId=g,this.applyCallConstraintsDeferred=new dt,this.applyCallConstraintsDeferred.promise)}async applyCapabilities(g,f,S){this.logger.safe.info(`[${g}] Applying incoming ${f} FMTP: ${JSON.stringify(S)}`);const v=modalityToMediaType(f);this.lastCauseId=g;let C=S;return this.mediaQualityController&&(this.mediaQualityController.addReceiver(v,S),C=this.mediaQualityController.getLayouts(v)),this.simulcastPerformanceAdaptationManager?.updateSenderState(v,!0),this.updateParameters(g,v,C)}getLocalMediaSources(){const g=this.getTracksInfo(),f=[];return g.forEach((g=>{f.some((f=>f.modality===g.modality))||f.push({sourceId:this.getSourceIdForTrack(g),modality:g.modality})})),f}setMuted(g,f,S){this.muted.set(g,f),this.applyMuteState(S,!1)}async setHold(g,f){await Promise.all([...this.senders.values()].map((async S=>S.setHold(g,f))))}onStatisticsChanged(g){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.mediaQualityController?.onStatisticsChanged(g),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher||this.localVideoStreamWatcher.onStatisticsChanged(g)}onDiagnosticUpdated(g){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation&&this.mediaQualityController?.onDiagnosticUpdated(g),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher&&this.localVideoStreamWatcher.onDiagnosticUpdated(g)}async updateParameters(g,f,S){try{const v=this.senders.get(f);v?await v.updateParameters(S):this.logger.safe.info(`[${this.lastCauseId}] Capabilities ignored ${JSON.stringify(S)}, no ${JSON.stringify(f)} sender`),this.logger.safe.debug(`[${g}] Capabilities completed`);const C={modality:mediaTypeToModality(f),causeId:g,capabilities:S};this.statisticsGatherer.onMaxCapabilitiesApplied(C),this.qmDiagnostics.onMaxCapabilitiesApplied(C)}catch(v){const C=stringifyObject(v);this.logger.safe.error(`[${g}] Error applying capabilities ${C}`);const _={modality:mediaTypeToModality(f),causeId:g,capabilities:S,error:C};this.statisticsGatherer.onMaxCapabilitiesApplied(_),this.qmDiagnostics.onMaxCapabilitiesApplied(_)}}applyMuteState(g,f){for(const[S,v]of this.muted)this.senders.get(S)&&this.senders.get(S).setMuted(v,g,f)}setAndUpdateLocalTracksInfo(g){const f=this.getTracksInfo();this.logger.safe.debug(`Local tracks info: ${JSON.stringify(f)}`),this.mediaManager.setLocalTracksInfo(f),g&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statisticsGatherer.updateStatsWithLocalSsrcTrackInfo())}getTracksInfo(){const g=[];return this.senders.forEach((f=>g.push(f.getTrackInfo()))),g}async updateSenders(g,f=generateCauseId()){const S=await this.streamsProvider.getStreams(),v=g||sendStreamsToModalities(S);this.logger.safe.info(`[${f}] Updating senders with modalities: ${JSON.stringify(v)}, override: ${!!g}`),await Promise.all(keys(v).map((async g=>{const S=v[g];if(S===this.previousMediaModalities[g])return;if(!S)return this.logger.safe.info(`[${f}] Removing sender for ${JSON.stringify(g)}`),void await this.removeSender(g);const C=(await this.streamsProvider.getStreams())?.[g];if(await this.createAndStartSender(C,g),this.logger.safe.info(`[${f}] Sender for ${JSON.stringify(g)} is added`),this.applyCallConstraintsDeferred&&"Video"===g){const g=this.senders.get("Video");try{await g.applyCallConstraints(this.callConstraintsCauseId),this.applyCallConstraintsDeferred.resolve()}catch(g){this.applyCallConstraintsDeferred.reject(g)}this.applyCallConstraintsDeferred=void 0,this.callConstraintsCauseId=void 0}await this.addAudioSharingStream(C),this.event("onSendStreamChanged").raise(C,g)}))),this.logger.safe.info(`[${f}] Senders updated. Enabled: ${JSON.stringify(Object.keys(v).filter((g=>v[g])))}`)}createCapabilityManager(g,f){if("Video"===g&&this.configProvider.config.sendVideoCapabilityManager?.isEnabled)return new bA(f.createChild("SVCM"),this.configProvider,this.videoFeatureManager,this.simulcastPerformanceAdaptationManager)}createAndStartSender(g,f){if(this.senders.get(f))return this.logger.safe.error(`Sender already created, modality: ${JSON.stringify(f)}`),this.senders.get(f).start();const S=this.mediaManager.getMediaEntitiesByModality(mediaTypeToModality(f))[0],v=S?.getSimulcastContext(),C=!this.configProvider.config.specCompliantSimulcast?.disableTilde&&!!v?.shouldUseSimulcast(),_="Audio"===f||!this.isMultiparty||C,T=this.logger.createChild(`Sender_${JSON.stringify(f)}:${this.senderId++}`),I=this.createCapabilityManager(f,T),b=new yA(this.mediaConnection,g||new qb(f,this.logger.createChild("tempStream")),new MediaStream,f,this.serialQueue,T,this.configProvider,_,this.encStreamsManager,v,I);this.senders.set(f,b);const A=[b.on("onSendersChanged",((g,f)=>this.onSenderStateChanged(g,f))),b.on("onNewStreamNeeded",(()=>this.streamsProvider.requestStreamUpdate(f,!0))),b.on("onMaxVideoSendCapabilitiesChanged",(g=>{this.event("onMaxVideoSendCapabilitiesChanged").raise(f,g),"Video"===f&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateMaxCapabilities(g)}))];return this.senderSubs.set(b,A),b.start()}async removeSender(g){const f=this.senders.get(g);f&&(this.senders.delete(g),this.event("onSendStreamChanged").raise(null,g),await f.terminateAsync(),this.senderSubs.get(f).forEach((g=>g.dispose())),this.senderSubs.delete(f),this.logger.safe.info(`Removed sender with mediaType: ${JSON.stringify(g)}`)),this.mediaQualityController?.removeReceiver(g),this.simulcastPerformanceAdaptationManager?.updateSenderState(g,!1),"Video"===g&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateLayout(void 0)}getSourceIdForTrack(g){const f=g.trackId,S=this.mediaManager.getMediaEntityByLocalTrackId(f);return S?(this.logger.safe.info(`Media entity found: ${JSON.stringify(S.getXSourceStreamId())}`),S.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(f)}`),0)}onVideoCaptureFreeze(g,f){g||(f?this.qmDiagnostics.registerWebcamFreeze():this.qmDiagnostics.registerProcessedStreamFreeze()),this.event("onVideoCaptureFreeze").raise(g)}onVideoQualityDegraded(g){const f=this.mediaQualityController?.getLayouts("Video")??[];let S=!1;for(const v of g)if(this.logger.safe.warn(`rid:${v.layout.rid} ${v.type} degraded - expected: ${v.expected}, actual: ${v.actual}`),!S&&this.simulcastPerformanceAdaptationManager)switch(v.type){case"QL":"cpu"===v.actual&&(S=this.simulcastPerformanceAdaptationManager.mitigatePerformanceIssue(f));break;case"FS":"1"===v.layout.rid&&(S=this.simulcastPerformanceAdaptationManager.mitigatePerformanceIssue(f))}S&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.onMitigationApplied()}async onStreamUpdated(g,f){if(!this.senders.has(g))return void this.logger.safe.warn(`Sender with media type ${g} does not exist, do not update media stream`);let S=(await this.streamsProvider.getStreams())[g];if(S||(this.logger.safe.info(`Stream is missing for mediaType: ${g}, using fake stream...`),S=new qb(g,this.logger.createChild("NullStreamClient"))),S.isDisposed())return void this.logger.safe.info(`Stream is already disposed for mediaType: ${g}`);this.event("onSendStreamChanged").raise(S,g);const v=this.senders.get(g);await this.addAudioSharingStream(S),await v.updateStream(S),this.logger.safe.debug(`Stream updated for mediaType: ${g}, updated: ${f}`),this.setAndUpdateLocalTracksInfo(f)}onSenderStateChanged(g,f){if(this.mediaManager.updateMediaEntitiesWithActivityState(g.mediaType,g.getActiveStreamIndexes()),this.statisticsGatherer.onSendersChanged(g.mediaType,f),"Video"===g.mediaType)if(f){const g=this.getTracksInfo().filter((g=>g.modality===qt.MODALITY.video));this.localVideoStreamWatcher.startWatching(g,this.simulcastPerformanceMonitor)}else this.localVideoStreamWatcher.stopWatching()}async addAudioSharingStream(g){"ScreenShare"===g?.mediaType&&g?.hasAudio()&&(this.logger.safe.info("Adding audio stream from sharing to audio sender"),await(this.senders.get("Audio")?.addAdditionalStream(g)))}};function getSendStreamModalities(g,f=!0){const S={Audio:hasSendDirectionality(g.audio),Video:hasSendDirectionality(g.video),ScreenShare:hasSendDirectionality(g.sharing)};return f||(S.Data=hasSendDirectionality(g.data)),S}var PA=class{constructor(g,f,S,v,C){this.recvStream=g,this.mainTrack=f,this.receiveStreamCollection=S,this.logger=v,this.settings=C,this.removeOtherTracks(f),this.subscribeOnStreamEvents()}get stream(){return this.recvStream.getMediaStream()}dispose(){this.unsubscribeFromStreamEvents(),this.receiveStreamCollection=null,this.mainTrack=null,this.recvStream.dispose()}getId(){return this.recvStream.getId()}getModality(){return this.recvStream.getModality()}getMsi(){return this.recvStream.getMsi()}getMediaStream(){return this.stream}getReceiver(){return this.recvStream.getReceiver()}requestSource(g){return this.recvStream.requestSource(g)}getSourceStreamId(){return this.recvStream.getSourceStreamId()}getSubstreamIndex(){return this.recvStream.getSubstreamIndex()}removeOtherTracks(g){if(this.settings.onAddTrackRemoveOtherTracks){this.stream.getTracks().forEach((f=>{f.id!==g.id&&this.stream.removeTrack(f)}))}}subscribeOnStreamEvents(){const logEvent=g=>this.logger.safe.info(`${g} track: ${this.mainTrack.id}, stream: ${this.stream.id}`);this.stream.onremovetrack=()=>{logEvent("onremovetrack"),this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onended=()=>{logEvent("onended"),this.settings.removeRecvStreamOnEnded&&this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onmute=()=>logEvent("onmute"),this.mainTrack.onunmute=()=>logEvent("onunmute")}unsubscribeFromStreamEvents(){this.stream.onremovetrack=null,this.mainTrack.onended=null,this.mainTrack.onmute=null,this.mainTrack.onunmute=null}},RA=class{constructor(g){this.startTimestamp=0,this.totalTime=0,this.lastActiveTime=0,this.id=g}},MA=class{constructor(g){this.speakersHistory=[],this.sources=[],this.configProvider=g.configProvider,this.ping=this.setupTimer()}setSources(g=[]){const f=g.map(this.getOrCreateSource.bind(this)),S=this.excludeSources(this.sources,f);f.forEach((g=>{this.isAlreadyActive(g)||this.updateSourceTimestamp(g),this.updateSourceLastActiveTime(g)})),S.forEach((g=>{this.updateTotalTime(g),this.resetStartTimestamp(g)})),this.ping||(this.ping=this.setupTimer())}setOnDominantSpeakerChanged(g){this.callback=g}dispose(){this.clearTimer(),this.sources=null,this.callback=null}excludeSources(g,f){return g.filter((g=>!f.some((f=>g.id===f.id))))}trigger(){if(!this.hasAnyoneSpoken())return void this.clearTimer();const byActivity=(g,f)=>f.totalTime-g.totalTime||f.lastActiveTime-g.lastActiveTime,toSourceId=g=>g.id,g=this.sources.map(this.updateTotalTime).sort(byActivity).map(toSourceId).slice(0,this.configProvider.config.ovcMaxCount);g.length&&!deepEqual(this.speakersHistory,g)&&(this.speakersHistory=g,this.callback&&this.callback(this.speakersHistory,"client")),this.sources.map(this.resetTotalTime).filter(this.isAlreadyActive).forEach(this.updateSourceTimestamp)}isAlreadyActive(g){return!!g.startTimestamp}setupTimer(){return window.setInterval(this.trigger.bind(this),this.configProvider.config.activeSpeaker.timeToPromote)}clearTimer(){this.ping&&(clearInterval(this.ping),this.ping=null)}getOrCreateSource(g){if(this.isExist(g))return this.sourceById(g);{const f=new RA(g);return this.sources.push(f),f}}isExist(g){return this.sources.some((f=>g===f.id))}hasAnyoneSpoken(){return this.sources.some((g=>0!==g.startTimestamp||0!==g.totalTime))}sourceById(g){return this.sources.find((f=>g===f.id))}updateSourceTimestamp(g){g.startTimestamp=Date.now()}updateSourceLastActiveTime(g){g.lastActiveTime=Date.now()}updateTotalTime(g){return g.startTimestamp&&(g.totalTime+=Date.now()-g.startTimestamp),g}resetStartTimestamp(g){return g.startTimestamp=0,g}resetTotalTime(g){return g.totalTime=0,g}},wA=class extends Ht{constructor(g,f){super(),this.configProvider=g,this.logger=f,this.bandwidthEstimationAvailable=!1,this.smoothingWindow=[],this.totalSamples=0,this.isStarted=!1,this.maxCountStatic=this.configProvider.config.ovcMaxCount,this.previousParticipantsCount=0,this.isMcpSrAvailable=!1;const S=window.navigator;this.updateStaticConstraint(S.hardwareConcurrency,this.configProvider.config.ovcAvailableConcurrencyForBiggerGrid,4),this.updateStaticConstraint(S.deviceMemory,this.configProvider.config.ovcMemoryForBiggerGrid,4),this.throttler=new OA(this.logger.createChild("ovcThrottler"),this.configProvider.config.ovcRampDownCooldown,this.configProvider.config.ovcRampUpCooldown)}start(){this.logger.safe.debug("Starting OptimalVideoCountCalculator"),this.isStarted=!0,this.throttler.changed((()=>this.event("calculatorStateChanged").raise(2,{ovc:this.throttler.value,ovcPayload:this.payload})))}stop(){this.isStarted=!1}dispose(){super.dispose(),this.logger.safe.debug("Disposing OptimalVideoCountCalculator"),this.throttler.dispose()}processEstimatedBandwidth(g){this.bandwidthConstrainedOvc=this.getOVCEstimate(g),this.payload={bandwidth:g,reason:0},this.throttler.setValue(this.getOvcValue(),0)}updateParticipantCount(g){if(!this.configProvider||g===this.previousParticipantsCount)return;const f=this.configProvider.config.ovcXLParticipantsCount;g>f&&this.previousParticipantsCount<=f&&(this.maxCountStatic=this.configProvider.config.ovcMaxCountXL),g<=f&&this.previousParticipantsCount>f&&(this.configProvider.config.multiStreamSupported&&this.isMcpSrAvailable?this.maxCountStatic=this.configProvider.config.ovcMaxCountMultiStream:this.maxCountStatic=this.configProvider.config.ovcMaxCount),this.previousParticipantsCount=g,this.payload?.bandwidth&&(this.bandwidthConstrainedOvc=this.getOVCEstimate(this.payload.bandwidth),this.payload.reason=2),this.throttler.setValue(this.getOvcValue(),2)}setPerfConstrainedValue(g){this.perfConstrainedOvc=g,this.logger.safe.info(`Setting perfConstrainedOvc to ${g}`),this.payload&&this.getOvcValue()===g&&(this.payload={reason:1}),this.throttler.setValue(this.getOvcValue(),1)}mcpSourceRequestsAvailable(){this.configProvider.config.multiStreamSupported&&(this.isMcpSrAvailable=!0,this.maxCountStatic===this.configProvider.config.ovcMaxCount&&(this.maxCountStatic=this.configProvider.config.ovcMaxCountMultiStream),this.payload?.bandwidth&&(this.bandwidthConstrainedOvc=this.getOVCEstimate(this.payload.bandwidth),this.payload.reason=2),this.throttler.setValue(this.getOvcValue(),2))}getOVCEstimate(g){this.bandwidthEstimationAvailable||(this.bandwidthEstimationAvailable=this.isStarted&&g>0&&(this.totalSamples++>=this.configProvider.config.ovcIgnoreFirstSamples||Math.floor(g)/this.configProvider.config.ovcBandwidthPerVideoReceiver>=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount));let f=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount;return this.bandwidthEstimationAvailable&&(f=Math.floor(this.sampleSmoothed(g)/this.configProvider.config.ovcBandwidthPerVideoReceiver)),f}getOvcValue(){return Math.max(1,Math.min(this.bandwidthConstrainedOvc??this.maxCountStatic,this.perfConstrainedOvc??this.maxCountStatic,this.maxCountStatic))}sampleSmoothed(g){if(this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples?this.smoothingWindow.shift():this.smoothingWindow.length===this.configProvider.config.ovcSlidingWindowSamples-1&&(this.smoothingWindow=this.smoothingWindow.map((()=>g))),this.smoothingWindow.push(g),this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples){const g=this.smoothingWindow.slice().sort(),f=average(g);return g[g.length-1]-(g[g.length-1]-f*(1-this.configProvider.config.ovcSlidingWindowPercentile))}return g}updateStaticConstraint(g,f,S){g&&g<f&&(this.maxCountStatic=Math.min(this.maxCountStatic,S))}},OA=class extends Ht{constructor(g,f,S){super(g),this.logger=g,this.throttleDownCooldown=f,this.throttleUpCooldown=S,this.wasRampingUp=!0,this.lastUpdateTime=0}get value(){return this.lastValue}setValue(g,f){if(g===this.lastValue)return;const S=g>this.lastValue,v=void 0!==this.lastValue&&S!==this.wasRampingUp?S?this.throttleUpCooldown:this.throttleDownCooldown:-1,C=Date.now();C-this.lastUpdateTime<v&&(2!==f||S)||(void 0!==this.lastValue&&(this.lastUpdateTime=C,this.wasRampingUp=S),this.logger.safe.info(`optimal video receivers count updated ${this.lastValue} -> ${g}, reason: ${f}`),this.lastValue=g,this.raiseChanged())}},DA=class _CPUUsageMetricCollector{constructor(g,f=30){this.logger=g,this.maxEventNum=f,this.report=[],this.started=!1}isSupported(){return Boolean(window.chrome?.runtime?.connect)}start(){this.isSupported?(this.started=!0,this.logger.debug("Starting collecting CPU metric"),this.port=window.chrome.runtime.connect(_CPUUsageMetricCollector.extensionID,{name:_CPUUsageMetricCollector.extensionName}),this.port.onMessage.addListener((g=>{g&&arrayLimitedPush2(this.report,{timeStamp:Date.now(),value:g},this.maxEventNum)}))):this.logger.debug("Chrome runtime is not supported")}stop(){this.port?.disconnect(),this.port=null,this.started=!1}getSamples(){return this.report}getLastSample(){return getLast(this.report)}getCurrentCpuSample(){return new Promise(((g,f)=>{this.started&&g(getLast(this.report)),this.isSupported()||f("Not supported"),this.port=window.chrome.runtime.connect(_CPUUsageMetricCollector.extensionID,{name:_CPUUsageMetricCollector.extensionName}),this.port.onMessage.addListener((S=>{this.stop(),S||f("Not supported"),g({timeStamp:Date.now(),value:S})}))}))}clearStats(){this.report=[]}};DA.extensionID="nkeimhogjdpnpccoofpliimaahmaaome",DA.extensionName="processCpu";var NA=DA,kA=class{constructor(g){this.logger=g,this.started=!1}static isSupported(){return void 0!==globalThis.PressureObserver}get cpuState(){return this.currentCpuState}start(){if(this.logger.safe.debug("Starting CPU pressure observer"),this.started)this.logger.safe.debug("CPU pressure observer is already started");else{try{this.cpuObserver=new globalThis.PressureObserver((g=>{g.forEach((f=>{"cpu"===f.source&&this.currentCpuState!==f.state&&(this.logger.safe.debug(`CPU pressure state changed: ${JSON.stringify(g)}`),this.currentCpuState=f.state)}))}),{sampleRate:1})}catch(g){throw this.logger.safe.error(`Error while creating pressure observer: ${g}`),g}this.started=!0,this.cpuObserver?.observe("cpu")}}stop(){this.started=!1,this.cpuObserver?.disconnect()}},LA=class extends Ht{constructor(g,f,S,v){super(),this.statsGatherer=g,this.diagnostics=f,this.configProvider=S,this.logger=v,this.paused=!1,this.started=!1,this.trackInterval=this.configProvider.config.diagnostics.performanceMonitoring.remoteVideoTrackInterval,this.badPerfIds=new Set,this.perfTrackerMap=new Map,this.subs=[],this.rendererFpsCap=40,this.configProvider.config.diagnostics.performanceMonitoring.useComputePressure&&kA.isSupported()&&(this.cpuPressureObserver=new kA(this.logger)),this.configProvider.config.diagnostics.performanceMonitoring.useCpuSample&&(this.cpuMetricCollector=new NA(this.logger,this.configProvider.config.diagnostics.performanceMonitoring.cpuMetricCollector))}start(){this.logger.safe.debug("Starting RemoteVideoPerformanceCalculator"),this.started?this.logger.safe.debug("RemoteVideoPerformanceCalculator already running. Do nothing."):(this.calculatorStrategy=BC.getStrategy(this.configProvider),this.started=!0,this.cpuPressureObserver?.start(),this.subs.push(this.statsGatherer.on("onDiagnosticUpdated",(g=>this.processStats(g)))))}stop(){this.logger.safe.debug("Stopping RemoteVideoPerformanceCalculator"),this.started=!1,this.subs.forEach((g=>{g.dispose()})),this.cpuMetricCollector?.stop(),this.cpuPressureObserver?.stop()}dispose(){this.logger.safe.debug("Disposing RemoteVideoPerformanceCalculator"),this.cleanupMaps(),this.stop()}cleanupMaps(){this.badPerfIds.clear(),this.perfTrackerMap.clear()}async processStats(g){try{if(this.paused)return;if(!g.video?.recv?.length)return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Calculating remote video performance"),g.video?.recv?.forEach((async f=>{const S=f.renderer?.msi;if(!this.perfTrackerMap.has(S)){const g={id:f.mediaEntity?.remoteTrackId,decodeTimeTracker:new Jv(this.trackInterval),macroblockLossTracker:new Jv(this.trackInterval),macroblockMaxLossTracker:0,freezeDurationPercent:0,frameHeight:0,frameWidth:0,rendererFps:new Jv(this.trackInterval),incomingFps:new Jv(this.trackInterval),framesReceived:0,framesDecoded:0,decoder:"",msi:S};this.perfTrackerMap.set(S,g)}const v=this.perfTrackerMap.get(S);if(f.inboundRTP.totalDecodeTime&&f.inboundRTP.framesDecoded){const g=round(f.inboundRTP.totalDecodeTime/f.inboundRTP.framesDecoded*1e3,2);v.decodeTimeTracker.captureSample(g)}const C=f.extensions?.macroblockRateStats?.macroblockRateDecoderLossPercent;v.macroblockLossTracker.captureSample(C),v.macroblockMaxLossTracker=f.extensions?.macroblockRateStats?.macroblockRateMaxDecoderLossPercent,f.extensions?.duration&&(v.freezeDurationPercent=f.extensions?.totalFreezeDuration/f.extensions?.duration*100),v.frameHeight=f.inboundRTP.frameHeight||0,v.frameWidth=f.inboundRTP.frameWidth||0,void 0!==f.extensions?.frameRateDecoded&&void 0!==f.inboundRTP.framesPerSecond&&f.extensions?.frameRateDecoded<=this.rendererFpsCap&&f.inboundRTP.framesPerSecond<=this.rendererFpsCap&&(v.rendererFps.captureSample(f.extensions?.frameRateDecoded),v.incomingFps.captureSample(f.inboundRTP.framesPerSecond)),f.inboundRTP.framesReceived&&f.inboundRTP.framesDecoded&&(v.framesReceived=f.inboundRTP.framesReceived,v.framesDecoded=f.inboundRTP.framesDecoded),v.decoder=f.inboundRTP.decoderImplementation,v.rendererFps.isReportComplete()&&v.incomingFps.isReportComplete()&&v.decodeTimeTracker.isReportComplete()&&(this.paused=!0,await this.checkQuality(v,g.perfCounters,g.video?.recv?.length),this.paused=!1)}))}catch(g){this.logger.error("Failed to processes diagnostics update: "+g)}}async checkQuality(g,f,S){if(!S)return;const v=[];let C;try{C=await(this.cpuMetricCollector?.getCurrentCpuSample())}catch{this.logger.safe.debug("CPU sampling is not supported")}const _={ts:Date.now(),trackId:g.id,decodeTime:g.decodeTimeTracker.getReport(),macroblockLossPercent:g.macroblockLossTracker.getReport(),macroblockMaxLossPercent:g.macroblockMaxLossTracker,freezeDurationPercent:g.freezeDurationPercent,perfCounters:f,cpuUsage:C,rendererFps:g.rendererFps.getReport(),incomingFps:g.incomingFps.getReport(),framesDecoded:g.framesDecoded,framesReceived:g.framesReceived,msi:g.msi,frameHeight:g.frameHeight,decoder:g.decoder};v.push(_);const T=this.calculatorStrategy.checkQuality(g);if(0===T){if(this.logger.safe.debug(`Bad perf detected for msi ${g.msi}: ${JSON.stringify(v)}`),this.configProvider.config.diagnostics.performanceMonitoring.usePerfConstrainedOvc&&!ei.Recv.getNextLowerResolution(g.frameWidth,g.frameHeight)){const g=Math.max(S-1,1);return this.logger.info(`Min resolution reached, decreasing OVC to: ${g}`),this.diagnostics.registerVideoPerformanceEvent(v,1,g),this.event("calculatorStateChanged").raise(2,{ovc:g}),void this.perfTrackerMap.clear()}this.diagnostics.registerVideoPerformanceEvent(v,1),this.event("calculatorStateChanged").raise(1,{msi:g.msi})}2===T&&(this.diagnostics.registerVideoPerformanceEvent(v,0),this.logger.safe.debug(`Good perf detected for msi ${g.msi}: ${JSON.stringify(v)}`),this.event("calculatorStateChanged").raise(0,{msi:g.msi})),this.perfTrackerMap.delete(g.msi)}},FA=class extends Ht{constructor(g,f,S,v){super(),this.statsGatherer=g,this.diagnostics=f,this.configProvider=S,this.logger=v,this.calculators=new Map,this.subs=[]}on(g,f){switch(g){case"onIncomingVideoQualityChanged":this.addCalculator(0),this.startCalculator(0);break;case"onOptimalVideoCountChanged":this.addCalculator(2),this.startCalculator(2)}return this.subscribe({changed:void 0,on:{name:String(g),handler:f}})}addCalculator(g){let f=this.calculators.get(g);if(!f){switch(g){case 0:if(!this.configProvider.config.diagnostics.performanceMonitoring.enableRemoteVideoCalculator)return;f=new LA(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("RemoteVideoPerformanceCalculator"));break;case 2:if(!this.configProvider.config.enableOptimalVideoCount)return;f=new wA(this.configProvider,this.logger.createChild("OptimalVideoCountCalculator"));break;case 1:throw new Error("Not implemented")}this.subs.push(f.on("calculatorStateChanged",((f,S)=>{this.handleChanged(g,f,S)}))),this.calculators.set(g,f)}}startCalculator(g){this.logger.safe.debug(`adding calculator with id ${g}`);const f=this.calculators.get(g);f&&f.start()}stopCalculator(g){this.logger.safe.debug(`stopping calculator with id ${g}`);const f=this.calculators.get(g);f&&f.stop()}processNotification(g,f){switch(g){case"BandwidthNotification":this.calculators.get(2)?.processEstimatedBandwidth(f.bw);break;case"ParticipantCountChanged":this.calculators.get(2)?.updateParticipantCount(f.count);break;case"McpSourceRequestsAvailable":this.calculators.get(2)?.mcpSourceRequestsAvailable();break;default:this.logger.safe.info(`Notification message handler not found for type: ${g}`)}}dispose(){super.dispose(),this.calculators.forEach((g=>{g.dispose()})),this.subs.forEach((g=>{g.dispose()}))}handleChanged(g,f,S){switch(this.logger.info(`calculatorStateChanged  ${f}: calculatorType ${g} ${JSON.stringify(S)}`),g){case 0:if(2===f){this.calculators.get(2)?.setPerfConstrainedValue(S?.ovc);break}this.configProvider.config.diagnostics.performanceMonitoring.enableLowerResolution&&this.event("onIncomingVideoQualityChanged").raise(f,S?.msi);break;case 2:this.event("onOptimalVideoCountChanged").raise(S?.ovc,S?.ovcPayload)}}},xA=M,UA=class{constructor(g){this.configProvider=g,this.outboundNetworkQuality="Good",this.inboundNetworkQuality="Good",this.jitterAccumulator=new Uv(this.configProvider.config.webrtcJitterWindowSize),this.healedRatioAccumulator=new Uv(this.configProvider.config.webrtcHealedRatioWindowSize),this.jitterStateProcessor=new uI(g.config.webrtcJitterLowThreshold,g.config.webrtcJitterHighThreshold,!0,g.config.webrtcJitterSticknessTime),this.lossRateStateProcessor=new uI(g.config.webrtcLossRateLowThreshold,g.config.webrtcLossRateHighThreshold,!0,g.config.webrtcLossRateSticknessTime)}processReport(g){g.audio?.recv?.length&&(this.inboundNetworkQuality=this.processInboundSample((0,xA.last)(g.audio.recv))),g.audio?.send?.length&&(this.outboundNetworkQuality=this.processOutboundSample((0,xA.last)(g.audio.send)))}getInboundNetworkQuality(){return this.inboundNetworkQuality}getOutboundNetworkQuality(){return this.outboundNetworkQuality}processInboundSample(g){const f=this.inboundNetworkQuality,{totalSamplesReceived:S}=g.inboundRTP,{healedRatio:v}=g.extensions??{};null!=v&&this.healedRatioAccumulator.add(v);const C=(0,xA.mean)(this.healedRatioAccumulator.items);return!S||S<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality?f:C&&this.healedRatioAccumulator.isFull?this.determineInboundQualityLevel(C):f}determineInboundQualityLevel(g){const f=this.inboundNetworkQuality,S=this.configProvider.config.webrtcStatNetworkDetectionHysteresis,v=this.configProvider.config.webrtcStatNetworkDetectionBadLevel,C=this.configProvider.config.webrtcStatNetworkDetectionGoodLevel;return g<C-S/2?"Good":g<C+S/2?"Good"===f?"Good":"Poor":g<v-S/2?"Poor":g<v+S/2?"Bad"===f?"Bad":"Poor":"Bad"}processOutboundSample(g){const f=this.outboundNetworkQuality,{packetsSent:S,timestamp:v}=g.outboundRTP,{jitter:C}=g.remoteInboundRTP??{},{lossRate:_}=g.extensions??{};if(!S||S<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return f;null!=C&&this.jitterAccumulator.add(C);const T=(0,xA.mean)(this.jitterAccumulator.items),I=this.jitterAccumulator.isFull?this.jitterStateProcessor.onSample(T,v):"Good",b=_?this.lossRateStateProcessor.onSample(_,v):"Good";return"Good"===I&&"Good"===b?"Good":"Bad"}},VA=M,BA=class{constructor(g){this.configProvider=g,this.speechWindow=new Uv(g.config.webrtcSpeakingWhileMutedDetectionWindow)}processReport(g){if(!g.audio?.send?.length)return!1;const f=g.audio.send[0],{rawInputVolume:S,callIsMuted:v}=f.extensions??{},{audioLevel:C}=f.mediaSource??{},{useAudioAnalyzer:_,webrtcSpeakingWhileMutedDetectionLevel:T}=this.configProvider.config;if(!v)return this.speechWindow.clear(),!1;const I=_?S:C;return null!=I&&this.speechWindow.add(I),!!this.speechWindow.isFull&&(0,VA.mean)(this.speechWindow.items)>T}},HA=class{constructor(g){this.context=g,this.cname=uniqueId()}toLocal(g,f,S){return this.modify({sdpSource:0,sdpType:S},g,f)}toOffer(g,f,S){return this.modify({sdpSource:1,sdpType:"offer"},g,f,S)}toAnswer(g,f,S){return this.modify({sdpSource:1,sdpType:"answer"},g,f,S)}toRemote(g,f,S,v,C=!1){return this.modify({sdpSource:2,sdpType:v,isOrWasProvisional:C},g,f,S)}modify(g,f,S,v){const C=new EE(this.context,S,v,this.cname).build(g),_=deepClone(f);return C.modify(_),_}},$A=class{get sdp(){return this.originalDescription.sdp}set sdp(g){this.originalDescription=new Xs.window.RTCSessionDescription({sdp:g,type:this.originalDescription.type})}get type(){return this.originalDescription.type}set type(g){this.originalDescription=new Xs.window.RTCSessionDescription({sdp:this.originalDescription.sdp,type:g})}constructor(g){this.originalDescription=new Xs.window.RTCSessionDescription(g)}toJSON(){return this.originalDescription.toJSON()}},jA=class{constructor(g,f,S,v,C,_,T,I,b,A,P){this.logger=g,this.configProvider=f,this.diagnostics=S,this.reinvitelessContext=v,this.mediaManager=C,this.audioCodecManager=_,this.ufdManager=T,this.sessionContext=I,this.qualityManager=b,this.streamSendersManager=A,this.callbacks=P,this.negotiationQueue=new zC(this.logger),this.negotiatedModalitiesInternal={},this.disabledModalitiesInternal={},this.initiatorInternal=!1,this.noIceCandidates=!1,this.noRelayIceCandidates=!1,this.isRollbackSupported=!1,this.canTriggerRenegotiation=!0,this.triggerRenegotiationFlag=!1,this.capabilityGatherer=nb.build({global:this.sessionContext.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround),this.mediaContentTypeInternal=getFrom("webrtcMediaContentType",this.sessionContext.config,this.configProvider.config),this.allowedMediaContentTypeInternal=getFrom("webrtcAllowedMediaContentType",this.sessionContext.config,this.configProvider.config).concat(),this.useNGC1webrtcContentType=getFrom("useNGC1webrtcContentType",this.sessionContext.config,this.configProvider.config),this.negotiationCompletedDefer=new dt,this.iceCandidatesDeferred=new dt,this.iceCandidateReceivedInternal=!1,this.initialNegotiationCompleted=!1,this.terminated=!1,this.sessionDescription=V_.build({sdpTransform:new HA(this.sessionContext),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:{unifiedPlanEnabled:!0,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}),this.negotiationEmulator=new mb(this.logger.createChild("negotiationEmulator"),$A,this.sessionDescription,this.negotiationQueue,this.mediaManager),this.negotiationCompletedDefer.promise.catch((()=>{})),this.negotiationCompletedDefer.reject("placeholder")}get configuredModalities(){return this.configuredModalitiesInternal}get offeredModalities(){return this.offeredModalitiesInternal}get disabledModalities(){return this.disabledModalitiesInternal}get negotiatedModalities(){return this.negotiatedModalitiesInternal}get allowedMediaContentType(){return this.allowedMediaContentTypeInternal}get negotiationCompletedPromise(){return this.negotiationCompletedDefer}get iceRelayGatheringStartTime(){return this.iceRelayCandidatesGatherStartTime}get iceCandidatesDefer(){return this.iceCandidatesDeferred}get initiator(){return this.initiatorInternal}set rollbackSupported(g){this.isRollbackSupported=g}set iceCandidateReceived(g){this.iceCandidateReceivedInternal=g}get mediaContentType(){return this.useNGC1webrtcContentType?qt.CONTENT_TYPE.SDP_NGC:this.mediaContentTypeInternal}setInternals(g,f,S){this.logger.safe.debug(`Setting internals tm: ${!!g} tsp: ${!!f} dc: ${!!S}`),this.transceiverManager=g,this.transportStateProvider=f,this.dataChannel=S}terminate(g){this.logger.safe.info(`[${g}] terminating`),this.terminated=!0,this.canTriggerRenegotiation=!1,this.negotiatedModalitiesInternal={},this.resetCandidateGathering(g),this.negotiationCompletedDefer.reject("webRtcSession cleanup"),this.negotiationQueue.dispose()}pauseNegotiations(g=generateCauseId()){const f=new dt;return this.negotiationCompletedDefer.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(f,g)})),f}async configureModalities(g,f,S){const getPendingPromise=async()=>{if(await this.configureModalitiesPromise,!g.audio&&!g.video&&!g.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(g)}`);const v=shallowClone(g),C=shallowClone(this.negotiatedModalities);this.configProvider.config.alwaysNegotiateDataChannel&&(delete v.data,delete C.data);const _=!this.configuredModalities||!areNegotiatedDirectionsFulfilled(v,C);this.logger.safe.info(`[${f}] configureModalities ${stringifyObject(this.configuredModalities)} -> ${stringifyObject(g)} (${_?`update from ${stringifyObject(this.negotiatedModalities)}`:"fulfilled"})`),this.configuredModalities=g,_&&!this.updateSendStreamsReinviteless(f,S)&&(this.configProvider.config.removeSendersOnConfigureModalities&&!isOnHold(this.configuredModalities)&&await this.streamSendersManager.update(g,1,f),this.triggerRenegotiation(!1,f,S))};return this.configureModalitiesPromise=getPendingPromise(),this.configureModalitiesPromise.catch((g=>{this.logger.safe.warn(`[${f}] Error during configuring modalities: ${stringifyObject(g)}`)})),this.configureModalitiesPromise}async completeNegotiation(g){this.mediaManager.commit();let f=areNegotiatedDirectionsAcceptable(this.configuredModalities,this.negotiatingModalities,this.negotiatedModalities)&&!this.triggerRenegotiationFlag;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${g}] negotiation completed isComplete: ${f} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`);let S=this.negotiatedModalities;if(this.streamSendersManager.pendingStreamsPromise){this.logger.safe.info(`[${g}] Waiting for stream acquisitions to complete...`);const v=await this.streamSendersManager.pendingStreamsPromise;this.streamSendersManager.clearStreamsPromise(),this.logger.safe.info(`[${g}] Stream acquisitions completed: ${stringifyObject(v)}`),areNegotiatedDirectionsAcceptable(v,this.negotiatingModalities,this.negotiatedModalities)||(this.logger.safe.warn(`[${g}] Some streams were not acquired successfully, considering the negotiation as incomplete`),S=v,f=!1)}return f||this.triggerRenegotiation(!1,g),this.initialNegotiationCompleted=!0,this.negotiationCompletedDefer.resolve(),{isComplete:f,activeModalities:S,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiatorInternal}}async rejectNegotiation(g,f,S=!1){let v;this.mediaManager.rollback(),this.logger.safe.warn(`[${f}] negotiation rejected isComplete: ${!S} error: ${stringifyObject(g)} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),this.qualityManager.clearPendingCapabilities();const C=removeChangedSendDirection(this.negotiatedModalities,this.negotiatingModalities);this.logger.safe.debug(`[${f}] configured modalities for rollback: ${JSON.stringify(C)}`),this.transceiverManager?.syncTransceivers(C),this.sessionContext.getSmallCallTelemetry()?.setEventType("rejectNegotiation"),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data);const _=isOnHold(C);isOnHold(this.negotiatedModalities)!==_&&await this.streamSendersManager.setHold(_,f),_?this.logger.safe.info(`[${f}] Hold is configured. Not updating streams`):await this.streamSendersManager.update(C,0,f);const T=this.transportStateProvider?.signalingState;if("have-local-offer"===T){v={},this.logger.safe.info(`[${f}] rolling back local description`);try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRollback){v.type="LocalRN",this.logger.safe.info(`[${f}] rolling back using local renegotiation`);const g=[this.callbacks.getRollbackModifier(this.logger)];await this.negotiationEmulator.renegotiate(g,!0),this.logger.safe.info(`[${f}] rolling back using local complete`)}else this.logger.safe.info(`[${f}] rolling back using rollback`),v.type="Rollback",await this.callbacks.setLocalDescription({type:"rollback"})}catch(g){this.logger.safe.error(`[${f}] rollback error: ${stringifyObject(g)}`),v.error=g}}else if("have-remote-offer"===T){v={};try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRemoteRollback){v.type="RemoteRN",this.logger.safe.info(`[${f}] applying answer for remote renegotiation`);const g=[this.callbacks.getRollbackModifier(this.logger)];await this.negotiationEmulator.renegotiate(g,!0,"remote")}else this.logger.safe.info(`[${f}] rolling back using rollback on remote description`),v.type="Rollback",await this.callbacks.setRemoteDescription({type:"rollback"})}catch(g){this.logger.safe.error(`[${f}] rollback error: ${stringifyObject(g)}`),v.error=g}}else this.callbacks.hasPC()&&this.logger.safe.error(`[${f}] cannot rollback local description in current state: ${this.transportStateProvider.signalingState}`);return this.canTriggerRenegotiation=!0,this.negotiationCompletedDefer.reject("negotiation rejected"),S&&(this.logger.safe.info(`[${f}] retrying failed negotiation`),this.triggerRenegotiation(!1,f)),{isComplete:!S,activeModalities:C,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiatorInternal,rollback:v}}triggerRenegotiation(g,f=generateCauseId(),S){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${f}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired(f,S)):g&&(this.logger.safe.info(`[${f}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}configureCrypto(g,f){let S=!1;const v=preferSdesSrtp(this.configProvider,f);if(this.offeredDescription){const g=this.offeredDescription.getSrtpInfo();this.diagnostics.offeredSrtp=g,S=!g.dtls||g.sdes&&v}else S=v;return S&&(this.logger.safe.info("configuring peer connection to use sdes"),g.optional.push({DtlsSrtpKeyAgreement:!1})),this.diagnostics.negotiatedSrtp={dtls:!S,sdes:!!S},S?0:1}createOffer(g,f){const S=this.negotiationQueue.add((()=>this.createOfferAsync(g,f)),g);return this.resetNegotiationQueue(g),S}processOffer(g,f){const S=this.negotiationQueue.add((()=>this.processOfferAsync(g,f)),f);return this.resetNegotiationQueue(f),S}async createAnswer(g,f){if((this.sessionContext.config.isPstnCall?!this.configProvider.config.createProvisionalAnswer.enabledPstn:!this.configProvider.config.createProvisionalAnswer.enabled)&&g)return this.logger.safe.info("createAnswer(): Ignoring provisional answer"),{blob:"",contentType:this.mediaContentType};const S=g?"pranswer":"answer",v=g?"createProvisionalAnswerAsync":"createAnswerAsync",C=this.diagnostics.getTimerTracker(v,{first:!0});if(C.mark("start"),this.logger.safe.info(`[${f}] create [${S}] offered: ${JSON.stringify(this.offeredModalities)} configured: ${JSON.stringify(this.configuredModalities)}`),!this.configuredModalities)throw new Error("no configured modalities to create answer for");let _=this.negotiatingModalities=negotiateModalities(this.offeredModalities,this.configuredModalities);await this.callbacks.assurePC(f,C.clone("assurePeerConnectionAsync"));const T=this.transportStateProvider.isWaitingAcceptProvisional;if(this.transportStateProvider.isWaitingAcceptProvisional=g,C.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${f}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.transportStateProvider.signalingState)}`),!this.offeredDescription.isCodecSwitchSupported())try{const g=(await this.capabilityGatherer.getCapabilities(qt.MEDIA_TYPE.audio)).codecs.map((g=>g.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(g)}catch(g){this.logger.safe.error(`[${f}] failed to set primary codec based on audio capability ${stringifyObject(g)}`)}C.markAndMeasure("assurePeerConnectionAsync","handleCodecSwitchUnsupported"),this.audioCodecManager.prepareForNegotiation(this.initiatorInternal),this.offeredDescription.setModalities(_),await this.detectSendProfileSupport();const I=this.offeredDescription.toRemote(g||T);this.configProvider.config.createProvisionalAnswer.streamsBeforeSetFullRD&&!g&&T&&["have-remote-offer","stable"].includes(this.transportStateProvider.signalingState)&&!this.initialNegotiationCompleted&&(this.logger.safe.info(`[${f}] create [${S}] provisional was applied, requesting streams and activating senders before set remote description is finished`),await this.updateStreamSenders(C,f,g,_)),this.logger.unsafe.info(`[${f}] create [${S}] set remote description', 'negotiated:`,_,"sdp:",I),await this.callbacks.setRemoteDescription({sdp:I,type:"offer"}),C.markAndMeasure("handleCodecSwitchUnsupported","setRemoteDescription"),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data),await this.updateStreamSenders(C,f,g,_),C.markAndMeasure("assurePeerConnectionAsync","assureStreamsAndDataChannel"),C.markAndMeasure("setRemoteDescription","assureStreamsAndDataChannel"),this.callbacks.onTransportInitialized();const b=this.configProvider.config.createProvisionalAnswer.setProperAnswerType?await this.callbacks.createAnswer({type:S}):await this.callbacks.createAnswer();C.markAndMeasure("assureStreamsAndDataChannel","createAnswer"),this.logger.unsafe.info(`[${f}] create [${S}] answer from peer connection type: ${b.type}, sdp:`,b.sdp);const A=this.sessionDescription.createLocalAnswer(b.sdp);this.hasIceCandidates(A)||this.resetCandidateGathering(f),this.callbacks.startWaitingForStreamStart(_),this.setupIceGatheringTimeout(f);const P=A.toLocal();this.logger.unsafe.info(`[${f}] create [${S}] set local description sdp:`,P),await this.callbacks.setLocalDescription({sdp:P,type:this.configProvider.config.createProvisionalAnswer.setProperAnswerType?S:"answer"}),C.markAndMeasure("createAnswer","sLD"),await this.iceCandidatesDeferred.promise,C.markAndMeasure("sLD","candidates");const R=this.sessionDescription.createLocalAnswer(this.callbacks.getLocalDescription().sdp);this.fixLocalDescription(R),R.updateModalities(_),this.checkIceCandidates(R),g&&this.configProvider.config.createProvisionalAnswer.forceRecvonly&&(this.logger.safe.info(`[${f}] create [${S}] munge returned local sdp to recvonly modalities`),R.forceRecvonly());const M=R.toAnswer();this.audioCodecManager.decoder?.setRecvPayloads(R.getPayloadsForMedia(qt.MEDIA_TYPE.audio)),this.checkAudioCodecNegotiated(f),g?this.logger.safe.debug(`[${f}] create [${S}] skip stream senders manager activation`):(this.logger.safe.debug(`[${f}] create [${S}] activating stream senders manager`),await this.streamSendersManager.activate(f)),C.markAndMeasure("candidates","streamSendersManagerActivate"),g?this.logger.safe.debug(`[${f}] create [${S}] skip updating sources and capabilities`):(this.logger.safe.debug(`[${f}] create [${S}] updating sources and capabilities`),this.callbacks.updateLocalMediaSources(),this.applyReceiveCapabilities(f)),_=R.getModalities(),this.reinvitelessContext.enabled&&(_=removeChangedSendDirection(this.negotiatingModalities,_)),areNegotiatedDirectionsAcceptable(this.configuredModalities,this.negotiatingModalities,_)||this.triggerRenegotiation(!0,f),this.negotiatedModalities=_,this.diagnostics.bweType=R.getBweType(),this.logger.unsafe.info(`[${f}] CREATE ANSWER`,"sdp:",M);const w={blob:M,contentType:this.mediaContentType};return this.configProvider.countryCode&&(w.clientLocation=this.configProvider.countryCode),this.reinvitelessContext.enabled&&(w.mediaDescriptions=this.getMediaDescriptions(_)),this.callbacks.setBWSeed(w),C.markAndMeasure("start",v),w}async detectSendProfileSupport(){if(this.configProvider.config.preferredH264VideoSendProfile||this.configProvider.config.preferredH264SharingSendProfile){let g=this.capabilityGatherer;this.configProvider.config.learnCodecSendCapabilitiesFromSenderApi&&(g=nb.build({global:this.sessionContext.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround,!0));const f=await g.getCapabilities("video"),S=this.mediaManager.getMediaEntities().filter((g=>{const f=g.getModality();return f===qt.MEDIA_TYPE.video||f===qt.MEDIA_TYPE.sharing})).filter((g=>g.isEnabled()));for(const g of f.codecs)if(g.sdpFmtpLine&&g.mimeType.toLocaleLowerCase().includes("h264")){const f=g.sdpFmtpLine.match(/profile-level-id=([a-fA-F0-9]{6})/);2===f?.length&&S.forEach((g=>g.addSupportedSendProfile("H264",f[1])))}}}async updateStreamSenders(g,f,S,v){this.transceiverManager.syncTransceivers(v),this.mediaManager.getMediaEntities().forEach((g=>{g.setExtension("midApplied",!0)}));const C=isOnHold(this.negotiatingModalities);if(isOnHold(this.negotiatedModalities)!==C&&(g?.mark("startConfigureHold"),await this.streamSendersManager.setHold(C,f),g?.markAndMeasure("startConfigureHold","configureHold")),C)this.logger.safe.info(`[${f}] Hold is configured. Not updating streams`);else{let C=this.configProvider.config.negotiationParallelStreamAcquisitionCreateAnswer&&!this.initialNegotiationCompleted?2:0;S&&(C=4),await this.streamSendersManager.update(v,C,f),g?.markAndMeasure("configureHold","updateStreams")}}configureBroadcastScenario(g,f){const S=this.configProvider.config.broadcastMode;if(this.diagnostics.meetingScenario=g.meetingScenario,(S?.prioritizeLayoutOnServer||S?.prioritizeLayoutOnClient||S?.maxSessionBandwidthKbps)&&g.meetingScenario&&S.townHallScenarioNames?.length){-1!==S.townHallScenarioNames.map((g=>g.toLowerCase())).indexOf(g.meetingScenario.toLowerCase())&&(this.sessionContext.config.isTownHall=!0,this.diagnostics.isTownHall=!0,S?.maxSessionBandwidthKbps&&this.configProvider.overrideMaxSessionBandwidth(S.maxSessionBandwidthKbps)&&(this.logger.safe.info(`Adjusting maxSessionBandwidth for TownHall: ${this.configProvider.mediaConfig.maxBandwidthInKbps}`),this.triggerRenegotiation(!0,f)))}}async processAnswer(g,f,S,v=!1){try{const C=g.blob;this.logger.unsafe.debug(S?`[${f}] PROCESS PRANSWER`:`[${f}] PROCESS ANSWER`,"sdp:",C);const _=S?"pranswer":"answer";if(S&&(!acceptProvisionalAnswer(this.sessionContext,v)||"have-local-offer"!==this.transportStateProvider.signalingState))return void this.logger.safe.info(`[${f}] process [${_}] ignored`);this.configureBroadcastScenario(g,f);const T=this.diagnostics.getTimerTracker(""+(S?"processProvisionalAnswerAsync":"processAnswerAsync"),{first:!0});T.mark("start");const I=this.sessionDescription.createRemoteAnswer(C);let b=invertModalities(I.getModalities());this.reinvitelessContext.enabled&&(b=removeChangedSendDirection(this.offeredModalities,b)),I.setModalities(b),await this.detectSendProfileSupport();const A=I.toRemote();if(S||(this.useNGC1webrtcContentType||(this.mediaContentType=g.contentType),-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType),isOnHold(b)||(await this.streamSendersManager.update(b,1,f),T.markAndMeasure("start","streamSendersManagerUpdate"),hasSendDirectionality(this.offeredModalities.data)&&!b.data&&this.dataChannel?.disable()),this.negotiatedModalities=b,this.callbacks.updateLocalMediaSources(),this.diagnostics.bweType=I.getBweType()),this.callbacks.onTransportInitialized(),this.logger.unsafe.info(`[${f}] process [${_}] set remote description`,"negotiated:",b,"sdp:",A),T.mark("startSetRemoteDescription"),await this.callbacks.setRemoteDescription({sdp:A,type:_}),T.markAndMeasure("startSetRemoteDescription","setRemoteDescription"),S)return;await this.streamSendersManager.activate(f),T.markAndMeasure("setRemoteDescription","streamSendersManagerActivate"),this.applyReceiveCapabilities(f),this.checkAudioCodecNegotiated(f),this.transceiverManager.syncTransceivers(b),T.markAndMeasure("start","processAnswerAsync")}catch(g){if(S)return void this.logger.safe.warn(`Error thrown during pranswer generation, ignoring: ${stringifyObject(g)}`);throw g}}async createOfferAsync(g,f){const S=this.diagnostics.getTimerTracker("createOfferAsync",{first:!0});if(S.mark("start"),this.logger.safe.info(`[${g}] create [offer] configured: ${JSON.stringify(this.configuredModalities)}`),this.initiatorInternal=!0,!this.configuredModalities)throw new Error("no configured modalities to create offer for");this.canTriggerRenegotiation=!1,this.negotiatingModalities=this.configuredModalities,await this.callbacks.assurePC(g,S.clone("assurePeerConnectionAsync")),S.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${g}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.transportStateProvider.signalingState)}`),isOnHold(this.negotiatingModalities)&&!isEmpty(this.negotiatedModalities)&&Object.keys(this.negotiatingModalities).forEach((g=>{void 0===this.negotiatedModalities[g]&&delete this.negotiatingModalities[g]})),this.transceiverManager?.assureTransceivers(this.negotiatingModalities),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data);const v=isOnHold(this.negotiatingModalities);let C;isOnHold(this.negotiatedModalities)!==v&&(S?.mark("startConfigureHold"),await this.streamSendersManager.setHold(v,g),S?.markAndMeasure("startConfigureHold","configureHold")),v?(this.logger.safe.info(`[${g}] Hold is configured. Not updating streams`),C=this.negotiatingModalities):(C=await this.streamSendersManager.update(this.negotiatingModalities,this.configProvider.config.negotiationParallelStreamAcquisitionCreateOffer&&!this.initialNegotiationCompleted?2:0,g),S?.markAndMeasure("configureHold","updateStreams"),this.dataChannel&&this.negotiatingModalities.data&&(C.data=this.negotiatingModalities.data)),S.markAndMeasure("assurePeerConnectionAsync","assureStreamsAndDataChannel"),this.offeredModalities=C,!allowDataChannel(this.sessionContext)&&this.configProvider.config.webrtcNegotiateDisabledDataModality&&!this.offeredModalities[qt.MODALITY.data]&&this.sessionContext.config?.isConference&&(this.offeredModalities[qt.MODALITY.data]=qt.MEDIA_STATE.inactive),this.audioCodecManager.prepareForNegotiation(this.initiatorInternal),this.logger.safe.info(`[${g}] create [offer] offered: ${JSON.stringify(this.offeredModalities)}`);const _=await this.callbacks.createOffer();S.markAndMeasure("assureStreamsAndDataChannel","createOffer"),this.logger.unsafe.info(`[${g}] create [offer] offer from peer connection, sdp: ${_.sdp}`);const T=this.sessionDescription.createLocalOffer(_.sdp);this.hasIceCandidates(T)||this.resetCandidateGathering(g),this.callbacks.startWaitingForStreamStart(C),this.setupIceGatheringTimeout(g);const I=T.toLocal();this.logger.unsafe.info(`[${g}] create [offer] set local description`,"sdp:",I),await this.callbacks.setLocalDescription({sdp:I,type:"offer"}),S.markAndMeasure("createOffer","sLD"),await this.iceCandidatesDeferred.promise,S.markAndMeasure("sLD","candidates");const b=this.sessionDescription.createLocalOffer(this.callbacks.getLocalDescription().sdp);this.fixLocalDescription(b),b.updateModalities(this.offeredModalities),this.checkIceCandidates(b);const A=b.toOffer();this.logger.unsafe.info(`[${g}] CREATE OFFER`,"sdp:",A);const P={blob:A,contentType:this.mediaContentType};""===this.configProvider.mediaConfig.webrtcRequiredFeatures||this.sessionContext.config.isConference||(P.requiredFeatures=this.configProvider.mediaConfig.webrtcRequiredFeatures),this.audioCodecManager.decoder?.setRecvPayloads(b.getPayloadsForMedia(qt.MEDIA_TYPE.audio)),this.configProvider.countryCode&&(P.clientLocation=this.configProvider.countryCode),this.mediaManager.getMediaEntities().forEach((g=>{g.setExtension("midApplied",!0)}));const R=T.isIceRestart();return this.logger.safe.info(`[${g}] ICE restart: ${R}`),this.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription?.isMSRTC()&&R&&!this.sessionContext.config.isConference&&T.getSrtpInfo().sdes&&(P.newOffer=!0),this.reinvitelessContext.enabled&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),P.mediaDescriptions=this.getMediaDescriptions(this.offeredModalities)),f&&(P.negotiationTag=f),this.callbacks.setBWSeed(P),S.markAndMeasure("start","createOfferAsync"),P}async processOfferAsync(g,f){const S=this.diagnostics.getTimerTracker("processOfferAsync",{first:!0});S.mark("start"),this.mediaManager.backup();const v=g.blob;if(this.logger.unsafe.info(`[${f}] process [offer]`,"sdp:",v),this.configProvider.config.webrtcCompareContentTypeInOffer&&!this.useNGC1webrtcContentType&&(assertContentTypeSupported(g.contentType,this.allowedMediaContentType),this.mediaContentType=g.contentType),this.configureBroadcastScenario(g,f),this.offerOriginator&&this.offerOriginator!==g.originator&&this.configProvider.config.rejectIncompatibleOriginator)throw{detail:"mediaContent.originator is different on renegotiation",type:qt.MEDIA_ERROR.incompatibleOriginator};if(this.offerOriginator=g.originator,g.requiredFeatures){const f=this.configProvider.mediaConfig.webrtcRejectedFeatures.split(",");throwIfFeatureNotSupported(g.requiredFeatures.split(","),f)}if(this.initiatorInternal=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(v),this.configProvider.config.multiStreamSupported){const g=getMultiStreamCountFromSdp(v),S=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;this.configProvider.mediaConfig.multiStreamChannelsOffered=g,g<S&&(this.logger.safe.info(`Received ${g} multi stream channels, ${S} channels supported`),this.triggerRenegotiation(!0,f))}this.canTriggerRenegotiation=!1,this.offeredModalities=invertModalities(this.offeredDescription.getModalities()),this.callbacks.hasPC()||(this.configProvider.mediaConfig.isTransportUnbundled?this.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.couldBeUnbundled():this.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.isUnbundled());let C=this.configProvider.config.removeUnsupportedVideoModality?this.offeredModalities:shallowClone(this.offeredModalities);if(hasSendDirectionality(this.offeredModalities.video)||hasReceiveDirectionality(this.offeredModalities.video)||hasSendDirectionality(this.offeredModalities.sharing)||hasReceiveDirectionality(this.offeredModalities.sharing)){const g=this.offeredDescription.getVideoCodecs();try{S.mark("startGetCapabilities");const v=await this.capabilityGatherer.getCapabilities("video");S.markAndMeasure("startGetCapabilities","getCapabilities");v.codecs.some((f=>g.some((g=>f.mimeType===g&&this.configProvider.config.primaryVideoCodecs.includes(g)))))||(this.logger.safe.warn(`[${f}] offer doesn't contain any supported video codecs`),this.disabledModalities.video=C.video,this.disabledModalities.sharing=C.sharing,delete C.video,delete C.sharing)}catch(g){this.logger.safe.error(`[${f}] failed to get video capability ${stringifyObject(g)}`)}}return(!allowDataChannel(this.sessionContext)&&(hasSendDirectionality(this.offeredModalities.data)||hasReceiveDirectionality(this.offeredModalities.data))||"Failed"===this.dataChannel?.state)&&(this.logger.safe.info(`[${f}] Supressing data modality as data channel is not possible`),C=shallowClone(C),delete C.data),S.markAndMeasure("start","processOfferAsync"),this.logger.safe.info(`[${f}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(C)}`),C}async startMediaDescriptionsUpdate(g,f){this.dataChannel?.updateDataModalityState(this.reinvitelessRequestedModalities?.data);const S=isOnHold(this.negotiatedModalities),v=isOnHold(this.reinvitelessRequestedModalities);return S!==v&&await this.streamSendersManager.setHold(v,g),v?this.reinvitelessAppliedModalities=this.reinvitelessRequestedModalities:(this.reinvitelessAppliedModalities=await this.streamSendersManager.update(this.reinvitelessRequestedModalities,0,g),this.dataChannel&&this.reinvitelessRequestedModalities.data&&(this.reinvitelessAppliedModalities.data=this.reinvitelessRequestedModalities.data)),this.callbacks.updateLocalMediaSources(),await this.streamSendersManager.activate(g),this.getMediaDescriptions(this.reinvitelessAppliedModalities,f)}async completeMediaDescriptionsUpdate(g){this.logger.safe.info(`[${g}] complete media descriptions update`),this.negotiatedModalities=this.reinvitelessAppliedModalities;const f=this.reinvitelessAppliedModalities,S=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:f,requestedModalities:S}}async rejectMediaDescriptionsUpdate(g,f=!1){this.logger.safe.info(`[${g}] reject media descriptions update`),f&&(this.logger.safe.info(`[${g}] trigger renegotiation after failed media descriptions update`),this.triggerRenegotiation(!1,g));const S=await this.streamSendersManager.update(this.negotiatedModalities,1,g),v=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:S,requestedModalities:v}}getMediaDescriptions(g,f){if(isOnHold(g))return{};const S=[];for(const f of this.mediaManager.getMediaEntities()){if(!f.getExtension("reinviteless"))continue;const v=g[f.getModality()],C={mid:f.getMid(),direction:!f.getLocalTrackId()&&hasSendDirectionality(v)?removeSendDirectionality(v):v};S.push(C)}return{descriptions:S,negotiationTag:f}}updateSendStreamsReinviteless(g,f){if(isEmpty(this.negotiatedModalities)||isOnHold(this.negotiatedModalities)||isOnHold(this.configuredModalities))return!1;this.reinvitelessRequestedModalities=shallowClone(this.negotiatedModalities);for(const[g,f]of Object.entries(this.configuredModalities)){const S=this.mediaManager.getMediaEntitiesByModality(g)[0];S?.getExtension("reinviteless")&&(this.reinvitelessRequestedModalities[g]=f)}return!deepEqual(this.reinvitelessRequestedModalities,this.negotiatedModalities)&&(this.callbacks.onUpdateMediaDescriptionsRequired(g,f),deepEqual(this.reinvitelessRequestedModalities,this.configuredModalities))}checkAudioCodecNegotiated(g){const f=this.audioCodecManager.negotiationCompleted();if(this.audioCodecManager.decoder?.getUnmixedAudioProvider()?.configured){const S=f?"Good":"Bad";this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable",S,"Audio",!0,g)}}fixLocalDescription(g){this.configProvider.config.insertFakeCandidateIfNeeded&&(this.iceCandidateReceivedInternal||!this.iceCandidateReceivedInternal&&this.transportStateProvider.isIceConnected)&&(this.diagnostics.fakeCandidate=g.insertFakeCandidateIfNeeded()),g.fixDataModality()}applyReceiveCapabilities(g){const f=this.mediaManager.getMediaEntities().map((g=>g.getRemoteRecvCapabilities()));this.sessionContext.config?.isConference?this.qualityManager.setPendingCapabilities():this.qualityManager.setMaxCapabilities(f,g)}resetNegotiationQueue(g){this.negotiationCompletedDefer.reject("promise expired"),this.setNegotiationPromise(new dt,g)}setNegotiationPromise(g,f=generateCauseId()){this.terminated||(this.negotiationCompletedDefer=g,this.negotiationQueue.add(this.negotiationCompletedDefer,f))}hasIceCandidates(g){return this.configProvider.mediaConfig.isTransportUnbundled?g.hasUnbundledIceCandidates():g.hasIceCandidates()}checkIceCandidates(g){const f=this.hasIceCandidates(g);if(f===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:qt.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(f){const f=this.hasRelayIceCandidates(g);if(f===this.noRelayIceCandidates){if(!f&&this.transportStateProvider.isIceConnected)return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasRelayIceCandidates(g){return this.configProvider.mediaConfig.isTransportUnbundled?g.hasUnbundledRelayIceCandidates():g.hasRelayIceCandidates()}setupIceGatheringTimeout(g){this.iceRelayCandidatesGatherStartTime=Date.now();const f=this.sessionContext.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!f)return;this.iceCandidatesTimer&&clearTimeout(this.iceCandidatesTimer);const S=this.iceCandidatesDeferred;this.iceCandidatesTimer=window.setTimeout((()=>{this.iceCandidatesTimer=void 0,S.isPending&&(this.logger.safe.warn(`[${g}] ICE candidates gathering terminated due to timeout ${f}`),S.resolve())}),f)}resetCandidateGathering(g){this.logger.safe.info(`[${g}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new dt,this.iceCandidateReceivedInternal=!1}set offeredModalities(g){this.offeredModalitiesInternal=g,this.diagnostics.offeredModalities=g}set negotiatedModalities(g){this.logger.safe.info(`setNegotiatedModalities ${JSON.stringify(g)}`),this.negotiatedModalitiesInternal=g,this.diagnostics.negotiatedModalities=g}set configuredModalities(g){this.configuredModalitiesInternal=g}set mediaContentType(g){this.mediaContentTypeInternal=g}};function acceptProvisionalAnswer(g,f=!1){const S=!g.configProvider.config.acceptProvisionalAnswerFromPstnOnly||f;return g.config.isPstnCall?g.configProvider.config.acceptProvisionalAnswerPstn&&S:g.configProvider.config.acceptProvisionalAnswer}var GA=class{constructor(g){this.mcpConfig=g,this.data={sourceRequestsSignaling:{},sourceRequestsMCP:{},fallbackMCPMessagesCounter:0,sourceRequestsResponses:{},errors:[]}}setRecord(g,f,S){const v={sequenceNumber:f,timestamp:Date.now(),sourceId:S?.sourceId,fmtp:S?.fmtParams};g.records??(g.records=[]),arrayLimitedPush2(g.records,v,this.mcpConfig.storedSRRecordsCount)}recordSignalingOperation(g,f){var S;(S=this.data.sourceRequestsSignaling)[g]??(S[g]={counter:0}),this.data.sourceRequestsSignaling[g].counter++}recordMCPOperation(g,f,S){var v;(v=this.data.sourceRequestsMCP)[g]??(v[g]={counter:0}),this.data.sourceRequestsMCP[g].counter++,this.mcpConfig.verboseTelemetry&&this.setRecord(this.data.sourceRequestsMCP[g],f,S)}recordError(g,f){const S=[Date.now(),f,g];arrayLimitedPush2(this.data.errors,S,this.mcpConfig.storedSRRecordsCount)}recordSignalingOperationDuration(g,f){const S=this.data.sourceRequestsSignaling[g]?.records?.find((g=>g.sequenceNumber===f));S&&(S.duration=Date.now()-S.timestamp)}recordMCPMessageFallback(g,f){if(this.data.fallbackMCPMessagesCounter++,this.mcpConfig.verboseTelemetry){const S=this.data.sourceRequestsMCP[f]?.records?.find((f=>f.sequenceNumber===g));S&&(S.fallback=!0,S.fallbackTimestamp=Date.now())}}recordSrResultReceived(g,f,S){var v;if(this.mcpConfig.verboseTelemetry){const v=this.data.sourceRequestsMCP[S]?.records?.find((g=>g.sequenceNumber===f));v&&(v.duration=Date.now()-v.timestamp,v.result=g)}(v=this.data.sourceRequestsResponses)[g]??(v[g]=0),this.data.sourceRequestsResponses[g]++}getObjectRef(){return this.data}},qA=5,WA=class{constructor(g){this.mcpConfig=g,this.storage={createTime:Date.now(),startedCount:0,stoppedCount:0,clientCapabilities:[],events:[]},this.sourceRequestSenderDiagnostics=new GA(this.mcpConfig)}get getSourceRequestSenderDiagnostics(){return this.sourceRequestSenderDiagnostics}logStarted(){if(this.storage.startedCount++,this.storage.startedCount>qA)return;const g={startedTs:duration(this.storage.createTime),mpCapabilities:{},sentMessages:{},recvMessages:{},sentFailed:0,recvFailed:0,cachedDshReceived:!1};this.storage.events.push(g),this.lastEventConnecting=!0}logStopped(){this.storage.stoppedCount++;const g=this.getCurrentDCSessionEvent();g&&(g.stoppedTs=duration(this.storage.createTime)),this.lastEventConnecting=!1}logSentMsg(g){var f,S;const v=this.getCurrentDCSessionEvent();v&&((f=v.sentMessages)[S=g.type]??(f[S]=0),v.sentMessages[g.type]++)}logReceivedMsg(g){var f,S;this.lastEventConnecting=!1;const v=this.getCurrentDCSessionEvent();v&&((f=v.recvMessages)[S=g.type]??(f[S]=0),v.recvMessages[g.type]++,"dsh"!==g.type||v.handshakeDuration||(v.cachedDshReceived=!0))}logHandshakeStarted(g){const f=this.getCurrentDCSessionEvent();f&&(f.handshakeStartedTs=Date.now()),this.storage.clientCapabilities=g}logHandshakeCompleted(g){const f=this.getCurrentDCSessionEvent();f&&(f.handshakeDuration||(f.handshakeDuration=duration(f.handshakeStartedTs)),f.mpCapabilities.send=g.send_capabilities,f.mpCapabilities.recv=g.receive_capabilities)}logHandshakeFailed(g){const f=this.getCurrentDCSessionEvent();f&&(f.handshakeDuration=duration(f.handshakeStartedTs),f.handshakeFailedWithError=g)}logSentFailed(g){const f=this.getCurrentDCSessionEvent();f&&(f.sentFailed++,f.lastSentFailed={ts:duration(this.storage.createTime),error:g})}logRecvFailed(g){const f=this.getCurrentDCSessionEvent();f&&(f.recvFailed++,f.lastRecvFailed={ts:duration(this.storage.createTime),error:g})}logTimeout(){if(this.storage.startedCount>=qA&&!this.lastEventConnecting)return;const g={timeoutTs:Date.now()},f=this.getCurrentDCSessionEvent();f&&(g.handshakeStartedTs=f.handshakeStartedTs),this.lastEventConnecting&&this.storage.events.pop(),this.storage.events.push(g),this.lastEventConnecting=!1}getReport(){const g=this.sourceRequestSenderDiagnostics.getObjectRef();return this.storage.sourceRequestsReport=g,this.storage}getCurrentDCSessionEvent(){const g=this.storage.events[this.storage.events.length-1];return this.storage.startedCount<=qA&&void 0!==g?.startedTs?g:null}};function duration(g){return Date.now()-g}var zA=4294967292,KA=class extends Ke{constructor(g,f,S){super(),this.dataChannel=g,this.logger=f,this.mcpConfig=S,this.mcpState="Created",this.handshakeTimeout=null,this.telemetryLogger=new WA(this.mcpConfig),this.mcpSupportedFeatures={sourceRequestsEnabled:!1,sourceRequestsResponseEnabled:!1,dominantSpeakerHistoryEnabled:this.mcpConfig?.enableDominantSpeakerHistory,senderSideBandwidthEstimationEnabled:!1},this.subscribeToDataChannel()}getTelemetryLogger(){return this.telemetryLogger}mcpFeaturesSupported(g){return this.mcpSupportedFeatures[g]}switchMcpFeature(g,f){this.logger.warn(`Switching ${g} to ${f}`),this.mcpSupportedFeatures[g]=f}getConfig(){return this.mcpConfig??{}}getMcpState(){return this.mcpState}dispose(){super.dispose(),clearTimeout(this.handshakeTimeout),this.handshakeTimeout=null,this.mcpState="Inactive",this.switchMcpFeature("sourceRequestsEnabled",!1),this.switchMcpFeature("sourceRequestsResponseEnabled",!1)}getTelemetryReport(){return this.logger.debug(`Telemetry ${JSON.stringify(this.telemetryLogger.getReport())}`),this.telemetryLogger.getReport()}async sendMsg(g){return this.sendMsgInternal(g)}async onDCStarted(){this.logger.info("Data channel is started, starting handshake"),this.telemetryLogger.logStarted(),await this.startHandshake()}async onDCStopped(){this.logger.info("Data channel handler is stopped"),this.telemetryLogger.logStopped(),this.mcpState="Inactive"}subscribeToDataChannel(){this.dataChannel.on("onStateChanged",(()=>this.onDataChannelStateChanged())),this.dataChannel.on("onmessage",((g,f,S)=>this.processIncomingData(g,S)))}onDataChannelStateChanged(){switch(this.dataChannel.state){case"Connected":this.onDCStarted();break;case"Closed":case"Destroyed":this.onDCStopped()}}async startHandshake(){try{this.mcpState="Handshaking";const g=[];this.mcpConfig.enableDominantSpeakerHistory&&g.push("dsh"),this.mcpConfig.enableBweNotifications&&g.push("bwe"),this.mcpConfig.enableSourceRequests&&g.push("sr"),this.mcpConfig.enableSendBandwidthNotificationsEnabled&&g.push("ssbwe"),this.telemetryLogger.logHandshakeStarted(g),this.logger.info(`Send syn, client capabilities: ${JSON.stringify(g)}`),await this.sendMsgInternal({type:"syn",client_capabilities:g}),this.handshakeTimeout=window.setTimeout((()=>{this.handshakeTimeout=null,this.telemetryLogger.logTimeout(),this.mcpState="TimedOut",this.switchMcpFeature("sourceRequestsEnabled",!1),this.logger.warn(`Timeout after ${this.mcpConfig.handshakeTimeout}ms, raising onHandshakeTimeout`),this.event("onHandshakeTimeout").raise()}),this.mcpConfig.handshakeTimeout)}catch(g){this.logger.error(`Handshake failed with: ${stringifyObject(g)}`),this.telemetryLogger.logHandshakeFailed(stringifyObject(g))}}async sendMsgInternal(g){const f=Array.isArray(g)?g:[g],S=(new TextEncoder).encode(JSON.stringify(f)),v=new Uint8Array(1+S.length);v[0]=1,v.set(S,1);try{await this.dataChannel.sendMessage(18,void 0,v,[zA]);for(const g of f)this.telemetryLogger.logSentMsg(g)}catch(g){throw this.logger.error(`Send failed: ${stringifyObject(g)}`),this.telemetryLogger.logSentFailed(stringifyObject(g)),g}}processIncomingData(g,f){if(18!==g)return;if(1!==f[0]){const g=`Unsupported header version ${f[0]}`;return this.logger.info(g),void this.telemetryLogger.logRecvFailed(g)}const S=new DataView(f.buffer,1);let v;try{const g=(new TextDecoder).decode(S);v=JSON.parse(g)}catch(g){return this.logger.error(`Failed to parse received data, error ${stringifyObject(g)}`),void this.telemetryLogger.logRecvFailed(stringifyObject(g))}for(const g of v)switch(this.telemetryLogger.logReceivedMsg(g),g.type){case"syn":break;case"ack":this.processAckMsg(g);break;case"bwe":this.processBweMsg(g);break;case"dsh":this.processDshMsg(g);break;case"sr_res":this.processSrResMsg(g);break;default:{const f=`Unsupported msg type ${g.type}`;this.logger.error(f),this.telemetryLogger.logRecvFailed(f)}}}processDshMsg(g){this.mcpConfig.enableDominantSpeakerHistory&&(this.logger.debug(`DSH received: ${JSON.stringify(g)}`),this.event("mpDshChanged").raise(g.history))}processSrResMsg(g){this.mcpConfig.enableSourceRequests&&this.event("mpSrResReceived").raise(g.sequenceNumber,g.result),this.mcpState="Active"}processBweMsg(g){this.mcpConfig.enableBweNotifications&&this.event("mpSendBandwidthChanged").raise(g.bw)}processAckMsg(g){this.telemetryLogger.logHandshakeCompleted(g),this.logger.info(`Ack received: ${JSON.stringify(g)}`),this.switchMcpFeature("dominantSpeakerHistoryEnabled",!(!this.mcpConfig.enableDominantSpeakerHistory||!g.send_capabilities?.includes("dsh"))),this.switchMcpFeature("sourceRequestsEnabled",!(!this.mcpConfig.enableSourceRequests||!g.receive_capabilities?.includes("sr"))),this.switchMcpFeature("sourceRequestsResponseEnabled",!(!this.mcpConfig.enableSourceRequests||!g.send_capabilities?.includes("sr_res"))),this.switchMcpFeature("senderSideBandwidthEstimationEnabled",!(!this.mcpConfig.enableSendBandwidthNotificationsEnabled||!g.receive_capabilities?.includes("ssbwe"))),this.logger.info(`Mcp handshake completed:\n            Dominant speaker history: ${this.mcpSupportedFeatures.dominantSpeakerHistoryEnabled},\n            Source requests: ${this.mcpSupportedFeatures.sourceRequestsEnabled},\n            Source requests response: ${this.mcpSupportedFeatures.sourceRequestsResponseEnabled},\n            Bandwidth estimation response: ${this.mcpSupportedFeatures.senderSideBandwidthEstimationEnabled}`),this.event("mcpHandshakeCompleted").raise(),clearTimeout(this.handshakeTimeout),this.handshakeTimeout=null,this.mcpState="Active"}},JA=class{constructor(g,f,S){this.mediaControlPlane=g,this.sendSignalingMessage=f,this.logger=S,this.pendingSourceRequests=new Map,this.mediaControlPlane&&(this.diagnostics=this.mediaControlPlane.getTelemetryLogger().getSourceRequestSenderDiagnostics,this.mediaControlPlane.on("mpSrResReceived",((g,f)=>this.onMsgReceived(g,f))))}mapToSignalingOperation(g){switch(g){case"ApplyChannelParametersSourceRequest":case"ApplyChannelParametersVideoCapabilities":return 0;case"ControlVideoStreaming":return 1;default:return this.logger.error("Unknown send operation"),null}}send(g,f,S,v){switch(g){case"ApplyChannelParametersSourceRequest":return this.sendMcpMessage(g,f,S,v);case"ApplyChannelParametersVideoCapabilities":case"ControlVideoStreaming":return this.sendSignalingMessage?(this.diagnostics?.recordSignalingOperation(g),this.sendSignalingMessage(this.mapToSignalingOperation(g),f)):Promise.reject(new Error("no signaling session"));default:return this.logger.warn(`Unable to send message reason: Operation unknown ${g}`),Promise.reject(new Error("Unable to send message"))}}setResendingMechanism(g,f,S,v){const C=window.setTimeout((()=>{this.logger.warn(`Timed out message ${g}, sending message through signaling`),this.resendPendingMessageThroughSignaling(g,v)}),this.mediaControlPlane?.getConfig().sourceRequestsMessagesTimeout);this.pendingSourceRequests.set(g,{sequenceNumber:g,timeoutId:C,deferred:f,message:S,operation:v})}isAllowedToSendMcpMessage(){if(!this.mediaControlPlane)return!1;const g=this.mediaControlPlane.getMcpState(),f=this.mediaControlPlane.getConfig();return"Created"!==g&&("Handshaking"===g?f.sendBeforeAck&&f.enableSourceRequests:"Active"===g&&this.mediaControlPlane.mcpFeaturesSupported("sourceRequestsEnabled"))}isResendingMechanismRequired(g){return this.mediaControlPlane.getConfig().setResendingMechanism&&"ApplyChannelParametersSourceRequest"===g}async sendMcpMessage(g,f,S,v){if(this.isAllowedToSendMcpMessage()){const C=new dt;this.isResendingMechanismRequired(g)&&this.setResendingMechanism(S,C,v,g);try{return this.diagnostics.recordMCPOperation(g,S,f.controlVideoStreaming?.controlInfo),await this.mediaControlPlane.sendMsg(f),this.logger.info(`Sending ${f.type} by MCP sequenceNumber:${S}`),this.isResendingMechanismRequired(g)?C.promise:Promise.resolve()}catch(f){const v=stringifyObject(f);this.diagnostics.recordError(v,S),this.logger.error(`sendMsgInternal failed with error: ${v}`),this.isResendingMechanismRequired(g)&&this.clearPendingSourceRequestTimeout(S)}}if(!this.sendSignalingMessage)throw new Error("no signaling session");return this.diagnostics?.recordSignalingOperation(g),this.logger.info(`Sending SR by signaling sequenceNumber:${S}`),this.sendSignalingMessage(this.mapToSignalingOperation(g),v)}async resendPendingMessageThroughSignaling(g,f){this.diagnostics.recordMCPMessageFallback(g,f);const S=this.pendingSourceRequests.get(g);try{this.diagnostics.recordSignalingOperation(S.operation),await this.sendSignalingMessage(this.mapToSignalingOperation(S.operation),S.message),S.deferred.resolve()}catch{this.logger.warn(`Failed to resend source request via signaling ${g}`),S.deferred.reject(new Error("Sending source request failed via signaling"))}finally{this.clearPendingSourceRequestTimeout(g)}}clearPendingSourceRequestTimeout(g){const f=this.pendingSourceRequests.get(g);f&&(this.pendingSourceRequests.delete(g),clearTimeout(f.timeoutId))}onMsgReceived(g,f){this.logger.info(`Received SR result: ${f} for sequenceNumber: ${g}`);const S=this.pendingSourceRequests.get(g);if(S){switch(this.diagnostics.recordSrResultReceived(f,g,S.operation),f){case"ok":case"duplicate":case"out_of_order":S.deferred.resolve();break;default:S.deferred.reject(`SequenceNumber: ${g} failed with ${f}!`)}this.clearPendingSourceRequestTimeout(g)}else this.logger.warn(`No pending SR found for sequenceNumber: ${g}`)}},YA=0,QA=class _WebRtcSession2{constructor(g,f,S){this.context=g,this.callId=f,this.callback=S,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc2-"+ ++YA),this.videoFeatureManager=new xb(this.logger.createChild("VFM")),this.ufdManager=this.context.getUfdManager(),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.capabilityGatherer=nb.build({global:this.context.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround),this.reinvitelessContext=makeReinvitelessContext(this.context.config.reinvitelessConfig,this.multiParty),this.iceHostCandidateOnly=this.multiParty&&getFrom("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new CE({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:this.multiParty,reinviteltessContext:this.reinvitelessContext}),this.receiveStreamCollection=new MT({streamAdded:g=>this.streamAdded(g),streamRemoved:g=>this.streamRemoved(g)}),this.diagnostics=this.context.diagnostics,this.qmDiagnostics=this.diagnostics.newQualityManagerDiagnostics(),this.statsGatherer=new JI(this.logger.createChild("stats"),this.configProvider,this.diagnostics,this.mediaManager,this.multiParty),this.networkQualityDiagnostics=new UA(this.configProvider),this.speechDetectionDiagnostics=new BA(this.configProvider),this.qualityManager=new _b(this.logger.createChild("qm"),{scalingEnabled:this.configProvider.config.webrtcVideoScaling,customBwEstimationEnabled:this.configProvider.config.webrtcEnabledCustomBwEstimationForVideo},this,this.statsGatherer,this.qmDiagnostics,this.configProvider),this.activeSpeakerManager=new RT(this.callback.onContributingSourcesChanged,this.callback.onDominantSpeakerChanged,this.logger.createChild("ActiveSpeakerManager"),this.diagnostics.dshDiagnostics),this.wasConnected=!1,this.isAudioInputMuted=this.context.config.muted,this.isAudioOutputMuted=!1,this.relayCandidateGathered=!1,this.iceDisconnectedTimer=null,this.statisticsReport=Promise.resolve({type:"WebRtcMediaStats",data:{}}),this.terminated=!1,this.dtmfSender=Db.build({logger:this.logger,configProvider:this.configProvider}),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new qy(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:g=>this.streamsChangedListener=g},this.diagnostics.newSubscriptionManagerDiagnostics()),this.remoteVideoResolutionManager=new Tb(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.statsGatherer,this.diagnostics),this.remoteVideoManager=new Rb(this.logger.createChild("RemoteVideoManager"),this.configProvider,this.statsGatherer,this.diagnostics,this.remoteVideoResolutionManager,this.context.maContext.domOverrides),this.encStreamsManager=new Ca(this.configProvider,this.context.maContext.getEncodedStreamsWorkerProvider?.(),this.logger.createChild("EncodedStreamsManager")),this.streamSendersManager=new AA(this.mediaManager,this.logger.createChild("SSM"),this.context.callDeviceManager,this.configProvider,this.context.config,this.statsGatherer,this.diagnostics,this.qmDiagnostics,this.multiParty,this.encStreamsManager,this.videoFeatureManager),this.hwSilent=!1,this.deviceManagerSubs=[],this.isMuteHold=!1,this.rawIncomingAudioStreamManager=new es(this.logger.createChild("rawIncomingAudioStream")),this.useNullAudioStream=!1,this.audioCodecManager=new Ua(this.encStreamsManager,this.logger,this.configProvider),this.perfMonitorSubs=[],this.performanceMonitor=new FA(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("PerformanceMonitor")),this.negotiation=new jA(this.logger.createChild("negotiation"),this.configProvider,this.diagnostics.newNegotiationDiagnostics(this.statsGatherer.sessionInfo),this.reinvitelessContext,this.mediaManager,this.audioCodecManager,this.ufdManager,this.context,this.qualityManager,this.streamSendersManager,{onNegotiationRequired:(g,f)=>this.callbacks.onNegotiationRequired?.(g,f),onUpdateMediaDescriptionsRequired:(g,f)=>this.callbacks.onUpdateMediaDescriptionsRequired?.(g,f),updateLocalMediaSources:this.updateLocalMediaSources.bind(this),assurePC:this.assurePeerConnectionAsync.bind(this),hasPC:()=>!!this.peerConnection,createOffer:g=>this.peerConnection.createOffer(g),createAnswer:g=>this.peerConnection.createAnswer(g),setLocalDescription:g=>this.peerConnection.setLocalDescription(g),getLocalDescription:()=>this.peerConnection.localDescription,setRemoteDescription:g=>this.peerConnection.setRemoteDescription(g),setBWSeed:this.setBWSeed.bind(this),onTransportInitialized:()=>this.callbacks.onTransportInitialized(),startWaitingForStreamStart:g=>{this.statsGatherer.startWaitingForStreamStart(g)},getRollbackModifier:g=>new DT(this.peerConnection,this.configProvider,g)}),this.streamConfigurationHandler=new kb(this.logger,this.negotiation.negotiationEmulator,this.qualityManager,this.qmDiagnostics,this.configProvider,this.statsGatherer),this.pauseNegotiations=this.negotiation.pauseNegotiations.bind(this.negotiation),this.configureModalitiesAsync=this.negotiation.configureModalities.bind(this.negotiation),this.createOfferAsync=this.negotiation.createOffer.bind(this.negotiation),this.processOfferAsync=this.negotiation.processOffer.bind(this.negotiation),this.createAnswerAsync=this.negotiation.createAnswer.bind(this.negotiation),this.processAnswerAsync=this.negotiation.processAnswer.bind(this.negotiation),this.completeNegotiationAsync=this.negotiation.completeNegotiation.bind(this.negotiation),this.rejectNegotiationAsync=this.negotiation.rejectNegotiation.bind(this.negotiation),this.startMediaDescriptionsUpdateAsync=this.negotiation.startMediaDescriptionsUpdate.bind(this.negotiation),this.completeMediaDescriptionsUpdateAsync=this.negotiation.completeMediaDescriptionsUpdate.bind(this.negotiation),this.rejectMediaDescriptionsUpdateAsync=this.negotiation.rejectMediaDescriptionsUpdate.bind(this.negotiation),this.statsGatherer.on("onDiagnosticUpdated",(g=>this.processStatsReport(g))),this.statsGatherer.on("onStatisticsChanged",(g=>this.processLegacyStats(g))),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.negotiation.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((g,f,S)=>this.requestSource(g,f,S))),this.setSubsForSubscriptionManager(),this.setSubsForStreamManagerEvents(),this.configProvider.mediaConfig.maxBandwidthInKbps&&(this.statsGatherer.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.diagnostics.maxSessionBandwidth=this.configProvider.mediaConfig.maxBandwidthInKbps),this.createAudioRenderer(),this.setSubsForDeviceManager(),this.context.callDeviceManager.isVirtualDeviceEnabled&&this.setupCallDeviceManagerSubs(),this.configProvider.config.enableActiveSpeakerBasedDSH&&this.activeSpeakerManager.setStrategy(new MA({configProvider:this.configProvider})),this.perfMonitorSubs.push(this.performanceMonitor.on("onIncomingVideoQualityChanged",((g,f)=>{this.onIncomingVideoQualityChanged(g,f)}))),this.configProvider.config.webrtcVideoScaling&&(this.perfMonitorSubs.push(this.performanceMonitor.on("onOptimalVideoCountChanged",((g,f)=>{this.onOptimalVideoCountChanged(g,f)}))),this.onOptimalVideoCountChanged(this.configProvider.config.nonEstimatedDefaultVideoReceiversCount)),this.configProvider.config.setBWSeed&&(this.bandwidthCache=new oC(this.configProvider)),this.diagnostics.reinvitelessContext=this.reinvitelessContext,this.multiParty&&this.configProvider.config.enableVideoFeatureManager&&this.videoFeatureManager.manageFeatureSupport((()=>{if(this.detectVideoFeatures(),this.configProvider.config.enableDevtoolsAPI){const g=window?.webMA;g?.initVideoFeatures&&g.initVideoFeatures(this.videoFeatureManager)}}))}initializeMediaControlPlane(g){const f=this.dataChannel.getDataChannel(g);f?(this.mediaControlPlane=new KA(f,this.logger.createChild("MediaControlPlane"),this.configProvider.config.mediaControlPlaneConfig),this.mediaControlPlane.on("mpSendBandwidthChanged",(g=>{this.performanceMonitor.processNotification("BandwidthNotification",{bw:g}),this.bandwidthCache?.saveSeed(g),this.statsGatherer.addReportedReceiveBandwidth(g),this.diagnostics.addReportedReceiveBandwidth(g)})),this.mediaControlPlane.on("mcpHandshakeCompleted",(()=>{this.callback.onUpdateSignalingDSHMessageSubscription(!this.mediaControlPlane.mcpFeaturesSupported("dominantSpeakerHistoryEnabled")),this.mediaControlPlane.mcpFeaturesSupported("dominantSpeakerHistoryEnabled")&&this.diagnostics.dshDiagnostics.setCurrentActiveStrategy("server"),this.mediaControlPlane.mcpFeaturesSupported("sourceRequestsEnabled")&&(this.subscriptionManager.mcpSourceRequestsAvailable(),this.notifyStreamsChanged()),this.mediaControlPlane.mcpFeaturesSupported("senderSideBandwidthEstimationEnabled")&&this.configProvider.config.specCompliantSimulcast.enableSimulcastLayoutControlStrategy&&this.videoFeatureManager.get("Video").toggleServer(0,!0)})),this.mediaControlPlane.on("onHandshakeTimeout",(()=>{this.configProvider.config.enableSignalingDSHFallback&&this.callback.onUpdateSignalingDSHMessageSubscription(!0)})),this.mediaControlPlane.on("mpDshChanged",(g=>{this.activeSpeakerManager.onDominantSpeakerHistoryChanged(g,"server")}))):this.logger.safe.error(`[${g}] Unable to initialize MediaControlPlane due to datachannel creation failure`)}getMediaControlPlaneInstance(){return this.mediaControlPlane}getAcceptedTypes(){return this.negotiation.allowedMediaContentType}clone(g,f){const S=shallowClone(this.context);S.config=shallowClone(this.context.config),S.config.webrtcMediaContentType=this.negotiation.mediaContentType,S.config.webrtcAllowedMediaContentType=this.negotiation.allowedMediaContentType,S.configProvider=f,S.diagnostics=this.context.diagnostics?.newNativeSession(!1),g?(S.config.isConference=!0,S.config.isPstnCall=!1):(S.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(S.config.webrtcIceGatheringTimeoutIncreased=!0));const v=new _WebRtcSession2(S,this.callId,this.callback);return this.useNullAudioStream&&v.useNullAudioStreamClient(),this.relayManagerProvider&&(v.relayManagerProvider=this.relayManagerProvider),v.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,v}async setCallConstraints(g,f){const S=this.configProvider.setCallConstraints(g);if(this.logger.safe.info(`[${f}] Setting call constraints ${JSON.stringify(S)}, enableDynamicCallConstraints: ${this.configProvider.config.enableDynamicCallConstraints}`),this.configProvider.config.enableDynamicCallConstraints)try{await this.streamSendersManager.applyCallConstraints(f),this.configProvider.addCallConstraintsTelemetryEvent(S,"applied")}catch(g){throw this.logger.safe.error(`Error while applying constraints: ${g}`),g}else this.configProvider.addCallConstraintsTelemetryEvent(S,"applied");return S}setInternals(g,f){this.logger.safe.info(`[${f}] Setting internals from previous session`),this.diagnostics.commitNativeSession(),g.subscriptionManager&&(this.subscriptionManager?.dispose(),this.subscriptionManager=g.subscriptionManager,this.subscriptionManager.setDiagnostics(this.diagnostics.newSubscriptionManagerDiagnostics()),this.subscriptionManager.setStreamProvider({getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:g=>this.streamsChangedListener=g}),this.subscriptionManager.setLogger(this.logger.createChild("subs")),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),g.audioRenderer&&(g.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=g.audioRenderer),g.remoteVideoManager?.moveRenderers(this.remoteVideoManager),g.rawIncomingAudioStreamManager&&this.rawIncomingAudioStreamManager.updateHandlers(g.rawIncomingAudioStreamManager.handlerMap),this.audioRenderer.getStream()&&this.rawIncomingAudioStreamManager.streamChanged(this.audioRenderer.getStream())}setSubsForDeviceManager(){const g=this.getVideoDeviceManager();this.configProvider.config.enablePlayVideoOnStreamUnmuteWorkaround&&this.deviceManagerSubs.push(g.on("onAudioStreamMuted",(f=>{f||(this.remoteVideoManager.playVideo(),g.getLocalVideoRenderers().forEach((g=>g.playVideo())))})))}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(g=>this.statsGatherer.setSubscribedTrackIds(g))),this.subscriptionManager.on("onTrackSsrcChanged",(g=>this.statsGatherer.setSubscribedTrackSsrc(g))),this.subscriptionManager.on("onSubscriptionChanged",((g,f,S,v,C,_)=>this.onSubscriptionChanged(g,f,S,v,C,_))),this.subscriptionManager.on("onSubscriptionFailed",((g,f,S,v,C)=>this.statsGatherer.addSubscriptionEvent(g,f,S,v,C)))]}onSubscriptionChanged(g,f,S,v,C,_){f===qt.MODALITY.video&&(2===g&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount()),3===g&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount())),this.statsGatherer.addSubscriptionEvent(g,f,S,v,null,C,_)}setSubsForStreamManagerEvents(){this.streamSendersManager.on("onSendStreamChanged",((g,f)=>{this.statsGatherer.updateSendStream(g,f),g?.hasAudio()&&this.diagnostics.setAudioSendStream(g,f),this.diagnostics.setPresentationAudioOnScreenSharing(g,f)})),this.streamSendersManager.on("onVideoCaptureFreeze",(g=>{this.transportStateProvider.isConnected&&!this.transportStateProvider.isWaitingAcceptProvisional&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",g?"Bad":"Good","Video")})),this.streamSendersManager.on("onMaxVideoSendCapabilitiesChanged",((g,f)=>this.onMaxVideoSendCapabilitiesChanged(g,f))),this.streamSendersManager.on("onBandwidthAllocationChanged",(g=>this.onSendBandwidthChanged(g)))}move(g,f){this.logger.safe.info(`[${f}] moving to new session`),g.setInternals({subscriptionManager:this.subscriptionManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager,rawIncomingAudioStreamManager:this.rawIncomingAudioStreamManager},f),g.muteHold(this.isMuteHold,f),this.isAudioInputMuted?g.muteInputAsync(f):g.unmuteInputAsync(f),this.isAudioOutputMuted?g.muteOutputAsync(f):g.unmuteOutputAsync(f),this.subscriptionManager=null,this.audioRenderer=null,this.rawIncomingAudioStreamManager=null,this.callbacks.onTerminated=null}setMute(g,f,S){this.logger.safe.info(`[${S}] call setMute for ${g} with mute state ${f}`),this.streamSendersManager.setMuted(g,f,S),this.processLegacyStats(this.statsGatherer.getLastStatistics())}getConfiguredModalities(){return this.negotiation.configuredModalities}getDisabledModalities(){return this.negotiation.disabledModalities}createAudioElement(g){this.configProvider.config.devices.setSinkImmediately&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),this.audioRenderer.assureAudioElement(g)}useNullAudioStreamClient(){this.useNullAudioStream=!0,this.streamSendersManager.useNullAudioStreamClient()}createRemoteRenderer(g){return this.remoteVideoManager.createRenderer(g,this.subscriptionManager,this.logger)}getStatsAsync(g){if(this.statsGatherer&&!this.statsGatherer.isDisposed){if(this.audioCodecManager){const g=this.audioCodecManager.getSessionEvents();this.statsGatherer.sessionInfo.setAudioCodecEvents(g),this.diagnostics.audioCodecEvents=g}this.statisticsReport=this.statisticsReport.then((()=>this.statsGatherer.getReport(g))).catch((g=>(this.logger.safe.error(`getting statistics should never fail: ${g.error}`),g.partialReport)))}return this.statisticsReport}getLastKnownStats(g){return this.statsGatherer.getReport(!1,g)}muteHold(g,f){this.logger.safe.info(`[${f}] set muteHold state ${g}`),this.isMuteHold=g;const S=[qt.MODALITY.audio,qt.MODALITY.video,qt.MODALITY.sharing].filter((g=>hasSendDirectionality(this.negotiation.negotiatedModalities[g])&&(g!==qt.MODALITY.audio||!this.isAudioInputMuted)));for(const v of S)this.setMute(modalityToMediaType(v),g,f)}async muteInputAsync(g){this.isAudioInputMuted=!0,this.setMute("Audio",!0,g)}async unmuteInputAsync(g){this.isAudioInputMuted=!1,this.setMute("Audio",!1,g)}async muteOutputAsync(g){return this.isAudioOutputMuted=!0,this.audioCodecManager.decoder?.disableStreamsMixer(!0),this.audioRenderer?.setMuted(!0,g)}async unmuteOutputAsync(g){return this.isAudioOutputMuted=!1,this.audioCodecManager.decoder?.disableStreamsMixer(!1),this.audioRenderer?.setMuted(!1,g)}async getSpeakerVolume(g){return this.audioRenderer?.getSpeakerVolume(g)||0}async setSpeakerVolume(g,f){return this.audioRenderer?.setSpeakerVolume(g,f)}sendDtmf(g){return this.dtmfSender.sendDtmf(this.peerConnection,g)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}onDeviceEvent(g){this.statsGatherer.onDeviceEvent(g)}deviceSelectionChanged(){this.peerConnection&&this.audioRenderer?.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId())}async terminate(g,f,S=!0){this.logger.safe.info(`[${g}] terminate`),this.statsGatherer.setTerminated(),this.diagnostics.terminate(),this.perfMonitorSubs.forEach((g=>g?.dispose())),this.performanceMonitor.dispose(),this.terminated=!0,this.negotiation.terminate(g),await(this.audioCodecManager.decoder?.storeApiRecording()),this.rawIncomingAudioStreamManager?.dispose(),this.remoteVideoManager.dispose(),this.dataChannel&&(this.dataChannel.dispose(),this.dataChannel=null),this.logger.safe.info(`[${g}] reset peer connection`),this.contributingSources?.dispose(),this.activeSpeakerManager.dispose(),this.qualityManager?.dispose(),this.qualityManager=null,this.audioRenderer?.dispose(),this.dtmfSender?.dispose(),this.dtmfSender=null,this.streamSendersManager?.dispose(),this.streamSendersManager=null,this.transceiverManager=null,this.encStreamsManager.dispose(),this.receiveStreamCollection.clear(),this.transportStateProvider?.dispose(),this.transportStateProvider=null,this.audioCodecManager.dispose(),this.mediaManager.reset(),this.mediaControlPlane?.dispose(),this.peerConnection?.close(),this.peerConnection=null,this.negotiation.negotiationEmulator.configure(null),this.peerConnectionPromise=null,this.subscriptionManagerSubs.forEach((g=>g.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.deviceManagerSubs.forEach((g=>g.dispose())),this.callDeviceManagerSub?.dispose(),this.clearIceDisconnectedTimer(),this.callbacks.onTerminated&&this.callbacks.onTerminated();try{S&&await this.getStatsAsync(!1)}catch(f){this.logger.safe.error(`[${g}] Error while gathering stats ${stringifyObject(f)}`)}finally{this.statsGatherer.dispose()}}getIncomingRawAudioStream(g){this.logger.info("IRawStream for incoming audio stream requested");const f=this.audioRenderer.getStream();return this.rawIncomingAudioStreamManager.createIRawStreamClient(f,g)}getUnmixedAudioProvider(){return this.audioCodecManager.decoder?.getUnmixedAudioProvider()}configureSpatialAudio(g,f){this.configProvider.mediaConfig.spatialAudioEnabled=g,this.audioCodecManager.configureSpatialAudio(g,f)||this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable","Bad","Audio",!0,f)}setParticipantSpatialAudioPositions(g,f){if(!this.audioCodecManager?.decoder||!this.getUnmixedAudioProvider()?.configured)throw this.logger.safe.error(`[${f}] setParticipantSpatialAudioPositions is called while MUCH audio decoder is not created or not enabled`),"setParticipantSpatialAudioPositions not allowed";this.audioCodecManager.decoder?.setParticipantSpatialAudioPositions(g)}processNotification(g,f){"McpSourceRequestsAvailable"===g&&(this.subscriptionManager.mcpSourceRequestsAvailable(),this.notifyStreamsChanged()),"DominantSpeakerInfo"===g&&this.activeSpeakerManager.onDominantSpeakerHistoryChanged(f.previousDominantSpeakerHistory,"signaling"),"ControlVideoStreaming"===g&&this.streamConfigurationHandler.handleMessage(f),this.performanceMonitor.processNotification(g,f)}processStatsReport(g){try{if(this.remoteVideoManager.processStatsReport(g),this.configProvider.config.diagnostics.features.useNewNetworkUFD){this.networkQualityDiagnostics.processReport(g);const f=this.networkQualityDiagnostics.getInboundNetworkQuality();this.ufdManager.signalEvent("NetworkRecvQuality",f);const S=this.networkQualityDiagnostics.getOutboundNetworkQuality();this.ufdManager.signalEvent("NetworkSendQuality",this.isAudioInputMuted?"Good":S)}this.ufdManager.signalEvent("DeviceSpeakWhileMuted",this.speechDetectionDiagnostics.processReport(g)?"Bad":"Good"),this.streamSendersManager.onDiagnosticUpdated(g);for(const f of this.getVideoDeviceManager().getLocalVideoRenderers())f.onDiagnosticUpdated(g)}catch(g){this.logger.error("Failed to processes diagnostics update: "+g)}}processLegacyStats(g){g&&(this.remoteVideoManager.processLegacyStats(g),this.hwSilent!==g.audioHwSilent&&(this.hwSilent=g.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.configProvider.config.diagnostics.features.useNewNetworkUFD||(this.ufdManager.signalEvent("NetworkRecvQuality",g.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:g.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",this.isAudioInputMuted?"Good":g.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:g.networkSendLevel})),this.streamSendersManager.onStatisticsChanged(g))}assurePeerConnectionAsync(g,f){return this.peerConnectionPromise??(this.peerConnectionPromise=this.getPeerConnectionPromise(g,f)),this.peerConnectionPromise}async getPeerConnectionPromise(g,f){if(!this.relayManagerProvider)throw new Error("relay manager provider is not set!");this.logger.safe.info(`[${g}] fetching relay details from RelayManager...`);const S={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};f.mark("startQueryRelaysAsync");const v=await this.relayManagerProvider.getRelayManager().queryRelaysAsync(S);if(f.markAndMeasure("startQueryRelaysAsync","queryRelaysAsync"),this.terminated)throw new Error("session already disposed");const C={optional:[]},_=createIceServers(v,this.configProvider.config),T=this.negotiation.configureCrypto(C,this.context.config.isPstnCall);this.configureCpuThreshold(C),this.logger.safe.info("create peer connection");const I="unified-plan",b=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle";try{this.peerConnection=new Xs.window.RTCPeerConnection({iceServers:_,rtcpMuxPolicy:"require",iceTransportPolicy:this.configProvider.getIceTransportPolicy(),iceCandidatePoolSize:this.configProvider.config.iceCandidatePoolSize,bundlePolicy:b,sdpSemantics:I,audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===T,encodedInsertableStreams:!!this.configProvider.config.useInsertableStreams},C)}catch(g){throw g.code===DOMException.INVALID_STATE_ERR&&this.ufdManager.signalEvent("NoNetwork","Bad"),g}const A=this.peerConnection;this.negotiation.rollbackSupported=1===T&&this.context.configProvider.userAgentConfig.isBrowserRollbackSupported,this.negotiation.negotiationEmulator.configure(A),this.statsGatherer.initialize(A),this.statsGatherer.sessionInfo.setIceServers(_),this.statsGatherer.sessionInfo.setIceTransportPolicy(this.configProvider.getIceTransportPolicy()),this.statsGatherer.sessionInfo.setSdpSemantics(I),this.statsGatherer.sessionInfo.setBundlePolicy(b),this.diagnostics.iceServers=_,this.diagnostics.iceTransportPolicy=this.configProvider.getIceTransportPolicy(),this.diagnostics.sdpSemantics=I,this.diagnostics.bundlePolicy=b,await this.checkVideoCodecsSupport(),f.markAndMeasure("queryRelaysAsync","checkVideoCodecsSupport"),A.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${A.signalingState}`)},A.onicecandidateerror=g=>{const f=g,[S,v]=[f.address,f.port];if(this.logger.safe.warn(`On ICE candidate error ${f.url} | ${S}:${v}: code ${f.errorCode}: ${f.errorText}`),!this.transportStateProvider.isConnected||this.negotiation.iceCandidatesDefer.isPending){const g={address:S,port:+v,url:f.url,errorCode:f.errorCode,errorText:f.errorText};this.statsGatherer.addIceCandidateError(g),this.diagnostics.addIceCandidateError(g)}},A.onaddstream=g=>{this.logger.safe.info(`onaddstream stream: ${g.stream.id}`)};const processTrack=(g,f,S,v)=>{this.logger.safe.info(`ontrack processing ${g.kind}: ${f.id}`);let C=f.active;if(!f.active&&this.configProvider.config.useInactiveAudioTrack&&"audio"===g.kind&&(this.logger.safe.warn("ontrack override forcing to use inactive audio stream"),C=!0),!C||"stopped"===v?.currentDirection||v?.stopped)return void this.logger.safe.info("ontrack ignore non active stream");let _=this.mediaManager.getMediaEntityByRemoteStreamId(f.id);if(_||(this.logger.safe.info(`cannot find media entity with stream id ${f.id} trying to fallback`),f.getAudioTracks()[0]&&(_=this.mediaManager.getMediaEntitiesByModality(qt.MODALITY.audio)[0])),_){const v=this.createReceiveStream(f,S,g,_);_.setRemoteTrackId(g.id),this.addReceiveStreamTransforms(S,_.getModality()),this.receiveStreamCollection.add(v)}else this.logger.safe.error(`could not find media entity for an added stream: ${f.id}`)};A.ontrack=g=>{const{track:f,receiver:S,transceiver:v}=g,C=g.streams[0]??new MediaStream([f]),trackCallback=()=>processTrack(f,C,S,v);if(!(this.configProvider.config.addAudioStreamBeforeConnection&&qt.TRACK_KIND.audio===f.kind)&&!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional)return this.logger.safe.info(`ontrack queueing to be run once connected ${f.kind}: ${C.id}`),void this.transportStateProvider.doOnConnected(trackCallback,"ontrack",!1);trackCallback()},A.onremovestream=g=>{this.logger.safe.info(`onremovestream ${g.stream.id}`),this.transportStateProvider.doOnConnected((()=>this.receiveStreamCollection.remove(g.stream.id)),"onremovestream")},A.onicecandidate=f=>{const S=f.candidate;if(S){const f=parseCandidateString(S.candidate);if(this.logger.safe.info(`[${g}] onicecandidate candidate: component:${f.component} protocol:${f.protocol} prio:${f.priority} type:${f.type} port:${f.port}`),this.logger.unsafe.info(`[${g}] candidate details: ${S.candidate}`),"1"!==f.component)return;if(this.negotiation.iceCandidateReceived=!0,this.statsGatherer.sessionInfo.setCandidateDetails(f),this.diagnostics.setCandidateDetails(f),!this.relayCandidateGathered&&S.candidate.indexOf("typ relay")>-1){const g={priority:S.priority?.toString()||f.priority,time:Date.now()-this.negotiation.iceRelayGatheringStartTime};this.statsGatherer.sessionInfo.setRelayCandidateInfo(g),this.diagnostics.relayCandidateInfo=g,this.relayCandidateGathered=!0}}else this.logger.safe.info(`[${g}] onicecandidate candidate: null`);if(!this.negotiation.iceCandidatesDefer.isPending)return;const v=!this.context.config.webrtcIceGatheringTimeoutIncreased||this.configProvider.config.emptyIceCandidateMarksGatheredAnswerer&&!this.negotiation.initiator,C=this.iceHostCandidateOnly||0===_.length;if(!S&&v||C){S&&this.logger.safe.info(`[${g}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${g}] Is connected:`,this.transportStateProvider.isConnected,this.transportStateProvider.iceConnectionState,this.transportStateProvider.signalingState);let f=!0;if(this.context.configProvider.mediaConfig.isTransportUnbundled&&S){f=this.negotiation.sessionDescription.createLocalOffer(A.localDescription.sdp).hasUnbundledIceCandidates()}f&&this.completeCandidateGathering(g)}else if(this.relayCandidateGathered){let f=!0;if(this.context.configProvider.mediaConfig.isTransportUnbundled){f=this.negotiation.sessionDescription.createLocalOffer(A.localDescription.sdp).hasUnbundledRelayIceCandidates()}f&&(this.statsGatherer.clearIceCandidateErrors(),this.diagnostics.clearIceCandidateErrors(),this.completeCandidateGathering(g))}},A.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${A.iceGatheringState}`)},this.transportStateProvider=new Nb(A,T,this.logger.createChild("TransportStateProvider"),this.configProvider,this.diagnostics.newTransportStateDiagnostics()),this.transportStateProvider.on("stateChanged",((S,v,C)=>{if(this.terminated)return;const _=this.wasConnected?C:g;if(this.statsGatherer.sessionInfo.setIceConnectionState(S),"connecting"===S&&f.mark("transportConnecting"),"connected"===S||"completed"===S)f.markAndMeasure("transportConnecting","transportConnected"),this.onTransportConnected(_);else if("failed"===S||"closed"===S&&"failed"!==v){if(this.negotiation.iceCandidatesDefer.isPending)return this.logger.safe.info(`[${_}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(_);this.raiseError({type:qt.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},_),this.configProvider.config.webrtcCloseAfterIceFailure&&A.close(),this.callbacks.onTransportFailed?.()}"disconnected"===S?(this.callbacks.onTransportDisconnected?.(g),this.startIceDisconnectedTimer(_)):this.clearIceDisconnectedTimer()})),this.transportStateProvider.on("signalingStateChanged",((f,S,v)=>{this.configProvider.config.reconnectOnPcClose&&!this.terminated&&"closed"===f&&this.transportStateProvider.isTransportConnected&&this.raiseError({type:qt.MEDIA_ERROR.unexpectedClose,detail:"PeerConnection is closed"},v),"have-remote-pranswer"===S&&"stable"===f&&this.configProvider.config.webrtcPranswerWaitFinalAnswer&&this.transportStateProvider.isTransportConnected&&(this.logger.safe.info(`[${v}] remote final answer, activating audio`),this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g))})),this.transceiverManager=new va(this.logger,this.peerConnection,this.mediaManager,this.context,this.reinvitelessContext),this.streamSendersManager.registerRtpSenderManager(this.transceiverManager),allowDataChannel(this.context)&&!this.dataChannel&&(this.dataChannel=new Rs(this.peerConnection,this.diagnostics,this.logger,this.configProvider),this.callback.onDataChannelUpdated?.(this.dataChannel),this.multiParty&&this.initializeMediaControlPlane(g)),this.sourceRequestSender=new JA(this.mediaControlPlane,this.context.sendWebRtcMediaNotificationAsyncCallback,this.logger.createChild("SourceRequestSender")),this.mediaMessageController=new Bb(this.logger.createChild("SourceRequester"),this.configProvider,this.sourceRequestSender,this.mediaControlPlane),this.negotiation.setInternals(this.transceiverManager,this.transportStateProvider,this.dataChannel),this.multiParty&&(this.contributingSources=new hb(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new ub(this.logger.createChild("ContributingSourcesProvider"),A,this.configProvider.config.diagnostics.features.logContributingSourcesError,this.diagnostics))),f.mark("startInitialize"),await this.encStreamsManager.initialize(),f.markAndMeasure("startInitialize","encStreamsManagerInitialize");const P=this.encStreamsManager.isWorkerLoaded();this.initAudioCodec(P),this.statsGatherer.sessionInfo.setEncodedStreamWorkerLoaded(P),this.diagnostics.encodedStreamWorker=P}configureCpuThreshold(g){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&g.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(g){this.negotiation.iceCandidatesDefer.isPending&&(this.logger.safe.info(`[${g}] ICE candidates gathered completely`),this.negotiation.iceCandidatesDefer.resolve())}detectVideoFeatures(){const g=this.videoFeatureManager.get("Video"),f=this.configProvider.config.specCompliantSimulcast;if(f?.enableSimulcastLayoutControlStrategy&&f?.video?.layerScaleFactors?.length>2&&g.toggleClient(0,!0),this.context.config.isTownHall){const f=this.configProvider.config.broadcastMode;(f?.prioritizeLayoutOnServer||f?.prioritizeLayoutOnClient)&&g.toggleClient(3,!0),f?.maxSessionBandwidthKbps&&(this.statsGatherer.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.diagnostics.maxSessionBandwidth=this.configProvider.mediaConfig.maxBandwidthInKbps)}const S=this.mediaManager.getMediaEntitiesByModality("video"),v=this.configProvider.config.preferredH264VideoSendProfile;v?.startsWith("64")&&S.length>0&&S[0].isSendProfileSupported("H264",v)&&g.toggleClient(1,!0)}onTransportConnected(g){if(this.statsGatherer.clearIceCandidateErrors(),this.diagnostics.clearIceCandidateErrors(),!this.terminated){if(this.transportStateProvider.isWaitingAcceptProvisional)return this.logger.safe.info(`[${g}] transport connected provisional`),this.configProvider.config.createProvisionalAnswer.audioState&&this.callbacks.onAudioStateChanged?.(this.configProvider.config.createProvisionalAnswer.audioState,g),void(this.configProvider.config.createProvisionalAnswer.connectTransport&&this.callbacks.onTransportConnected?.(g));this.logger.safe.info(`[${g}] audio transport connected`),this.wasConnected=!0,this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval&&"have-remote-pranswer"===this.transportStateProvider.signalingState?this.handleEarlyMediaAudioState(g):this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g),this.multiParty&&this.configProvider.config.enableVideoFeatureManager&&(this.videoFeatureManager.manageFeatureSupport((()=>{this.detectVideoFeatures()})),this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2&&this.videoFeatureManager.on("onVideoFeaturesChanged",(g=>{if("Video"===g.mediaType&&this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2){const f=this.mediaManager.getMediaEntitiesByModality("video");f.length>0&&this.mediaMessageController.sendMaxVideoSendCapabilitiesV2(f[0],g)}}))),this.callbacks.onTransportConnected?.(g)}}handleEarlyMediaAudioState(g){const f=this.peerConnection.getReceivers().filter((g=>"audio"===g.track.kind))[0];if(!f)return this.logger.safe.warn(`[${g}] Connected transport with provisional answer with no audio receiver`),void this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g);this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.started,g);const S=this.configProvider.config.webrtcPranswerMediaPollingTimeout,v=this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval;this.logger.safe.info(`[${g}] Starting polling for early media audio stats`);const pollStats=async()=>{try{if(!this.canPollAudioStats())return;let C;this.logger.safe.debug(`[${g}] Polling audio receiver stats to detect early media start`);const _=deferWithTimeout(S,"Unable to get audio receiver stats report");f.getStats().then(_.resolve,_.reject);const T=await _.promise;this.diagnostics.registerEarlyMediaPoll();for(const g of T.values())if("inbound-rtp"===g.type){C=g;break}if(!this.canPollAudioStats())return void this.logger.safe.info(`[${g}] Finished polling early media audio stats, terminated: ${!this.terminated}`);if((this.configProvider.config.webrtcPranswerCheckAudioEnergy?C?.totalAudioEnergy:C?.bytesReceived)>this.configProvider.config.webrtcPranswerAudioThreshold)return this.logger.safe.info(`[${g}] Finished polling early media audio stats, activating audio`),void this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g);this.logger.safe.info(`[${g}] No audio data received yet, polling again in ${v}ms`),setTimeout(pollStats,v)}catch(f){const S=stringifyObject(f);if(this.logger.safe.error(`[${g}] Error polling stats for pranswer: ${S}. Will stop polling: ${this.configProvider.config.webrtcPranswerStopPollingAfterError}`),this.diagnostics.addStatsError("WebrtcSession::earlyMediaPolling",S),this.configProvider.config.webrtcPranswerStopPollingAfterError)return void this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g);setTimeout(pollStats,v)}};setTimeout(pollStats,this.configProvider.config.webrtcPranswerWaitIntervalBeforePolling)}canPollAudioStats(){return!this.terminated&&"have-remote-pranswer"===this.transportStateProvider.signalingState}startIceDisconnectedTimer(g){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${g}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise ${qt.MEDIA_ERROR.iceConnectionError}`),this.raiseError({type:qt.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},g)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(g,f=generateCauseId()){this.logger.safe.error(`[${f}] Media error occurred type: ${g.type} detail: ${g.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(g,f)}notifyStreamsChanged(){this.streamsChangedNotificationScheduled||(this.logger.safe.info("Scheduling NotifyStreamsChanged"),this.streamsChangedNotificationScheduled=!0,this.negotiation.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.streamsChangedNotificationScheduled=!1,this.logger.safe.info("Executing NotifyStreamsChanged callback"),this.streamsChangedListener?.()})))}async streamAdded(g){if(qt.MODALITY.audio===g.getModality()&&(this.webrtcAudioRecvStream=g.getMediaStream(),await this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),await this.updateAudioRendererStream(this.webrtcAudioRecvStream)),this.configProvider.config.mapSsrcToTrackForStats){const f=this.mediaManager.getMediaEntityByRemoteStreamId(g.getMediaStream().id);this.statsGatherer.setSsrcTrackPair(f.getRemoteSsrc(),f.getRemoteTrackId())}this.notifyStreamsChanged()}async updateAudioRendererStream(g){await this.audioRenderer.play(g),this.rawIncomingAudioStreamManager.streamChanged(g)}streamRemoved(g){if(qt.MODALITY.audio===g.getModality())this.audioRenderer.getStream()===g.getMediaStream()&&(this.audioRenderer.stop(),this.rawIncomingAudioStreamManager.streamChanged(null)),this.webrtcAudioRecvStream=null;else if(qt.MODALITY.video===g.getModality()){const f=this.mediaManager.getMediaEntityByRemoteStreamId(g.getMediaStream().id);f?.getLocalRecvCapabilities()?.resetToInitial()}this.clearReceiveStreamTransforms(g.getReceiver()),g.dispose(),this.notifyStreamsChanged()}hasRelayCandidates(){return this.relayCandidateGathered}createReceiveStream(g,f,S,v){const C=this.configProvider.config.addFmtpToInitialSubscription?v.getLocalRecvCapabilities():null,_=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&v.getModality()!==qt.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null,T=new $y(g,f,v.getModality(),+v.getXSourceStreamId(),this,C,_,v.getSubstreamIndex());return new PA(T,S,this.receiveStreamCollection,this.logger.createChild("RecvStream"),this.configProvider.config)}async requestSource(g,f,S){if(!this.multiParty)return;const v=this.mediaManager.getMediaEntityByRemoteStreamId(g);if((this.isMuteHold||this.negotiation.negotiatedModalities[v.getModality()]===qt.MEDIA_STATE.inactive)&&-1!==f)return await delay(10),this.requestSource(g,f,S);if(this.negotiation.negotiationCompletedPromise.isPending)try{await this.negotiation.negotiationCompletedPromise.promise}catch(g){this.logger.safe.info("source request should be sent even if negotiation rejected",g)}if(!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional){this.logger.safe.info("requestSource is postponed till transport is connected");const g=new dt;this.transportStateProvider.doOnConnected((()=>g.resolve()),"requestSource"),await g.promise}return this.mediaMessageController.sendSourceRequest(v.getXSourceStreamId(),f,v?.getMid(),S,v.getSubstreamIndex())}async onReceiveCapabilitiesChanged(g,f,S){if(!this.streamSendersManager)return!1;try{return await this.streamSendersManager.applyCapabilities(f,g,S),!0}catch(g){return!1}}onOptimalVideoCountChanged(g,f){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(g),this.diagnostics.addOvcSubscriptionReport(g,this.subscriptionManager?.getSubscriptionsCount(),f)}async onSendBandwidthChanged(g){if(!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional||!this.mediaControlPlane.mcpFeaturesSupported("senderSideBandwidthEstimationEnabled"))return;const f=[],S=Object.keys(g);for(const v of S){const S=this.mediaManager.getMediaEntitiesByModality(mediaTypeToModality(v)).filter((g=>g.isEnabled()&&null!==g.getLocalTrackId()));if(0===S.length||0===g[v])return;f.push({streamMsid:S[0].getXSourceStreamId(),bw:g[v]})}await this.mediaMessageController.sendBandwidthInfo(f),this.diagnostics.reportedSendBandwidthLayouts(g)}onMaxVideoSendCapabilitiesChanged(g,f){("Video"===g&&this.configProvider.config.maxSendVideoCapabilities.enableForVideo||"ScreenShare"===g&&this.configProvider.config.maxSendVideoCapabilities.enableForSharing)&&this.transportStateProvider.doOnConnected((()=>this.notifyMaxVideoCapabilitiesChanged(g,f)),"maxCapabilities")}notifyMaxVideoCapabilitiesChanged(g,f){const S=mediaTypeToModality(g),v=this.mediaManager.getMediaEntitiesByModality(S)[0];if(!v)return;const C=v.getMid();"Video"===g&&this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2?this.mediaMessageController.sendMaxVideoSendCapabilitiesV2(v,this.videoFeatureManager.get("Video"),f):this.mediaMessageController.sendMaxVideoSendCapabilities([C],f)}createAudioRenderer(){this.audioRenderer=new WC(this.logger.createChild("AudioRenderer"),this.configProvider,this.diagnostics.newAudioRendererDiagnostics()),this.ufdManager.signalDeviceEvent(1,"Good","Audio"),this.context.maContext.domOverrides.onMediaElementAdded&&this.audioRenderer.on("onAudioElementAdded",this.context.maContext.domOverrides.onMediaElementAdded),this.context.maContext.domOverrides.onMediaElementRemoved&&this.audioRenderer.on("onAudioElementRemoved",this.context.maContext.domOverrides.onMediaElementRemoved),this.audioRenderer.on("onAudioPlaybackError",((g,f,S)=>this.onAudioPlaybackError(g,f,S))),this.audioRenderer.on("onAudioStateChanged",((g,f)=>this.deviceManager.effectsManager.setAecRefStream(g,f)))}onAudioPlaybackError(g,f,S){const v={type:f,detail:S,isAudio:!0};this.ufdManager.signalDeviceEvent(1,"Bad","Audio"),this.deviceManager.raiseTelemetryEvent("reconnect_on_audio_playback_error",{error:g,mediaError:f,message:S}),this.context.reconnectRetry&&this.configProvider.config.audioRendererFailedRetryCodes?.includes(g)&&(this.logger.warn(`Reconnect required, attempt No: ${this.context.reconnectRetry}`),this.context.reconnectRetry--,this.raiseError(v))}getSessionConfig(){return this.configProvider}getLocalMediaTrackId(g){const f=this.mediaManager.getLocalTracksInfo(),S=mediaTypeToModality(g),v=f.find((g=>g.modality===S));return v?v.trackId:null}addReceiveStreamTransforms(g,f){const S=this.encStreamsManager.initTransformsCollection(g,"Receiver",modalityToMediaType(f));S&&f!==qt.MODALITY.audio&&this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&S.addTransform(new Wa(this.logger.createChild(`RecvStreamAnalyzer [${f}/${g.track.id}]`)))}clearReceiveStreamTransforms(g){this.encStreamsManager.clearTransformsCollection(g)}async checkVideoCodecsSupport(){try{const g=await this.capabilityGatherer.getCapabilities("video");this.statsGatherer.setH264AvailableProfiles(g);const f=nb.build({global:this.context.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround,!0),S=await f.getCapabilities("video"),v=nb.build({global:this.context.maContext},!1),C=await v.getCapabilities("video");this.statsGatherer.setSupportedH264Profiles(S,C);const _=await oa.isCodecsSupported(this.configProvider.config.hevcCodecs);this.diagnostics.videoCapabilities=g,this.diagnostics.setSupportedH264Profiles(S,C),this.diagnostics.isCodecsSupported=_;const T=new Set(g?.codecs?.map((g=>g.mimeType.toLocaleLowerCase()))||[]);for(const g of this.configProvider.config.requiredVideoCodecs)if(!T.has(g)){this.ufdManager.signalEvent("NoRequiredVideoCodecs","Bad","Video");break}}catch(g){this.logger.safe.error(`failed to get video capability ${stringifyObject(g)}`)}}setBWSeed(g){if(!this.bandwidthCache)return;const f=this.bandwidthCache.getSeed();g.applyChannelParameters={multiChannelParameter:{mids:this.configProvider.config.bwSeedOptions.mids,mediaParameter:JSON.stringify({sendSideBWSeed:{seedValueBitsPerSec:f}})}},this.diagnostics.sentBWSeed=f}getSubscriptionManager(){return this.subscriptionManager}initAudioCodec(g){this.audioCodecManager.init(g,this.isAudioOutputMuted);const f=this.audioCodecManager.decoder;f&&(f.on("usedDecoderChanged",(g=>{this.updateAudioRendererStream(g?f.stream:this.webrtcAudioRecvStream),this.statsGatherer.setAudioDecoderStatsProvider(g?f.getStatsProvider():void 0),this.contributingSources?.useCustomCodec(g)})),f.on("contributingSourcesChanged",(g=>this.contributingSources?.updateContributingSources(g))),this.audioCodecManager.on("negotiationNeeded",(g=>this.negotiation.triggerRenegotiation(!0,g))))}onIncomingVideoQualityChanged(g,f){1===g&&this.remoteVideoResolutionManager.limitResolutionOnPoorPerformance(f)}getVideoDeviceManager(){return this.context.callDeviceManager.getDeviceManager("Video")}setupCallDeviceManagerSubs(){this.callDeviceManagerSub=this.context.callDeviceManager.on("onSelectedVirtualDevicesChanged",(()=>{this.logger.info("VirtualDevice changed, disposing deviceManager subscriptions"),this.deviceManagerSubs.forEach((g=>g.dispose())),this.logger.info("New subscriptions for deviceManager created"),this.setSubsForDeviceManager()}))}updateLocalMediaSources(){this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statsGatherer.updateStatsWithLocalSsrcTrackInfo();const g=this.streamSendersManager.getLocalMediaSources();this.qualityManager.updateRegisteredSources(g)}},XA={build:(g,f,S)=>new QA(g,f,S)};function makeReinvitelessContext(g,f){const S=(f?g?.maxReinvitelessMediaForVideoMultiparty:g?.maxReinvitelessMediaForVideo1on1)||0,v=(f?g?.maxReinvitelessMediaForVBSSMultiparty:g?.maxReinvitelessMediaForVBSS1on1)||0;return{enabled:S>0||v>0,maxStreamsForModality:{video:S,sharing:v}}}var ZA=class{constructor(g,f,S,v,C,_,T,I){this.logger=g,this.context=f,this.configProvider=S,this.diagnostics=v,this.ufdManager=C,this.deviceManager=_,this.capabilities=T,this.midCallTelemetry=I,this.activeSessions=[],this.pendingDeviceTelemetryEvents=[],this.pendingVideoEffectsTelemetryEvents=[],this.pendingAudioEffectsTelemetryEvents=[],this.callsCount=0,this.mediaConfig={},this.configProvider.on("configUpdated",(()=>this.configApplied())),this.deviceManager.on("onDeviceTelemetryEvent",(g=>this.onDeviceTelemetryEvent(g))),this.deviceManager.on("onVideoEffectsTelemetryEvent",(g=>this.onVideoEffectsTelemetryEvent(g))),this.deviceManager.on("onAudioEffectsTelemetryEvent",(g=>this.onAudioEffectsTelemetryEvent(g)))}createSession(g,f,S,v,C,_){const T=(0,sT.merge)({},this.mediaConfig,_);this.configProvider.setMediaConfiguration(T);const I=this.configProvider.getConfigView(S?.isConference),b=this.logger,A=f.correlationId,P=this.diagnostics.newSession(I,A,this.logger.createChild("sessionDiagnostics"));C?.setDiagnosticsReport(this.diagnostics.reportGenerator);const R={getLogger:()=>b,getUfdManager:()=>this.ufdManager,sendWebRtcMediaNotificationAsyncCallback:(g,S)=>f.sendWebRtcMediaNotificationAsync(g,S),maContext:this.context,config:S??{},configProvider:I,diagnostics:P.newNativeSessionDiag(),reconnectRetry:I.config.audioRendererFailedReconnectTimes,callDeviceManager:v,getSmallCallTelemetry:()=>C},M=(I.mediaConfig.simulcastSessionEnabled?XA:jb).build(R,A,g),w=new PT(I,++this.callsCount,P);w.setMediaQosEnabled(!!T.enableMediaQoS),w.setPortRangeConfigured(!!T.mediaPortRanges);const O=new ET(M,A,R,g,w,this.configProvider,P);for(O.on("onTerminated",(g=>this.onSessionTerminated(g))),this.activeSessions.push(O),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector=lT.getInstance(this.logger.createChild("WebRtcInternals"),I),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length);this.pendingDeviceTelemetryEvents.length>0;)O.registerDeviceTelemetryEvent(this.pendingDeviceTelemetryEvents.pop());for(;this.pendingVideoEffectsTelemetryEvents.length>0;)O.registerVideoEffectsTelemetryEvent(this.pendingVideoEffectsTelemetryEvents.pop());for(;this.pendingAudioEffectsTelemetryEvents.length>0;)O.registerAudioEffectsTelemetryEvent(this.pendingAudioEffectsTelemetryEvents.pop());return O}getDeviceManager(){return this.deviceManager}getCapabilities(){return this.capabilities}getScreenSharingManager(){return new hT(this.deviceManager)}updateConfig(g,f,S,v){this.configProvider.updateConfig(g,f,S,v)}getConfig(){return this.configProvider.config}getConfigProvider(){return this.configProvider}setMediaConfig(g){(0,sT.merge)(this.mediaConfig,g),this.diagnostics.mediaConfig=this.mediaConfig}getMediaLogs(){return this.webRtcInternalsCollector?this.webRtcInternalsCollector.collect():Promise.resolve("")}getDiagnosticsData(){return this.diagnostics.rootRef}dispose(g){return Promise.all([...this.activeSessions.map((async f=>{await f.terminate(g,{}).catch((()=>{})),f.dispose()}))]).then((()=>{}),(()=>{}))}handleSendMidCallTelemetry(g){this.midCallTelemetry?.on("sendMidCallTelemetry",g)}configApplied(){window&&(this.configProvider.config.enableDevtoolsAPI?window.webMA||this.injectDevtoolsAPI():window.webMA&&delete window.webMA)}injectDevtoolsAPI(){const g=[],f={config:{addOverride:(g,f)=>this.configProvider.setConsoleOverride(g,f),setOverrides:g=>this.configProvider.setConsoleOverrides(g),clearOverride:g=>this.configProvider.clearConsoleOverride(g),clearAllOverrides:()=>this.configProvider.clearAllConsoleOverrides(),setPlatformConstraints:g=>this.configProvider.setCallConstraints(g),setCallConstraints:g=>{this.activeSessions.length&&this.activeSessions[this.activeSessions.length-1].setCallConstraints(g,"webMA")},setRelayConfigOverride:g=>this.context.getRelayManager().setRelayOverride(g),manageVideoFeatures:f=>{g.push(f)}},diagnosticsReport:this.diagnostics.reportGenerator,initVideoFeatures:f=>{g.forEach((g=>{g(((g,S,v)=>{let C;const _=Lb[v];return void 0!==_&&(("video"===S||"sharing"===S)&&(C=f.get("Video")),void 0!==C)&&(g?(C.toggleServer(_,!0),!0):(C.toggleClient(_,!0),!0))}))}))},deviceManager:{setAudioProcessingFlags:g=>this.deviceManager.setAudioProcessingFlags(g)},ufdManager:{raiseUFD:(g,f="Bad",S="Video")=>this.ufdManager.signalEvent(g,f,S)}};window.webMA=f}onDeviceTelemetryEvent(g){this.activeSessions.length>0?this.activeSessions.forEach((f=>f.registerDeviceTelemetryEvent(g))):this.pendingDeviceTelemetryEvents.push(g)}onVideoEffectsTelemetryEvent(g){this.activeSessions.length>0?this.activeSessions.forEach((f=>f.registerVideoEffectsTelemetryEvent(g))):this.pendingVideoEffectsTelemetryEvents.push(g)}onAudioEffectsTelemetryEvent(g){this.activeSessions.length>0?this.activeSessions.forEach((f=>f.registerAudioEffectsTelemetryEvent(g))):this.pendingAudioEffectsTelemetryEvents.push(g)}onSessionTerminated(g){remove2(this.activeSessions,(f=>f===g)),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length),0===this.activeSessions.length&&this.ufdManager.reset()}},eP=class{static build(g,f,S,v,C,_,T,I){return new ZA(g,f,S,v,C,_,T,I)}};eP.constants=qt,eP.helper=aa;var tP=class{constructor(g,f,S){this.logger=g,this.callbacks=f,this.deviceManagerDiagnostics=S,this.createWasmCVWorker=()=>(this.logger.info("Creating wasmcv worker"),this.create({msg:"wasmcv"})),this.createEncodedStreamsWorker=()=>(this.logger.info("Creating encoded-stream worker"),this.create({msg:"encoded-stream"})),this.createTimerWorker=()=>(this.logger.info("Creating timer worker"),this.create({msg:"timer"})),this.getWasmVqeWorker=()=>(this.logger.info("Creating wasmvqe worker"),this.create({msg:"wasmvqe"}))}getWorkerFunction(g){if(this.logger.info(`getWorkerFunction, loaderName: ${g}`),!this.callbacks?.createGenericWebRTCWorker)switch(g){case"encoded-stream":return this.callbacks?.createEncodedStreamsWorker;case"wasmcv":return this.callbacks?.createWasmCVWorker;default:return}switch(g){case"encoded-stream":return this.createEncodedStreamsWorker;case"wasmcv":return this.createWasmCVWorker;case"timer":return this.createTimerWorker;default:return}}get audioWorklet(){return this.callbacks?.createGenericWebRTCWorker?{getWasmVqeWorker:this.getWasmVqeWorker,getWasmDnsWorklet:this.callbacks?.audioWorklet?.getWasmDnsWorklet,getWasmAecWorklet:this.callbacks?.audioWorklet?.getWasmAecWorklet,getWasmVqeWorklet:this.callbacks?.audioWorklet?.getWasmVqeWorklet}:this.callbacks?.audioWorklet}create(g){const f=this.callbacks.createGenericWebRTCWorker(),S=Date.now(),onError=S=>{this.logger.error(`Worker ${JSON.stringify(g)} error: ${S}`),this.deviceManagerDiagnostics?.registerWorkerEvent({timestamp:Date.now(),workerType:g.msg,msg:"generic-worker-error",payload:JSON.stringify(S)}),f.removeEventListener("error",onError)},onMessage=v=>{let C;"wasm-worker-loaded"===v?.data?.msg&&(this.logger.info(`Worker ${JSON.stringify(g)} event: ${JSON.stringify(v.data)}`),C={timestamp:Date.now(),workerType:g.msg,workerLoadTimeMs:Date.now()-S,msg:JSON.stringify(v?.data?.msg),payload:JSON.stringify(v?.data?.payload)},f.removeEventListener("message",onMessage)),"wasm-worker-load-error"===v?.data?.msg&&(this.logger.info(`Worker ${JSON.stringify(g)} error: ${JSON.stringify(v.data)}`),C={timestamp:Date.now(),workerType:g.msg,msg:"load-worker-error",payload:JSON.stringify(v?.data?.payload)}),C&&this.deviceManagerDiagnostics?.registerWorkerEvent(C)};return f.addEventListener("error",onError),f.addEventListener("message",onMessage),f.postMessage(g),f}},iP=class{constructor(g,f){this.wasmLoader=g,f&&f.getWorkerUrl().then((g=>{this.url=g}))}getWorker(g){try{g.safe.info("creating worker");const f=this.wasmLoader.getWorkerFunction("encoded-stream");return f?f():this.url?(g.safe.warn("WasmLoader didn't provide worker function, falling back to legacy worker provider"),new Worker(this.url)):(g.safe.error("no worker provider"),null)}catch(f){g.safe.error(`failed to create worker ${stringifyObject(f)}`)}return null}},nP=class{constructor(g,f,S){this.mediaAgents=[],g.logger??(g.logger=new Mo),g.domOverrides??(g.domOverrides={}),this.config=g;const v=g.mediaSettings;setAgentPlatformInfo(g.clientInformation),this.logger=new rT(g.safeLogger?.createChild("MA",v.debug),g.logger.createChild("MA",v.debug)),this.configProvider=new By(this.logger.createChild("configProvider"),S,v);const C=new ay(this.configProvider);this.mediaAgentDiagnostics=new nT(this.configProvider,C),this.ufdManager=new Do(this.logger.createChild("UFD"),this.configProvider),this.wasmLoader=new tP(this.logger.createChild("WasmLoader"),g.createWasmWorkerCbs,C),this.deviceManager=new Oy(this.logger.createChild("DeviceManager"),this.configProvider,C,g.domOverrides,this.ufdManager,g.webcvProvider,g.wasmdnsProvider,g.wasmaecProvider,g.wasmVqeProvider,this.wasmLoader),this.capabilities=new wo(this.configProvider),ei.initialize(this.configProvider),f.on("OnECSChanged",(()=>{const g=f.getEcsConfig("SkypeWebMedia","mediaAgent");g?this.configProvider.updateConfig(g,f.ETag,f.getEcsConfig("ConfigIDs","SkypeWebMedia"),f.getEcsConfig("Headers","CountryCode")):this.logger.warn("No SkypeWebMedia.mediaAgent config.")}))}getDeviceManager(){return this.deviceManager}async buildAgent(g,f,S){if(!oa.hasMediaApi())throw[new rP(`${g} not supported by media agent provider`,"not_supported")];if(this.config?.detectH264Support&&!await oa.hasH264CodecSupport(this.config.logger))throw[new rP("H264 is not supported","not_supported")];const v=new iP(this.wasmLoader,this.config.encodedStreamsWorkerProvider),C={getRelayManager:()=>f.getOrCreateRelayManager(),getWebCVProvider:()=>this.config.webcvProvider,getWasmDnsProvider:()=>this.config.wasmdnsProvider,getWasmAecProvider:()=>this.config.wasmaecProvider,getWasmVqeProvider:()=>this.config.wasmVqeProvider,getEncodedStreamsWorkerProvider:()=>v,domOverrides:this.config.domOverrides,configProvider:this.configProvider};f.setConfigProvider(this.configProvider);const _=eP.build(this.logger,C,this.configProvider,this.mediaAgentDiagnostics,this.ufdManager,this.deviceManager,this.capabilities,S);return _.constants=eP.constants,this.mediaAgents.push(_),_}async dispose(g){return Promise.all([this.deviceManager.dispose(),this.ufdManager.dispose(),this.configProvider.dispose(),this.capabilities.dispose(),...this.mediaAgents.map((f=>f.dispose(g)))]).then((()=>{this.mediaAgents=[]}))}},rP=class extends Error{constructor(g,f="failure"){super(g),this.reason=f}},sP=class{constructor(){this.supportedPlatforms=new Map([["Chrome","59.0"],["EdgeAnaheim","79.0"],["Safari","13.1"],["Electron","3.0"],["Firefox","96.0"],["Maglev","1.0"]]),this.experimentalPlatforms=new Map}getPlatformSupportLevel(g){const f=et.getBrowserInfo(),S=this.supportedPlatforms.get(f.name);if(g&&S&&et.isVersionGreaterOrEqual(S))return 1;if(g&&!S){if(et.isEngine("Chromium","ChromiumAVD"))return 2;const g=this.experimentalPlatforms.get(f.name);if(g&&et.isVersionGreaterOrEqual(g))return 2}return 0}},aP=class extends Ke{constructor(g,f,S){super(),this.relayManagerProvider=g,this.configProvider=f,this.logger=S,this.currentInfo={},this.currentAreaContent={},this.isEnabled=!1,this.isEnabled=this.configProvider.config.enableE911,f.on("configUpdated",(()=>{const g=this.isEnabled;this.isEnabled=this.configProvider.config.enableE911,!this.isEnabled||g===this.isEnabled&&this.prober||(this.prober?.dispose(),this.prober=void 0,this.configProvider.config.probeE911OnInit&&this.probeForIP("config"))}))}get info(){return this.currentInfo}get areaContent(){return this.currentAreaContent}async getInfo(){return this.isEnabled&&!this.prober&&await this.probeForIP("publicGetInfo"),this.currentInfo}setClientInfo(g,f){if(this.isEnabled)switch(this.logger.info(`Client info for ${g} set`),g){case 3:this.mergeClientAreaInfo(JSON.parse(f));break;case 1:break;case 2:this.mergeClientNetworkInfo(JSON.parse(f))}}mergeClientAreaInfo(g){const f=JSON.stringify(this.currentAreaContent);this.currentAreaContent.geoCoordinates=g.geoCoordinates,removeUndefinedFields(this.currentAreaContent),JSON.stringify(this.currentAreaContent)!==f&&this.raiseChanged()}mergeClientNetworkInfo(g){if(0===Object.keys(g).length){const g=Object.keys(this.currentInfo).length+Object.keys(this.currentAreaContent).length;return this.currentInfo={},this.currentAreaContent={},void(g>0&&this.raiseChanged())}const f=this.currentInfo.bssid!==g.bssid||this.currentInfo.bssidv6!==g.bssidv6||this.currentInfo.mac!==g.mac||this.currentInfo.macv6!==g.macv6||this.currentInfo.subnetLengthIpv4!==g.subnetLengthIpv4||this.currentInfo.subnetLengthIpv6!==g.subnetLengthIpv6,S=this.currentInfo.e911;this.currentInfo.bssid=g.bssid,this.currentInfo.bssidv6=g.bssidv6,this.currentInfo.e911=g.e911,this.currentInfo.mac=g.mac,this.currentInfo.macv6=g.macv6,this.currentInfo.subnetLengthIpv4=g.subnetLengthIpv4,this.currentInfo.subnetLengthIpv6=g.subnetLengthIpv6,removeUndefinedFields(this.currentInfo),f?this.probeForIP("clientNetworkInfoChanged").then((g=>{g||this.raiseChanged()})):JSON.stringify(S)!==JSON.stringify(g.e911)&&this.raiseChanged()}async probeForIP(g){return this.probingPromise?(this.logger.info(`Probing already in progress, tried to start for: ${g}`),this.probingPromise):(this.probingPromise=this.probeForIPInternal(g),this.probingPromise.then((g=>(this.probingPromise=void 0,g))).catch((g=>(this.probingPromise=void 0,this.logger.error(`E911 probing failed: ${stringifyObject(g)}`),!1))))}async probeForIPInternal(g){this.logger.info(`Probing for public IP address: ${g}`);const f=await this.ensureProber();if(await f.ensureOnline(),f.ipFromRelay){if((this.currentInfo.ipv4||this.currentInfo.ipv6)!==f.ipFromRelay)return delete this.currentInfo.ipv4,delete this.currentInfo.ipv6,this.currentInfo[la.test(f.ipFromRelay)?"ipv4":"ipv6"]=f.ipFromRelay,this.raiseChanged(),!0}else if(0!==Object.keys(this.currentInfo).length)return this.currentInfo={},this.raiseChanged(),!0;return!1}async ensureProber(){if(this.prober)return this.prober;const g=createProbeIceServers(await this.relayManagerProvider.getOrCreateRelayManager().queryRelaysAsync({relayType:"turn"}),this.configProvider.config);return this.prober=new ST(g,new rT(this.logger.createChild("Prober"),this.logger.createChild("ProberUnsafe"))),this.prober}},oP=class extends Ke{constructor(g){super(),this.ecsFilters=g,this.config=null}get ETag(){return this.etag}async setEcsConfig(g){this.config=JSON.parse(g.ecsBlob),this.etag=g.etag,this.event("OnECSChanged").raise()}async setUserEcsServerUrl(g,f){throw new Error("Not implemented")}async getUserEcsServerUrl(g){throw new Error("Not implemented")}async setActiveUserForEcs(g){throw new Error("Not implemented")}async getEcsQueryParameters(){const g={};g.CLRelease=getTsCallingVersion();const f="_TS_BUILC_VERSION_".replace("C","D"),S=this.ecsFilters?.["UserInfo.Ring"]?.value,v=this.getTeamsExperience();g.CLRelease===f&&(g.CLRelease="9999.99"),S&&(g.audienceGroup=S,g.teamsRing=S),v&&(g.Experience=v),"vdi3"===this.ecsFilters?.vdi?.value&&(g.vdi="vdi3");const C=et.getBrowserInfo();return g.BrowserName=C.name,g.BrowserEngine=C.engine,g.BrowserVersion=C.version,g.FormFactor=C.formFactor,g.OsName=C.osName,g.OsVer=C.osVersion,oa.hardwareConcurrency&&(g.CPUCount=oa.hardwareConcurrency),JSON.stringify(g)}async ecsGetUserQueryParameters(g){return this.getEcsQueryParameters()}async shouldTriggerCQF(g,f,S){throw new Error("Not implemented")}getEcsConfig(g,f){const S=this.config?.[g];return f?S?.[f]:S}createEcsConfiguration(){return new class{constructor(g){this.provider=g}getBoolean(g,f){return this.provider.getEcsConfig(g,f)}getNumber(g,f){return this.provider.getEcsConfig(g,f)}getString(g,f){const S=this.provider.getEcsConfig(g,f);return JSON.stringify(S)}}(this)}getTeamsExperience(){return!0===this.ecsFilters?.isTeams2?.value?"teams2":!1===this.ecsFilters?.isTeams2?.value?"teams1":void 0}},lP=class{constructor(g){this._sharingSource=g}getId(){return this._sharingSource.getId()}getDeviceId(){return this._sharingSource.getDeviceId()}getType(){return this.mapSharingSourceType(this._sharingSource.getType())}getPreview(g,f,S){return Promise.reject("not implemented")}getPreviewAsync(g,f){return this._sharingSource.getPreviewAsync(g,f)}getDescription(){return this._sharingSource.getDescription()}getIcon(g,f){return this._sharingSource.getIcon(g,f)}getBounds(){}mapSharingSourceType(g){switch(g){case 1:return 1;case 2:return 2;case 3:return 3;default:throw new Error("Invalid sharing source type")}}},cP=class extends Ke{constructor(g){super(),this._screenSharingManager=g,this._screenSharingManager.onScreensChanged((()=>{this.event("screensChanged").raise()}))}enumerateScreensAsync(){return this._screenSharingManager.enumerateScreensAsync().then((g=>g.map((g=>new lP(g)))))}enumerateWindowsAsync(){return this._screenSharingManager.enumerateWindowsAsync().then((g=>g.map((g=>new lP(g)))))}enumerateCamerasAsync(){return this._screenSharingManager.enumerateCamerasAsync().then((g=>g.map((g=>new lP(g)))))}},dP=R,updateSignalingAgentConfig=(g,f)=>{if(!f)return g;const S={...g};if(f.ngIncoming&&f.ngOutgoing){const v=convertScreenSharingFlag(f.ngIncoming.isVBSSEnabled,f.ngOutgoing.isVBSSEnabled);S.cloudScreenSharingFlag=getParam(v,g.cloudScreenSharingFlag)}return f.ngOutgoing&&(S.emergencyCallCountry=convertEmergencyCallCountryFlag(f.ngOutgoing.isEmergencyCallingEnabled,g.emergencyCallCountry),S.isGVCOutgoingEnabled=getParam(f.ngOutgoing.isGVCEnabled,g.isGVCOutgoingEnabled),S.brokerEnabledOutgoing=getParam(f.ngOutgoing.isBrokerEnabled,g.brokerEnabledOutgoing)),f.ngIncoming&&(S.isGVCJoiningEnabled=getParam(f.ngIncoming.isGVCEnabled,g.isGVCJoiningEnabled),S.brokerEnabledIncoming=getParam(f.ngIncoming.isBrokerEnabled,g.brokerEnabledIncoming)),S.conversationServiceUrl=getUrl(f.conversationServiceUrl,g.conversationServiceUrl),S.uploadLogRequestUrl=getUrl(f.uploadLogRequestUrl,g.uploadLogRequestUrl),S.isConversationServiceUrlFromEcs=!!f.conversationServiceUrl,S.isUploadLogRequestUrlFromEcs=!!f.uploadLogRequestUrl,S.callingTokenLogicalUrl=getUrl(f.callingTokenLogicalUrl,g.callingTokenLogicalUrl),S.doHostlessCalling=getParam(f.allowHostlessCalls,g.doHostlessCalling),S.supportsCompressedServicePayload=getParam(f.supportCompressedTrouterPayload,g.supportsCompressedServicePayload),S.brokerRequestBatching=getParam(f.allowBrokerSubscribeBatching,g.brokerRequestBatching),S.brokerExclusively=getParam(f.brokerExclusively,g.brokerExclusively),S.handleMediaOfferFromPushNotification=getParam(f.handleMediaOfferFromPushNotification,g.handleMediaOfferFromPushNotification),S.handleNewOfferRequest=getParam(f.handleNewOfferRequest,g.handleNewOfferRequest),S.sendProgressFromCC=getParam(f.sendProgressFromCC,g.sendProgressFromCC),S.useInternalHttpDispatcher=getParam(f.webInternalHttpDispatcher,g.useInternalHttpDispatcher),(f.webInternalHttpDispatcherConfigNetworkRequest||g.requestTypeHttpDispatcherConfigMap)&&(f.webInternalHttpDispatcherConfigNetworkRequest=f.webInternalHttpDispatcherConfigNetworkRequest||{},g.requestTypeHttpDispatcherConfigMap=g.requestTypeHttpDispatcherConfigMap||{},S.requestTypeHttpDispatcherConfigMap={...g.requestTypeHttpDispatcherConfigMap,...f.webInternalHttpDispatcherConfigNetworkRequest}),(f.operationTypeHttpDispatcherConfigMap||g.operationTypeHttpDispatcherConfigMap)&&(f.operationTypeHttpDispatcherConfigMap=f.operationTypeHttpDispatcherConfigMap||{},g.operationTypeHttpDispatcherConfigMap=g.operationTypeHttpDispatcherConfigMap||{},S.operationTypeHttpDispatcherConfigMap={...g.operationTypeHttpDispatcherConfigMap,...f.operationTypeHttpDispatcherConfigMap}),(f.csaTimeoutConfiguration||g.csaTimeoutConfiguration)&&(f.csaTimeoutConfiguration=f.csaTimeoutConfiguration||{},g.csaTimeoutConfiguration=g.csaTimeoutConfiguration||{},S.csaTimeoutConfiguration={...g.csaTimeoutConfiguration,...f.csaTimeoutConfiguration}),S.autoJoinOnConflict=getParam(f.autoJoinOnConflict,g.autoJoinOnConflict),S.enableQuickSendAcceptanceAck=getParam(f.enableQuickSendAcceptanceAck,g.enableQuickSendAcceptanceAck),S.supportMediaRetargetWhileIncomingRenegotiation=getParam(f.supportMediaRetargetWhileIncomingRenegotiation,g.supportMediaRetargetWhileIncomingRenegotiation),S.enableCallEstablishmentTimeoutsForStartJoinCall=getParam(f.enableCallEstablishmentTimeoutsForStartJoinCall,g.enableCallEstablishmentTimeoutsForStartJoinCall),S.callingServiceSupportsCAETokens=getParam(f.callingServiceSupportsCAETokens,g.callingServiceSupportsCAETokens),S.callingServiceSupportsAADTokens=getParam(f.callingServiceSupportsAADTokens,g.callingServiceSupportsAADTokens),S.aadTokenExpirationTimeInSeconds=getParam(f.aadTokenExpirationTimeInSeconds,g.aadTokenExpirationTimeInSeconds),S.caeTokenExpirationTimeInSeconds=getParam(f.caeTokenExpirationTimeInSeconds,g.caeTokenExpirationTimeInSeconds),S.disableTokenMigrationHeader=getParam(f.disableTokenMigrationHeader,g.disableTokenMigrationHeader),S.enablePublishTokenTelemetry=getParam(f.enablePublishTokenTelemetry,g.enablePublishTokenTelemetry),S.refreshTimeBeforeTokenTimeoutInSeconds=getParam(f.refreshTimeBeforeTokenTimeoutInSeconds,g.refreshTimeBeforeTokenTimeoutInSeconds),S.forceClearExpiredTokens=getParam(f.forceClearExpiredTokens,g.forceClearExpiredTokens),S.enableRefreshToken=getParam(f.enableRefreshToken,g.enableRefreshToken),S.enableAsyncDisablePreheat=getParam(f.enableAsyncDisablePreheat,g.enableAsyncDisablePreheat),S.forceLowercaseHttpHeaders=getParam(f.forceLowercaseHttpHeaders,g.forceLowercaseHttpHeaders),S.enableResolveScreenSharingWhenNegotiationComplete=getParam(f.enableResolveScreenSharingWhenNegotiationComplete,g.enableResolveScreenSharingWhenNegotiationComplete),S.maxReinvitelessMediaForVideoForWeb=getParam(f.maxReinvitelessMediaForVideoForWeb,g.maxReinvitelessMediaForVideoForWeb),S.maxReinvitelessMediaForVBSSForWeb=getParam(f.maxReinvitelessMediaForVBSSForWeb,g.maxReinvitelessMediaForVBSSForWeb),S.enableRefreshTokenRetry=getParam(f.enableRefreshTokenRetry,g.enableRefreshTokenRetry),S.enableRefreshTokenRetryInSeconds=getParam(f.enableRefreshTokenRetryInSeconds,g.enableRefreshTokenRetryInSeconds),S.enableConversationTypeUpdateOnCallEnd=getParam(f.enableConversationTypeUpdateOnCallEnd,g.enableConversationTypeUpdateOnCallEnd),S.supportMissingTokenTypesInResponse=getParam(f.supportMissingTokenTypesInResponse,g.supportMissingTokenTypesInResponse),S.useSkypeTokenWhenNoAuthenticateHeader=getParam(f.useSkypeTokenWhenNoAuthenticateHeader,g.useSkypeTokenWhenNoAuthenticateHeader),S.enableAutoPromotion=getParam(f.enableAutoPromotion,g.enableAutoPromotion),S.enableTokenCache=getParam(f.enableTokenCache,g.enableTokenCache),S.enableBatchedSendMessageStatus=getParam(f.enableBatchedSendMessageStatus,g.enableBatchedSendMessageStatus),S.enableBatchedReceiveMessage=getParam(f.enableBatchedReceiveMessage,g.enableBatchedReceiveMessage),S.enableTokenCacheForGenericTokenAPI=getParam(f.enableTokenCacheForGenericTokenAPI,g.enableTokenCacheForGenericTokenAPI),S.disableRealTimeModeFromRoster=getParam(f.disableRealTimeModeFromRoster,g.disableRealTimeModeFromRoster),S.enableLongOutgoing1To1SetupTimeoutForWeb=getParam(f.enableLongOutgoing1To1SetupTimeoutForWeb,g.enableLongOutgoing1To1SetupTimeoutForWeb),S.checkAttendeeRoleInCreateContentSharing=getParam(f.checkAttendeeRoleInCreateContentSharing,g.checkAttendeeRoleInCreateContentSharing),S.enableSpecificErrorCodesForCallEnd=getParam(f.enableSpecificErrorCodesForCallEnd,g.enableSpecificErrorCodesForCallEnd),S.enableSplitConversationEndUrl=getParam(f.enableSplitConversationEndUrl,g.enableSplitConversationEndUrl),S.enableFetchRequestWithKeepAlive=getParam(f.enableFetchRequestWithKeepAlive,g.enableFetchRequestWithKeepAlive),S.enableFetchApi=getParam(f.enableFetchApi,g.enableFetchApi),S.enableFetchApiForBeacon=getParam(f.enableFetchApiForBeacon,g.enableFetchApiForBeacon),S};function getParam(g,f){return null==g?f:g}function getUrl(g,f){return g||f}function convertScreenSharingFlag(g,f){return f&&g?"enabled":g?"recvOnly":!1===g&&!1===f?"disabled":void 0}function convertEmergencyCallCountryFlag(g,f){return!1===g?"":f}var hP,uP="SkypeCalling",gP=class{constructor(g,f,S,v){this.signalingAgentConfig=g,this.ecsProvider=f,this.logger=S,this.telemetryLogger=v,this.ecsProvider.on("OnECSChanged",(()=>this.onEcsUpdate())),this.signalingAgentConfig.clientInformation+=`/TsCallingVersion=${getTsCallingVersion()}/Ovb=${getOvb()}`,this.signalingAgentConfig.piiScrubber={omit:dP.pii.Omit,mri:dP.pii.Mri},this.signalingAgent=new ir(this.getSignalingAgentConfig())}getSignalingAgent(){return this.signalingAgent}onEcsUpdate(){const g=this.ecsProvider.getEcsConfig(uP);this.logger.info(`onEcsUpdate, ecsTag=${this.ecsProvider.ETag||""}, ecsConfig=${JSON.stringify(g)}`),this.signalingAgentConfig=updateSignalingAgentConfig(this.signalingAgentConfig,g),this.signalingAgentConfig.ecsEtag=this.ecsProvider.ETag,this.signalingAgent.updateSignalingAgentConfig(this.getSignalingAgentConfig())}getSignalingAgentConfig(){return this.signalingAgentConfig.oneDsTelemetryLogger=this.telemetryLogger,this.signalingAgentConfig}},pP={build:(g,f,S,v)=>new gP(g,f,S,v)},mP=__toESM(M),fP="toLowerCase",SP="blkVal",vP="length",CP="rdOnly",yP="notify",EP="warnToConsole",_P="throwInternal",TP="setDf",IP="watch",bP="logger",AP="apply",PP="push",RP="splice",MP="hdlr",wP="cancel",OP="initialize",DP="identifier",NP="isInitialized",kP="getPlugin",LP="name",FP="time",xP="processNext",UP="getProcessTelContext",VP="unload",BP="loggingLevelConsole",HP="createNew",$P="teardown",jP="messageId",GP="message",qP="isAsync",WP="diagLog",zP="_doTeardown",KP="update",JP="getNext",YP="setNextPlugin",QP="userAgent",XP="nodeType",ZP="replace",eR="logInternalMessage",tR="isChildEvt",iR="getCtx",nR="setCtx",rR="complete";function throwAggregationError2(g,f){hP||(hP=createCustomError("AggregationError",(function(g,f){f[vP]>1&&(g.errors=f[1])})));var S=g||"One or more errors occurred.";throw arrForEach(f,(function(g,f){S+="\n".concat(f," > ").concat(dumpObj(g))})),new hP(S,f||[])}var sR=void 0,aR="",oR="core",lR="disabled",cR="extensionConfig",dR="processTelemetry",hR="priority",uR="getPerfMgr",gR="Not dynamic - ",pR=/-([a-z])/g,mR=/([^\w\d_$])/g,fR=/^(\d+[\w\d_$])/;function isNotNullOrUndefined2(g){return!isNullOrUndefined(g)}function normalizeJsName2(g){var f=g;return f&&dl(f)&&(f=(f=(f=f[ZP](pR,(function(g,f){return f.toUpperCase()})))[ZP](mR,"_"))[ZP](fR,(function(g,f){return"_"+f}))),f}function strContains2(g,f){return!(!g||!f)&&-1!==oc(g,f)}function toISOString2(g){return g&&g.toISOString()||""}function _createProxyFunction2(g,f){var S=null,v=null;return hl(g)?S=g:v=g,function(){var g=arguments;if(S&&(v=S()),v)return v[f][AP](v,g)}}function proxyFunctionAs2(g,f,S,v,C){g&&f&&S&&(!1!==C||isUndefined4(g[f]))&&(g[f]=_createProxyFunction2(S,v))}var SR="console",vR="JSON",CR="crypto",yR="msCrypto",ER="msie",_R="trident/",TR=null,IR=null;function getConsole2(){return typeof console!==Fo?console:getInst(SR)}function hasJSON2(){return Boolean(typeof JSON===Lo&&JSON||null!==getInst(vR))}function getJSON2(){return hasJSON2()?JSON||getInst(vR):null}function getCrypto2(){return getInst(CR)}function getMsCrypto2(){return getInst(yR)}function isIE2(){var g=Kl();if(g&&(g[QP]!==IR||null===TR)){var f=((IR=g[QP])||aR)[fP]();TR=strContains2(f,ER)||strContains2(f,_R)}return TR}var bR=4294967296,AR=4294967295,PR=123456789,RR=987654321,MR=!1,wR=PR,OR=RR;function _mwcSeed2(g){g<0&&(g>>>=0),wR=PR+g&AR,OR=RR-g&AR,MR=!0}function _autoSeedMwc2(){try{var g=2147483647&utcNow();_mwcSeed2((Math.random()*bR^g)+g)}catch(g){}}function random322(g){var f=0,S=getCrypto2()||getMsCrypto2();return S&&S.getRandomValues&&(f=S.getRandomValues(new Uint32Array(1))[0]&AR),0===f&&isIE2()&&(MR||_autoSeedMwc2(),f=mwcRandom322()&AR),0===f&&(f=Math.floor(bR*Math.random()|0)),g||(f>>>=0),f}function mwcRandom322(g){var f=((OR=36969*(65535&OR)+(OR>>16)&AR)<<16)+(65535&(wR=18e3*(65535&wR)+(wR>>16)&AR))>>>0&AR|0;return g||(f>>>=0),f}function newId2(g){void 0===g&&(g=22);for(var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S=random322()>>>0,v=0,C=aR;C[vP]<g;)v++,C+=f.charAt(63&S),S>>>=6,5===v&&(S=(random322()<<2&4294967295|3&S)>>>0,v=0);return C}var DR="3.3.1",NR="."+newId2(6),kR=0;function _canAcceptData2(g){return 1===g[XP]||9===g[XP]||!+g[XP]}function _getCache2(g,f){var S=f[g.id];if(!S){S={};try{_canAcceptData2(f)&&objDefine(f,g.id,{e:!1,v:S})}catch(g){}}return S}function createUniqueNamespace2(g,f){return void 0===f&&(f=!1),normalizeJsName2(g+kR+++(f?"."+DR:aR)+NR)}function createElmNodeData2(g){var f={id:createUniqueNamespace2("_aiData-"+(g||aR)+"."+DR),accept:function(g){return _canAcceptData2(g)},get:function(g,S,v,C){var _=g[f.id];return _?_[normalizeJsName2(S)]:(C&&((_=_getCache2(f,g))[normalizeJsName2(S)]=v),v)},kill:function(g,f){if(g&&g[f])try{delete g[f]}catch(g){}}};return f}function _isConfigDefaults2(g){return g&&isObject3(g)&&(g.isVal||g.fb||vl(g,"v")||vl(g,"mrg")||vl(g,"ref")||g.set)}function _getDefault2(g,f,S){var v,C=S.dfVal||isDefined2;if(f&&S.fb){var _=S.fb;ul(_)||(_=[_]);for(var T=0;T<_[vP];T++){var I=_[T],b=f[I];if(C(b)?v=b:g&&(C(b=g.cfg[I])&&(v=b),g.set(g.cfg,_l(I),b)),C(v))break}}return!C(v)&&C(S.v)&&(v=S.v),v}function _resolveDefaultValue2(g,f,S){var v,C=S;(S&&_isConfigDefaults2(S)&&(C=_getDefault2(g,f,S)),C)&&(_isConfigDefaults2(C)&&(C=_resolveDefaultValue2(g,f,C)),ul(C)?(v=[])[vP]=C[vP]:isPlainObject(C)&&(v={}),v&&(objForEachKey(C,(function(S,C){C&&_isConfigDefaults2(C)&&(C=_resolveDefaultValue2(g,f,C)),v[S]=C})),C=v));return C}function _applyDefaultValue2(g,f,S,v){var C,_,T,I,b,A,P,R,M=v;_isConfigDefaults2(M)?(C=M.isVal,_=M.set,A=M[CP],P=M[SP],I=M.mrg,!(b=M.ref)&&isUndefined4(b)&&(b=!!I),T=_getDefault2(g,f,M)):T=v,P&&g[SP](f,S);var w=!0,O=f[S];!O&&isNullOrUndefined(O)||(R=O,w=!1,C&&R!==T&&!C(R)&&(R=T,w=!0),_&&(w=(R=_(R,T,f))===T)),w?R=T?_resolveDefaultValue2(g,f,T):T:(isPlainObject(R)||ul(T))&&I&&T&&(isPlainObject(T)||ul(T))&&objForEachKey(T,(function(f,S){_applyDefaultValue2(g,R,f,S)})),g.set(f,S,R),b&&g.ref(f,S),A&&g[CP](f,S)}var LR=symbolFor("[[ai_dynCfg_1]]"),FR=symbolFor("[[ai_blkDynCfg_1]]"),xR=symbolFor("[[ai_frcDynCfg_1]]");function _cfgDeepCopy2(g){var f;if(g&&(ul(g)?(f=[])[vP]=g[vP]:isPlainObject(g)&&(f={}),f))return objForEachKey(g,(function(g,S){f[g]=_cfgDeepCopy2(S)})),f;return g}function getDynamicConfigHandler2(g){if(g){var f=g[LR]||g;if(f.cfg&&(f.cfg===g||f.cfg[LR]===f))return f}return null}function blockDynamicConversion2(g){if(g&&(isPlainObject(g)||ul(g)))try{g[FR]=!0}catch(g){}return g}function _canMakeDynamic2(g,f,S){var v=!1;return S&&!g[f.blkVal]&&((v=S[xR])||S[FR]||(v=isPlainObject(S)||ul(S))),v}function throwInvalidAccess2(g){throwTypeError("InvalidAccess:"+g)}var UR=["push","pop","shift","unshift","splice"],_throwDynamicError2=function(g,f,S,v){g&&g[_P](3,108,"".concat(S," [").concat(f,"] failed - ")+dumpObj(v))};function _patchArray2(g,f,S){ul(f)&&arrForEach(UR,(function(v){var C=f[v];f[v]=function(){for(var v=[],_=0;_<arguments.length;_++)v[_]=arguments[_];var T=C[AP](this,v);return _makeDynamicObject2(g,f,S,"Patching"),T}}))}function _getOwnPropGetter2(g,f){var S=Sl(g,f);return S&&S.get}function _createDynamicProperty2(g,f,S,v){var C={n:S,h:[],trk:function(f){f&&f.fn&&(-1===Yl(C.h,f)&&C.h[PP](f),g.trk(f,C))},clr:function(g){var f=Yl(C.h,g);-1!==f&&C.h[RP](f,1)}},_=!0,T=!1;function _getProperty(){_&&(T=T||_canMakeDynamic2(_getProperty,g,v),v&&!v[LR]&&T&&(v=_makeDynamicObject2(g,v,S,"Converting")),_=!1);var f=g.act;return f&&C.trk(f),v}function _setProperty(I){if(v!==I){_getProperty[g.ro]&&!g.upd&&throwInvalidAccess2("["+S+"] is read-only:"+dumpObj(f)),_&&(T=T||_canMakeDynamic2(_getProperty,g,v),_=!1);var b=T&&_getProperty[g.rf];if(T)if(b){objForEachKey(v,(function(g){v[g]=I?I[g]:sR}));try{objForEachKey(I,(function(f,S){_setDynamicProperty2(g,v,f,S)})),I=v}catch(f){_throwDynamicError2((g.hdlr||{})[bP],S,"Assigning",f),T=!1}}else v&&v[LR]&&objForEachKey(v,(function(f){var S=_getOwnPropGetter2(v,f);if(S){var C=S[g.prop];C&&C.chng()}}));if(I!==v){var A=I&&_canMakeDynamic2(_getProperty,g,I);!b&&A&&(I=_makeDynamicObject2(g,I,S,"Converting")),v=I,T=A}g.add(C)}}_getProperty[g.prop]={chng:function(){g.add(C)}},objDefine(f,C.n,{g:_getProperty,s:_setProperty})}function _setDynamicProperty2(g,f,S,v){if(f){var C=_getOwnPropGetter2(f,S);C&&!!C[g.prop]?f[S]=v:_createDynamicProperty2(g,f,S,v)}return f}function _setDynamicPropertyState2(g,f,S,v){if(f){var C=_getOwnPropGetter2(f,S),_=C&&!!C[g.prop],T=v&&v[0],I=v&&v[1],b=v&&v[2];if(!_){if(b)try{blockDynamicConversion2(f)}catch(f){_throwDynamicError2((g.hdlr||{})[bP],S,"Blocking",f)}try{_setDynamicProperty2(g,f,S,f[S]),C=_getOwnPropGetter2(f,S)}catch(f){_throwDynamicError2((g.hdlr||{})[bP],S,"State",f)}}T&&(C[g.rf]=T),I&&(C[g.ro]=I),b&&(C[g.blkVal]=!0)}return f}function _makeDynamicObject2(g,f,S,v){try{objForEachKey(f,(function(S,v){_setDynamicProperty2(g,f,S,v)})),f[LR]||(yl(f,LR,{get:function(){return g[MP]}}),_patchArray2(g,f,S))}catch(f){_throwDynamicError2((g.hdlr||{})[bP],S,v,f)}return f}var VR="[[ai_",BR="]]";function _createState2(g){var f,S,v=newSymbol(VR+"get"+g.uid+BR),C=newSymbol(VR+"ro"+g.uid+BR),_=newSymbol(VR+"rf"+g.uid+BR),T=newSymbol(VR+"blkVal"+g.uid+BR),I=newSymbol(VR+"dtl"+g.uid+BR),b=null,A=null;function _useHandler(f,v){var C=S.act;try{S.act=f,f&&f[I]&&(arrForEach(f[I],(function(g){g.clr(f)})),f[I]=[]),v({cfg:g.cfg,set:g.set.bind(g),setDf:g[TP].bind(g),ref:g.ref.bind(g),rdOnly:g[CP].bind(g)})}catch(f){var _=g[bP];throw _&&_[_P](1,107,dumpObj(f)),f}finally{S.act=C||null}}function _notifyWatchers(){if(b){var g=b;b=null,A&&A[wP](),A=null;var f=[];if(arrForEach(g,(function(g){if(g&&(g[I]&&(arrForEach(g[I],(function(f){f.clr(g)})),g[I]=null),g.fn))try{_useHandler(g,g.fn)}catch(g){f[PP](g)}})),b)try{_notifyWatchers()}catch(g){f[PP](g)}f[vP]>0&&throwAggregationError2("Watcher error(s): ",f)}}function _addWatcher(g){if(g&&g.h[vP]>0){b||(b=[]),A||(A=scheduleTimeout((function(){A=null,_notifyWatchers()}),0));for(var f=0;f<g.h[vP];f++){var S=g.h[f];S&&-1===Yl(b,S)&&b[PP](S)}}}function _trackHandler(g,f){if(g){var S=g[I]=g[I]||[];-1===Yl(S,f)&&S[PP](f)}}return(f={prop:v,ro:C,rf:_})[SP]=T,f[MP]=g,f.add=_addWatcher,f[yP]=_notifyWatchers,f.use=_useHandler,f.trk=_trackHandler,S=f}function _createAndUseHandler2(g,f){var S={fn:f,rm:function(){S.fn=null,g=null,f=null}};return objDefine(S,"toJSON",{v:function(){return"WatcherHandler"+(S.fn?"":"[X]")}}),g.use(S,f),S}function _createDynamicHandler2(g,f,S){var v,C=getDynamicConfigHandler2(f);if(C)return C;var _,T=createUniqueNamespace2("dyncfg",!0),I=f&&!1!==S?f:_cfgDeepCopy2(f);function _notifyWatchers(){_[yP]()}function _setValue(f,S,v){try{f=_setDynamicProperty2(_,f,S,v)}catch(f){_throwDynamicError2(g,S,"Setting value",f)}return f[S]}function _watch(g){return _createAndUseHandler2(_,g)}function _block(g,f){_.use(null,(function(S){var v=_.upd;try{isUndefined4(f)||(_.upd=f),g(S)}finally{_.upd=v}}))}function _ref(g,f){var S;return _setDynamicPropertyState2(_,g,f,(S={},S[0]=!0,S))[f]}function _rdOnly(g,f){var S;return _setDynamicPropertyState2(_,g,f,(S={},S[1]=!0,S))[f]}function _blkPropValue(g,f){var S;return _setDynamicPropertyState2(_,g,f,(S={},S[2]=!0,S))[f]}function _applyDefaults(g,f){return f&&objForEachKey(f,(function(f,S){_applyDefaultValue2(b,g,f,S)})),g}var b=((v={uid:null,cfg:I})[bP]=g,v[yP]=_notifyWatchers,v.set=_setValue,v[TP]=_applyDefaults,v[IP]=_watch,v.ref=_ref,v[CP]=_rdOnly,v[SP]=_blkPropValue,v._block=_block,v);return objDefine(b,"uid",{c:!1,e:!1,w:!1,v:T}),_makeDynamicObject2(_=_createState2(b),I,"config","Creating"),b}function _logInvalidAccess2(g,f){g?(g[EP](f),g[_P](2,108,f)):throwInvalidAccess2(f)}function createDynamicConfig2(g,f,S,v){var C=_createDynamicHandler2(S,g||{},v);return f&&C[TP](C.cfg,f),C}function onConfigChange2(g,f,S){var v=g[LR]||g;return!v.cfg||v.cfg!==g&&v.cfg[LR]!==v?(_logInvalidAccess2(S,gR+dumpObj(g)),createDynamicConfig2(g,null,S)[IP](f)):v[IP](f)}var HR,$R=null;function _getExtensionNamespace2(){var g=getInst("Microsoft");return g&&($R=g.ApplicationInsights),$R}function getDebugExt2(g){var f=$R;return f||!0===g.disableDbgExt||(f=$R||_getExtensionNamespace2()),f?f.ChromeDbgExt:null}var jR="warnToConsole",GR="AI (Internal): ",qR="AI: ",WR="AITR_",zR={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},KR=((HR={})[0]=null,HR[1]="errorToConsole",HR[2]=jR,HR[3]="debugToConsole",HR);function _sanitizeDiagnosticText2(g){return g?'"'+g[ZP](/\"/g,aR)+'"':aR}function _logToConsole2(g,f){var S=getConsole2();if(S){var v="log";S[g]&&(v=g),hl(S[v])&&S[v](f)}}var JR=function(){function _InternalLogMessage3(g,f,S,v){void 0===S&&(S=!1);var C=this;C[jP]=g,C[GP]=(S?qR:GR)+g;var _=aR;hasJSON2()&&(_=getJSON2().stringify(v));var T=(f?" message:"+_sanitizeDiagnosticText2(f):aR)+(v?" props:"+_sanitizeDiagnosticText2(_):aR);C[GP]+=T}return _InternalLogMessage3.dataType="MessageData",_InternalLogMessage3}();function safeGetLogger2(g,f){return(g||{})[bP]||new YR(f)}var YR=function(){function DiagnosticLogger3(g){this.identifier="DiagnosticLogger",this.queue=[];var f,S,v,C,_,T=0,I={};dynamicProto(DiagnosticLogger3,this,(function(b){function _logInternalMessage3(g,f){if(!_areInternalMessagesThrottled()){var C=!0,_=WR+f[jP];if(I[_]?C=!1:I[_]=!0,C&&(g<=S&&(b.queue[PP](f),T++,_debugExtMsg(1===g?"error":"warn",f)),T===v)){var A="Internal events throttle limit per PageView reached for this app.",P=new JR(23,A,!1);b.queue[PP](P),1===g?b.errorToConsole(A):b[EP](A)}}}function _setDefaultsFromConfig(g){return onConfigChange2(createDynamicConfig2(g,zR,b).cfg,(function(g){var _=g.cfg;f=_[BP],S=_.loggingLevelTelemetry,v=_.maxMessageLimit,C=_.enableDebug}))}function _areInternalMessagesThrottled(){return T>=v}function _debugExtMsg(f,S){var v=getDebugExt2(g||{});v&&v[WP]&&v[WP](f,S)}_=_setDefaultsFromConfig(g||{}),b.consoleLoggingLevel=function(){return f},b[_P]=function(g,S,v,_,T){void 0===T&&(T=!1);var A=new JR(S,v,T,_);if(C)throw dumpObj(A);var P=KR[g]||jR;if(isUndefined4(A[GP]))_debugExtMsg("throw"+(1===g?"Critical":"Warning"),A);else{if(T){var R=+A[jP];!I[R]&&f>=g&&(b[P](A[GP]),I[R]=!0)}else f>=g&&b[P](A[GP]);_logInternalMessage3(g,A)}},b.debugToConsole=function(g){_logToConsole2("debug",g),_debugExtMsg("warning",g)},b[EP]=function(g){_logToConsole2("warn",g),_debugExtMsg("warning",g)},b.errorToConsole=function(g){_logToConsole2("error",g),_debugExtMsg("error",g)},b.resetInternalMessageCount=function(){T=0,I={}},b[eR]=_logInternalMessage3,b[VP]=function(g){_&&_.rm(),_=null}}))}return DiagnosticLogger3.__ieDyn=1,DiagnosticLogger3}();function _getLogger2(g){return g||new YR}function _throwInternal2(g,f,S,v,C,_){void 0===_&&(_=!1),_getLogger2(g)[_P](f,S,v,C,_)}var QR="ctx",XR="ParentContextKey",ZR="ChildrenContextKey",eM=function(){function PerfEvent3(g,f,S){var v,C=this;(C.start=utcNow(),C[LP]=g,C[qP]=S,C[tR]=function(){return!1},hl(f))&&objDefine(C,"payload",{g:function(){return!v&&hl(f)&&(v=f(),f=null),v}});C[iR]=function(g){return g?g===PerfEvent3[XR]||g===PerfEvent3[ZR]?C[g]:(C[QR]||{})[g]:null},C[nR]=function(g,f){if(g)if(g===PerfEvent3[XR])C[g]||(C[tR]=function(){return!0}),C[g]=f;else if(g===PerfEvent3[ZR])C[g]=f;else{(C[QR]=C[QR]||{})[g]=f}},C[rR]=function(){var g=0,f=C[iR](PerfEvent3[ZR]);if(ul(f))for(var S=0;S<f[vP];S++){var v=f[S];v&&(g+=v[FP])}C[FP]=utcNow()-C.start,C.exTime=C[FP]-g,C[rR]=function(){}}}return PerfEvent3.ParentContextKey="parent",PerfEvent3.ChildrenContextKey="childEvts",PerfEvent3}(),tM="CoreUtils.doPerf";function doPerf2(g,f,S,v,C){if(g){var _=g;if(_[uR]&&(_=_[uR]()),_){var T=void 0,I=_[iR](tM);try{if(T=_.create(f(),v,C)){if(I&&T[nR]&&(T[nR](eM[XR],I),I[iR]&&I[nR])){var b=I[iR](eM[ZR]);b||(b=[],I[nR](eM[ZR],b)),b[PP](T)}return _[nR](tM,T),S(T)}}catch(g){T&&T[nR]&&T[nR]("exception",g)}finally{T&&_.fire(T),_[nR](tM,I)}}}return S()}function newGuid3(){var g=generateW3CId2();return Ll(g,0,8)+"-"+Ll(g,8,12)+"-"+Ll(g,12,16)+"-"+Ll(g,16,20)+"-"+Ll(g,20)}function generateW3CId2(){for(var g,f=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],S=aR,v=0;v<4;v++)S+=f[15&(g=random322())]+f[g>>4&15]+f[g>>8&15]+f[g>>12&15]+f[g>>16&15]+f[g>>20&15]+f[g>>24&15]+f[g>>28&15];var C=f[8+(3&random322())|0];return Fl(S,0,8)+Fl(S,9,4)+"4"+Fl(S,13,3)+C+Fl(S,16,3)+Fl(S,19,12)}var iM=createElmNodeData2("plugin");function _getPluginState2(g){return iM.get(g,"state",{},!0)}var nM,rM="TelemetryPluginChain",sM="_hasRun",aM="_getTelCtx",oM=0;function _getNextProxyStart2(g,f,S){for(;g;){if(g[kP]()===S)return g;g=g[JP]()}return createTelemetryProxyChain2([S],f.config||{},f)}function _createInternalContext2(g,f,S,v){var C=null,_=[];f||(f=createDynamicConfig2({},null,S[bP])),null!==v&&(C=v?_getNextProxyStart2(g,S,v):g);var T={_next:_moveNext,ctx:{core:function(){return S},diagLog:function(){return safeGetLogger2(S,f.cfg)},getCfg:function(){return f.cfg},getExtCfg:_resolveExtCfg,getConfig:_getConfig,hasNext:function(){return!!C},getNext:function(){return C},setNext:function(g){C=g},iterate:_iterateChain,onComplete:_addOnComplete}};function _addOnComplete(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];g&&_[PP]({func:g,self:isUndefined4(f)?T.ctx:f,args:S})}function _moveNext(){var g=C;if(C=g?g[JP]():null,!g){var f=_;f&&f[vP]>0&&(arrForEach(f,(function(g){try{g.func.call(g.self,g.args)}catch(g){_throwInternal2(S[bP],2,73,"Unexpected Exception during onComplete - "+dumpObj(g))}})),_=[])}return g}function _getExtCfg(g,S){var v=null,C=f.cfg;if(C&&g){var _=C[cR];!_&&S&&(_={}),C[cR]=_,(_=f.ref(C,cR))&&(!(v=_[g])&&S&&(v={}),_[g]=v,v=f.ref(_,g))}return v}function _resolveExtCfg(g,S){var v=_getExtCfg(g,!0);return S&&objForEachKey(S,(function(g,S){if(isNullOrUndefined(v[g])){var C=f.cfg[g];!C&&isNullOrUndefined(C)||(v[g]=C)}_applyDefaultValue2(f,v,g,S)})),f[TP](v,S)}function _getConfig(g,S,v){var C;void 0===v&&(v=!1);var _=_getExtCfg(g,!1),T=f.cfg;return!_||!_[S]&&isNullOrUndefined(_[S])?!T[S]&&isNullOrUndefined(T[S])||(C=T[S]):C=_[S],C||!isNullOrUndefined(C)?C:v}function _iterateChain(g){for(var f;f=T._next();){var S=f[kP]();S&&g(S)}}return T}function createProcessTelemetryContext2(g,f,S,v){var C=createDynamicConfig2(f),_=_createInternalContext2(g,C,S,v),T=_.ctx;function _processNext(g){var f=_._next();return f&&f[dR](g,T),!f}function _createNew(g,f){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain2(g,C.cfg,S,f)),createProcessTelemetryContext2(g||T[JP](),C.cfg,S,f)}return T[xP]=_processNext,T[HP]=_createNew,T}function createProcessTelemetryUnloadContext2(g,f,S){var v=createDynamicConfig2(f.config),C=_createInternalContext2(g,v,f,S),_=C.ctx;function _processNext(g){var f=C._next();return f&&f[VP](_,g),!f}function _createNew(g,S){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain2(g,v.cfg,f,S)),createProcessTelemetryUnloadContext2(g||_[JP](),f,S)}return _[xP]=_processNext,_[HP]=_createNew,_}function createProcessTelemetryUpdateContext2(g,f,S){var v=createDynamicConfig2(f.config),C=_createInternalContext2(g,v,f,S).ctx;function _processNext(g){return C.iterate((function(f){hl(f[KP])&&f[KP](C,g)}))}function _createNew(g,S){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain2(g,v.cfg,f,S)),createProcessTelemetryUpdateContext2(g||C[JP](),f,S)}return C[xP]=_processNext,C[HP]=_createNew,C}function createTelemetryProxyChain2(g,f,S,v){var C=null,_=!v;if(ul(g)&&g[vP]>0){var T=null;arrForEach(g,(function(g){if(_||v!==g||(_=!0),_&&g&&hl(g[dR])){var I=createTelemetryPluginProxy2(g,f,S);C||(C=I),T&&T._setNext(I),T=I}}))}return v&&!C?createTelemetryProxyChain2([v],f,S):C}function createTelemetryPluginProxy2(g,f,S){var v,C=null,_=hl(g[dR]),T=hl(g[YP]),I={getPlugin:function(){return g},getNext:function(){return C},processTelemetry:_processTelemetry,unload:_unloadPlugin,update:_updatePlugin,_id:v=g?g[DP]+"-"+g[hR]+"-"+oM++:"Unknown-0-"+oM++,_setNext:function(g){C=g}};function _getTelCtx(){var v;return g&&hl(g[aM])&&(v=g[aM]()),v||(v=createProcessTelemetryContext2(I,f,S)),v}function _processChain(f,S,_,T,I){var b=!1,A=g?g[DP]:rM,P=f[sM];return P||(P=f[sM]={}),f.setNext(C),g&&doPerf2(f[oR](),(function(){return A+":"+_}),(function(){P[v]=!0;try{var g=C?C._id:aR;g&&(P[g]=!1),b=S(f)}catch(g){var T=!C||P[C._id];T&&(b=!0),C&&T||_throwInternal2(f[WP](),1,73,"Plugin ["+A+"] failed during "+_+" - "+dumpObj(g)+", run flags: "+dumpObj(P))}}),T,I),b}function _processTelemetry(f,S){function _callProcessTelemetry(S){if(!g||!_)return!1;var v=_getPluginState2(g);return!v[$P]&&!v[lR]&&(T&&g[YP](C),g[dR](f,S),!0)}_processChain(S=S||_getTelCtx(),_callProcessTelemetry,"processTelemetry",(function(){return{item:f}}),!f.sync)||S[xP](f)}function _unloadPlugin(f,S){function _callTeardown(){var v=!1;if(g){var C=_getPluginState2(g),_=g[oR]||C[oR];!g||_&&_!==f.core()||C[$P]||(C[oR]=null,C[$P]=!0,C[NP]=!1,g[$P]&&!0===g[$P](f,S)&&(v=!0))}return v}_processChain(f,_callTeardown,"unload",(function(){}),S[qP])||f[xP](S)}function _updatePlugin(f,S){function _callUpdate(){var v=!1;if(g){var C=_getPluginState2(g),_=g[oR]||C[oR];!g||_&&_!==f.core()||C[$P]||g[KP]&&!0===g[KP](f,S)&&(v=!0)}return v}_processChain(f,_callUpdate,"update",(function(){}),!1)||f[xP](S)}return Pl(I)}function createUnloadHandlerContainer2(){var g=[];function _addHandler(f){f&&g[PP](f)}function _runHandlers(f,S){arrForEach(g,(function(g){try{g(f,S)}catch(g){_throwInternal2(f[WP](),2,73,"Unexpected error calling unload handler - "+dumpObj(g))}})),g=[]}return{add:_addHandler,run:_runHandlers}}function createUnloadHookContainer2(){var g=[];function _doUnload(f){var S=g;g=[],arrForEach(S,(function(g){try{(g.rm||g.remove).call(g)}catch(g){_throwInternal2(f,2,73,"Unloading:"+dumpObj(g))}}))}function _addHook(f){f&&arrAppend(g,f)}return{run:_doUnload,add:_addHook}}var lM,cM="getPlugin",dM=((nM={})[cR]={isVal:isNotNullOrUndefined2,v:{}},nM),hM=function(){function BaseTelemetryPlugin3(){var g,f,S,v,C,_=this;function _getTelCtx(g){void 0===g&&(g=null);var v=g;if(!v){var C=f||createProcessTelemetryContext2(null,{},_[oR]);v=S&&S[cM]?C[HP](null,S[cM]):C[HP](null,S)}return v}function _setDefaults(g,v,C){createDynamicConfig2(g,dM,safeGetLogger2(v)),!C&&v&&(C=v[UP]()[JP]());var T=S;S&&S[cM]&&(T=S[cM]()),_[oR]=v,f=createProcessTelemetryContext2(C,g,v,T)}function _initDefaults(){g=!1,_[oR]=null,f=null,S=null,C=createUnloadHookContainer2(),v=createUnloadHandlerContainer2()}_initDefaults(),dynamicProto(BaseTelemetryPlugin3,_,(function(f){f[OP]=function(f,S,v,C){_setDefaults(f,S,C),g=!0},f[$P]=function(g,_){var T,I=f[oR];if(I&&(!g||I===g[oR]())){var b,A=!1,P=g||createProcessTelemetryUnloadContext2(null,I,S&&S[cM]?S[cM]():S),R=_||((T={reason:0})[qP]=!1,T);return f[zP]&&!0===f[zP](P,R,_unloadCallback)?b=!0:_unloadCallback(),b}function _unloadCallback(){A||(A=!0,v.run(P,_),C.run(P[WP]()),!0===b&&P[xP](R),_initDefaults())}},f[KP]=function(g,v){var C=f[oR];if(C&&(!g||C===g[oR]())){var _,T=!1,I=g||createProcessTelemetryUpdateContext2(null,C,S&&S[cM]?S[cM]():S),b=v||{reason:0};return f._doUpdate&&!0===f._doUpdate(I,b,_updateCallback)?_=!0:_updateCallback(),_}function _updateCallback(){T||(T=!0,_setDefaults(I.getCfg(),I.core(),I[JP]()))}},proxyFunctionAs2(f,"_addUnloadCb",(function(){return v}),"add"),proxyFunctionAs2(f,"_addHook",(function(){return C}),"add"),objDefine(f,"_unloadHooks",{g:function(){return C}})})),_[WP]=function(g){return _getTelCtx(g)[WP]()},_[NP]=function(){return g},_.setInitialized=function(f){g=f},_[YP]=function(g){S=g},_[xP]=function(g,f){f?f[xP](g):S&&hl(S[dR])&&S[dR](g,null)},_._getTelCtx=_getTelCtx}return BaseTelemetryPlugin3.__ieDyn=1,BaseTelemetryPlugin3}(),uM="",gM="timings",pM="processTelemetryStart";(lM={})[0]=0,lM[2]=6,lM[1]=1,lM[3]=7,lM[4098]=6,lM[4097]=1,lM[4099]=7;function getTenantId2(g){if(g){var f=oc(g,"-");if(f>-1)return strLeft(g,f)}return uM}var mM,fM,SM=perfNow;function setProcessTelemetryTimings2(g,f){var S=g;S[gM]=S[gM]||{},S[gM][pM]=S[gM][pM]||{},S[gM][pM][f]=SM()}function isGreaterThanZero2(g){return g>0}function isValidPersistenceLevel(g){return pl(g)&&g>=1&&g<=2}(fM=mM||(mM={}))[fM.LocalStorage=1]="LocalStorage",fM[fM.SessionStorage=2]="SessionStorage",fM[fM.IndexedDb=3]="IndexedDb";var vM="readwrite",CM="result",yM="DBError: Unable to open database",EM="Database is not open",_M="DBError: Failed to Open Cursor",TM="DBError: Failed to delete the database",IM="DBError: Database does not exist",bM="DBError: Database upgrade required",AM="DBError: Feature not supported",PM=["indexedDB"],RM=hl,MM=dl,wM=0;function _getDbFactory(){var g=getGlobal()||{},f=null;if(g)try{for(var S=0;S<PM.length;S++)if((f=g[PM[S]])&&RM(f.open))return f}catch(g){f=null}return f||null}function _debugLog(g,f){getInst("QUnit")&&console&&console.log("  ["+toISOString2(new Date)+"]: IndexedDbHelper ["+g+"] "+f)}function _warnLog(g,f,S){g&&g.warnToConsole("IndexedDbHelper ["+f+"] "+S)}function _eventReject(g,f,S,v){return function(C){S(new Error(f)),_debugLog(g,"["+v+"] event rejected")}}var OM=[];function _getDbContext(g,f){for(var S=null,v=0;v<OM.length;v++)if((S=OM[v]).name===g)return S;return S={name:g,sch:createTaskScheduler(createAsyncPromise,"IndexedDbHelper["+g+"]"),dbHdl:[],add:function(f){S.dbHdl.push(f),_debugLog(g,"- dbOpened (add) -- hdls ["+S.dbHdl.length+"]")},remove:function(f){for(var v=S.dbHdl,C=0;C<v.length;C++)if(v[C]===f){v.splice(C,1);break}_debugLog(g,"- dbClosed (remove) -- hdls ["+S.dbHdl.length+"]")},isOpen:function(){return S.dbHdl.length>0},openHdl:function(){return S.dbHdl.length>0?S.dbHdl[0]:null}},OM.push(S),S}var DM=function(){function IndexedDbHelper2(g){var f=wM++,S=0;dynamicProto(IndexedDbHelper2,this,(function(v){var C=_getDbFactory()||null;function _createStoreContext(v,C,_){var T=v.db,I=S++;_debugLog(v.dbName,"["+f+":"+I+"] txn.open - "+C+" -- "+_);var b=T.transaction(C,vM);return b.onabort=function(){_warnLog(g,v.dbName,"["+f+":"+I+"] txn.onabort - "+C+" -- "+_+" -- "+dumpObj(b.error))},b.onerror=function(){_warnLog(g,v.dbName,"["+f+":"+I+"] txn.onerror - "+C+" -- "+_)},b.oncomplete=function(){_debugLog(v.dbName,"["+f+":"+I+"] txn.oncomplete - "+C+" -- "+_)},{db:v,store:b.objectStore(C),tx:b,tbl:C,openCursor:function(g,f){return _openCursor(v,C,g,f)},newTransaction:function(g){return _openStore(v,C,g)}}}function _openStore(g,f,S){if(!g||!g.db)return mh(new Error(EM));try{var v=S(_createStoreContext(g,f,"openStore"));return isPromiseLike2(v)?v:ph(v)}catch(g){return mh(g)}}function _openCursor(g,f,S,v){if(!g||!g.db)return mh(new Error(EM));var C=null;return S&&MM(S)?C=new NM(S):S&&S.isMatch&&(C=S),createAsyncPromise((function(S,_){var T=[],I=null,b=null;C&&C.keyRange&&(b=C.keyRange());var A=_createStoreContext(g,f,"openCursor");(I=b?A.store.openCursor(b):A.store.openCursor()).onerror=_eventReject(A.db.dbName,_M,_,"openCursor"),I.onsuccess=function(g){var f=g.target[CM];if(f){var I={store:A,cursor:f,continue:function(){f.continue()},done:function(){S(T)}},b=f.value;if(!C||C.isMatch(b))if(v)try{switch(v(I,b,T)){case 2:S(T);break;case 1:break;default:I.continue()}}catch(g){_(g)}else T.push(b),I.continue();else I.continue()}else S(T)}}))}function _scheduleEvent(g,f,S,v){return _getDbContext(g).sch.queue(S,f,v)}v.isAvailable=function(){return!!C},v.openDb=function(f,S,v,_){return _scheduleEvent(f,"openDb",(function(T){return createAsyncPromise((function(I,b){var A=!1;function _createDbCtx(g,v,C,_,T){var I={db:v,dbName:f,dbVersion:S,ctx:null,isNew:_,txn:C?C.transaction:null};return T||(I.openStore=function(g,f){return _openStore(I,g,f)},I.openCursor=function(g,f,S){return _openCursor(I,g,f,S)}),I}function _databaseUpgrade(g,f){var S=_createDbCtx(null,g,f,!0,!0);if(_)A=!0,doAwaitResponse(_(S),(function(g){if(g.rejected)try{f.transaction&&f.transaction.abort()}finally{b(g.reason)}else S.txn||(S.txn=f.transaction)}));else try{f.transaction&&f.transaction.abort()}finally{b(new Error(bM))}}function _databaseOpen(S,C){var _=_getDbContext(f);_.add(S),S.onabort=function(v){_warnLog(g,f,"onabort -- closing the Db"),_.remove(S)},S.onerror=function(v){_warnLog(g,f,"onerror -- closing the Db"),_.remove(S)},S.onclose=function(v){_warnLog(g,f,"onclose -- closing the Db"),_.remove(S)},S.onversionchange=function(v){_warnLog(g,f,"onversionchange -- force closing the Db"),S.close(),_.remove(S)};var T=null,P=null;_.dbHdl.length>0&&(P=_.dbHdl[0]),T=_createDbCtx(_,P,C,A);try{doAwait(v(T),I,b)}catch(g){b(g)}}var P=_getDbContext(f);if(null==C)b(new Error("No available storage factory"));else if(P.isOpen()){var R=_createDbCtx(P,P.openHdl(),null,!1);doAwait(v(R),I,b)}else{var M=C.open(f,S);M.onblocked=function(S){_warnLog(g,f,"Db Open Blocked event ["+T+"] - "+(M.error||"")),b(new Error(yM))},M.onerror=function(S){_warnLog(g,f,"Db Open Error event ["+T+"] - "+(M.error||"")),b(new Error(yM))},M.onupgradeneeded=function(g){_debugLog(f,"Db Open Create/Upgrade needed event ["+T+"]");try{var S=g.target[CM];if(!S)return void b(new Error(yM));_databaseUpgrade(S,M)}catch(g){_eventReject(f,yM,b,T)(g)}},M.onsuccess=function(g){var f=g.target[CM];f?_databaseOpen(f,M):b(new Error(yM))}}}))}))},v.closeDb=function(g){_scheduleEvent(g,"closeDb",(function(f){var S=_getDbContext(g),v=S.dbHdl,C=v.length;if(C>0){for(var _=0;_<C;_++)v[_].close();S.dbHdl=[]}return 1})).catch((function(g){}))},v.deleteDb=function(f){return null!=C&&_scheduleEvent(f,"deleteDb",(function(S){var v=_getDbContext(f),_=v.dbHdl,T=_.length;if(T>0){_warnLog(g,f,"Db is open ["+T+"] force closing");for(var I=0;I<T;I++)_[I].close();v.dbHdl=[]}return createAsyncPromise((function(v,_){setTimeout((function(){try{_debugLog(f,"["+S+"] starting");var T=C.deleteDatabase(f);T.onerror=function(v){_warnLog(g,f,"["+S+"] error!!"),_(new Error(TM))},T.onblocked=function(v){_warnLog(g,f,"["+S+"] blocked!!"),_(new Error(TM))},T.onupgradeneeded=function(v){_warnLog(g,f,"["+S+"] upgrade needed!!"),_(new Error(TM))},T.onsuccess=function(g){_debugLog(f,"["+S+"] complete"),v(!0)},_debugLog(f,"["+S+"] started")}catch(v){_warnLog(g,f,"["+S+"] threw - "+v),_(new Error(TM+" - "+v))}}),0)}))}))},v.getDbDetails=function(g){return _scheduleEvent(g,"getDbDetails",(function(f){return null!=C&&C.databases?createAsyncPromise((function(f,S){C.databases().then((function(v){for(var C=0;C<v.length;C++)if(v[C].name===g)return void f(v[C]);S(new Error(IM))}),S)})):mh(new Error(AM))}),2e3)}}))}return IndexedDbHelper2.__ieDyn=1,IndexedDbHelper2}(),NM=function(){function SimpleQuery2(g){var f=[],S=null;dynamicProto(SimpleQuery2,this,(function(v){v.keyRange=function(){return S},v.parseQuery=function(g){if(f=[],g)for(var C=g.split(";"),_=0;_<C.length;_++){var T=C[_],I=T.indexOf("=");if(-1!==I){var b=T.substring(0,I),A=T.substring(I+1);0===b.indexOf("#")&&(b=b.substring(1),S||(S=IDBKeyRange.bound(A,A+""))),v.startsWith(b,A)}}},v.startsWith=function(g,S){f.push({name:g,value:S,type:0})},v.contains=function(g,S){f.push({name:g,value:S,type:1})},v.isMatch=function(g){if(!f||0===f.length)return!0;if(!g)return!1;for(var S=0;S<f.length;S++){var v=f[S],C=g[v.name];if(C)if(0===v.type){if(0!==C.indexOf(v.value))return!1}else if(1===v.type&&-1===C.indexOf(v.value))return!1}return!0},g&&v.parseQuery(g)}))}return SimpleQuery2.__ieDyn=1,SimpleQuery2}(),kM=10,LM=1,FM=6e5,xM=6048e5,UM="Unknown",VM=-1,BM="DBError: Unable to add event",HM="DBError: Unable to update iKey",$M=1,jM="Evts",GM="iKey",qM=isValidPersistenceLevel;function _getTime(){return(new Date).getTime()}function _eventReject2(g,f){return function(S){return f(new Error(g))}}function _createDb(g){g.objectStoreNames.contains(jM)||g.createObjectStore(jM,{keyPath:"key"}).createIndex("EvntId","key",{unique:!1});g.objectStoreNames.contains(GM)||g.createObjectStore(GM,{keyPath:"iKey"}).createIndex("iKey","iKey",{unique:!0})}function _updateiKey(g){return g.openStore(GM,(function(f){return createAsyncPromise((function(S,v){var C={iKey:g.ctx.iKey,tm:_getTime()},_=f.store.put(C);_.onsuccess=function(g){S(_.result.toString())},_.onerror=function(g){v(new Error(BM))},_.onerror=_eventReject2(HM,v)}))}))}function _orderEventsByPriority(g){for(var f=[],S=2;S>=1;S--)for(var v=0;v<g.length;v++){var C=g[v];C&&C.evt.persistence===S&&f.push(C.evt)}return f}function _addEventByTime(g,f){for(var S=0;S<g.length;S++)if(f.tm<g[S].tm)return void g.splice(S,0,f);g.push(f)}function _getKeyIndex(g,f){for(var S=f.length,v=0;v<S;v++)if(g===f[v].id)return v;return-1}function _isOldItem(g,f){var S=g.tm;return _getTime()-S>f}function _cursorContinueEvent(g){return function(f){return g.continue()}}function _cursorDeleteAndContinue(g){var f=g.cursor.delete();return f.onerror=_cursorContinueEvent(g),f.onsuccess=_cursorContinueEvent(g),1}function _getAllEventsForiKey(g,f){return g.openCursor(jM,f,(function(g,f,S){return S.push(f),0}))}function _deleteEvents(g,f,S){return g.openCursor(jM,f,(function(g,f,v){return S(f)?(v.push(f),_cursorDeleteAndContinue(g)):0}))}function _deleteOrphanedEvents(g){return createAsyncPromise((function(f,S){var v=!1;g.openCursor(GM,null,(function(g,f,S){var C=f.tm;return _getTime()-C<xM?0:(v=!0,2)})).then((function(){if(v){var C={};_deleteEvents(g,null,(function(g){if(!g||!g.evt||!g.evt.iKey)return!0;var f=g.tm;return _getTime()-f>xM||(C[g.evt.iKey]=1,!1)})).then((function(){var v=[];g.openCursor(GM,null,(function(g,f,S){var _=f.tm;return _getTime()-_<xM||C[f.iKey]?0:(v.push(f),_cursorDeleteAndContinue(g))})).then((function(){f(v)}),S)}),S)}else f([])}),S)}))}function _moveOldEventsToCurrentStore(g,f){return g.openCursor(jM,"#key="+g.ctx.iKeyPrefix(),(function(S,v){var C=v.key;if(0===C.indexOf(g.ctx.iKeyPrefix())&&-1===C.indexOf(g.ctx.evtKeyPrefix())&&_isOldItem(v,f)){v.key=g.ctx.evtKeyPrefix()+v.id;var _=S.store.store.put(v);return _.onerror=_cursorContinueEvent(S),_.onsuccess=function(g){try{_cursorDeleteAndContinue(S)}catch(g){S.continue()}},1}return 0}))}function _checkVersionAndMoveEventsToCurrentStorage(g,f){return createAsyncPromise((function(S,v){_deleteOrphanedEvents(g).then((function(){_moveOldEventsToCurrentStore(g,f).then(S,S)}),v)}))}function _dropEventsUpToPersistence(g,f){return createAsyncPromise((function(S,v){var C=0,_=g.ctx.evtKeyPrefix();function _resolveWithDroppedEvents(){S(C)}function _dropEvent(g,f){return createAsyncPromise((function(S){var v=g.store.delete(f.key);v.onsuccess=function(g){C++,S()},v.onerror=function(g){S()}}))}function _processCandidates(f){0!==f.length?g.openStore(jM,(function(g){for(var S=[],v=0;v<f.length;v++)S.push(_dropEvent(g,f[v]));return gh(S).then(_resolveWithDroppedEvents,_resolveWithDroppedEvents)})):_resolveWithDroppedEvents()}g.openCursor(jM,"#key="+_,(function(g,S,v){return S.evt.persistence<=f&&0===S.key.indexOf(_)&&(_addEventByTime(v,S),v.length>kM&&v.splice(v.length-1,1)),0})).then(_processCandidates,(function(){S(0)}))}))}var WM=function(){function IndexedDbProvider2(g,f){dynamicProto(IndexedDbProvider2,this,(function(S){var v=null,C=null,_=UM,T=null,I=null,b=null,A=VM,P=0,R=FM;function _openDb(g){function _handleDbUpgrade(g){return createAsyncPromise((function(f,S){_createDb(g.db),f()}))}function _handleDbOpen(f){return createAsyncPromise((function(S,v){var C={iKey:_,storageId:T,iKeyPrefix:function(){return I},evtKeyPrefix:function(){return b}};f.ctx=C,doAwait(_updateiKey(f),(function(){doAwait(g(f),S,v)}),v)}))}return v.openDb(C,$M,_handleDbOpen,_handleDbUpgrade)}function _addDbEvent(g,f,S){return createAsyncPromise((function(v,C){function dropEvents(f,S){_dropEventsUpToPersistence(g,f).then((function(g){g>0&&(P-=g),S(g)}),(function(g){S(0)}))}function resolveAddEvent(g){v(f.evt)}function _insertNewEvent(){g.openStore(jM,(function(_){var T=_.store.put(f);T.onsuccess=function(C){S&&_updateiKey(g).then(resolveAddEvent,resolveAddEvent),P++,v(f.evt)},T.onerror=function(_){function _retryAddEvent(S){0===S&&C(new Error(BM)),_addDbEvent(g,f,!1).then((function(g){v(f.evt)}),(function(){C(new Error(BM))}))}S?dropEvents(1,(function(g){g>0?_retryAddEvent(g):f.evt.persistence>=2?dropEvents(2,(function(g){_retryAddEvent(g)})):C(new Error(BM))})):C(new Error(BM))}}))}A>0&&P>=A?dropEvents(1,(function(g){0===g?f.evt.persistence>=2?dropEvents(2,(function(g){_insertNewEvent()})):C(new Error(BM)):_insertNewEvent()})):_insertNewEvent()}))}S.id=g,S.initialize=function(g){var P=g.itemCtx.diagLog();if(!(v=new DM(P)).isAvailable())return v=null,!1;var M=g.itemCtx.getCfg(),w=g.storageConfig;_=M.instrumentationKey||_,T=S.id||g.id||newGuid3(),b=(I=_+"::")+T+"::",R=w.accessThresholdInMs||R;var O=onConfigChange2(w,(function(){A=w.maxStorageItems;var g=w.indexedDbName;C&&g!==C&&C&&doAwaitResponse(S.clear(),(function(f){C=g,_openDb((function(g){return g.isNew?[]:_checkVersionAndMoveEventsToCurrentStorage(g,R)})).then((function(g){}),(function(g){P.warnToConsole("IndexedDbProvider failed to initialize - "+(g||"<unknown>")),v=null}))})),C=g}));return f&&f.add(O),_openDb((function(g){return g.isNew?[]:_checkVersionAndMoveEventsToCurrentStorage(g,R)})).then((function(g){}),(function(g){P.warnToConsole("IndexedDbProvider failed to initialize - "+(g||"<unknown>")),v=null})),!0},S._getDbgPlgTargets=function(){return[C]},S.supportsSyncRequests=function(){return!1},S.getAllEvents=function(){return null!=v&&v.isAvailable()?_openDb((function(g){return createAsyncPromise((function(f,S){_getAllEventsForiKey(g,"#key="+g.ctx.evtKeyPrefix()).then((function(g){P=g.length,f(_orderEventsByPriority(g))}),S)}))})):[]},S.addEvent=function(g,f,S){return null!=v&&v.isAvailable()?(f.id=f.id||newGuid3(),qM(f.persistence)||(f.persistence=1),_openDb((function(S){var v=g||f.id,C={key:S.ctx.evtKeyPrefix()+v,id:v,evt:f,tm:_getTime(),v:LM};return _addDbEvent(S,C,!0)}))):f},S.removeEvents=function(g){if(null==v||!v.isAvailable())return[];var f=[];return createAsyncPromise((function(S,v){_openDb((function(S){return S.openCursor(jM,"#key="+S.ctx.iKey,(function(S,v,C){if(-1!==_getKeyIndex(v.id,g)){var _=S.cursor.delete();return _.onerror=_cursorContinueEvent(S),_.onsuccess=function(){f.push(v.evt),S.continue()},1}return 0}))})).then((function(g){P-=f.length,S(f)}),(function(g){P-=f.length,S(f)}))}))},S.clear=function(){return null!=v&&v.isAvailable()?createAsyncPromise((function(g,f){_openDb((function(g){return _deleteEvents(g,"#key="+g.ctx.evtKeyPrefix(),(function(f){return 0===f.key.indexOf(g.ctx.evtKeyPrefix())}))})).then((function(f){P=0,g(_orderEventsByPriority(f))}),f)})):[]},S.moveStaleEvents=function(){_openDb((function(g){return _checkVersionAndMoveEventsToCurrentStorage(g,R)}))},S.teardown=function(){v&&v.closeDb(C)}}))}return IndexedDbProvider2.__ieDyn=1,IndexedDbProvider2}(),zM=10,KM="3",JM="Version",YM="AWTEvents",QM=5e6;function _isQuotaExceeded(g,f){var S=!1;return f instanceof DOMException&&(22!==f.code&&"QuotaExceededError"!==f.name&&1014!==f.code&&"NS_ERROR_DOM_QUOTA_REACHED"!==f.name||g&&0!==g.length&&(S=!0)),S}function _getAvailableStorage(g){var f=getGlobal()||{},S=null;try{if(S=f[g]){var v="__storage_test__";S.setItem(v,v),S.removeItem(v)}}catch(g){_isQuotaExceeded(S,g)||(S=null)}return S}function _forEachMap(g,f){if(g)for(var S=Al(g),v=0;v<S.length;v++){var C=S[v];if(!f(g[C],C))break}}function _isMapEmpty(g){var f=!0;return _forEachMap(g,(function(g,S){return g&&(f=!1),f})),f}function _dropEventsUpToPersistence2(g,f){for(var S=1,v=0,_loop_1=function(){var g=[],C=f[S];if(_forEachMap(C,(function(f,S){return g.push(S),++v<zM})),v>0){for(var _=0;_<g.length;_++)delete C[g[_]];return{value:!0}}S++};S<=g&&v<zM;){var C=_loop_1();if("object"==typeof C)return C.value}return v>0}var XM=isValidPersistenceLevel,ZM=function(){function WebStorageProvider2(g,f,S){dynamicProto(WebStorageProvider2,this,(function(v){var C=null,_=YM,T=null,I=KM,b=null,A=null,P=QM,R=6e5,M=null,w=null;function _newStore(g,f){return{key:g,db:f}}function _fetchStoredDb(g,f){void 0===f&&(f=!0);var S=null;if(C){var v=C.getItem(g);if(v)try{S=JSON.parse(v)}catch(f){C.removeItem(g)}}return f&&!S&&(S={events:{1:{},2:{},3:{}},lastAccessTime:0}),_newStore(g,S)}function _updateStoredDb(g,f){void 0===f&&(f=!0);var S=!0,v=g.db;if(v){f&&(v.lastAccessTime=(new Date).getTime());for(var _=1;_<=2;_++)if(!_isMapEmpty(v.events[_])){S=!1;break}}try{if(S)C&&C.removeItem(g.key);else{var T=JSON.stringify(v);if(T.length>P)return!1;C&&C.setItem(g.key,T)}}catch(g){return!1}return!0}function _clearDatabase(g){var f=[],S=_fetchStoredDb(g,!1),v=S.db;if(v){var _=v.events;try{for(var T=1;T<=2;T++)_forEachMap(_[T],(function(g,S){return g&&f.push(g),!0}))}catch(g){}C&&C.removeItem(S.key)}return f}function _checkVersionAndMoveEventsToCurrentStorage2(){if(C){for(var g=C.getItem(M),f=[],S=_fetchStoredDb(w),v=!1,T=0;T<C.length;T++){var b=C.key(T);if(0===b.indexOf(_)&&b!==M){if(g!==KM){f.push(_newStore(b,null));continue}var P=_fetchStoredDb(b,!1),O=P.db;if(O){if((new Date).getTime()-O.lastAccessTime>R){for(var D=1,_loop_3=function(){var g=O.events[D],f=S.db.events[D];_forEachMap(g,(function(S,v){return(getTenantId2(S.iKey)||S.iKey)===A&&(f[v]=S,delete g[v]),!0})),D++};D<=2;)_loop_3();v=!0,f.push(P)}}else f.push(_newStore(b,null))}}for(T=0;T<f.length;T++)_updateStoredDb(f[T],!1);v&&_updateStoredDb(S),C.setItem(M,I)}}v.id=f,C=_getAvailableStorage(g)||null,v._getDbgPlgTargets=function(){return[_,P]},v.initialize=function(g){if(!C)return!1;var f=g.storageConfig;T=v.id||g.id||newGuid3(),b=g.itemCtx.getCfg().instrumentationKey,A=getTenantId2(b)||b,R=f.accessThresholdInMs?f.accessThresholdInMs:R;var I=onConfigChange2(f,(function(){P=f.maxStorageSizeInBytes;var g=f.storageKey;_&&g!==_&&doAwaitResponse(v.clear(),(function(f){w=(_=g)+"."+T,M=_+JM,_checkVersionAndMoveEventsToCurrentStorage2()}))}));return S&&S.add(I),_=f.storageKey,w=_+"."+T,M=_+JM,_checkVersionAndMoveEventsToCurrentStorage2(),!0},v.supportsSyncRequests=function(){return!0},v.getAllEvents=function(){try{var g=[],f=_fetchStoredDb(w,!1).db;if(f)for(var S=f.events,v=2;v>=1;v--)_forEachMap(S[v],(function(f){f&&((getTenantId2(f.iKey)||f.iKey)===A&&g.push(f));return!0}));return g}catch(g){return mh(g)}},v.addEvent=function(g,f,S){try{var v=_fetchStoredDb(w);f.id=f.id||newGuid3(),XM(f.persistence)||(f.persistence=1);for(var C=f.persistence,_=f.id,T=v.db.events;;){if(T[C][_]=f,_updateStoredDb(v))return f;if(delete T[C][_],!_dropEventsUpToPersistence2(C,T))return mh(new Error("Unable to free up event space"))}}catch(g){return mh(g)}},v.removeEvents=function(g){try{var f=_fetchStoredDb(w,!1),S=f.db;if(S){var v=S.events;try{for(var C=0;C<g.length;++C){var _=g[C];delete v[_.persistence][_.id]}if(_updateStoredDb(f))return g}catch(g){}g=_clearDatabase(f.key)}return g}catch(g){return mh(g)}},v.clear=function(){try{var g=[],f=_fetchStoredDb(w,!1),S=f.db;if(S){for(var v=S.events,_loop_2=function(f){var S=v[f];_forEachMap(S,(function(f){f&&((getTenantId2(f.iKey)||f.iKey)===A&&(delete S[f.id],g.push(f)));return!0}))},C=2;C>=1;C--)_loop_2(C);_updateStoredDb(f)}return g}catch(g){return mh(g)}},v.teardown=function(){try{var g=_fetchStoredDb(w,!1),f=g.db;f&&(f.lastAccessTime=0,_updateStoredDb(g,!1))}catch(g){}},v.moveStaleEvents=function(){_checkVersionAndMoveEventsToCurrentStorage2()}}))}return WebStorageProvider2.__ieDyn=1,WebStorageProvider2}(),ew="4.3.1",tw="LocalStorage",iw=5,nw=isValidPersistenceLevel,rw=void 0,sw="AppInsightEvents.1",aw=objDeepFreeze({maxStorageSizeInBytes:{isVal:isGreaterThanZero2,v:5e6},storageKey:"AWTEvents",minPersistenceLevel:{isVal:nw,v:1},providers:[mM.LocalStorage,mM.IndexedDb],indexedDbName:sw,maxStorageItems:{isVal:isGreaterThanZero2,v:rw}}),ow=function(g){function LocalStorageChannel2(){var f=g.call(this)||this;return f.identifier=tw,f.priority=1009,f.version=ew,dynamicProto(LocalStorageChannel2,f,(function(g,f){var S,v,C,_;function _initDefaults(){S=!1,v=!1,C=null,_=[]}function _queueStorageEvent(g,f){C||(C=createTaskScheduler(createAsyncPromise,"LocalStorage")),C.queue((function(g){return f(g)}),g).catch((function(g){}))}function _sendStoredEventsToNextPlugin(f){doPerf2(g.core,(function(){return"LocalStorageChannel:_sendStoredEventsToNextPlugin"}),(function(){_queueStorageEvent("sendToNext",(function(S){return doAwaitResponse(f.provider.getAllEvents(),(function(S){for(var v=S.value||[],C=0;C<v.length;C++)try{var _=v[C];(getTenantId2(_.iKey)||_.iKey)===f.tenantId&&g.processNext(_,f.coreRootCtx.createNew())}catch(g){}}))}))}),(function(){return{iKeyConfig:f}}))}function _removeEvents(f,S){doPerf2(g.core,(function(){return"LocalStorageChannel:_removeEvents"}),(function(){_queueStorageEvent("removeEvents",(function(g){var v=[];if(arrForEach(S,(function(g){(getTenantId2(g.iKey)||g.iKey)===f.tenantId&&v.push(g)})),v.length>0)return doAwaitResponse(f.provider.removeEvents(v),(function(g){}))}))}),(function(){return{iKeyConfig:f,events:S}}))}function _shouldCacheEvent(g,f){return!(f.sync||f.persistence<g.minPersistenceCacheLevel)}function _tryGetIndexedDbProvider(f){var S=new WM(void 0,g._unloadHooks);return S.initialize(f)||(S=null),S}function _tryGetWebStorageProvider(f,S){var v=new ZM(f,void 0,g._unloadHooks);return v.initialize(S)||(v=null),v}function _initializeProvider(g){for(var f=g.storageConfig.providers,S=null,v=0;!S&&v<f.length&&v<iw;)switch(f[v++]){case mM.LocalStorage:S=_tryGetWebStorageProvider("localStorage",g);break;case mM.SessionStorage:S=_tryGetWebStorageProvider("sessionStorage",g);break;case mM.IndexedDb:S=_tryGetIndexedDbProvider(g)}return S}function _compareProviders(g,f){if(g.length!==f.length)return!1;var S=!0;return arrForEach(g,(function(g,v){if(g!==f[v])return S=!1,-1})),S}function _getCoreItemCtx(f,S,v,C){f&&(f.extensionConfig=f.extensionConfig||[]),!C&&S&&(C=S.getProcessTelContext().getNext());var _=null,T=g._getTelCtx().getNext();return T&&(_=T.getPlugin()),createProcessTelemetryContext2(C,f,S,_)}function _createIkeyConfig(f,S,v,C){var T=!1;if(arrForEach(_,(function(g){if(g.iKey===f.instrumentationKey)return T=!0,-1})),!T){var I=null;g._addHook(onConfigChange2(f,(function(v){var C=createProcessTelemetryContext2(null,v.cfg,S);I=C.getExtCfg(g.identifier,aw);var T=!1,b=null,A=f.instrumentationKey;if(arrForEach(_,(function(g){if(g.iKey===A)return T=!0,b=g,-1})),T&&b){var R=I.providers,M=b.preProviders;_compareProviders(R,M)||doAwaitResponse(P.clear(),(function(g){if(!g.rejected)try{var f=_.indexOf(b);-1!==f&&_.splice(f,1);var v=_initializeProvider(b.providerContext);b.provider=v,b.preProviders=R.slice();var C=b.preListener;C&&S.removeNotificationListener(C);var T={eventsSent:function(g){_removeEvents(b,g)},eventsDiscarded:function(g,f){_removeEvents(b,g)}};b.preListener=T,_.push(b),S.addNotificationListener(T),_sendStoredEventsToNextPlugin(b)}catch(g){}}))}})));var b=_getCoreItemCtx(f,S,v,C),A={itemCtx:b,storageConfig:I,id:g.id};if(!dl(f.instrumentationKey))return;var P=_initializeProvider(A),R={iKey:f.instrumentationKey,tenantId:getTenantId2(f.instrumentationKey)||f.instrumentationKey,minPersistenceCacheLevel:1,coreRootCtx:b,providerContext:A,provider:P,preProviders:I.providers.slice()};if(P){nw(I.minPersistenceLevel||-1)&&(R.minPersistenceCacheLevel=I.minPersistenceLevel);var M={eventsSent:function(g){_removeEvents(R,g)},eventsDiscarded:function(g,f){_removeEvents(R,g)}};R.preListener=M,_.push(R),S.addNotificationListener(M),_sendStoredEventsToNextPlugin(R)}else _.push(R)}}_initDefaults(),g.initialize=function(g,v,_,T){doPerf2(v,(function(){return"LocalStorageChannel.initialize"}),(function(){S||(f.initialize(g,v,_),f.setInitialized(!1),S=!0,C=createTaskScheduler(createAsyncPromise,"LocalStorage")),_createIkeyConfig(g,v,_,T)}),(function(){return{coreConfig:g,core:v,extensions:_,pluginChain:T}}))},g.processTelemetry=function(f,C){var T=f;if(S&&!v){C=g._getTelCtx(C),setProcessTelemetryTimings2(f,g.identifier);var I=null;arrForEach(_,(function(g){g.iKey===f.iKey&&(I=g)}));var b=I?I.provider:null;if(T.sync||!b)return void g.processNext(T,C);T.id=T.id||newGuid3(),isValidPersistenceLevel(T.persistence)||(T.persistence=1),_shouldCacheEvent(I,T)&&_queueStorageEvent("processTelemetry",(function(g){return b.addEvent(T.id,T,C)}))}g.processNext(T,C)},g.pause=function(){v=!0},g.resume=function(){doPerf2(g.core,(function(){return"LocalStorageChannel:resume"}),(function(){v=!1,arrForEach(_,(function(g){g.provider&&_sendStoredEventsToNextPlugin(g)}))}))},g._doTeardown=function(g,f){arrForEach(_,(function(g){var f=g.provider;f&&f.teardown()})),_initDefaults()},g.flush=function(g,f,S){},g._getDbgPlgTargets=function(){return[_]},g._sendStale=function(g){arrForEach(_,(function(f){if(f&&f.iKey===g&&f.provider)return f.provider.moveStaleEvents(),_sendStoredEventsToNextPlugin(f),-1}))}})),f}return __extendsFn(LocalStorageChannel2,g),LocalStorageChannel2.__ieDyn=1,LocalStorageChannel2}(hM),lw="LocalStorage",cw=class{constructor(g,f,S,v,C,_){this.logger=g,this.configProvider=f,this.clientInfo=S,this.contextProvider=v,this.accountCollectorURL=C,this.envOverride=_,this.manager=new Ov,this.managerConfig=this.createConfigForManager(),this.currentTransmitProfile=qt.REPORTING_PROFILE.RT_PROFILE,this.initManager(),this.uiVersion=this.getUiVersion(),this.configProvider.on("configUpdated",(()=>this.updateChannelConfig()))}createLogger(g,f){return new dw(g,this.manager,this.logger,this.configProvider,this.uiVersion,f,this.contextProvider,this.envOverride)}createConfigForManager(){return{channels:[],extensionConfig:{},propertyConfiguration:{populateBrowserInfo:!0,populateOperatingSystemInfo:!0},channelConfiguration:{eventsLimitInMem:this.configProvider.config.eventsLimitInMem,disableFetchKeepAlive:this.configProvider.config.oneDSDisableFetchKeepAlive,useSendBeacon:this.configProvider.config.oneDSUseSendBeacon},endpointUrl:this.accountCollectorURL,enableCompoundKey:this.configProvider.config.enableCompoundKey,disablePageUnloadEvents:this.configProvider.config.oneDSDisabledPageUnloadEvents}}getUiVersion(){const g=this.clientInfo.match(/^.*?\/(\d+\/)(.*?)\/.*$/);return g?g[1]+g[2]:this.clientInfo}updateChannelConfig(){this.configProvider.config.eventsLimitInMem!==this.managerConfig.channelConfiguration.eventsLimitInMem&&this.manager.getPostChannel().setEventQueueLimits(this.configProvider.config.eventsLimitInMem),this.setTransmitProfile()}initManager(){this.initLocalStorageChannel(),this.manager.create(this.managerConfig,[]),this.manager.getNotifyMgr().addNotificationListener({eventsDiscarded:(g,f)=>this.logDiscardedEvents(g,f),eventsSent:g=>this.logSentEvents(g)}),this.setTransmitProfile()}initLocalStorageChannel(){if(!this.configProvider.config.useLocalStorageForOneDs)return;const g=new ow;this.managerConfig.channels.push([g]);const f={storageKey:"TsCalling",accessThresholdInMs:this.configProvider.config.oneDSLocalStorage.accessThresholdInMs??6e5};this.managerConfig.extensionConfig[lw]=f}logDiscardedEvents(g,f){let S="discarded events:";g.forEach((g=>S=`${S+g.name};`)),this.logger.info(`${S} reason:${f}`)}logSentEvents(g){let f=`sent events: ${g[0]?.data?.CorrelationId&&getFrom("value",g[0].data.CorrelationId)}:`;g.forEach((g=>{f=`${f+g.name};`})),this.logger.info(`${f}`)}setTransmitProfile(){this.configProvider.config.transmitProfileTimings.length&&this.manager.getPostChannel()._loadTransmitProfiles({[this.configProvider.config.transmitProfileName]:this.configProvider.config.transmitProfileTimings}),this.configProvider.config.transmitProfileName!==this.currentTransmitProfile&&this.manager.getPostChannel()._setTransmitProfile(this.configProvider.config.transmitProfileName),this.currentTransmitProfile=this.configProvider.config.transmitProfileName}},dw=class{constructor(g,f,S,v,C,_,T,I){this.tenant=g,this.manager=f,this.logger=S,this.configProvider=v,this.uiVersion=C,this.eventLatency=_,this.contextProvider=T,this.envOverride=I,this.instanceConfig={extensions:[],extensionConfig:{}};const{oneDSLocalStorage:b,oneDSNotificationManager:A}=this.configProvider.config;A.blockEventsDiscardedNotifications&&this.blockEventsDiscarded(),A.blockNotificationsOnPageUnload&&this.blockNotificationListenersOnPageUnload(),b.sendStaleEvents&&this.sendStaleEvents()}sendEvent(g){this.setEnvPropertiesToEveryEvent();const f=g.props,S={};switch(this.logger.info(`preparing event for delivery: ${g.props?.CorrelationId??""}/${g.eventName}`),this.tenant){case"signaling":f.SkypeId&&(S.user_id={value:f.SkypeId,kind:10},S.Skype_InitiatingUser_Username={value:f.SkypeId,kind:10},S.SkypeId={value:f.SkypeId,kind:10},delete f.SkypeId),this.uiVersion&&(S.ui_version={value:this.uiVersion,kind:0});break;case"media":case"tlePlayer":this.uiVersion&&(S.uiVersion={value:this.uiVersion,kind:0});break;case"realtimeMedia":this.uiVersion&&(S["AppInfo.Version"]={value:this.uiVersion,kind:0})}for(const g of Object.keys(f)){const v=f[g];S[g]={value:v?.value??v,kind:v?.piiKind??0}}const v={name:g.eventName,data:S,latency:this.eventLatency,persistence:_p.Normal,sync:this.configProvider.config.oneDSEventSendType};this.configProvider.config.smallCallTelemetry.enable&&"mdsc_webrtc_call_session"===v.name&&(v.sync=this.configProvider.config.smallCallTelemetry.eventSendType),this.logger.info(`about to send event ${JSON.stringify(mP.omit(v,["LocalUser","TargetUser"]))}`),this.applicationInsights.track(v)}sendStaleEvents(){this.logger.info("preparing to send stalled telemetry events");const g=this.applicationInsights.getPlugin(lw).plugin;g._sendStale&&g._sendStale(this.tenantToken)}get applicationInsights(){return this.manager.getInst(this.tenantToken)??this.manager.newInst(this.tenantToken,this.instanceConfig,[])}get tenantToken(){return this.configProvider.config.telemetryTenants[this.tenant]}blockNotificationListenersOnPageUnload(){let g=!1;const setPageUnloading=()=>{g=!0},resetPageUnloading=()=>{g=!1};window.addEventListener("beforeunload",setPageUnloading),window.addEventListener("unload",setPageUnloading),window.addEventListener("pagehide",setPageUnloading),window.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?setPageUnloading():resetPageUnloading()})),this.applicationInsights.getNotifyMgr().listeners.forEach((f=>{const{eventsSent:S,eventsDiscarded:v}=f;S&&(f.eventsSent=f=>{g?this.logger.info("1DS eventSent was not raised due to page unload"):S(f)}),v&&(f.eventsDiscarded=(f,S)=>{g?this.logger.log("1DS eventsDiscarded was not raised due to page unload"):v(f,S)})}))}blockEventsDiscarded(){this.applicationInsights.getNotifyMgr().listeners.forEach((g=>{g.eventsDiscarded=(g,f)=>{this.logger.log(`1DS eventsDiscarded with reason ${f} was not raised due to configuration`)}}))}setEnvPropertiesToEveryEvent(){const g=this.contextProvider?.();if(!deepEqual(this.ctx,g)&&(this.ctx=g,this.ctx))if(this.envOverride){for(const g of Object.keys(this.envOverride||{}))if(this.ctx[g]){const f=this.ctx[g].piiKind??0,S=convertContextProperty(this.ctx[g].value);this.manager.getPropertyManager().setProperty(this.envOverride[g],{value:S,kind:f})}}else for(const g of Object.keys(this.ctx)){const f=this.ctx[g].piiKind??0,S=convertContextProperty(this.ctx[g].value);this.manager.getPropertyManager().setProperty(g,{value:S,kind:f})}}},hw=class extends Error{constructor(g,f=1){super(g),this.callSupport=f}};function createTelemetryLoggersFromConfig(g){let f={};return g.telemetryLoggers?f=g.telemetryLoggers:g.telemetryService?.getGenericTelemetryLogger&&g.telemetryTenants?Object.keys(g.telemetryTenants).forEach((S=>f[S]=g.telemetryService.getGenericTelemetryLogger(g.telemetryTenants[S]))):g.telemetryService&&(g.telemetryService.sendEvents||g.telemetryService.getCallingAdapter)&&(g.telemetryService.sendEvents&&(f.media={sendEvent(f){f.eventName&&(f.eventName=f.eventName.replace(/^(mdsc_)/,"")),g.telemetryService.sendEvents([f])}},f.tlePlayer={sendEvent(f){f.eventName&&(f.eventName=f.eventName.replace(/^(mdsc_)/,"")),g.telemetryService.sendEvents([f])}}),g.telemetryService?.sendRealTimeEvents&&(f.realtimeMedia={sendEvent(f){f.eventName&&(f.eventName=f.eventName.replace(/^(mdsc_)/,"")),g.telemetryService.sendRealTimeEvents([f])}}),g.telemetryService.getCallingAdapter&&(f.signaling={sendEvent(f){g.telemetryService.getCallingAdapter().sendEvent(f.eventName,f.props)}})),f}function createTelemetryLoggersForOneDs(g,f,S,v,C,_){const T={signaling:[],media:[],tlePlayer:[],realtimeMedia:[]};let I={signaling:{sendEvent:g=>T.signaling.push(g)},media:{sendEvent:g=>T.media.push(g)},tlePlayer:{sendEvent:g=>T.tlePlayer.push(g)},realtimeMedia:{sendEvent:g=>T.realtimeMedia.push(g)},gtcAudit:{sendEvent:g=>T.realtimeMedia.push(g)}};return f.getConfigReceivedOrTimeout().then((async()=>{let b=(await C)?.serviceUrls?.OneDsCollectorUrl;if(b=b??f.config.collectorUrl,b){const C=new cw(g,f,S,v,b);I.signaling=C.createLogger("signaling",f.config.eventLatency),I.media=C.createLogger("media",f.config.eventLatency),I.tlePlayer=C.createLogger("tlePlayer",f.config.eventLatency),I.gtcAudit=C.createLogger("gtcAudit",Ep.Immediate);const _=new cw(g,f,S,v,b,{"UserInfo.Ring":"Ring","UserInfo.TenantId":"TenantId","AppInfo.ClientType":"client_type","UserInfo.ETag":"AppInfo.EcsEtag",appversion:"First/Second Client VDI Desktop Version",vdiMode:"First/Second Client VDI Mode",vdiConnectedState:"First/Second Client VDI Connected State",vdiShimVersion:"First/Second Client VDI Shim Version",vdiProvider:"First/Second Client VDI Provider Version"});I.realtimeMedia=_.createLogger("realtimeMedia",f.config.eventLatencyRealTime)}else I=createTelemetryLoggersFromConfig(_);for(const[g,f]of Object.entries(T))for(const S of f)I[g].sendEvent(S)})),I}var uw=class _PluginlessStack extends Ke{constructor(g,f){super(),this._config=g,this._ecsProvider=f,this.callRegistries=[],this._logger=new Ge(this._config.logger).createChild("PluginlessStack"),this._platformManager=new sP,this._waitForAccountConfiguration=new dt,this.platformCallConstraintsProvider=new ii(this._logger.createChild("PlatformConstraintsProvider"))}async initializeMediaAgent(g){if(this._mediaAgent)throw new hw("Media agent is already initialized");let f,S=null;if(!this._mediaAgentProvider)throw new hw("PluginlessStack initialize MediaAgent error, Media Stack not initialized",S);try{this._relayManagerProvider=new pi(g,this._signalingAgentProvider,this._ecsProvider,this._logger),f=await this._mediaAgentProvider.buildAgent(this._config.platformType,this._relayManagerProvider,this._midCallTelemetry)}catch(g){const f=g.some((g=>"incompatible_version"===g.reason));S=f?2:1}if(!this._config.usePlatformSupportApi&&!this._config.callSettings?.useLwjForAllCalls){if(S)throw new hw("PluginlessStack initialization failed",S);{const g=(new sP).getPlatformSupportLevel(!0);if(1!==g&&2!==g)throw new hw("PluginlessStack initialization failed",1)}}f?(this._screenSharingManager=new cP(f.getScreenSharingManager()),this._waitForAccountConfigurationTimeout=window.setTimeout((()=>{this._waitForAccountConfiguration.resolve(void 0),this._waitForAccountConfigurationTimeout=void 0}),3e4),this._oneDsTelemetryLoggers=createTelemetryLoggersForOneDs(this._logger.createChild("OneDsLogger"),f.getConfigProvider(),g.clientInformation,this._config.telemetryContextProvider,this._waitForAccountConfiguration.promise,this._config),f.getConfigProvider().config.useOneDsLogger&&(this.signalingLoggerAdapter={sendEvent:(g,f)=>{const S={eventName:g,props:f};this._oneDsTelemetryLoggers.signaling.sendEvent(S)}}),this._mediaAgent=f,this._e911=new aP(this._relayManagerProvider,this._mediaAgent.getConfigProvider(),this._logger.createChild("E911")),this._e911?.changed((()=>{this.event("e911InfoChanged").raise(this._e911?.info,this._e911?.areaContent)}))):this._deviceManager=new xt}async initializeSignalingAgentProvider(g){this._trouterService=g.trouterService,this._signalingAgentProvider=pP.build(g.signalingAgentConfig,this._ecsProvider,this._config.logger,this.signalingLoggerAdapter)}static async build(g,f,S){try{const v=new _PluginlessStack({detectH264Support:g.mediaAgentFactoryConfig.detectH264Support,domOverrides:g.mediaAgentFactoryConfig.domOverrides,mediaSettings:g.mediaAgentFactoryConfig.settings,logger:g.logger,telemetryLoggers:g.telemetryLoggers,telemetryService:g.telemetryService,telemetryTenants:g.telemetryTenants,telemetryContextProvider:g.telemetryContextProvider,platformType:g.platformType,callSettings:g.callSettings,usePlatformSupportApi:g.usePlatformSupportApi,clientInformation:g.signalingAgentConfig.clientInformation,vdi3diagnostics:g.vdi3diagnostics},f);return v.initializeMediaProvider({detectH264Support:g.mediaAgentFactoryConfig.detectH264Support,domOverrides:g.mediaAgentFactoryConfig.domOverrides,mediaSettings:g.mediaAgentFactoryConfig.settings,logger:g.mediaAgentFactoryConfig.logger,safeLogger:g.mediaAgentFactoryConfig.safeLogger,webcvProvider:g.mediaAgentFactoryConfig.webcvProvider,wasmdnsProvider:g.mediaAgentFactoryConfig.wasmdnsProvider,wasmaecProvider:g.mediaAgentFactoryConfig.wasmaecProvider,wasmVqeProvider:g.mediaAgentFactoryConfig.wasmVqeProvider,createWasmWorkerCbs:g.mediaAgentFactoryConfig.createWasmWorkerCbs,encodedStreamsWorkerProvider:g.mediaAgentFactoryConfig.encodedStreamsWorkerProvider,clientInformation:g.signalingAgentConfig.clientInformation}),v.setMidCallTelemetry(S),v.initializeSignalingAgentProvider({signalingAgentConfig:g.signalingAgentConfig,trouterService:g.trouterService}),await v.initializeMediaAgent({httpRequestDispatcher:g.mediaAgentFactoryConfig.httpRequestDispatcher,tokenProvider:g.mediaAgentFactoryConfig.tokenProvider,configProvider:g.mediaAgentFactoryConfig.configProvider,appStateProvider:g.mediaAgentFactoryConfig.appStateProvider,clientInformation:g.signalingAgentConfig.clientInformation,trapTokenCredentialsProvider:g.mediaAgentFactoryConfig.trapTokenCredentialsProvider,relayManager:g.mediaAgentFactoryConfig.relayManager}),v}catch(g){throw g instanceof hw?g:new hw(`${g}`)}}static async buildBaseStack(g,f){const S=new _PluginlessStack(g,f);return S.initializeMediaProvider({detectH264Support:g.detectH264Support,domOverrides:g.domOverrides,mediaSettings:g.mediaSettings,logger:g.logger,safeLogger:g.safeLogger,webcvProvider:g.webcvProvider,wasmdnsProvider:g.wasmdnsProvider,wasmaecProvider:g.wasmaecProvider,wasmVqeProvider:g.wasmVqeProvider,createWasmWorkerCbs:g.createWasmWorkerCbs,encodedStreamsWorkerProvider:g.encodedStreamsWorkerProvider,clientInformation:g.clientInformation}),S}async init(){}async dispose(g=generateCauseId()){const f=this._logger.createFnLogger("dispose",g);f.info("Dispose"),this._ecsProvider.dispose(),this._e911?.dispose();const handleDisposeError=g=>{f.warn("Failed:",g)},S=this.callRegistries.map((f=>f.dispose(g).catch(handleDisposeError)));await Promise.all(S),await this._mediaAgentProvider.dispose(g),f.info("media agent is disposed"),this.callRegistries=[],f.info("call registries are disposed"),this._screenSharingManager&&(this._screenSharingManager.dispose(g),this._screenSharingManager=void 0,f.info("screensharing manager is disposed")),this._deviceManager=void 0,super.dispose()}getCallRegistry(){return this._logger.info("returning default callRegistry"),this.callRegistries[0]?this.callRegistries[0]:this._createCallRegistry()}async createCallRegistry(g,f=generateCauseId()){const S=g?mriOrId(g.id):void 0,v=this._logger.createFnLogger(`createCallRegistry[identity=${S}]`,f),C=this.callRegistries.find((f=>f.identity===g.id));return C&&!C.isDisposing?(v.info(`callRegistry already exists for ${mriOrId(g.id)}`),C):(C?.isDisposing&&await C.disposePromise,this._createCallRegistry(g))}createCompositor(g){throw new Error("Method not implemented.")}_createCallRegistry(g){if(!this._trouterService)throw new hw("Unable to create call registry, trouter service undefined");if(!this._mediaAgent)throw new hw("Unable to create call registry, media agent undefined");if(!this._signalingAgentProvider)throw new hw("Unable to create call registry, signaling agent undefined");const f=new po(this._trouterService,this._signalingAgentProvider,this._mediaAgent,this._logger,createTelemetryLoggersFromConfig(this._config),this._ecsProvider,g,this._oneDsTelemetryLoggers,this._config.vdi3diagnostics);return f.on("disposed",(()=>{this.callRegistries.splice(this.callRegistries.indexOf(f),1)})),f.on("accountConfigurationReceived",(g=>{this._waitForAccountConfiguration.isPending&&(this._waitForAccountConfiguration.resolve(g),window.clearTimeout(this._waitForAccountConfigurationTimeout)),this._relayManagerProvider.getOrCreateRelayManager().setDefaultRelayConfig(g.relayConfig),this._relayManagerProvider.getOrCreateRelayManager().setClientSupportsGenericTokenApi(g.clientSupportsGenericTokenAPI)})),f.on("locationInfoSet",((g,f)=>{this._e911?.setClientInfo(g,f)})),this._relayManagerProvider.getOrCreateRelayManager(),this.callRegistries.push(f),f}initializeMediaProvider(g){const f=(0,je.assign)({},g);this._mediaAgentProvider=new nP(f,this._ecsProvider,this.platformCallConstraintsProvider),this._deviceManager=new vo(this._mediaAgentProvider.getDeviceManager())}setMidCallTelemetry(g){this._midCallTelemetry=g}getDeviceManager(){return this._deviceManager}async getDeviceManagerAsync(){return this._deviceManager}createDeviceManager(g){return this._deviceManager}getScreenSharingManager(){return this._screenSharingManager}getSetup(){}getEcsProvider(){return this._ecsProvider}async getEcsProviderAsync(){return this._ecsProvider}getCallFeedback(){return null}getAiMdp(){return null}fireIntent(g,f){}getVersion(){return{build:getTsCallingVersion(),ovb:getOvb()}}async getVersionAsync(){return{build:getTsCallingVersion(),ovb:getOvb()}}getMediaStatus(){return null}getVideoCapabilityLimits(){return null}async setMediaConfig(g){this._mediaAgent.setMediaConfig(g)}async getE911Info(){return this._e911?.getInfo()}setPlatformCallConstraints(g){this.platformCallConstraintsProvider.setConstraints(g)}getPlatformSupportLevel(){return this._platformManager.getPlatformSupportLevel(!!this._mediaAgent)}async getPlatformSupportLevelAsync(){return this.getPlatformSupportLevel()}getLiveStreamClient(){const getTelemetryLogger=()=>createTelemetryLoggersFromConfig(this._config).tlePlayer;return new Ft(this._ecsProvider.createEcsConfiguration(),this._logger.createChild("LiveStreamClient"),getTelemetryLogger)}createVoipCallCoordinator(){}async setLogFileName(g,f,S){throw new Error("not supported")}aggregateDiagnosticLogs(g){return Promise.reject("not supported")}submitBrbReport(g,f){return Promise.reject("not supported")}extendBrbFeedback(g,f){return Promise.reject("not supported")}async addOcclusion(g,f,S,v,C,_){}async removeOcclusion(g,f,S,v){}async flushLogs(){throw new Error("not supported")}getDebugDump(){return this._mediaAgent&&maskSensitiveData(JSON.stringify(this._mediaAgent.getDiagnosticsData()),'"(redacted)",')}async getStageCapability(){throw new Error("not supported")}async getAiCameraCapability(){throw new Error("not supported")}createAiCameraManager(){throw new Error("not supported")}async disposeMediaAgent(g=generateCauseId()){if(!this._mediaAgent)throw new hw("_mediaAgent is not initialized");await(this._mediaAgent?.dispose(g)),this._mediaAgent=null}async updateSignalingAgentProviderConfig(g){if(!this._signalingAgentProvider)throw new hw("_signalingAgentProvider not initialized");this._trouterService=g.trouterService,this._signalingAgentProvider.getSignalingAgent().updateSignalingAgentConfig(g.signalingAgentConfig)}},gw={build(g,f=!0){const S=g.telemetryContextProvider?.(),v=new oP(S),C=new Ao;return f&&initLogger(g,v,C),uw.build(g,v,C)},buildBaseStack(g){const f=g.telemetryContextProvider?.(),S=new oP(f);return uw.buildBaseStack(g,S)},getVersion:()=>({build:getTsCallingVersion(),ovb:getOvb()})},pw=[{className:lo,props:["callId","endpointId","participantId","callMode","spamRiskLevel","spamStirAttestation","groupId","threadId","messageId","backroomThreadId","lobbyThreadId","streamThreadId","callType","conversationType","calleeAlternateId","callerMri","acceptedElsewhereBy","state","terminatedReason","failureType","callEndDiagnosticsInfo","transferDiagnosticsInfo","capabilities","transferState","parkState","origin","isPreheatEnabled","publishedStates","participants","dominantSpeakerInfo","slowedDownActiveTalkerInfo","callStartedAt","callHeldAt","participantCounts","conversationStartTime","isAudioStreamConnected","isVideoOn","isScreenSharingOn","isIncomingOneOnOneVideoCall","localMediaStreams","mediaStreams","isMuted","isServerMuted","isSpeakerMuted","conversationId","isEmergency","isCast","isHuddleGroupCall","label","isHostless","endpoints","meetingDetails","meetingStates","role","meetingRole","advancedMeetingRole","meetingRoles","participantType","tenantId","transferorMri","transferorDisplayName","transferorType","consultativeCallId","callQueueInfo","incomingCallType","invitationData","customHeaderContext","clientTransferContext","onBehalfOfMri","onBehalfOfUserDisplayName","callPhoneLineType","forwardingDestinationType","optimalVideoCount","maxIncomingVideoCount","maxIncomingVbssCount","contentSharingSessions","screenSharingControl","ptzHandler","broadcastMeeting","broadcastMetadata","dataChannelAdapter","meetingData","meetingInfo","region","meetingGroupDetails","breakoutDetails","videoLayout","callLimits","redirectionProperties","fromApplicationType","maskedIdentityDetails","complianceRecordingContent","bannerContent","callQueueSupervisorContent","supervisorCallQueueMri","meetingLayoutDetails","compositionServiceDetails","joinAsStreamingUser","otpIdentity","enableCaptcha","groupKeyManagerMri","sendSignalLevel","displayNameSource","getIncomingRawAudioStream","getUnmixedAudioProvider","init","initAsync","setDeviceManager","forceUpdate","join","joinCallWithoutCallModality","start","startCallToVoicemail","startCallWithNudge","startWithMeetingData","joinWithMeetingData","subscribeWithMeetingData","startAndUnpark","unpark","joinPreheatedCall","park","updateMeetingRoles","acknowledge","accept","reject","admitParticipant","admit","addParticipant","nudgeParticipants","updateParticipantsProperties","callMeBack","removeParticipant","stop","cancelNudge","mute","unmute","muteParticipants","muteSpeaker","unmuteSpeaker","getSpeakerVolume","setSpeakerVolume","hold","unhold","updateEndpointMetadata","sendDtmfTone","setMaxVideoChannels","setMaxVbssChannels","startVideo","stopVideo","startAudio","stopAudio","startScreenSharing","changeCropRegion","stopScreenSharing","isRecordingLocally","startLocalRecording","stopLocalRecording","includeSystemAudioInLocalRecording","startDataChannel","stopDataChannel","sendUserEvents","shareSystemSound","startFaceStream","stopFaceStream","startInRoomFaceAtrribution","stopInRoomFaceAtrribution","startMultichannelAudioDevice","stopMultichannelAudioDevice","transferCall","callBlindTransfer","callSafeTransfer","transferCallToVoicemail","callConsultativeTransfer","consultativeTransferWithPickupCode","callRedirect","assimilate","merge","getServerHoldLocation","getJoinBlob","getTechnicalInformationJson","createContentSharingSession","setAudioUsageMode","setAudioMidcallConfig","setAudioMidcallConfigJson","setParticipantSpatialAudioPositions","reconnect","provideCallQualityFeedback","dumpVideoSourceImages","addGroupModality","addParticipants","addBroadcastModality","mergeWithPickupCode","publishState","publishStatesForEveryone","removeState","removeStatesForEveryone","updateMeetingSettings","updateMeetingGroups","updateMeetingLiveState","updateParticipantInterpretationState","joinMeetingGroup","leaveMeetingGroup","mergeParticipants","sendMessages","setMeetingLayout","updateMonitorSession","updateMeetingStates","showCQFInfo","isCqfRendered","provideCallQualityFeedbackEx","searchParticipants","getAllParticipants","getMediaTelemetry","getMediaSessionStats","getMediaSessionStatsAsync","getMediaLogs","setVideoMidcallConfigJson","pictureInPicture","setPlatformCallConstraints","setCallConstraints","switchInterpreterGroup","setLiveInterpretationAttributes","selectDevices","getSelectDevices","createStage","setAudioStreamConnectedAsync","setSpamRiskLevelAsync","setSpamStirAttestationAsync","setDominantSpeakerInfoAsync","setSlowedDownActiveTalkerInfoAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:po,props:["calls","identity","setConfiguration","updateDisplayName","updateSkypeToken","updateToken","fireIntent","getSetup","getEcsConfig","dispose","createCallAsync","getCall","getCallState","debugInformation","setLocationInfo","createDownloader","getUnassembledLocalRecordingSessions","submitBrbReport","extendBrbFeedback","initialize","logout","init","uninit","login","createCall","createCallWithGroupId","createCallWithMeetingData","deleteCall","deleteCallAsync","enableWindowUninitEventHandler","disableWindowUninitEventHandler","enableWindowUninitEventHandlerAsync","disableWindowUninitEventHandlerAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:hs,props:["id","displayName","role","tenantId","voiceLevel","isServerMuted","state","stateReason","streams","participantCapabilities","acceptedBy","endpoints","contentSharingRole","callEndDiagnosticsInfo","balanceUpdates","meetingRole","advancedMeetingRole","meetingRoles","participantType","otpIdentity","getSourceIdForMediaType","getDiagnosticData","getDiagnosticDataAsync","isIdentityMasked","nonMaskedId","nonMaskedDisplayName","nonMaskedObjectId","maskedIdSeqNumber","version","propertyBag","dispose","disposeAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:vo,props:["getPermissionState","getPermissionStateAsync","isAudioOutputSelectionSupported","askDevicePermission","enumerateDevicesAsync","getPreferredCamera","selectDevices","getSelectedDevices","createPreview","createPreviewRenderer","createScreenSharingPreviewRenderer","getDeviceNameAsync","getSpeakerDeviceDomIdAsync","setDeviceEffectsAsync","getDeviceEffectsCapabilityAsync","setBackgroundImageAsync","getImagePropertyAsync","transformImageAsync","sendMessageDeviceVideoEffectsAsync","sendMessageDeviceVideoExtensibilityAsync","setVideoCaptureConfigAsync","captureVideoFrameWithoutEffectsAsync","enableSignLanguageDetectionAsync","downloadAiModel","setAudioProcessingFlags","getSpeakerVolume","getSpeakerSystemVolume","setSpeakerVolume","setSpeakerSystemVolume","unmuteMicrophone","unmuteSpeaker","getNrgLevelsForDeviceTuner","getNrgLevelPollerForDeviceTuner","setAudioEffectsAsync","getAudioFeatureCapability","getMicrophoneVolume","setMicrophoneVolume","setDeviceTelemetryData","getSourceFormats","enableShellSharing","disableShellSharing","enableParticipantCameras","registerDerivedSource","unregisterDerivedSource","getMicrophoneGeometryArrayInfoAsync","startAudioLoopbackDevice","getRawDeviceMediaStream","setRawMediaStream","unsetRawMediaStream","createAudioRenderer","getPersonalizedNoiseSuppression","getRtcAudioManager","dispose","registerCompositeVideoDevice","unregisterCompositeVideoDevice","createAudioPlayer","mapBrowserDevices","setAudioProcessingFlagsAsync","selectDevicesAsync","getSelectedDevicesAsync","getAudioFeatureProviderName","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:oP,props:["setEcsConfig","setUserEcsServerUrl","getUserEcsServerUrl","setActiveUserForEcs","getEcsQueryParameters","ecsGetUserQueryParameters","shouldTriggerCQF"]},{className:sa,props:["controlState","role","enableScreenSharingControl","setScreenSharingControlFeatureFlag","isScreenSharingControlEnabled","initControlForSharer","initControlForViewer","shutdownControlForSharer","shutdownControlForViewer","sendRemoteControlEvent","setRenderer","setPointerImage","setLocalPointerImage","setRemotePointerImage","startPointerMode","stopPointerMode","requestControl","acceptControlRequest","denyControlRequest","grantControl","terminateControl","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:us,props:["contentSharingState","contentSharingStatus","contentSharingTerminationReason","contentSharingIdentity","contentSharingGuid","startContentSharing","joinContentSharing","updateContentSharingSessionState","takeContentSharingControl","updateContentSharingParticipantStateToViewer","stopContentSharing","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:Ms,props:["addHandler","removeHandler","updateNegotiationTag"]},{className:rs,props:["id","type","rank","label","mediaSourceId","dynamicVirtualParticipantId","deviceCapabilities","ordinal","getRawStream","start","stop","selectVideoTrack","setVideoStreamConfig","getDiagnosticData","getStats","isAvailable","isStreaming","participantId","endpointId","negotiationTag","isActive","dispose","disposeAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:ns,props:["id","type","rank","label","mediaSourceId","dynamicVirtualParticipantId","deviceCapabilities","ordinal","getRawStream","start","stop","selectVideoTrack","setVideoStreamConfig","getDiagnosticData","getStats","isAvailable","isStreaming","participantId","endpointId","negotiationTag","isActive","dispose","disposeAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:uw,props:["init","getCallRegistry","createCallRegistry","callRegistries","cancelOperation","getDeviceManager","createDeviceManager","getScreenSharingManager","getSetup","getEcsProvider","getCallFeedback","getAiMdp","getVersion","getMediaStatus","getVideoCapabilityLimits","setMediaConfig","fireIntent","getE911Info","getLocationInfo","setAllowPrivacySensitiveApis","getGeolocationCapabilityState","getLiveStreamClient","getUmsStream","createVoipCallCoordinator","setLogFileName","aggregateDiagnosticLogs","addOcclusion","removeOcclusion","extendBrbFeedback","getDebugDump","flushLogs","getStageCapability","getAiCameraCapability","createAiCameraManager","dispose","getVersionAsync","getDeviceManagerAsync","getEcsProviderAsync","changed","on","once","changedAsync","onAsync","onceAsync"].concat(["getPlatformSupportLevel","setPlatformCallConstraints","createCompositor","initializeMediaAgent","initializeSignalingAgentProvider","disposeMediaAgent","updateSignalingAgentProviderConfig","getPlatformSupportLevelAsync"])}];
/*! Bundled license information:

	@nevware21/ts-utils/dist/es5/mod/ts-utils.js:
	  (*! https://github.com/nevware21/ts-utils v0.11.3 *)

	@nevware21/ts-async/dist/es5/mod/ts-async.js:
	  (*!
	   * NevWare21 Solutions LLC - ts-async, 0.5.2
	   * https://github.com/nevware21/ts-async
	   * Copyright (c) NevWare21 Solutions LLC and contributors. All rights reserved.
	   * Licensed under the MIT license.
	   *)
	*/
if("object"==typeof C.exports&&"object"==typeof v){var __cp=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let C of Object.getOwnPropertyNames(f))Object.prototype.hasOwnProperty.call(g,C)||C===S||Object.defineProperty(g,C,{get:()=>f[C],enumerable:!(v=Object.getOwnPropertyDescriptor(f,C))||v.enumerable});return g};C.exports=__cp(C.exports,v)}return C.exports}))})),O={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,MEDIA_ERROR:410,PRECONDITION_FAILED:412,UNSUPPORTED_MEDIA_TYPE:415,UNPROCESSABLE_ENTITY:422,INTERNAL_ERROR:500,NOT_IMPLEMENTED:501};const D={CALL_AGENT_RTC:{INCOMING_CALL_HANDLING_INVALID_NOTIFICATION_PAYLOAD:{message:"Failed to handle incoming call notification. Invalid payload in the notification",code:400,subCode:3080,resultCategories:["UnexpectedServerError"]},INCOMING_CALL_HANDLING_FAILED_TO_EXTRACT_PAYLOAD:{message:"Failed to handle incoming call notification. Failed to extract payload from notification",code:400,subCode:3081,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_HANDLING_CALL_ALREADY_HANDLED:{message:"Failed to handle incoming call notification. Notification ignored as this exact call is already ongoing",code:400,subCode:3082,resultCategories:["ExpectedError"]},INCOMING_CALL_HANDLING_IGNORING_DUPLICATE_NOTIFICATION:{message:"Failed to handle incoming call notification. Ignored duplicated notification for this call as it was already handled",code:400,subCode:3083,resultCategories:["ExpectedError"]},INCOMING_CALL_HANDLING_FAILED_TO_HANDLE_NOTIFICATION_FOR_GROUPID_CALL:{message:"Failed to handle incoming call notification. Failed to create call based on notification payload",code:400,subCode:3084,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_HANDLING_BAD_NOTIFICATION_PAYLOAD:{message:"Failed to handle incoming call notification. The payload is improperly formatted and cannot be processed",code:400,subCode:3085,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_HANDLING_CALL_SETUP_SUCCEEDED:{message:"Failed to handle incoming call notification. Notification handling succeeded and incoming call will ring",code:400,subCode:3086,resultCategories:["Success"]},INCOMING_CALL_HANDLING_CALL_SETUP_FAILED:{message:"Failed to handle incoming call notification. Failed to setup incoming call",code:400,subCode:3087,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_HANDLING_BAD_NOTIFICATION_EVENT_TYPE:{message:"Failed to handle incoming call notification. Notification type is not a supported.",code:400,subCode:3088,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_HANDLING_CALL_ALREADY_EXISTS:{message:"Failed to handle incoming call notification. Client already exists and in progress",code:400,subCode:3089,resultCategories:["ExpectedError"]},INCOMING_CALL_HANDLING_CALL_FAILED_CANNOT_CONNECT:{message:"Failed to handle incoming call notification. Couldn't complete setup due to network issues",code:400,subCode:3090,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_HANDLING_CALL_FAILED_NO_SIGNALING:{message:"Failed to handle incoming call notification. Client couldn't start call signaling",code:400,subCode:3091,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_HANDLING_CALL_FAILED_CONFLICT:{message:"Failed to handle incoming call notification. There is already an active call with the same caller",code:400,subCode:3092,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_HANDLING_CALL_FAILED_PUSH_IGNORED:{message:"Failed to handle incoming call notification. The notification was ignored",code:400,subCode:3093,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_HANDLING_CALL_FAILED_ANSWERED_ELSEWHERE:{message:"Failed to handle incoming call notification. The call was already answered elsewhere before this endpoint could process this notification",code:400,subCode:3094,resultCategories:["ExpectedError"]},INCOMING_CALL_HANDLING_CALL_FAILED_CALL_ALREADY_ENDED:{message:"Failed to handle incoming call notification. The call was either canceled by caller or timed out",code:400,subCode:3095,resultCategories:["ExpectedError"]},INCOMING_CALL_HANDLING_CALL_SETUP_IN_PROGRESS:{message:"Failed to handle incoming call notification. The call notification was processed successfully and another event will be raised when the notification processing completes with result code",code:400,subCode:3096,resultCategories:["ExpectedError"]}},CALL_CLIENT:{INIT_CALL_CLIENT:{message:"Failed to initialize CallClient. Please try again, if issue persists, gather browser console logs, and contact Azure Communication Services support.",code:500,subCode:4e4,resultCategories:["UnexpectedClientError"]},CREATE_CALL_AGENT:{message:"Failed to create CallAgent. Please try again, if issue persists, gather browser console logs, and contact Azure Communication Services support.",code:409,subCode:40001,resultCategories:["UnexpectedClientError"]},CREATE_TEAMS_CALL_AGENT:{message:"Failed to create TeamsCallAgent. Please try again, if issue persists, gather browser console logs, and contact Azure Communication Services support.",code:409,subCode:40002,resultCategories:["UnexpectedClientError"]},RELAY_INFO:{message:"Failed to create a URL object with the ICE server URL provided.",code:400,subCode:40003,resultCategories:["ExpectedError"]},RELAY_UNRECOGNIZED_SCHEMA:{message:"The ICE server url must contain 'turn', 'turns', or 'stun'.",code:400,subCode:40004,resultCategories:["ExpectedError"]},PROXY_SHORT_URL:{message:"Failed setup proxy, the url is too short",code:400,subCode:40005,resultCategories:["ExpectedError"]},PROXY_PROTOCOL:{message:"Failed setup proxy, the protocol is not https or http",code:400,subCode:40006,resultCategories:["ExpectedError"]},SETUP_PROXY:{message:"Failed to create a URL object with the proxy URL provided.",code:400,subCode:40007,resultCategories:["ExpectedError"]},ONE_CALL_AGENT_PER_CALL_CLIENT:{message:"CallClient instance can support only one CallAgent or TeamsCallAgent create new CallClient instance to create new CallAgent or TeamsCallAgent",code:400,subCode:40008,resultCategories:["ExpectedError"]},EMERGENCY_CODE_TOO_LONG:{message:"EmergencyCountryCode is invalid, max length is 10",code:400,subCode:40009,resultCategories:["ExpectedError"]}},CALL_STACK:{BAD_PROTOCOL:{message:"ACS Web Calling SDK must be used through https, file:, or localhost",code:400,subCode:40100,resultCategories:["ExpectedError"]},BASE_STACK_INIT_TIMEOUT:{message:"Failed to create CallAgent, timeout during initialization of the calling base stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:408,subCode:40101,resultCategories:["UnexpectedClientError"]},BASE_STACK_INIT_FAILED:{message:"Failed to create CallAgent, failure during initialization of the calling base stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40102,resultCategories:["UnexpectedClientError"]},USER_STACK_NO_BASE_STACK:{message:"Failed to create CallAgent, failure to initialize calling user stack because calling base stack failed to create. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40103,resultCategories:["UnexpectedClientError"]},USER_STACK_INIT_TIMEOUT:{message:"Failed to create CallAgent, timeout during initialization of the calling user stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:408,subCode:40104,resultCategories:["UnexpectedClientError"]},USER_STACK_INIT_FAILED:{message:"Failed to create CallAgent, failure during initialization of the calling user stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40105,resultCategories:["UnexpectedClientError"]},PARSE_CONFIG:{message:"Failed to set configurations for the calling stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40106,resultCategories:["UnexpectedClientError"]},SET_STACK_CONFIG:{message:"Failed to set user configurations for calling stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40107,resultCategories:["UnexpectedClientError"]},GET_DM:{message:"Failed to get device manager due to internal call stack undefined. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40108,resultCategories:["UnexpectedClientError"]},SET_STACK_PARAMS:{message:"Failed to set configuration parameters for the calling stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40109,resultCategories:["UnexpectedClientError"]},FOUND_UNDEFINED_CONFIGS:{message:"Fetched undefined configurations for the calling stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40110,resultCategories:["UnexpectedClientError"]},SIGNALING_SERVICE_CREATE_FAIL:{message:"Failed to connect to Azure Communication Services infrastructure. Please try again and check the browser's network requests. If the requests keep failing, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40111,resultCategories:["UnexpectedClientError"]},SIGNALING_INIT_FAIL:{message:"Failed to initialize connection to Azure Communication Services infrastructure. Please try again and check the browser's network requests. If the requests keep failing, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40112,resultCategories:["UnexpectedClientError"]},SIGNALING_SERVICE_ALREADY_INITIALIZED:{message:"Already connected to Azure Communication Services infrastructure. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40113,resultCategories:["ExpectedError"]},SIGNALING_SERVICE_CREATE_TIMEOUT:{message:"Failed to connect to Azure Communication Services infrastructure, timeout during initialization. Please try again and check the browser's network requests. If the requests keep failing, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:408,subCode:40114,resultCategories:["UnexpectedClientError"]},SIGNALING_UNINITIALIZED:{message:"Failed to create CallAgent, unable to initialize connection to Azure Communication Services infrastructure. Please try again and check the browser's network requests. If the requests keep failing, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:412,subCode:40115,resultCategories:["UnexpectedClientError"]},USER_STACK_MEDIA_INIT_FAILED:{message:"Failed to create CallAgent, media failure during initialization of the calling user stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40116,resultCategories:["UnexpectedClientError"]},USER_STACK_SIGNALING_INIT_FAILED:{message:"Failed to create CallAgent, signaling failure during initialization of the calling user stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40117,resultCategories:["UnexpectedClientError"]},USER_STACK_INTERNAL_INIT_FAILED:{message:"Failed to create CallAgent, internal stack failure during initialization of the calling user stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40118,resultCategories:["UnexpectedClientError"]},USER_STACK_MEDIA_INIT_FAILED_PLATFORM_NOT_SUPPORTED:{message:"Media stack is not supported on this platform",code:400,subCode:40119,resultCategories:["UnexpectedClientError"]},FETCH_CONFIG:{message:"Failed to fetch configurations for the calling stack",code:500,subCode:40120,resultCategories:["UnexpectedClientError"]}},CALL_AGENT:{PROXY_CUSTOM_TURN_FORBIDDEN:{message:"Using proxy or custom TURN for calls involving Teams is disabled",code:403,subCode:40200,resultCategories:["ExpectedError"]},PARSE_ACCESSTOKEN:{message:"Failed to parse AccessToken",code:500,subCode:40201,resultCategories:["UnexpectedClientError"]},CANT_CALL_YOURSELF:{message:"Call to yourself is not supported.",code:400,subCode:40202,resultCategories:["ExpectedError"]},ACS_ALREADY_DISPOSED:{message:"Call Agent is already disposed",code:409,subCode:40203,resultCategories:["ExpectedError"]},CTE_ALREADY_DISPOSED:{message:"Teams Call Agent is already disposed",code:409,subCode:40204,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to CallAgent event, unknown event name.",code:422,subCode:40205,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from CallAgent event, unknown event name.",code:422,subCode:40206,resultCategories:["ExpectedError"]},MESH_DEVICETYPE_V2:{message:"Device type must be msft-acs-mesh-deviceType-v2 to join immersive call",code:400,subCode:40207,resultCategories:["ExpectedError"]},STACK_NOT_INIT:{message:"Failed to start or join call, call stack did not initialize",code:500,subCode:40208,resultCategories:["UnexpectedClientError"]},INVALID_JOIN_LOCATOR:{message:"Invalid join locator specified.",code:400,subCode:40209,resultCategories:["ExpectedError"]},INVALID_MEETING_LINK:{message:"The provided Teams meeting link is invalid.",code:400,subCode:40210,resultCategories:["ExpectedError"]},GROUPCALL_THREADID:{message:"Starting a group call must include thread ID in StartTeamsGroupCallOptions.",code:400,subCode:40212,resultCategories:["ExpectedError"]},ONE_TO_ONE_THREADID:{message:"Starting a one to one with thread ID is invalid.",code:400,subCode:40213,resultCategories:["ExpectedError"]},ENTERPRISE_DISPLAY_NAME:{message:"Display name is not allowed to be set for Teams users.",code:400,subCode:40214,resultCategories:["ExpectedError"]},DISPLAY_NAME_TOO_LONG:{message:"Display name is too long.",code:400,subCode:40215,resultCategories:["ExpectedError"]},INIT_FAIL:{message:"Failed to create CallAgent. Please try again, if issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:40216,resultCategories:["UnexpectedClientError"]},GET_TOKEN_BEFORE_INIT:{message:"Attempted to get AccessToken before initialization",code:422,subCode:40217,resultCategories:["UnexpectedClientError"]},INVALID_PUSH_NOTIFICATION_DATA:{message:"Invalid push notification data provided. No 'incomingCallContext' key found in the PushNotificationData.",code:400,subCode:40218,resultCategories:["ExpectedError"]},PUSH_NOTIFICATION_FAIL:{message:"Failed to handle push notification",code:500,subCode:40219,resultCategories:["UnexpectedClientError"]},INCOMING_PUSH_NOTIFICATION_PAYLOAD_TOO_MANY_KEYS:{message:"Incoming Call push notification payload provided has too many keys. Only 'incomingCallContext' key is expected in the PushNotificationData.",code:400,subCode:40220,resultCategories:["ExpectedError"]},INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD_NO_CONTEXT_PROVIDED:{message:"Invalid push notification data provided. No 'incomingCallContext' key found in the PushNotificatitonData.",code:400,subCode:40221,resultCategories:["ExpectedError"]},INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD:{message:"The decoded 'incomingCallContext' data is invalid.",code:400,subCode:40222,resultCategories:["ExpectedError"]},INCOMING_PUSH_NOTIFICATION_ALREADY_PROCESSED:{message:"Incoming Call is already being processed",code:400,subCode:40223,resultCategories:["ExpectedError"]},INCOMING_PUSH_NOTIFICATION_FAILED_TO_PROCESS:{message:"Failed to handle Incoming Call push notification",code:500,subCode:40224,resultCategories:["UnexpectedClientError"]},INCOMING_PUSH_NOTIFICATION_CALL_MISSED:{message:"Missed call",code:400,subCode:40225,resultCategories:["ExpectedError"]},USERIDS_MUST_BE_OBJECTS:{message:"AssertIsObject failed. : userIds must be object",code:400,subCode:40226,resultCategories:["ExpectedError"]},USERIDS_CANNOT_BE_NULL:{message:"AssertNotNull failed. : userIds cannot be null",code:400,subCode:40227,resultCategories:["ExpectedError"]},ACS_CALLAGENT_ALREADY_EXSISTS:{message:"Failed to create CallAgent, an instance of CallAgent associated with this identity already exists. Please dispose the existing CallAgent, or create a new one with a different identity.",code:409,subCode:40228,resultCategories:["ExpectedError"]},ACS_CALLAGENT_TOKEN_ONLY:{message:"CallAgent must be created only with ACS token",code:403,subCode:40229,resultCategories:["ExpectedError"]},TEAMS_CALLAGENT_ALREADY_EXSISTS:{message:"Failed to create TeamsCallAgent, an instance of TeamsCallAgent associated with this identity already exists. Please dispose the existing TeamsCallAgent before creating a new one.",code:409,subCode:40230,resultCategories:["ExpectedError"]},TEAMS_CALLAGENT_TOKEN_ONLY:{message:"TeamsCallAgent must be created only with Teams token",code:403,subCode:40231,resultCategories:["ExpectedError"]},FAILED_TO_GET_TOKEN:{message:"Failed to get token",code:409,subCode:40232,resultCategories:["UnexpectedClientError"]},REFRESHED_TOKEN_INVALID_USERID:{message:"Refreshed AccessToken User Id doesnt match initial User Id.",code:400,subCode:40233,resultCategories:["ExpectedError"]},REFRESHED_TOKEN_RETRIES:{message:"Access token is expired and failed to fetch a valid one after retries.",code:400,subCode:40234,resultCategories:["ExpectedError"]},ACCESSTOKEN_EXPIRED:{message:"AccessToken expired",code:401,subCode:40235,resultCategories:["ExpectedError"]},UNSUPPORTED_TARGET_TYPE:{message:"Unsupported target participant type in ACS-Teams call",code:400,subCode:40236,resultCategories:["ExpectedError"]},UNSUPPORTED_TFL_MEETING_JOIN:{message:"Joining a Teams for life meeting is not supported",code:400,subCode:40238,resultCategories:["ExpectedError"]},SET_DEVICE_TYPE_NOT_ALLOWED:{message:"setDeviceType is not allowed",code:500,subCode:40239,resultCategories:["UnexpectedClientError"]}},DEVICE_MANAGER:{GET_MEDIA_STREAM_TRACK:{message:"Failed to get raw device stream track",code:500,subCode:40600,resultCategories:["UnexpectedClientError"]},GET_MEDIA_STREAM_DEVICE_UNAVAILABLE:{message:"Failed to get raw device stream track, make sure there is available device",code:412,subCode:40601,resultCategories:["UnexpectedClientError"]},GET_DM:{message:"Failed to get device manager.",code:500,subCode:40602,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to DeviceManager event, unknown event name.",code:422,subCode:40603,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from DeviceManager event, unknown event name.",code:422,subCode:40604,resultCategories:["ExpectedError"]},ACCESS_DM:{message:"Unable to access device manager",code:500,subCode:40605,resultCategories:["UnexpectedClientError"]},SPEAKER_ENUMERATION_UNSUPPORTED:{message:"Failed to enumerate speakers, it is not supported to enumerate/select speakers on Android Chrome, iOS Safari, nor MacOS Safari.",code:405,subCode:40606,resultCategories:["ExpectedError"]},SELECT_MICROPHONE_TIMEOUT:{message:"Microphone selection timed out.",code:408,subCode:40607,resultCategories:["UnexpectedClientError"]},SELECT_MICROPHONE_FAIL:{message:"There was an issue with selecting the microphone",code:500,subCode:40608,resultCategories:["UnexpectedClientError"]},SELECT_SPEAKER_TIMEOUT:{message:"Speaker selection timed out.",code:408,subCode:40609,resultCategories:["UnexpectedClientError"]},SELECT_SPEAKER_FAIL:{message:"There was an issue with selecting the speaker",code:500,subCode:40610,resultCategories:["UnexpectedClientError"]},SPEAKER_SELECTION_UNSUPPORTED:{message:"This device does not support speaker selection.",code:405,subCode:40611,resultCategories:["ExpectedError"]},ONE_PERMISSION_ATLEAST:{message:"At least one permission must be requested",code:400,subCode:40612,resultCategories:["ExpectedError"]},PERMISSION_NOT_GRANTED_OR_FAILED:{message:"Failed to obtain permission to use microphone and/or camera, it was denied or it failed. Please ensure to allow the permissions in the browser's setttings and in the OS setttings.",code:400,subCode:40613,resultCategories:["ExpectedError"]},ADP_FAIL:{message:"Failed to ask for device permissions Please ensure to allow the permissions in the browser's setttings and in the OS setttings and try again. If issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:40614,resultCategories:["UnexpectedClientError"]},INVALID_DEVICE:{message:"Invalid AudioDeviceInfo object passed in. Ensure it has an Id.",code:400,subCode:40615,resultCategories:["ExpectedError"]},DEVICE_NOT_SELECTABLE:{message:"The device is not selectable",code:400,subCode:40616,resultCategories:["ExpectedError"]},DEVICE_ENUMERATING_FAIL:{message:"Failed to enumerate device.",code:500,subCode:40617,resultCategories:["UnexpectedClientError"]}},CALL:{OPERATION_NOT_ALLOWED_DURING_EMERGENCY_CALL:{message:"Attempted invalid operation during Emergency Call.",code:500,subCode:41e3,resultCategories:["ExpectedError"]},OPERATION_FAILED:{message:"{0} failed",code:500,subCode:41001,resultCategories:["UnexpectedClientError"]},REMOTE_AUDIO_GET_MEDIA_STREAM_UNDEFINED:{message:"Unable to get remote audio stream, getMediaStream returned undefined",code:500,subCode:41002,resultCategories:["UnexpectedClientError"]},REMOTE_AUDIO_GET_MEDIA_STREAM_RETURNED_ERROR:{message:"Unable to get remote audio stream, getMediaStream returned error",code:500,subCode:41003,resultCategories:["UnexpectedClientError"]},REMOTE_AUDIO_GET_MEDIA_STREAM_DISABLED:{message:"Getting raw audio media stream is currently disabled by Azure Communication Services.",code:409,subCode:41004,resultCategories:["ExpectedError"]},ACCEPT_INCOMING_CALL:{message:"Failed to accept the Incoming Call",code:500,subCode:41005,resultCategories:["UnexpectedClientError"]},ACCEPT_NOT_RINGING:{message:"Failed to accept the incoming call, it is not in the Ringing state. Subcscribe to CallAgent's 'incomingCall' event to accept the incoming call.",code:400,subCode:41006,resultCategories:["ExpectedError"]},REJECT_NOT_RINGING:{message:"Failed to reject the incoming call, it is not in the Ringing state. Subcscribe to CallAgent's 'incomingCall' event to reject the incoming call.",code:400,subCode:41007,resultCategories:["ExpectedError"]},LOCAL_AUDIO_GET_MEDIA_STREAM:{message:"Failed to get raw stream from local audio stream",code:500,subCode:41008,resultCategories:["UnexpectedClientError"]},LOCAL_AUDIO_SET_MEDIA_STREAM:{message:"Failed to set raw input audio stream",code:500,subCode:41009,resultCategories:["UnexpectedClientError"]},LOCAL_AUDIO_UNSET_MEDIA_STREAM:{message:"Failed to unset raw input audio stream",code:500,subCode:41010,resultCategories:["UnexpectedClientError"]},LOCAL_AUDIO_UNDEFINED_STACK:{message:"Failed to process audio because the calling stack is undefined. Please collect browser console logs and contact Azure Communication Services support.",code:500,subCode:41011,resultCategories:["UnexpectedClientError"]},REMOVE_LOCAL_VIDEO_ON_BAD_UFD:{message:"Removing local video stream due to video fail UFD being raised before call connected. Please ensure to allow video permissions in the browser's setttings and in the OS setttings, and ensure the camera device is not being used by another process.",code:409,subCode:41012,resultCategories:["UnexpectedClientError"]},STOP_AUDIO_ON_BAD_UFD:{message:"Failed to stop audio on microphone device not functioning or capture mute event {0} with value {1}",code:400,subCode:41013,resultCategories:["UnexpectedClientError"]},INSTANTIATE_CALL:{message:"Failed to instantiate the Call",code:500,subCode:41014,resultCategories:["UnexpectedClientError"]},MIC_MUTE:{message:"Failed to mute microphone. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41015,resultCategories:["UnexpectedClientError"]},MIC_UNMUTE:{message:"Failed to unmute microphone. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:400,subCode:41016,resultCategories:["UnexpectedClientError"]},MIC_UNMUTE_AND_STARTAUDIO:{message:"Failed to recover the microphone audio after bad microphone UFD recovered. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:410,subCode:41017,resultCategories:["UnexpectedClientError"]},MUTE_ALL_PARTICIPANTS_DISABLED:{message:"Mute other participants is currently disabled by ACS service.",code:403,subCode:41018,resultCategories:["ExpectedError"]},MUTE_ALL_PARTICIPANTS:{message:"Failed to mute all remote participants",code:500,subCode:41019,resultCategories:["UnexpectedClientError"]},MUTE_INCOMING_AUDIO:{message:"Failed to mute incoming audio",code:500,subCode:41020,resultCategories:["UnexpectedClientError"]},UNMUTE_INCOMING_AUDIO:{message:"Failed to unmute incoming audio",code:500,subCode:41021,resultCategories:["UnexpectedClientError"]},DTMF_TONE:{message:"Failed to send DTMF tone",code:400,subCode:41022,resultCategories:["UnexpectedClientError"]},INVALID_DTMF_TONE:{message:"Invalid value passed to DtfmTone",code:422,subCode:41023,resultCategories:["ExpectedError"]},START_AUDIO_BEFORE_VIDEO:{message:"Failed to start audio before starting video",code:500,subCode:41024,resultCategories:["UnexpectedClientError"]},STREAM_NULL:{message:"Failed to start video, LocalVideoStream instance is invalid or empty. Please pass in a LocalVideoStream instance.",code:400,subCode:41025,resultCategories:["ExpectedError"]},STREAM_IS_NOT_LVS:{message:"Failed to start video, localVideoStream is not an instance of LocalVideoStream",code:400,subCode:41026,resultCategories:["ExpectedError"]},VIDEO_ALREADY_ON:{message:"Failed to start video, video is already started.",code:400,subCode:41027,resultCategories:["ExpectedError"]},VIDEO_SET_MEDIA_STREAM:{message:"Failed to set media stream",code:500,subCode:41028,resultCategories:["UnexpectedClientError"]},START_VIDEO:{message:"Failed to start video",code:500,subCode:41029,resultCategories:["UnexpectedClientError"]},VIDEO_ALREADY_OFF:{message:"Failed to stop video, video is already stopped.",code:400,subCode:41030,resultCategories:["ExpectedError"]},VIDEO_UNDEFINED_STACK:{message:"Failed to start video because the calling stack is undefined. Please gether browser console logs, .HAR files, and contact Aure Communication Services support.",code:500,subCode:41031,resultCategories:["UnexpectedClientError"]},STOP_WRONG_STREAM:{message:"Failed to stop video, invalid argument. LocalVideoStream used as an input is currently not being sent.",code:400,subCode:41032,resultCategories:["ExpectedError"]},HOLD_CALL:{message:"Failed to hold the call. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41033,resultCategories:["UnexpectedClientError"]},RESUME_CALL:{message:"Failed to resume the call.Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41034,resultCategories:["UnexpectedClientError"]},SS_ALREADY_ON:{message:"Failed to start screen share, screen share is already started.",code:400,subCode:41035,resultCategories:["ExpectedError"]},SS_RAW_STREAM_IS_NOT_LVS:{message:"Failed to start raw screen sharing, localVideoStream is not an instance of LocalVideoStream",code:400,subCode:41036,resultCategories:["ExpectedError"]},SS_RAW_STREAM_UNDEFINED:{message:"Unable to get media stream from local video stream for raw media screen sharing. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41037,resultCategories:["UnexpectedClientError"]},SS_RAW_STREAM_SET:{message:"Failed to set raw media stream for screen sharing. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:422,subCode:41038,resultCategories:["UnexpectedClientError"]},SS_RAW_STREAM_GET:{message:"Failed to get raw screen sharing stream. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:422,subCode:41039,resultCategories:["UnexpectedClientError"]},START_SS:{message:"Failed to start screen sharing",code:500,subCode:41040,resultCategories:["UnexpectedClientError"]},SS_ALREADY_OFF:{message:"Failed to stop screen share, screen share is already stopped.",code:400,subCode:41041,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to Call event, unknown event name.",code:422,subCode:41042,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Call event, unknown event name.",code:422,subCode:41043,resultCategories:["ExpectedError"]},ONLY_SINGLE_VIDEO_STREAM:{message:"Only single LocalVideoStream is supported currently",code:400,subCode:41044,resultCategories:["ExpectedError"]},NOT_INSTANCE_OF_LVS:{message:"Stream is not an instance of LocalVideoStream",code:400,subCode:41045,resultCategories:["ExpectedError"]},ONLY_SINGLE_AUDIO_STREAM:{message:"Only single LocalAudioStream is supported currently",code:400,subCode:41046,resultCategories:["ExpectedError"]},NOT_INSTANCE_OF_LAS:{message:"Stream is not an instance of LocalAudioStream",code:400,subCode:41047,resultCategories:["ExpectedError"]},VIDEO_FAILED_TO_START:{message:"Failed to start video during call setup process. Please ensure to allow video permissions in the browser's setttings and in the OS setttings, and ensure the camera device is not being used by another process.",code:410,subCode:41048,resultCategories:["UnexpectedClientError"]},AUDIO_FAILED_TO_START:{message:"Failed to start audio during call setup process. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:400,subCode:41049,resultCategories:["UnexpectedClientError"]},LARGE_MEETING_FORCE_ISAVAILABLE:{message:"Failed to force isAvailable flag to false during large meeting",code:500,subCode:41050,resultCategories:["UnexpectedClientError"]},LARGE_MEETING_DISPOSE_VIEW:{message:"Failed to dispose view in large meeting",code:500,subCode:41051,resultCategories:["UnexpectedClientError"]},ADD_UNKNOWN:{message:"Not able to add unkown participant.",code:400,subCode:41052,resultCategories:["ExpectedError"]},PARTICIPANT_ALREADY_IN_CALL:{message:"Participant is already in the call.",code:400,subCode:41053,resultCategories:["ExpectedError"]},PARTICIPANT_NOT_IN_CALL:{message:"Failed to remove the specified participant. The participant is not in the call.",code:400,subCode:41054,resultCategories:["ExpectedError"]},CTE_ADDPARTICIPANT_NO_THREAD_ID:{message:"Add participant failed: thread ID is missing in options.",code:400,subCode:41055,resultCategories:["ExpectedError"]},CTE_VOICE_NOT_ENABLED:{message:"Failed to start or join to the call, Teams Enterprise voice policy is not enabled for this Azure Communication Services resource. Follow the tutorial online to enable it.",code:412,subCode:41056,resultCategories:["ExpectedError"]},SERVER_CALL_ID:{message:"Failed to get server call Id",code:500,subCode:41057,resultCategories:["UnexpectedClientError"]},VOLUME_TRACK:{message:"Failed to get the MediaStream to initialize the Volume indicator. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41058,resultCategories:["UnexpectedClientError"]},VOLUME_INIT:{message:"Failed to setup volume calcualtor using AudioContext, please retry getVolumeindicator on a working audio stream with exponential backoff",code:500,subCode:41059,resultCategories:["UnexpectedClientError"]},VOLUME_EVENT_SUBSCRIBE:{message:"Not able to subscribe to Volume Indicator event, unknown event name.",code:400,subCode:41060,resultCategories:["ExpectedError"]},VOLUME_EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Volume Indicator event, unknown event name.",code:400,subCode:41061,resultCategories:["ExpectedError"]},VOLUME_GET:{message:"Failed to setup volume calculator, please retry after exponential backoff",code:500,subCode:41062,resultCategories:["UnexpectedClientError"]},GET_SERVER_CALL_ID:{message:"Failed to get serverCallId, serverCallId is empty",code:404,subCode:41063,resultCategories:["UnexpectedClientError"]},MEDIA_CONSTRAINTS_DISABLED:{message:"Setting call constraint is currently disabled by ACS service.",code:409,subCode:41064,resultCategories:["ExpectedError"]},SET_CONSTRAINTS_START_OR_ACCEPT:{message:"Error setting call constraints at call setup. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41065,resultCategories:["UnexpectedClientError"]},SET_CONSTRAINTS_MID_CALL:{message:"Error setting call constraints during mid-call",code:500,subCode:41066,resultCategories:["UnexpectedClientError"]},SET_CONSTRAINTS:{message:"Error settting video constraints during call settup or mid-call. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41067,resultCategories:["UnexpectedClientError"]},ACCEPT_VIDEO_CONSTRAINTS:{message:"Error setting video constraints during call accept",code:500,subCode:41068,resultCategories:["UnexpectedClientError"]},CALLSTART_VIDEO_CONSTRAINTS:{message:"Error setting video constraints during call start",code:500,subCode:41069,resultCategories:["UnexpectedClientError"]},SET_VIDEO_CONSTRAINTS:{message:"Failed to set call constraints during mid call",code:500,subCode:41070,resultCategories:["UnexpectedClientError"]},START_SS_CALL_NOT_CONNECTED:{message:"Failed to start screen share, call is not in Connected state. Subscribe to the Call's 'statteChanged' event to know when the call is connected.",code:412,subCode:41071,resultCategories:["ExpectedError"]},STOP_SS_CALL_NOT_CONNECTED:{message:"Failed to stop screen sharing. Call must be in connected state",code:412,subCode:41072,resultCategories:["ExpectedError"]},ACCESS_RAW_MEDIA_STREAM_DISABLED:{message:"Failed to get or set custom MediaStream, this functionality is currently disabled by Azure Communication Services.",code:412,subCode:41073,resultCategories:["ExpectedError"]},ACCESS_RAW_MEDIA_STREAM_UNDEFINED_FUNC:{message:"The raw media stream function is currently not available",code:500,subCode:41074,resultCategories:["UnexpectedClientError"]},SS_RAW_STREAM_LVS_IS_NOT_RAW_MEDIA:{message:"Failed to start raw screen sharing, localVideoStream doesn't contain a raw media stream",code:400,subCode:41075,resultCategories:["ExpectedError"]},START_AUDIO_STREAM_FAILED:{message:"Failed to start audio stream.",code:400,subCode:41076,resultCategories:["UnexpectedClientError"]},STOP_VIDEO_FAILED:{message:"Failed to stop video.",code:500,subCode:41077,resultCategories:["UnexpectedClientError"]},START_AUDIO_LAS_NOT_RAW_MEDIA:{message:"Failed to start raw audio, localAudioStream doesn't contain a raw media stream. To start raw audio, the LocalAudioStream passed in, must be constructed with a MediaStream object.",code:400,subCode:41083,resultCategories:["ExpectedError"]},STOP_AUDIO_LAS_NOT_RAW_MEDIA:{message:"Failed to stop raw audio, localAudioStream doesn't contain a raw media stream. To stop raw audio, the current LocalAudioStream in the call must have a MediaStream as the source.",code:400,subCode:41084,resultCategories:["ExpectedError"]},TEAMS_INVALID_THREAD_ID:{message:"Thread ID is invalid.",code:400,subCode:41085,resultCategories:["ExpectedError"]},MUTE_ALL_PARTICIPANTS_PSTN_UNSUPPORTED:{message:"Failed to mute ineligible PSTN remote participants.",code:405,subCode:41086,resultCategories:["ExpectedError"]},MUTE_ALL_PARTICIPANTS_CALL_NOT_CONNECTED:{message:"Failed to mute all remote participants. Call must be in connected state",code:412,subCode:41087,resultCategories:["ExpectedError"]},STOP_AUDIO_STREAM_CALL_NOT_CONNECTED:{message:"Failed to stop audio stream. Call must be in connected state",code:412,subCode:41088,resultCategories:["ExpectedError"]},ADD_PARTICIPANT_CALL_NOT_CONNECTED:{message:"Failed to add participant. Call must be in connected state",code:412,subCode:41089,resultCategories:["ExpectedError"]},REMOVE_PARTICIPANT_CALL_NOT_CONNECTED:{message:"Failed to remove participant. Call must be in connected state",code:412,subCode:41090,resultCategories:["ExpectedError"]},STOP_AUDIO_STREAM_FAILED:{message:"Failed to stop audio stream.",code:400,subCode:41091,resultCategories:["UnexpectedClientError"]},MUTE_ALL_PARTICIPANTS_NONCONNECTED_UNSUPPORTED:{message:"Failed to mute remote participants that are not in connected state.",code:405,subCode:41092,resultCategories:["ExpectedError"]},MUTE_ALL_PARTICIPANTS_1_TO_1_UNSUPPORTED:{message:"Failed to mute remote participants as mute others in 1-1 calls are unsupported.",code:405,subCode:41093,resultCategories:["ExpectedError"]},IP_AUDIO_NOT_ALLOWED:{message:"Failed to mute/unmute as VOIP Audio is not allowed in this call.",code:403,subCode:41104,resultCategories:["ExpectedError"]},IP_VIDEO_NOT_ALLOWED:{message:"Failed to start/stop video as VOIP Video is not allowed in this call.",code:403,subCode:41105,resultCategories:["ExpectedError"]},MIC_DISABLED:{message:"Failed to unmute as mic is disabled in this call.",code:403,subCode:41106,resultCategories:["ExpectedError"]},CAMERA_DISABLED:{message:"Failed to start video as camera is disabled in this call.",code:403,subCode:41107,resultCategories:["ExpectedError"]},UNMUTE_CONSENT_RESTRICTED:{message:"Unmute operation not allowed for participants that have not provided consent for recording or transcription as explicit consent is enabled.",code:400,subCode:41108,resultCategories:["ExpectedError"]},VIDEOSTART_CONSENT_RESTRICTED:{message:"Video start operation not allowed for participants that have not provided consent for recording or transcription as explicit consent is enabled.",code:400,subCode:41109,resultCategories:["ExpectedError"]},SCREENSHARE_CONSENT_RESTRICTED:{message:"Screen Share operation not allowed for participants that have not provided consent for recording or transcription as explicit consent is enabled.",code:400,subCode:41110,resultCategories:["ExpectedError"]},CONSENT_NOT_SUPPORTED_1TO1:{message:"Bad request. Explicit consent is not supported for 1:1 calls.",code:400,subCode:41111,resultCategories:["ExpectedError"]},FAILED_TO_SET_CONSENT:{message:"Failed to set user consent publish state. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41112,resultCategories:["UnexpectedServerError"]},CONSENT_ALREADY_SET_OR_NOT_REQUIRED:{message:"Bad request. Consent for recording or transcription is either already provided or it is not required for the call.",code:400,subCode:41113,resultCategories:["ExpectedError"]}},LOBBY:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to Lobby event, unknown event name.",code:422,subCode:41800,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Lobby event, unknown event name.",code:422,subCode:41801,resultCategories:["ExpectedError"]},CONV_UNSUPPORTED:{message:"Current conversation type doesn't support lobby admit and reject",code:400,subCode:41802,resultCategories:["ExpectedError"]},ALREADY_IN_MEETING:{message:"Participant is already in the meeting.",code:400,subCode:41803,resultCategories:["ExpectedError"]},NOT_IN_LOBBY:{message:"Participant is not in the lobby.",code:400,subCode:41804,resultCategories:["ExpectedError"]},UNAUTHORIZED_ADMIT_REJECT:{message:"only Organizer, Co-organizer or Presenter can admit/reject participants from lobby",code:403,subCode:41805,resultCategories:["ExpectedError"]}},CTE_MID_TIER_POLICY_SERVICE:{TEAMS_USER_ID_NOT_PROVIDED:{message:"Failed to fetch Teams user policies and settings cannot proceed, because teams user Id was not found in the AccessToken.",code:400,subCode:41900,resultCategories:["ExpectedError"]},FETCH_POLICY:{message:"Error Fetching Teams user policy from ACS MiddleTier Service",code:500,subCode:41901,resultCategories:["UnexpectedServerError"]},DERIVE_EMERGENCY_POLICY:{message:"Unable to derive emergency policy from ACS MiddleTier Service response",code:500,subCode:41902,resultCategories:["UnexpectedServerError"]},TEAMSUSER_CALLINGPOLICY_FETCHING_FAILED:{message:"Unable to fetch Teams calling policy from ACS MiddleTier Service response. Please try again, if the issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:41903,resultCategories:["UnexpectedServerError"]},TEAMSUSER_MEETINGPOLICY_FETCHING_FAILED:{message:"Unable to fetch Teams meeting policy from ACS MiddleTier Service response. Please try again, if the issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:41904,resultCategories:["UnexpectedServerError"]},TEAMSUSER_FEATURETYPE_TEAMSPROMGMT_FETCHING_FAILED:{message:"Unable to fetch feature types from ACS MiddleTier Service response. Please try again, if the issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:41905,resultCategories:["UnexpectedServerError"]},CREATETHREAD_FAILED:{message:"Unable to create thread for the Teams User groupcall from ACS MiddleTier Service response",code:500,subCode:41906,resultCategories:["UnexpectedServerError"]},ADD_PARTICIPANTS_TO_THREAD_FAILED:{message:"Unable to add particpant for the thread for Teams groupcall from ACS MiddleTier Service",code:500,subCode:41907,resultCategories:["UnexpectedServerError"]}},REMOTE_PARTICIPANT:{MUTE_PARTICIPANT_DISABLED:{message:"Mute other participants is disabled by ACS service.",code:403,subCode:42e3,resultCategories:["ExpectedError"]},MUTE_PARTICIPANT_FAILED:{message:"Failed to mute specific participant",code:500,subCode:42001,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to RemoteParticipant event, unknown event name.",code:422,subCode:42002,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from RemoteParticipant event, unknown event name.",code:422,subCode:42003,resultCategories:["ExpectedError"]},MUTE_PARTICIPANT_PSTN_UNSUPPORTED:{message:"The scenario to soft mute a PSTN participant is not supported.",code:405,subCode:42004,resultCategories:["ExpectedError"]},MUTE_PARTICIPANT_NONCONNECTED_UNSUPPORTED:{message:"The scenario to soft mute a participant who is not connected is not supported.",code:405,subCode:42005,resultCategories:["ExpectedError"]},MUTE_PARTICIPANT_1_TO_1_UNSUPPORTED:{message:"The scenario to soft mute a participant is a 1-1 call is not supported.",code:405,subCode:42006,resultCategories:["ExpectedError"]}},LOCAL_VIDEO_STREAM:{SOURCE_UNAVAILABLE:{message:"Failed to start video, video device is being used by another process/application. Stop your camera from being used in the other process/application and try again.",code:412,subCode:43e3,resultCategories:["ExpectedError"]},PERMISSION_DENIED:{message:"Failed to start video, permission was not granted to use selected video device. Ensure video device permissions are allowed in the browser's settings and in the system's setttings.",code:403,subCode:43001,resultCategories:["ExpectedError"]},UNKNOWN:{message:"Failed to start video, unknown error. Please try again. If the issue persists, contact Azure Communication Services support.",code:500,subCode:43002,resultCategories:["UnexpectedClientError"]},WRONG_STREAM_TYPE:{message:"Failed to create local video stream, source was not of type VideoDeviceInfo or MediaStream",code:400,subCode:43003,resultCategories:["ExpectedError"]},SWITCH_SOURCE_WRONG_TYPE:{message:"Failed to switch video device, invalid input. Input must be of a VideoDeviceInfo type.",code:400,subCode:43004,resultCategories:["ExpectedError"]},SWITCH_SAME_SOURCE:{message:"Failed to switch video device, unable to switch to the same video device, it's already selected.",code:400,subCode:43005,resultCategories:["ExpectedError"]},CANT_GET_DEVICE_TYPE:{message:"Unable to get device type",code:500,subCode:43006,resultCategories:["UnexpectedClientError"]},VIDEO_GET_MEDIA_STREAM:{message:"Failed to get raw video stream. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43007,resultCategories:["UnexpectedClientError"]},SET_MEDIA_STREAM_WRONG_TYPE:{message:"Failed to set media stream source is not MediaStream",code:400,subCode:43008,resultCategories:["ExpectedError"]},SET_MEDIA_STREAM_UNDEFINED_FUNC:{message:"Failed to set raw video stream. Found undefined function. Gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43009,resultCategories:["UnexpectedClientError"]},SET_MEDIA_STREAM:{message:"Failed to set raw video stream. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43010,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to LocalVideoStream event, unknown event name.",code:422,subCode:43011,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from LocalVideoStream event, unknown event name.",code:422,subCode:43012,resultCategories:["ExpectedError"]},DEVICES_NOT_FOUND:{message:"Failed to start video, no video devices found. Ensure video devices are plugged in and enabled in the system settings.",code:412,subCode:43013,resultCategories:["ExpectedError"]},MEDIA_STREAM_REQUEST_ERROR:{message:"Failed to start video, error requesting media stream. Please try again, if issue persists, contact Azure Communication Services support.",code:412,subCode:43014,resultCategories:["UnexpectedClientError"]},MEDIA_STREAM_REQUEST_TIMEDOUT:{message:"Failed to start video, media stream request timed out. PLease allow permission on the browser's prompt to access the camera and try again.",code:412,subCode:43015,resultCategories:["ExpectedError"]},PERMISSION_DENIED_BY_SYSTEM:{message:"Failed to start video, permissions denied by system. Ensure video device permissions are allowed in the browser's settings and in the system's setttings.",code:412,subCode:43016,resultCategories:["ExpectedError"]},UNSUPPORTED_STREAM:{message:"Failed to start video, unsupported stream. Please try again, if issue persists, contact Azure Communication Services support.",code:412,subCode:43017,resultCategories:["UnexpectedClientError"]},CONSTRAINT_NOT_SATISFIED:{message:"Failed to start video, failed to set constraints. Please try again, if issue persists, contact Azure Communication Services support.",code:412,subCode:43018,resultCategories:["UnexpectedClientError"]},NO_DEVICE_SELECTED:{message:"Failed to start video, no device selected. Please ensure to pass a LocalVideoStream constructed with a VideoDeviceInfo and try again. If issue persists, contact Azure Communication Services support.",code:412,subCode:43019,resultCategories:["UnexpectedClientError"]},CALL_NOT_FOUND:{message:"Start video is cancelled because call has ended.",code:412,subCode:43021,resultCategories:["ExpectedError"]}},REMOTE_VIDEO_STREAM:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to RemoteVideoStream event, unknown event name.",code:422,subCode:43100,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from RemoteVideoStream event, unknown event name.",code:422,subCode:43101,resultCategories:["ExpectedError"]},GET_RAW_MEDIA_STREAM:{message:"Not able to get media stream",code:500,subCode:43102,resultCategories:["UnexpectedClientError"]},RAWMEDIA_LVS_NOT_AVAILABLE:{message:"The remote video stream is currently not available, subscribe to the stream's isAvailable property to get notified when it is ready to get the raw media stream.",code:400,subCode:43103,resultCategories:["ExpectedError"]},SUBSCRIBE_MEDIA_STREAM_TIMEOUT:{message:"Failed to subscribe to media stream, timeout",code:408,subCode:43104,resultCategories:["UnexpectedClientError"]},GET_TRACK:{message:"Failed to get media stream",code:500,subCode:43105,resultCategories:["UnexpectedClientError"]},TRACK_UNMUTED_TIMEOUT:{message:"Failed to subscribe to media stream, muted",code:408,subCode:43106,resultCategories:["UnexpectedClientError"]},GET_MEDIA_STREAM:{message:"Failed to get raw media stream",code:500,subCode:43107,resultCategories:["UnexpectedClientError"]}},VIEW:{ISAVAILABLE_FALSE:{message:"Failed to render video stream, this stream is not available. Subscribe to the stream's isAvailable property to get notified when the remote participant has their video on and the stream is available for rendering.",code:412,subCode:43200,resultCategories:["ExpectedError"]},START_ALREADY_DISPOSED:{message:"Failed to start stream, already disposed",code:405,subCode:43201,resultCategories:["ExpectedError"]},STREAM_BECAME_UNAVAILABLE:{message:"Failed to render video stream, this stream is not longer available. Remote participant turned their video off.",code:404,subCode:43202,resultCategories:["ExpectedError"]},TIMEOUT:{message:"Failed to render video stream, rendering timed out while waiting for video frames. Please try again, if issue persists, contact Azure Communication Services support.",code:408,subCode:43203,resultCategories:["UnexpectedClientError"]},SUBSCRIBE:{message:"Failed to render video stream, failed to subscribe to video on the Azure Communication Services infrastructure. Please try again, if issue persists, contact Azure Communication Services support.",code:500,subCode:43204,resultCategories:["UnexpectedClientError"]},START:{message:"Failed to start stream, internal error",code:500,subCode:43205,resultCategories:["UnexpectedClientError"]},SCALING_MODE:{message:"Failed to updateScalingMode, failed to update",code:500,subCode:43206,resultCategories:["UnexpectedClientError"]},LARGE_MEETING_VIEW_DISPOSED:{message:"Failed to start stream, disposing stream because participant is not a dominant speaker in the large meeting",code:405,subCode:43207,resultCategories:["ExpectedError"]},REMOTE_VIDEO_STREAM_DISPOSED:{message:"Failed to start stream, disposing stream because remote video stream is disposing",code:405,subCode:43208,resultCategories:["ExpectedError"]},APP_VIEW_DISPOSED:{message:"Failed to render video stream, VideoStreamRenderer was disposed during initialization process.",code:405,subCode:43209,resultCategories:["ExpectedError"]},RENDERER_DISPOSE_ALREADY_DISPOSED:{message:"Failed to dispose VideoStreamRenderer, it is already disposed.",code:400,subCode:43210,resultCategories:["ExpectedError"]},REMOTE_RENDERER_DISPOSE_FAIL:{message:"Failed to dispose remote renderer",code:500,subCode:43211,resultCategories:["UnexpectedClientError"]},VIEW_WRONG_STREAM_TYPE:{message:"Failed to create VideoStreamRendererView, videoStream must be either LocalVideoStream or RemoteVideoStream type",code:400,subCode:43212,resultCategories:["ExpectedError"]},VIEW_ALREADY_DISPOSED:{message:"Failed to dispose, VideoStreamRendererView is disposed",code:400,subCode:43213,resultCategories:["ExpectedError"]},RENDER_FAIL_STREAM_DISPOSED:{message:"Failed to render, stream disposed",code:400,subCode:43214,resultCategories:["ExpectedError"]},SCALING_MODE_DISPOSED:{message:"Failed to updateScalingMode, VideoStreamRendererView is disposed",code:400,subCode:43215,resultCategories:["ExpectedError"]},SCALING_MODE_WRONG_VAL:{message:"Failed to updateScalingMode, wrong scalingMode value",code:400,subCode:43216,resultCategories:["ExpectedError"]},DISPOSE_FAIL:{message:"Failed to dispose view",code:500,subCode:43217,resultCategories:["UnexpectedClientError"]},RENDERER_WRONG_STREAM_TYPE:{message:"Failed to create VideoStreamRenderer, videoStream must be either LocalVideoStream or RemoteVideoStreamCommon type",code:400,subCode:43218,resultCategories:["ExpectedError"]},RENDERER_DISPOSED:{message:"Failed to create view, VideoStreamRenderer is disposed",code:400,subCode:43219,resultCategories:["ExpectedError"]},MAX_NUM_OF_VIEWS_REACHED:{message:"Failed to create view, maximum number of active RemoteVideoStream views has been reached. You can dispose of a previous one in order to create new one.",code:400,subCode:43220,resultCategories:["ExpectedError"]},CREATE_VIEW_FAILED:{message:"Failed to create view",code:500,subCode:43221,resultCategories:["UnexpectedClientError"]},RENDERER_ALREADY_DISPOSED:{message:"Failed to dispose, VideoStreamRendererView is already disposed",code:400,subCode:43222,resultCategories:["ExpectedError"]},UNKNOWN_STREAM_TYPE:{message:"Unknown stream type",code:400,subCode:43223,resultCategories:["ExpectedError"]},LOCAL_RENDERER_DISPOSE_FAIL:{message:"Failed to dispose local renderer",code:500,subCode:43224,resultCategories:["UnexpectedClientError"]},WATERMARK_ATTACH_FAIL:{message:"Meeting has watermark enabled, but failed to generate and attach watermark. Please try again. If the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43225,resultCategories:["UnexpectedClientError"]},WATERMARK_UNEXPECTED_VALUES:{message:"Unknown watermark settings from server. Please check meeting organizer settings for watermark. If the issue persists, gather browser logs and contact Azure Communication Services support.",code:500,subCode:43226,resultCategories:["UnexpectedClientError"]},NO_WATERMARK_CAPABILITY_RECEIVED:{message:"Missing watermark capability from server. Please try again. If the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43227,resultCategories:["UnexpectedServerError"]}},LOCAL_AUDIO_STREAM:{WRONG_STREAM_TYPE:{message:"Failed to create local audio stream, source is not of type AudioDeviceInfo or MediaStream",code:400,subCode:43600,resultCategories:["ExpectedError"]},SOURCE_WRONG_TYPE:{message:"Failed to create local audio stream, source is not a microphone",code:400,subCode:43601,resultCategories:["ExpectedError"]},GET_MEDIA_STREAM:{message:"Failed to get media stream source is not AudioDeviceInfo or MediaStream",code:500,subCode:43602,resultCategories:["UnexpectedClientError"]},SET_MEDIA_STREAM_WRONG_TYPE:{message:"Failed to switch stream on local audio, source is not of type MediaStream",code:400,subCode:43603,resultCategories:["ExpectedError"]},SWITCH_SOURCE_WRONG_TYPE:{message:"Failed to create local audio stream, source is not a microphone",code:400,subCode:43604,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to LocalAudioStream event, unknown event name.",code:422,subCode:43605,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from LocalAudioStream event, unknown event name.",code:422,subCode:43606,resultCategories:["ExpectedError"]},SWITCH_SAME_SOURCE:{message:"Failed to switch audio device, unable to switch to the same audio device, it's already selected.",code:400,subCode:43607,resultCategories:["ExpectedError"]},UNKNOWN:{message:"Failed to start audio, unknown error. Please try again. If the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43608,resultCategories:["UnexpectedClientError"]}},REMOTE_AUDIO_STREAM:{},IDENTIFIER:{PARSE_PHONENUMBER:{message:"Unable to parse PhoneNumberIdentifier object",code:422,subCode:44e3,resultCategories:["ExpectedError"]},PARSE_MSFT_TEAMS_USER:{message:"Unable to parse MicrosoftTeamsUserIdentifier object",code:422,subCode:44001,resultCategories:["ExpectedError"]},PARSE_MSFT_TEAMS_APP:{message:"Unable to parse MicrosoftTeamsAppIdentifier object",code:422,subCode:44002,resultCategories:["ExpectedError"]},PARSE_IDENTIFIER:{message:"Unable to parse Identifier object, please check the syntax",code:422,subCode:44003,resultCategories:["ExpectedError"]},INVALID_COMM_USER:{message:"Invalid CommunicationUser identifier specified",code:422,subCode:44004,resultCategories:["ExpectedError"]},INVALID_MSFT_TEAMS_USER_RAWID:{message:"Invalid MicrosoftTeamsUser rawId specified",code:422,subCode:44005,resultCategories:["ExpectedError"]},INVALID_MSFT_TEAMS_USER_USERID:{message:"Invalid MicrosoftTeamsUser microsoftTeamsUserId specified",code:422,subCode:44006,resultCategories:["ExpectedError"]},INVALID_MSFT_TEAMS_APP_RAWID:{message:"Invalid MicrosoftTeamsApp rawId specified",code:422,subCode:44007,resultCategories:["ExpectedError"]},INVALID_MSFT_TEAMS_APP_APPID:{message:"Invalid MicrosoftTeamsApp teamsAppId specified",code:422,subCode:44008,resultCategories:["ExpectedError"]},INVALID_UNKNOWN_IDENTIFIER:{message:"Invalid identifier specified, please specify an id",code:422,subCode:44009,resultCategories:["ExpectedError"]},PARSE_INVALID_IDENTIFIER:{message:"Unable to parse Identifier object",code:422,subCode:44010,resultCategories:["ExpectedError"]},INVALID_IDENTIFIER_ARRAY:{message:"AssertIsArrayOfIdentifiers failed. : userIds must be array of CommunicationIdentifier",code:422,subCode:44011,resultCategories:["ExpectedError"]},NO_CLOUD_PREFIX_FOUND:{message:"No cloud prefix found in identity",code:409,subCode:44012,resultCategories:["ExpectedError"]}},INTERNAL:{ECS_CONFIG_EMPTY:{message:"Config is empty",code:500,subCode:44100,resultCategories:["UnexpectedServerError"]},ECS_CONFIG_MISSING_ACS:{message:"Missing ACS config key",code:500,subCode:44101,resultCategories:["UnexpectedServerError"]},ECS_CONFIG_MERGING_ERROR:{message:"Error while merging config",code:500,subCode:44102,resultCategories:["UnexpectedClientError"]},TELEMETRY_FAILED_TO_INITIALIZE_INVALID_CLOUD_TYPE:{message:"Failed to initialize telemetry",code:500,subCode:44103,resultCategories:["UnexpectedClientError"]},TELEMETRY_FAILED_TO_INITIALIZE_ALREADY_INITIALIZED:{message:"Failed to initialize telemetry",code:500,subCode:44104,resultCategories:["UnexpectedClientError"]},TELEMETRY_FAILED_TO_INITIALIZE:{message:"Failed to create and initialize telemetry logger for tenant. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:44105,resultCategories:["UnexpectedClientError"]},TELEMETRY_FAILED_TO_FLUSH:{message:"Failed to flush telemetry",code:500,subCode:44106,resultCategories:["UnexpectedClientError"]},TELEMETRY_LOGGER_INIT_FAIL:{message:"Failed to initialize telemetry logger",code:500,subCode:44107,resultCategories:["UnexpectedClientError"]},NO_TOKEN_PROVIDED:{message:"No CommunicationTokenCredential provided",code:401,subCode:44108,resultCategories:["ExpectedError"]},EMPTY_TOKEN:{message:"AccessToken is empty",code:401,subCode:44109,resultCategories:["ExpectedError"]},GET_TOKEN:{message:"Failed to get AccessToken",code:401,subCode:44110,resultCategories:["UnexpectedClientError"]},TOKEN_PAYLOAD_UNDEFINED:{message:"Invalid token",code:401,subCode:44111,resultCategories:["ExpectedError"]},TOKEN_UNDEFINED:{message:"Failed to parse AccessToken",code:401,subCode:44112,resultCategories:["ExpectedError"]},INVALID_TOKEN_SCOPE:{message:"AccessToken does not contain 'voip' or 'voip.join' scope",code:401,subCode:44113,resultCategories:["ExpectedError"]},INVALID_TOKEN_SCOPE_FORMAT:{message:"Wrong AccessToken scope format. Scope is expected to be a string that contains 'voip'",code:401,subCode:44114,resultCategories:["ExpectedError"]},RESOURCE_NOT_FOUND_IN_TOKEN:{message:"AccessToken does not contain ACS resource Id",code:401,subCode:44115,resultCategories:["ExpectedError"]},USERID_NOT_FOUND_IN_TOKEN:{message:"AccessToken does not contain ACS user Id",code:401,subCode:44116,resultCategories:["ExpectedError"]},PARSE_TOKEN_FAIL:{message:"Failed to parse AccessToken",code:401,subCode:44117,resultCategories:["UnexpectedClientError"]},OPERATION_TIMEDOUT:{message:"Operation timed out",code:408,subCode:44118,resultCategories:["UnexpectedClientError"]}},RAW_MEDIA:{},FEATURES:{AUDIO_EFFECTS:{SET_ECHO_CANCELLATION:{message:"Error while trying to start or stop echo cancellation. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45e3,resultCategories:["UnexpectedClientError"]},SET_NOISE_SUPPRESSION:{message:"Error while trying to start or stop noise suppression. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45001,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to AudioEffects event, unknown event name.",code:400,subCode:45002,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from AudioEffects event, unknown event name.",code:400,subCode:45003,resultCategories:["ExpectedError"]},DISABLED:{message:"Setting audio effects is currently disabled by Azure Communication Services.",code:403,subCode:45004,resultCategories:["ExpectedError"]},START_DISPOSED:{message:"Audio effects feature is disposed. Create a new AudioEffects feature instance.",code:400,subCode:45005,resultCategories:["ExpectedError"]},SOURCE_UNSUPPORTED:{message:"Current source is not supported",code:415,subCode:45006,resultCategories:["ExpectedError"]},START_DEVICE_MANAGER:{message:"Failed to get device manager to start effects.",code:500,subCode:45007,resultCategories:["UnexpectedClientError"]},STOP_DISPOSED:{message:"Audio effects feature is disposed. Create a new AudioEffects feature instance.",code:400,subCode:45008,resultCategories:["ExpectedError"]},STOP_DEVICE_MANAGER:{message:"Failed to get device manager to stop effects.",code:500,subCode:45009,resultCategories:["UnexpectedClientError"]},FAILED_TO_GET_DM:{message:"Internal error - DM missing",code:500,subCode:45010,resultCategories:["UnexpectedClientError"]},PROVIDER_UNAVAILABLE:{message:"EffectProvider not available",code:500,subCode:45011,resultCategories:["UnexpectedClientError"]},AEC_PROVIDER_MISSING:{message:"Internal error - stack aec provider missing",code:500,subCode:45012,resultCategories:["UnexpectedClientError"]},INVALID_EFFECT:{message:"Invalid effect provided",code:400,subCode:45013,resultCategories:["ExpectedError"]},INVALID_EFFECT_ECHO:{message:"Invalid or no echo cancellation effect provided",code:400,subCode:45014,resultCategories:["ExpectedError"]},INVALID_EFFECT_NOISE_SUPP:{message:"Invalid or no noise suppression effect provided",code:400,subCode:45015,resultCategories:["ExpectedError"]},UNSUPPORTED_EFFECT:{message:"Unsupported effect specified. Please specify a supported audio effect.",code:415,subCode:45016,resultCategories:["UnexpectedClientError"]},SUPPORT_CHECK_FAILED:{message:"Error while checking support",code:501,subCode:45017,resultCategories:["UnexpectedClientError"]},INVALID_EFFECT_GAINCONTROL:{message:"Invalid or no auto gain control effect provided",code:400,subCode:45018,resultCategories:["ExpectedError"]},SET_AUTO_GAIN_CONTROL:{message:"Error while trying to start or stop auto gain control. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45019,resultCategories:["UnexpectedClientError"]},AUDIO_FLAGS:{message:"Error setting browser audio processing flags",code:500,subCode:45020,resultCategories:["UnexpectedClientError"]},START_FAILED:{message:"Error starting audio effects.",code:500,subCode:45021,resultCategories:["UnexpectedClientError"]},STOP_FAILED:{message:"Error stopping audio effects.",code:500,subCode:45022,resultCategories:["UnexpectedClientError"]},DISPOSE_FAILED:{message:"Error disposing audio effects feature.",code:500,subCode:45023,resultCategories:["UnexpectedClientError"]}},AUDIO_ZONES:{},CALL_SURVEY:{INVALID_SURVEY:{message:"Invalid call survey. Please submit a survey options.",code:400,subCode:45100,resultCategories:["ExpectedError"]},SUBMIT_TIMEOUT:{message:"Failed to submit survery, timedout. Please try again, if issue persists, gather browser console logs and contact Azure Communication Services support.",code:408,subCode:45101,resultCategories:["UnexpectedClientError"]}},CAPABILITIES:{},CAPTIONS:{INITIALIZE:{message:"Failed to initialize Captions.",code:500,subCode:45200,resultCategories:["UnexpectedClientError"]},DISABLED:{message:"Captions feature is currently disabled by Azure Communication services.",code:412,subCode:45201,resultCategories:["ExpectedError"]},SPOKEN_LANG_UNSUPPORTED:{message:"Spoken language requested is not supported.",code:400,subCode:45202,resultCategories:["ExpectedError"]},MEETING_POLICY_DISABLED:{message:"Captions feature is disabled in meeting policy.",code:403,subCode:45203,resultCategories:["ExpectedError"]},CALLING_POLICY_DISABLED:{message:"Captions feature is disabled in calling policy.",code:403,subCode:45204,resultCategories:["ExpectedError"]},START_FAILED:{message:"Could not start captions.",code:500,subCode:45205,resultCategories:["UnexpectedClientError"]},UPDATE_LANGUAGE_NOT_STARTED:{message:"Cannot update spoken language as captions has not started.",code:400,subCode:45206,resultCategories:["ExpectedError"]},SPOKEN_LANG_DISABLED:{message:"Set spoken language is currently disabled by Azure Communication Services.",code:412,subCode:45207,resultCategories:["ExpectedError"]},UPDATE_LANGUAGE_GET_TOKEN:{message:"Unable to update spoken language. Failed to get token.",code:401,subCode:45208,resultCategories:["UnexpectedClientError"]},UPDATE_LANGUAGE_FAILED:{message:"Unable to update spoken language.",code:500,subCode:45209,resultCategories:["UnexpectedClientError"]},UPDATE_CAPTIONS_NOT_STARTED:{message:"Cannot update caption language as captions has not started.",code:400,subCode:45210,resultCategories:["ExpectedError"]},CAPTIONS_LANG_DISABLED:{message:"Set caption language is currently disabled by Azure Communication Services.",code:412,subCode:45211,resultCategories:["ExpectedError"]},CAPTIONS_LANG_TEAMS_LICENSE:{message:"Set caption language failed. Teams premium license is needed to use this feature.",code:401,subCode:45212,resultCategories:["ExpectedError"]},CAPTIONS_LANG_UNSUPPORTED:{message:"Caption language requested is not supported.",code:400,subCode:45213,resultCategories:["ExpectedError"]},UPDATE_CAPTIONS_GET_TOKEN:{message:"Null token",code:401,subCode:45214,resultCategories:["ExpectedError"]},UPDATE_CAPTIONS_FAILED:{message:"Unable to update caption language.",code:500,subCode:45215,resultCategories:["UnexpectedClientError"]},CTE_POLICY_FETCH_FAIL:{message:"Failed to fetch policy for Teams Captions.",code:500,subCode:45216,resultCategories:["UnexpectedClientError"]},ALREADY_ACTIVE:{message:"Captions already active",code:400,subCode:45217,resultCategories:["ExpectedError"]},STOP_NOT_ACTIVE:{message:"Captions feature is not active.",code:400,subCode:45218,resultCategories:["ExpectedError"]},ALREADY_STARTING:{message:"Operation in progress",code:400,subCode:45219,resultCategories:["ExpectedError"]},SPOKEN_LANGUAGE_ALREADY_SET:{message:"Spoken language already set",code:400,subCode:45220,resultCategories:["ExpectedError"]},UPDATE_CAPTIONS_NOT_ACTIVE:{message:"Unable to update caption language as Captions is not active.",code:400,subCode:45221,resultCategories:["ExpectedError"]},CAPTIONS_LANG_ALREADY_SET:{message:"Caption language already set.",code:400,subCode:45222,resultCategories:["ExpectedError"]},UPDATE_ENDPOINT_METADATA:{message:"Failed to update endpoint metadata",code:500,subCode:45225,resultCategories:["UnexpectedClientError"]},START_FAILED_CALL_NOT_CONNECTED:{message:"Cannot start captions as call state is not connected.",code:400,subCode:45226,resultCategories:["ExpectedError"]},START_FAILED_CALL_ENDPOINTS_NOT_AVAILABLE:{message:"Cannot start captions as call endpoints are not available.",code:400,subCode:45227,resultCategories:["ExpectedError"]}},COMPOSED_STREAM:{},DATA_CHANNEL:{DISPOSED:{message:"DataChannel has been disposed",code:500,subCode:45300,resultCategories:["UnexpectedClientError"]},SENDER_NOT_READY:{message:"Sender is not ready",code:500,subCode:45301,resultCategories:["UnexpectedClientError"]},NO_AVAILABLE_CHANNEL_ID:{message:"No available channel id",code:500,subCode:45302,resultCategories:["UnexpectedClientError"]},INVALID_CHANNEL_ID:{message:"Invalid channel id",code:400,subCode:45303,resultCategories:["ExpectedError"]},INVALID_BITRATE_IN_KBPS:{message:"Invalid bitrateInKbps",code:400,subCode:45304,resultCategories:["ExpectedError"]},INVALID_PARTICIPANTS:{message:"Invalid participants",code:400,subCode:45305,resultCategories:["ExpectedError"]},TOO_MANY_PARTICIPANTS:{message:"Too many participants",code:400,subCode:45306,resultCategories:["ExpectedError"]},NO_VALID_PARTICIPANT:{message:"No valid participant",code:400,subCode:45307,resultCategories:["ExpectedError"]},MSG_DATA_EMPTY:{message:"Message data is empty",code:400,subCode:45308,resultCategories:["ExpectedError"]},MSG_DATA_TOO_LARGE:{message:"The size of message data is too large",code:400,subCode:45309,resultCategories:["ExpectedError"]},INVALID_MSG_LENGTH:{message:"Invalid message length",code:500,subCode:45310,resultCategories:["UnexpectedClientError"]},BUFFER_FULL:{message:"The buffer is full. Please wait and try again",code:500,subCode:45311,resultCategories:["UnexpectedClientError"]},SENDER_CLOSED:{message:"The sender has been closed",code:400,subCode:45312,resultCategories:["ExpectedError"]},NO_AVAILABLE_RELIABLE_CHANNEL:{message:"Currently there is no available reliable channel",code:500,subCode:45313,resultCategories:["UnexpectedClientError"]},NO_AVAILABLE_UNRELIABLE_CHANNEL:{message:"Currently there is no available unreliable channel",code:500,subCode:45314,resultCategories:["UnexpectedClientError"]},CHANNEL_ALREADY_ALLOCATED:{message:"Unable allocate the channel because a channel with the same channelId has already been allocated",code:500,subCode:45315,resultCategories:["UnexpectedClientError"]},INVALID_BITRATE:{message:"Invalid bitrate",code:400,subCode:45316,resultCategories:["ExpectedError"]},TRAFFIC_LIMITED:{message:"Traffic is limited",code:400,subCode:45317,resultCategories:["ExpectedError"]},SEND_FAIL:{message:"Failed to send message.",code:500,subCode:45318,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to DataChannel event, unknown event name.",code:422,subCode:45319,resultCategories:["ExpectedError"]},WRONG_ARGUMENT_TYPE:{message:"Wrong argument type specified.",code:400,subCode:45320,resultCategories:["ExpectedError"]},WRONG_ARGUMENT_VALUE:{message:"Wrong value specified.",code:400,subCode:45321,resultCategories:["ExpectedError"]},CANT_FIND_CHANNEL_ID:{message:"Cannot find the channelId specified.",code:400,subCode:45322,resultCategories:["ExpectedError"]},FAILED_TO_CREATE_SENDER:{message:"Failed to create the sender.",code:500,subCode:45323,resultCategories:["UnexpectedClientError"]}},DEBUG_INFO:{},DIAGNOSTICS:{INCORRECT_VALUETYPE_MAPPED:{message:"Mapped to an incorrect value type. Please gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45400,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to UserFacingDiagnostics event, unknown event name.",code:422,subCode:45401,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from UserFacingDiagnostics event, unknown event name.",code:422,subCode:45402,resultCategories:["ExpectedError"]},INCORRECT_VALUE_MAPPED:{message:"Failed to map diagnostic quality level. Please gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45403,resultCategories:["UnexpectedClientError"]}},DOMINANT_SPEAKER:{},LIVE_STREAM:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to LiveStream event, unknown event name.",code:422,subCode:45500,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribefrom LiveStream event, unknown event name.",code:422,subCode:45501,resultCategories:["ExpectedError"]},INVALID_AGGREGATION_INTERVAL_RANGE:{message:"Invalid aggregationInterval value range.",code:400,subCode:45502,resultCategories:["ExpectedError"]},INVALID_DATAPOINTS_AGGREGATION_RANGE:{message:"invalid dataPointsPerAggregation value range.",code:400,subCode:45503,resultCategories:["ExpectedError"]},DISPOSED:{message:"MediaStatsCallFeature has been disposed.",code:400,subCode:45504,resultCategories:["ExpectedError"]}},MEDIA_STATS:{INVALID_AGGREGATION_INTERVAL_RANGE:{message:"Invalid aggregationInterval value range.",code:400,subCode:45550,resultCategories:["ExpectedError"]},INVALID_DATAPOINTS_AGGREGATION_RANGE:{message:"invalid dataPointsPerAggregation value range.",code:400,subCode:45551,resultCategories:["ExpectedError"]},DISPOSED:{message:"MediaStatsCallFeature has been disposed.",code:400,subCode:45552,resultCategories:["ExpectedError"]}},OPTIMAL_VIDEO_COUNT:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to OptimalVideoCount event, unknown event name.",code:422,subCode:45600,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from OptimalVideoCount event, unknown event name.",code:422,subCode:45601,resultCategories:["ExpectedError"]}},PPTLIVE:{},PRECALL_DIAGNOSTICS:{SET_DEVICE_FAIL:{message:"Failed to set default microphone or speaker with error",code:412,subCode:45700,resultCategories:["UnexpectedClientError"]},GET_DIAGNOSTICS_INFO:{message:"Unable to return call diagnostic information.",code:500,subCode:45701,resultCategories:["UnexpectedClientError"]},VIDEO_STREAM_TIMEOUT:{message:"Timeout in checking media stream status",code:500,subCode:45702,resultCategories:["UnexpectedClientError"]},GET_CALL_AGENT:{message:"Failed to get existing call agent or create a new one",code:500,subCode:45703,resultCategories:["UnexpectedClientError"]},CONNECT_FAIL:{message:"Test call failed to connect",code:500,subCode:45704,resultCategories:["UnexpectedClientError"]},RENDER_VIDEO:{message:"Call failed to render video.",code:500,subCode:45705,resultCategories:["UnexpectedClientError"]},HANGUP_FAIL:{message:"Test call failed hang up the call",code:500,subCode:45706,resultCategories:["UnexpectedClientError"]},VIDEO_MEDIASTATS:{message:"Failed to get video call media stats",code:500,subCode:45707,resultCategories:["UnexpectedClientError"]},CALL_CONNECT_TIMEOUT:{message:"Call timed out to connect. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:408,subCode:45708,resultCategories:["UnexpectedClientError"]}},RAISE_HAND:{INITIALIZE:{message:"Could not initialize raise hand feature.",code:500,subCode:45750,resultCategories:["UnexpectedClientError"]},RAISE_HAND_PUBLISH_STATE:{message:"Could not change a participant state.",code:500,subCode:45751,resultCategories:["UnexpectedServerError"]},RAISE_HAND_FAIL:{message:"Could not change a participant state.",code:500,subCode:45752,resultCategories:["UnexpectedServerError"]},LOWER_HAND_FAIL:{message:"Could not change a participant state.",code:500,subCode:45753,resultCategories:["UnexpectedServerError"]},LOWER_REMOTEPARTICIPANTS_HANDS_FAIL:{message:"Could not change a participant state.",code:500,subCode:45754,resultCategories:["UnexpectedServerError"]},LOWER_ALL_HANDS_FAIL:{message:"Could not change a participant state.",code:500,subCode:45755,resultCategories:["UnexpectedServerError"]},NOT_SUPPORTED_1TO1:{message:"Raise hand is not supported for 1:1 direct calling",code:400,subCode:45758,resultCategories:["ExpectedError"]}},REACTION:{CALL_NOT_CONNECTED:{message:"Call is not connected yet to send reaction",code:400,subCode:45800,resultCategories:["ExpectedError"]},NOT_SUPPORTED_1TO1_CTE:{message:"Reaction send is not supported for 1:1 direct calling with teams identity",code:400,subCode:45801,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE_FAIL_POLICY:{message:"Unable to register listener due to meeting policy",code:403,subCode:45802,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE_FAIL_POLICY:{message:"Unable to deregister listener due to meeting policy",code:403,subCode:45803,resultCategories:["ExpectedError"]},SEND_FAIL_POLICY:{message:"Unable to send reaction due to meeting policy",code:403,subCode:45804,resultCategories:["ExpectedError"]},STATE_SERVICE_CONNECT_FAIL:{message:"Could not create state service proxy web-socket connection",code:500,subCode:45805,resultCategories:["UnexpectedServerError"]},MAP_CREATE_FAIL:{message:"Could not create sync map to exchange reaction",code:500,subCode:45806,resultCategories:["UnexpectedServerError"]},NOT_INIT_YET:{message:"Unable to handle send reaction",code:400,subCode:45807,resultCategories:["ExpectedError"]},SEND_REACTION_FAIL:{message:"Unable to handle send reaction",code:500,subCode:45808,resultCategories:["UnexpectedClientError"]},RECEIVE_REACTION_FAIL:{message:"Unable to parse reaction",code:500,subCode:45809,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to Reation event, unknown event name.",code:422,subCode:45810,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Reaction event, unknown event name.",code:422,subCode:45811,resultCategories:["ExpectedError"]}},RECORDING:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to Recording event, unknown event name.",code:422,subCode:45850,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Recording event, unknown event name.",code:422,subCode:45851,resultCategories:["ExpectedError"]},RECORDING_CONSENT_FAILURE:{message:"Failed to set consent publish state for recording. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45853,resultCategories:["UnexpectedServerError"]}},SPOTLIGHT:{ALREADY_SPOTLIGHTED:{message:"Bad request. All participants are already spotlighted",code:400,subCode:45900,resultCategories:["ExpectedError"]},START_SPOTLIGHT_FAILED:{message:"Internal Error. Start spotlight for participants failed",code:500,subCode:45901,resultCategories:["UnexpectedServerError"]},SPOTLIGHT_LIGHT_MAX_REACHED:{message:"Failed to start spotlight. Reached the maximum number of participants that can be Spotlighted.",code:400,subCode:45902,resultCategories:["ExpectedError"]},UNSUPPORTED_ROLE_TYPE:{message:"Failed to spotlight. User does not have a Presenter or Organizer role.",code:403,subCode:45903,resultCategories:["ExpectedError"]},NOT_SUPPORTED_1TO1:{message:"Spotlight is not supported for 1:1 direct calling",code:400,subCode:45906,resultCategories:["ExpectedError"]}},TEAMS_MEETING_AUDIO_CONFERENCING:{ONLY_AVAILABLE_IN_MEETINGS:{message:"Teams meeting audio conferencing feature is only available in meetings",code:400,subCode:45950,resultCategories:["ExpectedError"]},DISABLED:{message:"The Teams meeting audio conferencing details feature is disabled by ACS service.",code:405,subCode:45951,resultCategories:["ExpectedError"]},UNAVAILABLE_BEFORE_JOINING:{message:"Teams meeting audio conferencing details are not available before joining the Teams meeting",code:400,subCode:45952,resultCategories:["ExpectedError"]},UNVAILABLE_IN_LOBBY:{message:"Teams meeting audio conferencing details are not available in Lobby",code:400,subCode:45953,resultCategories:["ExpectedError"]},DETAILS_NOT_CONFIGURED:{message:"Teams meeting audio conferencing details is not configured",code:400,subCode:45954,resultCategories:["UnexpectedClientError"]},GET_DETAILS_FAILED:{message:"Error retrieving Teams meeting audio conferencing details",code:500,subCode:45955,resultCategories:["UnexpectedServerError"]}},TRANSCRIPTION:{TRANSCRIPTION_CONSENT_FAILURE:{message:"Failed to set consent publish state for transcription. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:46001,resultCategories:["UnexpectedServerError"]}},TRANSFER:{TRANSFER_TO_TARGET_FAILED:{message:"Transfer to target failed",code:500,subCode:46050,resultCategories:["UnexpectedClientError"]},UNSUPPORTED_CALL_TYPE:{message:"Transfer is not supported in this call.",code:400,subCode:46051,resultCategories:["ExpectedError"]},TARGET_NOT_RECOGNIZED:{message:"Transfer target is not recognized.",code:400,subCode:46052,resultCategories:["ExpectedError"]},INVALID_TARGET_TYPE:{message:"Invalid target participant type detected.",code:400,subCode:46053,resultCategories:["ExpectedError"]}},UNMIXED_AUDIO:{UNAVAILABLE:{message:"UnmixedAudio is not available.",code:500,subCode:46100,resultCategories:["UnexpectedClientError"]},PENDING_OPERATION:{message:"The operation cannot be done because there is a pending operation",code:400,subCode:46101,resultCategories:["ExpectedError"]},UNSUPPORTED_OPERATION:{message:"The operation is not supported in peer-to-peer call",code:400,subCode:46102,resultCategories:["ExpectedError"]},ENABLED:{message:"Unmixed audio has been enabled",code:400,subCode:46103,resultCategories:["ExpectedError"]},DISABLED:{message:"Unmixed audio has been disabled",code:400,subCode:46104,resultCategories:["ExpectedError"]},DISPOSED:{message:"Unmixed audio has been disposed",code:400,subCode:46105,resultCategories:["ExpectedError"]},EVENT_SUBSCIBE_UNSUBSCRIBE:{message:"Not able to subscribe or unsubscibe to UnmixedAudio event, unknown event name.",code:422,subCode:46106,resultCategories:["ExpectedError"]},WRONG_ARGUMENT_TYPE:{message:"Wrong argument type specified.",code:400,subCode:46107,resultCategories:["ExpectedError"]},WRONG_ARGUMENT_VALUE:{message:"Wrong value specified.",code:400,subCode:46108,resultCategories:["ExpectedError"]},INVALID_STATE:{message:"Invalid state.",code:400,subCode:46109,resultCategories:["ExpectedError"]},UNKNOWN_ERROR:{message:"Unknown error",code:500,subCode:46110,resultCategories:["UnexpectedClientError"]},FAILED_TO_ENABLE:{message:"Failed to enable unmixed audio: AudioContext={0}, UnmixedAudio={1}",code:500,subCode:46111,resultCategories:["UnexpectedClientError"]},FAILED_TO_DISABLE:{message:"Failed to disable unmixed audio: AudioContext={0}, UnmixedAudio={1}",code:500,subCode:46112,resultCategories:["UnexpectedClientError"]},FAILED_TO_INITIALIZE:{message:"Failed to initialize unmixed audio.",code:500,subCode:46113,resultCategories:["UnexpectedClientError"]}},VIDEO_EFFECTS:{DISABLED:{message:"Video effects feature is currently disabled by Azure Communication Services.",code:403,subCode:46150,resultCategories:["ExpectedError"]},START_DISPOSED:{message:"VideoEffects feature is disposed. Create a new VideoEffects Feature instance.",code:400,subCode:46151,resultCategories:["ExpectedError"]},UNSUPPORTED_SOURCE:{message:"Current source is unsupported to use effects",code:415,subCode:46152,resultCategories:["ExpectedError"]},START_DEVICE_MANAGER:{message:"Failed to get device manager to start effects.",code:500,subCode:46153,resultCategories:["UnexpectedClientError"]},PROVIDER_UNAVAILABLE:{message:"EffectProvider not available",code:500,subCode:46154,resultCategories:["UnexpectedClientError"]},WEBCV_PROVIDER_FAILED:{message:"Failed to get WebCV provider.",code:500,subCode:46155,resultCategories:["UnexpectedClientError"]},UNSUPPORTED_EFFECT:{message:"Effect is not supported.",code:501,subCode:46156,resultCategories:["UnexpectedClientError"]},STOP_DISPOSED:{message:"VideoEffects feature is disposed. Create a new VideoEffects Feature instance.",code:400,subCode:46157,resultCategories:["UnexpectedClientError"]},STOP_DEVICE_MANAGER:{message:"Failed to get device manager to stop effects.",code:500,subCode:46158,resultCategories:["UnexpectedClientError"]},INVALID_EFFECT:{message:"Invalid effect provided",code:400,subCode:46159,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to event {event}, unknown event name",code:400,subCode:46160,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe event {event}, unknown event name",code:400,subCode:46161,resultCategories:["ExpectedError"]},EFFECT_PROVIDER_TIMEOUT:{message:"Timed promise; rejected.",code:408,subCode:46162,resultCategories:["UnexpectedClientError"]},SUPPORT_CHECK_FAILED:{message:"Error while checking support",code:501,subCode:46163,resultCategories:["UnexpectedClientError"]},START_FAILED:{message:"Error starting video effects",code:500,subCode:46164,resultCategories:["UnexpectedClientError"]},STOP_FAILED:{message:"Error stopping video effects",code:500,subCode:46165,resultCategories:["UnexpectedClientError"]},DISPOSE_FAILED:{message:"Error disposing video effects feature",code:500,subCode:46166,resultCategories:["UnexpectedClientError"]},EFFECT_CONFIG_UPDATE_CALLBACK_FAILED:{message:"Effect config update callback had errors",code:500,subCode:46169,resultCategories:["UnexpectedClientError"]}},LOCAL_RECORDING:{ONLY_AVAILABLE_IN_MEETINGS:{message:"Local Recording feature is only available in meetings",code:400,subCode:46200,resultCategories:["ExpectedError"]},DISABLED:{message:"Local Recording feature is currently disabled by Azure Communication Service.",code:405,subCode:46201,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to LocalRecording event, unknown event name.",code:422,subCode:46202,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from LocalRecording event, unknown event name.",code:422,subCode:46203,resultCategories:["ExpectedError"]}},BREAKOUT_ROOMS:{ONLY_AVAILABLE_IN_MEETINGS:{message:"Breakout Rooms feature is only available in Teams meetings.",code:400,subCode:46250,resultCategories:["ExpectedError"]},DISABLED:{message:"Breakout Rooms feature is currently disabled by Azure Communication Services.",code:405,subCode:46251,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to Breakout Rooms event, unknown event name.",code:422,subCode:46252,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Breakout Rooms event, unknown event name.",code:422,subCode:46253,resultCategories:["ExpectedError"]},JOIN_FAILED:{message:"Not able to join Breakout Room due to an unexpected error. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:46254,resultCategories:["UnexpectedServerError"]},MAINMEETING_HOLD_FAILED:{message:"Not able to join Breakout Room as Main meeting hold is failed. Please try again, by calling join() method. If the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:46255,resultCategories:["UnexpectedServerError"]},JOIN_FAILED_ROOM_CLOSED:{message:"Not able to join Breakout Room as the room is closed. Please check the state of the Breakout Room before calling join.",code:412,subCode:46256,resultCategories:["ExpectedError"]},MAINMEETING_RESUME_FAILED:{message:"Not able to join back to the Main meeting as the resume failed.Please gather browser console logs and contact Azure Communication Services support.",code:412,subCode:46257,resultCategories:["UnexpectedServerError"]},BREAKOUT_ROOMS_UPDATEFAILED:{message:"Error while trying to update the Breakoutroom details. Please gather browser console logs and contact Azure Communication Services support.",code:412,subCode:46258,resultCategories:["UnexpectedClientError"]},BREAKOUT_ROOM_HANGUP_FAILED:{message:"Could not hang up the Breakout room call. Please gather browser console logs and contact Azure Communication Services support.",code:500,subCode:46259,resultCategories:["UnexpectedServerError"]},BREAKOUT_ROOM_URL_DOESNOT_EXIST:{message:"Cannot join Breakout Room as the url is null or empty.Can join BreakoutRoom only when assigned.",code:412,subCode:46260,resultCategories:["UnexpectedClientError"]},RETURN_TO_MAINMEETING_FAILED:{message:"Not able to join the main meeting. Please try again by calling the ReturnToMainMeeting() method. If the issue persists, gather browser console logs and contact Azure Communication Services support.",code:412,subCode:46261,resultCategories:["UnexpectedClientError"]},ALREADY_IN_MAINMEETING:{message:"Already in the main meeting. Please call this method only when the participant is in breakoutroom and removed from the main meeting.",code:412,subCode:46262,resultCategories:["ExpectedError"]},HANGUP_EXISTING_BREAKOUT_ROOM_FAILED:{message:"Existing breakout room call hangup failed. Try to call hangup() method again to hangup the call. Call join() method to join the breakout room again.",code:412,subCode:46263,resultCategories:["UnexpectedClientError"]}},TOGETHER_MODE:{ADD_TOGETHER_MODE_BOT_FAILED:{message:"Unable to add together mode bot. Please collect browser console logs and contact Azure Communication Services support.",code:500,subCode:46300,resultCategories:["UnexpectedServerError"]},PUBLISH_TOGETHER_MODE_STATE_FAILED:{message:"Internal Error. Publish together mode state failed. Please collect browser console logs and contact Azure Communication Services support.",code:500,subCode:46301,resultCategories:["UnexpectedServerError"]},SEAT_MAP_CALCULATION_FAILED:{message:"Seat coordinates calculation failed. Please collect browser console logs and contact Azure Communication Services support.",code:500,subCode:46302,resultCategories:["UnexpectedClientError"]},UNSUPPORTED_ROLE_TYPE:{message:"Start together mode failed. User does not have a Presenter, Co-Organizer or Organizer.",code:403,subCode:46303,resultCategories:["ExpectedError"]},UNSUPPORTED_CONVERSATION_TYPE:{message:"Start together mode failed. Together mode can only be started in group call or meeting scenarios.",code:403,subCode:46304,resultCategories:["ExpectedError"]},REQUEST_INITIAL_SEAT_MAPPING_FAILED:{message:"Unable to get initial seating coordinates. Please collect browser console logs and contact Azure Communication Services support.",code:500,subCode:46305,resultCategories:["UnexpectedClientError"]},UNSUPPORTED_USER_KIND:{message:"Start Together Mode failed. Only M365 users can start together mode.",code:403,subCode:46306,resultCategories:["ExpectedError"]}},CALLKIT:{},ONE_PHONE_SYSTEM:{CUSTOM_CONTEXT_NOT_SUPPORTED:{message:"Specifying custom context is not supported when OnBehalfOfOptions is specified.",code:412,subCode:46400,resultCategories:["ExpectedError"]},CALL_CANNOT_BE_STARTED:{message:"Call cannot be started for your subscription/tenant at this time.",code:403,subCode:46401,resultCategories:["ExpectedError"]}},SHAREDLINE_APPEARANCE:{DISABLED:{message:"Shared line appearance is currently disabled by Azure Communication Services.",code:405,subCode:46450,resultCategories:["ExpectedError"]},DISABLED_BY_CALLING_POLICY:{message:"Shared line appearance is disabled by Teams calling policy. Assign TeamsCalling policy with Allow delegation to true to enabled Sharedline appearance.",code:405,subCode:46451,resultCategories:["ExpectedError"]}},MEDIA_ACCESS:{MEDIA_ACCESS_UPDATE_FAILED:{message:"Internal error while updating the audio /video access.",code:500,subCode:46500,resultCategories:["UnexpectedServerError"]},INITIALIZE_FAILED:{message:"Could not initialize media access feature.",code:500,subCode:46501,resultCategories:["UnexpectedClientError"]},UNSUPPORTED_ROLE:{message:"Change media access failed. User does not have a Organizer, Co-Organizer or Presenter role.",code:403,subCode:46502,resultCategories:["ExpectedError"]},UNSUPPORTED_CONVERSATION_TYPE:{message:"Change media access failed. Change media access can only be done in meeting/group call scenarios.",code:403,subCode:46503,resultCategories:["ExpectedError"]},ROLE_RESTRICTED:{message:"Change media access failed. Only able to change media access for attendees.",code:403,subCode:46504,resultCategories:["ExpectedError"]},CALL_NOT_CONNECTED:{message:"Failed to change media access. Call must be in connected state",code:412,subCode:46505,resultCategories:["ExpectedError"]},INVALID_MEETING_CAPABILITY_ATTENDEE_RESTRICTIONS:{message:"Change audio video access failed. Meeting capability attendee restrictions is empty",code:500,subCode:46506,resultCategories:["UnexpectedClientError"]},FEATURE_DISABLED:{message:"Feature is disabled.",code:412,subCode:46507,resultCategories:["ExpectedError"]},INVALID_PARTICIPANTS_LIST:{message:"Invalid participants list, cannot be an empty array or contain null or undefined values.",code:400,subCode:46508,resultCategories:["ExpectedError"]},UNSUPPORTED_CONVERSATION_TYPE_FOR_FORBID_PERMIT_OTHERS_MEDIA_ACCESS:{message:"Attempt to change meeting media access failed. This action is only supported in Teams meetings.",code:403,subCode:46509,resultCategories:["ExpectedError"]}},REAL_TIME_TEXT:{INITIALIZE_FAILED:{message:"Failed to initialize RealTimeTextFeature",code:500,subCode:46550,resultCategories:["UnexpectedClientError"]},START_REAL_TIME_TEXT_FAILED:{message:"Failed to start RealTimeTextFeature",code:500,subCode:46551,resultCategories:["UnexpectedClientError"]},MESSAGE_LENGTH_EXCEEDS_MAX_INPUT_LENGTH:{message:"Message length exceeds max allowed input length",code:400,subCode:46552,resultCategories:["ExpectedError"]},SEND_REAL_TIME_TEXT_MESSAGE_FAILED:{message:"Failed to send a RealTimeText message",code:500,subCode:46553,resultCategories:["UnexpectedClientError"]},SEND_DATA_CHANNEL_MESSAGE_FAILED:{message:"Failed to send data channel message",code:500,subCode:46554,resultCategories:["UnexpectedClientError"]},REAL_TIME_TEXT_MESSAGE_PARSE_FAILED:{message:"Failed to parse RealTimeText message",code:500,subCode:46555,resultCategories:["UnexpectedClientError"]},REAL_TIME_TEXT_MESSAGE_CONTAINS_NO_SPEAKER:{message:"Real Time Text message contains no speaker",code:500,subCode:46556,resultCategories:["UnexpectedClientError"]},REAL_TIME_TEXT_MESSAGE_HANDLER_FAILED:{message:"Failed to handle RealTimeText Message",code:500,subCode:46557,resultCategories:["UnexpectedClientError"]},REAL_TIME_TEXT_MESSAGE_ENTRY_UPDATE_FAILED:{message:"Failed to update RealTimeText message entry",code:500,subCode:46558,resultCategories:["UnexpectedClientError"]}}}},N={0:{0:{public:!0,code:0,subCode:0,message:"Call ended successfully by local participant.",resultCategories:["Success"]},4097:{public:!0,code:0,subCode:4097,message:"Call ended for all users by the meeting organizer.",resultCategories:["Success"]},4521:{public:!0,code:0,subCode:4521,message:"Call ended because user disconnected from the call abruptly, this may be a result of a user closing the application that hosted the call, eg a user terminated application, closed browser of browser tab without proper hang-up.",resultCategories:["ExpectedError"]},5e3:{public:!0,code:0,subCode:5e3,message:"Call ended for this participant as it was removed from the conversation by another participant.",resultCategories:["Success"]},5003:{public:!0,code:0,subCode:5003,message:"Call ended successfully, as all callee endpoints declined the call.",resultCategories:["Success"]},5010:{code:0,subCode:5010,message:"This conversation has ended as only one participant was remaining in the conversation.",resultCategories:["Success"]},5013:{code:0,subCode:5013,message:"This conversation has ended as no one else has joined the group call.",resultCategories:["Success"]},5014:{code:0,subCode:5014,message:"",resultCategories:["Success"]},5300:{public:!0,code:0,subCode:5300,message:"Call ended for this participant as it was removed from the conversation by another participant.",resultCategories:["Success"]},5854:{code:0,subCode:5854,message:"Removed from the Teams meeting lobby by another participant.",resultCategories:["Success"]},5855:{code:0,subCode:5855,message:"Removed from Teams meeting lobby due to inactivity timeout.",resultCategories:["Success"]},7e3:{public:!0,code:0,subCode:7e3,message:"Call was ended by Azure Communication Service Call Automation API or a server bot.",resultCategories:["Success"]},7015:{code:0,subCode:7015,message:"Call ended by service because transfer completed successfully.",resultCategories:["Success"]},54e4:{public:!0,code:0,subCode:54e4,message:"Call ended successfully by local PSTN caller.",resultCategories:["Success"]},56e4:{public:!0,code:0,subCode:56e4,message:"Call ended successfully by remote PSTN participant.",resultCategories:["Success"]}},400:{580040:{code:400,subCode:580040,message:"Error from CreateUsageRequest: User is not entitled to call this destination.",resultCategories:["ExpectedError"]}},401:{10009:{public:!0,code:401,subCode:10009,message:"Unauthenticated identity. Ensure that your Communication Services token is valid and not expired.",resultCategories:["UnexpectedClientError"]}},403:{830:{code:403,subCode:830,message:"Only Communication Services user is allowed to join the Rooms meeting.",resultCategories:["ExpectedError"]},5829:{code:403,subCode:5829,message:"The join isn't allowed for the Rooms meeting beyond end time or prior to start time of the meeting.",resultCategories:["ExpectedError"]},510403:{public:!0,code:403,subCode:510403,message:"Call ended, as it has been marked as a spam and got blocked.",resultCategories:["ExpectedError"]},560403:{code:403,subCode:560403,message:"Call was forbidden, cancelled or rejected",resultCategories:["UnexpectedClientError"]}},404:{404:{code:404,subCode:404,message:"Call failed, unable to start or join to a call with given Id, call does not exist. Please check if provided id is correct, and if the call did not end already and try again.",resultCategories:["UnexpectedClientError"]},4500:{code:404,subCode:4500,message:"Call failed, unable to start or join to a call with given Id, call does not exist. Please check if provided id is correct, and if the call did not end already and try again.",resultCategories:["ExpectedError"]},560404:{code:404,subCode:560404,message:"Phone number not found.",resultCategories:["ExpectedError"]}},408:{4506:{public:!0,code:408,subCode:4506,message:"Call timed out. Check if the callee received and accepted the call.",resultCategories:["UnexpectedClientError"]},10057:{public:!0,code:408,subCode:10057,message:"Call failed, callee failed to finalize call setup, most likely callee lost network or terminated the application abruptly. Ensure clients are connected and available.",resultCategories:["ExpectedError"]},10325:{code:408,subCode:10325,message:"",resultCategories:["UnexpectedClientError"]},500001:{code:408,subCode:500001,message:"Gateway (SBC) failover timer expired.",resultCategories:["ExpectedError"]},560408:{code:408,subCode:560408,message:"The called party did not respond.",resultCategories:["ExpectedError"]}},410:{3100:{public:!0,code:410,subCode:3100,message:"Call setup failed due to unexpected network problem on the client, please check client's network and retry.",resultCategories:["UnexpectedClientError"]},3101:{public:!0,code:410,subCode:3101,message:"Call dropped due to unexpected network problem on the client, check the client's network and retry.",resultCategories:["UnexpectedClientError"]},3111:{public:!0,code:410,subCode:3111,message:"Call setup failed, unable to process media offer while connecting the call.",resultCategories:["UnexpectedClientError"]},3112:{public:!0,code:410,subCode:3112,message:"Call setup failed due to network configuration problem on the client side, please check client's network configuration, and retry.",resultCategories:["ExpectedError"]},301004:{public:!0,code:410,subCode:301004,message:"Participant was removed from the call by the Azure Communication Services infrastructure due to inability to establish media connectivity with Azure Communication Services infrastructure during call setup. Check user's network configuration, including local network, firewalls, VPNs configuration and try again.",resultCategories:["UnexpectedClientError"]},301005:{public:!0,code:410,subCode:301005,message:"Participant was removed from the call by the Azure Communication Services infrastructure due to loss of media connectivity with Azure Communication Services infrastructure, this usually happens if participant leaves the call abruptly or looses network connectivity. If participant wants to continue the call, it should reconnect.",resultCategories:["UnexpectedClientError"]}},429:{5029:{code:429,subCode:5029,message:"",resultCategories:["ExpectedError"]},10110:{code:429,subCode:10110,message:"This call has exceeded the maximum call lifetime.",resultCategories:["ExpectedError"]}},430:{10315:{code:430,subCode:10315,message:"Unable to deliver message to client application. Please ensure the client application is successfully sending netwwork requests to Azure Communication Services.",resultCategories:["ExpectedError"]},10317:{code:430,subCode:10317,message:"Unable to deliver message to client application. Please ensure the client application is successfully sending netwwork requests to Azure Communication Services.",resultCategories:["ExpectedError"]}},480:{10037:{public:!0,code:480,subCode:10037,message:"Target user did not have any endpoints registered with ACS. Please ensure that target user has at least one active endpoint and it is online.",resultCategories:["ExpectedError"]},10076:{public:!0,code:480,subCode:10076,message:"Target user was registered but it wasn't online at the time of the call. Ensure that target user has at least one active endpoint and it's online.",resultCategories:["ExpectedError"]},10077:{public:!0,code:480,subCode:10077,message:"Target user was registered with ACS and/or for push notifications, but it wasn't online at the time of the call. Ensure that target user has at least one active endpoint and it's online.",resultCategories:["ExpectedError"]},10078:{public:!0,code:480,subCode:10078,message:"Remote client endpoint not registered or not reachable. Ensure the remote client endpoint is successfully sending network requests to Azure Communication Services.",resultCategories:["ExpectedError"]},560480:{code:480,subCode:560480,message:"No answer from callee. Please double check why the callee did not answer the call. Retry the call later in case that the callee was temporary unavailable.",resultCategories:["UnexpectedServerError"]}},484:{560484:{code:484,subCode:560484,message:"Incomplete/Invalid callee address.",resultCategories:["ExpectedError"]}},486:{560486:{public:!0,code:486,subCode:560486,message:"Call ended because remote PSTN participant was busy. The number called was already in a call or having technical issues.",resultCategories:["Success"]}},487:{0:{public:!0,code:487,subCode:0,message:"Call ended successfully as caller canceled the call.",resultCategories:["Success"]},4501:{code:487,subCode:4501,message:"Call canceled, locally declined, ended due to an endpoint mismatch issue, or failed to generate media offer.",resultCategories:["Success"]},10003:{public:!0,code:487,subCode:10003,message:"Call was cancelled for this user endpoint as it was was accepted elsewhere, by another endpoint.",resultCategories:["Success"]},10004:{public:!0,code:487,subCode:10004,message:"Call was cancelled on timeout, as target user did not accept or reject it on time. Ensure that user saw the notification and/or application can handle it automatically and try to initiate that call again.",resultCategories:["ExpectedError"]},10024:{public:!0,code:487,subCode:10024,message:"Call ended successfully as it was declined by all callee endpoints.",resultCategories:["Success"]},540200:{code:487,subCode:540200,message:"Call canceled, locally declined, ended due to an endpoint mismatch issue, or failed to generate media offer.",resultCategories:["Success"]},540487:{public:!0,code:487,subCode:540487,message:"Call ended successfully as caller canceled the call.",resultCategories:["Success"]},560487:{code:487,subCode:560487,message:"Call cancelled by originator.",resultCategories:["Success"]}},490:{4502:{public:!0,code:490,subCode:4502,message:"Call failed due to network connectivity problems, browser failed to complete the network HTTP request.",resultCategories:["UnexpectedClientError"]}},495:{4507:{public:!0,code:495,subCode:4507,message:"Call ended as application didn't provide a valid Azure Communication Services token.",resultCategories:["UnexpectedClientError"]}},496:{7:{public:!0,code:496,subCode:7,message:"Call ended as client lost network connection abruptly, and despite retrying multiple times it wasn't able to connect.",resultCategories:["ExpectedError"]}},500:{10045:{code:500,subCode:10045,message:"Azure Communication Services infrastructure error. Please gather browser console logs, .HAR file, and contact Azure Communication Services support.",resultCategories:["UnexpectedClientError"]}},503:{560503:{code:503,subCode:560503,message:"Unexpected server error",resultCategories:["UnexpectedServerError"]}},603:{0:{public:!0,code:603,subCode:0,message:"Call ended successfully as it was declined from callee.",resultCategories:["Success"]}}},k=O.BAD_REQUEST,L=O.REQUEST_TIMEOUT,F=O.PRECONDITION_FAILED,x=O.UNPROCESSABLE_ENTITY,U=O.INTERNAL_ERROR,V="19:preview-",B={Date:!0,RegExp:!0,String:!0,Number:!0},H=3e3,$=Symbol("INTERNAL_TELEMETRY_ERROR_MESSAGE_SYMBOL");var j;class CallingCommunicationError extends Error{constructor(g){if(super(),this._code=0,this._subCode=0,this._resultCategories=[],this[j]="",this.name="CallingCommunicationError",g.originalError instanceof CallingCommunicationError)return this._code=g.originalError.code,this._subCode=g.originalError.subCode,this._resultCategories=g.originalError.resultCategories,this.message=g.originalError.message,this.stack=g.originalError.stack,void(this[$]=g.originalError[$]);g.defaultErrorMessageArgs?this.message=g.defaultError.message.replace(/{(\d+)}/g,(function(f,S){return g.defaultErrorMessageArgs&&void 0!==g.defaultErrorMessageArgs[S]?g.defaultErrorMessageArgs[S]:f})):this.message=g.defaultError.message,this._code=g.defaultError.code,this._subCode=g.defaultError.subCode,this._resultCategories=g.defaultError.resultCategories,g.originalError instanceof Error&&(this.stack=g.originalError.stack,this[$]=g.originalError.message)}get code(){return this._code}get subCode(){return this._subCode}get resultCategories(){return this._resultCategories}}j=$;const G=Symbol("loggerKeySymbol");var q,W,z;function syncOperation(g){return operationDecoratorFactory(g||"",!1)}function asyncOperation(g){return operationDecoratorFactory(g||"",!0)}(q=g.CallAgentKind||(g.CallAgentKind={})).CallAgent="CallAgent",q.TeamsCallAgent="TeamsCallAgent",(W=g.CallKind||(g.CallKind={})).Call="Call",W.TeamsCall="TeamsCall",(z=g.IncomingCallKind||(g.IncomingCallKind={})).IncomingCall="IncomingCall",z.TeamsIncomingCall="TeamsIncomingCall";const validateEmergencyCallOperation=f=>(S,v,C)=>{const _=C.value;return C.value=function(...S){if(this.kind===g.CallKind.TeamsCall&&this.isEmergencyCallInProgress())throw new CallingCommunicationError({defaultError:D.CALL.OPERATION_NOT_ALLOWED_DURING_EMERGENCY_CALL,defaultErrorMessageArgs:[f]});return _.apply(this,S)},C},operationDecoratorFactory=(g,f)=>f?(f,S,v)=>{const C=v.value;return v.value=async function(...f){let S;const v=+new Date;tryToLogAcsMessage(this,g,"started");try{S=await C.apply(this,f),tryToLogAcsMessage(this,g,"succeeded",v)}catch(f){const S=new CallingCommunicationError({defaultError:D.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[g],originalError:f});throw tryToLogAcsError(this,g,f,v),S}return S},v}:(f,S,v)=>{const C=v.value;return v.value=function(...f){let S;const v=+new Date;tryToLogAcsMessage(this,g,"started");try{S=C.apply(this,f),tryToLogAcsMessage(this,g,"succeeded",v)}catch(f){const S=new CallingCommunicationError({defaultError:D.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[g],originalError:f});throw tryToLogAcsError(this,g,f,v),S}return S},v};function tryToLogAcsMessage(g,f,S,v){const C=getAcsLogger(g);if(C){const g=v?`in ${(+new Date-v)/1e3}s`:"";C.info(`op:${f}, ${S} ${g}`)}}function tryToLogAcsError(g,f,S,v){const C=getAcsLogger(g);try{if(C){const g=v?`in ${(+new Date-v)/1e3}s`:"";C.error(`op:${f} failed, message=${S.message}, code=${S.code}${S.subCode?`, subCode=${S.subCode}`:""} ${g}`),S&&C.error(`op:${f} failed, message=${S.message}, code=${S.code}, subCode=${S.subCode}, resultCategories=${S.resultCategories}, time elapsed=${g}`)}}catch(S){}}function getAcsLogger(g){try{const f=Reflect.getMetadata(G,g);if(f)return g[f]}catch(g){}}var K="function",J="object",Y="undefined",Q="prototype",X=Object,Z=X[Q];
/*! https://github.com/nevware21/ts-utils v0.11.3 */
function _pureAssign(g,f){return g||f}function _pureRef(g,f){return g[f]}var ee,te=void 0,ie=null,ne="",re="function",se="object",ae="prototype",oe="__proto__",le="undefined",ce="constructor",de="Symbol",he="_polyfill",ue="length",ge="name",pe="call",me="toString",fe=_pureAssign(Object),Se=_pureRef(fe,ae),ve=_pureAssign(String),Ce=_pureRef(ve,ae),ye=_pureAssign(Math),Ee=_pureAssign(Array),_e=_pureRef(Ee,ae),Te=_pureRef(_e,"slice");function safe(g,f){try{return{v:g.apply(this,f)}}catch(g){return{e:g}}}function safeGet(g,f){var S=safe(g);return S.e?f:S.v}function _createIs(g){return function(f){return typeof f===g}}function _createObjIs(g){var f="[object "+g+"]";return function(g){return!(!g||objToString(g)!==f)}}function objToString(g){return Se[me].call(g)}function isUndefined(g){return typeof g===le||g===le}function isNullOrUndefined(g){return g===ie||isUndefined(g)}function isStrictNullOrUndefined(g){return g===ie||!isDefined(g)}function isDefined(g){return!!g||g!==te}function isPrimitiveType(g){return!ee&&(ee=["string","number","boolean",le,"symbol","bigint"]),g!==se&&-1!==ee.indexOf(g)}var Ie=_createIs("string"),be=_createIs(re);function isObject(g){return!(!g&&isNullOrUndefined(g))&&(!!g&&typeof g===se)}var Ae=_pureRef(Ee,"isArray"),Pe=_createObjIs("Date"),Re=_createIs("number"),Me=_createIs("boolean"),we=_createObjIs("Error");function isPromiseLike(g){return!!(g&&g.then&&be(g.then))}function isTruthy(g){return!(!g||safeGet((function(){return!(g&&0+g)}),!g))}var Oe=_pureRef(fe,"getOwnPropertyDescriptor");function objHasOwnProperty(g,f){return!!g&&Se.hasOwnProperty[pe](g,f)}var De=_pureAssign(_pureRef(fe,"hasOwn"),polyObjHasOwn);function polyObjHasOwn(g,f){return objHasOwnProperty(g,f)||!!Oe(g,f)}function objForEachKey(g,f,S){if(g&&isObject(g))for(var v in g)if(De(g,v)&&-1===f[pe](S||g,v,g[v]))break}var Ne={e:"enumerable",c:"configurable",v:"value",w:"writable",g:"get",s:"set"};function _createProp(g){var f={};if(f[Ne.c]=!0,f[Ne.e]=!0,g.l){f.get=function(){return g.l.v};var S=Oe(g.l,"v");S&&S.set&&(f.set=function(f){g.l.v=f})}return objForEachKey(g,(function(g,S){f[Ne[g]]=isUndefined(S)?f[Ne[g]]:S})),f}var ke=_pureRef(fe,"defineProperty"),Le=_pureRef(fe,"defineProperties");function objDefine(g,f,S){return ke(g,f,_createProp(S))}function objDefineProps(g,f){var S={};return objForEachKey(f,(function(g,f){S[g]=_createProp(f)})),Le(g,S)}function _createKeyValueMap(g,f,S,v,C){var _={};return objForEachKey(g,(function(g,v){_assignMapValue(_,g,f?v:g,C),_assignMapValue(_,v,S?v:g,C)})),v?v(_):_}function _assignMapValue(g,f,S,v){ke(g,f,{value:S,enumerable:!0,writable:!!v})}var Fe=_pureAssign(ve),xe="[object Error]";function dumpObj(g,f){var S=ne,v=Se[me][pe](g);v===xe&&(g={stack:Fe(g.stack),message:Fe(g.message),name:Fe(g.name)});try{S=(S=JSON.stringify(g,ie,f?"number"==typeof f?f:4:te))&&S.replace(/"(\w+)"\s*:\s{0,1}/g,"$1: ")||Fe(g)}catch(g){S=" - "+dumpObj(g,f)}return v+": "+S}function throwError(g){throw new Error(g)}function throwTypeError(g){throw new TypeError(g)}var Ue=_pureRef(fe,"freeze");function _doNothing(g){return g}function _getProto(g){return g[oe]||ie}var Ve=_pureRef(fe,"assign"),Be=_pureRef(fe,"keys");function objDeepFreeze(g){return Ue&&objForEachKey(g,(function(g,f){(Ae(f)||isObject(f))&&objDeepFreeze(f)})),He(g)}var He=_pureAssign(Ue,_doNothing),$e=_pureAssign(_pureRef(fe,"getPrototypeOf"),_getProto);function createEnum(g){return _createKeyValueMap(g,1,0,He)}function createEnumKeyMap(g){return _createKeyValueMap(g,0,0,He)}function createSimpleMap(g){var f={};return objForEachKey(g,(function(g,S){_assignMapValue(f,g,S[1]),_assignMapValue(f,S[0],S[1])})),He(f)}function createTypeMap(g){return createSimpleMap(g)}var je,Ge=createEnumKeyMap({asyncIterator:0,hasInstance:1,isConcatSpreadable:2,iterator:3,match:4,matchAll:5,replace:6,search:7,species:8,split:9,toPrimitive:10,toStringTag:11,unscopables:12}),qe="__tsUtils$gblCfg";function _getGlobalValue(){var g;return typeof globalThis!==le&&(g=globalThis),g||typeof self===le||(g=self),g||typeof window===le||(g=window),g||typeof global===le||(g=global),g}function _getGlobalConfig(){if(!je){var g=safe(_getGlobalValue).v||{};je=g[qe]=g[qe]||{}}return je}var We=_unwrapFunctionWithPoly;function _unwrapFunctionWithPoly(g,f,S){var v=f&&f[g];return function(f){var C=f&&f[g]||v;if(C||S){var _=arguments;return(C||S).apply(f,C?Te[pe](_,1):_)}throwTypeError('"'+Fe(g)+'" not defined for '+dumpObj(f))}}function _unwrapProp(g){return function(f){return f[g]}}var ze=_pureRef(ye,"max"),Ke=We("slice",Ce),Je=We("substring",Ce),Ye=_unwrapFunctionWithPoly("substr",Ce,polyStrSubstr);function polyStrSubstr(g,f,S){return isNullOrUndefined(g)&&throwTypeError("Invalid "+dumpObj(g)),S<0?ne:((f=f||0)<0&&(f=ze(f+g[ue],0)),isUndefined(S)?Ke(g,f):Ke(g,f,f+S))}function strLeft(g,f){return Je(g,0,f)}var Qe,Xe,Ze,et="_urid";function _globalSymbolRegistry(){if(!Qe){var g=_getGlobalConfig();Qe=g.gblSym=g.gblSym||{k:{},s:{}}}return Qe}function polyNewSymbol(g){var f={description:Fe(g),toString:function(){return de+"("+g+")"}};return f[he]=!0,f}function polySymbolFor(g){var f=_globalSymbolRegistry();if(!De(f.k,g)){var S=polyNewSymbol(g),v=Be(f.s).length;S[et]=function(){return v+"_"+S[me]()},f.k[g]=S,f.s[S[et]()]=Fe(g)}return f.k[g]}function polyGetKnownSymbol(g){var f;!Xe&&(Xe={});var S=Ge[g];return S&&(f=Xe[S]=Xe[S]||polyNewSymbol(de+"."+S)),f}function _initTestHooks(){Ze=_getGlobalConfig()}function getLazy(g){var f={};return!Ze&&_initTestHooks(),f.b=Ze.lzy,ke(f,"v",{configurable:!0,get:function(){var S=g();return Ze.lzy||ke(f,"v",{value:S}),f.b=Ze.lzy,S}}),f}function createCachedValue(g){return ke({toJSON:function(){return g}},"v",{value:g})}var tt,it="window";function _getGlobalInstFn(g,f){var S;return function(){return!Ze&&_initTestHooks(),(!S||Ze.lzy)&&(S=createCachedValue(safe(g,f).v)),S.v}}function getGlobal(g){return!Ze&&_initTestHooks(),(!tt||!1===g||Ze.lzy)&&(tt=createCachedValue(safe(_getGlobalValue).v||ie)),tt.v}function getInst(g,f){var S=tt&&!1!==f?tt.v:getGlobal(f);return S&&S[g]?S[g]:g===it?rt():ie}function hasDocument(){return!!nt()}var nt=_getGlobalInstFn(getInst,["document"]);function hasWindow(){return!!rt()}var rt=_getGlobalInstFn(getInst,[it]);function hasNavigator(){return!!lt()}var st,at,ot,lt=_getGlobalInstFn(getInst,["navigator"]),ct=_getGlobalInstFn((function(){return!!safe((function(){return process&&(process.versions||{}).node})).v}));function _initSymbol(){return st=createCachedValue(safe(getInst,[de]).v)}function _getSymbolKey(g){var f=(Ze.lzy?0:st)||_initSymbol();return f.v?f.v[g]:te}function hasSymbol(){return!!getSymbol()}function getSymbol(){return!Ze&&_initTestHooks(),((Ze.lzy?0:st)||_initSymbol()).v}function getKnownSymbol(g,f){var S=Ge[g];!Ze&&_initTestHooks();var v=(Ze.lzy?0:st)||_initSymbol();return v.v?v.v[S||g]:f?te:polyGetKnownSymbol(g)}function newSymbol(g,f){!Ze&&_initTestHooks();var S=(Ze.lzy?0:st)||_initSymbol();return S.v?S.v(g):f?ie:polyNewSymbol(g)}function symbolFor(g){return!Ze&&_initTestHooks(),((at=(Ze.lzy?0:at)||createCachedValue(safe(_getSymbolKey,["for"]).v)).v||polySymbolFor)(g)}function isIterator(g){return!!g&&be(g.next)}function isIterable(g){return!isStrictNullOrUndefined(g)&&be(g[getKnownSymbol(3)])}function iterForOf(g,f,S){if(g&&(isIterator(g)||(!ot&&(ot=createCachedValue(getKnownSymbol(3))),g=g[ot.v]?g[ot.v]():null),isIterator(g))){var v=te,C=te;try{for(var _=0;!(C=g.next()).done&&-1!==f[pe](S||g,C.value,_,g);)_++}catch(f){v={e:f},g.throw&&(C=ie,g.throw(v))}finally{try{C&&!C.done&&g.return&&g.return(C)}finally{if(v)throw v.e}}}}function fnApply(g,f,S){return g.apply(f,S)}function arrAppend(g,f){return!isUndefined(f)&&g&&(Ae(f)?fnApply(g.push,g,f):isIterator(f)||isIterable(f)?iterForOf(f,(function(f){g.push(f)})):g.push(f)),g}function arrForEach(g,f,S){if(g)for(var v=g[ue]>>>0,C=0;C<v&&(!(C in g)||-1!==f[pe](S||g,g[C],C,g));C++);}var dt=We("indexOf",_e);function arrSlice(g,f,S){return(g&&g.slice||Te).apply(g,Te[pe](arguments,1))}var ht,ut=_pureAssign(_pureRef(fe,"create"),polyObjCreate);function polyObjCreate(g){if(!g)return{};var f=typeof g;function tempFunc(){}return f!==se&&f!==re&&throwTypeError("Prototype must be an Object or function: "+dumpObj(g)),tempFunc[ae]=g,new tempFunc}function objSetPrototypeOf(g,f){var S=fe.setPrototypeOf||function(g,f){var S;!ht&&(ht=createCachedValue(((S={})[oe]=[],S instanceof Array))),ht.v?g[oe]=f:objForEachKey(f,(function(f,S){return g[f]=S}))};return S(g,f)}function _createCustomError(g,f,S){function __(){this[ce]=f,safe(objDefine,[this,ge,{v:g,c:!0,e:!1}])}return safe(objDefine,[f,ge,{v:g,c:!0,e:!1}]),(f=objSetPrototypeOf(f,S))[ae]=S===ie?ut(S):(__[ae]=S[ae],new __),f}function _setName(g,f){f&&(g[ge]=f)}function createCustomError(g,f,S){var v=S||Error,C=v[ae][ge],_=Error.captureStackTrace;return _createCustomError(g,(function(){var S=this,T=arguments;try{safe(_setName,[v,g]);var I=fnApply(v,S,Te[pe](T))||S;if(I!==S){var b=$e(S);b!==$e(I)&&objSetPrototypeOf(I,b)}return _&&_(I,S[ce]),f&&f(I,T),I}finally{safe(_setName,[v,C])}}),v)}function utcNow(){return(Date.now||polyUtcNow)()}function polyUtcNow(){return(new Date).getTime()}function _createTrimFn(g){return function _doTrim(f){return isNullOrUndefined(f)&&throwTypeError("strTrim called ["+dumpObj(f)+"]"),f&&f.replace&&(f=f.replace(g,ne)),f}}var gt,pt,mt,ft=_unwrapFunctionWithPoly("trim",Ce,_createTrimFn(/^\s+|(?=\s)\s+$/g));function isPlainObject(g){if(!g||typeof g!==se)return!1;mt||(mt=!hasWindow()||rt());var f=!1;if(g!==mt){pt||(gt=Function[ae][me],pt=gt[pe](fe));try{var S=$e(g);(f=!S)||(objHasOwnProperty(S,ce)&&(S=S[ce]),f=S&&typeof S===re&&gt[pe](S)===pt)}catch(g){}}return f}function _defaultDeepCopyHandler(g){return g.value&&plainObjDeepCopyHandler(g),!0}var St=[arrayDeepCopyHandler,plainObjDeepCopyHandler,functionDeepCopyHandler,dateDeepCopyHandler];function _getSetVisited(g,f,S,v){var C;return arrForEach(g,(function(g){if(g.k===f)return C=g,-1})),C||(C={k:f,v:f},g.push(C),v(C)),C.v}function _deepCopy(g,f,S,v){var C=S.handler,_=S.path?v?S.path.concat(v):S.path:[],T={handler:S.handler,src:S.src,path:_},I=typeof f,b=!1,A=!1;f&&I===se?b=isPlainObject(f):A=f===ie||isPrimitiveType(I);var P={type:I,isPrim:A,isPlain:b,value:f,result:f,path:_,origin:S.src,copy:function(f,v){return _deepCopy(g,f,v?T:S,v)},copyTo:function(f,S){return _copyProps(g,f,S,T)}};return P.isPrim?C&&C[pe](S,P)?P.result:f:_getSetVisited(g,f,_,(function(g){objDefine(P,"result",{g:function(){return g.v},s:function(f){g.v=f}});for(var f=0,v=C;!(v||(f<St.length?St[f++]:_defaultDeepCopyHandler))[pe](S,P);)v=ie}))}function _copyProps(g,f,S,v){if(!isNullOrUndefined(S))for(var C in S)f[C]=_deepCopy(g,S[C],v,C);return f}function objCopyProps(g,f,S){return _copyProps([],g,f,{handler:S,src:f,path:[]})}function objDeepCopy(g,f){return _deepCopy([],g,{handler:f,src:g})}function arrayDeepCopyHandler(g){var f=g.value;if(Ae(f)){var S=g.result=[];return S.length=f.length,g.copyTo(S,f),!0}return!1}function dateDeepCopyHandler(g){var f=g.value;return!!Pe(f)&&(g.result=new Date(f.getTime()),!0)}function functionDeepCopyHandler(g){return g.type===re}function plainObjDeepCopyHandler(g){var f=g.value;if(f&&g.isPlain){var S=g.result={};return g.copyTo(S,f),!0}return!1}function _doExtend(g,f){return arrForEach(f,(function(f){objCopyProps(g,f)})),g}function deepExtend(g,f,S,v,C,_,T){return _doExtend(objDeepCopy(g)||{},Te[pe](arguments))}var vt,Ct=_unwrapProp(ue);function getPerformance(){return!Ze&&_initTestHooks(),(!vt||Ze.lzy)&&(vt=createCachedValue(safe(getInst,["performance"]).v)),vt.v}function perfNow(){var g=getPerformance();return g&&g.now?g.now():utcNow()}var yt=_unwrapFunctionWithPoly("endsWith",Ce,polyStrEndsWith);function polyStrEndsWith(g,f,S){Ie(g)||throwTypeError("'"+dumpObj(g)+"' is not a string");var v=Ie(f)?f:Fe(f),C=!isUndefined(S)&&S<g[ue]?S:g[ue];return Je(g,C-v[ue],C)===v}var Et=We("indexOf",Ce),_t=_unwrapFunctionWithPoly("startsWith",Ce,polyStrStartsWith);function polyStrStartsWith(g,f,S){Ie(g)||throwTypeError("'"+dumpObj(g)+"' is not a string");var v=Ie(f)?f:Fe(f),C=S>0?S:0;return Je(g,C,C+v[ue])===v}var Tt="ref",It="unref",bt="hasRef",At="enabled";function _createTimerHandler(g,f,S){var v,C=!0,_=g?f(ie):ie;function _unref(){return C=!1,_&&_[It]&&_[It](),v}function _cancel(){_&&S(_),_=ie}function _refresh(){return _=f(_),C||_unref(),v}function _setEnabled(g){!g&&_&&_cancel(),g&&!_&&_refresh()}return(v={cancel:_cancel,refresh:_refresh})[bt]=function(){return _&&_[bt]?_[bt]():C},v[Tt]=function(){return C=!0,_&&_[Tt]&&_[Tt](),v},v[It]=_unref,{h:v=ke(v,At,{get:function(){return!!_},set:_setEnabled}),dn:function(){_=ie}}}function _createTimeoutWith(g,f,S){var v=Ae(f),C=v?f.length:0,_=(C>0?f[0]:v?te:f)||setTimeout,T=(C>1?f[1]:te)||clearTimeout,I=S[0];S[0]=function(){b.dn(),fnApply(I,te,Te[pe](arguments))};var b=_createTimerHandler(g,(function(g){if(g){if(g.refresh)return g.refresh(),g;fnApply(T,te,[g])}return fnApply(_,te,S)}),(function(g){fnApply(T,te,[g])}));return b.h}function scheduleTimeout(g,f){return _createTimeoutWith(!0,te,Te[pe](arguments))}function scheduleTimeoutWith(g,f,S){return _createTimeoutWith(!0,g,Te[pe](arguments,1))}function createTimeout(g,f){return _createTimeoutWith(!1,te,Te[pe](arguments))}(getGlobal()||{}).Symbol,(getGlobal()||{}).Reflect;var Pt,Rt="hasOwnProperty",extendStaticsFn=function(g,f){return extendStaticsFn=X.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f[Rt](S)&&(g[S]=f[S])},extendStaticsFn(g,f)};function __extendsFn(g,f){function __(){this.constructor=g}typeof f!==K&&null!==f&&throwTypeError("Class extends value "+String(f)+" is not a constructor or null"),extendStaticsFn(g,f),g[Q]=null===f?ut(f):(__[Q]=f[Q],new __)}function __spreadArrayFn(g,f){for(var S=0,v=f.length,C=g.length;S<v;S++,C++)g[C]=f[S];return g}var Mt="constructor",wt="prototype",Ot="function",Dt="_dynInstFuncs",Nt="_isDynProxy",kt="_dynClass",Lt="_dynCls$",Ft="_dynInstChk",xt=Ft,Ut="_dfOpts",Vt="_unknown_",Bt="__proto__",Ht="_dyn"+Bt,$t="__dynProto$Gbl",jt="_dynInstProto",Gt="useBaseInst",qt="setInstFuncs",Wt=Object,zt=Wt.getPrototypeOf,Kt=Wt.getOwnPropertyNames,Jt=getGlobal(),Yt=Jt[$t]||(Jt[$t]={o:(Pt={},Pt[qt]=!0,Pt[Gt]=!0,Pt),n:1e3});function _isObjectOrArrayPrototype(g){return g&&(g===Wt[wt]||g===Array[wt])}function _isObjectArrayOrFunctionPrototype(g){return _isObjectOrArrayPrototype(g)||g===Function[wt]}function _getObjProto(g){var f;if(g){if(zt)return zt(g);var S=g[Bt]||g[wt]||(g[Mt]?g[Mt][wt]:null);f=g[Ht]||S,objHasOwnProperty(g,Ht)||(delete g[jt],f=g[Ht]=g[jt]||g[Ht],g[jt]=S)}return f}function _forEachProp(g,f){var S=[];if(Kt)S=Kt(g);else for(var v in g)"string"==typeof v&&objHasOwnProperty(g,v)&&S.push(v);if(S&&S.length>0)for(var C=0;C<S.length;C++)f(S[C])}function _isDynamicCandidate(g,f,S){return f!==Mt&&typeof g[f]===Ot&&(S||objHasOwnProperty(g,f))&&f!==Bt&&f!==wt}function _throwTypeError(g){throwTypeError("DynamicProto: "+g)}function _getInstanceFuncs(g){var f=ut(null);return _forEachProp(g,(function(S){!f[S]&&_isDynamicCandidate(g,S,!1)&&(f[S]=g[S])})),f}function _hasVisited(g,f){for(var S=g.length-1;S>=0;S--)if(g[S]===f)return!0;return!1}function _getBaseFuncs(g,f,S,v){function _instFuncProxy(g,f,S){var C=f[S];if(C[Nt]&&v){var _=g[Dt]||{};!1!==_[xt]&&(C=(_[f[kt]]||{})[S]||C)}return function(){return C.apply(g,arguments)}}var C=ut(null);_forEachProp(S,(function(g){C[g]=_instFuncProxy(f,S,g)}));for(var _=_getObjProto(g),T=[];_&&!_isObjectArrayOrFunctionPrototype(_)&&!_hasVisited(T,_);)_forEachProp(_,(function(g){!C[g]&&_isDynamicCandidate(_,g,!zt)&&(C[g]=_instFuncProxy(f,_,g))})),T.push(_),_=_getObjProto(_);return C}function _getInstFunc(g,f,S,v){var C=null;if(g&&objHasOwnProperty(S,kt)){var _=g[Dt]||ut(null);if((C=(_[S[kt]]||ut(null))[f])||_throwTypeError("Missing ["+f+"] "+Ot),!C[Ft]&&!1!==_[xt]){for(var T=!objHasOwnProperty(g,f),I=_getObjProto(g),b=[];T&&I&&!_isObjectArrayOrFunctionPrototype(I)&&!_hasVisited(b,I);){var A=I[f];if(A){T=A===v;break}b.push(I),I=_getObjProto(I)}try{T&&(g[f]=C),C[Ft]=1}catch(g){_[xt]=!1}}}return C}function _getProtoFunc(g,f,S){var v=f[g];return v===S&&(v=_getObjProto(f)[g]),typeof v!==Ot&&_throwTypeError("["+g+"] is not a "+Ot),v}function _populatePrototype(g,f,S,v,C){function _createDynamicPrototype(g,f){var dynProtoProxy=function(){return(_getInstFunc(this,f,g,dynProtoProxy)||_getProtoFunc(f,g,dynProtoProxy)).apply(this,arguments)};return dynProtoProxy[Nt]=1,dynProtoProxy}if(!_isObjectOrArrayPrototype(g)){var _=S[Dt]=S[Dt]||ut(null);if(!_isObjectOrArrayPrototype(_)){var T=_[f]=_[f]||ut(null);!1!==_[xt]&&(_[xt]=!!C),_isObjectOrArrayPrototype(T)||_forEachProp(S,(function(f){_isDynamicCandidate(S,f,!1)&&S[f]!==v[f]&&(T[f]=S[f],delete S[f],(!objHasOwnProperty(g,f)||g[f]&&!g[f][Nt])&&(g[f]=_createDynamicPrototype(g,f)))}))}}}function _checkPrototype(g,f){if(zt){for(var S=[],v=_getObjProto(f);v&&!_isObjectArrayOrFunctionPrototype(v)&&!_hasVisited(S,v);){if(v===g)return!0;S.push(v),v=_getObjProto(v)}return!1}return!0}function _getObjName(g,f){return objHasOwnProperty(g,wt)?g.name||f||Vt:((g||{})[Mt]||{}).name||f||Vt}function dynamicProto(g,f,S,v){objHasOwnProperty(g,wt)||_throwTypeError("theClass is an invalid class definition.");var C=g[wt];_checkPrototype(C,f)||_throwTypeError("["+_getObjName(g)+"] not in hierarchy of ["+_getObjName(f)+"]");var _=null;objHasOwnProperty(C,kt)?_=C[kt]:(_=Lt+_getObjName(g,"_")+"$"+Yt.n,Yt.n++,C[kt]=_);var T=dynamicProto[Ut],I=!!T[Gt];I&&v&&void 0!==v[Gt]&&(I=!!v[Gt]);var b=_getInstanceFuncs(f);S(f,_getBaseFuncs(C,f,b,I));var A=!!zt&&!!T[qt];A&&v&&(A=!!v[qt]),_populatePrototype(C,_,f,b,!1!==A)}dynamicProto[Ut]=Yt.o;var Qt,Xt=createEnum,Zt=Xt({Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5}),ei=(Xt({Unknown:0,NonRetryableStatus:1,CleanStorage:2,MaxInStorageTimeExceeded:3}),Xt({NONE:0,PENDING:3,INACTIVE:1,ACTIVE:2})),ti="toLowerCase",ii="blkVal",ni="length",ri="rdOnly",si="notify",ai="warnToConsole",oi="throwInternal",li="setDf",ci="watch",di="logger",hi="apply",ui="push",gi="splice",pi="hdlr",mi="cancel",fi="initialize",Si="identifier",vi="removeNotificationListener",Ci="addNotificationListener",yi="isInitialized",Ei="instrumentationKey",_i="INACTIVE",Ti="value",Ii="getNotifyMgr",bi="getPlugin",Ai="name",Pi="iKey",Ri="time",Mi="processNext",wi="getProcessTelContext",Oi="pollInternalLogs",Di="enabled",Ni="stopPollingInternalLogs",ki="unload",Li="onComplete",Fi="version",xi="loggingLevelConsole",Ui="createNew",Vi="teardown",Bi="messageId",Hi="message",$i="isAsync",ji="diagLog",Gi="_doTeardown",qi="update",Wi="getNext",zi="setNextPlugin",Ki="protocol",Ji="userAgent",Yi="split",Qi="nodeType",Xi="replace",Zi="logInternalMessage",en="type",tn="handler",nn="status",rn="getResponseHeader",sn="getAllResponseHeaders",an="isChildEvt",on="data",ln="getCtx",cn="setCtx",dn="complete",hn="urlString",un="sendPOST",gn="headers",pn="timeout",mn="setRequestHeader",fn="traceId",Sn="spanId",vn="traceFlags";function throwAggregationError(g,f){Qt||(Qt=createCustomError("AggregationError",(function(g,f){f[ni]>1&&(g.errors=f[1])})));var S=g||"One or more errors occurred.";throw arrForEach(f,(function(g,f){S+="\n".concat(f," > ").concat(dumpObj(g))})),new Qt(S,f||[])}
/*!
	 * NevWare21 Solutions LLC - ts-async, 0.5.2
	 * https://github.com/nevware21/ts-async
	 * Copyright (c) NevWare21 Solutions LLC and contributors. All rights reserved.
	 * Licensed under the MIT license.
	 */var Cn="Promise",yn="rejected";function doAwaitResponse(g,f){return doAwait(g,(function(g){return f?f({status:"fulfilled",rejected:!1,value:g}):g}),(function(g){return f?f({status:yn,rejected:!0,reason:g}):g}))}function doAwait(g,f,S,v){var C=g;try{if(isPromiseLike(g))(f||S)&&(C=g.then(f,S));else try{f&&(C=f(g))}catch(g){if(!S)throw g;C=S(g)}}finally{v&&doFinally(C,v)}return C}function doFinally(g,f){var S=g;return f&&(isPromiseLike(g)?S=g.finally?g.finally(f):g.then((function(g){return f(),g}),(function(g){throw f(),g})):f()),S}var En,_n=["pending","resolving","resolved",yn],Tn="dispatchEvent";function _hasInitEventFn(g){var f;return g&&g.createEvent&&(f=g.createEvent("Event")),!!f&&f.initEvent}function emitEvent(g,f,S,v){var C=nt();!En&&(En=createCachedValue(!!safe(_hasInitEventFn,[C]).v));var _=En.v?C.createEvent("Event"):v?new Event(f):{};if(S&&S(_),En.v&&_.initEvent(f,!1,!0),_&&g[Tn])g[Tn](_);else{var T=g["on"+f];if(T)T(_);else{var I=getInst("console");I&&(I.error||I.log)(f,dumpObj(_))}}}var In,bn="unhandledRejection",An=bn.toLowerCase(),Pn=[],Rn=0,Mn=10;function dumpFnObj(g){return be(g)?g.toString():dumpObj(g)}function _createPromise(g,f,S){var v,C,_=arrSlice(arguments,3),T=0,I=!1,b=[],A=Rn++,P=!1,R=null;function _then(f,S){try{return Pn.push(A),P=!0,R&&R.cancel(),R=null,g((function(g,C){b.push((function(){try{var _=2===T?f:S,I=isUndefined(_)?v:be(_)?_(v):_;isPromiseLike(I)?I.then(g,C):_?g(I):3===T?C(I):g(I)}catch(g){C(g)}})),I&&_processQueue()}),_)}finally{Pn.pop()}}function _catch(g){return _then(void 0,g)}function _finally(g){var f=g,S=g;return be(g)&&(f=function(f){return g&&g(),f},S=function(f){throw g&&g(),f}),_then(f,S)}function _strState(){return _n[T]}function _processQueue(){if(b.length>0){var g=b.slice();b=[],P=!0,R&&R.cancel(),R=null,f(g)}}function _createSettleIfFn(g,f){return function(S){if(T===f){if(2===g&&isPromiseLike(S))return T=1,void S.then(_createSettleIfFn(2,1),_createSettleIfFn(3,1));T=g,I=!0,v=S,_processQueue(),P||3!==g||R||(R=scheduleTimeout(_notifyUnhandledRejection,Mn))}}}function _notifyUnhandledRejection(){if(!P)if(P=!0,ct())process.emit(bn,v,C);else{var g=rt()||getGlobal();!In&&(In=createCachedValue(safe(getInst,[Cn+"RejectionEvent"]).v)),emitEvent(g,An,(function(g){return objDefine(g,"promise",{g:function(){return C}}),g.reason=v,g}),!!In.v)}}function _toString(){return"IPromise "+_strState()+(I?" - "+dumpFnObj(v):"")}return ke(C={then:_then,catch:_catch,finally:_finally},"state",{get:_strState}),hasSymbol()&&(C[getKnownSymbol(11)]="IPromise"),C.toString=_toString,function _initialize(){be(S)||throwTypeError(Cn+": executor is not a function - "+dumpFnObj(S));var g=_createSettleIfFn(3,0);try{S.call(C,_createSettleIfFn(2,0),g)}catch(f){g(f)}}(),C}function _createAllPromise(g){return function(f){var S=arrSlice(arguments,1);return g((function(g,S){try{var v=[],C=1;iterForOf(f,(function(f,_){f&&(C++,doAwait(f,(function(f){v[_]=f,0==--C&&g(v)}),S))})),0===--C&&g(v)}catch(g){S(g)}}),S)}}function _createResolvedPromise(g){return function(f){var S=arrSlice(arguments,1);return isPromiseLike(f)?f:g((function(g){g(f)}),S)}}function _createRejectedPromise(g){return function(f){var S=arrSlice(arguments,1);return g((function(g,S){S(f)}),S)}}function _createAllSettledPromise(g){return createCachedValue((function(f){var S=arrSlice(arguments,1);return g((function(g,S){var v=[],C=1;function processItem(f,S){C++,doAwaitResponse(f,(function(f){f.rejected?v[S]={status:yn,reason:f.reason}:v[S]={status:"fulfilled",value:f.value},0==--C&&g(v)}))}try{Ae(f)?arrForEach(f,processItem):isIterable(f)?iterForOf(f,processItem):throwTypeError("Input is not an iterable"),0===--C&&g(v)}catch(g){S(g)}}),S)}))}function syncItemProcessor(g){arrForEach(g,(function(g){try{g()}catch(g){}}))}function timeoutItemProcessor(g){var f=Re(g)?g:0;return function(g){scheduleTimeout((function(){syncItemProcessor(g)}),f)}}function createAsyncPromise(g,f){return _createPromise(createAsyncPromise,timeoutItemProcessor(f),g,f)}var wn,On,Dn,Nn=_createAllPromise(createAsyncPromise),kn=_createResolvedPromise(createAsyncPromise),Ln=_createRejectedPromise(createAsyncPromise);function createNativePromise(g,f){!wn&&(wn=createCachedValue(safe(getInst,[Cn]).v||null));var S=wn.v;if(!S)return createAsyncPromise(g);be(g)||throwTypeError(Cn+": executor is not a function - "+dumpObj(g));var v=0;function _strState(){return _n[v]}var C=new S((function(f,S){function _resolve(g){v=2,f(g)}function _reject(g){v=3,S(g)}g(_resolve,_reject)}));return ke(C,"state",{get:_strState}),C}function createPromise(g,f){return!On&&(On=createCachedValue(createNativePromise)),On.v.call(this,g,f)}var Fn=_createAllPromise(createPromise);function createAllSettledPromise(g,f){return!Dn&&(Dn=_createAllSettledPromise(createPromise)),Dn.v(g,f)}var xn,Un,Vn="reject",Bn="Rejected",Hn=0,$n={};function _rejectDone(){}function _createError(g,f,S){!$n[g]&&($n[g]=createCustomError(g));var v=utcNow();return new $n[g]("Task [".concat(f.id,"] ").concat(S||"","- ").concat(f.st?"Running":"Waiting",": ").concat(_calcTime(v,f.st||f.cr)))}function _calcTime(g,f){return(g-f||"0")+" ms"}function _abortStaleTasks(g,f){var S=utcNow()-f;arrForEach(g,(function(g){(g&&!g.rj&&g.st&&g.st<S||!g.st&&g.cr&&g.cr<S)&&g&&g[Vn](g.rj||_createError("Aborted",g,"Stale "))}))}function _removeTask(g,f){var S=dt(g,f);-1!==S&&g.splice(S,1)}function _addDebugState(g,f,S){Un=Un||{toString:function(){return"[[SchedulerState]]"}},ke(g,xn=xn||{toString:function(){return"[[SchedulerName]]"}},{get:f}),ke(g,Un,{get:S})}function createTaskScheduler(g,f){var S,v,C=[],_=[],T=6e5,I=T/10,b=0,A=(f?f+".":"")+Hn++;g=g||createPromise;var _startBlockedTimer=function(){var g=Ct(C)+Ct(_)>0;T>0&&(v||(v=scheduleTimeout((function(){_abortStaleTasks(C,T),_abortStaleTasks(_,T),v&&(v.enabled=Ct(C)+Ct(_)>0)}),I)).unref(),v&&(v.enabled=g))},_queueTask=function(f,v,C){var _,T=A+"."+b++;v&&(T+="-("+v+")");var I=((_={id:T,cr:utcNow(),to:C})[Vn]=function(g){I.rj=g||_createError(Bn,I),I[Vn]=_rejectDone},_);return I.p=S?_waitForPreviousTask(I,S,f):g(_runTask(I,f)),S=I,I.p},_runTask=function(g,f){return g.st=utcNow(),C.push(g),_startBlockedTimer(),function(S,v){var _promiseReject=function(f){g.rj=g.rj||f||_createError(Bn,g),g[Vn]=_rejectDone,_doCleanup(g),S=null,v&&v(f),v=null},C=g.id;if(g.rj)_promiseReject(g.rj);else{g[Vn]=_promiseReject;try{var _=f(C);g.to&&isPromiseLike(_)&&(g.t=scheduleTimeout((function(){_promiseReject(_createError("Timeout",g))}),g.to)),doAwait(_,(function(f){_doCleanup(g);try{S&&S(f)}catch(g){v&&v(g)}v=null,S=null}),_promiseReject)}catch(g){_promiseReject(g)}}}},_waitForPreviousTask=function(f,S,v){return _.push(f),_startBlockedTimer(),g((function(g,C){doAwaitResponse(S.p,(function(){_removeTask(_,f),_runTask(f,v)(g,C)}))}))},_doCleanup=function(g){_removeTask(C,g),g.t&&g.t.cancel(),g.t=null,S&&S===g&&(S=null,Ct(C)+Ct(_)===0&&(v&&v.cancel(),v=null))},P={idle:!0,queue:_queueTask,setStaleTimeout:function(g,f){v&&v.cancel(),v=null,T=g,I=f||g/10,_startBlockedTimer()}};return objDefine(P,"idle",{g:function(){return Ct(C)+Ct(_)===0}}),_addDebugState(P,(function(){return A}),(function(){return{l:S,r:C,w:_}})),P}getKnownSymbol(11);var jn=void 0,Gn="",qn="channels",Wn="core",zn="createPerfMgr",Kn="disabled",Jn="extensionConfig",Yn="extensions",Qn="processTelemetry",Xn="priority",Zn="eventsSent",er="eventsDiscarded",tr="eventsSendRequest",ir="perfEvent",nr="offlineEventsStored",rr="offlineBatchSent",sr="offlineBatchDrop",ar="getPerfMgr",or="domain",lr="path",cr="Not dynamic - ",dr=/-([a-z])/g,hr=/([^\w\d_$])/g,ur=/^(\d+[\w\d_$])/;function isNotNullOrUndefined(g){return!isNullOrUndefined(g)}function normalizeJsName(g){var f=g;return f&&Ie(f)&&(f=(f=(f=f[Xi](dr,(function(g,f){return f.toUpperCase()})))[Xi](hr,"_"))[Xi](ur,(function(g,f){return"_"+f}))),f}function strContains(g,f){return!(!g||!f)&&-1!==Et(g,f)}function toISOString(g){return g&&g.toISOString()||""}function getExceptionName(g){return we(g)?g[Ai]:Gn}function setValue(g,f,S,v,C){var _=S;return g&&((_=g[f])===S||C&&!C(_)||v&&!v(S)||(_=S,g[f]=_)),_}function getSetValue(g,f,S){var v;return g?!(v=g[f])&&isNullOrUndefined(v)&&(v=isUndefined(S)?{}:S,g[f]=v):v=isUndefined(S)?{}:S,v}function _createProxyFunction(g,f){var S=null,v=null;return be(g)?S=g:v=g,function(){var g=arguments;if(S&&(v=S()),v)return v[f][hi](v,g)}}function proxyFunctionAs(g,f,S,v,C){g&&f&&S&&(!1!==C||isUndefined(g[f]))&&(g[f]=_createProxyFunction(S,v))}function proxyFunctions(g,f,S,v){return g&&f&&isObject(g)&&Ae(S)&&arrForEach(S,(function(S){Ie(S)&&proxyFunctionAs(g,S,f,S,v)})),g}function optimizeObject(g){return g&&Ve&&(g=X(Ve({},g))),g}function getResponseText(g){try{return g.responseText}catch(g){}return null}function formatErrorMessageXdr(g,f){return g?"XDomainRequest,Response:"+getResponseText(g)||"":f}function formatErrorMessageXhr(g,f){return g?"XMLHttpRequest,Status:"+g[nn]+",Response:"+getResponseText(g)||g.response||"":f}function prependTransports(g,f){return f&&(Re(f)?g=[f].concat(g):Ae(f)&&(g=f.concat(g))),g}var gr="Microsoft_ApplicationInsights_BypassAjaxInstrumentation",pr="withCredentials",mr="timeout";function openXhr(g,f,S,v,C,_){function _wrapSetXhrProp(g,f,S){try{g[f]=S}catch(g){}}void 0===v&&(v=!1),void 0===C&&(C=!1);var T=new XMLHttpRequest;return v&&_wrapSetXhrProp(T,gr,v),S&&_wrapSetXhrProp(T,pr,S),T.open(g,f,!C),S&&_wrapSetXhrProp(T,pr,S),!C&&_&&_wrapSetXhrProp(T,mr,_),T}function convertAllHeadersToMap(g){var f={};Ie(g)&&arrForEach(ft(g)[Yi](/[\r\n]+/),(function(g){if(g){var S=g.indexOf(": ");if(-1!==S){var v=ft(g.substring(0,S))[ti](),C=ft(g.substring(S+1));f[v]=C}else f[ft(g)]=1}}));return f}function _appendHeader(g,f,S){if(!g[S]&&f&&f[rn]){var v=f[rn](S);v&&(g[S]=ft(v))}return g}var fr="kill-duration",Sr="kill-duration-seconds",vr="time-delta-millis";function _getAllResponseHeaders(g,f){var S={};return g[sn]?S=convertAllHeadersToMap(g[sn]()):f&&(S=_appendHeader(S,g,vr),S=_appendHeader(S,g,fr),S=_appendHeader(S,g,Sr)),S}var Cr="location",yr="console",Er="JSON",_r="crypto",Tr="msCrypto",Ir="ReactNative",br="msie",Ar="trident/",Pr="XMLHttpRequest",Rr=null,Mr=null,wr=!1,Or=null,Dr=null;function _hasProperty(g,f){var S=!1;if(g){try{if(!(S=f in g)){var v=g[Q];v&&(S=f in v)}}catch(g){}if(!S)try{S=!isUndefined((new g)[f])}catch(g){}}return S}function getLocation(g){if(g&&wr){var f=getInst("__mockLocation");if(f)return f}return typeof location===J&&location?location:getInst(Cr)}function getConsole(){return typeof console!==Y?console:getInst(yr)}function hasJSON(){return Boolean(typeof JSON===J&&JSON||null!==getInst(Er))}function getJSON(){return hasJSON()?JSON||getInst(Er):null}function getCrypto(){return getInst(_r)}function getMsCrypto(){return getInst(Tr)}function isReactNative(){var g=lt();return!(!g||!g.product)&&g.product===Ir}function isIE(){var g=lt();if(g&&(g[Ji]!==Mr||null===Rr)){var f=((Mr=g[Ji])||Gn)[ti]();Rr=strContains(f,br)||strContains(f,Ar)}return Rr}function isBeaconsSupported(g){return null!==Dr&&!1!==g||(Dr=hasNavigator()&&Boolean(lt().sendBeacon)),Dr}function isFetchSupported(g){var f=!1;try{f=!!getInst("fetch");var S=getInst("Request");f&&g&&S&&(f=_hasProperty(S,"keepalive"))}catch(g){}return f}function useXDomainRequest(){return null===Or&&(Or=typeof XDomainRequest!==Y)&&isXhrSupported()&&(Or=Or&&!_hasProperty(getInst(Pr),"withCredentials")),Or}function isXhrSupported(){var g=!1;try{g=!!getInst(Pr)}catch(g){}return g}var Nr=4294967296,kr=4294967295,Lr=123456789,Fr=987654321,xr=!1,Ur=Lr,Vr=Fr;function _mwcSeed(g){g<0&&(g>>>=0),Ur=Lr+g&kr,Vr=Fr-g&kr,xr=!0}function _autoSeedMwc(){try{var g=2147483647&utcNow();_mwcSeed((Math.random()*Nr^g)+g)}catch(g){}}function random32(g){var f=0,S=getCrypto()||getMsCrypto();return S&&S.getRandomValues&&(f=S.getRandomValues(new Uint32Array(1))[0]&kr),0===f&&isIE()&&(xr||_autoSeedMwc(),f=mwcRandom32()&kr),0===f&&(f=Math.floor(Nr*Math.random()|0)),g||(f>>>=0),f}function mwcRandom32(g){var f=((Vr=36969*(65535&Vr)+(Vr>>16)&kr)<<16)+(65535&(Ur=18e3*(65535&Ur)+(Ur>>16)&kr))>>>0&kr|0;return g||(f>>>=0),f}function newId(g){void 0===g&&(g=22);for(var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S=random32()>>>0,v=0,C=Gn;C[ni]<g;)v++,C+=f.charAt(63&S),S>>>=6,5===v&&(S=(random32()<<2&4294967295|3&S)>>>0,v=0);return C}var Br="3.3.2",Hr="."+newId(6),$r=0;function _canAcceptData(g){return 1===g[Qi]||9===g[Qi]||!+g[Qi]}function _getCache(g,f){var S=f[g.id];if(!S){S={};try{_canAcceptData(f)&&objDefine(f,g.id,{e:!1,v:S})}catch(g){}}return S}function createUniqueNamespace(g,f){return void 0===f&&(f=!1),normalizeJsName(g+$r+++(f?"."+Br:Gn)+Hr)}function createElmNodeData(g){var f={id:createUniqueNamespace("_aiData-"+(g||Gn)+"."+Br),accept:function(g){return _canAcceptData(g)},get:function(g,S,v,C){var _=g[f.id];return _?_[normalizeJsName(S)]:(C&&((_=_getCache(f,g))[normalizeJsName(S)]=v),v)},kill:function(g,f){if(g&&g[f])try{delete g[f]}catch(g){}}};return f}function _isConfigDefaults(g){return g&&isObject(g)&&(g.isVal||g.fb||De(g,"v")||De(g,"mrg")||De(g,"ref")||g.set)}function _getDefault(g,f,S){var v,C=S.dfVal||isDefined;if(f&&S.fb){var _=S.fb;Ae(_)||(_=[_]);for(var T=0;T<_[ni];T++){var I=_[T],b=f[I];if(C(b)?v=b:g&&(C(b=g.cfg[I])&&(v=b),g.set(g.cfg,Fe(I),b)),C(v))break}}return!C(v)&&C(S.v)&&(v=S.v),v}function _resolveDefaultValue(g,f,S){var v,C=S;(S&&_isConfigDefaults(S)&&(C=_getDefault(g,f,S)),C)&&(_isConfigDefaults(C)&&(C=_resolveDefaultValue(g,f,C)),Ae(C)?(v=[])[ni]=C[ni]:isPlainObject(C)&&(v={}),v&&(objForEachKey(C,(function(S,C){C&&_isConfigDefaults(C)&&(C=_resolveDefaultValue(g,f,C)),v[S]=C})),C=v));return C}function _applyDefaultValue(g,f,S,v){var C,_,T,I,b,A,P,R,M=v;_isConfigDefaults(M)?(C=M.isVal,_=M.set,A=M[ri],P=M[ii],I=M.mrg,!(b=M.ref)&&isUndefined(b)&&(b=!!I),T=_getDefault(g,f,M)):T=v,P&&g[ii](f,S);var w=!0,O=f[S];!O&&isNullOrUndefined(O)||(R=O,w=!1,C&&R!==T&&!C(R)&&(R=T,w=!0),_&&(w=(R=_(R,T,f))===T)),w?R=T?_resolveDefaultValue(g,f,T):T:(isPlainObject(R)||Ae(T))&&I&&T&&(isPlainObject(T)||Ae(T))&&objForEachKey(T,(function(f,S){_applyDefaultValue(g,R,f,S)})),g.set(f,S,R),b&&g.ref(f,S),A&&g[ri](f,S)}var jr=symbolFor("[[ai_dynCfg_1]]"),Gr=symbolFor("[[ai_blkDynCfg_1]]"),qr=symbolFor("[[ai_frcDynCfg_1]]");function _cfgDeepCopy(g){var f;if(g&&(Ae(g)?(f=[])[ni]=g[ni]:isPlainObject(g)&&(f={}),f))return objForEachKey(g,(function(g,S){f[g]=_cfgDeepCopy(S)})),f;return g}function getDynamicConfigHandler(g){if(g){var f=g[jr]||g;if(f.cfg&&(f.cfg===g||f.cfg[jr]===f))return f}return null}function blockDynamicConversion(g){if(g&&(isPlainObject(g)||Ae(g)))try{g[Gr]=!0}catch(g){}return g}function _canMakeDynamic(g,f,S){var v=!1;return S&&!g[f.blkVal]&&((v=S[qr])||S[Gr]||(v=isPlainObject(S)||Ae(S))),v}function throwInvalidAccess(g){throwTypeError("InvalidAccess:"+g)}var Wr=["push","pop","shift","unshift","splice"],_throwDynamicError=function(g,f,S,v){g&&g[oi](3,108,"".concat(S," [").concat(f,"] failed - ")+dumpObj(v))};function _patchArray(g,f,S){Ae(f)&&arrForEach(Wr,(function(v){var C=f[v];f[v]=function(){for(var v=[],_=0;_<arguments.length;_++)v[_]=arguments[_];var T=C[hi](this,v);return _makeDynamicObject(g,f,S,"Patching"),T}}))}function _getOwnPropGetter(g,f){var S=Oe(g,f);return S&&S.get}function _createDynamicProperty(g,f,S,v){var C={n:S,h:[],trk:function(f){f&&f.fn&&(-1===dt(C.h,f)&&C.h[ui](f),g.trk(f,C))},clr:function(g){var f=dt(C.h,g);-1!==f&&C.h[gi](f,1)}},_=!0,T=!1;function _getProperty(){_&&(T=T||_canMakeDynamic(_getProperty,g,v),v&&!v[jr]&&T&&(v=_makeDynamicObject(g,v,S,"Converting")),_=!1);var f=g.act;return f&&C.trk(f),v}function _setProperty(I){if(v!==I){_getProperty[g.ro]&&!g.upd&&throwInvalidAccess("["+S+"] is read-only:"+dumpObj(f)),_&&(T=T||_canMakeDynamic(_getProperty,g,v),_=!1);var b=T&&_getProperty[g.rf];if(T)if(b){objForEachKey(v,(function(g){v[g]=I?I[g]:jn}));try{objForEachKey(I,(function(f,S){_setDynamicProperty(g,v,f,S)})),I=v}catch(f){_throwDynamicError((g.hdlr||{})[di],S,"Assigning",f),T=!1}}else v&&v[jr]&&objForEachKey(v,(function(f){var S=_getOwnPropGetter(v,f);if(S){var C=S[g.prop];C&&C.chng()}}));if(I!==v){var A=I&&_canMakeDynamic(_getProperty,g,I);!b&&A&&(I=_makeDynamicObject(g,I,S,"Converting")),v=I,T=A}g.add(C)}}_getProperty[g.prop]={chng:function(){g.add(C)}},objDefine(f,C.n,{g:_getProperty,s:_setProperty})}function _setDynamicProperty(g,f,S,v){if(f){var C=_getOwnPropGetter(f,S);C&&!!C[g.prop]?f[S]=v:_createDynamicProperty(g,f,S,v)}return f}function _setDynamicPropertyState(g,f,S,v){if(f){var C=_getOwnPropGetter(f,S),_=C&&!!C[g.prop],T=v&&v[0],I=v&&v[1],b=v&&v[2];if(!_){if(b)try{blockDynamicConversion(f)}catch(f){_throwDynamicError((g.hdlr||{})[di],S,"Blocking",f)}try{_setDynamicProperty(g,f,S,f[S]),C=_getOwnPropGetter(f,S)}catch(f){_throwDynamicError((g.hdlr||{})[di],S,"State",f)}}T&&(C[g.rf]=T),I&&(C[g.ro]=I),b&&(C[g.blkVal]=!0)}return f}function _makeDynamicObject(g,f,S,v){try{objForEachKey(f,(function(S,v){_setDynamicProperty(g,f,S,v)})),f[jr]||(ke(f,jr,{get:function(){return g[pi]}}),_patchArray(g,f,S))}catch(f){_throwDynamicError((g.hdlr||{})[di],S,v,f)}return f}var zr="[[ai_",Kr="]]";function _createState(g){var f,S,v=newSymbol(zr+"get"+g.uid+Kr),C=newSymbol(zr+"ro"+g.uid+Kr),_=newSymbol(zr+"rf"+g.uid+Kr),T=newSymbol(zr+"blkVal"+g.uid+Kr),I=newSymbol(zr+"dtl"+g.uid+Kr),b=null,A=null;function _useHandler(f,v){var C=S.act;try{S.act=f,f&&f[I]&&(arrForEach(f[I],(function(g){g.clr(f)})),f[I]=[]),v({cfg:g.cfg,set:g.set.bind(g),setDf:g[li].bind(g),ref:g.ref.bind(g),rdOnly:g[ri].bind(g)})}catch(f){var _=g[di];throw _&&_[oi](1,107,dumpObj(f)),f}finally{S.act=C||null}}function _notifyWatchers(){if(b){var g=b;b=null,A&&A[mi](),A=null;var f=[];if(arrForEach(g,(function(g){if(g&&(g[I]&&(arrForEach(g[I],(function(f){f.clr(g)})),g[I]=null),g.fn))try{_useHandler(g,g.fn)}catch(g){f[ui](g)}})),b)try{_notifyWatchers()}catch(g){f[ui](g)}f[ni]>0&&throwAggregationError("Watcher error(s): ",f)}}function _addWatcher(g){if(g&&g.h[ni]>0){b||(b=[]),A||(A=scheduleTimeout((function(){A=null,_notifyWatchers()}),0));for(var f=0;f<g.h[ni];f++){var S=g.h[f];S&&-1===dt(b,S)&&b[ui](S)}}}function _trackHandler(g,f){if(g){var S=g[I]=g[I]||[];-1===dt(S,f)&&S[ui](f)}}return(f={prop:v,ro:C,rf:_})[ii]=T,f[pi]=g,f.add=_addWatcher,f[si]=_notifyWatchers,f.use=_useHandler,f.trk=_trackHandler,S=f}function _createAndUseHandler(g,f){var S={fn:f,rm:function(){S.fn=null,g=null,f=null}};return objDefine(S,"toJSON",{v:function(){return"WatcherHandler"+(S.fn?"":"[X]")}}),g.use(S,f),S}function _createDynamicHandler(g,f,S){var v,C=getDynamicConfigHandler(f);if(C)return C;var _,T=createUniqueNamespace("dyncfg",!0),I=f&&!1!==S?f:_cfgDeepCopy(f);function _notifyWatchers(){_[si]()}function _setValue(f,S,v){try{f=_setDynamicProperty(_,f,S,v)}catch(f){_throwDynamicError(g,S,"Setting value",f)}return f[S]}function _watch(g){return _createAndUseHandler(_,g)}function _block(g,f){_.use(null,(function(S){var v=_.upd;try{isUndefined(f)||(_.upd=f),g(S)}finally{_.upd=v}}))}function _ref(g,f){var S;return _setDynamicPropertyState(_,g,f,(S={},S[0]=!0,S))[f]}function _rdOnly(g,f){var S;return _setDynamicPropertyState(_,g,f,(S={},S[1]=!0,S))[f]}function _blkPropValue(g,f){var S;return _setDynamicPropertyState(_,g,f,(S={},S[2]=!0,S))[f]}function _applyDefaults(g,f){return f&&objForEachKey(f,(function(f,S){_applyDefaultValue(b,g,f,S)})),g}var b=((v={uid:null,cfg:I})[di]=g,v[si]=_notifyWatchers,v.set=_setValue,v[li]=_applyDefaults,v[ci]=_watch,v.ref=_ref,v[ri]=_rdOnly,v[ii]=_blkPropValue,v._block=_block,v);return objDefine(b,"uid",{c:!1,e:!1,w:!1,v:T}),_makeDynamicObject(_=_createState(b),I,"config","Creating"),b}function _logInvalidAccess(g,f){g?(g[ai](f),g[oi](2,108,f)):throwInvalidAccess(f)}function createDynamicConfig(g,f,S,v){var C=_createDynamicHandler(S,g||{},v);return f&&C[li](C.cfg,f),C}function onConfigChange(g,f,S){var v=g[jr]||g;return!v.cfg||v.cfg!==g&&v.cfg[jr]!==v?(_logInvalidAccess(S,cr+dumpObj(g)),createDynamicConfig(g,null,S)[ci](f)):v[ci](f)}function runTargetUnload(g,f){if(g&&g[ki])return g[ki](f)}function doUnloadAll(g,f,S){var v;return S||(v=createPromise((function(g){S=g}))),g&&Ct(g)>0?doAwaitResponse(runTargetUnload(g[0],f),(function(){doUnloadAll(arrSlice(g,1),f,S)})):S(),v}var Jr=500,Yr="Microsoft_ApplicationInsights_BypassAjaxInstrumentation";function cfgDfMerge(g){return{mrg:!0,v:g}}var Qr,Xr,Zr=[Zn,er,tr,ir],es=null;function _listenerProxyFunc(g,f){return function(){var S=arguments,v=getDebugExt(f);if(v){var C=v.listener;C&&C[g]&&C[g][hi](C,S)}}}function _getExtensionNamespace(){var g=getInst("Microsoft");return g&&(es=g.ApplicationInsights),es}function getDebugExt(g){var f=es;return f||!0===g.disableDbgExt||(f=es||_getExtensionNamespace()),f?f.ChromeDbgExt:null}function getDebugListener(g){if(!Qr){Qr={};for(var f=0;f<Zr[ni];f++)Qr[Zr[f]]=_listenerProxyFunc(Zr[f],g)}return Qr}var ts="warnToConsole",is="AI (Internal): ",ns="AI: ",rs="AITR_",ss={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},as=((Xr={})[0]=null,Xr[1]="errorToConsole",Xr[2]=ts,Xr[3]="debugToConsole",Xr);function _sanitizeDiagnosticText(g){return g?'"'+g[Xi](/\"/g,Gn)+'"':Gn}function _logToConsole(g,f){var S=getConsole();if(S){var v="log";S[g]&&(v=g),be(S[v])&&S[v](f)}}var os=function(){function _InternalLogMessage(g,f,S,v){void 0===S&&(S=!1);var C=this;C[Bi]=g,C[Hi]=(S?ns:is)+g;var _=Gn;hasJSON()&&(_=getJSON().stringify(v));var T=(f?" message:"+_sanitizeDiagnosticText(f):Gn)+(v?" props:"+_sanitizeDiagnosticText(_):Gn);C[Hi]+=T}return _InternalLogMessage.dataType="MessageData",_InternalLogMessage}();function safeGetLogger(g,f){return(g||{})[di]||new ds(f)}var ls,cs,ds=function(){function DiagnosticLogger(g){this.identifier="DiagnosticLogger",this.queue=[];var f,S,v,C,_,T=0,I={};dynamicProto(DiagnosticLogger,this,(function(b){function _logInternalMessage(g,f){if(!_areInternalMessagesThrottled()){var C=!0,_=rs+f[Bi];if(I[_]?C=!1:I[_]=!0,C&&(g<=S&&(b.queue[ui](f),T++,_debugExtMsg(1===g?"error":"warn",f)),T===v)){var A="Internal events throttle limit per PageView reached for this app.",P=new os(23,A,!1);b.queue[ui](P),1===g?b.errorToConsole(A):b[ai](A)}}}function _setDefaultsFromConfig(g){return onConfigChange(createDynamicConfig(g,ss,b).cfg,(function(g){var _=g.cfg;f=_[xi],S=_.loggingLevelTelemetry,v=_.maxMessageLimit,C=_.enableDebug}))}function _areInternalMessagesThrottled(){return T>=v}function _debugExtMsg(f,S){var v=getDebugExt(g||{});v&&v[ji]&&v[ji](f,S)}_=_setDefaultsFromConfig(g||{}),b.consoleLoggingLevel=function(){return f},b[oi]=function(g,S,v,_,T){void 0===T&&(T=!1);var A=new os(S,v,T,_);if(C)throw dumpObj(A);var P=as[g]||ts;if(isUndefined(A[Hi]))_debugExtMsg("throw"+(1===g?"Critical":"Warning"),A);else{if(T){var R=+A[Bi];!I[R]&&f>=g&&(b[P](A[Hi]),I[R]=!0)}else f>=g&&b[P](A[Hi]);_logInternalMessage(g,A)}},b.debugToConsole=function(g){_logToConsole("debug",g),_debugExtMsg("warning",g)},b[ai]=function(g){_logToConsole("warn",g),_debugExtMsg("warning",g)},b.errorToConsole=function(g){_logToConsole("error",g),_debugExtMsg("error",g)},b.resetInternalMessageCount=function(){T=0,I={}},b[Zi]=_logInternalMessage,b[ki]=function(g){_&&_.rm(),_=null}}))}return DiagnosticLogger.__ieDyn=1,DiagnosticLogger}();function _getLogger(g){return g||new ds}function _throwInternal(g,f,S,v,C,_){void 0===_&&(_=!1),_getLogger(g)[oi](f,S,v,C,_)}function _warnToConsole(g,f){_getLogger(g)[ai](f)}var hs,us="toGMTString",gs="toUTCString",ps="cookie",ms="expires",fs="isCookieUseDisabled",Ss="disableCookiesUsage",vs="_ckMgr",Cs=null,ys=null,Es=null,_s={},Ts={},Is=((ls={cookieCfg:cfgDfMerge((cs={},cs[or]={fb:"cookieDomain",dfVal:isNotNullOrUndefined},cs.path={fb:"cookiePath",dfVal:isNotNullOrUndefined},cs.enabled=jn,cs.ignoreCookies=jn,cs.blockedCookies=jn,cs)),cookieDomain:jn,cookiePath:jn})[Ss]=jn,ls);function _getDoc(){!hs&&(hs=getLazy((function(){return nt()})))}function _gblCookieMgr(g,f){var S=createCookieMgr[vs]||Ts[vs];return S||(S=createCookieMgr[vs]=createCookieMgr(g,f),Ts[vs]=S),S}function _isMgrEnabled(g){return!g||g.isEnabled()}function _isIgnoredCookie(g,f){return!!(f&&g&&Ae(g.ignoreCookies))&&-1!==dt(g.ignoreCookies,f)}function _isBlockedCookie(g,f){return!!(f&&g&&Ae(g.blockedCookies)&&-1!==dt(g.blockedCookies,f))||_isIgnoredCookie(g,f)}function _isCfgEnabled(g,f){var S=f[Di];if(isNullOrUndefined(S)){var v=void 0;isUndefined(g[fs])||(v=!g[fs]),isUndefined(g[Ss])||(v=!g[Ss]),S=v}return S}function safeGetCookieMgr(g,f){var S;if(g)S=g.getCookieMgr();else if(f){var v=f.cookieCfg;S=v&&v[vs]?v[vs]:createCookieMgr(f)}return S||(S=_gblCookieMgr(f,(g||{})[di])),S}function createCookieMgr(g,f){var S,v,C,_,T,I,b,A,P;g=createDynamicConfig(g||Ts,null,f).cfg,T=onConfigChange(g,(function(f){f[li](f.cfg,Is),v=f.ref(f.cfg,"cookieCfg"),C=v[lr]||"/",_=v[or],I=!1!==_isCfgEnabled(g,v),b=v.getCookie||_getCookieValue,A=v.setCookie||_setCookieValue,P=v.delCookie||_setCookieValue}),f);var R=((S={isEnabled:function(){var S=!1!==_isCfgEnabled(g,v)&&I&&areCookiesSupported(f),C=Ts[vs];return S&&C&&R!==C&&(S=_isMgrEnabled(C)),S},setEnabled:function(g){I=!1!==g,v[Di]=g},set:function(g,f,S,T,I){var b=!1;if(_isMgrEnabled(R)&&!_isBlockedCookie(v,g)){var P={},M=ft(f||Gn),w=Et(M,";");if(-1!==w&&(M=ft(strLeft(f,w)),P=_extractParts(Je(f,w+1))),setValue(P,or,T||_,isTruthy,isUndefined),!isNullOrUndefined(S)){var O=isIE();if(isUndefined(P[ms])){var D=utcNow()+1e3*S;if(D>0){var N=new Date;N.setTime(D),setValue(P,ms,_formatDate(N,O?us:gs)||_formatDate(N,O?us:gs)||Gn,isTruthy)}}O||setValue(P,"max-age",Gn+S,null,isUndefined)}var k=getLocation();k&&"https:"===k[Ki]&&(setValue(P,"secure",null,null,isUndefined),null===ys&&(ys=!uaDisallowsSameSiteNone((lt()||{})[Ji])),ys&&setValue(P,"SameSite","None",null,isUndefined)),setValue(P,lr,I||C,null,isUndefined),A(g,_formatCookieValue(M,P)),b=!0}return b},get:function(g){var f=Gn;return _isMgrEnabled(R)&&!_isIgnoredCookie(v,g)&&(f=b(g)),f},del:function(g,f){var S=!1;return _isMgrEnabled(R)&&(S=R.purge(g,f)),S},purge:function(g,S){var v,C=!1;if(areCookiesSupported(f)){var _=((v={})[lr]=S||"/",v[ms]="Thu, 01 Jan 1970 00:00:01 GMT",v);isIE()||(_["max-age"]="0"),P(g,_formatCookieValue(Gn,_)),C=!0}return C}})[ki]=function(g){T&&T.rm(),T=null},S);return R[vs]=R,R}function areCookiesSupported(g){if(null===Cs){Cs=!1,!hs&&_getDoc();try{var f=hs.v||{};Cs=void 0!==f[ps]}catch(f){_throwInternal(g,2,68,"Cannot access document.cookie - "+getExceptionName(f),{exception:dumpObj(f)})}}return Cs}function _extractParts(g){var f={};g&&g[ni]&&arrForEach(ft(g)[Yi](";"),(function(g){if(g=ft(g||Gn)){var S=Et(g,"=");-1===S?f[g]=null:f[ft(strLeft(g,S))]=ft(Je(g,S+1))}}));return f}function _formatDate(g,f){return be(g[f])?g[f]():null}function _formatCookieValue(g,f){var S=g||Gn;return objForEachKey(f,(function(g,f){S+="; "+g+(isNullOrUndefined(f)?Gn:"="+f)})),S}function _getCookieValue(g){var f=Gn;if(!hs&&_getDoc(),hs.v){var S=hs.v[ps]||Gn;Es!==S&&(_s=_extractParts(S),Es=S),f=ft(_s[g]||Gn)}return f}function _setCookieValue(g,f){!hs&&_getDoc(),hs.v&&(hs.v[ps]=g+"="+f)}function uaDisallowsSameSiteNone(g){return!!Ie(g)&&(!(!strContains(g,"CPU iPhone OS 12")&&!strContains(g,"iPad; CPU OS 12"))||(!!(strContains(g,"Macintosh; Intel Mac OS X 10_14")&&strContains(g,"Version/")&&strContains(g,"Safari"))||(!(!strContains(g,"Macintosh; Intel Mac OS X 10_14")||!yt(g,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))||(!(!strContains(g,"Chrome/5")&&!strContains(g,"Chrome/6"))||(!(!strContains(g,"UnrealEngine")||strContains(g,"Chrome"))||!(!strContains(g,"UCBrowser/12")&&!strContains(g,"UCBrowser/11")))))))}var bs={perfEvtsSendAll:!1};function _runScheduledListeners(g){g.h=null;var f=g.cb;g.cb=[],arrForEach(f,(function(g){safe(g.fn,[g.arg])}))}function _runListeners(g,f,S,v){arrForEach(g,(function(g){g&&g[f]&&(S?(S.cb[ui]({fn:v,arg:g}),S.h=S.h||scheduleTimeout(_runScheduledListeners,0,S)):safe(v,[g]))}))}var As=function(){function NotificationManager(g){var f,S;this.listeners=[];var v=[],C={h:null,cb:[]},_=createDynamicConfig(g,bs);S=_[ci]((function(g){f=!!g.cfg.perfEvtsSendAll})),dynamicProto(NotificationManager,this,(function(g){objDefine(g,"listeners",{g:function(){return v}}),g[Ci]=function(g){v[ui](g)},g[vi]=function(g){for(var f=dt(v,g);f>-1;)v[gi](f,1),f=dt(v,g)},g[Zn]=function(g){_runListeners(v,Zn,C,(function(f){f[Zn](g)}))},g[er]=function(g,f){_runListeners(v,er,C,(function(S){S[er](g,f)}))},g[tr]=function(g,f){_runListeners(v,tr,f?C:null,(function(S){S[tr](g,f)}))},g[ir]=function(g){g&&(!f&&g[an]()||_runListeners(v,ir,null,(function(f){g[$i]?scheduleTimeout((function(){return f[ir](g)}),0):f[ir](g)})))},g[nr]=function(g){g&&g[ni]&&_runListeners(v,nr,C,(function(f){f[nr](g)}))},g[rr]=function(g){g&&g[on]&&_runListeners(v,rr,C,(function(f){f[rr](g)}))},g[sr]=function(g,f){if(g>0){var S=f||0;_runListeners(v,sr,C,(function(f){f[sr](g,S)}))}},g[ki]=function(g){var f,_finishUnload=function(){S&&S.rm(),S=null,v=[],C.h&&C.h[mi](),C.h=null,C.cb=[]};if(_runListeners(v,"unload",null,(function(S){var v=S[ki](g);v&&(f||(f=[]),f[ui](v))})),f)return createPromise((function(g){return doAwaitResponse(Fn(f),(function(){_finishUnload(),g()}))}));_finishUnload()}}))}return NotificationManager.__ieDyn=1,NotificationManager}(),Ps="ctx",Rs="ParentContextKey",Ms="ChildrenContextKey",ws=null,Os=function(){function PerfEvent(g,f,S){var v,C=this;(C.start=utcNow(),C[Ai]=g,C[$i]=S,C[an]=function(){return!1},be(f))&&objDefine(C,"payload",{g:function(){return!v&&be(f)&&(v=f(),f=null),v}});C[ln]=function(g){return g?g===PerfEvent[Rs]||g===PerfEvent[Ms]?C[g]:(C[Ps]||{})[g]:null},C[cn]=function(g,f){if(g)if(g===PerfEvent[Rs])C[g]||(C[an]=function(){return!0}),C[g]=f;else if(g===PerfEvent[Ms])C[g]=f;else{(C[Ps]=C[Ps]||{})[g]=f}},C[dn]=function(){var g=0,f=C[ln](PerfEvent[Ms]);if(Ae(f))for(var S=0;S<f[ni];S++){var v=f[S];v&&(g+=v[Ri])}C[Ri]=utcNow()-C.start,C.exTime=C[Ri]-g,C[dn]=function(){}}}return PerfEvent.ParentContextKey="parent",PerfEvent.ChildrenContextKey="childEvts",PerfEvent}(),Ds=function(){function PerfManager(g){this.ctx={},dynamicProto(PerfManager,this,(function(f){f.create=function(g,f,S){return new Os(g,f,S)},f.fire=function(f){f&&(f[dn](),g&&be(g[ir])&&g[ir](f))},f[cn]=function(g,S){g&&((f[Ps]=f[Ps]||{})[g]=S)},f[ln]=function(g){return(f[Ps]||{})[g]}}))}return PerfManager.__ieDyn=1,PerfManager}(),Ns="CoreUtils.doPerf";function doPerf(g,f,S,v,C){if(g){var _=g;if(_[ar]&&(_=_[ar]()),_){var T=void 0,I=_[ln](Ns);try{if(T=_.create(f(),v,C)){if(I&&T[cn]&&(T[cn](Os[Rs],I),I[ln]&&I[cn])){var b=I[ln](Os[Ms]);b||(b=[],I[cn](Os[Ms],b)),b[ui](T)}return _[cn](Ns,T),S(T)}}catch(g){T&&T[cn]&&T[cn]("exception",g)}finally{T&&_.fire(T),_[cn](Ns,I)}}}return S()}function getGblPerfMgr(){return ws}function newGuid(){var g=generateW3CId();return Je(g,0,8)+"-"+Je(g,8,12)+"-"+Je(g,12,16)+"-"+Je(g,16,20)+"-"+Je(g,20)}function generateW3CId(){for(var g,f=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],S=Gn,v=0;v<4;v++)S+=f[15&(g=random32())]+f[g>>4&15]+f[g>>8&15]+f[g>>12&15]+f[g>>16&15]+f[g>>20&15]+f[g>>24&15]+f[g>>28&15];var C=f[8+(3&random32())|0];return Ye(S,0,8)+Ye(S,9,4)+"4"+Ye(S,13,3)+C+Ye(S,16,3)+Ye(S,19,12)}var ks="00000000000000000000000000000000",Ls="0000000000000000";function _isValid(g,f,S){return!(!g||g[ni]!==f||g===S)&&!!g.match(/^[\da-f]*$/i)}function isValidTraceId(g){return _isValid(g,32,ks)}function isValidSpanId(g){return _isValid(g,16,Ls)}var Fs=createElmNodeData("plugin");function _getPluginState(g){return Fs.get(g,"state",{},!0)}function initializePlugins(g,f){for(var S,v=[],C=null,_=g[Wi]();_;){var T=_[bi]();if(T){C&&C[zi]&&T[Qn]&&C[zi](T);var I=!!(S=_getPluginState(T))[yi];T[yi]&&(I=T[yi]()),I||v[ui](T),C=T,_=_[Wi]()}}arrForEach(v,(function(v){var C=g[Wn]();v[fi](g.getCfg(),C,f,g[Wi]()),S=_getPluginState(v),v[Wn]||S[Wn]||(S[Wn]=C),S[yi]=!0,delete S[Vi]}))}function sortPlugins(g){return g.sort((function(g,f){var S=0;if(f){var v=f[Qn];g[Qn]?S=v?g[Xn]-f[Xn]:1:v&&(S=-1)}else S=g?1:-1;return S}))}function createDistributedTraceContext(g){var f={};return{getName:function(){return f[Ai]},setName:function(S){g&&g.setName(S),f[Ai]=S},getTraceId:function(){return f[fn]},setTraceId:function(S){g&&g.setTraceId(S),isValidTraceId(S)&&(f[fn]=S)},getSpanId:function(){return f[Sn]},setSpanId:function(S){g&&g.setSpanId(S),isValidSpanId(S)&&(f[Sn]=S)},getTraceFlags:function(){return f[vn]},setTraceFlags:function(S){g&&g.setTraceFlags(S),f[vn]=S}}}var xs,Us="TelemetryPluginChain",Vs="_hasRun",Bs="_getTelCtx",Hs=0;function _getNextProxyStart(g,f,S){for(;g;){if(g[bi]()===S)return g;g=g[Wi]()}return createTelemetryProxyChain([S],f.config||{},f)}function _createInternalContext(g,f,S,v){var C=null,_=[];f||(f=createDynamicConfig({},null,S[di])),null!==v&&(C=v?_getNextProxyStart(g,S,v):g);var T={_next:_moveNext,ctx:{core:function(){return S},diagLog:function(){return safeGetLogger(S,f.cfg)},getCfg:function(){return f.cfg},getExtCfg:_resolveExtCfg,getConfig:_getConfig,hasNext:function(){return!!C},getNext:function(){return C},setNext:function(g){C=g},iterate:_iterateChain,onComplete:_addOnComplete}};function _addOnComplete(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];g&&_[ui]({func:g,self:isUndefined(f)?T.ctx:f,args:S})}function _moveNext(){var g=C;if(C=g?g[Wi]():null,!g){var f=_;f&&f[ni]>0&&(arrForEach(f,(function(g){try{g.func.call(g.self,g.args)}catch(g){_throwInternal(S[di],2,73,"Unexpected Exception during onComplete - "+dumpObj(g))}})),_=[])}return g}function _getExtCfg(g,S){var v=null,C=f.cfg;if(C&&g){var _=C[Jn];!_&&S&&(_={}),C[Jn]=_,(_=f.ref(C,Jn))&&(!(v=_[g])&&S&&(v={}),_[g]=v,v=f.ref(_,g))}return v}function _resolveExtCfg(g,S){var v=_getExtCfg(g,!0);return S&&objForEachKey(S,(function(g,S){if(isNullOrUndefined(v[g])){var C=f.cfg[g];!C&&isNullOrUndefined(C)||(v[g]=C)}_applyDefaultValue(f,v,g,S)})),f[li](v,S)}function _getConfig(g,S,v){var C;void 0===v&&(v=!1);var _=_getExtCfg(g,!1),T=f.cfg;return!_||!_[S]&&isNullOrUndefined(_[S])?!T[S]&&isNullOrUndefined(T[S])||(C=T[S]):C=_[S],C||!isNullOrUndefined(C)?C:v}function _iterateChain(g){for(var f;f=T._next();){var S=f[bi]();S&&g(S)}}return T}function createProcessTelemetryContext(g,f,S,v){var C=createDynamicConfig(f),_=_createInternalContext(g,C,S,v),T=_.ctx;function _processNext(g){var f=_._next();return f&&f[Qn](g,T),!f}function _createNew(g,f){return void 0===g&&(g=null),Ae(g)&&(g=createTelemetryProxyChain(g,C.cfg,S,f)),createProcessTelemetryContext(g||T[Wi](),C.cfg,S,f)}return T[Mi]=_processNext,T[Ui]=_createNew,T}function createProcessTelemetryUnloadContext(g,f,S){var v=createDynamicConfig(f.config),C=_createInternalContext(g,v,f,S),_=C.ctx;function _processNext(g){var f=C._next();return f&&f[ki](_,g),!f}function _createNew(g,S){return void 0===g&&(g=null),Ae(g)&&(g=createTelemetryProxyChain(g,v.cfg,f,S)),createProcessTelemetryUnloadContext(g||_[Wi](),f,S)}return _[Mi]=_processNext,_[Ui]=_createNew,_}function createProcessTelemetryUpdateContext(g,f,S){var v=createDynamicConfig(f.config),C=_createInternalContext(g,v,f,S).ctx;function _processNext(g){return C.iterate((function(f){be(f[qi])&&f[qi](C,g)}))}function _createNew(g,S){return void 0===g&&(g=null),Ae(g)&&(g=createTelemetryProxyChain(g,v.cfg,f,S)),createProcessTelemetryUpdateContext(g||C[Wi](),f,S)}return C[Mi]=_processNext,C[Ui]=_createNew,C}function createTelemetryProxyChain(g,f,S,v){var C=null,_=!v;if(Ae(g)&&g[ni]>0){var T=null;arrForEach(g,(function(g){if(_||v!==g||(_=!0),_&&g&&be(g[Qn])){var I=createTelemetryPluginProxy(g,f,S);C||(C=I),T&&T._setNext(I),T=I}}))}return v&&!C?createTelemetryProxyChain([v],f,S):C}function createTelemetryPluginProxy(g,f,S){var v,C=null,_=be(g[Qn]),T=be(g[zi]),I={getPlugin:function(){return g},getNext:function(){return C},processTelemetry:_processTelemetry,unload:_unloadPlugin,update:_updatePlugin,_id:v=g?g[Si]+"-"+g[Xn]+"-"+Hs++:"Unknown-0-"+Hs++,_setNext:function(g){C=g}};function _getTelCtx(){var v;return g&&be(g[Bs])&&(v=g[Bs]()),v||(v=createProcessTelemetryContext(I,f,S)),v}function _processChain(f,S,_,T,I){var b=!1,A=g?g[Si]:Us,P=f[Vs];return P||(P=f[Vs]={}),f.setNext(C),g&&doPerf(f[Wn](),(function(){return A+":"+_}),(function(){P[v]=!0;try{var g=C?C._id:Gn;g&&(P[g]=!1),b=S(f)}catch(g){var T=!C||P[C._id];T&&(b=!0),C&&T||_throwInternal(f[ji](),1,73,"Plugin ["+A+"] failed during "+_+" - "+dumpObj(g)+", run flags: "+dumpObj(P))}}),T,I),b}function _processTelemetry(f,S){function _callProcessTelemetry(S){if(!g||!_)return!1;var v=_getPluginState(g);return!v[Vi]&&!v[Kn]&&(T&&g[zi](C),g[Qn](f,S),!0)}_processChain(S=S||_getTelCtx(),_callProcessTelemetry,"processTelemetry",(function(){return{item:f}}),!f.sync)||S[Mi](f)}function _unloadPlugin(f,S){function _callTeardown(){var v=!1;if(g){var C=_getPluginState(g),_=g[Wn]||C[Wn];!g||_&&_!==f.core()||C[Vi]||(C[Wn]=null,C[Vi]=!0,C[yi]=!1,g[Vi]&&!0===g[Vi](f,S)&&(v=!0))}return v}_processChain(f,_callTeardown,"unload",(function(){}),S[$i])||f[Mi](S)}function _updatePlugin(f,S){function _callUpdate(){var v=!1;if(g){var C=_getPluginState(g),_=g[Wn]||C[Wn];!g||_&&_!==f.core()||C[Vi]||g[qi]&&!0===g[qi](f,S)&&(v=!0)}return v}_processChain(f,_callUpdate,"update",(function(){}),!1)||f[Mi](S)}return He(I)}function createUnloadHandlerContainer(){var g=[];function _addHandler(f){f&&g[ui](f)}function _runHandlers(f,S){arrForEach(g,(function(g){try{g(f,S)}catch(g){_throwInternal(f[ji](),2,73,"Unexpected error calling unload handler - "+dumpObj(g))}})),g=[]}return{add:_addHandler,run:_runHandlers}}function createUnloadHookContainer(){var g=[];function _doUnload(f){var S=g;g=[],arrForEach(S,(function(g){try{(g.rm||g.remove).call(g)}catch(g){_throwInternal(f,2,73,"Unloading:"+dumpObj(g))}}))}function _addHook(f){f&&arrAppend(g,f)}return{run:_doUnload,add:_addHook}}var $s="getPlugin",js=((xs={})[Jn]={isVal:isNotNullOrUndefined,v:{}},xs),Gs=function(){function BaseTelemetryPlugin(){var g,f,S,v,C,_=this;function _getTelCtx(g){void 0===g&&(g=null);var v=g;if(!v){var C=f||createProcessTelemetryContext(null,{},_[Wn]);v=S&&S[$s]?C[Ui](null,S[$s]):C[Ui](null,S)}return v}function _setDefaults(g,v,C){createDynamicConfig(g,js,safeGetLogger(v)),!C&&v&&(C=v[wi]()[Wi]());var T=S;S&&S[$s]&&(T=S[$s]()),_[Wn]=v,f=createProcessTelemetryContext(C,g,v,T)}function _initDefaults(){g=!1,_[Wn]=null,f=null,S=null,C=createUnloadHookContainer(),v=createUnloadHandlerContainer()}_initDefaults(),dynamicProto(BaseTelemetryPlugin,_,(function(f){f[fi]=function(f,S,v,C){_setDefaults(f,S,C),g=!0},f[Vi]=function(g,_){var T,I=f[Wn];if(I&&(!g||I===g[Wn]())){var b,A=!1,P=g||createProcessTelemetryUnloadContext(null,I,S&&S[$s]?S[$s]():S),R=_||((T={reason:0})[$i]=!1,T);return f[Gi]&&!0===f[Gi](P,R,_unloadCallback)?b=!0:_unloadCallback(),b}function _unloadCallback(){A||(A=!0,v.run(P,_),C.run(P[ji]()),!0===b&&P[Mi](R),_initDefaults())}},f[qi]=function(g,v){var C=f[Wn];if(C&&(!g||C===g[Wn]())){var _,T=!1,I=g||createProcessTelemetryUpdateContext(null,C,S&&S[$s]?S[$s]():S),b=v||{reason:0};return f._doUpdate&&!0===f._doUpdate(I,b,_updateCallback)?_=!0:_updateCallback(),_}function _updateCallback(){T||(T=!0,_setDefaults(I.getCfg(),I.core(),I[Wi]()))}},proxyFunctionAs(f,"_addUnloadCb",(function(){return v}),"add"),proxyFunctionAs(f,"_addHook",(function(){return C}),"add"),objDefine(f,"_unloadHooks",{g:function(){return C}})})),_[ji]=function(g){return _getTelCtx(g)[ji]()},_[yi]=function(){return g},_.setInitialized=function(f){g=f},_[zi]=function(g){S=g},_[Mi]=function(g,f){f?f[Mi](g):S&&be(S[Qn])&&S[Qn](g,null)},_._getTelCtx=_getTelCtx}return BaseTelemetryPlugin.__ieDyn=1,BaseTelemetryPlugin}();function _addInitializer(g,f,S){var v={id:f,fn:S};return arrAppend(g,v),{remove:function(){arrForEach(g,(function(f,S){if(f.id===v.id)return g[gi](S,1),-1}))}}}function _runInitializers(g,f,S){for(var v=!1,C=g[ni],_=0;_<C;++_){var T=g[_];if(T)try{if(!1===T.fn[hi](null,[f])){v=!0;break}}catch(g){_throwInternal(S,2,64,"Telemetry initializer failed: "+getExceptionName(g),{exception:dumpObj(g)},!0)}}return!v}var qs,Ws=function(g){function TelemetryInitializerPlugin(){var f,S,v=g.call(this)||this;function _initDefaults(){f=0,S=[]}return v.identifier="TelemetryInitializerPlugin",v.priority=199,_initDefaults(),dynamicProto(TelemetryInitializerPlugin,v,(function(g,v){g.addTelemetryInitializer=function(g){return _addInitializer(S,f++,g)},g[Qn]=function(f,v){_runInitializers(S,f,v?v[ji]():g[ji]())&&g[Mi](f,v)},g[Gi]=function(){_initDefaults()}})),v}return __extendsFn(TelemetryInitializerPlugin,g),TelemetryInitializerPlugin.__ieDyn=1,TelemetryInitializerPlugin}(Gs),zs="Plugins must provide initialize method",Ks="_notificationManager",Js="SDK is still unloading...",Ys="SDK is not initialized",Qs=100,Xs=5e4,Zs=objDeepFreeze(((qs={cookieCfg:{}})[Yn]={rdOnly:!0,ref:!0,v:[]},qs[qn]={rdOnly:!0,ref:!0,v:[]},qs[Jn]={ref:!0,v:{}},qs[zn]=jn,qs.loggingLevelConsole=0,qs.diagnosticLogInterval=jn,qs));function _createPerfManager(g,f){return new Ds(f)}function _validateExtensions(g,f,S){var v,C=[],_=[],T={};return arrForEach(S,(function(S){(isNullOrUndefined(S)||isNullOrUndefined(S[fi]))&&throwError(zs);var v=S[Xn],I=S[Si];S&&v&&(isNullOrUndefined(T[v])?T[v]=I:_warnToConsole(g,"Two extensions have same priority #"+v+" - "+T[v]+", "+I)),!v||v<f?C[ui](S):_[ui](S)})),(v={})[Wn]=C,v[qn]=_,v}function _isPluginPresent(g,f){var S=!1;return arrForEach(f,(function(f){if(f===g)return S=!0,-1})),S}function _deepMergeConfig(g,f,S,v){S&&objForEachKey(S,(function(S,C){v&&isPlainObject(C)&&isPlainObject(f[S])&&_deepMergeConfig(g,f[S],C,v),v&&isPlainObject(C)&&isPlainObject(f[S])?_deepMergeConfig(g,f[S],C,v):g.set(f,S,C)}))}function _findWatcher(g,f){var S=null,v=-1;return arrForEach(g,(function(g,C){if(g.w===f)return S=g,v=C,-1})),{i:v,l:S}}function _addDelayedCfgListener(g,f){var S=_findWatcher(g,f).l;return S||(S={w:f,rm:function(){var S=_findWatcher(g,f);-1!==S.i&&g[gi](S.i,1)}},g[ui](S)),S}function _registerDelayedCfgListener(g,f,S){arrForEach(f,(function(f){var v=onConfigChange(g,f.w,S);delete f.w,f.rm=function(){v.rm()}}))}function _initDebugListener(g,f,S,v){return f.add(g[ci]((function(g){var f=g.cfg.disableDbgExt;!0===f&&v&&(S[vi](v),v=null),S&&!v&&!0!==f&&(v=getDebugListener(g.cfg),S[Ci](v))}))),v}function _createUnloadHook(g){return objDefine({rm:function(){g.rm()}},"toJSON",{v:function(){return"aicore::onCfgChange<"+JSON.stringify(g)+">"}})}var ea=function(){function AppInsightsCore(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q,W,z,K;dynamicProto(AppInsightsCore,this,(function(J){function _setStatus(){q=!0,isNullOrUndefined(x)?($=ei[_i],_throwInternal(S,1,112,"ikey can't be resolved from promises")):$=ei.ACTIVE,_releaseQueues()}function _releaseQueues(){f&&(J.releaseQueue(),J[Oi]())}function _startLogPoller(f){W&&W[Di]||K||(f||S&&S.queue[ni]>0)&&(z||(z=!0,_addUnloadHook(g[ci]((function(g){var f=g.cfg.diagnosticLogInterval;f&&f>0||(f=1e4);var S=!1;W&&(S=W[Di],W[mi]()),(W=createTimeout(_flushInternalLogs,f)).unref(),W[Di]=S})))),W[Di]=!0);return W}function _setPluginVersions(){var g={};B=[];var _addPluginVersions=function(f){f&&arrForEach(f,(function(f){if(f[Si]&&f[Fi]&&!g[f.identifier]){var S=f[Si]+"="+f[Fi];B[ui](S),g[f.identifier]=f}}))};_addPluginVersions(R),P&&arrForEach(P,(function(g){_addPluginVersions(g)})),_addPluginVersions(A)}function _initDefaults(){f=!1,(g=createDynamicConfig({},Zs,J[di])).cfg[xi]=1,objDefine(J,"config",{g:function(){return g.cfg},s:function(g){J.updateCfg(g,!1)}}),objDefine(J,"pluginVersionStringArr",{g:function(){return B||_setPluginVersions(),B}}),objDefine(J,"pluginVersionString",{g:function(){return H||(B||_setPluginVersions(),H=B.join(";")),H||Gn}}),objDefine(J,"logger",{g:function(){return S||(S=new ds(g.cfg),g[di]=S),S},s:function(f){g[di]=f,S!==f&&(runTargetUnload(S,!1),S=f)}}),J[di]=new ds(g.cfg),V=[];var L=J.config[Yn]||[];L.splice(0,L[ni]),arrAppend(L,V),w=new Ws,v=[],runTargetUnload(C,!1),C=null,_=null,T=null,runTargetUnload(I,!1),I=null,b=null,A=[],P=null,R=null,M=!1,O=null,D=createUniqueNamespace("AIBaseCore",!0),N=createUnloadHandlerContainer(),F=null,x=null,k=createUnloadHookContainer(),U=[],H=null,B=null,K=!1,W=null,z=!1,$=0,j=null,G=null,q=!1,null}function _createTelCtx(){var f=createProcessTelemetryContext(_getPluginChain(),g.cfg,J);return f[Li](_startLogPoller),f}function _initPluginChain(g){var f=_validateExtensions(J[di],Jr,A);b=null,H=null,B=null,R=sortPlugins(arrAppend(R=(P||[])[0]||[],f[qn]));var S=arrAppend(sortPlugins(f[Wn]),R);V=He(S);var v=J.config[Yn]||[];v.splice(0,v[ni]),arrAppend(v,V);var C=_createTelCtx();R&&R[ni]>0&&initializePlugins(C[Ui](R),S),initializePlugins(C,S),g&&_doUpdate(g)}function _getPlugin(g){var f=null,S=null,v=[];return arrForEach(V,(function(f){if(f[Si]===g&&f!==w)return S=f,-1;f.getChannel&&v[ui](f)})),!S&&v[ni]>0&&arrForEach(v,(function(f){if(!(S=f.getChannel(g)))return-1})),S&&(f={plugin:S,setEnabled:function(g){_getPluginState(S)[Kn]=!g},isEnabled:function(){var g=_getPluginState(S);return!g[Vi]&&!g[Kn]},remove:function(g,f){var v;void 0===g&&(g=!0);var C=[S],_=((v={reason:1})[$i]=g,v);_removePlugins(C,_,(function(g){g&&_initPluginChain({reason:32,removed:C}),f&&f(g)}))}}),f}function _getPluginChain(){if(!b){var f=(V||[]).slice();-1===dt(f,w)&&f[ui](w),b=createTelemetryProxyChain(sortPlugins(f),g.cfg,J)}return b}function _removePlugins(f,S,v){if(f&&f[ni]>0){var C=createProcessTelemetryUnloadContext(createTelemetryProxyChain(f,g.cfg,J),J);C[Li]((function(){var g=!1,S=[];arrForEach(A,(function(v,C){_isPluginPresent(v,f)?g=!0:S[ui](v)})),A=S,H=null,B=null;var C=[];P&&(arrForEach(P,(function(S,v){var _=[];arrForEach(S,(function(S){_isPluginPresent(S,f)?g=!0:_[ui](S)})),C[ui](_)})),P=C),v&&v(g),_startLogPoller()})),C[Mi](S)}else v(!1)}function _flushInternalLogs(){if(S&&S.queue){var g=S.queue.slice(0);S.queue[ni]=0,arrForEach(g,(function(g){var f,S=((f={})[Ai]=O||"InternalMessageId: "+g[Bi],f[Pi]=x,f[Ri]=toISOString(new Date),f.baseType=os.dataType,f.baseData={message:g[Hi]},f);J.track(S)}))}}function _flushChannels(g,f,S,v){var C=1,_=!1,T=null;function doCallback(){C--,_&&0===C&&(T&&T[mi](),T=null,f&&f(_),f=null)}(v=v||5e3,R&&R[ni]>0)&&_createTelCtx()[Ui](R).iterate((function(f){if(f.flush){C++;var _=!1;f.flush(g,(function(){_=!0,doCallback()}),S)||_||(g&&null==T?T=scheduleTimeout((function(){T=null,doCallback()}),v):doCallback())}}));return _=!0,doCallback(),!0}function _initPerfManager(){var f;_addUnloadHook(g[ci]((function(g){if(g.cfg.enablePerfMgr){var S=g.cfg[zn];f!==S&&(S||(S=_createPerfManager),getSetValue(g.cfg,zn,S),f=S,T=null),_||T||!be(S)||(T=S(J,J[Ii]()))}else T=null,f=null})))}function _doUpdate(g){var f=createProcessTelemetryUpdateContext(_getPluginChain(),J);f[Li](_startLogPoller),J._updateHook&&!0===J._updateHook(f,g)||f[Mi](g)}function _logOrThrowError(g){var f=J[di];f?(_throwInternal(f,2,73,g),_startLogPoller()):throwError(g)}function _notifyInvalidEvent(g){var f=J[Ii]();f&&f[er]([g],2)}function _addUnloadHook(g){k.add(g)}_initDefaults(),J._getDbgPlgTargets=function(){return[V,v]},J[yi]=function(){return f},J.activeStatus=function(){return $},J._setPendingStatus=function(){$=3},J[fi]=function(v,_,T,I){M&&throwError(Js),J[yi]()&&throwError("Core cannot be initialized more than once"),g=createDynamicConfig(v,Zs,T||J[di],!1),v=g.cfg,_addUnloadHook(g[ci]((function(g){var C=g.cfg;if(!(3===$)){G=C.initInMemoMaxSize||Qs;var _=C[Ei],T=C.endpointUrl;if(isNullOrUndefined(_)){x=null,$=ei[_i];var I="Please provide instrumentation key";f?(_throwInternal(S,1,100,I),_releaseQueues()):throwError(I)}else{var b=[];if(isPromiseLike(_)?(b[ui](_),x=null):x=_,isPromiseLike(T)?(b[ui](T),j=null):j=T,b[ni]){q=!1,$=3;var A=isNotNullOrUndefined(C.initTimeOut)?C.initTimeOut:Xs,P=createAllSettledPromise(b);scheduleTimeout((function(){null,q||_setStatus()}),A),doAwaitResponse(P,(function(g){try{if(q)return;if(!g.rejected){var f=g[Ti];if(f&&f[ni]){var S=f[0];if(x=S&&S[Ti],f[ni]>1){var C=f[1];j=C&&C[Ti]}}x&&(v[Ei]=x,v.endpointUrl=j)}_setStatus()}catch(g){q||_setStatus()}}))}else _setStatus();var R=g.ref(g.cfg,Jn);objForEachKey(R,(function(f){g.ref(R,f)}))}}}))),L=_initDebugListener(g,k,(C=I)&&J[Ii](),L),_initPerfManager(),J[di]=T;var b=v[Yn];if((A=[])[ui].apply(A,__spreadArrayFn(__spreadArrayFn([],_,!1),b)),P=v[qn],_initPluginChain(null),R&&0!==R[ni]||throwError("No "+qn+" available"),P&&P[ni]>1){var w=J[bi]("TeeChannelController");w&&w.plugin||_throwInternal(S,1,28,"TeeChannel required")}_registerDelayedCfgListener(v,U,S),U=null,f=!0,$===ei.ACTIVE&&_releaseQueues()},J.getChannels=function(){var g=[];return R&&arrForEach(R,(function(f){g[ui](f)})),He(g)},J.track=function(g){doPerf(J[ar](),(function(){return"AppInsightsCore:track"}),(function(){null===g&&(_notifyInvalidEvent(g),throwError("Invalid telemetry item")),!g[Ai]&&isNullOrUndefined(g[Ai])&&(_notifyInvalidEvent(g),throwError("telemetry name required")),g[Pi]=g[Pi]||x,g[Ri]=g[Ri]||toISOString(new Date),g.ver=g.ver||"4.0",!M&&J[yi]()&&$===ei.ACTIVE?_createTelCtx()[Mi](g):$!==ei[_i]&&v[ni]<=G&&v[ui](g)}),(function(){return{item:g}}),!g.sync)},J[wi]=_createTelCtx,J[Ii]=function(){return C||(C=new As(g.cfg),J[Ks]=C),C},J[Ci]=function(g){J.getNotifyMgr()[Ci](g)},J[vi]=function(g){C&&C[vi](g)},J.getCookieMgr=function(){return I||(I=createCookieMgr(g.cfg,J[di])),I},J.setCookieMgr=function(g){I!==g&&(runTargetUnload(I,!1),I=g)},J[ar]=function(){return _||T||getGblPerfMgr()},J.setPerfMgr=function(g){_=g},J.eventCnt=function(){return v[ni]},J.releaseQueue=function(){if(f&&v[ni]>0){var g=v;v=[],2===$?arrForEach(g,(function(g){g[Pi]=g[Pi]||x,_createTelCtx()[Mi](g)})):_throwInternal(S,2,20,"core init status is not active")}},J[Oi]=function(g){return O=g||null,K=!1,W&&W[mi](),_startLogPoller(!0)},J[Ni]=function(){K=!0,W&&W[mi](),_flushInternalLogs()},proxyFunctions(J,(function(){return w}),["addTelemetryInitializer"]),J[ki]=function(g,v,_){var T;void 0===g&&(g=!0),f||throwError(Ys),M&&throwError(Js);var b,A=((T={reason:50})[$i]=g,T.flushComplete=!1,T);g&&!v&&(b=createPromise((function(g){v=g})));var P=createProcessTelemetryUnloadContext(_getPluginChain(),J);function _doUnload(g){A.flushComplete=g,M=!0,N.run(P,A),J[Ni](),P[Mi](A)}return P[Li]((function(){k.run(J[di]),doUnloadAll([I,C,S],g,(function(){_initDefaults(),v&&v(A)}))}),J),_flushInternalLogs(),_flushChannels(g,_doUnload,6,_),b},J[bi]=_getPlugin,J.addPlugin=function(g,f,S,v){if(!g)return v&&v(!1),void _logOrThrowError(zs);var C=_getPlugin(g[Si]);if(C&&!f)return v&&v(!1),void _logOrThrowError("Plugin ["+g[Si]+"] is already loaded!");var _={reason:16};function _addPlugin(f){A[ui](g),_.added=[g],_initPluginChain(_),v&&v(!0)}if(C){var T=[C.plugin];_removePlugins(T,{reason:2,isAsync:!!S},(function(g){g?(_.removed=T,_.reason|=32,_addPlugin()):v&&v(!1)}))}else _addPlugin()},J.updateCfg=function(f,S){var v;if(void 0===S&&(S=!0),J[yi]()){v={reason:1,cfg:g.cfg,oldCfg:deepExtend({},g.cfg),newConfig:deepExtend({},f),merge:S},f=v.newConfig;var C=g.cfg;f[Yn]=C[Yn],f[qn]=C[qn]}g._block((function(g){var v=g.cfg;_deepMergeConfig(g,v,f,S),S||objForEachKey(v,(function(S){De(f,S)||g.set(v,S,jn)})),g[li](v,Zs)}),!0),g[si](),v&&_doUpdate(v)},J.evtNamespace=function(){return D},J.flush=_flushChannels,J.getTraceCtx=function(g){return F||(F=createDistributedTraceContext()),F},J.setTraceCtx=function(g){F=g||null},J.addUnloadHook=_addUnloadHook,proxyFunctionAs(J,"addUnloadCb",(function(){return N}),"add"),J.onCfgChange=function(S){return _createUnloadHook(f?onConfigChange(g.cfg,S,J[di]):_addDelayedCfgListener(U,S))},J.getWParam=function(){return hasDocument()||g.cfg.enableWParam?0:-1}}))}return AppInsightsCore.__ieDyn=1,AppInsightsCore}(),ta="",ia="&"+"NoResponseBody"+"=true",na="POST",ra=function(){function SenderPostManager(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w,O=0;dynamicProto(SenderPostManager,this,(function(D,N){var k=!0;function _onSuccess(g,f){_doOnComplete(f,200,{},g)}function _onError(g,f){_throwInternal(S,2,26,"Failed to send telemetry.",{message:g}),_doOnComplete(f,400,{})}function _onNoPayloadUrl(g){_onError("No endpoint url is provided for the batch",g)}function _getSenderInterface(g,f){for(var S,v=0,C=null,_=0;null==C&&_<g[ni];)v=g[_],b||1!==v?2!==v||!isFetchSupported(f)||f&&R?3!==v||!isBeaconsSupported()||(f?P:A)||(C=_beaconSender):C=_doFetchSender:useXDomainRequest()?C=_xdrSender:isXhrSupported()&&(C=_xhrSender),_++;return C?((S={_transport:v,_isSync:f})[un]=C,S):null}function _doOnComplete(g,f,S,v){try{g&&g(f,S,v)}catch(g){}}function _doBeaconSend(g,f){var S=lt(),C=g[hn];if(!C)return _onNoPayloadUrl(f),!0;C=g[hn]+(M?ia:ta);var _=g[on],T=v?_:new Blob([_],{type:"text/plain;charset=UTF-8"});return S.sendBeacon(C,T)}function _beaconSender(g,f,_){var T=g[on];try{if(T)if(_doBeaconSend(g,f))_onSuccess(ta,f);else{var b=C&&C.beaconOnRetry;b&&be(b)?b(g,f,_doBeaconSend):(I&&I[un](g,f,!0),_throwInternal(S,2,40,". Failed to send telemetry with Beacon API, retried with normal sender."))}}catch(g){v&&_warnToConsole(S,"Failed to send telemetry using sendBeacon API. Ex:"+dumpObj(g)),_doOnComplete(f,v?0:400,{},ta)}}function _xhrSender(f,S,_){var T,I,b,A=f[gn]||{};!_&&g&&(T=createPromise((function(g,f){I=g,b=f}))),v&&_&&f.disableXhrSync&&(_=!1);var P=f[hn];if(!P)return _onNoPayloadUrl(S),void(I&&I(!1));var R=openXhr(na,P,k,!0,_,f[pn]);function _doOnReadyFunc(g){var _=C&&C.xhrOnComplete;if(_&&be(_))_(g,S,f);else{var T=getResponseText(g);_doOnComplete(S,g[nn],_getAllResponseHeaders(g,v),T)}}return v||R[mn]("Content-type","application/json"),arrForEach(Be(A),(function(g){R[mn](g,A[g])})),R.onreadystatechange=function(){v||(_doOnReadyFunc(R),4===R.readyState&&I&&I(!0))},R.onload=function(){v&&_doOnReadyFunc(R)},R.onerror=function(g){_doOnComplete(S,v?R[nn]:400,_getAllResponseHeaders(R,v),v?ta:formatErrorMessageXhr(R)),b&&b(g)},R.ontimeout=function(){_doOnComplete(S,v?R[nn]:500,_getAllResponseHeaders(R,v),v?ta:formatErrorMessageXhr(R)),I&&I(!1)},R.send(f[on]),T}function _doFetchSender(f,S,_){var I,b,A,P,R=f[hn],D=f[on],N=v?D:new Blob([D],{type:"application/json"}),L=new Headers,F=D[ni],x=!1,U=!1,V=f[gn]||{},B=((I={method:na,body:N})[Yr]=!0,I);f.headers&&Be(f.headers)[ni]>0&&(arrForEach(Be(V),(function(g){L.append(g,V[g])})),B[gn]=L),T?B.credentials=T:k&&v&&(B.credentials="include"),_&&(B.keepalive=!0,O+=F,v?2===f._sendReason&&(x=!0,M&&(R+=ia)):x=!0);var H=new Request(R,B);try{H[Yr]=!0}catch(g){}if(!_&&g&&(b=createPromise((function(g,f){A=g,P=f}))),!R)return _onNoPayloadUrl(S),void(A&&A(!1));function _handleError(g){_doOnComplete(S,v?0:400,{},v?ta:g)}function _onFetchComplete(g,f,v){var _=g[nn],T=C.fetchOnComplete;T&&be(T)?T(g,S,v||ta,f):_doOnComplete(S,_,{},v||ta)}try{doAwaitResponse(fetch(v?R:H,v?B:null),(function(g){if(_&&(O-=F,F=0),!U)if(U=!0,g.rejected)_handleError(g.reason&&g.reason[Hi]),P&&P(g.reason);else{var S=g[Ti];try{v||S.ok?v&&!S.body?(_onFetchComplete(S,null,ta),A&&A(!0)):doAwaitResponse(S.text(),(function(g){_onFetchComplete(S,f,g[Ti]),A&&A(!0)})):(_handleError(S.statusText),A&&A(!1))}catch(g){_handleError(dumpObj(g)),P&&P(g)}}}))}catch(g){U||(_handleError(dumpObj(g)),P&&P(g))}return x&&!U&&(U=!0,_doOnComplete(S,200,{}),A&&A(!0)),v&&!U&&f[pn]>0&&w&&w.set((function(){U||(U=!0,_doOnComplete(S,500,{}),A&&A(!0))}),f[pn]),b}function _xdrSender(g,f,_){var T=rt(),I=new XDomainRequest,b=g[on];I.onload=function(){var S=getResponseText(I),v=C&&C.xdrOnComplete;v&&be(v)?v(I,f,g):_doOnComplete(f,200,{},S)},I.onerror=function(){_doOnComplete(f,400,{},v?ta:formatErrorMessageXdr(I))},I.ontimeout=function(){_doOnComplete(f,500,{})},I.onprogress=function(){};var A=T&&T.location&&T.location[Ki]||"",P=g[hn];if(P){if(!v&&0!==P.lastIndexOf(A,0)){var R="Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.";return _throwInternal(S,2,40,". "+R),void _onError(R,f)}var M=v?P:P[Xi](/^(https?:)/,"");I.open(na,M),g[pn]&&(I[pn]=g[pn]),I.send(b),v&&_?w&&w.set((function(){I.send(b)}),0):I.send(b)}else _onNoPayloadUrl(f)}function _initDefaults(){O=0,f=!1,g=!1,S=null,v=null,C=null,_=null,T=null,I=null,b=!1,A=!1,P=!1,R=!1,M=!1,w=null}_initDefaults(),D[fi]=function(g,v){S=v,f&&_throwInternal(S,1,28,"Sender is already initialized"),D.SetConfig(g),f=!0},D._getDbgPlgTargets=function(){return[f,v,_,g]},D.SetConfig=function(f){try{if(C=f.senderOnCompleteCallBack||{},_=!!f.disableCredentials,T=f.fetchCredentials,v=!!f.isOneDs,g=!!f.enableSendPromise,b=!!f.disableXhr,A=!!f.disableBeacon,P=!!f.disableBeaconSync,w=f.timeWrapper,M=!!f.addNoResponse,R=!!f.disableFetchKeepAlive,I={sendPOST:_xhrSender},v||(k=!1),_){var S=getLocation();S&&S.protocol&&"file:"===S.protocol[ti]()&&(k=!1)}return!0}catch(g){}return!1},D.getSyncFetchPayload=function(){return O},D.getSenderInst=function(g,f){return g&&g[ni]?_getSenderInterface(g,f):null},D.getFallbackInst=function(){return I},D[Gi]=function(g,f){_initDefaults()}}))}return SenderPostManager.__ieDyn=1,SenderPostManager}(),sa="on",aa="attachEvent",oa="addEventListener",la="detachEvent",ca="removeEventListener",da="events",ha="visibilitychange",ua="pagehide",ga="pageshow",pa="unload",ma="beforeunload",fa=createUniqueNamespace("aiEvtPageHide"),Sa=createUniqueNamespace("aiEvtPageShow"),va=/\.[\.]+/g,Ca=/[\.]+$/,ya=1,Ea=createElmNodeData("events"),_a=/^([^.]*)(?:\.(.+)|)/;function _normalizeNamespace(g){return g&&g[Xi]?g[Xi](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g,Gn):g}function _getEvtNamespace(g,f){var S;if(f){var v=Gn;Ae(f)?(v=Gn,arrForEach(f,(function(g){(g=_normalizeNamespace(g))&&("."!==g[0]&&(g="."+g),v+=g)}))):v=_normalizeNamespace(f),v&&("."!==v[0]&&(v="."+v),g=(g||Gn)+v)}var C=_a.exec(g||Gn)||[];return(S={})[en]=C[1],S.ns=(C[2]||Gn).replace(va,".").replace(Ca,Gn)[Yi](".").sort().join("."),S}function _getRegisteredEvents(g,f,S){void 0===S&&(S=!0);var v=Ea.get(g,da,{},S),C=v[f];return C||(C=v[f]=[]),C}function _doDetach(g,f,S,v){g&&f&&f[en]&&(g[ca]?g[ca](f[en],S,v):g[la]&&g[la](sa+f[en],S))}function _doAttach(g,f,S,v){var C=!1;return g&&f&&f[en]&&S&&(g[oa]?(g[oa](f[en],S,v),C=!0):g[aa]&&(g[aa](sa+f[en],S),C=!0)),C}function _doUnregister(g,f,S,v){for(var C=f[ni];C--;){var _=f[C];_&&(S.ns&&S.ns!==_.evtName.ns||v&&!v(_)||(_doDetach(g,_.evtName,_[tn],_.capture),f[gi](C,1)))}}function _unregisterEvents(g,f,S){if(f[en])_doUnregister(g,_getRegisteredEvents(g,f[en]),f,S);else{var v=Ea.get(g,da,{});objForEachKey(v,(function(v,C){_doUnregister(g,C,f,S)})),0===Be(v)[ni]&&Ea.kill(g,da)}}function mergeEvtNamespace(g,f){return f?_getEvtNamespace("xx",Ae(f)?[g].concat(f):[g,f]).ns[Yi]("."):g}function eventOn(g,f,S,v,C){var _;void 0===C&&(C=!1);var T=!1;if(g)try{var I=_getEvtNamespace(f,v);if((T=_doAttach(g,I,S,C))&&Ea.accept(g)){var b=((_={guid:ya++,evtName:I})[tn]=S,_.capture=C,_);_getRegisteredEvents(g,I.type)[ui](b)}}catch(g){}return T}function eventOff(g,f,S,v,C){if(void 0===C&&(C=!1),g)try{var _=_getEvtNamespace(f,v),T=!1;_unregisterEvents(g,_,(function(g){return!((!_.ns||S)&&g[tn]!==S)&&(T=!0,!0)})),T||_doDetach(g,_,S,C)}catch(g){}}function addEventHandler(g,f,S){var v=!1,C=rt();C&&(v=eventOn(C,g,f,S),v=eventOn(C.body,g,f,S)||v);var _=nt();return _&&(v=eventOn(_,g,f,S)||v),v}function removeEventHandler(g,f,S){var v=rt();v&&(eventOff(v,g,f,S),eventOff(v.body,g,f,S));var C=nt();C&&eventOff(C,g,f,S)}function _addEventListeners(g,f,S,v){var C=!1;return f&&g&&g[ni]>0&&arrForEach(g,(function(g){g&&(S&&-1!==dt(S,g)||(C=addEventHandler(g,f,v)||C))})),C}function addEventListeners(g,f,S,v){var C=!1;return f&&g&&Ae(g)&&!(C=_addEventListeners(g,f,S,v))&&S&&S[ni]>0&&(C=_addEventListeners(g,f,null,v)),C}function removeEventListeners(g,f,S){g&&Ae(g)&&arrForEach(g,(function(g){g&&removeEventHandler(g,f,S)}))}function addPageUnloadEventListener(g,f,S){return addEventListeners([ma,pa,ua],g,f,S)}function removePageUnloadEventListener(g,f){removeEventListeners([ma,pa,ua],g,f)}function addPageHideEventListener(g,f,S){function _handlePageVisibility(f){var S=nt();g&&S&&"hidden"===S.visibilityState&&g(f)}var v=mergeEvtNamespace(fa,S),C=_addEventListeners([ua],g,f,v);return f&&-1!==dt(f,ha)||(C=_addEventListeners([ha],_handlePageVisibility,f,v)||C),!C&&f&&(C=addPageHideEventListener(g,null,S)),C}function removePageHideEventListener(g,f){var S=mergeEvtNamespace(fa,f);removeEventListeners([ua],g,S),removeEventListeners([ha],null,S)}function addPageShowEventListener(g,f,S){function _handlePageVisibility(f){var S=nt();g&&S&&"visible"===S.visibilityState&&g(f)}var v=mergeEvtNamespace(Sa,S),C=_addEventListeners([ga],g,f,v);return!(C=_addEventListeners([ha],_handlePageVisibility,f,v)||C)&&f&&(C=addPageShowEventListener(g,null,S)),C}function removePageShowEventListener(g,f){var S=mergeEvtNamespace(Sa,f);removeEventListeners([ga],g,S),removeEventListeners([ha],null,S)}var Ta,Ia="",ba="https://browser.events.data.microsoft.com/OneCollector/1.0/",Aa="version",Pa="properties",Ra="initialize",Ma="logger",wa="indexOf",Oa="timings",Da="pollInternalLogs",Na="value",ka="kind",La="length",Fa="processTelemetryStart",xa="1DS-Web-JS-"+"4.3.2",Ua=Z.hasOwnProperty,Va=((Ta={})[0]=0,Ta[2]=6,Ta[1]=1,Ta[3]=7,Ta[4098]=6,Ta[4097]=1,Ta[4099]=7,Ta);function isValueAssigned(g){return!(g===Ia||isNullOrUndefined(g))}function getTenantId(g){if(g){var f=Et(g,"-");if(f>-1)return strLeft(g,f)}return Ia}function isLatency(g){return!!(g&&Re(g)&&g>=1&&g<=4)}function sanitizeProperty(g,f,S){if(!f&&!isValueAssigned(f)||"string"!=typeof g)return null;var v=typeof f;if("string"===v||"number"===v||"boolean"===v||Ae(f))f={value:f};else if("object"!==v||Ua.call(f,"value")){if(isNullOrUndefined(f[Na])||f[Na]===Ia||!Ie(f[Na])&&!Re(f[Na])&&!Me(f[Na])&&!Ae(f[Na]))return null}else f={value:S?JSON.stringify(f):f};if(Ae(f[Na])&&!isArrayValid(f[Na]))return null;if(!isNullOrUndefined(f[ka])){if(Ae(f[Na])||!isValueKind(f[ka]))return null;f[Na]=f[Na].toString()}return f}function getCommonSchemaMetaData(g,f,S){var v=-1;if(!isUndefined(g))if(f>0&&(32===f?v=8192:f<=13&&(v=f<<5)),isDataType(S))-1===v&&(v=0),v|=S;else{var C=Va[getFieldValueType(g)]||-1;-1!==v&&-1!==C?v|=C:6===C&&(v=C)}return v}function getCookieValue(g,f,S){var v;return void 0===S&&(S=!0),g&&(v=g.get(f),S&&v&&decodeURIComponent&&(v=decodeURIComponent(v))),v||Ia}function createGuid(g){void 0===g&&(g="D");var f=newGuid();return"B"===g?f="{"+f+"}":"P"===g?f="("+f+")":"N"===g&&(f=f.replace(/-/g,Ia)),f}function extend(g,f,S,v,C){var _={},T=!1,I=0,b=arguments[La],A=arguments;for(Me(A[0])&&(T=A[0],I++);I<b;I++){objForEachKey(A[I],(function(g,f){T&&f&&isObject(f)?Ae(f)?(_[g]=_[g]||[],arrForEach(f,(function(f,S){f&&isObject(f)?_[g][S]=extend(!0,_[g][S],f):_[g][S]=f}))):_[g]=extend(!0,_[g],f):_[g]=f}))}return _}var Ba=perfNow;function isValueKind(g){return 0===g||g>0&&g<=13||32===g}function isDataType(g){return g>=0&&g<=9}function isArrayValid(g){return g[La]>0}function setProcessTelemetryTimings(g,f){var S=g;S[Oa]=S[Oa]||{},S[Oa][Fa]=S[Oa][Fa]||{},S[Oa][Fa][f]=Ba()}function getFieldValueType(g){var f=0;if(null!=g){var S=typeof g;"string"===S?f=1:"number"===S?f=2:"boolean"===S?f=3:S===J&&(f=4,Ae(g)?(f=4096,g[La]>0&&(f|=getFieldValueType(g[0]))):Ua.call(g,"value")&&(f=8192|getFieldValueType(g[Na])))}return f}function isChromium(){return!!getInst("chrome")}function isGreaterThanZero(g){return g>0}var Ha=objDeepFreeze({endpointUrl:ba,propertyStorageOverride:{isVal:_chkPropOverride}});function _chkPropOverride(g){return!g||g.getProperty&&g.setProperty||throwError("Invalid property storage override passed."),!0}var $a,ja=function(g){function AppInsightsCore(){var f=g.call(this)||this;return dynamicProto(AppInsightsCore,f,(function(g,f){g[Ra]=function(S,v,C,_){doPerf(g,(function(){return"AppInsightsCore.initialize"}),(function(){try{f[Ra](createDynamicConfig(S,Ha,C||g[Ma],!1).cfg,v,C,_)}catch(f){var T=g[Ma],I=dumpObj(f);-1!==I[wa]("channels")&&(I+="\n - Channels must be provided through config.channels only!"),_throwInternal(T,1,514,"SDK Initialization Failed - no telemetry will be sent: "+I)}}),(function(){return{config:S,extensions:v,logger:C,notificationManager:_}}))},g.track=function(S){doPerf(g,(function(){return"AppInsightsCore.track"}),(function(){var v=S;if(v){v[Oa]=v[Oa]||{},v[Oa].trackStart=Ba(),isLatency(v.latency)||(v.latency=1);var C=v.ext=v.ext||{};C.sdk=C.sdk||{},C.sdk.ver=xa;var _=v.baseData=v.baseData||{};_[Pa]=_[Pa]||{};var T=_[Pa];T[Aa]=T[Aa]||g.pluginVersionString||Ia}f.track(v)}),(function(){return{item:S}}),!S.sync)},g[Da]=function(g){return f[Da](g||"InternalLog")}})),f}return __extendsFn(AppInsightsCore,g),AppInsightsCore.__ieDyn=1,AppInsightsCore}(ea),Ga=(Xt({NotSet:0,Pii_DistinguishedName:1,Pii_GenericData:2,Pii_IPV4Address:3,Pii_IPv6Address:4,Pii_MailSubject:5,Pii_PhoneNumber:6,Pii_QueryString:7,Pii_SipAddress:8,Pii_SmtpAddress:9,Pii_Identity:10,Pii_Uri:11,Pii_Fqdn:12,Pii_IPV4AddressLegacy:13,Pii_IPv6ScrubLastHextets:14,Pii_DropValue:15,CustomerContent_GenericContent:32}),Xt({Normal:1,CostDeferred:2,RealTime:3,Immediate:4})),qa=(Xt({Unspecified:0,String:1,Int32:2,UInt32:3,Int64:4,UInt64:5,Double:6,Bool:7,Guid:8,DateTime:9}),Xt({Normal:1,Critical:2}),Xt({NONE:0,ERROR:1,WARNING:2,INFORMATION:3}),"function"),Wa="object",za="undefined",Ka="prototype",Ja=Object,Ya=((getGlobal()||{}).Symbol,(getGlobal()||{}).Reflect,"hasOwnProperty"),extendStaticsFn$1=function(g,f){return extendStaticsFn$1=Ja.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f[Ya](S)&&(g[S]=f[S])},extendStaticsFn$1(g,f)};function __extendsFn$1(g,f){function __(){this.constructor=g}typeof f!==qa&&null!==f&&throwTypeError("Class extends value "+String(f)+" is not a constructor or null"),extendStaticsFn$1(g,f),g[Ka]=null===f?ut(f):(__[Ka]=f[Ka],new __)}var Qa="constructor",Xa="prototype",Za="function",eo="_dynInstFuncs",to="_isDynProxy",io="_dynClass",no="_dynCls$",ro="_dynInstChk",so=ro,ao="_dfOpts",oo="_unknown_",lo="__proto__",co="_dyn"+lo,ho="__dynProto$Gbl",uo="_dynInstProto",go="useBaseInst",po="setInstFuncs",mo=Object,fo=mo.getPrototypeOf,So=mo.getOwnPropertyNames,vo=getGlobal(),Co=vo[ho]||(vo[ho]={o:($a={},$a[po]=!0,$a[go]=!0,$a),n:1e3});function _isObjectOrArrayPrototype$1(g){return g&&(g===mo[Xa]||g===Array[Xa])}function _isObjectArrayOrFunctionPrototype$1(g){return _isObjectOrArrayPrototype$1(g)||g===Function[Xa]}function _getObjProto$1(g){var f;if(g){if(fo)return fo(g);var S=g[lo]||g[Xa]||(g[Qa]?g[Qa][Xa]:null);f=g[co]||S,objHasOwnProperty(g,co)||(delete g[uo],f=g[co]=g[uo]||g[co],g[uo]=S)}return f}function _forEachProp$1(g,f){var S=[];if(So)S=So(g);else for(var v in g)"string"==typeof v&&objHasOwnProperty(g,v)&&S.push(v);if(S&&S.length>0)for(var C=0;C<S.length;C++)f(S[C])}function _isDynamicCandidate$1(g,f,S){return f!==Qa&&typeof g[f]===Za&&(S||objHasOwnProperty(g,f))&&f!==lo&&f!==Xa}function _throwTypeError$1(g){throwTypeError("DynamicProto: "+g)}function _getInstanceFuncs$1(g){var f=ut(null);return _forEachProp$1(g,(function(S){!f[S]&&_isDynamicCandidate$1(g,S,!1)&&(f[S]=g[S])})),f}function _hasVisited$1(g,f){for(var S=g.length-1;S>=0;S--)if(g[S]===f)return!0;return!1}function _getBaseFuncs$1(g,f,S,v){function _instFuncProxy(g,f,S){var C=f[S];if(C[to]&&v){var _=g[eo]||{};!1!==_[so]&&(C=(_[f[io]]||{})[S]||C)}return function(){return C.apply(g,arguments)}}var C=ut(null);_forEachProp$1(S,(function(g){C[g]=_instFuncProxy(f,S,g)}));for(var _=_getObjProto$1(g),T=[];_&&!_isObjectArrayOrFunctionPrototype$1(_)&&!_hasVisited$1(T,_);)_forEachProp$1(_,(function(g){!C[g]&&_isDynamicCandidate$1(_,g,!fo)&&(C[g]=_instFuncProxy(f,_,g))})),T.push(_),_=_getObjProto$1(_);return C}function _getInstFunc$1(g,f,S,v){var C=null;if(g&&objHasOwnProperty(S,io)){var _=g[eo]||ut(null);if((C=(_[S[io]]||ut(null))[f])||_throwTypeError$1("Missing ["+f+"] "+Za),!C[ro]&&!1!==_[so]){for(var T=!objHasOwnProperty(g,f),I=_getObjProto$1(g),b=[];T&&I&&!_isObjectArrayOrFunctionPrototype$1(I)&&!_hasVisited$1(b,I);){var A=I[f];if(A){T=A===v;break}b.push(I),I=_getObjProto$1(I)}try{T&&(g[f]=C),C[ro]=1}catch(g){_[so]=!1}}}return C}function _getProtoFunc$1(g,f,S){var v=f[g];return v===S&&(v=_getObjProto$1(f)[g]),typeof v!==Za&&_throwTypeError$1("["+g+"] is not a "+Za),v}function _populatePrototype$1(g,f,S,v,C){function _createDynamicPrototype(g,f){var dynProtoProxy=function(){return(_getInstFunc$1(this,f,g,dynProtoProxy)||_getProtoFunc$1(f,g,dynProtoProxy)).apply(this,arguments)};return dynProtoProxy[to]=1,dynProtoProxy}if(!_isObjectOrArrayPrototype$1(g)){var _=S[eo]=S[eo]||ut(null);if(!_isObjectOrArrayPrototype$1(_)){var T=_[f]=_[f]||ut(null);!1!==_[so]&&(_[so]=!!C),_isObjectOrArrayPrototype$1(T)||_forEachProp$1(S,(function(f){_isDynamicCandidate$1(S,f,!1)&&S[f]!==v[f]&&(T[f]=S[f],delete S[f],(!objHasOwnProperty(g,f)||g[f]&&!g[f][to])&&(g[f]=_createDynamicPrototype(g,f)))}))}}}function _checkPrototype$1(g,f){if(fo){for(var S=[],v=_getObjProto$1(f);v&&!_isObjectArrayOrFunctionPrototype$1(v)&&!_hasVisited$1(S,v);){if(v===g)return!0;S.push(v),v=_getObjProto$1(v)}return!1}return!0}function _getObjName$1(g,f){return objHasOwnProperty(g,Xa)?g.name||f||oo:((g||{})[Qa]||{}).name||f||oo}function dynamicProto$1(g,f,S,v){objHasOwnProperty(g,Xa)||_throwTypeError$1("theClass is an invalid class definition.");var C=g[Xa];_checkPrototype$1(C,f)||_throwTypeError$1("["+_getObjName$1(g)+"] not in hierarchy of ["+_getObjName$1(f)+"]");var _=null;objHasOwnProperty(C,io)?_=C[io]:(_=no+_getObjName$1(g,"_")+"$"+Co.n,Co.n++,C[io]=_);var T=dynamicProto$1[ao],I=!!T[go];I&&v&&void 0!==v[go]&&(I=!!v[go]);var b=_getInstanceFuncs$1(f);S(f,_getBaseFuncs$1(C,f,b,I));var A=!!fo&&!!T[po];A&&v&&(A=!!v[po]),_populatePrototype$1(C,_,f,b,!1!==A)}dynamicProto$1[ao]=Co.o;var yo,Eo="toLowerCase",_o="blkVal",To="length",Io="rdOnly",bo="notify",Ao="warnToConsole",Po="throwInternal",Ro="setDf",Mo="watch",wo="logger",Oo="apply",Do="push",No="splice",ko="hdlr",Lo="cancel",Fo="initialize",xo="identifier",Uo="isInitialized",Vo="getPlugin",Bo="name",Ho="time",$o="processNext",jo="getProcessTelContext",Go="unload",qo="loggingLevelConsole",Wo="createNew",zo="teardown",Ko="messageId",Jo="message",Yo="isAsync",Qo="diagLog",Xo="_doTeardown",Zo="update",el="getNext",tl="setNextPlugin",il="userAgent",nl="nodeType",rl="replace",sl="logInternalMessage",al="isChildEvt",ol="getCtx",ll="setCtx",cl="complete";function throwAggregationError$1(g,f){yo||(yo=createCustomError("AggregationError",(function(g,f){f[To]>1&&(g.errors=f[1])})));var S=g||"One or more errors occurred.";throw arrForEach(f,(function(g,f){S+="\n".concat(f," > ").concat(dumpObj(g))})),new yo(S,f||[])}var dl=void 0,hl="",ul="core",gl="disabled",pl="extensionConfig",ml="processTelemetry",fl="priority",Sl="getPerfMgr",vl="Not dynamic - ",Cl=/-([a-z])/g,yl=/([^\w\d_$])/g,El=/^(\d+[\w\d_$])/;function isNotNullOrUndefined$1(g){return!isNullOrUndefined(g)}function normalizeJsName$1(g){var f=g;return f&&Ie(f)&&(f=(f=(f=f[rl](Cl,(function(g,f){return f.toUpperCase()})))[rl](yl,"_"))[rl](El,(function(g,f){return"_"+f}))),f}function strContains$1(g,f){return!(!g||!f)&&-1!==Et(g,f)}function toISOString$1(g){return g&&g.toISOString()||""}function _createProxyFunction$1(g,f){var S=null,v=null;return be(g)?S=g:v=g,function(){var g=arguments;if(S&&(v=S()),v)return v[f][Oo](v,g)}}function proxyFunctionAs$1(g,f,S,v,C){g&&f&&S&&(!1!==C||isUndefined(g[f]))&&(g[f]=_createProxyFunction$1(S,v))}var _l="console",Tl="JSON",Il="crypto",bl="msCrypto",Al="msie",Pl="trident/",Rl=null,Ml=null;function getConsole$1(){return typeof console!==za?console:getInst(_l)}function hasJSON$1(){return Boolean(typeof JSON===Wa&&JSON||null!==getInst(Tl))}function getJSON$1(){return hasJSON$1()?JSON||getInst(Tl):null}function getCrypto$1(){return getInst(Il)}function getMsCrypto$1(){return getInst(bl)}function isIE$1(){var g=lt();if(g&&(g[il]!==Ml||null===Rl)){var f=((Ml=g[il])||hl)[Eo]();Rl=strContains$1(f,Al)||strContains$1(f,Pl)}return Rl}var wl=4294967296,Ol=4294967295,Dl=123456789,Nl=987654321,kl=!1,Ll=Dl,Fl=Nl;function _mwcSeed$1(g){g<0&&(g>>>=0),Ll=Dl+g&Ol,Fl=Nl-g&Ol,kl=!0}function _autoSeedMwc$1(){try{var g=2147483647&utcNow();_mwcSeed$1((Math.random()*wl^g)+g)}catch(g){}}function random32$1(g){var f=0,S=getCrypto$1()||getMsCrypto$1();return S&&S.getRandomValues&&(f=S.getRandomValues(new Uint32Array(1))[0]&Ol),0===f&&isIE$1()&&(kl||_autoSeedMwc$1(),f=mwcRandom32$1()&Ol),0===f&&(f=Math.floor(wl*Math.random()|0)),g||(f>>>=0),f}function mwcRandom32$1(g){var f=((Fl=36969*(65535&Fl)+(Fl>>16)&Ol)<<16)+(65535&(Ll=18e3*(65535&Ll)+(Ll>>16)&Ol))>>>0&Ol|0;return g||(f>>>=0),f}function newId$1(g){void 0===g&&(g=22);for(var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S=random32$1()>>>0,v=0,C=hl;C[To]<g;)v++,C+=f.charAt(63&S),S>>>=6,5===v&&(S=(random32$1()<<2&4294967295|3&S)>>>0,v=0);return C}var xl="3.3.1",Ul="."+newId$1(6),Vl=0;function _canAcceptData$1(g){return 1===g[nl]||9===g[nl]||!+g[nl]}function _getCache$1(g,f){var S=f[g.id];if(!S){S={};try{_canAcceptData$1(f)&&objDefine(f,g.id,{e:!1,v:S})}catch(g){}}return S}function createUniqueNamespace$1(g,f){return void 0===f&&(f=!1),normalizeJsName$1(g+Vl+++(f?"."+xl:hl)+Ul)}function createElmNodeData$1(g){var f={id:createUniqueNamespace$1("_aiData-"+(g||hl)+"."+xl),accept:function(g){return _canAcceptData$1(g)},get:function(g,S,v,C){var _=g[f.id];return _?_[normalizeJsName$1(S)]:(C&&((_=_getCache$1(f,g))[normalizeJsName$1(S)]=v),v)},kill:function(g,f){if(g&&g[f])try{delete g[f]}catch(g){}}};return f}function _isConfigDefaults$1(g){return g&&isObject(g)&&(g.isVal||g.fb||De(g,"v")||De(g,"mrg")||De(g,"ref")||g.set)}function _getDefault$1(g,f,S){var v,C=S.dfVal||isDefined;if(f&&S.fb){var _=S.fb;Ae(_)||(_=[_]);for(var T=0;T<_[To];T++){var I=_[T],b=f[I];if(C(b)?v=b:g&&(C(b=g.cfg[I])&&(v=b),g.set(g.cfg,Fe(I),b)),C(v))break}}return!C(v)&&C(S.v)&&(v=S.v),v}function _resolveDefaultValue$1(g,f,S){var v,C=S;(S&&_isConfigDefaults$1(S)&&(C=_getDefault$1(g,f,S)),C)&&(_isConfigDefaults$1(C)&&(C=_resolveDefaultValue$1(g,f,C)),Ae(C)?(v=[])[To]=C[To]:isPlainObject(C)&&(v={}),v&&(objForEachKey(C,(function(S,C){C&&_isConfigDefaults$1(C)&&(C=_resolveDefaultValue$1(g,f,C)),v[S]=C})),C=v));return C}function _applyDefaultValue$1(g,f,S,v){var C,_,T,I,b,A,P,R,M=v;_isConfigDefaults$1(M)?(C=M.isVal,_=M.set,A=M[Io],P=M[_o],I=M.mrg,!(b=M.ref)&&isUndefined(b)&&(b=!!I),T=_getDefault$1(g,f,M)):T=v,P&&g[_o](f,S);var w=!0,O=f[S];!O&&isNullOrUndefined(O)||(R=O,w=!1,C&&R!==T&&!C(R)&&(R=T,w=!0),_&&(w=(R=_(R,T,f))===T)),w?R=T?_resolveDefaultValue$1(g,f,T):T:(isPlainObject(R)||Ae(T))&&I&&T&&(isPlainObject(T)||Ae(T))&&objForEachKey(T,(function(f,S){_applyDefaultValue$1(g,R,f,S)})),g.set(f,S,R),b&&g.ref(f,S),A&&g[Io](f,S)}var Bl=symbolFor("[[ai_dynCfg_1]]"),Hl=symbolFor("[[ai_blkDynCfg_1]]"),$l=symbolFor("[[ai_frcDynCfg_1]]");function _cfgDeepCopy$1(g){var f;if(g&&(Ae(g)?(f=[])[To]=g[To]:isPlainObject(g)&&(f={}),f))return objForEachKey(g,(function(g,S){f[g]=_cfgDeepCopy$1(S)})),f;return g}function getDynamicConfigHandler$1(g){if(g){var f=g[Bl]||g;if(f.cfg&&(f.cfg===g||f.cfg[Bl]===f))return f}return null}function blockDynamicConversion$1(g){if(g&&(isPlainObject(g)||Ae(g)))try{g[Hl]=!0}catch(g){}return g}function _canMakeDynamic$1(g,f,S){var v=!1;return S&&!g[f.blkVal]&&((v=S[$l])||S[Hl]||(v=isPlainObject(S)||Ae(S))),v}function throwInvalidAccess$1(g){throwTypeError("InvalidAccess:"+g)}var jl=["push","pop","shift","unshift","splice"],_throwDynamicError$1=function(g,f,S,v){g&&g[Po](3,108,"".concat(S," [").concat(f,"] failed - ")+dumpObj(v))};function _patchArray$1(g,f,S){Ae(f)&&arrForEach(jl,(function(v){var C=f[v];f[v]=function(){for(var v=[],_=0;_<arguments.length;_++)v[_]=arguments[_];var T=C[Oo](this,v);return _makeDynamicObject$1(g,f,S,"Patching"),T}}))}function _getOwnPropGetter$1(g,f){var S=Oe(g,f);return S&&S.get}function _createDynamicProperty$1(g,f,S,v){var C={n:S,h:[],trk:function(f){f&&f.fn&&(-1===dt(C.h,f)&&C.h[Do](f),g.trk(f,C))},clr:function(g){var f=dt(C.h,g);-1!==f&&C.h[No](f,1)}},_=!0,T=!1;function _getProperty(){_&&(T=T||_canMakeDynamic$1(_getProperty,g,v),v&&!v[Bl]&&T&&(v=_makeDynamicObject$1(g,v,S,"Converting")),_=!1);var f=g.act;return f&&C.trk(f),v}function _setProperty(I){if(v!==I){_getProperty[g.ro]&&!g.upd&&throwInvalidAccess$1("["+S+"] is read-only:"+dumpObj(f)),_&&(T=T||_canMakeDynamic$1(_getProperty,g,v),_=!1);var b=T&&_getProperty[g.rf];if(T)if(b){objForEachKey(v,(function(g){v[g]=I?I[g]:dl}));try{objForEachKey(I,(function(f,S){_setDynamicProperty$1(g,v,f,S)})),I=v}catch(f){_throwDynamicError$1((g.hdlr||{})[wo],S,"Assigning",f),T=!1}}else v&&v[Bl]&&objForEachKey(v,(function(f){var S=_getOwnPropGetter$1(v,f);if(S){var C=S[g.prop];C&&C.chng()}}));if(I!==v){var A=I&&_canMakeDynamic$1(_getProperty,g,I);!b&&A&&(I=_makeDynamicObject$1(g,I,S,"Converting")),v=I,T=A}g.add(C)}}_getProperty[g.prop]={chng:function(){g.add(C)}},objDefine(f,C.n,{g:_getProperty,s:_setProperty})}function _setDynamicProperty$1(g,f,S,v){if(f){var C=_getOwnPropGetter$1(f,S);C&&!!C[g.prop]?f[S]=v:_createDynamicProperty$1(g,f,S,v)}return f}function _setDynamicPropertyState$1(g,f,S,v){if(f){var C=_getOwnPropGetter$1(f,S),_=C&&!!C[g.prop],T=v&&v[0],I=v&&v[1],b=v&&v[2];if(!_){if(b)try{blockDynamicConversion$1(f)}catch(f){_throwDynamicError$1((g.hdlr||{})[wo],S,"Blocking",f)}try{_setDynamicProperty$1(g,f,S,f[S]),C=_getOwnPropGetter$1(f,S)}catch(f){_throwDynamicError$1((g.hdlr||{})[wo],S,"State",f)}}T&&(C[g.rf]=T),I&&(C[g.ro]=I),b&&(C[g.blkVal]=!0)}return f}function _makeDynamicObject$1(g,f,S,v){try{objForEachKey(f,(function(S,v){_setDynamicProperty$1(g,f,S,v)})),f[Bl]||(ke(f,Bl,{get:function(){return g[ko]}}),_patchArray$1(g,f,S))}catch(f){_throwDynamicError$1((g.hdlr||{})[wo],S,v,f)}return f}var Gl="[[ai_",ql="]]";function _createState$1(g){var f,S,v=newSymbol(Gl+"get"+g.uid+ql),C=newSymbol(Gl+"ro"+g.uid+ql),_=newSymbol(Gl+"rf"+g.uid+ql),T=newSymbol(Gl+"blkVal"+g.uid+ql),I=newSymbol(Gl+"dtl"+g.uid+ql),b=null,A=null;function _useHandler(f,v){var C=S.act;try{S.act=f,f&&f[I]&&(arrForEach(f[I],(function(g){g.clr(f)})),f[I]=[]),v({cfg:g.cfg,set:g.set.bind(g),setDf:g[Ro].bind(g),ref:g.ref.bind(g),rdOnly:g[Io].bind(g)})}catch(f){var _=g[wo];throw _&&_[Po](1,107,dumpObj(f)),f}finally{S.act=C||null}}function _notifyWatchers(){if(b){var g=b;b=null,A&&A[Lo](),A=null;var f=[];if(arrForEach(g,(function(g){if(g&&(g[I]&&(arrForEach(g[I],(function(f){f.clr(g)})),g[I]=null),g.fn))try{_useHandler(g,g.fn)}catch(g){f[Do](g)}})),b)try{_notifyWatchers()}catch(g){f[Do](g)}f[To]>0&&throwAggregationError$1("Watcher error(s): ",f)}}function _addWatcher(g){if(g&&g.h[To]>0){b||(b=[]),A||(A=scheduleTimeout((function(){A=null,_notifyWatchers()}),0));for(var f=0;f<g.h[To];f++){var S=g.h[f];S&&-1===dt(b,S)&&b[Do](S)}}}function _trackHandler(g,f){if(g){var S=g[I]=g[I]||[];-1===dt(S,f)&&S[Do](f)}}return(f={prop:v,ro:C,rf:_})[_o]=T,f[ko]=g,f.add=_addWatcher,f[bo]=_notifyWatchers,f.use=_useHandler,f.trk=_trackHandler,S=f}function _createAndUseHandler$1(g,f){var S={fn:f,rm:function(){S.fn=null,g=null,f=null}};return objDefine(S,"toJSON",{v:function(){return"WatcherHandler"+(S.fn?"":"[X]")}}),g.use(S,f),S}function _createDynamicHandler$1(g,f,S){var v,C=getDynamicConfigHandler$1(f);if(C)return C;var _,T=createUniqueNamespace$1("dyncfg",!0),I=f&&!1!==S?f:_cfgDeepCopy$1(f);function _notifyWatchers(){_[bo]()}function _setValue(f,S,v){try{f=_setDynamicProperty$1(_,f,S,v)}catch(f){_throwDynamicError$1(g,S,"Setting value",f)}return f[S]}function _watch(g){return _createAndUseHandler$1(_,g)}function _block(g,f){_.use(null,(function(S){var v=_.upd;try{isUndefined(f)||(_.upd=f),g(S)}finally{_.upd=v}}))}function _ref(g,f){var S;return _setDynamicPropertyState$1(_,g,f,(S={},S[0]=!0,S))[f]}function _rdOnly(g,f){var S;return _setDynamicPropertyState$1(_,g,f,(S={},S[1]=!0,S))[f]}function _blkPropValue(g,f){var S;return _setDynamicPropertyState$1(_,g,f,(S={},S[2]=!0,S))[f]}function _applyDefaults(g,f){return f&&objForEachKey(f,(function(f,S){_applyDefaultValue$1(b,g,f,S)})),g}var b=((v={uid:null,cfg:I})[wo]=g,v[bo]=_notifyWatchers,v.set=_setValue,v[Ro]=_applyDefaults,v[Mo]=_watch,v.ref=_ref,v[Io]=_rdOnly,v[_o]=_blkPropValue,v._block=_block,v);return objDefine(b,"uid",{c:!1,e:!1,w:!1,v:T}),_makeDynamicObject$1(_=_createState$1(b),I,"config","Creating"),b}function _logInvalidAccess$1(g,f){g?(g[Ao](f),g[Po](2,108,f)):throwInvalidAccess$1(f)}function createDynamicConfig$1(g,f,S,v){var C=_createDynamicHandler$1(S,g||{},v);return f&&C[Ro](C.cfg,f),C}function onConfigChange$1(g,f,S){var v=g[Bl]||g;return!v.cfg||v.cfg!==g&&v.cfg[Bl]!==v?(_logInvalidAccess$1(S,vl+dumpObj(g)),createDynamicConfig$1(g,null,S)[Mo](f)):v[Mo](f)}var Wl,zl=null;function _getExtensionNamespace$1(){var g=getInst("Microsoft");return g&&(zl=g.ApplicationInsights),zl}function getDebugExt$1(g){var f=zl;return f||!0===g.disableDbgExt||(f=zl||_getExtensionNamespace$1()),f?f.ChromeDbgExt:null}var Kl="warnToConsole",Jl="AI (Internal): ",Yl="AI: ",Ql="AITR_",Xl={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},Zl=((Wl={})[0]=null,Wl[1]="errorToConsole",Wl[2]=Kl,Wl[3]="debugToConsole",Wl);function _sanitizeDiagnosticText$1(g){return g?'"'+g[rl](/\"/g,hl)+'"':hl}function _logToConsole$1(g,f){var S=getConsole$1();if(S){var v="log";S[g]&&(v=g),be(S[v])&&S[v](f)}}var ec=function(){function _InternalLogMessage(g,f,S,v){void 0===S&&(S=!1);var C=this;C[Ko]=g,C[Jo]=(S?Yl:Jl)+g;var _=hl;hasJSON$1()&&(_=getJSON$1().stringify(v));var T=(f?" message:"+_sanitizeDiagnosticText$1(f):hl)+(v?" props:"+_sanitizeDiagnosticText$1(_):hl);C[Jo]+=T}return _InternalLogMessage.dataType="MessageData",_InternalLogMessage}();function safeGetLogger$1(g,f){return(g||{})[wo]||new tc(f)}var tc=function(){function DiagnosticLogger(g){this.identifier="DiagnosticLogger",this.queue=[];var f,S,v,C,_,T=0,I={};dynamicProto$1(DiagnosticLogger,this,(function(b){function _logInternalMessage(g,f){if(!_areInternalMessagesThrottled()){var C=!0,_=Ql+f[Ko];if(I[_]?C=!1:I[_]=!0,C&&(g<=S&&(b.queue[Do](f),T++,_debugExtMsg(1===g?"error":"warn",f)),T===v)){var A="Internal events throttle limit per PageView reached for this app.",P=new ec(23,A,!1);b.queue[Do](P),1===g?b.errorToConsole(A):b[Ao](A)}}}function _setDefaultsFromConfig(g){return onConfigChange$1(createDynamicConfig$1(g,Xl,b).cfg,(function(g){var _=g.cfg;f=_[qo],S=_.loggingLevelTelemetry,v=_.maxMessageLimit,C=_.enableDebug}))}function _areInternalMessagesThrottled(){return T>=v}function _debugExtMsg(f,S){var v=getDebugExt$1(g||{});v&&v[Qo]&&v[Qo](f,S)}_=_setDefaultsFromConfig(g||{}),b.consoleLoggingLevel=function(){return f},b[Po]=function(g,S,v,_,T){void 0===T&&(T=!1);var A=new ec(S,v,T,_);if(C)throw dumpObj(A);var P=Zl[g]||Kl;if(isUndefined(A[Jo]))_debugExtMsg("throw"+(1===g?"Critical":"Warning"),A);else{if(T){var R=+A[Ko];!I[R]&&f>=g&&(b[P](A[Jo]),I[R]=!0)}else f>=g&&b[P](A[Jo]);_logInternalMessage(g,A)}},b.debugToConsole=function(g){_logToConsole$1("debug",g),_debugExtMsg("warning",g)},b[Ao]=function(g){_logToConsole$1("warn",g),_debugExtMsg("warning",g)},b.errorToConsole=function(g){_logToConsole$1("error",g),_debugExtMsg("error",g)},b.resetInternalMessageCount=function(){T=0,I={}},b[sl]=_logInternalMessage,b[Go]=function(g){_&&_.rm(),_=null}}))}return DiagnosticLogger.__ieDyn=1,DiagnosticLogger}();function _getLogger$1(g){return g||new tc}function _throwInternal$1(g,f,S,v,C,_){void 0===_&&(_=!1),_getLogger$1(g)[Po](f,S,v,C,_)}var ic="ctx",nc="ParentContextKey",rc="ChildrenContextKey",sc=function(){function PerfEvent(g,f,S){var v,C=this;(C.start=utcNow(),C[Bo]=g,C[Yo]=S,C[al]=function(){return!1},be(f))&&objDefine(C,"payload",{g:function(){return!v&&be(f)&&(v=f(),f=null),v}});C[ol]=function(g){return g?g===PerfEvent[nc]||g===PerfEvent[rc]?C[g]:(C[ic]||{})[g]:null},C[ll]=function(g,f){if(g)if(g===PerfEvent[nc])C[g]||(C[al]=function(){return!0}),C[g]=f;else if(g===PerfEvent[rc])C[g]=f;else{(C[ic]=C[ic]||{})[g]=f}},C[cl]=function(){var g=0,f=C[ol](PerfEvent[rc]);if(Ae(f))for(var S=0;S<f[To];S++){var v=f[S];v&&(g+=v[Ho])}C[Ho]=utcNow()-C.start,C.exTime=C[Ho]-g,C[cl]=function(){}}}return PerfEvent.ParentContextKey="parent",PerfEvent.ChildrenContextKey="childEvts",PerfEvent}(),ac="CoreUtils.doPerf";function doPerf$1(g,f,S,v,C){if(g){var _=g;if(_[Sl]&&(_=_[Sl]()),_){var T=void 0,I=_[ol](ac);try{if(T=_.create(f(),v,C)){if(I&&T[ll]&&(T[ll](sc[nc],I),I[ol]&&I[ll])){var b=I[ol](sc[rc]);b||(b=[],I[ll](sc[rc],b)),b[Do](T)}return _[ll](ac,T),S(T)}}catch(g){T&&T[ll]&&T[ll]("exception",g)}finally{T&&_.fire(T),_[ll](ac,I)}}}return S()}function newGuid$1(){var g=generateW3CId$1();return Je(g,0,8)+"-"+Je(g,8,12)+"-"+Je(g,12,16)+"-"+Je(g,16,20)+"-"+Je(g,20)}function generateW3CId$1(){for(var g,f=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],S=hl,v=0;v<4;v++)S+=f[15&(g=random32$1())]+f[g>>4&15]+f[g>>8&15]+f[g>>12&15]+f[g>>16&15]+f[g>>20&15]+f[g>>24&15]+f[g>>28&15];var C=f[8+(3&random32$1())|0];return Ye(S,0,8)+Ye(S,9,4)+"4"+Ye(S,13,3)+C+Ye(S,16,3)+Ye(S,19,12)}var oc=createElmNodeData$1("plugin");function _getPluginState$1(g){return oc.get(g,"state",{},!0)}var lc,cc="TelemetryPluginChain",dc="_hasRun",hc="_getTelCtx",uc=0;function _getNextProxyStart$1(g,f,S){for(;g;){if(g[Vo]()===S)return g;g=g[el]()}return createTelemetryProxyChain$1([S],f.config||{},f)}function _createInternalContext$1(g,f,S,v){var C=null,_=[];f||(f=createDynamicConfig$1({},null,S[wo])),null!==v&&(C=v?_getNextProxyStart$1(g,S,v):g);var T={_next:_moveNext,ctx:{core:function(){return S},diagLog:function(){return safeGetLogger$1(S,f.cfg)},getCfg:function(){return f.cfg},getExtCfg:_resolveExtCfg,getConfig:_getConfig,hasNext:function(){return!!C},getNext:function(){return C},setNext:function(g){C=g},iterate:_iterateChain,onComplete:_addOnComplete}};function _addOnComplete(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];g&&_[Do]({func:g,self:isUndefined(f)?T.ctx:f,args:S})}function _moveNext(){var g=C;if(C=g?g[el]():null,!g){var f=_;f&&f[To]>0&&(arrForEach(f,(function(g){try{g.func.call(g.self,g.args)}catch(g){_throwInternal$1(S[wo],2,73,"Unexpected Exception during onComplete - "+dumpObj(g))}})),_=[])}return g}function _getExtCfg(g,S){var v=null,C=f.cfg;if(C&&g){var _=C[pl];!_&&S&&(_={}),C[pl]=_,(_=f.ref(C,pl))&&(!(v=_[g])&&S&&(v={}),_[g]=v,v=f.ref(_,g))}return v}function _resolveExtCfg(g,S){var v=_getExtCfg(g,!0);return S&&objForEachKey(S,(function(g,S){if(isNullOrUndefined(v[g])){var C=f.cfg[g];!C&&isNullOrUndefined(C)||(v[g]=C)}_applyDefaultValue$1(f,v,g,S)})),f[Ro](v,S)}function _getConfig(g,S,v){var C;void 0===v&&(v=!1);var _=_getExtCfg(g,!1),T=f.cfg;return!_||!_[S]&&isNullOrUndefined(_[S])?!T[S]&&isNullOrUndefined(T[S])||(C=T[S]):C=_[S],C||!isNullOrUndefined(C)?C:v}function _iterateChain(g){for(var f;f=T._next();){var S=f[Vo]();S&&g(S)}}return T}function createProcessTelemetryContext$1(g,f,S,v){var C=createDynamicConfig$1(f),_=_createInternalContext$1(g,C,S,v),T=_.ctx;function _processNext(g){var f=_._next();return f&&f[ml](g,T),!f}function _createNew(g,f){return void 0===g&&(g=null),Ae(g)&&(g=createTelemetryProxyChain$1(g,C.cfg,S,f)),createProcessTelemetryContext$1(g||T[el](),C.cfg,S,f)}return T[$o]=_processNext,T[Wo]=_createNew,T}function createProcessTelemetryUnloadContext$1(g,f,S){var v=createDynamicConfig$1(f.config),C=_createInternalContext$1(g,v,f,S),_=C.ctx;function _processNext(g){var f=C._next();return f&&f[Go](_,g),!f}function _createNew(g,S){return void 0===g&&(g=null),Ae(g)&&(g=createTelemetryProxyChain$1(g,v.cfg,f,S)),createProcessTelemetryUnloadContext$1(g||_[el](),f,S)}return _[$o]=_processNext,_[Wo]=_createNew,_}function createProcessTelemetryUpdateContext$1(g,f,S){var v=createDynamicConfig$1(f.config),C=_createInternalContext$1(g,v,f,S).ctx;function _processNext(g){return C.iterate((function(f){be(f[Zo])&&f[Zo](C,g)}))}function _createNew(g,S){return void 0===g&&(g=null),Ae(g)&&(g=createTelemetryProxyChain$1(g,v.cfg,f,S)),createProcessTelemetryUpdateContext$1(g||C[el](),f,S)}return C[$o]=_processNext,C[Wo]=_createNew,C}function createTelemetryProxyChain$1(g,f,S,v){var C=null,_=!v;if(Ae(g)&&g[To]>0){var T=null;arrForEach(g,(function(g){if(_||v!==g||(_=!0),_&&g&&be(g[ml])){var I=createTelemetryPluginProxy$1(g,f,S);C||(C=I),T&&T._setNext(I),T=I}}))}return v&&!C?createTelemetryProxyChain$1([v],f,S):C}function createTelemetryPluginProxy$1(g,f,S){var v,C=null,_=be(g[ml]),T=be(g[tl]),I={getPlugin:function(){return g},getNext:function(){return C},processTelemetry:_processTelemetry,unload:_unloadPlugin,update:_updatePlugin,_id:v=g?g[xo]+"-"+g[fl]+"-"+uc++:"Unknown-0-"+uc++,_setNext:function(g){C=g}};function _getTelCtx(){var v;return g&&be(g[hc])&&(v=g[hc]()),v||(v=createProcessTelemetryContext$1(I,f,S)),v}function _processChain(f,S,_,T,I){var b=!1,A=g?g[xo]:cc,P=f[dc];return P||(P=f[dc]={}),f.setNext(C),g&&doPerf$1(f[ul](),(function(){return A+":"+_}),(function(){P[v]=!0;try{var g=C?C._id:hl;g&&(P[g]=!1),b=S(f)}catch(g){var T=!C||P[C._id];T&&(b=!0),C&&T||_throwInternal$1(f[Qo](),1,73,"Plugin ["+A+"] failed during "+_+" - "+dumpObj(g)+", run flags: "+dumpObj(P))}}),T,I),b}function _processTelemetry(f,S){function _callProcessTelemetry(S){if(!g||!_)return!1;var v=_getPluginState$1(g);return!v[zo]&&!v[gl]&&(T&&g[tl](C),g[ml](f,S),!0)}_processChain(S=S||_getTelCtx(),_callProcessTelemetry,"processTelemetry",(function(){return{item:f}}),!f.sync)||S[$o](f)}function _unloadPlugin(f,S){function _callTeardown(){var v=!1;if(g){var C=_getPluginState$1(g),_=g[ul]||C[ul];!g||_&&_!==f.core()||C[zo]||(C[ul]=null,C[zo]=!0,C[Uo]=!1,g[zo]&&!0===g[zo](f,S)&&(v=!0))}return v}_processChain(f,_callTeardown,"unload",(function(){}),S[Yo])||f[$o](S)}function _updatePlugin(f,S){function _callUpdate(){var v=!1;if(g){var C=_getPluginState$1(g),_=g[ul]||C[ul];!g||_&&_!==f.core()||C[zo]||g[Zo]&&!0===g[Zo](f,S)&&(v=!0)}return v}_processChain(f,_callUpdate,"update",(function(){}),!1)||f[$o](S)}return He(I)}function createUnloadHandlerContainer$1(){var g=[];function _addHandler(f){f&&g[Do](f)}function _runHandlers(f,S){arrForEach(g,(function(g){try{g(f,S)}catch(g){_throwInternal$1(f[Qo](),2,73,"Unexpected error calling unload handler - "+dumpObj(g))}})),g=[]}return{add:_addHandler,run:_runHandlers}}function createUnloadHookContainer$1(){var g=[];function _doUnload(f){var S=g;g=[],arrForEach(S,(function(g){try{(g.rm||g.remove).call(g)}catch(g){_throwInternal$1(f,2,73,"Unloading:"+dumpObj(g))}}))}function _addHook(f){f&&arrAppend(g,f)}return{run:_doUnload,add:_addHook}}var gc,pc="getPlugin",mc=((lc={})[pl]={isVal:isNotNullOrUndefined$1,v:{}},lc),fc=function(){function BaseTelemetryPlugin(){var g,f,S,v,C,_=this;function _getTelCtx(g){void 0===g&&(g=null);var v=g;if(!v){var C=f||createProcessTelemetryContext$1(null,{},_[ul]);v=S&&S[pc]?C[Wo](null,S[pc]):C[Wo](null,S)}return v}function _setDefaults(g,v,C){createDynamicConfig$1(g,mc,safeGetLogger$1(v)),!C&&v&&(C=v[jo]()[el]());var T=S;S&&S[pc]&&(T=S[pc]()),_[ul]=v,f=createProcessTelemetryContext$1(C,g,v,T)}function _initDefaults(){g=!1,_[ul]=null,f=null,S=null,C=createUnloadHookContainer$1(),v=createUnloadHandlerContainer$1()}_initDefaults(),dynamicProto$1(BaseTelemetryPlugin,_,(function(f){f[Fo]=function(f,S,v,C){_setDefaults(f,S,C),g=!0},f[zo]=function(g,_){var T,I=f[ul];if(I&&(!g||I===g[ul]())){var b,A=!1,P=g||createProcessTelemetryUnloadContext$1(null,I,S&&S[pc]?S[pc]():S),R=_||((T={reason:0})[Yo]=!1,T);return f[Xo]&&!0===f[Xo](P,R,_unloadCallback)?b=!0:_unloadCallback(),b}function _unloadCallback(){A||(A=!0,v.run(P,_),C.run(P[Qo]()),!0===b&&P[$o](R),_initDefaults())}},f[Zo]=function(g,v){var C=f[ul];if(C&&(!g||C===g[ul]())){var _,T=!1,I=g||createProcessTelemetryUpdateContext$1(null,C,S&&S[pc]?S[pc]():S),b=v||{reason:0};return f._doUpdate&&!0===f._doUpdate(I,b,_updateCallback)?_=!0:_updateCallback(),_}function _updateCallback(){T||(T=!0,_setDefaults(I.getCfg(),I.core(),I[el]()))}},proxyFunctionAs$1(f,"_addUnloadCb",(function(){return v}),"add"),proxyFunctionAs$1(f,"_addHook",(function(){return C}),"add"),objDefine(f,"_unloadHooks",{g:function(){return C}})})),_[Qo]=function(g){return _getTelCtx(g)[Qo]()},_[Uo]=function(){return g},_.setInitialized=function(f){g=f},_[tl]=function(g){S=g},_[$o]=function(g,f){f?f[$o](g):S&&be(S[ml])&&S[ml](g,null)},_._getTelCtx=_getTelCtx}return BaseTelemetryPlugin.__ieDyn=1,BaseTelemetryPlugin}(),Sc="",vc="timings",Cc="processTelemetryStart";(gc={})[0]=0,gc[2]=6,gc[1]=1,gc[3]=7,gc[4098]=6,gc[4097]=1,gc[4099]=7;function getTenantId$1(g){if(g){var f=Et(g,"-");if(f>-1)return strLeft(g,f)}return Sc}var yc,Ec=perfNow;function setProcessTelemetryTimings$1(g,f){var S=g;S[vc]=S[vc]||{},S[vc][Cc]=S[vc][Cc]||{},S[vc][Cc][f]=Ec()}function isGreaterThanZero$1(g){return g>0}function isValidPersistenceLevel(g){return Re(g)&&g>=1&&g<=2}!function(g){g[g.LocalStorage=1]="LocalStorage",g[g.SessionStorage=2]="SessionStorage",g[g.IndexedDb=3]="IndexedDb"}(yc||(yc={}));var _c="readwrite",Tc="result",Ic="DBError: Unable to open database",bc="Database is not open",Ac="DBError: Failed to Open Cursor",Pc="DBError: Failed to delete the database",Rc="DBError: Database does not exist",Mc="DBError: Database upgrade required",wc="DBError: Feature not supported",Oc=["indexedDB"],Dc=be,Nc=Ie,kc=0;function _getDbFactory(){var g=getGlobal()||{},f=null;if(g)try{for(var S=0;S<Oc.length;S++)if((f=g[Oc[S]])&&Dc(f.open))return f}catch(g){f=null}return f||null}function _debugLog(g,f){getInst("QUnit")&&console&&console.log("  ["+toISOString$1(new Date)+"]: IndexedDbHelper ["+g+"] "+f)}function _warnLog(g,f,S){g&&g.warnToConsole("IndexedDbHelper ["+f+"] "+S)}function _eventReject(g,f,S,v){return function(C){S(new Error(f)),_debugLog(g,"["+v+"] event rejected")}}var Lc=[];function _getDbContext(g,f){for(var S=null,v=0;v<Lc.length;v++)if((S=Lc[v]).name===g)return S;return S={name:g,sch:createTaskScheduler(createAsyncPromise,"IndexedDbHelper["+g+"]"),dbHdl:[],add:function(f){S.dbHdl.push(f),_debugLog(g,"- dbOpened (add) -- hdls ["+S.dbHdl.length+"]")},remove:function(f){for(var v=S.dbHdl,C=0;C<v.length;C++)if(v[C]===f){v.splice(C,1);break}_debugLog(g,"- dbClosed (remove) -- hdls ["+S.dbHdl.length+"]")},isOpen:function(){return S.dbHdl.length>0},openHdl:function(){return S.dbHdl.length>0?S.dbHdl[0]:null}},Lc.push(S),S}var Fc=function(){function IndexedDbHelper(g){var f=kc++,S=0;dynamicProto$1(IndexedDbHelper,this,(function(v){var C=_getDbFactory()||null;function _createStoreContext(v,C,_){var T=v.db,I=S++;_debugLog(v.dbName,"["+f+":"+I+"] txn.open - "+C+" -- "+_);var b=T.transaction(C,_c);return b.onabort=function(){_warnLog(g,v.dbName,"["+f+":"+I+"] txn.onabort - "+C+" -- "+_+" -- "+dumpObj(b.error))},b.onerror=function(){_warnLog(g,v.dbName,"["+f+":"+I+"] txn.onerror - "+C+" -- "+_)},b.oncomplete=function(){_debugLog(v.dbName,"["+f+":"+I+"] txn.oncomplete - "+C+" -- "+_)},{db:v,store:b.objectStore(C),tx:b,tbl:C,openCursor:function(g,f){return _openCursor(v,C,g,f)},newTransaction:function(g){return _openStore(v,C,g)}}}function _openStore(g,f,S){if(!g||!g.db)return Ln(new Error(bc));try{var v=S(_createStoreContext(g,f,"openStore"));return isPromiseLike(v)?v:kn(v)}catch(g){return Ln(g)}}function _openCursor(g,f,S,v){if(!g||!g.db)return Ln(new Error(bc));var C=null;return S&&Nc(S)?C=new xc(S):S&&S.isMatch&&(C=S),createAsyncPromise((function(S,_){var T=[],I=null,b=null;C&&C.keyRange&&(b=C.keyRange());var A=_createStoreContext(g,f,"openCursor");(I=b?A.store.openCursor(b):A.store.openCursor()).onerror=_eventReject(A.db.dbName,Ac,_,"openCursor"),I.onsuccess=function(g){var f=g.target[Tc];if(f){var I={store:A,cursor:f,continue:function(){f.continue()},done:function(){S(T)}},b=f.value;if(!C||C.isMatch(b))if(v)try{switch(v(I,b,T)){case 2:S(T);break;case 1:break;default:I.continue()}}catch(g){_(g)}else T.push(b),I.continue();else I.continue()}else S(T)}}))}function _scheduleEvent(g,f,S,v){return _getDbContext(g).sch.queue(S,f,v)}v.isAvailable=function(){return!!C},v.openDb=function(f,S,v,_){return _scheduleEvent(f,"openDb",(function(T){return createAsyncPromise((function(I,b){var A=!1;function _createDbCtx(g,v,C,_,T){var I={db:v,dbName:f,dbVersion:S,ctx:null,isNew:_,txn:C?C.transaction:null};return T||(I.openStore=function(g,f){return _openStore(I,g,f)},I.openCursor=function(g,f,S){return _openCursor(I,g,f,S)}),I}function _databaseUpgrade(g,f){var S=_createDbCtx(null,g,f,!0,!0);if(_)A=!0,doAwaitResponse(_(S),(function(g){if(g.rejected)try{f.transaction&&f.transaction.abort()}finally{b(g.reason)}else S.txn||(S.txn=f.transaction)}));else try{f.transaction&&f.transaction.abort()}finally{b(new Error(Mc))}}function _databaseOpen(S,C){var _=_getDbContext(f);_.add(S),S.onabort=function(v){_warnLog(g,f,"onabort -- closing the Db"),_.remove(S)},S.onerror=function(v){_warnLog(g,f,"onerror -- closing the Db"),_.remove(S)},S.onclose=function(v){_warnLog(g,f,"onclose -- closing the Db"),_.remove(S)},S.onversionchange=function(v){_warnLog(g,f,"onversionchange -- force closing the Db"),S.close(),_.remove(S)};var T=null,P=null;_.dbHdl.length>0&&(P=_.dbHdl[0]),T=_createDbCtx(_,P,C,A);try{doAwait(v(T),I,b)}catch(g){b(g)}}var P=_getDbContext(f);if(null==C)b(new Error("No available storage factory"));else if(P.isOpen()){var R=_createDbCtx(P,P.openHdl(),null,!1);doAwait(v(R),I,b)}else{var M=C.open(f,S);M.onblocked=function(S){_warnLog(g,f,"Db Open Blocked event ["+T+"] - "+(M.error||"")),b(new Error(Ic))},M.onerror=function(S){_warnLog(g,f,"Db Open Error event ["+T+"] - "+(M.error||"")),b(new Error(Ic))},M.onupgradeneeded=function(g){_debugLog(f,"Db Open Create/Upgrade needed event ["+T+"]");try{var S=g.target[Tc];if(!S)return void b(new Error(Ic));_databaseUpgrade(S,M)}catch(g){_eventReject(f,Ic,b,T)(g)}},M.onsuccess=function(g){var f=g.target[Tc];f?_databaseOpen(f,M):b(new Error(Ic))}}}))}))},v.closeDb=function(g){_scheduleEvent(g,"closeDb",(function(f){var S=_getDbContext(g),v=S.dbHdl,C=v.length;if(C>0){for(var _=0;_<C;_++)v[_].close();S.dbHdl=[]}return 1})).catch((function(g){}))},v.deleteDb=function(f){return null!=C&&_scheduleEvent(f,"deleteDb",(function(S){var v=_getDbContext(f),_=v.dbHdl,T=_.length;if(T>0){_warnLog(g,f,"Db is open ["+T+"] force closing");for(var I=0;I<T;I++)_[I].close();v.dbHdl=[]}return createAsyncPromise((function(v,_){setTimeout((function(){try{_debugLog(f,"["+S+"] starting");var T=C.deleteDatabase(f);T.onerror=function(v){_warnLog(g,f,"["+S+"] error!!"),_(new Error(Pc))},T.onblocked=function(v){_warnLog(g,f,"["+S+"] blocked!!"),_(new Error(Pc))},T.onupgradeneeded=function(v){_warnLog(g,f,"["+S+"] upgrade needed!!"),_(new Error(Pc))},T.onsuccess=function(g){_debugLog(f,"["+S+"] complete"),v(!0)},_debugLog(f,"["+S+"] started")}catch(v){_warnLog(g,f,"["+S+"] threw - "+v),_(new Error(Pc+" - "+v))}}),0)}))}))},v.getDbDetails=function(g){return _scheduleEvent(g,"getDbDetails",(function(f){return null!=C&&C.databases?createAsyncPromise((function(f,S){C.databases().then((function(v){for(var C=0;C<v.length;C++)if(v[C].name===g)return void f(v[C]);S(new Error(Rc))}),S)})):Ln(new Error(wc))}),2e3)}}))}return IndexedDbHelper.__ieDyn=1,IndexedDbHelper}(),xc=function(){function SimpleQuery(g){var f=[],S=null;dynamicProto$1(SimpleQuery,this,(function(v){v.keyRange=function(){return S},v.parseQuery=function(g){if(f=[],g)for(var C=g.split(";"),_=0;_<C.length;_++){var T=C[_],I=T.indexOf("=");if(-1!==I){var b=T.substring(0,I),A=T.substring(I+1);0===b.indexOf("#")&&(b=b.substring(1),S||(S=IDBKeyRange.bound(A,A+""))),v.startsWith(b,A)}}},v.startsWith=function(g,S){f.push({name:g,value:S,type:0})},v.contains=function(g,S){f.push({name:g,value:S,type:1})},v.isMatch=function(g){if(!f||0===f.length)return!0;if(!g)return!1;for(var S=0;S<f.length;S++){var v=f[S],C=g[v.name];if(C)if(0===v.type){if(0!==C.indexOf(v.value))return!1}else if(1===v.type&&-1===C.indexOf(v.value))return!1}return!0},g&&v.parseQuery(g)}))}return SimpleQuery.__ieDyn=1,SimpleQuery}(),Uc=10,Vc=1,Bc=6e5,Hc=6048e5,$c="Unknown",jc=-1,Gc="DBError: Unable to add event",qc="DBError: Unable to update iKey",Wc=1,zc="Evts",Kc="iKey",Jc=isValidPersistenceLevel;function _getTime(){return(new Date).getTime()}function _eventReject$1(g,f){return function(S){return f(new Error(g))}}function _createDb(g){g.objectStoreNames.contains(zc)||g.createObjectStore(zc,{keyPath:"key"}).createIndex("EvntId","key",{unique:!1});g.objectStoreNames.contains(Kc)||g.createObjectStore(Kc,{keyPath:"iKey"}).createIndex("iKey","iKey",{unique:!0})}function _updateiKey(g){return g.openStore(Kc,(function(f){return createAsyncPromise((function(S,v){var C={iKey:g.ctx.iKey,tm:_getTime()},_=f.store.put(C);_.onsuccess=function(g){S(_.result.toString())},_.onerror=function(g){v(new Error(Gc))},_.onerror=_eventReject$1(qc,v)}))}))}function _orderEventsByPriority(g){for(var f=[],S=2;S>=1;S--)for(var v=0;v<g.length;v++){var C=g[v];C&&C.evt.persistence===S&&f.push(C.evt)}return f}function _addEventByTime(g,f){for(var S=0;S<g.length;S++)if(f.tm<g[S].tm)return void g.splice(S,0,f);g.push(f)}function _getKeyIndex(g,f){for(var S=f.length,v=0;v<S;v++)if(g===f[v].id)return v;return-1}function _isOldItem(g,f){var S=g.tm;return _getTime()-S>f}function _cursorContinueEvent(g){return function(f){return g.continue()}}function _cursorDeleteAndContinue(g){var f=g.cursor.delete();return f.onerror=_cursorContinueEvent(g),f.onsuccess=_cursorContinueEvent(g),1}function _getAllEventsForiKey(g,f){return g.openCursor(zc,f,(function(g,f,S){return S.push(f),0}))}function _deleteEvents(g,f,S){return g.openCursor(zc,f,(function(g,f,v){return S(f)?(v.push(f),_cursorDeleteAndContinue(g)):0}))}function _deleteOrphanedEvents(g){return createAsyncPromise((function(f,S){var v=!1;g.openCursor(Kc,null,(function(g,f,S){var C=f.tm;return _getTime()-C<Hc?0:(v=!0,2)})).then((function(){if(v){var C={};_deleteEvents(g,null,(function(g){if(!g||!g.evt||!g.evt.iKey)return!0;var f=g.tm;return _getTime()-f>Hc||(C[g.evt.iKey]=1,!1)})).then((function(){var v=[];g.openCursor(Kc,null,(function(g,f,S){var _=f.tm;return _getTime()-_<Hc||C[f.iKey]?0:(v.push(f),_cursorDeleteAndContinue(g))})).then((function(){f(v)}),S)}),S)}else f([])}),S)}))}function _moveOldEventsToCurrentStore(g,f){return g.openCursor(zc,"#key="+g.ctx.iKeyPrefix(),(function(S,v){var C=v.key;if(0===C.indexOf(g.ctx.iKeyPrefix())&&-1===C.indexOf(g.ctx.evtKeyPrefix())&&_isOldItem(v,f)){v.key=g.ctx.evtKeyPrefix()+v.id;var _=S.store.store.put(v);return _.onerror=_cursorContinueEvent(S),_.onsuccess=function(g){try{_cursorDeleteAndContinue(S)}catch(g){S.continue()}},1}return 0}))}function _checkVersionAndMoveEventsToCurrentStorage(g,f){return createAsyncPromise((function(S,v){_deleteOrphanedEvents(g).then((function(){_moveOldEventsToCurrentStore(g,f).then(S,S)}),v)}))}function _dropEventsUpToPersistence(g,f){return createAsyncPromise((function(S,v){var C=0,_=g.ctx.evtKeyPrefix();function _resolveWithDroppedEvents(){S(C)}function _dropEvent(g,f){return createAsyncPromise((function(S){var v=g.store.delete(f.key);v.onsuccess=function(g){C++,S()},v.onerror=function(g){S()}}))}function _processCandidates(f){0!==f.length?g.openStore(zc,(function(g){for(var S=[],v=0;v<f.length;v++)S.push(_dropEvent(g,f[v]));return Nn(S).then(_resolveWithDroppedEvents,_resolveWithDroppedEvents)})):_resolveWithDroppedEvents()}g.openCursor(zc,"#key="+_,(function(g,S,v){return S.evt.persistence<=f&&0===S.key.indexOf(_)&&(_addEventByTime(v,S),v.length>Uc&&v.splice(v.length-1,1)),0})).then(_processCandidates,(function(){S(0)}))}))}var Yc=function(){function IndexedDbProvider(g,f){dynamicProto$1(IndexedDbProvider,this,(function(S){var v=null,C=null,_=$c,T=null,I=null,b=null,A=jc,P=0,R=Bc;function _openDb(g){function _handleDbUpgrade(g){return createAsyncPromise((function(f,S){_createDb(g.db),f()}))}function _handleDbOpen(f){return createAsyncPromise((function(S,v){var C={iKey:_,storageId:T,iKeyPrefix:function(){return I},evtKeyPrefix:function(){return b}};f.ctx=C,doAwait(_updateiKey(f),(function(){doAwait(g(f),S,v)}),v)}))}return v.openDb(C,Wc,_handleDbOpen,_handleDbUpgrade)}function _addDbEvent(g,f,S){return createAsyncPromise((function(v,C){function dropEvents(f,S){_dropEventsUpToPersistence(g,f).then((function(g){g>0&&(P-=g),S(g)}),(function(g){S(0)}))}function resolveAddEvent(g){v(f.evt)}function _insertNewEvent(){g.openStore(zc,(function(_){var T=_.store.put(f);T.onsuccess=function(C){S&&_updateiKey(g).then(resolveAddEvent,resolveAddEvent),P++,v(f.evt)},T.onerror=function(_){function _retryAddEvent(S){0===S&&C(new Error(Gc)),_addDbEvent(g,f,!1).then((function(g){v(f.evt)}),(function(){C(new Error(Gc))}))}S?dropEvents(1,(function(g){g>0?_retryAddEvent(g):f.evt.persistence>=2?dropEvents(2,(function(g){_retryAddEvent(g)})):C(new Error(Gc))})):C(new Error(Gc))}}))}A>0&&P>=A?dropEvents(1,(function(g){0===g?f.evt.persistence>=2?dropEvents(2,(function(g){_insertNewEvent()})):C(new Error(Gc)):_insertNewEvent()})):_insertNewEvent()}))}S.id=g,S.initialize=function(g){var P=g.itemCtx.diagLog();if(!(v=new Fc(P)).isAvailable())return v=null,!1;var M=g.itemCtx.getCfg(),w=g.storageConfig;_=M.instrumentationKey||_,T=S.id||g.id||newGuid$1(),b=(I=_+"::")+T+"::",R=w.accessThresholdInMs||R;var O=onConfigChange$1(w,(function(){A=w.maxStorageItems;var g=w.indexedDbName;C&&g!==C&&C&&doAwaitResponse(S.clear(),(function(f){C=g,_openDb((function(g){return g.isNew?[]:_checkVersionAndMoveEventsToCurrentStorage(g,R)})).then((function(g){}),(function(g){P.warnToConsole("IndexedDbProvider failed to initialize - "+(g||"<unknown>")),v=null}))})),C=g}));return f&&f.add(O),_openDb((function(g){return g.isNew?[]:_checkVersionAndMoveEventsToCurrentStorage(g,R)})).then((function(g){}),(function(g){P.warnToConsole("IndexedDbProvider failed to initialize - "+(g||"<unknown>")),v=null})),!0},S._getDbgPlgTargets=function(){return[C]},S.supportsSyncRequests=function(){return!1},S.getAllEvents=function(){return null!=v&&v.isAvailable()?_openDb((function(g){return createAsyncPromise((function(f,S){_getAllEventsForiKey(g,"#key="+g.ctx.evtKeyPrefix()).then((function(g){P=g.length,f(_orderEventsByPriority(g))}),S)}))})):[]},S.addEvent=function(g,f,S){return null!=v&&v.isAvailable()?(f.id=f.id||newGuid$1(),Jc(f.persistence)||(f.persistence=1),_openDb((function(S){var v=g||f.id,C={key:S.ctx.evtKeyPrefix()+v,id:v,evt:f,tm:_getTime(),v:Vc};return _addDbEvent(S,C,!0)}))):f},S.removeEvents=function(g){if(null==v||!v.isAvailable())return[];var f=[];return createAsyncPromise((function(S,v){_openDb((function(S){return S.openCursor(zc,"#key="+S.ctx.iKey,(function(S,v,C){if(-1!==_getKeyIndex(v.id,g)){var _=S.cursor.delete();return _.onerror=_cursorContinueEvent(S),_.onsuccess=function(){f.push(v.evt),S.continue()},1}return 0}))})).then((function(g){P-=f.length,S(f)}),(function(g){P-=f.length,S(f)}))}))},S.clear=function(){return null!=v&&v.isAvailable()?createAsyncPromise((function(g,f){_openDb((function(g){return _deleteEvents(g,"#key="+g.ctx.evtKeyPrefix(),(function(f){return 0===f.key.indexOf(g.ctx.evtKeyPrefix())}))})).then((function(f){P=0,g(_orderEventsByPriority(f))}),f)})):[]},S.moveStaleEvents=function(){_openDb((function(g){return _checkVersionAndMoveEventsToCurrentStorage(g,R)}))},S.teardown=function(){v&&v.closeDb(C)}}))}return IndexedDbProvider.__ieDyn=1,IndexedDbProvider}(),Qc=10,Xc="3",Zc="Version",ed="AWTEvents",td=5e6;function _isQuotaExceeded(g,f){var S=!1;return f instanceof DOMException&&(22!==f.code&&"QuotaExceededError"!==f.name&&1014!==f.code&&"NS_ERROR_DOM_QUOTA_REACHED"!==f.name||g&&0!==g.length&&(S=!0)),S}function _getAvailableStorage(g){var f=getGlobal()||{},S=null;try{if(S=f[g]){var v="__storage_test__";S.setItem(v,v),S.removeItem(v)}}catch(g){_isQuotaExceeded(S,g)||(S=null)}return S}function _forEachMap(g,f){if(g)for(var S=Be(g),v=0;v<S.length;v++){var C=S[v];if(!f(g[C],C))break}}function _isMapEmpty(g){var f=!0;return _forEachMap(g,(function(g,S){return g&&(f=!1),f})),f}function _dropEventsUpToPersistence$1(g,f){for(var S=1,v=0,_loop_1=function(){var g=[],C=f[S];if(_forEachMap(C,(function(f,S){return g.push(S),++v<Qc})),v>0){for(var _=0;_<g.length;_++)delete C[g[_]];return{value:!0}}S++};S<=g&&v<Qc;){var C=_loop_1();if("object"==typeof C)return C.value}return v>0}var id,nd=isValidPersistenceLevel,rd=function(){function WebStorageProvider(g,f,S){dynamicProto$1(WebStorageProvider,this,(function(v){var C=null,_=ed,T=null,I=Xc,b=null,A=null,P=td,R=6e5,M=null,w=null;function _newStore(g,f){return{key:g,db:f}}function _fetchStoredDb(g,f){void 0===f&&(f=!0);var S=null;if(C){var v=C.getItem(g);if(v)try{S=JSON.parse(v)}catch(f){C.removeItem(g)}}return f&&!S&&(S={events:{1:{},2:{},3:{}},lastAccessTime:0}),_newStore(g,S)}function _updateStoredDb(g,f){void 0===f&&(f=!0);var S=!0,v=g.db;if(v){f&&(v.lastAccessTime=(new Date).getTime());for(var _=1;_<=2;_++)if(!_isMapEmpty(v.events[_])){S=!1;break}}try{if(S)C&&C.removeItem(g.key);else{var T=JSON.stringify(v);if(T.length>P)return!1;C&&C.setItem(g.key,T)}}catch(g){return!1}return!0}function _clearDatabase(g){var f=[],S=_fetchStoredDb(g,!1),v=S.db;if(v){var _=v.events;try{for(var T=1;T<=2;T++)_forEachMap(_[T],(function(g,S){return g&&f.push(g),!0}))}catch(g){}C&&C.removeItem(S.key)}return f}function _checkVersionAndMoveEventsToCurrentStorage(){if(C){for(var g=C.getItem(M),f=[],S=_fetchStoredDb(w),v=!1,T=0;T<C.length;T++){var b=C.key(T);if(0===b.indexOf(_)&&b!==M){if(g!==Xc){f.push(_newStore(b,null));continue}var P=_fetchStoredDb(b,!1),O=P.db;if(O){if((new Date).getTime()-O.lastAccessTime>R){for(var D=1,_loop_3=function(){var g=O.events[D],f=S.db.events[D];_forEachMap(g,(function(S,v){return(getTenantId$1(S.iKey)||S.iKey)===A&&(f[v]=S,delete g[v]),!0})),D++};D<=2;)_loop_3();v=!0,f.push(P)}}else f.push(_newStore(b,null))}}for(T=0;T<f.length;T++)_updateStoredDb(f[T],!1);v&&_updateStoredDb(S),C.setItem(M,I)}}v.id=f,C=_getAvailableStorage(g)||null,v._getDbgPlgTargets=function(){return[_,P]},v.initialize=function(g){if(!C)return!1;var f=g.storageConfig;T=v.id||g.id||newGuid$1(),b=g.itemCtx.getCfg().instrumentationKey,A=getTenantId$1(b)||b,R=f.accessThresholdInMs?f.accessThresholdInMs:R;var I=onConfigChange$1(f,(function(){P=f.maxStorageSizeInBytes;var g=f.storageKey;_&&g!==_&&doAwaitResponse(v.clear(),(function(f){w=(_=g)+"."+T,M=_+Zc,_checkVersionAndMoveEventsToCurrentStorage()}))}));return S&&S.add(I),_=f.storageKey,w=_+"."+T,M=_+Zc,_checkVersionAndMoveEventsToCurrentStorage(),!0},v.supportsSyncRequests=function(){return!0},v.getAllEvents=function(){try{var g=[],f=_fetchStoredDb(w,!1).db;if(f)for(var S=f.events,v=2;v>=1;v--)_forEachMap(S[v],(function(f){f&&((getTenantId$1(f.iKey)||f.iKey)===A&&g.push(f));return!0}));return g}catch(g){return Ln(g)}},v.addEvent=function(g,f,S){try{var v=_fetchStoredDb(w);f.id=f.id||newGuid$1(),nd(f.persistence)||(f.persistence=1);for(var C=f.persistence,_=f.id,T=v.db.events;;){if(T[C][_]=f,_updateStoredDb(v))return f;if(delete T[C][_],!_dropEventsUpToPersistence$1(C,T))return Ln(new Error("Unable to free up event space"))}}catch(g){return Ln(g)}},v.removeEvents=function(g){try{var f=_fetchStoredDb(w,!1),S=f.db;if(S){var v=S.events;try{for(var C=0;C<g.length;++C){var _=g[C];delete v[_.persistence][_.id]}if(_updateStoredDb(f))return g}catch(g){}g=_clearDatabase(f.key)}return g}catch(g){return Ln(g)}},v.clear=function(){try{var g=[],f=_fetchStoredDb(w,!1),S=f.db;if(S){for(var v=S.events,_loop_2=function(f){var S=v[f];_forEachMap(S,(function(f){f&&((getTenantId$1(f.iKey)||f.iKey)===A&&(delete S[f.id],g.push(f)));return!0}))},C=2;C>=1;C--)_loop_2(C);_updateStoredDb(f)}return g}catch(g){return Ln(g)}},v.teardown=function(){try{var g=_fetchStoredDb(w,!1),f=g.db;f&&(f.lastAccessTime=0,_updateStoredDb(g,!1))}catch(g){}},v.moveStaleEvents=function(){_checkVersionAndMoveEventsToCurrentStorage()}}))}return WebStorageProvider.__ieDyn=1,WebStorageProvider}(),sd="4.3.1",ad="LocalStorage",od=5,ld=isValidPersistenceLevel,cd=void 0,dd="AppInsightEvents.1",hd=objDeepFreeze({maxStorageSizeInBytes:{isVal:isGreaterThanZero$1,v:5e6},storageKey:"AWTEvents",minPersistenceLevel:{isVal:ld,v:1},providers:[yc.LocalStorage,yc.IndexedDb],indexedDbName:dd,maxStorageItems:{isVal:isGreaterThanZero$1,v:cd}}),ud=function(g){function LocalStorageChannel(){var f=g.call(this)||this;return f.identifier=ad,f.priority=1009,f.version=sd,dynamicProto$1(LocalStorageChannel,f,(function(g,f){var S,v,C,_;function _initDefaults(){S=!1,v=!1,C=null,_=[]}function _queueStorageEvent(g,f){C||(C=createTaskScheduler(createAsyncPromise,"LocalStorage")),C.queue((function(g){return f(g)}),g).catch((function(g){}))}function _sendStoredEventsToNextPlugin(f){doPerf$1(g.core,(function(){return"LocalStorageChannel:_sendStoredEventsToNextPlugin"}),(function(){_queueStorageEvent("sendToNext",(function(S){return doAwaitResponse(f.provider.getAllEvents(),(function(S){for(var v=S.value||[],C=0;C<v.length;C++)try{var _=v[C];(getTenantId$1(_.iKey)||_.iKey)===f.tenantId&&g.processNext(_,f.coreRootCtx.createNew())}catch(g){}}))}))}),(function(){return{iKeyConfig:f}}))}function _removeEvents(f,S){doPerf$1(g.core,(function(){return"LocalStorageChannel:_removeEvents"}),(function(){_queueStorageEvent("removeEvents",(function(g){var v=[];if(arrForEach(S,(function(g){(getTenantId$1(g.iKey)||g.iKey)===f.tenantId&&v.push(g)})),v.length>0)return doAwaitResponse(f.provider.removeEvents(v),(function(g){}))}))}),(function(){return{iKeyConfig:f,events:S}}))}function _shouldCacheEvent(g,f){return!(f.sync||f.persistence<g.minPersistenceCacheLevel)}function _tryGetIndexedDbProvider(f){var S=new Yc(void 0,g._unloadHooks);return S.initialize(f)||(S=null),S}function _tryGetWebStorageProvider(f,S){var v=new rd(f,void 0,g._unloadHooks);return v.initialize(S)||(v=null),v}function _initializeProvider(g){for(var f=g.storageConfig.providers,S=null,v=0;!S&&v<f.length&&v<od;)switch(f[v++]){case yc.LocalStorage:S=_tryGetWebStorageProvider("localStorage",g);break;case yc.SessionStorage:S=_tryGetWebStorageProvider("sessionStorage",g);break;case yc.IndexedDb:S=_tryGetIndexedDbProvider(g)}return S}function _compareProviders(g,f){if(g.length!==f.length)return!1;var S=!0;return arrForEach(g,(function(g,v){if(g!==f[v])return S=!1,-1})),S}function _getCoreItemCtx(f,S,v,C){f&&(f.extensionConfig=f.extensionConfig||[]),!C&&S&&(C=S.getProcessTelContext().getNext());var _=null,T=g._getTelCtx().getNext();return T&&(_=T.getPlugin()),createProcessTelemetryContext$1(C,f,S,_)}function _createIkeyConfig(f,S,v,C){var T=!1;if(arrForEach(_,(function(g){if(g.iKey===f.instrumentationKey)return T=!0,-1})),!T){var I=null;g._addHook(onConfigChange$1(f,(function(v){var C=createProcessTelemetryContext$1(null,v.cfg,S);I=C.getExtCfg(g.identifier,hd);var T=!1,b=null,A=f.instrumentationKey;if(arrForEach(_,(function(g){if(g.iKey===A)return T=!0,b=g,-1})),T&&b){var R=I.providers,M=b.preProviders;_compareProviders(R,M)||doAwaitResponse(P.clear(),(function(g){if(!g.rejected)try{var f=_.indexOf(b);-1!==f&&_.splice(f,1);var v=_initializeProvider(b.providerContext);b.provider=v,b.preProviders=R.slice();var C=b.preListener;C&&S.removeNotificationListener(C);var T={eventsSent:function(g){_removeEvents(b,g)},eventsDiscarded:function(g,f){_removeEvents(b,g)}};b.preListener=T,_.push(b),S.addNotificationListener(T),_sendStoredEventsToNextPlugin(b)}catch(g){}}))}})));var b=_getCoreItemCtx(f,S,v,C),A={itemCtx:b,storageConfig:I,id:g.id};if(!Ie(f.instrumentationKey))return;var P=_initializeProvider(A),R={iKey:f.instrumentationKey,tenantId:getTenantId$1(f.instrumentationKey)||f.instrumentationKey,minPersistenceCacheLevel:1,coreRootCtx:b,providerContext:A,provider:P,preProviders:I.providers.slice()};if(P){ld(I.minPersistenceLevel||-1)&&(R.minPersistenceCacheLevel=I.minPersistenceLevel);var M={eventsSent:function(g){_removeEvents(R,g)},eventsDiscarded:function(g,f){_removeEvents(R,g)}};R.preListener=M,_.push(R),S.addNotificationListener(M),_sendStoredEventsToNextPlugin(R)}else _.push(R)}}_initDefaults(),g.initialize=function(g,v,_,T){doPerf$1(v,(function(){return"LocalStorageChannel.initialize"}),(function(){S||(f.initialize(g,v,_),f.setInitialized(!1),S=!0,C=createTaskScheduler(createAsyncPromise,"LocalStorage")),_createIkeyConfig(g,v,_,T)}),(function(){return{coreConfig:g,core:v,extensions:_,pluginChain:T}}))},g.processTelemetry=function(f,C){var T=f;if(S&&!v){C=g._getTelCtx(C),setProcessTelemetryTimings$1(f,g.identifier);var I=null;arrForEach(_,(function(g){g.iKey===f.iKey&&(I=g)}));var b=I?I.provider:null;if(T.sync||!b)return void g.processNext(T,C);T.id=T.id||newGuid$1(),isValidPersistenceLevel(T.persistence)||(T.persistence=1),_shouldCacheEvent(I,T)&&_queueStorageEvent("processTelemetry",(function(g){return b.addEvent(T.id,T,C)}))}g.processNext(T,C)},g.pause=function(){v=!0},g.resume=function(){doPerf$1(g.core,(function(){return"LocalStorageChannel:resume"}),(function(){v=!1,arrForEach(_,(function(g){g.provider&&_sendStoredEventsToNextPlugin(g)}))}))},g._doTeardown=function(g,f){arrForEach(_,(function(g){var f=g.provider;f&&f.teardown()})),_initDefaults()},g.flush=function(g,f,S){},g._getDbgPlgTargets=function(){return[_]},g._sendStale=function(g){arrForEach(_,(function(f){if(f&&f.iKey===g&&f.provider)return f.provider.moveStaleEvents(),_sendStoredEventsToNextPlugin(f),-1}))}})),f}return __extendsFn$1(LocalStorageChannel,g),LocalStorageChannel.__ieDyn=1,LocalStorageChannel}(fc),gd="REAL_TIME",pd="NEAR_REAL_TIME",md="BEST_EFFORT",fd="function",Sd="prototype",vd=Object,Cd=((getGlobal()||{}).Symbol,(getGlobal()||{}).Reflect,"hasOwnProperty"),extendStaticsFn$2=function(g,f){return extendStaticsFn$2=vd.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f[Cd](S)&&(g[S]=f[S])},extendStaticsFn$2(g,f)};function __extendsFn$2(g,f){function __(){this.constructor=g}typeof f!==fd&&null!==f&&throwTypeError("Class extends value "+String(f)+" is not a constructor or null"),extendStaticsFn$2(g,f),g[Sd]=null===f?ut(f):(__[Sd]=f[Sd],new __)}var yd="constructor",Ed="prototype",_d="function",Td="_dynInstFuncs",Id="_isDynProxy",bd="_dynClass",Ad="_dynCls$",Pd="_dynInstChk",Rd=Pd,Md="_dfOpts",wd="_unknown_",Od="__proto__",Dd="_dyn"+Od,Nd="__dynProto$Gbl",kd="_dynInstProto",Ld="useBaseInst",Fd="setInstFuncs",xd=Object,Ud=xd.getPrototypeOf,Vd=xd.getOwnPropertyNames,Bd=getGlobal(),Hd=Bd[Nd]||(Bd[Nd]={o:(id={},id[Fd]=!0,id[Ld]=!0,id),n:1e3});function _isObjectOrArrayPrototype$2(g){return g&&(g===xd[Ed]||g===Array[Ed])}function _isObjectArrayOrFunctionPrototype$2(g){return _isObjectOrArrayPrototype$2(g)||g===Function[Ed]}function _getObjProto$2(g){var f;if(g){if(Ud)return Ud(g);var S=g[Od]||g[Ed]||(g[yd]?g[yd][Ed]:null);f=g[Dd]||S,objHasOwnProperty(g,Dd)||(delete g[kd],f=g[Dd]=g[kd]||g[Dd],g[kd]=S)}return f}function _forEachProp$2(g,f){var S=[];if(Vd)S=Vd(g);else for(var v in g)"string"==typeof v&&objHasOwnProperty(g,v)&&S.push(v);if(S&&S.length>0)for(var C=0;C<S.length;C++)f(S[C])}function _isDynamicCandidate$2(g,f,S){return f!==yd&&typeof g[f]===_d&&(S||objHasOwnProperty(g,f))&&f!==Od&&f!==Ed}function _throwTypeError$2(g){throwTypeError("DynamicProto: "+g)}function _getInstanceFuncs$2(g){var f=ut(null);return _forEachProp$2(g,(function(S){!f[S]&&_isDynamicCandidate$2(g,S,!1)&&(f[S]=g[S])})),f}function _hasVisited$2(g,f){for(var S=g.length-1;S>=0;S--)if(g[S]===f)return!0;return!1}function _getBaseFuncs$2(g,f,S,v){function _instFuncProxy(g,f,S){var C=f[S];if(C[Id]&&v){var _=g[Td]||{};!1!==_[Rd]&&(C=(_[f[bd]]||{})[S]||C)}return function(){return C.apply(g,arguments)}}var C=ut(null);_forEachProp$2(S,(function(g){C[g]=_instFuncProxy(f,S,g)}));for(var _=_getObjProto$2(g),T=[];_&&!_isObjectArrayOrFunctionPrototype$2(_)&&!_hasVisited$2(T,_);)_forEachProp$2(_,(function(g){!C[g]&&_isDynamicCandidate$2(_,g,!Ud)&&(C[g]=_instFuncProxy(f,_,g))})),T.push(_),_=_getObjProto$2(_);return C}function _getInstFunc$2(g,f,S,v){var C=null;if(g&&objHasOwnProperty(S,bd)){var _=g[Td]||ut(null);if((C=(_[S[bd]]||ut(null))[f])||_throwTypeError$2("Missing ["+f+"] "+_d),!C[Pd]&&!1!==_[Rd]){for(var T=!objHasOwnProperty(g,f),I=_getObjProto$2(g),b=[];T&&I&&!_isObjectArrayOrFunctionPrototype$2(I)&&!_hasVisited$2(b,I);){var A=I[f];if(A){T=A===v;break}b.push(I),I=_getObjProto$2(I)}try{T&&(g[f]=C),C[Pd]=1}catch(g){_[Rd]=!1}}}return C}function _getProtoFunc$2(g,f,S){var v=f[g];return v===S&&(v=_getObjProto$2(f)[g]),typeof v!==_d&&_throwTypeError$2("["+g+"] is not a "+_d),v}function _populatePrototype$2(g,f,S,v,C){function _createDynamicPrototype(g,f){var dynProtoProxy=function(){return(_getInstFunc$2(this,f,g,dynProtoProxy)||_getProtoFunc$2(f,g,dynProtoProxy)).apply(this,arguments)};return dynProtoProxy[Id]=1,dynProtoProxy}if(!_isObjectOrArrayPrototype$2(g)){var _=S[Td]=S[Td]||ut(null);if(!_isObjectOrArrayPrototype$2(_)){var T=_[f]=_[f]||ut(null);!1!==_[Rd]&&(_[Rd]=!!C),_isObjectOrArrayPrototype$2(T)||_forEachProp$2(S,(function(f){_isDynamicCandidate$2(S,f,!1)&&S[f]!==v[f]&&(T[f]=S[f],delete S[f],(!objHasOwnProperty(g,f)||g[f]&&!g[f][Id])&&(g[f]=_createDynamicPrototype(g,f)))}))}}}function _checkPrototype$2(g,f){if(Ud){for(var S=[],v=_getObjProto$2(f);v&&!_isObjectArrayOrFunctionPrototype$2(v)&&!_hasVisited$2(S,v);){if(v===g)return!0;S.push(v),v=_getObjProto$2(v)}return!1}return!0}function _getObjName$2(g,f){return objHasOwnProperty(g,Ed)?g.name||f||wd:((g||{})[yd]||{}).name||f||wd}function dynamicProto$2(g,f,S,v){objHasOwnProperty(g,Ed)||_throwTypeError$2("theClass is an invalid class definition.");var C=g[Ed];_checkPrototype$2(C,f)||_throwTypeError$2("["+_getObjName$2(g)+"] not in hierarchy of ["+_getObjName$2(f)+"]");var _=null;objHasOwnProperty(C,bd)?_=C[bd]:(_=Ad+_getObjName$2(g,"_")+"$"+Hd.n,Hd.n++,C[bd]=_);var T=dynamicProto$2[Md],I=!!T[Ld];I&&v&&void 0!==v[Ld]&&(I=!!v[Ld]);var b=_getInstanceFuncs$2(f);S(f,_getBaseFuncs$2(C,f,b,I));var A=!!Ud&&!!T[Fd];A&&v&&(A=!!v[Fd]),_populatePrototype$2(C,_,f,b,!1!==A)}dynamicProto$2[Md]=Hd.o;var $d="",jd="drop",Gd="send",qd="requeue",Wd="rspFail",zd="oth",Kd="no-cache, no-store",Jd="application/x-json-stream",Yd="cache-control",Qd="content-type",Xd="kill-tokens",Zd="kill-duration",eh="time-delta-millis",th="client-version",ih="client-id",nh="time-delta-to-apply-millis",rh="upload-time",sh="apikey",ah="AuthMsaDeviceTicket",oh="WebAuthToken",lh="AuthXToken",ch="NoResponseBody",dh="msfpc",hh="trace",uh="user",gh="allowRequestSending",ph="firstRequestSent",mh="shouldAddClockSkewHeaders",fh="getClockSkewHeaderValue",Sh="setClockSkew",vh="length",Ch="concat",yh="iKey",Eh="count",_h="events",Th="push",Ih="split",bh="splice",Ah="toLowerCase",Ph="hdrs",Rh="useHdrs",Mh="initialize",wh="setTimeoutOverride",Oh="clearTimeoutOverride",Dh="payloadPreprocessor",Nh="overrideEndpointUrl",kh="avoidOptions",Lh="disableEventTimings",Fh="stringifyObjects",xh="enableCompoundKey",Uh="disableXhrSync",Vh="disableFetchKeepAlive",Bh="addNoResponse",Hh="excludeCsMetaData",$h="useSendBeacon",jh="fetchCredentials",Gh="alwaysUseXhrOverride",qh="unloadTransports",Wh="serializeOfflineEvt",zh="getOfflineRequestDetails",Kh="createPayload",Jh="createOneDSPayload",Yh="payloadBlob",Qh="headers",Xh="_thePayload",Zh="urlString",eu="batches",tu="sendType",iu="addHeader",nu="canSendRequest",ru="sendQueuedRequests",su="isCompletelyIdle",au="setUnloading",ou="isTenantKilled",lu="sendSynchronousBatch",cu="_transport",du="getWParam",hu="isBeacon",uu="timings",gu="isTeardown",pu="isSync",mu="data",fu="timeout",Su="_sendReason",vu="setKillSwitchTenants",Cu="_backOffTransmission",yu="identifier",Eu="disableOptimizeObj",_u="ignoreMc1Ms0CookieProcessing",Tu="eventsLimitInMem",Iu="autoFlushEventsLimit",bu="disableAutoBatchFlushLimit",Au="overrideInstrumentationKey",Pu="disableTelemetry",Ru="baseData",Mu="sendAttempt",wu="latency",Ou="sync";function _getEventMsfpc(g){var f=(g.ext||{}).intweb;return f&&isValueAssigned(f[dh])?f[dh]:null}function _getMsfpc(g){for(var f=null,S=0;null===f&&S<g[vh];S++)f=_getEventMsfpc(g[S]);return f}var Du=function(){function EventBatch(g,f){var S=f?[][Ch](f):[],v=this,C=_getMsfpc(S);v[yh]=function(){return g},v.Msfpc=function(){return C||$d},v[Eh]=function(){return S[vh]},v[_h]=function(){return S},v.addEvent=function(g){return!!g&&(S[Th](g),C||(C=_getEventMsfpc(g)),!0)},v[Ih]=function(f,v){var _;if(f<S[vh]){var T=S[vh]-f;isNullOrUndefined(v)||(T=v<T?v:T),_=S[bh](f,T),C=_getMsfpc(S)}return new EventBatch(g,_)}}return EventBatch.create=function(g,f){return new EventBatch(g,f)},EventBatch}(),Nu=function(){function ClockSkewManager(){var g=!0,f=!0,S=!0,v="use-collector-delta",C=!1;dynamicProto$2(ClockSkewManager,this,(function(_){_[gh]=function(){return g},_[ph]=function(){S&&(S=!1,C||(g=!1))},_[mh]=function(){return f},_[fh]=function(){return v},_[Sh]=function(S){C||(S?(v=S,f=!0,C=!0):f=!1,g=!0)}}))}return ClockSkewManager.__ieDyn=1,ClockSkewManager}(),ku=1e3,Lu=function(){function KillSwitch(){var g={};function _normalizeTenants(g){var f=[];return g&&arrForEach(g,(function(g){f[Th](ft(g))})),f}dynamicProto$2(KillSwitch,this,(function(f){f[vu]=function(f,S){if(f&&S)try{var v=_normalizeTenants(f[Ih](","));if("this-request-only"===S)return v;for(var C=parseInt(S,10)*ku,_=0;_<v[vh];++_)g[v[_]]=utcNow()+C}catch(g){return[]}return[]},f[ou]=function(f){var S=g,v=ft(f);return void 0!==S[v]&&S[v]>utcNow()||(delete S[v],!1)}}))}return KillSwitch.__ieDyn=1,KillSwitch}(),Fu=.8,xu=1.2,Uu=3e3,Vu=6e5;function retryPolicyShouldRetryForStatus(g){return!(g>=300&&g<500&&429!=g||501==g||505==g)}function retryPolicyGetMillisToBackoffForRetry(g){var f=0,S=Uu*Fu,v=Uu*xu,C=Math.floor(Math.random()*(v-S))+S;return f=Math.pow(2,g)*C,Math.min(f,Vu)}var Bu,Hu=20,$u=3984588,ju=65e3,Gu=2e6,qu=Math.min(Gu,ju),Wu="metadata",zu="f",Ku=/\./,Ju=function(){function Serializer(g,f,S,v,C,_){var T="data",I="baseData",b="ext",A=!!v,P=!0,R=f,M={},w=!!_,O=C||getCommonSchemaMetaData;dynamicProto$2(Serializer,this,(function(f){function _isReservedField(g,f){var S=M[g];return void 0===S&&(g.length>=7&&(S=_t(g,"ext.metadata")||_t(g,"ext.web")),M[g]=S),S}function _processPathKeys(g,f,v,C,_,T,I){objForEachKey(g,(function(g,b){var P=null;if(b||isValueAssigned(b)){var M=v,w=g,O=_,D=f;if(A&&!C&&Ku.test(g)){var N=g.split("."),k=N.length;if(k>1){O&&(O=O.slice());for(var L=0;L<k-1;L++){var F=N[L];D=D[F]=D[F]||{},M+="."+F,O&&O.push(F)}w=N[k-1]}}if(P=!(C&&_isReservedField(M))&&R&&R.handleField(M,w)?R.value(M,w,b,S):sanitizeProperty(w,b,S)){var x=P.value;if(D[w]=x,T&&T(O,w,P),I&&"object"==typeof x&&!Ae(x)){var U=O;U&&(U=U.slice()).push(w),_processPathKeys(b,x,M+"."+w,C,U,T,I)}}}}))}f.createPayload=function(g,f,S,v,C,_){return{apiKeys:[],payloadBlob:$d,overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:g,isTeardown:f,isSync:S,isBeacon:v,sendType:_,sendReason:C}},f.appendPayload=function(S,v,C){var _=S&&v&&!S.overflow;return _&&doPerf(g,(function(){return"Serializer:appendPayload"}),(function(){for(var g=v.events(),_=S.payloadBlob,T=S.numEvents,I=!1,b=[],A=[],P=S.isBeacon,R=P?ju:$u,M=P?qu:Gu,w=0,O=0;w<g.length;){var D=g[w];if(D){if(T>=C){S.overflow=v.split(w);break}var N=f.getEventBlob(D);if(N&&N.length<=M){var k=N.length;if(_.length+k>R){S.overflow=v.split(w);break}_&&(_+="\n"),_+=N,++O>Hu&&(Ye(_,0,1),O=0),I=!0,T++}else N?b.push(D):A.push(D),g.splice(w,1),w--}w++}if(b.length>0&&S.sizeExceed.push(Du.create(v.iKey(),b)),A.length>0&&S.failedEvts.push(Du.create(v.iKey(),A)),I){S.batches.push(v),S.payloadBlob=_,S.numEvents=T;var L=v.iKey();-1===dt(S.apiKeys,L)&&S.apiKeys.push(L)}}),(function(){return{payload:S,theBatch:{iKey:v.iKey(),evts:v.events()},max:C}})),_},f.getEventBlob=function(f){try{return doPerf(g,(function(){return"Serializer.getEventBlob"}),(function(){var g={};g.name=f.name,g.time=f.time,g.ver=f.ver,g.iKey="o:"+getTenantId(f.iKey);var S,v={};w||(S=function(g,f,S){_addJSONPropertyMetaData(O,v,g,f,S)});var C=f[b];C&&(g[b]=v,objForEachKey(C,(function(g,f){_processPathKeys(f,v[g]={},"ext."+g,!0,null,null,!0)})));var _=g[T]={};_.baseType=f.baseType;var A=_[I]={};return _processPathKeys(f.baseData,A,I,!1,[I],S,P),_processPathKeys(f.data,_,T,!1,[],S,P),JSON.stringify(g)}),(function(){return{item:f}}))}catch(g){return null}}}))}return Serializer.__ieDyn=1,Serializer}();function _addJSONPropertyMetaData(g,f,S,v,C){if(C&&f){var _=g(C.value,C.kind,C.propertyType);if(_>-1){var T=f[Wu];T||(T=f[Wu]={f:{}});var I=T[zu];if(I||(I=T[zu]={}),S)for(var b=0;b<S.length;b++){var A=S[b];I[A]||(I[A]={f:{}});var P=I[A][zu];P||(P=I[A][zu]={}),I=P}I=I[v]={},Ae(C.value)?I.a={t:_}:I.t=_}}}function createTimeoutWrapper(g,f){return{set:function(S,v){for(var C=[],_=2;_<arguments.length;_++)C[_-2]=arguments[_];return scheduleTimeoutWith([g,f],S,v,C)}}}var Yu="sendAttempt",Qu="&"+ch+"=true",Xu="?cors=true&"+Qd[Ah]()+"="+Jd,Zu=((Bu={})[1]=qd,Bu[100]=qd,Bu[200]="sent",Bu[8004]=jd,Bu[8003]=jd,Bu),eg={},tg={};function _addCollectorHeaderQsMapping(g,f,S){eg[g]=f,!1!==S&&(tg[f]=g)}function _hasHeader(g,f){var S=!1;if(g&&f){var v=Be(g);if(v&&v[vh]>0)for(var C=f[Ah](),_=0;_<v[vh];_++){var T=v[_];if(T&&objHasOwnProperty(f,T)&&T[Ah]()===C){S=!0;break}}}return S}function _addRequestDetails(g,f,S,v){f&&S&&S[vh]>0&&(v&&eg[f]?(g[Ph][eg[f]]=S,g[Rh]=!0):g.url+="&"+f+"="+S)}function _addQueryStringParameter(g,f,S){for(var v=0;v<g[vh];v++)if(g[v].name===f)return void(g[v].value=S);g[Th]({name:f,value:S})}function _removeQueryStringParameter(g,f){for(var S=0;S<g[vh];S++)if(g[S].name===f)return void g[bh](S,1)}_addCollectorHeaderQsMapping(ah,ah,!1),_addCollectorHeaderQsMapping(th,th),_addCollectorHeaderQsMapping(ih,"Client-Id"),_addCollectorHeaderQsMapping(sh,sh),_addCollectorHeaderQsMapping(nh,nh),_addCollectorHeaderQsMapping(rh,rh),_addCollectorHeaderQsMapping(lh,lh);var ig=function(){function HttpManager(g,f,S,v){var C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q,W,z,K,J,Q,X,Z,ee=!1;dynamicProto$2(HttpManager,this,(function(te){_initDefaults();var ie=!0;function _getSenderInterface(g,f){try{return X&&X.getSenderInst(g,f)}catch(g){}return null}function _getSendPostMgrConfig(){try{return{enableSendPromise:!1,isOneDs:!0,disableCredentials:!ie,fetchCredentials:Z,disableXhr:!1,disableBeacon:!ee,disableBeaconSync:!ee,disableFetchKeepAlive:H,timeWrapper:J,addNoResponse:j,senderOnCompleteCallBack:{xdrOnComplete:_xdrOncomplete,fetchOnComplete:_fetchOnComplete,xhrOnComplete:_xhrOnComplete,beaconOnRetry:_onBeaconRetry}}}catch(g){}return null}function _xdrOncomplete(g,f,S){var v=getResponseText(g);_doOnComplete(f,200,{},v),_handleCollectorResponse(v)}function _initDefaults(){var g;C=null,_=new Lu,T=!1,I=new Nu,ee=!1,b=0,A=null,P=null,R=null,M=null,w=!0,O=[],D={},N=[],k=null,L=!1,F=null,x=!1,U=!1,V=g,B=g,H=g,$=g,j=g,G=[],q=g,W=g,z=[],K=!1,J=createTimeoutWrapper(),Q=!1,X=null}function _fetchOnComplete(g,f,S,v){var handleResponse=function(g,S,v){_doOnComplete(f,g,S,v),_handleCollectorResponse(v)},C={},_=g[Qh];_&&_.forEach((function(g,f){C[f]=g})),handleResponse(g.status,C,S||$d)}function _xhrOnComplete(g,f,S){var v=getResponseText(g);_doOnComplete(f,g.status,_getAllResponseHeaders(g,!0),v),_handleCollectorResponse(v)}function _doOnComplete(g,f,S,v){try{g(f,S,v)}catch(g){_throwInternal(P,2,518,dumpObj(g))}}function _onBeaconRetry(g,f,S){var v=200,C=g[Xh],_=g[Zh]+(j?Qu:$d);try{var T=lt();if(C){var I=!!M.getPlugin("LocalStorage"),b=[],A=[];arrForEach(C[eu],(function(g){if(b&&g&&g[Eh]()>0)for(var f=g[_h](),S=0;S<f[vh];S++){if(!T.sendBeacon(_,k.getEventBlob(f[S]))){b[Th](g[Ih](S));break}A[Th](g[S])}else b[Th](g[Ih](0))})),A[vh]>0&&(C.sentEvts=A),I||_sendBatchesNotification(b,8003,C[tu],!0)}else v=0}catch(g){_warnToConsole(P,"Failed to send telemetry using sendBeacon API. Ex:"+dumpObj(g)),v=0}finally{_doOnComplete(f,v,{},$d)}}function _isBeaconPayload(g){return 2===g||3===g}function _adjustSendType(g){return x&&_isBeaconPayload(g)&&(g=2),g}function _hasIdleConnection(){return!T&&b<f}function _clearQueue(){var g=N;return N=[],g}function _canSendPayload(g,f,S){var v=!1;return g&&g[vh]>0&&!T&&R[f]&&k&&(v=0!==f||_hasIdleConnection()&&(S>0||I[gh]())),v}function _createDebugBatches(g){var f={};return g&&arrForEach(g,(function(g,S){f[S]={iKey:g[yh](),evts:g[_h]()}})),f}function _sendBatches(f,S,v,C,I){if(f&&0!==f[vh])if(T)_sendBatchesNotification(f,1,C);else{C=_adjustSendType(C);try{var b=f,A=0!==C;doPerf(M,(function(){return"HttpManager:_sendBatches"}),(function(T){T&&(f=f.slice(0));for(var b=[],P=null,M=Ba(),w=R[C]||(A?R[1]:R[0]),O=w&&w[cu],D=$&&(x||_isBeaconPayload(C)||3===O||w._isSync&&2===O);_canSendPayload(f,C,S);){var L=f.shift();L&&L[Eh]()>0&&(_.isTenantKilled(L[yh]())?b[Th](L):(P=P||k[Kh](S,v,A,D,I,C),k.appendPayload(P,L,g)?null!==P.overflow&&(f=[P.overflow][Ch](f),P.overflow=null,_doPayloadSend(P,M,Ba(),I),M=Ba(),P=null):(_doPayloadSend(P,M,Ba(),I),M=Ba(),f=[L][Ch](f),P=null)))}P&&_doPayloadSend(P,M,Ba(),I),f[vh]>0&&(N=f[Ch](N)),_sendBatchesNotification(b,8004,C)}),(function(){return{batches:_createDebugBatches(b),retryCount:S,isTeardown:v,isSynchronous:A,sendReason:I,useSendBeacon:_isBeaconPayload(C),sendType:C}}),!A)}catch(g){_throwInternal(P,2,48,"Unexpected Exception sending batch: "+dumpObj(g))}}}function _buildRequestDetails(g,f){var S={url:C,hdrs:{},useHdrs:!1};f?(S[Ph]=extend(S[Ph],D),S.useHdrs=Be(S.hdrs)[vh]>0):objForEachKey(D,(function(g,f){tg[g]?_addRequestDetails(S,tg[g],f,!1):(S[Ph][g]=f,S[Rh]=!0)})),_addRequestDetails(S,ih,"NO_AUTH",f),_addRequestDetails(S,th,xa,f);var v=$d;arrForEach(g.apiKeys,(function(g){v[vh]>0&&(v+=","),v+=g})),_addRequestDetails(S,sh,v,f),_addRequestDetails(S,rh,utcNow().toString(),f);var _=_getMsfpc(g);if(isValueAssigned(_)&&(S.url+="&ext.intweb.msfpc="+_),I[mh]()&&_addRequestDetails(S,nh,I[fh](),f),M[du]){var T=M[du]();T>=0&&(S.url+="&w="+T)}for(var b=0;b<O[vh];b++)S.url+="&"+O[b].name+"="+O[b].value;return S}function _setTimingValue(g,f,S){g[f]=g[f]||{},g[f][A.identifier]=S}function _doPayloadSend(g,f,S,v){if(g&&g.payloadBlob&&g.payloadBlob[vh]>0){var C=!!q,_=R[g.sendType];!_isBeaconPayload(g[tu])&&g[hu]&&2===g.sendReason&&(_=R[2]||R[3]||_);var T=U;(g.isBeacon||3===_[cu])&&(T=!1);var A=_buildRequestDetails(g,T);T=T||A[Rh];var O=Ba();doPerf(M,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var R=0;R<g.batches[vh];R++)for(var D=g[eu][R][_h](),N=0;N<D[vh];N++){var k=D[N];if(L){var F=k[uu]=k[uu]||{};_setTimingValue(F,"sendEventStart",O),_setTimingValue(F,"serializationStart",f),_setTimingValue(F,"serializationCompleted",S)}k[Yu]>0?k[Yu]++:k[Yu]=1}_sendBatchesNotification(g[eu],1e3+(v||0),g[tu],!0);var x={data:g[Yh],urlString:A.url,headers:A[Ph],_thePayload:g,_sendReason:v,timeout:V,disableXhrSync:B,disableFetchKeepAlive:H};T&&(_hasHeader(x[Qh],Yd)||(x[Qh][Yd]=Kd),_hasHeader(x[Qh],Qd)||(x[Qh][Qd]=Jd));var U=null;_&&(U=function(f){I[ph]();var onComplete=function(f,S){_retryRequestIfNeeded(f,S,g,v)},S=g[gu]||g[pu];try{_.sendPOST(f,onComplete,S),W&&W(x,f,S,g[hu])}catch(g){_warnToConsole(P,"Unexpected exception sending payload. Ex:"+dumpObj(g)),_doOnComplete(onComplete,0,{})}}),doPerf(M,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(U)if(0===g[tu]&&b++,C&&!g.isBeacon&&3!==_[cu]){var f={data:x[mu],urlString:x[Zh],headers:extend({},x[Qh]),timeout:x[fu],disableXhrSync:x[Uh],disableFetchKeepAlive:x[Vh]},S=!1;doPerf(M,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{q(f,(function(g){S=!0,w||g[Xh]||(g[Xh]=g[Xh]||x[Xh],g[Su]=g[Su]||x[Su]),U(g)}),g.isSync||g[gu])}catch(g){S||U(x)}}))}else U(x)}))}),(function(){return{thePayload:g,serializationStart:f,serializationCompleted:S,sendReason:v}}),g[pu])}g.sizeExceed&&g.sizeExceed[vh]>0&&_sendBatchesNotification(g.sizeExceed,8003,g[tu]),g.failedEvts&&g.failedEvts[vh]>0&&_sendBatchesNotification(g.failedEvts,8002,g[tu])}function _addEventCompletedTimings(g,f){L&&arrForEach(g,(function(g){_setTimingValue(g[uu]=g[uu]||{},"sendEventCompleted",f)}))}function _retryRequestIfNeeded(g,f,v,C){var T=9e3,A=null,P=!1,R=!1;try{var M=!0;if(typeof g!==Y){if(f){I[Sh](f[eh]);var w=f[Zd]||f["kill-duration-seconds"];arrForEach(_[vu](f[Xd],w),(function(g){arrForEach(v[eu],(function(f){if(f[yh]()===g){A=A||[];var S=f[Ih](0);v.numEvents-=S[Eh](),A[Th](S)}}))}))}if(200==g||204==g)return void(T=200);(!retryPolicyShouldRetryForStatus(g)||v.numEvents<=0)&&(M=!1),T=9e3+g%1e3}if(M){T=100;var O=v.retryCnt;0===v[tu]&&(O<S?(P=!0,_doAction((function(){0===v[tu]&&b--,_sendBatches(v[eu],O+1,v[gu],x?2:v[tu],5)}),x,retryPolicyGetMillisToBackoffForRetry(O))):(R=!0,x&&(T=8001)))}}finally{P||(I[Sh](),_handleRequestFinished(v,T,C,R)),_sendBatchesNotification(A,8004,v[tu])}}function _handleRequestFinished(g,f,S,v){try{v&&A[Cu]();var C=g[eu];200===f&&(C=g.sentEvts||g[eu],v||g[pu]||A._clearBackOff(),_addCompleteTimings(C)),_sendBatchesNotification(C,f,g[tu],!0)}finally{0===g[tu]&&(b--,5!==S&&te.sendQueuedRequests(g[tu],S))}}function _addCompleteTimings(g){if(L){var f=Ba();arrForEach(g,(function(g){g&&g[Eh]()>0&&_addEventCompletedTimings(g[_h](),f)}))}}function _doAction(g,f,S){f?g():J.set(g,S)}function _getMsfpc(g){for(var f=0;f<g.batches[vh];f++){var S=g[eu][f].Msfpc();if(S)return encodeURIComponent(S)}return $d}function _handleCollectorResponse(g){var f=z;try{for(var S=0;S<f[vh];S++)try{f[S](g)}catch(g){_throwInternal(P,1,519,"Response handler failed: "+g)}if(g){var v=JSON.parse(g);isValueAssigned(v.webResult)&&isValueAssigned(v.webResult[dh])&&F.set("MSFPC",v.webResult[dh],31536e3)}}catch(g){}}function _sendBatchesNotification(g,f,S,C){if(g&&g[vh]>0&&v){var _=v[_getNotificationAction(f)];if(_){var T=0!==S;doPerf(M,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){_doAction((function(){try{_.call(v,g,f,T,S)}catch(g){_throwInternal(P,1,74,"send request notification failed: "+g)}}),C||T,0)}),(function(){return{batches:_createDebugBatches(g),reason:f,isSync:T,sendSync:C,sendType:S}}),!T)}}}function _getNotificationAction(g){var f=Zu[g];return isValueAssigned(f)||(f=zd,g>=9e3&&g<=9999?f=Wd:g>=8e3&&g<=8999?f=jd:g>=1e3&&g<=1999&&(f=Gd)),f}te[Mh]=function(g,f,S){K||(M=f,F=f.getCookieMgr(),P=(A=S).diagLog(),arrAppend(G,onConfigChange(g,(function(g){var v,_=g.cfg,T=g.cfg.extensionConfig[S.identifier];J=createTimeoutWrapper(T[wh],T[Oh]),isValueAssigned(_.anonCookieName)?_addQueryStringParameter(O,"anoncknm",_.anonCookieName):_removeQueryStringParameter(O,"anoncknm"),q=T[Dh],W=T.payloadListener;var I=T.httpXHROverride,b=T[Nh]?T[Nh]:_.endpointUrl;C=b+Xu,U=!!isUndefined(T[kh])||!T[kh],L=!T[Lh];var A=T.valueSanitizer,D=T[Fh],N=!!_[xh];isUndefined(T[xh])||(N=!!T[xh]),V=T.xhrTimeout,B=!!T[Uh],H=!!T[Vh],j=!1!==T[Bh],Q=!!T[Hh],f.getPlugin("LocalStorage")&&(H=!0),ee=!isReactNative(),k=new Ju(M,A,D,N,getCommonSchemaMetaData,Q),isNullOrUndefined(T[$h])||(ee=!!T[$h]),T[jh]&&(Z=T[jh]);var F=_getSendPostMgrConfig();X?X.SetConfig(F):(X=new ra)[Mh](F,P);var x=I,G=T[Gh]?I:null,z=T[Gh]?I:null,K=[3,2];if(!I){w=!1;var Y=[];isReactNative()?(Y=[2,1],K=[2,1,3]):Y=[1,2,3],(I=_getSenderInterface(Y=prependTransports(Y,T.transports),!1))||_warnToConsole(P,"No available transport to send events"),x=_getSenderInterface(Y,!0)}G||(G=_getSenderInterface(K=prependTransports(K,T[qh]),!0)),$=!w&&(ee&&isBeaconsSupported()||!H&&isFetchSupported(!0)),(v={})[0]=I,v[1]=x||_getSenderInterface([1,2,3],!0),v[2]=G||x||_getSenderInterface([1],!0),v[3]=z||_getSenderInterface([2,3],!0)||x||_getSenderInterface([1],!0),R=v}))),K=!0)},te.addResponseHandler=function(g){return z[Th](g),{rm:function(){var f=z.indexOf(g);f>=0&&z[bh](f,1)}}},te[Wh]=function(g){try{if(k)return k.getEventBlob(g)}catch(g){}return $d},te[zh]=function(){try{return _buildRequestDetails(k&&k[Kh](0,!1,!1,!1,1,0),U)}catch(g){}return null},te[Jh]=function(f,S){try{var v=[];arrForEach(f,(function(g){S&&(g=optimizeObject(g));var f=Du.create(g[yh],[g]);v[Th](f)}));for(var C=null;v[vh]>0&&k;){var _=v.shift();_&&_[Eh]()>0&&(C=C||k[Kh](0,!1,!1,!1,1,0),k.appendPayload(C,_,g))}var T=_buildRequestDetails(C,U),I={data:C[Yh],urlString:T.url,headers:T[Ph],timeout:V,disableXhrSync:B,disableFetchKeepAlive:H};return U&&(_hasHeader(I[Qh],Yd)||(I[Qh][Yd]=Kd),_hasHeader(I[Qh],Qd)||(I[Qh][Qd]=Jd)),I}catch(g){}return null},te._getDbgPlgTargets=function(){return[R[0],_,k,R,_getSendPostMgrConfig()]},te[iu]=function(g,f){D[g]=f},te.removeHeader=function(g){delete D[g]},te[nu]=function(){return _hasIdleConnection()&&I[gh]()},te[ru]=function(g,f){isUndefined(g)&&(g=0),x&&(g=_adjustSendType(g),f=2),_canSendPayload(N,g,0)&&_sendBatches(_clearQueue(),0,!1,g,f||0)},te[su]=function(){return!T&&0===b&&0===N[vh]},te[au]=function(g){x=g},te.addBatch=function(g){if(g&&g[Eh]()>0){if(_.isTenantKilled(g[yh]()))return!1;N[Th](g)}return!0},te.teardown=function(){N[vh]>0&&_sendBatches(_clearQueue(),0,!0,2,2),arrForEach(G,(function(g){g&&g.rm&&g.rm()})),G=[]},te.pause=function(){T=!0},te.resume=function(){T=!1,te[ru](0,4)},te[lu]=function(g,f,S){g&&g[Eh]()>0&&(isNullOrUndefined(f)&&(f=1),x&&(f=_adjustSendType(f),S=2),_sendBatches([g],0,!1,f,S||0))}}))}return HttpManager.__ieDyn=1,HttpManager}(),ng=.25,rg=500,sg=20,ag=6,og=2,lg=4,cg=2,dg=1,hg=1e4,ug="eventsDiscarded",gg="",pg=void 0,mg=objDeepFreeze({eventsLimitInMem:{isVal:isGreaterThanZero,v:hg},immediateEventLimit:{isVal:isGreaterThanZero,v:500},autoFlushEventsLimit:{isVal:isGreaterThanZero,v:0},disableAutoBatchFlushLimit:!1,httpXHROverride:{isVal:isOverrideFn,v:pg},overrideInstrumentationKey:pg,overrideEndpointUrl:pg,disableTelemetry:!1,ignoreMc1Ms0CookieProcessing:!1,setTimeoutOverride:pg,clearTimeoutOverride:pg,payloadPreprocessor:pg,payloadListener:pg,disableEventTimings:pg,valueSanitizer:pg,stringifyObjects:pg,enableCompoundKey:pg,disableOptimizeObj:!1,fetchCredentials:pg,transports:pg,unloadTransports:pg,useSendBeacon:pg,disableFetchKeepAlive:pg,avoidOptions:!1,xhrTimeout:pg,disableXhrSync:pg,alwaysUseXhrOverride:!1,maxEventRetryAttempts:{isVal:Re,v:ag},maxUnloadEventRetryAttempts:{isVal:Re,v:og},addNoResponse:pg,excludeCsMetaData:pg});function isOverrideFn(g){return g&&g.sendPOST}var fg,Sg=function(g){function PostChannel(){var f,S=g.call(this)||this;S.identifier="PostChannel",S.priority=1011,S.version="4.3.2";var v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q=!1,W=[],z=!1,K=0,J=0,Y={},Q=gd;return dynamicProto$2(PostChannel,S,(function(g,S){function _removeUnloadHandlers(){removePageUnloadEventListener(null,x),removePageHideEventListener(null,x),removePageShowEventListener(null,x)}function _hookWParam(g){var f=g[du];g[du]=function(){var S=0;return V&&(S|=2),S|f.call(g)}}function _batch(g){var f=gg;return g&&g[vh]&&arrForEach(g,(function(g){f&&(f+="\n"),f+=g})),f}function _serialize(g){var f=gg;try{_cleanEvent(g),f=P[Wh](g)}catch(g){}return f}function _handleUnloadEvents(g){"beforeunload"!==(g||rt().event).type&&(k=!0,P[au](k)),_releaseAllQueues(2,2)}function _handleShowEvents(g){k=!1,P[au](k)}function _cleanEvent(g){g.ext&&g.ext[hh]&&delete g.ext[hh],g.ext&&g.ext[uh]&&g.ext[uh].id&&delete g.ext[uh].id,N&&(g.ext=optimizeObject(g.ext),g[Ru]&&(g[Ru]=optimizeObject(g[Ru])),g[mu]&&(g[mu]=optimizeObject(g[mu])))}function _addEventToQueues(g,f){if(g[Mu]||(g[Mu]=0),g[wu]||(g[wu]=1),_cleanEvent(g),g[Ou])if(b||z)g[wu]=3,g[Ou]=!1;else if(P)return N&&(g=optimizeObject(g)),void P[lu](Du.create(g[yh],[g]),!0===g[Ou]?1:g[Ou],3);var S=g[wu],v=J,T=_;4===S&&(v=K,T=C);var I=!1;if(v<T)I=!_addEventToProperQueue(g,f);else{var A=1,R=sg;4===S&&(A=4,R=1),I=!0,_dropEventWithLatencyOrLess(g[yh],g[wu],A,R)&&(I=!_addEventToProperQueue(g,f))}I&&_notifyEvents(ug,[g],Zt.QueueFull)}function _sendEventsForLatencyAndAbove(g,f,S){var v=_queueBatches(g,f,S);return P[ru](f,S),v}function _hasEvents(){return J>0}function _scheduleTimer(){if(O>=0&&_queueBatches(O,0,D)&&P[ru](0,D),K>0&&!I&&!z){var g=Y[Q][2];g>=0&&(I=_createTimer((function(){I=null,_sendEventsForLatencyAndAbove(4,0,1),_scheduleTimer()}),g))}var f=Y[Q][1];!T&&!v&&f>=0&&!z&&(_hasEvents()?T=_createTimer((function(){T=null,_sendEventsForLatencyAndAbove(0===A?3:1,0,1),A++,A%=2,_scheduleTimer()}),f):A=0)}function _initDefaults(){f=null,q=!1,W=[],v=null,z=!1,K=0,C=500,J=0,_=hg,Y={},Q=gd,T=null,I=null,b=0,A=0,R={},M=0,$=!1,w=0,O=-1,D=null,N=!0,k=!1,L=ag,F=og,x=null,j=null,G=!1,U=createTimeoutWrapper(),P=new ig(rg,cg,dg,{requeue:_requeueEvents,send:_sendingEvent,sent:_eventsSentEvent,drop:_eventsDropped,rspFail:_eventsResponseFail,oth:_otherEvent}),_initializeProfiles(),_clearQueues(),_setAutoLimits()}function _createTimer(g,f){0===f&&b&&(f=1);var S=1e3;return b&&(S=retryPolicyGetMillisToBackoffForRetry(b-1)),U.set(g,f*S)}function _clearScheduledTimer(){return null!==T&&(T.cancel(),T=null,A=0,!0)}function _releaseAllQueues(g,f){_clearScheduledTimer(),v&&(v.cancel(),v=null),z||_sendEventsForLatencyAndAbove(1,g,f)}function _clearQueues(){R[4]={batches:[],iKeyMap:{}},R[3]={batches:[],iKeyMap:{}},R[2]={batches:[],iKeyMap:{}},R[1]={batches:[],iKeyMap:{}}}function _getEventBatch(g,f,S){var v=R[f];v||(v=R[f=1]);var C=v.iKeyMap[g];return!C&&S&&(C=Du.create(g),v.batches[Th](C),v.iKeyMap[g]=C),C}function _performAutoFlush(f,S){P[nu]()&&!b&&(M>0&&J>M&&(S=!0),S&&null==v&&g.flush(f,(function(){}),20))}function _addEventToProperQueue(g,f){N&&(g=optimizeObject(g));var S=g[wu],v=_getEventBatch(g[yh],S,!0);return!!v.addEvent(g)&&(4!==S?(J++,f&&0===g[Mu]&&_performAutoFlush(!g.sync,w>0&&v[Eh]()>=w)):K++,!0)}function _dropEventWithLatencyOrLess(g,f,S,v){for(;S<=f;){var C=_getEventBatch(g,f,!0);if(C&&C[Eh]()>0){var _=C[Ih](0,v),T=_[Eh]();if(T>0)return 4===S?K-=T:J-=T,_notifyBatchEvents(ug,[_],Zt.QueueFull),!0}S++}return _resetQueueCounts(),!1}function _resetQueueCounts(){for(var g=0,f=0,_loop_1=function(S){var v=R[S];v&&v[eu]&&arrForEach(v[eu],(function(v){4===S?g+=v[Eh]():f+=v[Eh]()}))},S=1;S<=4;S++)_loop_1(S);J=f,K=g}function _queueBatches(f,S,v){var C=!1,_=0===S;return!_||P[nu]()?doPerf(g.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var g=[],S=4;S>=f;){var v=R[S];v&&v.batches&&v.batches[vh]>0&&(arrForEach(v[eu],(function(f){P.addBatch(f)?C=C||f&&f[Eh]()>0:g=g[Ch](f[_h]()),4===S?K-=f[Eh]():J-=f[Eh]()})),v[eu]=[],v.iKeyMap={}),S--}g[vh]>0&&_notifyEvents(ug,g,Zt.KillSwitch),C&&O>=f&&(O=-1,D=0)}),(function(){return{latency:f,sendType:S,sendReason:v}}),!_):(O=O>=0?Math.min(O,f):f,D=Math.max(D,v)),C}function _flushImpl(g,f){_sendEventsForLatencyAndAbove(1,0,f),_resetQueueCounts(),_waitForIdleManager((function(){g&&g(),W[vh]>0?v=_createTimer((function(){v=null,_flushImpl(W.shift(),f)}),0):(v=null,_scheduleTimer())}))}function _waitForIdleManager(g){P[su]()?g():v=_createTimer((function(){v=null,_waitForIdleManager(g)}),ng)}function _resetTransmitProfiles(){_clearScheduledTimer(),_initializeProfiles(),Q=gd,_scheduleTimer()}function _initializeProfiles(){(Y={})[gd]=[2,1,0],Y[pd]=[6,3,0],Y[md]=[18,9,0]}function _requeueEvents(f,S){var v=[],C=L;k&&(C=F),arrForEach(f,(function(f){f&&f[Eh]()>0&&arrForEach(f[_h](),(function(f){f&&(f[Ou]&&(f[wu]=4,f[Ou]=!1),f[Mu]<C?(setProcessTelemetryTimings(f,g[yu]),_addEventToQueues(f,!1)):v[Th](f))}))})),v[vh]>0&&_notifyEvents(ug,v,Zt.NonRetryableStatus),k&&_releaseAllQueues(2,2)}function _callNotification(f,S){var v=H||{},C=v[f];if(C)try{C.apply(v,S)}catch(S){_throwInternal(g.diagLog(),1,74,f+" notification failed: "+S)}}function _notifyEvents(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];f&&f[vh]>0&&_callNotification(g,[f][Ch](S))}function _notifyBatchEvents(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];f&&f[vh]>0&&arrForEach(f,(function(f){f&&f[Eh]()>0&&_callNotification(g,[f.events()][Ch](S))}))}function _sendingEvent(g,f,S){g&&g[vh]>0&&_callNotification("eventsSendRequest",[f>=1e3&&f<=1999?f-1e3:0,!0!==S])}function _eventsSentEvent(g,f){_notifyBatchEvents("eventsSent",g,f),_scheduleTimer()}function _eventsDropped(g,f){_notifyBatchEvents(ug,g,f>=8e3&&f<=8999?f-8e3:Zt.Unknown)}function _eventsResponseFail(g){_notifyBatchEvents(ug,g,Zt.NonRetryableStatus),_scheduleTimer()}function _otherEvent(g,f){_notifyBatchEvents(ug,g,Zt.Unknown),_scheduleTimer()}function _setAutoLimits(){w=B?0:Math.max(rg*(cg+1),_/6)}_initDefaults(),g._getDbgPlgTargets=function(){return[P,f]},g[Mh]=function(v,T,I){doPerf(T,(function(){return"PostChannel:initialize"}),(function(){S[Mh](v,T,I),H=T.getNotifyMgr();try{x=mergeEvtNamespace(createUniqueNamespace(g[yu]),T.evtNamespace&&T.evtNamespace()),g._addHook(onConfigChange(v,(function(S){var v=S.cfg,I=createProcessTelemetryContext(null,v,T);f=I.getExtCfg(g[yu],mg),U=createTimeoutWrapper(f[wh],f[Oh]),N=!f[Eu]&&isChromium(),V=f[_u],_hookWParam(T),_=f[Tu],C=f.immediateEventLimit,M=f[Iu],L=f.maxEventRetryAttempts,F=f.maxUnloadEventRetryAttempts,B=f[bu],_setAutoLimits(),j=f[Au],G=!!f[Pu],$&&_removeUnloadHandlers();var b=v.disablePageUnloadEvents||[];$=addPageUnloadEventListener(_handleUnloadEvents,b,x),$=addPageHideEventListener(_handleUnloadEvents,b,x)||$,$=addPageShowEventListener(_handleShowEvents,v.disablePageShowEvents,x)||$}))),P[Mh](v,g.core,g)}catch(f){throw g.setInitialized(!1),f}}),(function(){return{theConfig:v,core:T,extensions:I}}))},g.processTelemetry=function(f,S){setProcessTelemetryTimings(f,g[yu]),S=S||g._getTelCtx(S);var v=f;G||q||(j&&(v[yh]=j),_addEventToQueues(v,!0),k?_releaseAllQueues(2,2):_scheduleTimer()),g.processNext(v,S)},g.getOfflineSupport=function(){try{var g=P&&P[zh]();if(P)return{getUrl:function(){return g?g.url:null},serialize:_serialize,batch:_batch,shouldProcess:function(g){return!G},createPayload:function(g){return null},createOneDSPayload:function(g){if(P[Jh])return P[Jh](g,N)}}}catch(g){}return null},g._doTeardown=function(g,f){_releaseAllQueues(2,2),q=!0,P.teardown(),_removeUnloadHandlers(),_initDefaults()},g.setEventQueueLimits=function(g,S){f[Tu]=_=isGreaterThanZero(g)?g:hg,f[Iu]=M=isGreaterThanZero(S)?S:0,_setAutoLimits();var v=J>g;if(!v&&w>0)for(var C=1;!v&&C<=3;C++){var T=R[C];T&&T[eu]&&arrForEach(T[eu],(function(g){g&&g[Eh]()>=w&&(v=!0)}))}_performAutoFlush(!0,v)},g.pause=function(){_clearScheduledTimer(),z=!0,P.pause()},g.resume=function(){z=!1,P.resume(),_scheduleTimer()},g._loadTransmitProfiles=function(g){_resetTransmitProfiles(),objForEachKey(g,(function(g,f){var S=f[vh];if(S>=2){var v=S>2?f[2]:0;if(f[bh](0,S-2),f[1]<0&&(f[0]=-1),f[1]>0&&f[0]>0){var C=f[0]/f[1];f[0]=Math.ceil(C)*f[1]}v>=0&&f[1]>=0&&v>f[1]&&(v=f[1]),f[Th](v),Y[g]=f}}))},g.flush=function(g,f,S){var C;if(void 0===g&&(g=!0),!z)if(S=S||1,g)f||(C=createPromise((function(g){f=g}))),null==v?(_clearScheduledTimer(),_queueBatches(1,0,S),v=_createTimer((function(){v=null,_flushImpl(f,S)}),0)):W[Th](f);else{var _=_clearScheduledTimer();_sendEventsForLatencyAndAbove(1,1,S),f&&f(),_&&_scheduleTimer()}return C},g.setMsaAuthTicket=function(g){P[iu](ah,g)},g.setAuthPluginHeader=function(g){P[iu](oh,g)},g.removeAuthPluginHeader=function(){P.removeHeader(oh)},g.hasEvents=_hasEvents,g._setTransmitProfile=function(g){Q!==g&&void 0!==Y[g]&&(_clearScheduledTimer(),Q=g,_scheduleTimer())},proxyFunctions(g,(function(){return P}),["addResponseHandler"]),g[Cu]=function(){b<lg&&(b++,_clearScheduledTimer(),_scheduleTimer())},g._clearBackOff=function(){b&&(b=0,_clearScheduledTimer(),_scheduleTimer())}})),S}return __extendsFn$2(PostChannel,g),PostChannel.__ieDyn=1,PostChannel}(Gs),vg="function",Cg="prototype",yg=Object,Eg=((getGlobal()||{}).Symbol,(getGlobal()||{}).Reflect,"hasOwnProperty"),extendStaticsFn$3=function(g,f){return extendStaticsFn$3=yg.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f[Eg](S)&&(g[S]=f[S])},extendStaticsFn$3(g,f)};function __extendsFn$3(g,f){function __(){this.constructor=g}typeof f!==vg&&null!==f&&throwTypeError("Class extends value "+String(f)+" is not a constructor or null"),extendStaticsFn$3(g,f),g[Cg]=null===f?ut(f):(__[Cg]=f[Cg],new __)}var _g="constructor",Tg="prototype",Ig="function",bg="_dynInstFuncs",Ag="_isDynProxy",Pg="_dynClass",Rg="_dynCls$",Mg="_dynInstChk",wg=Mg,Og="_dfOpts",Dg="_unknown_",Ng="__proto__",kg="_dyn"+Ng,Lg="__dynProto$Gbl",Fg="_dynInstProto",xg="useBaseInst",Ug="setInstFuncs",Vg=Object,Bg=Vg.getPrototypeOf,Hg=Vg.getOwnPropertyNames,$g=getGlobal(),jg=$g[Lg]||($g[Lg]={o:(fg={},fg[Ug]=!0,fg[xg]=!0,fg),n:1e3});function _isObjectOrArrayPrototype$3(g){return g&&(g===Vg[Tg]||g===Array[Tg])}function _isObjectArrayOrFunctionPrototype$3(g){return _isObjectOrArrayPrototype$3(g)||g===Function[Tg]}function _getObjProto$3(g){var f;if(g){if(Bg)return Bg(g);var S=g[Ng]||g[Tg]||(g[_g]?g[_g][Tg]:null);f=g[kg]||S,objHasOwnProperty(g,kg)||(delete g[Fg],f=g[kg]=g[Fg]||g[kg],g[Fg]=S)}return f}function _forEachProp$3(g,f){var S=[];if(Hg)S=Hg(g);else for(var v in g)"string"==typeof v&&objHasOwnProperty(g,v)&&S.push(v);if(S&&S.length>0)for(var C=0;C<S.length;C++)f(S[C])}function _isDynamicCandidate$3(g,f,S){return f!==_g&&typeof g[f]===Ig&&(S||objHasOwnProperty(g,f))&&f!==Ng&&f!==Tg}function _throwTypeError$3(g){throwTypeError("DynamicProto: "+g)}function _getInstanceFuncs$3(g){var f=ut(null);return _forEachProp$3(g,(function(S){!f[S]&&_isDynamicCandidate$3(g,S,!1)&&(f[S]=g[S])})),f}function _hasVisited$3(g,f){for(var S=g.length-1;S>=0;S--)if(g[S]===f)return!0;return!1}function _getBaseFuncs$3(g,f,S,v){function _instFuncProxy(g,f,S){var C=f[S];if(C[Ag]&&v){var _=g[bg]||{};!1!==_[wg]&&(C=(_[f[Pg]]||{})[S]||C)}return function(){return C.apply(g,arguments)}}var C=ut(null);_forEachProp$3(S,(function(g){C[g]=_instFuncProxy(f,S,g)}));for(var _=_getObjProto$3(g),T=[];_&&!_isObjectArrayOrFunctionPrototype$3(_)&&!_hasVisited$3(T,_);)_forEachProp$3(_,(function(g){!C[g]&&_isDynamicCandidate$3(_,g,!Bg)&&(C[g]=_instFuncProxy(f,_,g))})),T.push(_),_=_getObjProto$3(_);return C}function _getInstFunc$3(g,f,S,v){var C=null;if(g&&objHasOwnProperty(S,Pg)){var _=g[bg]||ut(null);if((C=(_[S[Pg]]||ut(null))[f])||_throwTypeError$3("Missing ["+f+"] "+Ig),!C[Mg]&&!1!==_[wg]){for(var T=!objHasOwnProperty(g,f),I=_getObjProto$3(g),b=[];T&&I&&!_isObjectArrayOrFunctionPrototype$3(I)&&!_hasVisited$3(b,I);){var A=I[f];if(A){T=A===v;break}b.push(I),I=_getObjProto$3(I)}try{T&&(g[f]=C),C[Mg]=1}catch(g){_[wg]=!1}}}return C}function _getProtoFunc$3(g,f,S){var v=f[g];return v===S&&(v=_getObjProto$3(f)[g]),typeof v!==Ig&&_throwTypeError$3("["+g+"] is not a "+Ig),v}function _populatePrototype$3(g,f,S,v,C){function _createDynamicPrototype(g,f){var dynProtoProxy=function(){return(_getInstFunc$3(this,f,g,dynProtoProxy)||_getProtoFunc$3(f,g,dynProtoProxy)).apply(this,arguments)};return dynProtoProxy[Ag]=1,dynProtoProxy}if(!_isObjectOrArrayPrototype$3(g)){var _=S[bg]=S[bg]||ut(null);if(!_isObjectOrArrayPrototype$3(_)){var T=_[f]=_[f]||ut(null);!1!==_[wg]&&(_[wg]=!!C),_isObjectOrArrayPrototype$3(T)||_forEachProp$3(S,(function(f){_isDynamicCandidate$3(S,f,!1)&&S[f]!==v[f]&&(T[f]=S[f],delete S[f],(!objHasOwnProperty(g,f)||g[f]&&!g[f][Ag])&&(g[f]=_createDynamicPrototype(g,f)))}))}}}function _checkPrototype$3(g,f){if(Bg){for(var S=[],v=_getObjProto$3(f);v&&!_isObjectArrayOrFunctionPrototype$3(v)&&!_hasVisited$3(S,v);){if(v===g)return!0;S.push(v),v=_getObjProto$3(v)}return!1}return!0}function _getObjName$3(g,f){return objHasOwnProperty(g,Tg)?g.name||f||Dg:((g||{})[_g]||{}).name||f||Dg}function dynamicProto$3(g,f,S,v){objHasOwnProperty(g,Tg)||_throwTypeError$3("theClass is an invalid class definition.");var C=g[Tg];_checkPrototype$3(C,f)||_throwTypeError$3("["+_getObjName$3(g)+"] not in hierarchy of ["+_getObjName$3(f)+"]");var _=null;objHasOwnProperty(C,Pg)?_=C[Pg]:(_=Rg+_getObjName$3(g,"_")+"$"+jg.n,jg.n++,C[Pg]=_);var T=dynamicProto$3[Og],I=!!T[xg];I&&v&&void 0!==v[xg]&&(I=!!v[xg]);var b=_getInstanceFuncs$3(f);S(f,_getBaseFuncs$3(C,f,b,I));var A=!!Bg&&!!T[Ug];A&&v&&(A=!!v[Ug]),_populatePrototype$3(C,_,f,b,!1!==A)}dynamicProto$3[Og]=jg.o;var Gg=createTypeMap,qg="";function cfgDfMerge$1(g){return{mrg:!0,v:g}}function cfgDfString(g){return{isVal:Ie,v:Fe(g||qg)}}var Wg,zg="locale",Kg="ver",Jg="browser",Yg="browserVer",Qg="popSample",Xg="eventFlags",Zg="name",ep="serviceName",tp=Gg({UserExt:[0,"user"],DeviceExt:[1,"device"],TraceExt:[2,"trace"],WebExt:[3,"web"],AppExt:[4,"app"],OSExt:[5,"os"],SdkExt:[6,"sdk"],IntWebExt:[7,"intweb"],UtcExt:[8,"utc"],LocExt:[9,"loc"],CloudExt:[10,"cloud"],DtExt:[11,"dt"]}),ip=Gg({id:[0,"id"],ver:[1,Kg],appName:[2,Zg],locale:[3,zg],expId:[4,"expId"],env:[5,"env"]}),np=Gg({domain:[0,"domain"],browser:[1,Jg],browserVer:[2,Yg],screenRes:[3,"screenRes"],userConsent:[4,"userConsent"],consentDetails:[5,"consentDetails"]}),rp=Gg({locale:[0,zg],localId:[1,"localId"],id:[2,"id"]}),sp=Gg({osName:[0,Zg],ver:[1,Kg]}),ap=Gg({ver:[0,Kg],seq:[1,"seq"],installId:[2,"installId"],epoch:[3,"epoch"]}),op=Gg({msfpc:[0,"msfpc"],anid:[1,"anid"],serviceName:[2,ep]}),lp=Gg({popSample:[0,Qg],eventFlags:[1,Xg]}),cp=Gg({tz:[0,"tz"]}),dp=Gg({sessionId:[0,"sesId"]}),hp=Gg({localId:[0,"localId"],deviceClass:[1,"deviceClass"],make:[2,"make"],model:[3,"model"]}),up=Gg({role:[0,"role"],roleInstance:[1,"roleInstance"],roleVer:[2,"roleVer"]}),gp=Gg({traceId:[0,"traceID"],traceName:[1,Zg],parentId:[2,"parentID"]}),pp=Gg({traceId:[0,"traceId"],spanId:[1,"spanId"],traceFlags:[2,"traceFlags"]});function canUseLocalStorage(){return void 0===Wg&&(Wg=!!_getVerifiedStorageObject(0)),Wg}function _getLocalStorageObject(){return canUseLocalStorage()?_getVerifiedStorageObject(0):null}function _getVerifiedStorageObject(g){var f,S,v=null;try{var C=getGlobal();if(!C)return null;S=new Date,(v=0===g?C.localStorage:C.sessionStorage)&&be(v.setItem)&&(v.setItem(S,S),f=v.getItem(S)!==S,v.removeItem(S),f&&(v=null))}catch(g){v=null}return v}function setStorage(g,f,S){var v=_getLocalStorageObject();if(null!==v)try{return v.setItem(f,S),!0}catch(f){Wg=!1,_throwInternal(g,1,504,"Browser failed write to local storage. "+f)}return!1}function getStorage(g,f){var S=_getLocalStorageObject();if(null!==S)try{return S.getItem(f)}catch(f){Wg=!1,_throwInternal(g,1,503,"Browser failed read of local storage. "+f)}return null}function _getId(){return this.getId()}function _setId(g){this.setId(g)}var mp=function(){function Session(){dynamicProto$3(Session,this,(function(g){g.setId=function(f){g.customId=f},g.getId=function(){return Ie(g.customId)?g.customId:g.automaticId}}))}return Session._staticInit=void objDefine(Session.prototype,"id",{g:_getId,s:_setId}),Session}(),fp="ai_session",Sp=function(){function SessionManager(g,f,S){var v,C,_,T=safeGetLogger(g),I=safeGetCookieMgr(g);dynamicProto$3(SessionManager,this,(function(g){var b=onConfigChange(f,(function(){_=f,g.config=_}));function _initializeAutomaticSession(){var f=I.get(C());if(f&&be(f.split))_initializeAutomaticSessionWithData(f);else{var S=getStorage(T,C());S&&_initializeAutomaticSessionWithData(S)}g.automaticSession.getId()||_renew()}function _initializeAutomaticSessionWithData(f){var S=g.automaticSession,v=f.split("|");v.length>0&&S.setId(v[0]);try{if(v.length>1){var C=+v[1];S.acquisitionDate=+new Date(C),S.acquisitionDate=S.acquisitionDate>0?S.acquisitionDate:0}if(v.length>2){var _=+v[2];S.renewalDate=+new Date(_),S.renewalDate=S.renewalDate>0?S.renewalDate:0}}catch(g){_throwInternal(T,1,510,"Error parsing ai_session cookie, session will be reset: "+g)}0===S.renewalDate&&_throwInternal(T,2,517,"AI session renewal date is 0, session will be reset.")}function _renew(){var f=g.automaticSession,S=(new Date).getTime(),v=g.config.sessionAsGuid;!isUndefined(v)&&v?Me(v)?f.setId(createGuid()):f.setId(createGuid(v)):f.setId(newId(_.idLength||22)),f.acquisitionDate=S,f.renewalDate=S,_setCookie(f.getId(),f.acquisitionDate,f.renewalDate),canUseLocalStorage()||_throwInternal(T,2,505,"Browser does not support local storage. Session durations will be inaccurate.")}function _setCookie(f,S,_){var T=S+g.config.sessionExpirationMs,b=_+g.config.sessionRenewalMs,A=new Date,P=[f,S,_];T<b?A.setTime(T):A.setTime(b);var R=g.config.cookieDomain||null;I.set(C(),P.join("|")+";expires="+A.toUTCString(),null,R),v=(new Date).getTime()}function _setStorage(g,f,S){setStorage(T,C(),[g,f,S].join("|"))}S&&S.add(b),C=function(){return g.config.namePrefix?fp+g.config.namePrefix:fp},g.automaticSession=new mp,g.update=function(){g.automaticSession.getId()||_initializeAutomaticSession();var f=g.automaticSession,S=g.config,C=(new Date).getTime(),_=C-f.acquisitionDate>S.sessionExpirationMs,T=C-f.renewalDate>S.sessionRenewalMs;if(_||T)_renew();else{(!v||C-v>SessionManager.cookieUpdateInterval)&&(f.renewalDate=C,_setCookie(f.getId(),f.acquisitionDate,f.renewalDate))}},g.backup=function(){var f=g.automaticSession;_setStorage(f.getId(),f.acquisitionDate,f.renewalDate)}}))}return SessionManager.cookieUpdateInterval=6e4,SessionManager}(),vp=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function _validateAppExpId(g,f){void 0===f&&(f=vp);var S=null;if(g)for(var v=g.split(","),C=0;C<v.length;C++)_isValidAppFlightId(v[C],f)&&(S?S+=","+v[C]:S=v[C]);return S}function _isValidAppFlightId(g,f){if(void 0===f&&(f=vp),!g||g.length<4)return!1;for(var S=!1,v=256,C=g.substring(0,3).toString().toUpperCase(),_=0;_<f.length;_++)if(f[_]+":"===C&&g.length<=v){S=!0;break}return S}function _getExpId(){return this.getExpId()}var Cp=function(){function Application(g,f,S){var v,C=null,_=vp.slice(0),T="Treatments",I=null;dynamicProto$3(Application,this,(function(b){if(_populateDefaults(g),hasDocument()){var A=nt().documentElement;A&&(b.locale=A.lang)}function _getMetaDataFromDOM(g){var f,S={},v=nt();if(v){f=v&&v.querySelectorAll("meta");for(var C=0;C<f.length;C++){var _=f[C];if(_.name)if(0===_.name.toLowerCase().indexOf(g))S[_.name.replace(g,"")]=_.content}}return S}function _setAppExpId(g){g!==C&&(C=_validateAppExpId(g,_))}function _readExpIdFromCookie(){return _setAppExpId(getCookieValue(v,T)),C}function _readExpIdFromCoreData(g){return _setAppExpId(g),C}function _populateDefaults(g){var C=onConfigChange(g,(function(){v=f&&f.getCookieMgr(),I=g||{},b.env=I.env||_getMetaDataFromDOM("awa-").env}));S&&S.add(C)}b.getExpId=function(){return I.expId?_readExpIdFromCoreData(I.expId):_readExpIdFromCookie()}}))}return Application.validateAppExpId=_validateAppExpId,Application._staticInit=void objDefine(Application.prototype,"expId",{g:_getExpId}),Application}(),yp=function(){function Cloud(){}return Cloud}(),Ep=function(){function Device(){}return Device}();
/**
	* Cloud.ts
	* @author Hector Hernandez (hectorh)
	* @copyright Microsoft 2020
	*/function _getMsfpc$1(){return this.getMsfpc()}function _getAnid(){return this.getAnid()}var _p=function(){function IntWeb(g,f,S){var v;dynamicProto$3(IntWeb,this,(function(C){function _populateDefaults(g){var _=onConfigChange(g,(function(){v=f&&f.getCookieMgr();var S=g||{};S.serviceName&&(C.serviceName=S.serviceName)}));S&&S.add(_)}_populateDefaults(g),C.getMsfpc=function(){return getCookieValue(v,"MSFPC")},C.getAnid=function(){return getCookieValue(v,"ANON").slice(0,34)}}))}var g;return IntWeb._staticInit=(objDefine(g=IntWeb.prototype,"msfpc",{g:_getMsfpc$1}),void objDefine(g,"anid",{g:_getAnid})),IntWeb}(),Tp=function(){function Loc(){var g=(new Date).getTimezoneOffset(),f=g%60,S=(g-f)/60,v="+";S>0&&(v="-"),S=Math.abs(S),f=Math.abs(f),this.tz=v+(S<10?"0"+S:S.toString())+":"+(f<10?"0"+f:f.toString())}return Loc}(),Ip={WIN:/(windows|win32)/i,WINRT:/ arm;/i,WINPHONE:/windows\sphone\s\d+\.\d+/i,OSX:/(macintosh|mac os x)/i,IOS:/(ipad|iphone|ipod)(?=.*like mac os x)/i,LINUX:/(linux|joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)/i,ANDROID:/android/i,CROS:/CrOS/i},bp={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},Ap="([\\d,.]+)",Pp="([\\d,_,.]+)",Rp="Unknown",Mp=[{r:Ip.WINPHONE,os:"Windows Phone"},{r:Ip.WINRT,os:"Windows RT"},{r:Ip.WIN,os:"Windows"},{r:Ip.IOS,os:"iOS"},{r:Ip.ANDROID,os:"Android"},{r:Ip.LINUX,os:"Linux"},{r:Ip.CROS,os:"Chrome OS"},{s:"x11",os:"Unix"},{s:"blackberry",os:"BlackBerry"},{s:"symbian",os:"Symbian"},{s:"nokia",os:"Nokia"},{r:Ip.OSX,os:"Mac OS X"}];
/**
	* Loc.ts
	* @author Hector Hernandez (hectorh)
	* @copyright Microsoft 2019
	*/function _getOsName(g){for(var f=0;f<Mp.length;f++){var S=Mp[f];if(S.r&&g.match(S.r))return S.os;if(S.s&&-1!==g.indexOf(S.s))return S.os}return Rp}function _getOsVersion(g,f){return"Windows"===f?_getGenericOsVersion(g,"Windows NT"):"Android"===f?_getGenericOsVersion(g,f):"Mac OS X"===f?_getMacOsxVersion(g):"iOS"===f?_getIosVersion(g):Rp}function _getGenericOsVersion(g,f){var S=g.match(new RegExp(f+" "+Ap));return S?bp[S[1]]?bp[S[1]]:S[1]:Rp}function _getMacOsxVersion(g){var f=g.match(new RegExp("Mac OS X "+Pp));if(f){var S=f[1].replace(/_/g,".");if(S){var v=_getDelimiter(S);return v?S.split(v)[0]:S}}return Rp}function _getIosVersion(g){var f=g.match(new RegExp("OS "+Pp));if(f){var S=f[1].replace(/_/g,".");if(S){var v=_getDelimiter(S);return v?S.split(v)[0]:S}}return Rp}function _getDelimiter(g){return g.indexOf(".")>-1?".":g.indexOf("_")>-1?"_":null}var wp=function(){function OperatingSystem(g,f){var S=this,v=null,C=null,_=null,T=null,_setSysName=function(g){_=g},_setSysVer=function(g){T=g},_getSysName=function(){return _||v},_getSysVer=function(){return T||C},I=onConfigChange(g,(function(){if((g||{}).populateOperatingSystemInfo){var f=lt()||{},S=g.userAgent||f.userAgent||"",_=(g.userAgentData||{}).platform||(f.userAgentData||{}).platform;if(S){var T=_getOsName(S.toLowerCase());v=T,C=_getOsVersion(S,T)}v&&v!==Rp||!Ie(_)||(v=_)}}));f&&f.add(I),objDefine(S,"name",{s:_setSysName,g:_getSysName}),objDefine(S,"ver",{s:_setSysVer,g:_getSysVer})}return OperatingSystem}(),Op="MicrosoftApplicationsTelemetryDeviceId";function _saveData(g,f,S,v){f?f.setProperty(S,v):g.set(S,v,31536e3)}function _getData(g,f,S){return f?f.getProperty(S)||"":getCookieValue(g,S)}var Dp=function(){function Sdk(g,f,S){var v,C=0;dynamicProto$3(Sdk,this,(function(_){_.seq=C,_.epoch=random32(!1).toString(),_.getSequenceId=function(){return++C};var T=onConfigChange(g,(function(g){v=f&&f.getCookieMgr();var S=g.cfg.propertyStorageOverride;if(v.isEnabled()||S){var C=_getData(v,S,Op);C||(C=newGuid()),_saveData(v,S,Op,C),_.installId=C}else v.purge(Op)}));S&&S.add(T)}))}return Sdk.__ieDyn=1,Sdk}(),Np=function(){function Trace(g,f,S,v,C){var _=this;_.traceId=f||generateW3CId();var T=onConfigChange(g,(function(){var f=g;if(f.enableDistributedTracing&&!S&&(S=generateW3CId().substring(0,16)),_.parentId=_.parentId||S,f.enableApplicationInsightsTrace&&!v){var C=getLocation();C&&C.pathname&&(v=C.pathname)}_.name=_.name||v}));C&&C.add(T)}return Trace}(),kp="setLocalId";function _getLocalId(){return this.getLocalId()}function _setLocalId(g){this[kp](g)}var Lp=function(){function User(g,f,S,v){var C,_,T;dynamicProto$3(User,this,(function(I){if(_populateDefaults(f),"undefined"!=typeof navigator){var b=navigator;I.locale=b.userLanguage||b.language}function _populateMuidFromCookie(){if(!C.hashIdentifiers&&!C.dropIdentifiers){var g=getCookieValue(T,"MUID");g&&(_="t:"+g)}return _}function _populateDefaults(f){var b=onConfigChange(f,(function(){if(T=S&&S.getCookieMgr(),C=f,_=null,T&&T.isEnabled()&&(_populateMuidFromCookie(),C.enableApplicationInsightsUser)){var v=getCookieValue(T,User.userCookieName);if(v){var b=v.split(User.cookieSeparator);b.length>0&&(I.id=b[0])}if(!I.id){I.id=newId(g&&!isUndefined(g.idLength)?g.idLength:22);var A=toISOString(new Date);I.accountAcquisitionDate=A;var P=[I.id,A],R=C.cookieDomain?C.cookieDomain:void 0;T.set(User.userCookieName,P.join(User.cookieSeparator),31536e3,R)}}}));v&&v.add(b)}I.getLocalId=function(){return _||_populateMuidFromCookie()},I[kp]=function(g){_=g}}))}return User.cookieSeparator="|",User.userCookieName="ai_user",User._staticInit=void objDefine(User.prototype,"localId",{g:_getLocalId,s:_setLocalId}),User}(),Fp=1048576,xp=2097152,Up=4194304,Vp=function(){function Utc(g,f){var S=this;S.popSample=100;var v=onConfigChange(g,(function(){S.eventFlags=0,g.hashIdentifiers&&(S.eventFlags=S.eventFlags|Fp),g.dropIdentifiers&&(S.eventFlags=S.eventFlags|xp),g.scrubIpOnly&&(S.eventFlags=S.eventFlags|Up)}));f&&f.add(v)}return Utc}(),Bp=["Required","Analytics","SocialMedia","Advertising"],Hp="([\\d,.]+)",$p="Unknown",jp="Edg/",Gp="EdgiOS/",qp=[{ua:"OPR/",b:"Opera"},{ua:"PhantomJS",b:"PhantomJS"},{ua:"Edge",b:"Edge"},{ua:jp,b:"Edge"},{ua:Gp,b:"Edge"},{ua:"Electron",b:"Electron"},{ua:"Chrome",b:"Chrome"},{ua:"Trident",b:"MSIE"},{ua:"MSIE ",b:"MSIE"},{ua:"Firefox",b:"Firefox"},{ua:"Safari",b:"Safari"},{ua:"SkypeShell",b:"SkypeShell"}],Wp=[{br:"Microsoft Edge",b:"Edge"},{br:"Google Chrome",b:"Chrome"},{br:"Opera",b:"Opera"}];function _userAgentContainsString(g,f){return f.indexOf(g)>-1}function _getBrandVersion(g,f){for(var S=0;S<f.length;S++)if(g==f[S].brand)return f[S].version;return null}function _getBrowserName(g){if(g)for(var f=0;f<qp.length;f++){if(_userAgentContainsString(qp[f].ua,g))return qp[f].b}return $p}function _getBrowserVersion(g,f){return"MSIE"===f?_getIeVersion(g):_getOtherVersion(f,g)}function _getIeVersion(g){var f=g.match(new RegExp("MSIE "+Hp));if(f)return f[1];var S=g.match(new RegExp("rv:"+Hp));return S?S[1]:void 0}function _getOtherVersion(g,f){"Safari"===g?g="Version":"Edge"===g&&(_userAgentContainsString(jp,f)?g="Edg":_userAgentContainsString(Gp,f)&&(g="EdgiOS"));var S=f.match(new RegExp(g+"/"+Hp));return S||"Opera"===g&&(S=f.match(new RegExp("OPR/"+Hp)))?S[1]:$p}function _getScreenResolution(){var g={h:0,w:0},f=rt();return f&&f.screen&&(g.h=screen.height,g.w=screen.width),g}function _getUserConsent(){return this.getUserConsent()}var zp=function(){function Web(g,f,S){safeGetCookieMgr(f);var v=g||{},C=null,_=null,T=null,I=null,b=null,A=null,P=null;dynamicProto$3(Web,this,(function(f){_populateDefaults(g);var R=getLocation();if(R){var M=R.hostname;M&&(f.domain="file:"===R.protocol?"local":M)}var w=_getScreenResolution();function _parseUserAgent(g,f){if(Ae(f))try{for(var S=0;S<Wp.length;S++){var v=_getBrandVersion(Wp[S].br,f);if(v)return b=Wp[S].b,void(A=v)}}catch(g){}if(g){var C=_getBrowserName(g);b=C,A=_getBrowserVersion(g,C)}}function _setBrowser(g){T=g}function _setBrowserVer(g){I=g}function _getBrowser(){return T||b}function _getBrowserVer(){return I||A}f.screenRes=w.w+"X"+w.h,f.getUserConsent=function(){return!1},f.getUserConsentDetails=function(){var g=null;try{var f=v.callback;if(f&&f.userConsentDetails){var S=f.userConsentDetails();if(S){g=v.disableConsentDetailsSanitize?S:{};for(var C=0;C<Bp.length;C++){var _=Bp[C];g[_]=S[_]||!1}}}return null!==P&&((g=g||{}).GPC_DataSharingOptIn=!!P),g?JSON.stringify(g):null}catch(g){}};var _getGpcDataSharing=function(){return P},_setGpcDataSharing=function(g){P=Me(g)?g:null,v.gpcDataSharingOptIn=P};function _populateDefaults(g){var f=onConfigChange(g,(function(){if((v=g).populateBrowserInfo){var f=v.userAgent,S=(v.userAgentData||{}).brands;if(f!==C||S!==_){if(!f||!S||0===S.length){var T=lt();T&&(f=f||T.userAgent||"",S=S||(T.userAgentData||{}).brands)}_parseUserAgent(f,S),C=f,_=S}}P=Me(v.gpcDataSharingOptIn)?v.gpcDataSharingOptIn:null}));S&&S.add(f)}objDefineProps(f,{userConsent:{g:f.getUserConsent},browser:{s:_setBrowser,g:_getBrowser},browserVer:{s:_setBrowserVer,g:_getBrowserVer},gpcDataSharingOptIn:{g:_getGpcDataSharing,s:_setGpcDataSharing}})}))}return Web._staticInit=void objDefine(Web.prototype,"userConsent",{g:_getUserConsent}),Web}();function _applyExtValues(g,f,S,v,C){var _=f.ext[tp[g]];if(_)try{objForEachKey(v,(function(g,f){if(Ie(f)||Re(f)||Me(f)){var v=_[S[g]];!C&&(v||Ie(v)||Re(v)||Me(v))&&(f=v),_[S[g]]=f}}))}catch(g){}return _}var Kp,Jp=function(){function TelemetryContext(g,f,S,v){dynamicProto$3(TelemetryContext,this,(function(C){C.app=new Cp(f,S,v),C.cloud=new yp,C.user=new Lp(g,f,S,v),C.os=new wp(f,v),C.web=new zp(f,S,v);var _=new Dp(g,S,v),T=new _p(f,S,v),I=new Vp(f,v);C.loc=new Tp,C.device=new Ep;var b=new Sp(S,f,v);C.session=new mp;var A=void 0,P=createDistributedTraceContextFromTraceCtx(new Np(f,A,A,A,v),_getTraceCtx()),R=!(f||{}).eventContainExtFields;function _getSessionId(){var g=C.session;if(g&&Ie(g.customId))return g.customId;b.update();var f=b.automaticSession;if(f){var S=f.getId();S&&Ie(S)&&(g.automaticId=S)}return g.automaticId}function _getTraceCtx(){var g=P;return S&&S.getTraceCtx&&(g=S.getTraceCtx(!1)||P),g}C.getTraceCtx=function(){return P},C.getSessionId=_getSessionId,C.applyApplicationContext=function(g){var f,S=C.app;_applyExtValues(4,g,ip,((f={})[0]=S.id,f[1]=S.ver,f[2]=S.name,f[3]=S.locale,f[4]=S.getExpId(),f[5]=S.env,f),R)},C.applyUserContext=function(g){var f,S=C.user;_applyExtValues(0,g,rp,((f={})[1]=S.getLocalId(),f[0]=S.locale,f[2]=S.id,f),R)},C.applyWebContext=function(g){var f,S=C.web;_applyExtValues(3,g,np,((f={})[0]=S.domain,f[1]=S.browser,f[2]=S.browserVer,f[3]=S.screenRes,f[5]=S.getUserConsentDetails(),f[4]=!1,f),R)},C.applyOsContext=function(g){var f,S=C.os;_applyExtValues(5,g,sp,((f={})[0]=S.name,f[1]=S.ver,f),R)},C.applySdkContext=function(g){var f;_applyExtValues(6,g,ap,((f={})[2]=_.installId,f[1]=_.getSequenceId(),f[3]=_.epoch,f),R)},C.applyIntWebContext=function(g){var f;_applyExtValues(7,g,op,((f={})[0]=T.getMsfpc(),f[1]=T.getAnid(),f[2]=T.serviceName,f),R)},C.applyUtcContext=function(g){var f,S=((f={})[0]=I.popSample,f);I.eventFlags>0&&(S[1]=I.eventFlags),_applyExtValues(8,g,lp,S,R)},C.applyLocContext=function(g){var f;_applyExtValues(9,g,cp,((f={})[0]=C.loc.tz,f),R)},C.applySessionContext=function(g){var f;_applyExtValues(4,g,dp,((f={})[0]=_getSessionId(),f),R)},C.applyDeviceContext=function(g){var f,S=C.device;_applyExtValues(1,g,hp,((f={})[0]=S.localId,f[2]=S.make,f[3]=S.model,f[1]=S.deviceClass,f),R)},C.applyCloudContext=function(g){var f,S=C.cloud;_applyExtValues(10,g,up,((f={})[0]=S.role,f[1]=S.roleInstance,f[2]=S.roleVer,f),R)},C.applyAITraceContext=function(g){var S;if(f.enableApplicationInsightsTrace){var v=_getTraceCtx();v&&_applyExtValues(2,g,gp,((S={})[0]=v.getTraceId(),S[1]=v.getName(),S[2]=v.getSpanId(),S),!1)}},C.applyDistributedTraceContext=function(g){var f,S=_getTraceCtx();if(S){var v=((f={})[0]=S.getTraceId(),f[1]=S.getSpanId(),f),C=S.getTraceFlags();isNullOrUndefined(C)||(v[2]=C),_applyExtValues(11,g,pp,v,!1)}}}))}return TelemetryContext.__ieDyn=1,TelemetryContext}();function createDistributedTraceContextFromTraceCtx(g,f){var S=g||{};return{getName:function(){return S.name},setName:function(g){f&&f.setName(g),S.name=g},getTraceId:function(){return S.traceId},setTraceId:function(g){f&&f.setTraceId(g),isValidTraceId(g)&&(S.traceId=g)},getSpanId:function(){return S.parentId},setSpanId:function(g){f&&f.setSpanId(g),isValidSpanId(g)&&(S.parentId=g)},getTraceFlags:function(){return S.traceFlags},setTraceFlags:function(g){f&&f.setTraceFlags(g),S.traceFlags=g}}}var Yp=[tp[4],tp[0],tp[3],tp[5],tp[6],tp[7],tp[8],tp[9],tp[1],tp[2],tp[11],tp[10]],Qp=objDeepFreeze({populateBrowserInfo:!1,populateOperatingSystemInfo:!1,userAgent:cfgDfString(),userAgentData:cfgDfMerge$1({brands:Kp,mobile:Kp,platform:Kp}),userConsentCookieName:cfgDfString(),userConsented:!1,serviceName:cfgDfString(),env:cfgDfString(),expId:cfgDfString(),sessionRenewalMs:18e5,sessionExpirationMs:864e5,sessionAsGuid:null,cookieDomain:cfgDfString(),namePrefix:cfgDfString(),enableApplicationInsightsTrace:!1,enableApplicationInsightsUser:!1,hashIdentifiers:!1,dropIdentifiers:!1,scrubIpOnly:!1,callback:cfgDfMerge$1({userConsentDetails:null}),gpcDataSharingOptIn:Kp,idLength:22,enableDistributedTracing:!1,eventContainExtFields:!1}),Xp=function(g){function PropertiesPlugin(){var f,S,v,C=g.call(this)||this;return C.identifier="SystemPropertiesCollector",C.priority=3,C.version="4.3.2",dynamicProto$3(PropertiesPlugin,C,(function(g,C){function _initDefaults(){f=null,S={}}function _populateDefaults(S){var C=g.identifier,_=g.core;g._addHook(onConfigChange(S,(function(){var g=createProcessTelemetryContext(null,S,_);v=g.getExtCfg(C,Qp)}))),f=new Jp(S,v,_,g._unloadHooks),_&&_.setTraceCtx&&_.setTraceCtx(f.getTraceCtx())}function _addPropertiesIfAbsent(g,f){g&&objForEachKey(g,(function(g,S){f[g]||(f[g]=S)}))}_initDefaults(),g.initialize=function(g,f,S){C.initialize(g,f,S),_populateDefaults(g)},g.processTelemetry=function(C,_){setProcessTelemetryTimings(C,g.identifier),_=g._getTelCtx(_);var T=C.ext=C.ext?C.ext:{};C.data=C.data?C.data:{},arrForEach(Yp,(function(g){T[g]=T[g]||{}})),f&&(f.applyUtcContext(C),f.applyApplicationContext(C),f.applyUserContext(C),f.applyWebContext(C),f.applyOsContext(C),f.applySdkContext(C),f.applyIntWebContext(C),f.applyLocContext(C),f.applySessionContext(C),f.applyDeviceContext(C),v.enableApplicationInsightsTrace&&f.applyAITraceContext(C),v.enableDistributedTracing&&f.applyDistributedTraceContext(C),f.applyCloudContext(C)),arrForEach(Be(T),(function(g){0===Be(T[g]).length&&delete T[g]})),_addPropertiesIfAbsent(S,C.data),g.processNext(C,_)},g.getPropertiesContext=function(){return f},g.setProperty=function(g,f){S[g]=f},g._doTeardown=function(g,S){var v=(g||{}).core();if(v&&v.getTraceCtx&&f){var C=v.getTraceCtx(!1);C&&C===f.getTraceCtx()&&v.setTraceCtx(null)}_initDefaults()},g._getDbgPlgTargets=function(){return[v]}})),C}return __extendsFn$3(PropertiesPlugin,g),PropertiesPlugin.__ieDyn=1,PropertiesPlugin}(Gs);function generateGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(g=>{const f=16*Math.random()|0;return("x"===g?f:3&f|8).toString(16)}))}const Zp="Skype",em={Public:"https://ic3.events.data.microsoft.com/OneCollector/1.0/",PublicEUDB:"https://eu-ic3.events.data.microsoft.com/OneCollector/1.0/",GccHigh:"https://tb.events.data.microsoft.com/OneCollector/1.0/",Dod:"https://pf.events.data.microsoft.com/OneCollector/1.0/",AirGap08:"https://collector.azure.eaglex.ic.gov/OneCollector/1.0/",AirGap09:"https://collector.azure.microsoft.scloud/OneCollector/1.0/",Enterprise:"https://teams.events.data.microsoft.com/OneCollector/1.0",EnterpriseEUDB:"https://eu-teams.events.data.microsoft.com/OneCollector/1.0"};var tm,im;!function(g){g.Public="Public",g.GccHigh="GCCHigh",g.Dod="DoD",g.AirGap08="AirGap08",g.AirGap09="AirGap09"}(tm||(tm={})),function(g){g.OrgId="orgid",g.Acs="acs",g.Spool="spool",g.GccHigh="gcch",g.GccHighAcs="gcch-acs",g.Dod="dod",g.DodAcs="dod-acs",g.AirGap08="ag08",g.AirGap08Acs="ag08-acs",g.AirGap09="ag09",g.AirGap09Acs="ag09-acs"}(im||(im={}));const nm={Public_EcsServer_Url:"https://ecs.communication.microsoft.com",GccHigh_EcsServer_Url:"https://config.ecs.gov.teams.microsoft.us",Dod_EcsServer_Url:"https://config.ecs.dod.teams.microsoft.us",AirGap08_EcsServer_Url:"https://config.ecs.teams.eaglex.ic.go",AirGap09_EcsServer_Url:"https://config.ecs.teams.microsoft.scloud",Enterprise_Ecs_ServerUrl:"https://config.teams.microsoft.com"},rm={Public_ConversationServiceUrl:"https://api.flightproxy.skype.com/api/v2/cpconv",Public_TrouterServiceUrl:"https://go.trouter.communication.microsoft.com/v4/a",Public_RegistrarServiceUrl:"https://prod.registrar.skype.com/v3/registrations",Public_MdnTrapServiceUrl:"https://edge.skype.com/trap",Public_MdnTrapServiceTokenUrl:"https://edge.skype.com/trap/tokens",Public_MdnTrapRelaySkypeFqdns:"worldaz.tr.skype.com",Public_MdnTrapRelayTurnFqdns:"turn.azure.com",Public_MdnTrapRelayTurnUrl:"",GccHigh_ConversationServiceUrl:"https://api.cc.gov.teams.microsoft.us/conv/",GccHigh_TrouterServiceUrl:"https://go.trouter.gov.teams.microsoft.us/v4/a",GccHigh_RegistrarServiceUrl:"https://registrar.gov.teams.microsoft.us/v3/registrations",GccHigh_MdnTrapServiceUrl:"https://trap.gov.teams.microsoft.us",GccHigh_MdnTrapServiceTokenUrl:"https://trap.gov.teams.microsoft.us/tokens",GccHigh_MdnTrapRelaySkypeFqdns:"tr.gov.teams.microsoft.us",GccHigh_MdnTrapRelayTurnFqdns:"turn.gov.teams.microsoft.us",GccHigh_MdnTrapRelayTurnUrl:"https://turn.gov.teams.microsoft.us/relay",Dod_ConversationServiceUrl:"https://api.cc.dod.teams.microsoft.us/conv/",Dod_TrouterServiceUrl:"https://go.trouter.dod.teams.microsoft.us/v4/a",Dod_RegistrarServiceUrl:"https://registrar.dod.teams.microsoft.us/v3/registrations",Dod_MdnTrapServiceUrl:"https://trap.dod.teams.microsoft.us",Dod_MdnTrapServiceTokenUrl:"https://trap.dod.teams.microsoft.us/tokens",Dod_MdnTrapRelaySkypeFqdns:"tr.dod.teams.microsoft.us",Dod_MdnTrapRelayTurnFqdns:"turn.dod.teams.microsoft.us",Dod_MdnTrapRelayTurnUrl:"https://turn.dod.teams.microsoft.us/relay",AirGap08_ConversationServiceUrl:"https://api.cc.skype.com/conv/",AirGap08_TrouterServiceUrl:"https://go.trouter.teams.eaglex.ic.gov/v4/a",AirGap08_RegistrarServiceUrl:"https://api.registrar.teams.eaglex.ic.gov/v3/registrations",AirGap09_ConversationServiceUrl:"https://api.cc.skype.com/conv/",AirGap09_TrouterServiceUrl:"https://go.trouter.teams.microsoft.scloud/v4/a",AirGap09_RegistrarServiceUrl:"https://api.registrar.teams.microsoft.scloud/v3/registrations",Enterprise_ConversationServiceUrl:"https://api.flightproxy.teams.microsoft.com/api/v2/epconv",Enterprise_TrouterServiceUrl:"https://go.trouter.teams.microsoft.com/v4/a",Enterprise_RegistrarServiceUrl:"https://teams.microsoft.com/registrar/prod/v3/registrations",Enterprise_MdnTrapServiceUrl:"https://teams.microsoft.com/trap",Enterprise_MdnTrapServiceTokenUrl:"https://teams.microsoft.com/trap/tokens",Enterprise_MdnTrapRelaySkypeFqdns:"worldaz.relay.teams.microsoft.com",Enterprise_MdnTrapRelayTurnFqdns:"worldaz.relay.teams.microsoft.com",Enterprise_MdnTrapRelayTurnUrl:""};var sm;!function(g){g.Public_ConversationServiceUrl_EUDB="https://api.flightproxy.skype.com/api/v2/cpconv",g.Public_TrouterServiceUrl_EUDB="https://go-eu.trouter.communication.microsoft.com/v4/a",g.Public_RegistrarServiceUrl_EUDB="https://emea.prod.registrar.skype.com/v3/registrations",g.Public_MdnTrapServiceUrl_EUDB="https://edge.skype.com/trap",g.Public_MdnTrapServiceTokenUrl_EUDB="https://edge.skype.com/trap/tokens",g.Public_MdnTrapRelaySkypeFqdns_EUDB="eu.relay.skype.com",g.Public_MdnTrapRelayTurnFqdns_EUDB="eu.relay.skype.com",g.Public_MdnTrapRelayTurnUrl_EUDB="",g.Enterprise_ConversationServiceUrl_EUDB="https://api.flightproxy.teams.microsoft.com/api/v2/epconv",g.Enterprise_TrouterServiceUrl_EUDB="https://go-eu.trouter.teams.microsoft.com/v4/a",g.Enterprise_RegistrarServiceUrl_EUDB="https://teams.microsoft.com/registrar/prod/v3/registrations",g.Enterprise_MdnTrapServiceUrl_EUDB="https://teams.microsoft.com/trap",g.Enterprise_MdnTrapServiceTokenUrl_EUDB="https://teams.microsoft.com/trap/tokens",g.Enterprise_MdnTrapRelaySkypeFqdns_EUDB="euaz.relay.teams.microsoft.com",g.Enterprise_MdnTrapRelayTurnFqdns_EUDB="euaz.relay.teams.microsoft.com",g.Enterprise_MdnTrapRelayTurnUrl_EUDB=""}(sm||(sm={}));const am={...rm,...nm},om={baseServiceUrl:"https://global.mtgw.prod.communication.microsoft.com/",policyUrlSuffix:"acsmt/v1/useraggregatepolicysettings/",policyUrlSuffixV2:"acsmt/v2/useraggregatepolicysettings/",createThreadSuffix:"acsmt/v1/threads/",addParticipantSuffix:"acsmt/v1/addParticipantsToThread/"};var lm,cm;!function(g){g.Consumer="consumer",g.Enterprise="enterprise"}(lm||(lm={})),function(g){g.TeamsMultiPersona="teamsMultiPersona",g.ACSByoi="acsByoi",g.TeamsUser="teamsUser",g.TeamsDod="teamsDod",g.TeamsGov="teamsGov",g.TeamsAG08="teamsAG08",g.TeamsAG09="teamsAG09",g.TeamsAnonymous="teamsVisitor",g.ACSPublicLegacy="spool",g.ACSDod="dod-acs",g.ACSGov="gcch-acs",g.ACSAg08="ag08-acs",g.ACSAg09="ag09-acs",g.Unknown="unknown"}(cm||(cm={}));const dm=["europe","france","germany","norway","switzerland","sweden"],hm=["emea","fr","de","se"],um=Array.from(new Set(dm.concat(["qatar","uae","africa","uk"]))),gm=["asiapacific","india","japan","korea","australia"],pm=["unitedstates","brazil","canada"];var mm,fm;!function(g){g.EU="EU",g.RoW="RoW"}(mm||(mm={})),function(g){g.APAC="APAC",g.NOAM="NOAM",g.EMEA="EMEA",g.UNKNOWN=""}(fm||(fm={}));const Sm={AUDIO:{JITTER:{GOOD:30,AVERAGE:75},RTT:{GOOD:200,AVERAGE:350},PACKETS_LOSS_PERCENTAGE:{GOOD:3,AVERAGE:6}},VIDEO:{JITTER:{GOOD:20,AVERAGE:75},RTT:{GOOD:200,AVERAGE:350},PACKETS_LOSS_PERCENTAGE:{GOOD:3,AVERAGE:6}},BANDWIDTH:{GOOD:1500,AVERAGE:500},CALL:{DURATION_IN_SEC:30,GROUP_ID:generateGuid(),AGGREGATION:{INTERVAL:1e3,DATAPOINTS:1},VIDEO_SIZE:{heigth:720,width:1280},MEDIASTREAM_TIMEOUT_IN_SEC:15,CONNECT_TIMEOUT_IN_SEC:10}};var vm;!function(g){g.AcsOrganizerRole="acsorganizer",g.AcsPresenterRole="acspresenter",g.AcsAttendeeRole="acsattendee",g.AcsConsumerRole="acsconsumer",g.TeamsOrganizer="organizer",g.TeamsAttendee="attendee",g.TeamsPresenter="presenter",g.TeamsCoorganizer="coorganizer"}(vm||(vm={}));const Cm=["airpod","bluetooth","hands-free","stereo","wireless","citrix hdx","remote audio","vmware","built-in","integrated","internal","teams","high definition","facetime","macbook","smartaudio","front","rear","back","iphone","ipad","display","displayport","dp","hdmi","amd","nvidia","intel","analog","digital","dock","line( in| out)?","s/pdif","external","thunderbolt\\d*","usb","panoramic","desktop","capture","cable","cam","virtual","manycam","snap camera","obs","vb-audio","vaio","effect","sink","source","default","test"],ym="28:9cd07db6-fab5-438c-8e34-44117fac7650",Em="28:b102ccd8-1925-448b-90a7-b083aba25074";let _m="3617";const getPlatformId=()=>_m,Tm=2e3,Im=5e4,bm=3e4,Am=25e3,Pm=6e3,Rm=5e3,Mm=1e3,wm=3,Om="acs_broadcast_channel",Dm=5e3,Nm=500,km=!1,Lm=500,Fm=512,xm=0,Um=.4,Vm=200,Bm=100,Hm=255,$m=-127,jm=6e3,Gm=2500,qm=1500,Wm=5e3,zm=12,Km=2e4,Jm=6e4,Ym={WIDTH:0,HEIGHT:0},Qm=0,Xm=6e3,Zm=100,ef=4,tf="4cf9ed87f7dc4e148f77855cd1f2fdca-61fb83a7-6672-4264-806f-7aded29f9b49-7618",nf="53fdaa090eb946b5a1d6cbdeb4f2ef66-bcbf6380-2590-41cc-ae60-9e467cd51835-7413",rf="1cae5691997646c98b01d15beddae7a3-ce16e198-bc32-420f-ac64-42bb916111af-6865",sf="2efdf03d07594586a5977c404e185186-71b046c4-f48f-4ba7-96d3-2a74b54e1d46-7326",af="708a9eb9fe2646fe8f4c37b7eee2e3da-9b97485a-57b9-43a8-8177-07ca7a653a30-6706",of=7e3,lf=10,cf=3,df="28:8133db4c-c049-4346-9edd-273f164a9227",hf="28:b1902c3e-b9f7-4650-9b23-5772bd429747",uf="28:bdd75849-e0a6-4cce-8fc1-d7c0d4da43e5",gf="28:4b25d9f8-18f5-4d09-a582-cd0a28f63181",pf="ACS-Public",mf="Teams-Public",ff=["en-us"],Sf=["en"],vf="en-us",Cf=10,yf="setLanguage",Ef="mode",_f="Transcription",Tf="RecordingAndTranscription",If="transcriptionModes",bf="processingModes",Af=["closedCaptions"],Pf=["scheduledMeeting","adhocMeeting"],Rf=["28:f4693563-c70b-4e4d-bda6-01792aa21440","28:e32c9418-a835-4eb1-bfb9-733fa74dd6e8"],Mf=["28:5f2511f1-6da9-41d9-80d9-af7da23a2c27","28:accb0009-8d12-4cfe-969c-39b204e3ed0c"],wf="tlePlayer",Of=256,Df="0.0",Nf=!0,kf=Symbol("global_telemetry_logger"),Lf=Symbol("global_call_client_index"),Ff=107,xf="orgid",Uf="dod",Vf="gcch",Bf="8:",Hf="28:",$f="4:",jf=":",Gf="Unknown",qf="ACSWeb",Wf=Bf+(xf+jf),zf=Bf+(Uf+jf),Kf=Bf+(Vf+jf),Jf=Bf+("ag08"+jf),Yf=Bf+("ag09"+jf),Qf=Bf+("teamsvisitor"+jf),Xf=Bf+("acs"+jf),Zf=Bf+("spool"+jf),eS=Bf+("dod-acs"+jf),tS=Bf+("gcch-acs"+jf),iS=Bf+("ag08-acs"+jf),nS=Bf+("ag09-acs"+jf),rS=Hf+(xf+jf),sS=Hf+(Vf+jf),aS=Hf+(Uf+jf),oS={audioBitrate:{aggregation_needed:!1,raw_data_reduction:!0},videoBitrate:{aggregation_needed:!1,raw_data_reduction:!0},downloadBitrate:{aggregation_needed:!0,multiplier:8,integer:!0,calculation_method:"rate"},bufferLengthInMs:{aggregation_needed:!0},mediaDelayInMs:{aggregation_needed:!0,is_internal:!0},videoHeight:{aggregation_needed:!1,raw_data_reduction:!0},videoWidth:{aggregation_needed:!1,raw_data_reduction:!0},playerHeight:{aggregation_needed:!1,raw_data_reduction:!0,is_internal:!0},playerWidth:{aggregation_needed:!1,raw_data_reduction:!0,is_internal:!0},currentPlayPosition:{aggregation_needed:!1,raw_data_reduction:!0}};var lS,cS;!function(g){g.GroupCall="joinGroupId",g.GroupChatCall="joinThreadId",g.TeamsCoordinates="joinMeetingCoordinates",g.TeamsMeetingId="joinMeetingId",g.TeamsMeetingLink="joinMeetingLink",g.RoomCall="joinRoom",g.Unknown="Unknown"}(lS||(lS={})),function(g){g.Organizer="Organizer",g.Coorganizer="Co-organizer",g.Attendee="Attendee",g.Presenter="Presenter",g.Consumer="Consumer",g.Unknown="Unknown"}(cS||(cS={}));const dS={"msft-acs-room-deviceType":"room","msft-acs-3proom-deviceType":"3proom","msft-acs-mesh-deviceType":"mesh","msft-acs-mesh-deviceType-v2":"meshV2"};var hS,uS;!function(g){g.onlyUsedProxy="onlyUsedProxy",g.onlyUsedNonMsftTurn="onlyUsedNonMsftTurn",g.usedProxyAndNonMsftTurn="usedProxyAndNonMsftTurn",g.noCustomProxyAndTurnUsed="noCustomProxyAndTurnUsed"}(hS||(hS={})),function(g){g.RoleRestricted="RoleRestricted",g.FeatureNotSupported="FeatureNotSupported",g.ClientRestricted="ClientRestricted",g.MeetingRestricted="MeetingRestricted",g.UserPolicyRestricted="UserPolicyRestricted",g.TeamsPremiumLicenseRestricted="TeamsPremiumLicenseRestricted",g.NotInitialized="NotInitialized",g.Capable="Capable",g.NotCapable="NotCapable",g.CapabilityNotApplicableForTheCallType="CapabilityNotApplicableForTheCallType",g.IpModeUserPolicyRestricted="IpModeUserPolicyRestricted",g.ExplicitConsentRequired="ExplicitConsentRequired"}(uS||(uS={}));const gS="roomsRoleBasedCapabilities",pS="teamsRoleBasedCapabilities",mS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,fS=/(\:[0-9]{1,6})(?=$|\/|\?)/;var SS,vS;!function(g){g.TeamsProMgmt="TeamsProMgmt"}(SS||(SS={})),function(g){g.Disabled="Disabled",g.DisabledUserOverride="DisabledUserOverride"}(vS||(vS={}));const CS={Unknown:"Unknown",UsbCamera:"UsbCamera",CaptureAdapter:"CaptureAdapter",Virtual:"Virtual",ScreenSharing:"ScreenSharing"};var yS;function getMriFromIdentifier(g){const f=S.getIdentifierKind(g);switch(f.kind){case yS.communicationUser:return f.communicationUserId;case yS.phoneNumber:if(f.rawId)return`${f.rawId}`;if(f.phoneNumber)return`${$f}${f.phoneNumber}`;throw new CallingCommunicationError({defaultError:D.IDENTIFIER.PARSE_PHONENUMBER});case yS.microsoftTeamsUser:if(f.rawId)return f.rawId;if(f.microsoftTeamsUserId){if(f.isAnonymous)return`${Qf}${f.microsoftTeamsUserId}`;if("public"===f.cloud)return`${Wf}${f.microsoftTeamsUserId}`;if("dod"===f.cloud)return`${zf}${f.microsoftTeamsUserId}`;if("gcch"===f.cloud)return`${Kf}${f.microsoftTeamsUserId}`;if(!f.cloud)return`${Wf}${f.microsoftTeamsUserId}`}throw new CallingCommunicationError({defaultError:D.IDENTIFIER.PARSE_MSFT_TEAMS_USER});case yS.microsoftTeamsApp:if(f.rawId)return f.rawId;if(f.teamsAppId){if("public"===f.cloud)return`${rS}${f.teamsAppId}`;if("dod"===f.cloud)return`${aS}${f.teamsAppId}`;if("gcch"===f.cloud)return`${sS}${f.teamsAppId}`;if(!f.cloud)return`${rS}${f.teamsAppId}`}throw new CallingCommunicationError({defaultError:D.IDENTIFIER.PARSE_MSFT_TEAMS_APP});case"unknown":return f.id;default:throw new CallingCommunicationError({defaultError:D.IDENTIFIER.PARSE_IDENTIFIER})}}function getMriType(g){return checkIfTeamsMultipersonaUser(g)?cm.TeamsMultiPersona:g.startsWith(Wf)?cm.TeamsUser:g.startsWith(zf)?cm.TeamsDod:g.startsWith(Kf)?cm.TeamsGov:g.startsWith(Jf)?cm.TeamsAG08:g.startsWith(Yf)?cm.TeamsAG09:g.startsWith(Qf)?cm.TeamsAnonymous:g.startsWith(Xf)?cm.ACSByoi:g.startsWith(Zf)?cm.ACSPublicLegacy:g.startsWith(eS)?cm.ACSDod:g.startsWith(tS)?cm.ACSGov:g.startsWith(iS)?cm.ACSAg08:g.startsWith(nS)?cm.ACSAg09:cm.Unknown}function constructIdentifierKindFromMri(g){const f=checkIfTeamsMultipersonaUser(g);return f?{kind:yS.microsoftTeamsUser,rawId:g,microsoftTeamsUserId:f,isAnonymous:!1,cloud:"public"}:g.startsWith(Wf)?{kind:yS.microsoftTeamsUser,rawId:g,microsoftTeamsUserId:g.substring(8),isAnonymous:!1,cloud:"public"}:g.startsWith(zf)?{kind:yS.microsoftTeamsUser,rawId:g,microsoftTeamsUserId:g.substring(6),isAnonymous:!1,cloud:"dod"}:g.startsWith(Kf)?{kind:yS.microsoftTeamsUser,rawId:g,microsoftTeamsUserId:g.substring(7),isAnonymous:!1,cloud:"gcch"}:g.startsWith(Qf)?{kind:yS.microsoftTeamsUser,rawId:g,microsoftTeamsUserId:g.substring(15),isAnonymous:!0}:g.startsWith($f)?{kind:yS.phoneNumber,rawId:g,phoneNumber:g.substring(2)}:g.startsWith(Xf)||g.startsWith(Zf)||g.startsWith(tS)||g.startsWith(eS)?{kind:yS.communicationUser,communicationUserId:g}:g.startsWith(rS)?{kind:yS.microsoftTeamsApp,rawId:g,teamsAppId:g.substring(9),cloud:"public"}:g.startsWith(sS)?{kind:yS.microsoftTeamsApp,rawId:g,teamsAppId:g.substring(8),cloud:"gcch"}:g.startsWith(aS)?{kind:yS.microsoftTeamsApp,rawId:g,teamsAppId:g.substring(7),cloud:"dod"}:{kind:yS.unknown,id:g}}function checkIfTeamsMultipersonaUser(g){if(g.startsWith(Xf)){const f=g.split("_");if(3===f.length)return f[f.length-1]}return!1}function isCallingApplication(g){return!!g.startsWith(Hf)}function isGlobalCallingApplication(g){return!(!g.startsWith(Hf)||g.startsWith(rS)||g.startsWith(aS)||g.startsWith(sS))}function validateIdentifier(g){const f=S.getIdentifierKind(g);switch(f.kind){case yS.communicationUser:if(!(f.communicationUserId.startsWith(Xf)||f.communicationUserId.startsWith(Zf)||f.communicationUserId.startsWith(tS)||f.communicationUserId.startsWith(eS)))throw new CallingCommunicationError({defaultError:D.IDENTIFIER.INVALID_COMM_USER});return f;case"phoneNumber":return f;case yS.microsoftTeamsUser:if(f.rawId&&!f.rawId.startsWith(Wf)&&!f.rawId.startsWith(zf)&&!f.rawId.startsWith(Kf)&&!f.rawId.startsWith(Qf))throw new CallingCommunicationError({defaultError:D.IDENTIFIER.INVALID_MSFT_TEAMS_USER_RAWID});if(!f.microsoftTeamsUserId)throw new CallingCommunicationError({defaultError:D.IDENTIFIER.INVALID_MSFT_TEAMS_USER_USERID});return f;case yS.microsoftTeamsApp:if(f.rawId&&!f.rawId.startsWith(Hf))throw new CallingCommunicationError({defaultError:D.IDENTIFIER.INVALID_MSFT_TEAMS_APP_RAWID});if(!f.teamsAppId)throw new CallingCommunicationError({defaultError:D.IDENTIFIER.INVALID_MSFT_TEAMS_APP_APPID});return f;case yS.unknown:if(!f.id)throw new CallingCommunicationError({defaultError:D.IDENTIFIER.INVALID_UNKNOWN_IDENTIFIER});return f;default:throw new CallingCommunicationError({defaultError:D.IDENTIFIER.PARSE_INVALID_IDENTIFIER})}}function assertIsArrayOfIdentifiers(g){if(!(g instanceof Array))throw new CallingCommunicationError({defaultError:D.IDENTIFIER.INVALID_IDENTIFIER_ARRAY})}function getCloudTypeFromSkypeId(g){const f=g.substring(0,g.indexOf(":"));if(!f)throw new CallingCommunicationError({defaultError:D.IDENTIFIER.NO_CLOUD_PREFIX_FOUND});switch(f){case im.OrgId:case im.Acs:case im.Spool:return tm.Public;case im.GccHigh:case im.GccHighAcs:return tm.GccHigh;case im.Dod:case im.DodAcs:return tm.Dod;case im.AirGap08:case im.AirGap08Acs:return tm.AirGap08;case im.AirGap09:case im.AirGap09Acs:return tm.AirGap09;default:return tm.Public}}!function(g){g.communicationUser="communicationUser",g.microsoftTeamsUser="microsoftTeamsUser",g.microsoftTeamsApp="microsoftTeamsApp",g.phoneNumber="phoneNumber",g.unknown="unknown",g.group="group"}(yS||(yS={}));const ES="1.33.2.0_stable",_S="1.33.2";function getSdkInternalVersion(){const g="ACS_CLIENT_INTERNAL_SZK_VERSION".replace("Z","D");return ES===g?"1.0.0.0":ES}function getSdkVersion(){const g="ACS_CLIENT_SZK_VERSION".replace("Z","D");return _S===g?"1.0.0.0":_S}function getDateInIsoFormat(){return(new Date).toISOString()}function arrayMergeCustomizer(g,f){if(Array.isArray(g))return f.slice()}function redactUrlQueryParameters(g){try{const f="string"==typeof g?new URL(g):g;return`${f.protocol}//${f.host}${f.pathname}`}catch(g){return""}}function isNonEmptyArray(g){return Array.isArray(g)&&0!==g.length}function isNullOrUndefined$1(g){return null==g||void 0===g}function valueOrDefault(g,f){return void 0!==g?g:f}function isPromiseLike$1(g){return!!g&&"function"==typeof g.then}function safeJsonStringify(g){try{return JSON.stringify(g,null,2)}catch(f){return`failed to stringify obj ${g}`}}function isIpv4Address(g){return new RegExp(mS).test(g)}function clampEmail(g,f){const S=3,v=2,C=1,_=/^(.+)@([^@]+)$/,T=g.match(_),I=T?.[v],b=T?.length===S?T[C]:g,A=b.length>f?`${b.substring(0,f)}***`:b;return I?`${A}@${I}`:A}const calculateWatermarkPatternScaling=(g,f,S)=>{const v=document.documentElement.clientWidth/document.documentElement.clientHeight,C=Math.max(v,1),_=1/C,T=.001,I=.5,b=.5,A=4.5,P=11.5,R=.75,M=24,w=1,O=Math.min(g,f)*T*C;return{scaledFontSize:M*Math.max(R,O)*_,scaledBorderSize:w*Math.max(1,O)*_,scaledHorizontalGap:b*Math.max(I,Math.min(1,O)),scaledVerticalGap:Math.max(P*Math.min(1,O),A*C)}},createTextDiagonalCalculation=g=>{const f=toRadians(90-g),S=1/Math.cos(toRadians(g)),v=1/Math.cos(f),C=Math.tan(f);return(g,f)=>g<C*f?g*S:f*v},toRadians=g=>{const f=180;return g*(Math.PI/f)},TS={"audio.send":{bitrate:{min:0,max:535500},packetsPerSecond:{min:0,max:200},packetsLostPerSecond:{min:0,max:200}},"audio.receive":{bitrate:{min:0,max:535500},packetsPerSecond:{min:0,max:200},packetsLostPerSecond:{min:0,max:200}},"video.send":{bitrate:{min:0,max:8e6},packetsPerSecond:{min:0,max:1e3},packetsLostPerSecond:{min:0,max:1e3},frameRateInput:{min:0,max:66},frameRateEncoded:{min:0,max:66},frameRateSent:{min:0,max:66}},"video.receive":{bitrate:{min:0,max:8e6},packetsPerSecond:{min:0,max:1e3},packetsLostPerSecond:{min:0,max:1e3},frameRateOutput:{min:0,max:66},frameRateDecoded:{min:0,max:66},frameRateReceived:{min:0,max:66}},"screenShare.send":{bitrate:{min:0,max:8e6},packetsPerSecond:{min:0,max:1e3},packetsLostPerSecond:{min:0,max:1e3},frameRateInput:{min:0,max:33},frameRateEncoded:{min:0,max:33},frameRateSent:{min:0,max:33}},"screenShare.receive":{bitrate:{min:0,max:8e6},packetsPerSecond:{min:0,max:1e3},packetsLostPerSecond:{min:0,max:1e3},frameRateOutput:{min:0,max:33},frameRateDecoded:{min:0,max:33},frameRateReceived:{min:0,max:33}}};var IS,bS,AS,PS,RS,MS,wS,OS,DS,NS,kS,LS,FS,xS,US,VS,BS,HS,$S,jS,GS,qS,WS;!function(g){g.Outgoing="Outgoing",g.Incoming="Incoming",g.TransferOutgoing="TransferOutgoing"}(IS||(IS={})),function(g){g.CreateCallAgent="CreateCallAgent",g.CreateTeamsCallAgent="CreateTeamsCallAgent",g.GetDeviceManager="GetDeviceManager",g.GetEnvironmentInfo="GetEnvironmentInfo",g.GetSDKVersion="GetSDKVersion",g.Feature="Feature"}(bS||(bS={})),function(g){g.StartCall="StartCall",g.Join="Join",g.HandlePushNotification="HandlePushNotification",g.Initialize="Initialize",g.Dispose="Dispose",g.CreateCall="CreateCall",g.Feature="Feature"}(AS||(AS={})),function(g){g.Call="Call",g.StartCall="StartCall",g.CallGroup="CallGroup",g.JoinGroup="JoinGroup",g.Accept="Accept",g.Reject="Reject",g.Mute="Mute",g.Unmute="Unmute",g.MuteAllRemoteParticipants="MuteAllRemoteParticipants",g.MuteIncomingAudio="MuteIncomingAudio",g.UnmuteIncomingAudio="UnmuteIncomingAudio",g.SendDtmf="SendDtmf",g.HangUp="HangUp",g.StartVideo="StartVideo",g.StartAudio="StartAudio",g.StopAudio="StopAudio",g.StopVideo="StopVideo",g.AddParticipant="AddParticipant",g.RemoveParticipant="RemoveParticipant",g.LobbyAdmitParticipant="LobbyAdmitParticipant",g.LobbyRejectParticipant="LobbyRejectParticipant",g.LobbyAdmitAll="LobbyAdmitAll",g.Hold="Hold",g.Resume="Resume",g.StartScreenShare="StartScreenShare",g.StopScreenShare="StopScreenShare",g.Transfer="Transfer",g.BindToCall="BindToCall",g.Feature="Feature",g.SetConstraints="SetConstraints"}(PS||(PS={})),function(g){g.Mute="Mute"}(RS||(RS={})),function(g){g.GetServerCallId="GetServerCallId"}(MS||(MS={})),function(g){g.CreateStackBase="CreateStackBase",g.GetDeviceManager="GetDeviceManager",g.InitializeStackForUser="InitializeStackForUser",g.InitializeEcsBase="InitializeEcsBase",g.InitializeEcsForUser="InitializeEcsForUser",g.Dispose="Dispose"}(wS||(wS={})),function(g){g.GetDeviceManager="GetDeviceManager",g.GetCameras="GetCameras",g.GetMicrophones="GetMicrophones",g.GetSpeakers="GetSpeakers",g.GetCamera="GetCamera",g.SelectCamera="SelectCamera",g.GetSelectedMicrophone="GetSelectedMicrophone",g.SelectMicrophone="SelectMicrophone",g.GetSelectedSpeaker="GetSelectedSpeaker",g.SelectSpeaker="SelectSpeaker",g.RenderPreviewVideo="RenderPreviewVideo",g.AskDevicePermission="AskDevicePermission"}(OS||(OS={})),function(g){g.Dispose="Dispose",g.UpdateScalingMode="UpdateScalingMode",g.Render="Render",g.RenderRemoteStream="RenderRemoteStream",g.RenderLocalStream="RenderLocalStream"}(DS||(DS={})),function(g){g.Dispose="Dispose",g.CreateView="CreateView"}(NS||(NS={})),function(g){g.SwitchSource="SwitchSource",g.Render="Render",g.GetMediaStream="GetMediaStream",g.SetMediaStream="SetMediaStream",g.SwitchVideo="SwitchVideo",g.Feature="Feature"}(kS||(kS={})),function(g){g.SwitchSource="SwitchSource",g.GetMediaStream="GetMediaStream",g.SetMediaStream="SetMediaStream",g.Feature="Feature"}(LS||(LS={})),function(g){g.SetScalingMode="SetScalingMode",g.Start="Start",g.Stop="Stop",g.SwitchDevice="SwitchDevice",g.Dispose="Dispose"}(FS||(FS={})),function(g){g.Render="Render",g.GetMediaStream="GetMediaStream"}(xS||(xS={})),function(g){g.Start="Start",g.Resume="Resume",g.Pause="Pause",g.SetScalingMode="SetScalingMode",g.Dispose="Dispose"}(US||(US={})),function(g){g.Start="Start",g.Resume="Resume",g.Pause="Pause",g.SetScalingMode="SetScalingMode",g.Dispose="Dispose",g.SetSourceObject="SetSourceObject"}(VS||(VS={})),function(g){g.SourceUnavailableError="SourceUnavailableError",g.permissionDeniedError="permissionDeniedError",g.PermissionDeniedError="PermissionDeniedError",g.DevicesNotFoundError="DevicesNotFoundError",g.MediaStreamRequestError="MediaStreamRequestError",g.PermissionsDeniedBySystem="PermissionsDeniedBySystem",g.UnknownFailureForVideoOperation="UnknownFailureForVideoOperation",g.noDeviceSelected="noDeviceSelected",g.NoDeviceSelected="NoDeviceSelected",g.MediaStreamRequestTimedout="MediaStreamRequestTimedout",g.UnsupportedStream="UnsupportedStream",g.ConstraintNotSatisfiedError="ConstraintNotSatisfiedError"}(BS||(BS={})),function(g){g.BrowserNotSupported="BrowserNotSupported",g.IncompatibleVersions="IncompatibleVersions"}(HS||(HS={})),function(g){g.JoinTeamMeeting="JoinTeamMeeting",g.JoinRoom="JoinRoom",g.JoinWithGroupId="JoinWithGroupId",g.PlaceCall="PlaceCall",g.AcceptCall="AcceptCall",g.TransferToParticipant="TransferToParticipant",g.TransferToCall="TransferToCall",g.CallQueue="CallQueue"}($S||($S={})),function(g){g.TeamsMeeting="TeamsMeeting",g.Rooms="Rooms",g.GroupIdCall="GroupIdCall",g.TwoParty="TwoParty",g.MultiParty="MultiParty"}(jS||(jS={})),function(g){g.Enabled="Enabled",g.UserOverride="UserOverride",g.Disabled="Disabled"}(GS||(GS={})),function(g){g.Standard="standard",g.MusicOnHold="musicOnHold"}(qS||(qS={})),function(g){g.Disabled="Disabled",g.EnabledOutgoingIncoming="EnabledOutgoingIncoming"}(WS||(WS={}));const zS={telemetry:{callStatsFlushTimeout:Pm,discardedTelemetryRetryTimeout:Rm,discardedEventsBufferMaxLength:Mm,discardedEventsMaxRetries:wm,telemetryFlushTimeout:Tm,asyncTelemetryFlush:!0,allowedEvents:[],blockedEvents:["acs_calling_feature_usage","acs_calling_call_client_init"],blockedKindOfEvents:[{name:"acs_calling_token_expiration_changed",kindOfEvents:["attempt","success"]}],limit:{outSideCall:{enabled:!1,deltaTimeInMs:15e3,includedEvents:[],excludedEvents:[]},rates:[]},telemetryBeforeUnload:!1,gzipTelemetryPayload:!0,localStorageEnable:!1,speakingWhileMutedThrottleInterval:18e4,mediaStatsConfig:{enabled:!0,throttleTelemetry:1,aggregationInterval:10,dataPointsPerAggregation:6,metricsProperties:{},dataToSend:{raw:!1,min:!0,max:!0,sum:!0,count:!0},enableNetworkInformation:!1,enableMemoryInformationV1:!1,enableMemoryInformationV2:!1,enableBatteryInformation:!1,enablePressureInformation:!1,enableAudioLeakInformation:!1,audioLeakThreshold:46e-5,enableVideoLeakInformation:!1,enableVideoMaxCapCallStats:!1},liveStreamStatsConfig:{enabled:!1,aggregationInterval:10,dataPointsPerAggregation:6,additionalStats:{},dataToSend:{raw:!1,min:!0,max:!0,sum:!0,count:!0}},reportSdkUaToService:!0,reportEnvToService:!0,sendNetworkChangedTelemetry:!1,deviceChangedEvents:{enabled:!0,piiSafeWordsMode:"merge",piiSafeWords:Cm},maxExistingReportedParticipants:25,sendNetworkInfo:!1,apiCauseIdHeader:"X-Microsoft-Skype-Message-ID"},ecsClient:{throttling:{triggerCount:5,triggerDuration:1e4,coolDownDuration:3e5,startingDelay:3e3,maxDelay:6e4,delayFactor:2}},mediaStats:{blockMetrics:{},transformMetrics:{},activeState:[3,10,9],fetchInterval:1,aggregationInterval:10,dataPointsPerAggregation:6,pollingMethod:"interval",timerThrottlingFilter:{enabled:!1,delayRatio:0,filterRange:TS}},liveStreamStats:{activeState:[3],fetchInterval:1,aggregationInterval:10,dataPointsPerAggregation:6,pollingMethod:"interval"},debugInfo:{broadcastChannelName:Om,tabsBroadcastDelay:Dm,tabsUpdateDelay:Nm,enableLogDump:km,maxLogDumpLength:Lm,includeList:[],excludeList:[]},volumeIndicator:{fftSize:Fm,minDecibels:$m,maxDecibels:xm,smoothingConstant:Um,microphoneVolumeSampleIntervalMs:Vm,normalisedMaxVolume:Bm,maxAvailableVolume:Hm},telemetryEvents:{eventNameToPriority:{eventName:["acs_calling_call_stats"],priority:[Ga.Immediate]}},rendering:{remoteVideo:{createViewTimeout:jm,speedupCreateViewWithPlayEvent:!1,createViewUnsubscribeTimeout:Gm,debounceTimeout:qm,createViewSendMediaStats:!0,createViewSendMediaStatsMaxLength:120,createViewSendMediaStatsInitialMaxLength:1,createViewFailureNetworkUfdCheckWindowInMs:2e3,forceCheckIfVideoWasAttachedToDom:!0,checkIfVideoAttachedToDom_poll:!0,checkIfVideoAttachedToDom_intervalTime:Wm,checkIfVideoAttachedToDom_intervalMaxTries:zm,checkIfVideoAttachedToDom_timeout:Km,createViewSenderStatsDuration:Jm,registeredViewIdsMaxLength:Qm,getMediaStreamTimeout:Xm,largeMeeting:{handleVideoRendering:!0,participantCountThreshold:Zm,dominantSpeakersWithVideoOn_topCount:ef}}},captions:{acsBotMri:df,teamsBotMri:uf,teamsGccBotMri:gf,clientInfo:pf,availableLanguages:ff,enabled:!0,dataChannelId:cf,useCapabilities:!0,setBotMetadataWhenEmptyFix:!0,acs:{enabled:!0,botMri:df,modeKey:Ef,modeVal:_f,modesKey:If,modesVal:Af,clientInfo:{ring:pf},spokenLanguages:{enabled:!0,languages:ff}},teams:{enabled:!0,legacyBotMri:hf,botMri:uf,gccBotMri:gf,modeKey:Ef,modeVal:Tf,modesKey:bf,modesVal:Af,clientInfo:{ring:mf},spokenLanguages:{enabled:!0,languages:ff},captionLanguages:{enabled:!1,languages:Sf}}},audioEffects:{enableAudioEffects:!1,maxStringLengthForTelemetry:250},videoEffects:{enableVideoEffects:!1,imageTransparencyCheckTimeoutInMs:1e3,effectInitTimeThresholdInMs:2e4,fpsWarningThreshold:5,waitTimeToInitiateFpsChecksInMs:2e4,fpsCheckIntervalTimeInMs:3e3,maxStringLengthForTelemetry:250},calling:{enableMuteOthers:!0,enableSmePassFakeConversation:!1,doNotWaitForTrouter:!0,hangUpCallOnPageHide:!1,maxNumberOfTokenFetchRetries:10,deviceSelectionTimeoutInMs:3e3,deviceNotFunctioningMuted:!0,muteUnmuteOnMicrophoneNotFunctioning:!1,unmuteDelayForMicrophoneNotFunctioningInMs:0,preventStopAudio:!1,preventFakeMute:!1,osAutoRecoverAudio:!1,deviceCaptureMuteRecover:!1,allowMuteOnBadUfd:!0,preventStopVideo:!0,mediaMetricsDeviceEventsEnabled:!1,allowAccessRawMediaStream:!1,applyViewLimit:!0,deviceCaptureMutedVideo:!0,removeLvsCheckOnCallStartAndCallAccept:!1,removeLocalAudioStreamCheckOnCallStartAndCallAccept:!1,turnOffScreenShareBeforeHold:!0,teamsMultipersonaSettings:{enableStartCall:!0,enableJoinCall:!1,enableServerMutePSTNParticipant:!1},allowMutePstnRemoteParticipant:!0,constraints:{enabled:!1,maxOutgoingResolution:0,maxOutgoingFrameRate:0,maxOutgoingVideoBitrate:0},sharedLineAppearance:{enabled:!1},supportLiveStreaming:!1,liveStreamingBotIds:Rf,composedStreamBotIds:Mf,teamsCallQualityFeedback:{enabled:!0,tenantId:rf},setDeviceType:!1,devicePermissions:{splitAskAudioVideo:!1,timeoutInBetween:0,getCurrentState:!0},applicationSettingsUrls:{Public_ConversationServiceUrl:am.Public_ConversationServiceUrl,Public_TrouterServiceUrl:am.Public_TrouterServiceUrl,Public_RegistrarServiceUrl:am.Public_RegistrarServiceUrl,Public_MdnTrapServiceUrl:am.Public_MdnTrapServiceUrl,Public_MdnTrapServiceTokenUrl:am.Public_MdnTrapServiceTokenUrl,Public_MdnTrapRelaySkypeFqdns:am.Public_MdnTrapRelaySkypeFqdns,Public_MdnTrapRelayTurnFqdns:am.Public_MdnTrapRelayTurnFqdns,Public_MdnTrapRelayTurnUrl:am.Public_MdnTrapRelayTurnUrl,GccHigh_ConversationServiceUrl:am.GccHigh_ConversationServiceUrl,GccHigh_TrouterServiceUrl:am.GccHigh_TrouterServiceUrl,GccHigh_RegistrarServiceUrl:am.GccHigh_RegistrarServiceUrl,GccHigh_MdnTrapServiceUrl:am.GccHigh_MdnTrapServiceUrl,GccHigh_MdnTrapServiceTokenUrl:am.GccHigh_MdnTrapServiceTokenUrl,GccHigh_MdnTrapRelaySkypeFqdns:am.GccHigh_MdnTrapRelaySkypeFqdns,GccHigh_MdnTrapRelayTurnFqdns:am.GccHigh_MdnTrapRelayTurnFqdns,GccHigh_MdnTrapRelayTurnUrl:am.GccHigh_MdnTrapRelayTurnUrl,Dod_ConversationServiceUrl:am.Dod_ConversationServiceUrl,Dod_TrouterServiceUrl:am.Dod_TrouterServiceUrl,Dod_RegistrarServiceUrl:am.Dod_RegistrarServiceUrl,Dod_MdnTrapServiceUrl:am.Dod_MdnTrapServiceUrl,Dod_MdnTrapServiceTokenUrl:am.Dod_MdnTrapServiceTokenUrl,Dod_MdnTrapRelaySkypeFqdns:am.Dod_MdnTrapRelaySkypeFqdns,Dod_MdnTrapRelayTurnFqdns:am.Dod_MdnTrapRelayTurnFqdns,Dod_MdnTrapRelayTurnUrl:am.Dod_MdnTrapRelayTurnUrl,AirGap08_ConversationServiceUrl:am.AirGap08_ConversationServiceUrl,AirGap08_TrouterServiceUrl:am.AirGap08_TrouterServiceUrl,AirGap08_RegistrarServiceUrl:am.AirGap08_RegistrarServiceUrl,AirGap09_ConversationServiceUrl:am.AirGap09_ConversationServiceUrl,AirGap09_TrouterServiceUrl:am.AirGap09_TrouterServiceUrl,AirGap09_RegistrarServiceUrl:am.AirGap09_RegistrarServiceUrl,Enterprise_ConversationServiceUrl:am.Enterprise_ConversationServiceUrl,Enterprise_TrouterServiceUrl:am.Enterprise_TrouterServiceUrl,Enterprise_RegistrarServiceUrl:am.Enterprise_RegistrarServiceUrl,Enterprise_MdnTrapServiceUrl:am.Enterprise_MdnTrapServiceUrl,Enterprise_MdnTrapServiceTokenUrl:am.Enterprise_MdnTrapServiceTokenUrl,Enterprise_MdnTrapRelaySkypeFqdns:am.Enterprise_MdnTrapRelaySkypeFqdns,Enterprise_MdnTrapRelayTurnFqdns:am.Enterprise_MdnTrapRelayTurnFqdns,Enterprise_MdnTrapRelayTurnUrl:am.Enterprise_MdnTrapRelayTurnUrl},applicationSettingsEudbUrls:{Public_ConversationServiceUrl_EUDB:sm.Public_ConversationServiceUrl_EUDB,Public_TrouterServiceUrl_EUDB:sm.Public_TrouterServiceUrl_EUDB,Public_RegistrarServiceUrl_EUDB:sm.Public_RegistrarServiceUrl_EUDB,Public_MdnTrapServiceUrl_EUDB:sm.Public_MdnTrapServiceUrl_EUDB,Public_MdnTrapServiceTokenUrl_EUDB:sm.Public_MdnTrapServiceTokenUrl_EUDB,Public_MdnTrapRelaySkypeFqdns_EUDB:sm.Public_MdnTrapRelaySkypeFqdns_EUDB,Public_MdnTrapRelayTurnFqdns_EUDB:sm.Public_MdnTrapRelayTurnFqdns_EUDB,Public_MdnTrapRelayTurnUrl_EUDB:sm.Public_MdnTrapRelayTurnUrl_EUDB,Enterprise_ConversationServiceUrl_EUDB:sm.Enterprise_ConversationServiceUrl_EUDB,Enterprise_TrouterServiceUrl_EUDB:sm.Enterprise_TrouterServiceUrl_EUDB,Enterprise_RegistrarServiceUrl_EUDB:sm.Enterprise_RegistrarServiceUrl_EUDB,Enterprise_MdnTrapServiceUrl_EUDB:sm.Enterprise_MdnTrapServiceUrl_EUDB,Enterprise_MdnTrapServiceTokenUrl_EUDB:sm.Enterprise_MdnTrapServiceTokenUrl_EUDB,Enterprise_MdnTrapRelaySkypeFqdns_EUDB:sm.Enterprise_MdnTrapRelaySkypeFqdns_EUDB,Enterprise_MdnTrapRelayTurnFqdns_EUDB:sm.Enterprise_MdnTrapRelayTurnFqdns_EUDB,Enterprise_MdnTrapRelayTurnUrl_EUDB:sm.Enterprise_MdnTrapRelayTurnUrl_EUDB},maxDisplayNameLength:256,callDiagnostics:Sm,eudb:{isEnabled:!0,countries:dm,regions:hm,defaultDataLocationEurope:!1,EmeaTenants:um,ApacTenants:gm,NoamTenants:pm,acsCompliantEvents:{},isRgnClaimEnabledForACS:!0,sendRegionToNgc:!0},tfl:{isEnabled:!1,hosts:["teams.live.com"]},remoteDiagnostic:{sourceEvents:["cameraStartTimedOut","speakingWhileMicrophoneIsMuted"],exposedEvents:["cameraStartFailed",""]},lobbyAdmitAndReject:{enabled:!0,supportedConversationTypes:["scheduledMeeting","adHocMeeting"]},localRecording:{enabled:!0,supportedConversationTypes:["scheduledMeeting","adHocMeeting"]},platformSupportValidation:!1,enableCustomTurnUsage:!1,allowProxyForTeamsCalls:!1,allowCustomTurnForTeamsCalls:!1,spotlight:{enabled:!0,maxSpotlightParticipants:7,supportedRoles:["presenter","organizer","coorganizer"],meetingTypes:["scheduledMeeting"]},teamsMeetingAudioConferencing:{enabled:!0,supportedConversationTypes:["scheduledMeeting","adHocMeeting"]},breakoutRooms:{enabled:!0,supportedConversationTypes:["scheduledMeeting"],autoMoveInMilliSeconds:3e3,hangUpCallDelayInMilliSeconds:5e3},explicitConsentFeatureEnabled:{enabled:!0},transfer:{autoAccept:!0},reaction:{enabled:!0,telemetryEventAggregationIntervalInSecond:3,enableStateServiceConsoleLogs:!0,StateServiceProxySettings:{batchedRequestsEnabled:!1,websocketAliveTimeAfterLoseFocusInMS:3e4,pingTimeoutInMs:2e4,pongTimeoutInMs:5e3,maxSessionRetries:2,offlineMessageCacheEnabled:!0,maxOfflineMessageCacheLength:64,maxOfflineMessageCacheTimeInMs:2e4,autoRoutingEnabled:!0}},pptlive:{enabled:!0,wdParams:{wdModernSlideShowInTeams:!0,wdPresenterViewInTeams:!1,wdForceModernSlideShowInTeams:!1,isMovePrivateViewingToPPTEnabled:!0},appSettings:{takeFocusOnBoot:!0,enableAdvanceOnClick:!1,enableAdvanceOnTap:!1},stateServiceProxySettings:{batchedRequestsEnabled:!1,maxRoundtripRaw:300,pingTimeoutInMs:15e3,pongTimeoutInMs:15e3,retryIntervalsInMs:[1e3,2e3,4e3],verbose:!1,websocketAliveTimeAfterLoseFocusInMS:3e4,autoRoutingEnabled:!0,useServiceGeneratedClientId:!0,offlineMessageCacheEnabled:!0,maxOfflineMessageCacheTimeInMs:2e4,maxOfflineMessageCacheLength:64,allowReconnectOnSendMessage:!0},enableStateServiceInPreviewerFeatures:'["Ink","Media","Nav","NavSync","PresUrl","PresUrlBoot"]',featureGates:'{"ModernSlideShowAllowListForFileType":"pptx;ppsx;potx;pptm;ppsm;pot;ppt;odp;pps"}'},togetherMode:{enable:!0,botId:ym,gccBotId:Em,dataChannelId:13,forceSeatMapRequest:!1,supportedConversationTypes:["scheduledMeeting","adHocMeeting","groupCall"],mainVideo:{scaledWidthRatio:.6,scaledHeightRatio:.8}},checkHiddenBotOnCallStart:!0,blacklistedBots:[],musicOnHoldEnabled:!0,customContext:{userToUser:{headerKey:"User-To-User"},xHeaders:{headerKeyPrefix:"X-MS-Custom-",headerKeyRegex:"^[a-zA-Z0-9.!%*_+~-]{1,64}$",headerValueRegex:"^[a-zA-Z0-9.!%*_+~=;-]{1,256}$",maxCount:5}},watermark:{watermarkEnabledForAcsUsers:!0,watermarkEnabledForCteUsers:!0,watermarkDefaultOpacity:30,watermarkDefaultPattern:"Tiled",enableAudioOnlyFallback:!0,watermarkMaxUsernameLength:17,watermarkEmptyDisplayNamePlaceholder:"UnknownUser"},mediaAccess:{enabled:!0,ipMediaPolicyEnabled:!0,supportedRoles:["presenter","organizer","coorganizer"],supportedConversationTypes:["scheduledMeeting","adHocMeeting","groupCall","huddleGroupCall","screenShareCall"],supportedConversationTypesForMuteAll:["scheduledMeeting","adHocMeeting"]}},teamsMeetingShortUrlJoin:{validatePattern:!0,regexPattern:"\\/meet\\/[^\\/\\?]+(\\?p=[^\\/\\?]+)?$"},dataChannel:{maxReceiveBufferSize:2097152,receiveTimeoutInMs:12e4,maxSendBandwidth:5e5,maxBroadcastPacketRate:80,defaultBitrate:32e3,maxMessageSize:32768,enableBroadcastLimitOnReliableChannel:!1,dataIdConfigs:[]},unmixedAudio:{maxStreamSize:7,operationTimeoutInMs:1e4,skipProviderStateCheck:!1},roles:{acsOrganizer:vm.AcsOrganizerRole,acsPresenter:vm.AcsPresenterRole,acsAttendee:vm.AcsAttendeeRole,acsConsumer:vm.AcsConsumerRole,teamsAttendee:vm.TeamsAttendee,teamsOrganizer:vm.TeamsOrganizer,teamsPresenter:vm.TeamsPresenter,teamsCoorganizer:vm.TeamsCoorganizer},roomsRoleBasedCapabilities:{presenter:getDefaultCapabilities(jS.Rooms,"Presenter"),attendee:getDefaultCapabilities(jS.Rooms,"Attendee"),consumer:getDefaultCapabilities(jS.Rooms,"Consumer")},teamsRoleBasedCapabilities:{organizer:getDefaultCapabilities(jS.TeamsMeeting,"Organizer"),coorganizer:getDefaultCapabilities(jS.TeamsMeeting,"Co-organizer"),presenter:getDefaultCapabilities(jS.TeamsMeeting,"Presenter"),attendee:getDefaultCapabilities(jS.TeamsMeeting,"Attendee")},environments:{android:{chrome:{minVersion:Df,isSupportedOnSdkVersion:Nf},edgeanaheim:{minVersion:Df,isSupportedOnSdkVersion:Nf}},ios:{safari:{minVersion:Df,isSupportedOnSdkVersion:Nf},chrome:{minVersion:Df,isSupportedOnSdkVersion:!getSdkVersion().includes("stable")},edgeanaheim:{minVersion:Df,isSupportedOnSdkVersion:!getSdkVersion().includes("stable")},applewebview:{minVersion:Df,isSupportedOnSdkVersion:Nf}},mac:{chrome:{minVersion:Df,isSupportedOnSdkVersion:Nf},safari:{minVersion:Df,isSupportedOnSdkVersion:Nf},edgeanaheim:{minVersion:Df,isSupportedOnSdkVersion:Nf},firefox:{minVersion:Df,isSupportedOnSdkVersion:!getSdkVersion().includes("stable")}},windows:{chrome:{minVersion:Df,isSupportedOnSdkVersion:Nf},chromium:{minVersion:Df,isSupportedOnSdkVersion:Nf},edgeanaheim:{minVersion:Df,isSupportedOnSdkVersion:Nf},firefox:{minVersion:Df,isSupportedOnSdkVersion:!getSdkVersion().includes("stable")}},linux:{chrome:{minVersion:Df,isSupportedOnSdkVersion:Nf},firefox:{minVersion:Df,isSupportedOnSdkVersion:!getSdkVersion().includes("stable")}}},MiddleTier:{enabled:!1,maxRetry:3,baseServiceUrl:om.baseServiceUrl,policyUrlSuffix:om.policyUrlSuffix,policyUrlSuffixV2:om.policyUrlSuffixV2,userPolicySettingsApi:!1,serverManagedThreadIdApiConfiguration:{allowServerThreadCreation:!0,decoupleChatThreadFromCalls:!0,createThreadSuffix:om.createThreadSuffix,addParticipantSuffix:om.addParticipantSuffix}},PowerPointStateServiceUrl:{public:{amer:"https://usc.pptservicescast.officeapps.live.com",apac:"https://apac.pptservicescast.officeapps.live.com",emea:"https://emea.pptservicescast.officeapps.live.com",uk:"https://ukc.pptservicescast.officeapps.live.com",eu:"https://euc.pptservicescast.officeapps.live.com",in:"https://inc.pptservicescast.officeapps.live.com",au:"https://auc.pptservicescast.officeapps.live.com",ca:"https://canc.pptservicescast.officeapps.live.com",fr:"https://fr.pptservicescast.officeapps.live.com",jp:"https://jpc.pptservicescast.officeapps.live.com",ae:"https://ae.pptservicescast.officeapps.live.com",kr:"https://krc.pptservicescast.officeapps.live.com",sg:"https://sg.pptservicescast.officeapps.live.com",za:"https://za.pptservicescast.officeapps.live.com",de:"https://de.pptservicescast.officeapps.live.com",ch:"https://ch.pptservicescast.officeapps.live.com",no:"https://no.pptservicescast.officeapps.live.com",br:"https://pptservicescast.officeapps.live.com",se:"https://se.pptservicescast.officeapps.live.com",qa:"https://qa.pptservicescast.officeapps.live.com",gallatin:"https://pptservicescast.osi.microsoftonline.cn",pl:"https://pl.pptservicescast.officeapps.live.com",it:"https://euc.pptservicescast.officeapps.live.com",il:"https://pptservicescast.officeapps.live.com",mx:"https://pptservicescast.officeapps.live.com"},gcc:"https://pptservicescast.gcc.osi.office365.us",gcch:"https://pptservicescast.osi.office365.us",dod:"https://pptservicescast.osi.apps.mil",ag08:"https://pptservicescast.osi.eaglex.ic.gov",ag09:"https://pptservicescast.osi.microsoft.scloud"}};let KS;function setAcsEcsConfig(g){if(!g)throw new CallingCommunicationError({defaultError:D.INTERNAL.ECS_CONFIG_EMPTY});if(!g.AcsCallingSDKWeb)throw new CallingCommunicationError({defaultError:D.INTERNAL.ECS_CONFIG_MISSING_ACS});try{const f=zS.telemetry.deviceChangedEvents.piiSafeWords.slice();M.mergeWith(zS,g.AcsCallingSDKWeb,arrayMergeCustomizer);const S=zS.telemetry.deviceChangedEvents;"merge"===S.piiSafeWordsMode&&(S.piiSafeWords=M.union(f,S.piiSafeWords))}catch(g){throw new CallingCommunicationError({defaultError:D.INTERNAL.ECS_CONFIG_MERGING_ERROR})}}function getAcsEcsConfig(){return zS}function setMediaConfig(g){KS=g}function getMediaConfig(){return KS}function getDefaultCapabilities(g,f){const S={turnVideoOn:!0,unmuteMic:!0,shareScreen:!0,removeParticipant:!0,hangUpForEveryOne:!0,addCommunicationUser:!0,addTeamsUser:!0,addPhoneNumber:!0,manageLobby:!0,spotlightParticipant:!0,removeParticipantsSpotlight:!0,blurBackground:!0,startLiveMeetingCaptions:!0,startLiveCallingCaptions:!0,setCaptionLanguage:!0,raiseHand:!0,pstnDialOut:!0,muteOthers:!0,useReactions:!0,viewAttendeeNames:!0,startTogetherMode:!0,joinBreakoutRooms:!0,forbidOthersAudio:!0,forbidOthersVideo:!0};if(g==jS.TeamsMeeting){if("Co-organizer"==f||"Organizer"==f)return{...S};if("Presenter"==f){const g={...S};return g.hangUpForEveryOne=!1,g}if("Attendee"==f){const g={...S};return g.removeParticipant=!1,g.manageLobby=!1,g.spotlightParticipant=!1,g.removeParticipantsSpotlight=!1,g.shareScreen=!1,g.muteOthers=!1,g.hangUpForEveryOne=!1,g.startTogetherMode=!1,g.joinBreakoutRooms=!0,g.forbidOthersAudio=!1,g.forbidOthersVideo=!1,g}}if(g==jS.Rooms){const g={...S};if(g.removeParticipant=!1,g.hangUpForEveryOne=!1,g.addCommunicationUser=!1,g.addTeamsUser=!1,g.manageLobby=!1,g.spotlightParticipant=!1,g.removeParticipantsSpotlight=!1,g.blurBackground=!1,g.startLiveMeetingCaptions=!0,g.startLiveCallingCaptions=!0,g.setCaptionLanguage=!1,g.raiseHand=!1,g.startTogetherMode=!1,g.joinBreakoutRooms=!1,g.forbidOthersAudio=!1,g.forbidOthersVideo=!1,"Presenter"==f)return{...g};if("Attendee"==f){const f={...g};return f.shareScreen=!1,f.muteOthers=!1,f.addPhoneNumber=!1,f.pstnDialOut=!1,f}if("Consumer"==f){const f={...g};return f.turnVideoOn=!1,f.unmuteMic=!1,f.shareScreen=!1,f.muteOthers=!1,f.addPhoneNumber=!1,f.pstnDialOut=!1,f}}return S}const JS=["response","responseText","responseURL","status","state","statusText","timeout","withCredentials","stack","message","name","error","piiSafe","phase","code","participantId","phrase","subCode","reason"];function toTsScalingMode(g){switch(g){case"Crop":return 1;case"Fit":return 2;default:return 0}}function stringifyObject(g){return g.toString===Object.prototype.toString?JSON.stringify(g):g.toString()}function getSizeInBytes(g,f){try{return"string"==typeof g?new Blob([g]).size:g.byteLength}catch(g){return f.error(g),0}}function shallowEqual(g,f){const S=Object.keys(g);for(let v of S)if(g[v]!==f[v])return!1;return!0}function convertMapToFrozenJson(g){let f={};return g.forEach(((g,S)=>{f[S]=g})),Object.freeze(f)}function defer(){let g,f,S=!0;return{isPending:()=>S,promise:new Promise(((S,v)=>{g=S,f=v})),resolve:f=>{S&&(g(f),S=!1)},reject:g=>{S&&(f(g),S=!1)},dispose:()=>{S&&(f("disposed"),S=!1)}}}function timedDefer(g,f="Timed promise; rejected."){let S,v,C,_=!0;const timerStart=()=>{C=window.setTimeout((()=>{v(new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.EFFECT_PROVIDER_TIMEOUT}))}),g)},timerStop=()=>{window.clearTimeout(C)};let T=new Promise(((g,f)=>{S=f=>{timerStop(),_=!1,g(f)},v=g=>{timerStop(),_=!1,f(g)}}));return{timerStart:timerStart,timerStop:timerStop,deferredPromise:{promise:T,resolve:S,reject:v,isPending:()=>_,dispose:()=>{v("disposed")}}}}function assertNotNull(g,f){if(null==g)throw new CallingCommunicationError({defaultError:f})}function assertIsObject(g,f){if("object"!=typeof g)throw new CallingCommunicationError({defaultError:f})}function parseJWT(g){let[,f]=g?.split(".");if(void 0===f)throw new CallingCommunicationError({defaultError:D.INTERNAL.TOKEN_PAYLOAD_UNDEFINED});return f=f.replace(/-/g,"+").replace(/_/g,"/"),JSON.parse(decodeURIComponent(escape(atob(f))))}function logErrorAndThrow(g,f){throw f.error(`CallingCommunicationError: Message={${g.message},Code={${g.code}}, SubCode={${g.subCode}}, ResultCategories={${g.resultCategories}}`),new CallingCommunicationError({defaultError:g})}function noop(){}function isEudbLocation(g,f){const S=getGeoLocations(g);return!!f&&!!S.find((g=>g===f))}function isEudbConfigurationsApplicable(g,f){return getAcsEcsConfig().calling.eudb.isEnabled&&isEudbLocation(g,f||"")}function isRgnClaimApplicable(g){return getAcsEcsConfig().calling.eudb.isRgnClaimEnabledForACS||!!g&&g===lm.Enterprise||!1}function getGeoLocations(g){return isRgnClaimApplicable(g)?getAcsEcsConfig().calling.eudb.regions:getAcsEcsConfig().calling.eudb.countries}async function parseTokenCredential(g,f,S){let v;try{if(!g)throw new CallingCommunicationError({defaultError:D.INTERNAL.NO_TOKEN_PROVIDED});try{v=(await g.getToken(S))?.token}catch(g){throw new CallingCommunicationError("The token returned from the tokenRefresher is expired."===g.message?{defaultError:D.CALL_AGENT.ACCESSTOKEN_EXPIRED}:{defaultError:D.INTERNAL.GET_TOKEN})}if(!v)throw new CallingCommunicationError({defaultError:D.INTERNAL.EMPTY_TOKEN})}catch(g){throw new CallingCommunicationError({defaultError:D.INTERNAL.GET_TOKEN,originalError:g})}try{let g=parseJWT(v);if(!g)throw new CallingCommunicationError({defaultError:D.INTERNAL.TOKEN_UNDEFINED});if("string"!=typeof g.acsScope)throw new CallingCommunicationError({defaultError:D.INTERNAL.INVALID_TOKEN_SCOPE_FORMAT});if(!g.acsScope.split(",").find((g=>"voip"===g||"voip.join"===g)))throw new CallingCommunicationError({defaultError:D.INTERNAL.INVALID_TOKEN_SCOPE});const S=g.resourceId,_=constructIdentifierKindFromMri(`8:${g.skypeid}`);if(!S&&!("microsoftTeamsUser"===_?.kind))throw new CallingCommunicationError({defaultError:D.INTERNAL.RESOURCE_NOT_FOUND_IN_TOKEN});let T=g.skypeid;if(!T)throw new CallingCommunicationError({defaultError:D.INTERNAL.USERID_NOT_FOUND_IN_TOKEN});const I=getCloudTypeFromSkypeId(T);var C=getMriType(`8:${T}`);const b=!!g.tid,A=!!g.rgn,P=(b||f?g.rgn:g.resourceLocation)||"";let R=!1;return b&&(R=!!g.aad_pft),{jwtToken:v,acsResourceId:S,identityMri:T,cloudType:I,mriType:C,isEnterpriseUser:b,region:P,rgnClaimExists:A,exp:1e3*g.exp,aadpftClaimExists:R}}catch(g){throw new CallingCommunicationError({defaultError:D.INTERNAL.PARSE_TOKEN_FAIL,originalError:g})}}function buildCallingUserAgent(g,f,S){const v=`azsdk-js-communication-calling/${g}`;let C="";if(S?.diagnostics?.appName){let g=S?.diagnostics?.appName.trim().replace(/\s/g,"_");g.length>64&&(f.warn("appName is too long, max allowed length is 64 chars, appName was truncated to max length"),g=g.substr(0,64)),C+=g?`${g}/`:"default/"}else C+="default/";if(S?.diagnostics?.appVersion){let g=S?.diagnostics?.appVersion.trim().replace(/\s/g,"_");g.length>64&&(f.warn("appVersion is too long, max allowed length is 64 chars, appVersion was truncated to max length"),g=g.substr(0,64)),C+=g||"0.0.0"}else C+="0.0.0";if(C+=` ${v}`,S?.diagnostics?.tags&&Array.isArray(S?.diagnostics?.tags)&&S?.diagnostics?.tags.length>0){let g=S?.diagnostics?.tags.map((g=>g.trim().replace(/\s/g,"_"))).filter((g=>!!g)).join(";");g.length>128&&(f.warn("tags are too long, max allowed length is 128 chars, tags were truncated to max length"),g=g.substr(0,128)),g.length>0&&(C+=" ("+g+").")}return C}function getJoinContextDescription(g){return g?g.groupId?lS.GroupCall:!g.threadId||g.organizerId||g.tenantId||g.messageId?g.threadId&&g.organizerId&&g.tenantId&&g.messageId?lS.TeamsCoordinates:g.meetingId?lS.TeamsMeetingId:g.meetingLink?lS.TeamsMeetingLink:g.roomId?lS.RoomCall:lS.Unknown:lS.GroupChatCall:lS.Unknown}function getPrintableObject(g,f=!1){const processStackTrace=g=>{try{return g.split("\n")[0]}catch(g){return"invalid stack"}};if(void 0===g)return"void";if(g instanceof Error)return g.toString();if(g instanceof String||g instanceof Number||g instanceof Boolean)return g.toString();try{return g.stack&&(g.stack=processStackTrace(g.stack)),(f?JSON.stringify(g):JSON.stringify(g,JS,4)).replace(/(\r\n\t|\n|\r\t|\s)/gm,"")}catch(f){return`failed to get error information:${g&&"function"==typeof g.toString&&g.toString()} ${g&&g.response&&JSON.stringify(g.response)}`}}function permissionStateToBool(g,f){return f.info("permission state to boolean",g),"granted"===g}function getSafeObjectDiff(g,f,S=[]){let v=[];try{const C=Array.isArray(g);for(const _ in g){const T=g[_],I=C?+_:_;if(!(_ in f)){v.push({type:"REMOVE",path:[I],oldValue:g[_]});continue}const b=f[_],A="object"==typeof T&&"object"==typeof b;if(T&&b&&A&&!B[Object.getPrototypeOf(T).constructor.name]&&!S.includes(T)){const g=getSafeObjectDiff(T,b);v.push.apply(v,g.map((g=>(g.path.unshift(I),g))))}else T===b||A&&(isNaN(T)?T+""==b+"":+T==+b)||v.push({path:[I],type:"CHANGE",value:b,oldValue:T})}const _=Array.isArray(f);for(const S in f)S in g||v.push({type:"CREATE",path:[_?+S:S],value:f[S]})}catch(g){}return v}function advancedMeetingRoleToParticipantRole(g,f){const S={[g.roles.acsOrganizer.toLowerCase()]:cS.Organizer,[g.roles.teamsOrganizer.toLowerCase()]:cS.Organizer,[g.roles.acsPresenter.toLowerCase()]:cS.Presenter,[g.roles.teamsPresenter.toLowerCase()]:cS.Presenter,[g.roles.acsAttendee.toLowerCase()]:cS.Attendee,[g.roles.teamsAttendee.toLowerCase()]:cS.Attendee,[g.roles.acsConsumer.toLowerCase()]:cS.Consumer,[g.roles.teamsCoorganizer.toLowerCase()]:cS.Coorganizer};return f&&S[f.toString().toLowerCase()]?S[f.toString().toLowerCase()]:cS.Unknown}function hasMeetingDetailsChanged(g,f){return null==f.meetingCapability&&null!=g.meetingCapability||(null==f.capabilities&&null!=g.capabilities||!(M.isEqual(f.capabilities,g.capabilities)&&M.isEqual(f.meetingCapability,g.meetingCapability)&&M.isEqual(f.recordingConsentDetails,g.recordingConsentDetails)))}function hasCoreMeetingCapabilitiesChanged(g,f){return!(!g.capabilities||null==g.capabilities.allowVideo||null!=f.capabilities?.allowVideo&&f.capabilities.allowVideo==g.capabilities.allowVideo)||(!(!g.meetingCapability||null==g.meetingCapability.allowIPVideo||null!=f.meetingCapability?.allowIPVideo&&f.meetingCapability.allowIPVideo==g.meetingCapability.allowIPVideo)||(!(!g.meetingCapability||null==g.meetingCapability.attendeeRestrictions||null!=f.meetingCapability?.attendeeRestrictions&&f.meetingCapability.attendeeRestrictions==g.meetingCapability.attendeeRestrictions)||(!(!g.meetingCapability||null==g.meetingCapability.allowPstnConferencing||null!=f.meetingCapability?.allowPstnConferencing&&f.meetingCapability.allowPstnConferencing==g.meetingCapability.allowPstnConferencing)||(!(!g.meetingCapability||null==g.meetingCapability.allowTranslatedCaptions||null!=f.meetingCapability?.allowTranslatedCaptions&&f.meetingCapability?.allowTranslatedCaptions==g.meetingCapability.allowTranslatedCaptions)||(!(!g.meetingCapability||null==g.meetingCapability.allowTranslatedTranscriptions||null!=f.meetingCapability?.allowTranslatedTranscriptions&&f.meetingCapability?.allowTranslatedTranscriptions==g.meetingCapability.allowTranslatedTranscriptions)||(!(!g.meetingCapability||null==g.meetingCapability.allowRaiseHands||null!=f.meetingCapability?.allowRaiseHands&&f.meetingCapability?.allowRaiseHands==g.meetingCapability.allowRaiseHands)||(!(!g.meetingCapability||null==g.meetingCapability.allowTeamsMeetingReactions||null!=f.meetingCapability?.allowTeamsMeetingReactions&&f.meetingCapability?.allowTeamsMeetingReactions==g.meetingCapability.allowTeamsMeetingReactions)||(!(!g.meetingCapability||null==g.meetingCapability.presenterOption||null!=f.meetingCapability?.presenterOption&&f.meetingCapability?.presenterOption==g.meetingCapability.presenterOption)||(!(!g.capabilities||null==g.capabilities.maskIdentitiesForRole||null!=f.capabilities?.maskIdentitiesForRole&&f.capabilities?.maskIdentitiesForRole==g.capabilities.maskIdentitiesForRole)||!(!g.recordingConsentDetails||null==g.recordingConsentDetails.consentActivelyRequired||null!=f.recordingConsentDetails?.consentActivelyRequired&&f.recordingConsentDetails.consentActivelyRequired==g.recordingConsentDetails.consentActivelyRequired))))))))))}function getTotalNotBotParticipantCount(g){let f=1;if(g.participantCounts&&g.participantCounts.totalParticipants>0&&(f=g.participantCounts.totalParticipants),g.participants){f-=g.participants.filter((g=>isHiddenBot(g))).length}return f}function isHiddenBot(g){if(isCallingApplication(g.id)){if(isGlobalCallingApplication(g.id))return!0;if(getAcsEcsConfig()?.calling?.blacklistedBots?.includes(g.id))return!0;if(g.endpoints?.endpointDetails&&g.endpoints?.endpointDetails.length>0)return g.endpoints?.endpointDetails[0].endpointMetadata?.__platform?.ui?.hidden}return!1}function isProxyAndCustomTurnAllowed(g,f,S,v,C){if(S||v&&"microsoftTeamsUser"===v.kind||C&&callContextHasTeamsJoinOptions(C)){const S=getAcsEcsConfig().calling.allowProxyForTeamsCalls,v=g.proxyInUse,C=getAcsEcsConfig().calling.allowCustomTurnForTeamsCalls,_=f.customRelayManagerInUse;if(v&&!S)return!1;if(_&&!C)return!1}return!0}function isAcsTeamParticipantPresentInCall(f,v){let C=v==g.CallAgentKind.TeamsCallAgent?"communicationUser":"microsoftTeamsUser";return!!f.find((g=>S.getIdentifierKind(g).kind===C))}function isAcsThreadlessId(g){return g.startsWith(V)}function callContextHasTeamsJoinOptions(g){return!!(g.meetingId||g.meetingLink||g.messageId||g.organizerId||g.tenantId||g.threadId)}function initializeUfdsCorrelationIdCache(){return{1:{0:void 0,1:void 0,2:void 0,3:void 0},2:{0:void 0,1:void 0,2:void 0,3:void 0},3:{0:void 0,1:void 0,2:void 0,3:void 0},4:{0:void 0,1:void 0,2:void 0,3:void 0},5:{0:void 0,1:void 0,2:void 0,3:void 0},6:{0:void 0,1:void 0,2:void 0,3:void 0},7:{0:void 0,1:void 0,2:void 0,3:void 0},8:{0:void 0,1:void 0,2:void 0,3:void 0},9:{0:void 0,1:void 0,2:void 0,3:void 0},10:{0:void 0,1:void 0,2:void 0,3:void 0},11:{0:void 0,1:void 0,2:void 0,3:void 0},12:{0:void 0,1:void 0,2:void 0,3:void 0},13:{0:void 0,1:void 0,2:void 0,3:void 0},14:{0:void 0,1:void 0,2:void 0,3:void 0},15:{0:void 0,1:void 0,2:void 0,3:void 0},16:{0:void 0,1:void 0,2:void 0,3:void 0},17:{0:void 0,1:void 0,2:void 0,3:void 0},18:{0:void 0,1:void 0,2:void 0,3:void 0},19:{0:void 0,1:void 0,2:void 0,3:void 0},20:{0:void 0,1:void 0,2:void 0,3:void 0},21:{0:void 0,1:void 0,2:void 0,3:void 0},22:{0:void 0,1:void 0,2:void 0,3:void 0},23:{0:void 0,1:void 0,2:void 0,3:void 0},24:{0:void 0,1:void 0,2:void 0,3:void 0},25:{0:void 0,1:void 0,2:void 0,3:void 0},26:{0:void 0,1:void 0,2:void 0,3:void 0},27:{0:void 0,1:void 0,2:void 0,3:void 0},28:{0:void 0,1:void 0,2:void 0,3:void 0},29:{0:void 0,1:void 0,2:void 0,3:void 0},30:{0:void 0,1:void 0,2:void 0,3:void 0},31:{0:void 0,1:void 0,2:void 0,3:void 0},32:{0:void 0,1:void 0,2:void 0,3:void 0},33:{0:void 0,1:void 0,2:void 0,3:void 0},34:{0:void 0,1:void 0,2:void 0,3:void 0},35:{0:void 0,1:void 0,2:void 0,3:void 0},36:{0:void 0,1:void 0,2:void 0,3:void 0},37:{0:void 0,1:void 0,2:void 0,3:void 0},38:{0:void 0,1:void 0,2:void 0,3:void 0},39:{0:void 0,1:void 0,2:void 0,3:void 0},40:{0:void 0,1:void 0,2:void 0,3:void 0},41:{0:void 0,1:void 0,2:void 0,3:void 0},42:{0:void 0,1:void 0,2:void 0,3:void 0},43:{0:void 0,1:void 0,2:void 0,3:void 0},44:{0:void 0,1:void 0,2:void 0,3:void 0},45:{0:void 0,1:void 0,2:void 0,3:void 0},46:{0:void 0,1:void 0,2:void 0,3:void 0},47:{0:void 0,1:void 0,2:void 0,3:void 0},48:{0:void 0,1:void 0,2:void 0,3:void 0},49:{0:void 0,1:void 0,2:void 0,3:void 0},50:{0:void 0,1:void 0,2:void 0,3:void 0},51:{0:void 0,1:void 0,2:void 0,3:void 0},52:{0:void 0,1:void 0,2:void 0,3:void 0},53:{0:void 0,1:void 0,2:void 0,3:void 0},54:{0:void 0,1:void 0,2:void 0,3:void 0},55:{0:void 0,1:void 0,2:void 0,3:void 0},56:{0:void 0,1:void 0,2:void 0,3:void 0},57:{0:void 0,1:void 0,2:void 0,3:void 0},58:{0:void 0,1:void 0,2:void 0,3:void 0},59:{0:void 0,1:void 0,2:void 0,3:void 0},60:{0:void 0,1:void 0,2:void 0,3:void 0},61:{0:void 0,1:void 0,2:void 0,3:void 0},62:{0:void 0,1:void 0,2:void 0,3:void 0},63:{0:void 0,1:void 0,2:void 0,3:void 0},64:{0:void 0,1:void 0,2:void 0,3:void 0},65:{0:void 0,1:void 0,2:void 0,3:void 0},80:{0:void 0,1:void 0,2:void 0,3:void 0},66:{0:void 0,1:void 0,2:void 0,3:void 0},67:{0:void 0,1:void 0,2:void 0,3:void 0},68:{0:void 0,1:void 0,2:void 0,3:void 0},69:{0:void 0,1:void 0,2:void 0,3:void 0},70:{0:void 0,1:void 0,2:void 0,3:void 0},71:{0:void 0,1:void 0,2:void 0,3:void 0},72:{0:void 0,1:void 0,2:void 0,3:void 0},73:{0:void 0,1:void 0,2:void 0,3:void 0},74:{0:void 0,1:void 0,2:void 0,3:void 0},75:{0:void 0,1:void 0,2:void 0,3:void 0},76:{0:void 0,1:void 0,2:void 0,3:void 0},77:{0:void 0,1:void 0,2:void 0,3:void 0},78:{0:void 0,1:void 0,2:void 0,3:void 0},79:{0:void 0,1:void 0,2:void 0,3:void 0}}}function processCustomContext(g){if(!g||!g.customContext)return;const f={},S={};if(g.customContext.userToUser&&(f[getAcsEcsConfig().calling.customContext.userToUser.headerKey]=g.customContext.userToUser),g.customContext.xHeaders&&!g.customContext.sipHeaders){const S=getAcsEcsConfig().calling.customContext.xHeaders.headerKeyPrefix,v=new RegExp(getAcsEcsConfig().calling.customContext.xHeaders.headerKeyRegex),C=new RegExp(getAcsEcsConfig().calling.customContext.xHeaders.headerValueRegex);g.customContext.xHeaders.forEach((g=>{const f=g.key.toLowerCase().startsWith(S.toLowerCase());g.key=f?`${S}${g.key.slice(S.length)}`:`${S}${g.key}`})),g.customContext.xHeaders.filter((g=>v.test(g.key)&&C.test(g.value))).slice(0,getAcsEcsConfig().calling.customContext.xHeaders.maxCount).forEach((g=>f[g.key]=g.value))}if(g.customContext.sipHeaders){const S=getAcsEcsConfig().calling.customContext.xHeaders.headerKeyPrefix,v=new RegExp(getAcsEcsConfig().calling.customContext.xHeaders.headerKeyRegex),C=new RegExp(getAcsEcsConfig().calling.customContext.xHeaders.headerValueRegex);g.customContext.sipHeaders.forEach((g=>{const f=g.key.toLowerCase().startsWith(S.toLowerCase());g.key=f?`${S}${g.key.slice(S.length)}`:`${S}${g.key}`})),g.customContext.sipHeaders.filter((g=>v.test(g.key)&&C.test(g.value))).slice(0,getAcsEcsConfig().calling.customContext.xHeaders.maxCount).forEach((g=>f[g.key]=g.value))}g.customContext.voipHeaders&&g.customContext.voipHeaders.forEach((g=>S[g.key]=g.value));const v={};return Object.keys(f).length>0&&(v.sipHeaders=f),Object.keys(S).length>0&&(v.voipHeaders=S),Object.keys(f).length>0||Object.keys(S).length>0?v:void 0}function parseCustomContext(g){return parseCustomContextInner(g.customHeaderContext)||parseCustomContextInner(g.clientTransferContext)}function parseCustomContextInner(g){if(!g)return;const f=g.sipHeaders||g.customContext?.sipHeaders,S=g.voipHeaders||g.customContext?.voipHeaders;if(!f&&!S)return;const v=getAcsEcsConfig().calling.customContext.userToUser.headerKey,C=getAcsEcsConfig().calling.customContext.xHeaders.headerKeyPrefix,_=f&&Object.entries(f).find((g=>g[0]?.toLowerCase()===v.toLowerCase())),T=f&&Object.entries(f).filter((g=>g[0]?.toLowerCase().startsWith(C?.toLowerCase()))).map((g=>({key:g[0],value:g[1]}))),I=S&&Object.entries(S).map((g=>({key:g[0],value:g[1]}))),b={};f&&_&&(b.userToUser=_[1]),T&&T.length>0&&(b.xHeaders=T,b.sipHeaders=T),I&&I.length>0&&(b.voipHeaders=I);return void 0===b.userToUser&&0===b.xHeaders?.length&&0===b.sipHeaders?.length&&0===b.voipHeaders?.length?void 0:b}var YS=createCommonjsModule((function(g,f){var S="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;f.assign=function(g){for(var f=Array.prototype.slice.call(arguments,1);f.length;){var S=f.shift();if(S){if("object"!=typeof S)throw new TypeError(S+"must be non-object");for(var v in S)S.hasOwnProperty(v)&&(g[v]=S[v])}}return g},f.shrinkBuf=function(g,f){return g.length===f?g:g.subarray?g.subarray(0,f):(g.length=f,g)};var v={arraySet:function(g,f,S,v,C){if(f.subarray&&g.subarray)g.set(f.subarray(S,S+v),C);else for(var _=0;_<v;_++)g[C+_]=f[S+_]},flattenChunks:function(g){var f,S,v,C,_,T;for(v=0,f=0,S=g.length;f<S;f++)v+=g[f].length;for(T=new Uint8Array(v),C=0,f=0,S=g.length;f<S;f++)_=g[f],T.set(_,C),C+=_.length;return T}},C={arraySet:function(g,f,S,v,C){for(var _=0;_<v;_++)g[C+_]=f[S+_]},flattenChunks:function(g){return[].concat.apply([],g)}};f.setTyped=function(g){g?(f.Buf8=Uint8Array,f.Buf16=Uint16Array,f.Buf32=Int32Array,f.assign(f,v)):(f.Buf8=Array,f.Buf16=Array,f.Buf32=Array,f.assign(f,C))},f.setTyped(S)})),QS=4,XS=0,ZS=1,ev=2;function zero(g){for(var f=g.length;--f>=0;)g[f]=0}var tv=0,iv=1,nv=2,rv=3,sv=258,av=29,ov=256,lv=ov+1+av,cv=30,dv=19,hv=2*lv+1,uv=15,gv=16,pv=7,mv=256,fv=16,Sv=17,vv=18,Cv=[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],yv=[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],Ev=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],_v=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Tv=512,Iv=new Array(2*(lv+2));zero(Iv);var bv=new Array(2*cv);zero(bv);var Av=new Array(Tv);zero(Av);var Pv=new Array(sv-rv+1);zero(Pv);var Rv=new Array(av);zero(Rv);var Mv,wv,Ov,Dv=new Array(cv);function StaticTreeDesc(g,f,S,v,C){this.static_tree=g,this.extra_bits=f,this.extra_base=S,this.elems=v,this.max_length=C,this.has_stree=g&&g.length}function TreeDesc(g,f){this.dyn_tree=g,this.max_code=0,this.stat_desc=f}function d_code(g){return g<256?Av[g]:Av[256+(g>>>7)]}function put_short(g,f){g.pending_buf[g.pending++]=255&f,g.pending_buf[g.pending++]=f>>>8&255}function send_bits(g,f,S){g.bi_valid>gv-S?(g.bi_buf|=f<<g.bi_valid&65535,put_short(g,g.bi_buf),g.bi_buf=f>>gv-g.bi_valid,g.bi_valid+=S-gv):(g.bi_buf|=f<<g.bi_valid&65535,g.bi_valid+=S)}function send_code(g,f,S){send_bits(g,S[2*f],S[2*f+1])}function bi_reverse(g,f){var S=0;do{S|=1&g,g>>>=1,S<<=1}while(--f>0);return S>>>1}function bi_flush(g){16===g.bi_valid?(put_short(g,g.bi_buf),g.bi_buf=0,g.bi_valid=0):g.bi_valid>=8&&(g.pending_buf[g.pending++]=255&g.bi_buf,g.bi_buf>>=8,g.bi_valid-=8)}function gen_bitlen(g,f){var S,v,C,_,T,I,b=f.dyn_tree,A=f.max_code,P=f.stat_desc.static_tree,R=f.stat_desc.has_stree,M=f.stat_desc.extra_bits,w=f.stat_desc.extra_base,O=f.stat_desc.max_length,D=0;for(_=0;_<=uv;_++)g.bl_count[_]=0;for(b[2*g.heap[g.heap_max]+1]=0,S=g.heap_max+1;S<hv;S++)(_=b[2*b[2*(v=g.heap[S])+1]+1]+1)>O&&(_=O,D++),b[2*v+1]=_,v>A||(g.bl_count[_]++,T=0,v>=w&&(T=M[v-w]),I=b[2*v],g.opt_len+=I*(_+T),R&&(g.static_len+=I*(P[2*v+1]+T)));if(0!==D){do{for(_=O-1;0===g.bl_count[_];)_--;g.bl_count[_]--,g.bl_count[_+1]+=2,g.bl_count[O]--,D-=2}while(D>0);for(_=O;0!==_;_--)for(v=g.bl_count[_];0!==v;)(C=g.heap[--S])>A||(b[2*C+1]!==_&&(g.opt_len+=(_-b[2*C+1])*b[2*C],b[2*C+1]=_),v--)}}function gen_codes(g,f,S){var v,C,_=new Array(uv+1),T=0;for(v=1;v<=uv;v++)_[v]=T=T+S[v-1]<<1;for(C=0;C<=f;C++){var I=g[2*C+1];0!==I&&(g[2*C]=bi_reverse(_[I]++,I))}}function tr_static_init(){var g,f,S,v,C,_=new Array(uv+1);for(S=0,v=0;v<av-1;v++)for(Rv[v]=S,g=0;g<1<<Cv[v];g++)Pv[S++]=v;for(Pv[S-1]=v,C=0,v=0;v<16;v++)for(Dv[v]=C,g=0;g<1<<yv[v];g++)Av[C++]=v;for(C>>=7;v<cv;v++)for(Dv[v]=C<<7,g=0;g<1<<yv[v]-7;g++)Av[256+C++]=v;for(f=0;f<=uv;f++)_[f]=0;for(g=0;g<=143;)Iv[2*g+1]=8,g++,_[8]++;for(;g<=255;)Iv[2*g+1]=9,g++,_[9]++;for(;g<=279;)Iv[2*g+1]=7,g++,_[7]++;for(;g<=287;)Iv[2*g+1]=8,g++,_[8]++;for(gen_codes(Iv,lv+1,_),g=0;g<cv;g++)bv[2*g+1]=5,bv[2*g]=bi_reverse(g,5);Mv=new StaticTreeDesc(Iv,Cv,ov+1,lv,uv),wv=new StaticTreeDesc(bv,yv,0,cv,uv),Ov=new StaticTreeDesc(new Array(0),Ev,0,dv,pv)}function init_block(g){var f;for(f=0;f<lv;f++)g.dyn_ltree[2*f]=0;for(f=0;f<cv;f++)g.dyn_dtree[2*f]=0;for(f=0;f<dv;f++)g.bl_tree[2*f]=0;g.dyn_ltree[2*mv]=1,g.opt_len=g.static_len=0,g.last_lit=g.matches=0}function bi_windup(g){g.bi_valid>8?put_short(g,g.bi_buf):g.bi_valid>0&&(g.pending_buf[g.pending++]=g.bi_buf),g.bi_buf=0,g.bi_valid=0}function copy_block(g,f,S,v){bi_windup(g),v&&(put_short(g,S),put_short(g,~S)),YS.arraySet(g.pending_buf,g.window,f,S,g.pending),g.pending+=S}function smaller(g,f,S,v){var C=2*f,_=2*S;return g[C]<g[_]||g[C]===g[_]&&v[f]<=v[S]}function pqdownheap(g,f,S){for(var v=g.heap[S],C=S<<1;C<=g.heap_len&&(C<g.heap_len&&smaller(f,g.heap[C+1],g.heap[C],g.depth)&&C++,!smaller(f,v,g.heap[C],g.depth));)g.heap[S]=g.heap[C],S=C,C<<=1;g.heap[S]=v}function compress_block(g,f,S){var v,C,_,T,I=0;if(0!==g.last_lit)do{v=g.pending_buf[g.d_buf+2*I]<<8|g.pending_buf[g.d_buf+2*I+1],C=g.pending_buf[g.l_buf+I],I++,0===v?send_code(g,C,f):(send_code(g,(_=Pv[C])+ov+1,f),0!==(T=Cv[_])&&send_bits(g,C-=Rv[_],T),send_code(g,_=d_code(--v),S),0!==(T=yv[_])&&send_bits(g,v-=Dv[_],T))}while(I<g.last_lit);send_code(g,mv,f)}function build_tree(g,f){var S,v,C,_=f.dyn_tree,T=f.stat_desc.static_tree,I=f.stat_desc.has_stree,b=f.stat_desc.elems,A=-1;for(g.heap_len=0,g.heap_max=hv,S=0;S<b;S++)0!==_[2*S]?(g.heap[++g.heap_len]=A=S,g.depth[S]=0):_[2*S+1]=0;for(;g.heap_len<2;)_[2*(C=g.heap[++g.heap_len]=A<2?++A:0)]=1,g.depth[C]=0,g.opt_len--,I&&(g.static_len-=T[2*C+1]);for(f.max_code=A,S=g.heap_len>>1;S>=1;S--)pqdownheap(g,_,S);C=b;do{S=g.heap[1],g.heap[1]=g.heap[g.heap_len--],pqdownheap(g,_,1),v=g.heap[1],g.heap[--g.heap_max]=S,g.heap[--g.heap_max]=v,_[2*C]=_[2*S]+_[2*v],g.depth[C]=(g.depth[S]>=g.depth[v]?g.depth[S]:g.depth[v])+1,_[2*S+1]=_[2*v+1]=C,g.heap[1]=C++,pqdownheap(g,_,1)}while(g.heap_len>=2);g.heap[--g.heap_max]=g.heap[1],gen_bitlen(g,f),gen_codes(_,A,g.bl_count)}function scan_tree(g,f,S){var v,C,_=-1,T=f[1],I=0,b=7,A=4;for(0===T&&(b=138,A=3),f[2*(S+1)+1]=65535,v=0;v<=S;v++)C=T,T=f[2*(v+1)+1],++I<b&&C===T||(I<A?g.bl_tree[2*C]+=I:0!==C?(C!==_&&g.bl_tree[2*C]++,g.bl_tree[2*fv]++):I<=10?g.bl_tree[2*Sv]++:g.bl_tree[2*vv]++,I=0,_=C,0===T?(b=138,A=3):C===T?(b=6,A=3):(b=7,A=4))}function send_tree(g,f,S){var v,C,_=-1,T=f[1],I=0,b=7,A=4;for(0===T&&(b=138,A=3),v=0;v<=S;v++)if(C=T,T=f[2*(v+1)+1],!(++I<b&&C===T)){if(I<A)do{send_code(g,C,g.bl_tree)}while(0!=--I);else 0!==C?(C!==_&&(send_code(g,C,g.bl_tree),I--),send_code(g,fv,g.bl_tree),send_bits(g,I-3,2)):I<=10?(send_code(g,Sv,g.bl_tree),send_bits(g,I-3,3)):(send_code(g,vv,g.bl_tree),send_bits(g,I-11,7));I=0,_=C,0===T?(b=138,A=3):C===T?(b=6,A=3):(b=7,A=4)}}function build_bl_tree(g){var f;for(scan_tree(g,g.dyn_ltree,g.l_desc.max_code),scan_tree(g,g.dyn_dtree,g.d_desc.max_code),build_tree(g,g.bl_desc),f=dv-1;f>=3&&0===g.bl_tree[2*_v[f]+1];f--);return g.opt_len+=3*(f+1)+5+5+4,f}function send_all_trees(g,f,S,v){var C;for(send_bits(g,f-257,5),send_bits(g,S-1,5),send_bits(g,v-4,4),C=0;C<v;C++)send_bits(g,g.bl_tree[2*_v[C]+1],3);send_tree(g,g.dyn_ltree,f-1),send_tree(g,g.dyn_dtree,S-1)}function detect_data_type(g){var f,S=4093624447;for(f=0;f<=31;f++,S>>>=1)if(1&S&&0!==g.dyn_ltree[2*f])return XS;if(0!==g.dyn_ltree[18]||0!==g.dyn_ltree[20]||0!==g.dyn_ltree[26])return ZS;for(f=32;f<ov;f++)if(0!==g.dyn_ltree[2*f])return ZS;return XS}zero(Dv);var Nv=!1;function _tr_init(g){Nv||(tr_static_init(),Nv=!0),g.l_desc=new TreeDesc(g.dyn_ltree,Mv),g.d_desc=new TreeDesc(g.dyn_dtree,wv),g.bl_desc=new TreeDesc(g.bl_tree,Ov),g.bi_buf=0,g.bi_valid=0,init_block(g)}function _tr_stored_block(g,f,S,v){send_bits(g,(tv<<1)+(v?1:0),3),copy_block(g,f,S,!0)}function _tr_align(g){send_bits(g,iv<<1,3),send_code(g,mv,Iv),bi_flush(g)}function _tr_flush_block(g,f,S,v){var C,_,T=0;g.level>0?(g.strm.data_type===ev&&(g.strm.data_type=detect_data_type(g)),build_tree(g,g.l_desc),build_tree(g,g.d_desc),T=build_bl_tree(g),C=g.opt_len+3+7>>>3,(_=g.static_len+3+7>>>3)<=C&&(C=_)):C=_=S+5,S+4<=C&&-1!==f?_tr_stored_block(g,f,S,v):g.strategy===QS||_===C?(send_bits(g,(iv<<1)+(v?1:0),3),compress_block(g,Iv,bv)):(send_bits(g,(nv<<1)+(v?1:0),3),send_all_trees(g,g.l_desc.max_code+1,g.d_desc.max_code+1,T+1),compress_block(g,g.dyn_ltree,g.dyn_dtree)),init_block(g),v&&bi_windup(g)}function _tr_tally(g,f,S){return g.pending_buf[g.d_buf+2*g.last_lit]=f>>>8&255,g.pending_buf[g.d_buf+2*g.last_lit+1]=255&f,g.pending_buf[g.l_buf+g.last_lit]=255&S,g.last_lit++,0===f?g.dyn_ltree[2*S]++:(g.matches++,f--,g.dyn_ltree[2*(Pv[S]+ov+1)]++,g.dyn_dtree[2*d_code(f)]++),g.last_lit===g.lit_bufsize-1}var kv={_tr_init:_tr_init,_tr_stored_block:_tr_stored_block,_tr_flush_block:_tr_flush_block,_tr_tally:_tr_tally,_tr_align:_tr_align};function adler32(g,f,S,v){for(var C=65535&g|0,_=g>>>16&65535|0,T=0;0!==S;){S-=T=S>2e3?2e3:S;do{_=_+(C=C+f[v++]|0)|0}while(--T);C%=65521,_%=65521}return C|_<<16|0}var Lv=adler32;function makeTable(){for(var g,f=[],S=0;S<256;S++){g=S;for(var v=0;v<8;v++)g=1&g?3988292384^g>>>1:g>>>1;f[S]=g}return f}var Fv=makeTable();function crc32(g,f,S,v){var C=Fv,_=v+S;g^=-1;for(var T=v;T<_;T++)g=g>>>8^C[255&(g^f[T])];return-1^g}var xv,Uv=crc32,Vv={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"},Bv=0,Hv=1,$v=3,jv=4,Gv=5,qv=0,Wv=1,zv=-2,Kv=-3,Jv=-5,Yv=-1,Qv=1,Xv=2,Zv=3,eC=4,tC=0,iC=2,nC=8,rC=9,sC=15,aC=8,oC=256+1+29,lC=30,cC=19,dC=2*oC+1,hC=15,uC=3,gC=258,pC=gC+uC+1,mC=32,fC=42,SC=69,vC=73,CC=91,yC=103,EC=113,_C=666,TC=1,IC=2,bC=3,AC=4,PC=3;function err(g,f){return g.msg=Vv[f],f}function rank(g){return(g<<1)-(g>4?9:0)}function zero$1(g){for(var f=g.length;--f>=0;)g[f]=0}function flush_pending(g){var f=g.state,S=f.pending;S>g.avail_out&&(S=g.avail_out),0!==S&&(YS.arraySet(g.output,f.pending_buf,f.pending_out,S,g.next_out),g.next_out+=S,f.pending_out+=S,g.total_out+=S,g.avail_out-=S,f.pending-=S,0===f.pending&&(f.pending_out=0))}function flush_block_only(g,f){kv._tr_flush_block(g,g.block_start>=0?g.block_start:-1,g.strstart-g.block_start,f),g.block_start=g.strstart,flush_pending(g.strm)}function put_byte(g,f){g.pending_buf[g.pending++]=f}function putShortMSB(g,f){g.pending_buf[g.pending++]=f>>>8&255,g.pending_buf[g.pending++]=255&f}function read_buf(g,f,S,v){var C=g.avail_in;return C>v&&(C=v),0===C?0:(g.avail_in-=C,YS.arraySet(f,g.input,g.next_in,C,S),1===g.state.wrap?g.adler=Lv(g.adler,f,C,S):2===g.state.wrap&&(g.adler=Uv(g.adler,f,C,S)),g.next_in+=C,g.total_in+=C,C)}function longest_match(g,f){var S,v,C=g.max_chain_length,_=g.strstart,T=g.prev_length,I=g.nice_match,b=g.strstart>g.w_size-pC?g.strstart-(g.w_size-pC):0,A=g.window,P=g.w_mask,R=g.prev,M=g.strstart+gC,w=A[_+T-1],O=A[_+T];g.prev_length>=g.good_match&&(C>>=2),I>g.lookahead&&(I=g.lookahead);do{if(A[(S=f)+T]===O&&A[S+T-1]===w&&A[S]===A[_]&&A[++S]===A[_+1]){_+=2,S++;do{}while(A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&_<M);if(v=gC-(M-_),_=M-gC,v>T){if(g.match_start=f,T=v,v>=I)break;w=A[_+T-1],O=A[_+T]}}}while((f=R[f&P])>b&&0!=--C);return T<=g.lookahead?T:g.lookahead}function fill_window(g){var f,S,v,C,_,T=g.w_size;do{if(C=g.window_size-g.lookahead-g.strstart,g.strstart>=T+(T-pC)){YS.arraySet(g.window,g.window,T,T,0),g.match_start-=T,g.strstart-=T,g.block_start-=T,f=S=g.hash_size;do{v=g.head[--f],g.head[f]=v>=T?v-T:0}while(--S);f=S=T;do{v=g.prev[--f],g.prev[f]=v>=T?v-T:0}while(--S);C+=T}if(0===g.strm.avail_in)break;if(S=read_buf(g.strm,g.window,g.strstart+g.lookahead,C),g.lookahead+=S,g.lookahead+g.insert>=uC)for(_=g.strstart-g.insert,g.ins_h=g.window[_],g.ins_h=(g.ins_h<<g.hash_shift^g.window[_+1])&g.hash_mask;g.insert&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[_+uC-1])&g.hash_mask,g.prev[_&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=_,_++,g.insert--,!(g.lookahead+g.insert<uC)););}while(g.lookahead<pC&&0!==g.strm.avail_in)}function deflate_stored(g,f){var S=65535;for(S>g.pending_buf_size-5&&(S=g.pending_buf_size-5);;){if(g.lookahead<=1){if(fill_window(g),0===g.lookahead&&f===Bv)return TC;if(0===g.lookahead)break}g.strstart+=g.lookahead,g.lookahead=0;var v=g.block_start+S;if((0===g.strstart||g.strstart>=v)&&(g.lookahead=g.strstart-v,g.strstart=v,flush_block_only(g,!1),0===g.strm.avail_out))return TC;if(g.strstart-g.block_start>=g.w_size-pC&&(flush_block_only(g,!1),0===g.strm.avail_out))return TC}return g.insert=0,f===jv?(flush_block_only(g,!0),0===g.strm.avail_out?bC:AC):(g.strstart>g.block_start&&(flush_block_only(g,!1),g.strm.avail_out),TC)}function deflate_fast(g,f){for(var S,v;;){if(g.lookahead<pC){if(fill_window(g),g.lookahead<pC&&f===Bv)return TC;if(0===g.lookahead)break}if(S=0,g.lookahead>=uC&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+uC-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart),0!==S&&g.strstart-S<=g.w_size-pC&&(g.match_length=longest_match(g,S)),g.match_length>=uC)if(v=kv._tr_tally(g,g.strstart-g.match_start,g.match_length-uC),g.lookahead-=g.match_length,g.match_length<=g.max_lazy_match&&g.lookahead>=uC){g.match_length--;do{g.strstart++,g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+uC-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart}while(0!=--g.match_length);g.strstart++}else g.strstart+=g.match_length,g.match_length=0,g.ins_h=g.window[g.strstart],g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+1])&g.hash_mask;else v=kv._tr_tally(g,0,g.window[g.strstart]),g.lookahead--,g.strstart++;if(v&&(flush_block_only(g,!1),0===g.strm.avail_out))return TC}return g.insert=g.strstart<uC-1?g.strstart:uC-1,f===jv?(flush_block_only(g,!0),0===g.strm.avail_out?bC:AC):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?TC:IC}function deflate_slow(g,f){for(var S,v,C;;){if(g.lookahead<pC){if(fill_window(g),g.lookahead<pC&&f===Bv)return TC;if(0===g.lookahead)break}if(S=0,g.lookahead>=uC&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+uC-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart),g.prev_length=g.match_length,g.prev_match=g.match_start,g.match_length=uC-1,0!==S&&g.prev_length<g.max_lazy_match&&g.strstart-S<=g.w_size-pC&&(g.match_length=longest_match(g,S),g.match_length<=5&&(g.strategy===Qv||g.match_length===uC&&g.strstart-g.match_start>4096)&&(g.match_length=uC-1)),g.prev_length>=uC&&g.match_length<=g.prev_length){C=g.strstart+g.lookahead-uC,v=kv._tr_tally(g,g.strstart-1-g.prev_match,g.prev_length-uC),g.lookahead-=g.prev_length-1,g.prev_length-=2;do{++g.strstart<=C&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+uC-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart)}while(0!=--g.prev_length);if(g.match_available=0,g.match_length=uC-1,g.strstart++,v&&(flush_block_only(g,!1),0===g.strm.avail_out))return TC}else if(g.match_available){if((v=kv._tr_tally(g,0,g.window[g.strstart-1]))&&flush_block_only(g,!1),g.strstart++,g.lookahead--,0===g.strm.avail_out)return TC}else g.match_available=1,g.strstart++,g.lookahead--}return g.match_available&&(v=kv._tr_tally(g,0,g.window[g.strstart-1]),g.match_available=0),g.insert=g.strstart<uC-1?g.strstart:uC-1,f===jv?(flush_block_only(g,!0),0===g.strm.avail_out?bC:AC):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?TC:IC}function deflate_rle(g,f){for(var S,v,C,_,T=g.window;;){if(g.lookahead<=gC){if(fill_window(g),g.lookahead<=gC&&f===Bv)return TC;if(0===g.lookahead)break}if(g.match_length=0,g.lookahead>=uC&&g.strstart>0&&(v=T[C=g.strstart-1])===T[++C]&&v===T[++C]&&v===T[++C]){_=g.strstart+gC;do{}while(v===T[++C]&&v===T[++C]&&v===T[++C]&&v===T[++C]&&v===T[++C]&&v===T[++C]&&v===T[++C]&&v===T[++C]&&C<_);g.match_length=gC-(_-C),g.match_length>g.lookahead&&(g.match_length=g.lookahead)}if(g.match_length>=uC?(S=kv._tr_tally(g,1,g.match_length-uC),g.lookahead-=g.match_length,g.strstart+=g.match_length,g.match_length=0):(S=kv._tr_tally(g,0,g.window[g.strstart]),g.lookahead--,g.strstart++),S&&(flush_block_only(g,!1),0===g.strm.avail_out))return TC}return g.insert=0,f===jv?(flush_block_only(g,!0),0===g.strm.avail_out?bC:AC):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?TC:IC}function deflate_huff(g,f){for(var S;;){if(0===g.lookahead&&(fill_window(g),0===g.lookahead)){if(f===Bv)return TC;break}if(g.match_length=0,S=kv._tr_tally(g,0,g.window[g.strstart]),g.lookahead--,g.strstart++,S&&(flush_block_only(g,!1),0===g.strm.avail_out))return TC}return g.insert=0,f===jv?(flush_block_only(g,!0),0===g.strm.avail_out?bC:AC):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?TC:IC}function Config(g,f,S,v,C){this.good_length=g,this.max_lazy=f,this.nice_length=S,this.max_chain=v,this.func=C}function lm_init(g){g.window_size=2*g.w_size,zero$1(g.head),g.max_lazy_match=xv[g.level].max_lazy,g.good_match=xv[g.level].good_length,g.nice_match=xv[g.level].nice_length,g.max_chain_length=xv[g.level].max_chain,g.strstart=0,g.block_start=0,g.lookahead=0,g.insert=0,g.match_length=g.prev_length=uC-1,g.match_available=0,g.ins_h=0}function DeflateState(){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=nC,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 YS.Buf16(2*dC),this.dyn_dtree=new YS.Buf16(2*(2*lC+1)),this.bl_tree=new YS.Buf16(2*(2*cC+1)),zero$1(this.dyn_ltree),zero$1(this.dyn_dtree),zero$1(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new YS.Buf16(hC+1),this.heap=new YS.Buf16(2*oC+1),zero$1(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new YS.Buf16(2*oC+1),zero$1(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(g){var f;return g&&g.state?(g.total_in=g.total_out=0,g.data_type=iC,(f=g.state).pending=0,f.pending_out=0,f.wrap<0&&(f.wrap=-f.wrap),f.status=f.wrap?fC:EC,g.adler=2===f.wrap?0:1,f.last_flush=Bv,kv._tr_init(f),qv):err(g,zv)}function deflateReset(g){var f=deflateResetKeep(g);return f===qv&&lm_init(g.state),f}function deflateSetHeader(g,f){return g&&g.state?2!==g.state.wrap?zv:(g.state.gzhead=f,qv):zv}function deflateInit2(g,f,S,v,C,_){if(!g)return zv;var T=1;if(f===Yv&&(f=6),v<0?(T=0,v=-v):v>15&&(T=2,v-=16),C<1||C>rC||S!==nC||v<8||v>15||f<0||f>9||_<0||_>eC)return err(g,zv);8===v&&(v=9);var I=new DeflateState;return g.state=I,I.strm=g,I.wrap=T,I.gzhead=null,I.w_bits=v,I.w_size=1<<I.w_bits,I.w_mask=I.w_size-1,I.hash_bits=C+7,I.hash_size=1<<I.hash_bits,I.hash_mask=I.hash_size-1,I.hash_shift=~~((I.hash_bits+uC-1)/uC),I.window=new YS.Buf8(2*I.w_size),I.head=new YS.Buf16(I.hash_size),I.prev=new YS.Buf16(I.w_size),I.lit_bufsize=1<<C+6,I.pending_buf_size=4*I.lit_bufsize,I.pending_buf=new YS.Buf8(I.pending_buf_size),I.d_buf=I.lit_bufsize>>1,I.l_buf=3*I.lit_bufsize,I.level=f,I.strategy=_,I.method=S,deflateReset(g)}function deflateInit(g,f){return deflateInit2(g,f,nC,sC,aC,tC)}function deflate(g,f){var S,v,C,_;if(!g||!g.state||f>Gv||f<0)return g?err(g,zv):zv;if(v=g.state,!g.output||!g.input&&0!==g.avail_in||v.status===_C&&f!==jv)return err(g,0===g.avail_out?Jv:zv);if(v.strm=g,S=v.last_flush,v.last_flush=f,v.status===fC)if(2===v.wrap)g.adler=0,put_byte(v,31),put_byte(v,139),put_byte(v,8),v.gzhead?(put_byte(v,(v.gzhead.text?1:0)+(v.gzhead.hcrc?2:0)+(v.gzhead.extra?4:0)+(v.gzhead.name?8:0)+(v.gzhead.comment?16:0)),put_byte(v,255&v.gzhead.time),put_byte(v,v.gzhead.time>>8&255),put_byte(v,v.gzhead.time>>16&255),put_byte(v,v.gzhead.time>>24&255),put_byte(v,9===v.level?2:v.strategy>=Xv||v.level<2?4:0),put_byte(v,255&v.gzhead.os),v.gzhead.extra&&v.gzhead.extra.length&&(put_byte(v,255&v.gzhead.extra.length),put_byte(v,v.gzhead.extra.length>>8&255)),v.gzhead.hcrc&&(g.adler=Uv(g.adler,v.pending_buf,v.pending,0)),v.gzindex=0,v.status=SC):(put_byte(v,0),put_byte(v,0),put_byte(v,0),put_byte(v,0),put_byte(v,0),put_byte(v,9===v.level?2:v.strategy>=Xv||v.level<2?4:0),put_byte(v,PC),v.status=EC);else{var T=nC+(v.w_bits-8<<4)<<8;T|=(v.strategy>=Xv||v.level<2?0:v.level<6?1:6===v.level?2:3)<<6,0!==v.strstart&&(T|=mC),T+=31-T%31,v.status=EC,putShortMSB(v,T),0!==v.strstart&&(putShortMSB(v,g.adler>>>16),putShortMSB(v,65535&g.adler)),g.adler=1}if(v.status===SC)if(v.gzhead.extra){for(C=v.pending;v.gzindex<(65535&v.gzhead.extra.length)&&(v.pending!==v.pending_buf_size||(v.gzhead.hcrc&&v.pending>C&&(g.adler=Uv(g.adler,v.pending_buf,v.pending-C,C)),flush_pending(g),C=v.pending,v.pending!==v.pending_buf_size));)put_byte(v,255&v.gzhead.extra[v.gzindex]),v.gzindex++;v.gzhead.hcrc&&v.pending>C&&(g.adler=Uv(g.adler,v.pending_buf,v.pending-C,C)),v.gzindex===v.gzhead.extra.length&&(v.gzindex=0,v.status=vC)}else v.status=vC;if(v.status===vC)if(v.gzhead.name){C=v.pending;do{if(v.pending===v.pending_buf_size&&(v.gzhead.hcrc&&v.pending>C&&(g.adler=Uv(g.adler,v.pending_buf,v.pending-C,C)),flush_pending(g),C=v.pending,v.pending===v.pending_buf_size)){_=1;break}_=v.gzindex<v.gzhead.name.length?255&v.gzhead.name.charCodeAt(v.gzindex++):0,put_byte(v,_)}while(0!==_);v.gzhead.hcrc&&v.pending>C&&(g.adler=Uv(g.adler,v.pending_buf,v.pending-C,C)),0===_&&(v.gzindex=0,v.status=CC)}else v.status=CC;if(v.status===CC)if(v.gzhead.comment){C=v.pending;do{if(v.pending===v.pending_buf_size&&(v.gzhead.hcrc&&v.pending>C&&(g.adler=Uv(g.adler,v.pending_buf,v.pending-C,C)),flush_pending(g),C=v.pending,v.pending===v.pending_buf_size)){_=1;break}_=v.gzindex<v.gzhead.comment.length?255&v.gzhead.comment.charCodeAt(v.gzindex++):0,put_byte(v,_)}while(0!==_);v.gzhead.hcrc&&v.pending>C&&(g.adler=Uv(g.adler,v.pending_buf,v.pending-C,C)),0===_&&(v.status=yC)}else v.status=yC;if(v.status===yC&&(v.gzhead.hcrc?(v.pending+2>v.pending_buf_size&&flush_pending(g),v.pending+2<=v.pending_buf_size&&(put_byte(v,255&g.adler),put_byte(v,g.adler>>8&255),g.adler=0,v.status=EC)):v.status=EC),0!==v.pending){if(flush_pending(g),0===g.avail_out)return v.last_flush=-1,qv}else if(0===g.avail_in&&rank(f)<=rank(S)&&f!==jv)return err(g,Jv);if(v.status===_C&&0!==g.avail_in)return err(g,Jv);if(0!==g.avail_in||0!==v.lookahead||f!==Bv&&v.status!==_C){var I=v.strategy===Xv?deflate_huff(v,f):v.strategy===Zv?deflate_rle(v,f):xv[v.level].func(v,f);if(I!==bC&&I!==AC||(v.status=_C),I===TC||I===bC)return 0===g.avail_out&&(v.last_flush=-1),qv;if(I===IC&&(f===Hv?kv._tr_align(v):f!==Gv&&(kv._tr_stored_block(v,0,0,!1),f===$v&&(zero$1(v.head),0===v.lookahead&&(v.strstart=0,v.block_start=0,v.insert=0))),flush_pending(g),0===g.avail_out))return v.last_flush=-1,qv}return f!==jv?qv:v.wrap<=0?Wv:(2===v.wrap?(put_byte(v,255&g.adler),put_byte(v,g.adler>>8&255),put_byte(v,g.adler>>16&255),put_byte(v,g.adler>>24&255),put_byte(v,255&g.total_in),put_byte(v,g.total_in>>8&255),put_byte(v,g.total_in>>16&255),put_byte(v,g.total_in>>24&255)):(putShortMSB(v,g.adler>>>16),putShortMSB(v,65535&g.adler)),flush_pending(g),v.wrap>0&&(v.wrap=-v.wrap),0!==v.pending?qv:Wv)}function deflateEnd(g){var f;return g&&g.state?(f=g.state.status)!==fC&&f!==SC&&f!==vC&&f!==CC&&f!==yC&&f!==EC&&f!==_C?err(g,zv):(g.state=null,f===EC?err(g,Kv):qv):zv}function deflateSetDictionary(g,f){var S,v,C,_,T,I,b,A,P=f.length;if(!g||!g.state)return zv;if(2===(_=(S=g.state).wrap)||1===_&&S.status!==fC||S.lookahead)return zv;for(1===_&&(g.adler=Lv(g.adler,f,P,0)),S.wrap=0,P>=S.w_size&&(0===_&&(zero$1(S.head),S.strstart=0,S.block_start=0,S.insert=0),A=new YS.Buf8(S.w_size),YS.arraySet(A,f,P-S.w_size,S.w_size,0),f=A,P=S.w_size),T=g.avail_in,I=g.next_in,b=g.input,g.avail_in=P,g.next_in=0,g.input=f,fill_window(S);S.lookahead>=uC;){v=S.strstart,C=S.lookahead-(uC-1);do{S.ins_h=(S.ins_h<<S.hash_shift^S.window[v+uC-1])&S.hash_mask,S.prev[v&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=v,v++}while(--C);S.strstart=v,S.lookahead=uC-1,fill_window(S)}return S.strstart+=S.lookahead,S.block_start=S.strstart,S.insert=S.lookahead,S.lookahead=0,S.match_length=S.prev_length=uC-1,S.match_available=0,g.next_in=I,g.input=b,g.avail_in=T,S.wrap=_,qv}xv=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];var RC={deflateInit:deflateInit,deflateInit2:deflateInit2,deflateReset:deflateReset,deflateResetKeep:deflateResetKeep,deflateSetHeader:deflateSetHeader,deflate:deflate,deflateEnd:deflateEnd,deflateSetDictionary:deflateSetDictionary,deflateInfo:"pako deflate (from Nodeca project)"},MC=!0,wC=!0;try{String.fromCharCode.apply(null,[0])}catch(g){MC=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(g){wC=!1}for(var OC=new YS.Buf8(256),DC=0;DC<256;DC++)OC[DC]=DC>=252?6:DC>=248?5:DC>=240?4:DC>=224?3:DC>=192?2:1;OC[254]=OC[254]=1;var string2buf=function(g){var f,S,v,C,_,T=g.length,I=0;for(C=0;C<T;C++)55296==(64512&(S=g.charCodeAt(C)))&&C+1<T&&56320==(64512&(v=g.charCodeAt(C+1)))&&(S=65536+(S-55296<<10)+(v-56320),C++),I+=S<128?1:S<2048?2:S<65536?3:4;for(f=new YS.Buf8(I),_=0,C=0;_<I;C++)55296==(64512&(S=g.charCodeAt(C)))&&C+1<T&&56320==(64512&(v=g.charCodeAt(C+1)))&&(S=65536+(S-55296<<10)+(v-56320),C++),S<128?f[_++]=S:S<2048?(f[_++]=192|S>>>6,f[_++]=128|63&S):S<65536?(f[_++]=224|S>>>12,f[_++]=128|S>>>6&63,f[_++]=128|63&S):(f[_++]=240|S>>>18,f[_++]=128|S>>>12&63,f[_++]=128|S>>>6&63,f[_++]=128|63&S);return f};function buf2binstring(g,f){if(f<65537&&(g.subarray&&wC||!g.subarray&&MC))return String.fromCharCode.apply(null,YS.shrinkBuf(g,f));for(var S="",v=0;v<f;v++)S+=String.fromCharCode(g[v]);return S}var binstring2buf=function(g){for(var f=new YS.Buf8(g.length),S=0,v=f.length;S<v;S++)f[S]=g.charCodeAt(S);return f},buf2string=function(g,f){var S,v,C,_,T=f||g.length,I=new Array(2*T);for(v=0,S=0;S<T;)if((C=g[S++])<128)I[v++]=C;else if((_=OC[C])>4)I[v++]=65533,S+=_-1;else{for(C&=2===_?31:3===_?15:7;_>1&&S<T;)C=C<<6|63&g[S++],_--;_>1?I[v++]=65533:C<65536?I[v++]=C:(C-=65536,I[v++]=55296|C>>10&1023,I[v++]=56320|1023&C)}return buf2binstring(I,v)},NC={string2buf:string2buf,buf2binstring:function(g){return buf2binstring(g,g.length)},binstring2buf:binstring2buf,buf2string:buf2string,utf8border:function(g,f){var S;for((f=f||g.length)>g.length&&(f=g.length),S=f-1;S>=0&&128==(192&g[S]);)S--;return S<0||0===S?f:S+OC[g[S]]>f?S:f}};function ZStream(){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}var kC=ZStream,LC=Object.prototype.toString,FC=0,xC=4,UC=0,VC=1,BC=2,HC=-1,$C=0,jC=8;function Deflate(g){if(!(this instanceof Deflate))return new Deflate(g);this.options=YS.assign({level:HC,method:jC,chunkSize:16384,windowBits:15,memLevel:8,strategy:$C,to:""},g||{});var f=this.options;f.raw&&f.windowBits>0?f.windowBits=-f.windowBits:f.gzip&&f.windowBits>0&&f.windowBits<16&&(f.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new kC,this.strm.avail_out=0;var S=RC.deflateInit2(this.strm,f.level,f.method,f.windowBits,f.memLevel,f.strategy);if(S!==UC)throw new Error(Vv[S]);if(f.header&&RC.deflateSetHeader(this.strm,f.header),f.dictionary){var v;if(v="string"==typeof f.dictionary?NC.string2buf(f.dictionary):"[object ArrayBuffer]"===LC.call(f.dictionary)?new Uint8Array(f.dictionary):f.dictionary,(S=RC.deflateSetDictionary(this.strm,v))!==UC)throw new Error(Vv[S]);this._dict_set=!0}}function deflate$1(g,f){var S=new Deflate(f);if(S.push(g,!0),S.err)throw S.msg;return S.result}function deflateRaw(g,f){return(f=f||{}).raw=!0,deflate$1(g,f)}function gzip(g,f){return(f=f||{}).gzip=!0,deflate$1(g,f)}Deflate.prototype.push=function(g,f){var S,v,C=this.strm,_=this.options.chunkSize;if(this.ended)return!1;v=f===~~f?f:!0===f?xC:FC,"string"==typeof g?C.input=NC.string2buf(g):"[object ArrayBuffer]"===LC.call(g)?C.input=new Uint8Array(g):C.input=g,C.next_in=0,C.avail_in=C.input.length;do{if(0===C.avail_out&&(C.output=new YS.Buf8(_),C.next_out=0,C.avail_out=_),(S=RC.deflate(C,v))!==VC&&S!==UC)return this.onEnd(S),this.ended=!0,!1;0!==C.avail_out&&(0!==C.avail_in||v!==xC&&v!==BC)||("string"===this.options.to?this.onData(NC.buf2binstring(YS.shrinkBuf(C.output,C.next_out))):this.onData(YS.shrinkBuf(C.output,C.next_out)))}while((C.avail_in>0||0===C.avail_out)&&S!==VC);return v===xC?(S=RC.deflateEnd(this.strm),this.onEnd(S),this.ended=!0,S===UC):v!==BC||(this.onEnd(UC),C.avail_out=0,!0)},Deflate.prototype.onData=function(g){this.chunks.push(g)},Deflate.prototype.onEnd=function(g){g===UC&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=YS.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg};var GC={Deflate:Deflate,deflate:deflate$1,deflateRaw:deflateRaw,gzip:gzip},qC=30,WC=12,zC=function inflate_fast(g,f){var S,v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j;S=g.state,v=g.next_in,$=g.input,C=v+(g.avail_in-5),_=g.next_out,j=g.output,T=_-(f-g.avail_out),I=_+(g.avail_out-257),b=S.dmax,A=S.wsize,P=S.whave,R=S.wnext,M=S.window,w=S.hold,O=S.bits,D=S.lencode,N=S.distcode,k=(1<<S.lenbits)-1,L=(1<<S.distbits)-1;e:do{O<15&&(w+=$[v++]<<O,O+=8,w+=$[v++]<<O,O+=8),F=D[w&k];t:for(;;){if(w>>>=x=F>>>24,O-=x,0===(x=F>>>16&255))j[_++]=65535&F;else{if(!(16&x)){if(0==(64&x)){F=D[(65535&F)+(w&(1<<x)-1)];continue t}if(32&x){S.mode=WC;break e}g.msg="invalid literal/length code",S.mode=qC;break e}U=65535&F,(x&=15)&&(O<x&&(w+=$[v++]<<O,O+=8),U+=w&(1<<x)-1,w>>>=x,O-=x),O<15&&(w+=$[v++]<<O,O+=8,w+=$[v++]<<O,O+=8),F=N[w&L];i:for(;;){if(w>>>=x=F>>>24,O-=x,!(16&(x=F>>>16&255))){if(0==(64&x)){F=N[(65535&F)+(w&(1<<x)-1)];continue i}g.msg="invalid distance code",S.mode=qC;break e}if(V=65535&F,O<(x&=15)&&(w+=$[v++]<<O,(O+=8)<x&&(w+=$[v++]<<O,O+=8)),(V+=w&(1<<x)-1)>b){g.msg="invalid distance too far back",S.mode=qC;break e}if(w>>>=x,O-=x,V>(x=_-T)){if((x=V-x)>P&&S.sane){g.msg="invalid distance too far back",S.mode=qC;break e}if(B=0,H=M,0===R){if(B+=A-x,x<U){U-=x;do{j[_++]=M[B++]}while(--x);B=_-V,H=j}}else if(R<x){if(B+=A+R-x,(x-=R)<U){U-=x;do{j[_++]=M[B++]}while(--x);if(B=0,R<U){U-=x=R;do{j[_++]=M[B++]}while(--x);B=_-V,H=j}}}else if(B+=R-x,x<U){U-=x;do{j[_++]=M[B++]}while(--x);B=_-V,H=j}for(;U>2;)j[_++]=H[B++],j[_++]=H[B++],j[_++]=H[B++],U-=3;U&&(j[_++]=H[B++],U>1&&(j[_++]=H[B++]))}else{B=_-V;do{j[_++]=j[B++],j[_++]=j[B++],j[_++]=j[B++],U-=3}while(U>2);U&&(j[_++]=j[B++],U>1&&(j[_++]=j[B++]))}break}}break}}while(v<C&&_<I);v-=U=O>>3,w&=(1<<(O-=U<<3))-1,g.next_in=v,g.next_out=_,g.avail_in=v<C?C-v+5:5-(v-C),g.avail_out=_<I?I-_+257:257-(_-I),S.hold=w,S.bits=O},KC=15,JC=852,YC=592,QC=0,XC=1,ZC=2,ey=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],ty=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],iy=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],ny=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64],ry=function inflate_table(g,f,S,v,C,_,T,I){var b,A,P,R,M,w,O,D,N,k=I.bits,L=0,F=0,x=0,U=0,V=0,B=0,H=0,$=0,j=0,G=0,q=null,W=0,z=new YS.Buf16(KC+1),K=new YS.Buf16(KC+1),J=null,Y=0;for(L=0;L<=KC;L++)z[L]=0;for(F=0;F<v;F++)z[f[S+F]]++;for(V=k,U=KC;U>=1&&0===z[U];U--);if(V>U&&(V=U),0===U)return C[_++]=20971520,C[_++]=20971520,I.bits=1,0;for(x=1;x<U&&0===z[x];x++);for(V<x&&(V=x),$=1,L=1;L<=KC;L++)if($<<=1,($-=z[L])<0)return-1;if($>0&&(g===QC||1!==U))return-1;for(K[1]=0,L=1;L<KC;L++)K[L+1]=K[L]+z[L];for(F=0;F<v;F++)0!==f[S+F]&&(T[K[f[S+F]]++]=F);if(g===QC?(q=J=T,w=19):g===XC?(q=ey,W-=257,J=ty,Y-=257,w=256):(q=iy,J=ny,w=-1),G=0,F=0,L=x,M=_,B=V,H=0,P=-1,R=(j=1<<V)-1,g===XC&&j>JC||g===ZC&&j>YC)return 1;for(;;){O=L-H,T[F]<w?(D=0,N=T[F]):T[F]>w?(D=J[Y+T[F]],N=q[W+T[F]]):(D=96,N=0),b=1<<L-H,x=A=1<<B;do{C[M+(G>>H)+(A-=b)]=O<<24|D<<16|N|0}while(0!==A);for(b=1<<L-1;G&b;)b>>=1;if(0!==b?(G&=b-1,G+=b):G=0,F++,0==--z[L]){if(L===U)break;L=f[S+T[F]]}if(L>V&&(G&R)!==P){for(0===H&&(H=V),M+=x,$=1<<(B=L-H);B+H<U&&!(($-=z[B+H])<=0);)B++,$<<=1;if(j+=1<<B,g===XC&&j>JC||g===ZC&&j>YC)return 1;C[P=G&R]=V<<24|B<<16|M-_|0}}return 0!==G&&(C[M+G]=L-H<<24|64<<16|0),I.bits=V,0},sy=0,ay=1,oy=2,ly=4,cy=5,dy=6,hy=0,uy=1,gy=2,py=-2,my=-3,fy=-4,Sy=-5,vy=8,Cy=1,yy=2,Ey=3,_y=4,Ty=5,Iy=6,by=7,Ay=8,Py=9,Ry=10,My=11,wy=12,Oy=13,Dy=14,Ny=15,ky=16,Ly=17,Fy=18,xy=19,Uy=20,Vy=21,By=22,Hy=23,$y=24,jy=25,Gy=26,qy=27,Wy=28,zy=29,Ky=30,Jy=31,Yy=852,Qy=592,Xy=15;function zswap32(g){return(g>>>24&255)+(g>>>8&65280)+((65280&g)<<8)+((255&g)<<24)}function InflateState(){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 YS.Buf16(320),this.work=new YS.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(g){var f;return g&&g.state?(f=g.state,g.total_in=g.total_out=f.total=0,g.msg="",f.wrap&&(g.adler=1&f.wrap),f.mode=Cy,f.last=0,f.havedict=0,f.dmax=32768,f.head=null,f.hold=0,f.bits=0,f.lencode=f.lendyn=new YS.Buf32(Yy),f.distcode=f.distdyn=new YS.Buf32(Qy),f.sane=1,f.back=-1,hy):py}function inflateReset(g){var f;return g&&g.state?((f=g.state).wsize=0,f.whave=0,f.wnext=0,inflateResetKeep(g)):py}function inflateReset2(g,f){var S,v;return g&&g.state?(v=g.state,f<0?(S=0,f=-f):(S=1+(f>>4),f<48&&(f&=15)),f&&(f<8||f>15)?py:(null!==v.window&&v.wbits!==f&&(v.window=null),v.wrap=S,v.wbits=f,inflateReset(g))):py}function inflateInit2(g,f){var S,v;return g?(v=new InflateState,g.state=v,v.window=null,(S=inflateReset2(g,f))!==hy&&(g.state=null),S):py}function inflateInit(g){return inflateInit2(g,Xy)}var Zy,eE,tE=!0;function fixedtables(g){if(tE){var f;for(Zy=new YS.Buf32(512),eE=new YS.Buf32(32),f=0;f<144;)g.lens[f++]=8;for(;f<256;)g.lens[f++]=9;for(;f<280;)g.lens[f++]=7;for(;f<288;)g.lens[f++]=8;for(ry(ay,g.lens,0,288,Zy,0,g.work,{bits:9}),f=0;f<32;)g.lens[f++]=5;ry(oy,g.lens,0,32,eE,0,g.work,{bits:5}),tE=!1}g.lencode=Zy,g.lenbits=9,g.distcode=eE,g.distbits=5}function updatewindow(g,f,S,v){var C,_=g.state;return null===_.window&&(_.wsize=1<<_.wbits,_.wnext=0,_.whave=0,_.window=new YS.Buf8(_.wsize)),v>=_.wsize?(YS.arraySet(_.window,f,S-_.wsize,_.wsize,0),_.wnext=0,_.whave=_.wsize):((C=_.wsize-_.wnext)>v&&(C=v),YS.arraySet(_.window,f,S-v,C,_.wnext),(v-=C)?(YS.arraySet(_.window,f,S-v,v,0),_.wnext=v,_.whave=_.wsize):(_.wnext+=C,_.wnext===_.wsize&&(_.wnext=0),_.whave<_.wsize&&(_.whave+=C))),0}function inflate(g,f){var S,v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j=0,G=new YS.Buf8(4),q=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!g||!g.state||!g.output||!g.input&&0!==g.avail_in)return py;(S=g.state).mode===wy&&(S.mode=Oy),T=g.next_out,C=g.output,b=g.avail_out,_=g.next_in,v=g.input,I=g.avail_in,A=S.hold,P=S.bits,R=I,M=b,B=hy;e:for(;;)switch(S.mode){case Cy:if(0===S.wrap){S.mode=Oy;break}for(;P<16;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if(2&S.wrap&&35615===A){S.check=0,G[0]=255&A,G[1]=A>>>8&255,S.check=Uv(S.check,G,2,0),A=0,P=0,S.mode=yy;break}if(S.flags=0,S.head&&(S.head.done=!1),!(1&S.wrap)||(((255&A)<<8)+(A>>8))%31){g.msg="incorrect header check",S.mode=Ky;break}if((15&A)!==vy){g.msg="unknown compression method",S.mode=Ky;break}if(P-=4,V=8+(15&(A>>>=4)),0===S.wbits)S.wbits=V;else if(V>S.wbits){g.msg="invalid window size",S.mode=Ky;break}S.dmax=1<<V,g.adler=S.check=1,S.mode=512&A?Ry:wy,A=0,P=0;break;case yy:for(;P<16;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if(S.flags=A,(255&S.flags)!==vy){g.msg="unknown compression method",S.mode=Ky;break}if(57344&S.flags){g.msg="unknown header flags set",S.mode=Ky;break}S.head&&(S.head.text=A>>8&1),512&S.flags&&(G[0]=255&A,G[1]=A>>>8&255,S.check=Uv(S.check,G,2,0)),A=0,P=0,S.mode=Ey;case Ey:for(;P<32;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}S.head&&(S.head.time=A),512&S.flags&&(G[0]=255&A,G[1]=A>>>8&255,G[2]=A>>>16&255,G[3]=A>>>24&255,S.check=Uv(S.check,G,4,0)),A=0,P=0,S.mode=_y;case _y:for(;P<16;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}S.head&&(S.head.xflags=255&A,S.head.os=A>>8),512&S.flags&&(G[0]=255&A,G[1]=A>>>8&255,S.check=Uv(S.check,G,2,0)),A=0,P=0,S.mode=Ty;case Ty:if(1024&S.flags){for(;P<16;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}S.length=A,S.head&&(S.head.extra_len=A),512&S.flags&&(G[0]=255&A,G[1]=A>>>8&255,S.check=Uv(S.check,G,2,0)),A=0,P=0}else S.head&&(S.head.extra=null);S.mode=Iy;case Iy:if(1024&S.flags&&((w=S.length)>I&&(w=I),w&&(S.head&&(V=S.head.extra_len-S.length,S.head.extra||(S.head.extra=new Array(S.head.extra_len)),YS.arraySet(S.head.extra,v,_,w,V)),512&S.flags&&(S.check=Uv(S.check,v,w,_)),I-=w,_+=w,S.length-=w),S.length))break e;S.length=0,S.mode=by;case by:if(2048&S.flags){if(0===I)break e;w=0;do{V=v[_+w++],S.head&&V&&S.length<65536&&(S.head.name+=String.fromCharCode(V))}while(V&&w<I);if(512&S.flags&&(S.check=Uv(S.check,v,w,_)),I-=w,_+=w,V)break e}else S.head&&(S.head.name=null);S.length=0,S.mode=Ay;case Ay:if(4096&S.flags){if(0===I)break e;w=0;do{V=v[_+w++],S.head&&V&&S.length<65536&&(S.head.comment+=String.fromCharCode(V))}while(V&&w<I);if(512&S.flags&&(S.check=Uv(S.check,v,w,_)),I-=w,_+=w,V)break e}else S.head&&(S.head.comment=null);S.mode=Py;case Py:if(512&S.flags){for(;P<16;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if(A!==(65535&S.check)){g.msg="header crc mismatch",S.mode=Ky;break}A=0,P=0}S.head&&(S.head.hcrc=S.flags>>9&1,S.head.done=!0),g.adler=S.check=0,S.mode=wy;break;case Ry:for(;P<32;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}g.adler=S.check=zswap32(A),A=0,P=0,S.mode=My;case My:if(0===S.havedict)return g.next_out=T,g.avail_out=b,g.next_in=_,g.avail_in=I,S.hold=A,S.bits=P,gy;g.adler=S.check=1,S.mode=wy;case wy:if(f===cy||f===dy)break e;case Oy:if(S.last){A>>>=7&P,P-=7&P,S.mode=qy;break}for(;P<3;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}switch(S.last=1&A,P-=1,3&(A>>>=1)){case 0:S.mode=Dy;break;case 1:if(fixedtables(S),S.mode=Uy,f===dy){A>>>=2,P-=2;break e}break;case 2:S.mode=Ly;break;case 3:g.msg="invalid block type",S.mode=Ky}A>>>=2,P-=2;break;case Dy:for(A>>>=7&P,P-=7&P;P<32;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if((65535&A)!=(A>>>16^65535)){g.msg="invalid stored block lengths",S.mode=Ky;break}if(S.length=65535&A,A=0,P=0,S.mode=Ny,f===dy)break e;case Ny:S.mode=ky;case ky:if(w=S.length){if(w>I&&(w=I),w>b&&(w=b),0===w)break e;YS.arraySet(C,v,_,w,T),I-=w,_+=w,b-=w,T+=w,S.length-=w;break}S.mode=wy;break;case Ly:for(;P<14;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if(S.nlen=257+(31&A),A>>>=5,P-=5,S.ndist=1+(31&A),A>>>=5,P-=5,S.ncode=4+(15&A),A>>>=4,P-=4,S.nlen>286||S.ndist>30){g.msg="too many length or distance symbols",S.mode=Ky;break}S.have=0,S.mode=Fy;case Fy:for(;S.have<S.ncode;){for(;P<3;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}S.lens[q[S.have++]]=7&A,A>>>=3,P-=3}for(;S.have<19;)S.lens[q[S.have++]]=0;if(S.lencode=S.lendyn,S.lenbits=7,H={bits:S.lenbits},B=ry(sy,S.lens,0,19,S.lencode,0,S.work,H),S.lenbits=H.bits,B){g.msg="invalid code lengths set",S.mode=Ky;break}S.have=0,S.mode=xy;case xy:for(;S.have<S.nlen+S.ndist;){for(;k=(j=S.lencode[A&(1<<S.lenbits)-1])>>>16&255,L=65535&j,!((N=j>>>24)<=P);){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if(L<16)A>>>=N,P-=N,S.lens[S.have++]=L;else{if(16===L){for($=N+2;P<$;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if(A>>>=N,P-=N,0===S.have){g.msg="invalid bit length repeat",S.mode=Ky;break}V=S.lens[S.have-1],w=3+(3&A),A>>>=2,P-=2}else if(17===L){for($=N+3;P<$;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}P-=N,V=0,w=3+(7&(A>>>=N)),A>>>=3,P-=3}else{for($=N+7;P<$;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}P-=N,V=0,w=11+(127&(A>>>=N)),A>>>=7,P-=7}if(S.have+w>S.nlen+S.ndist){g.msg="invalid bit length repeat",S.mode=Ky;break}for(;w--;)S.lens[S.have++]=V}}if(S.mode===Ky)break;if(0===S.lens[256]){g.msg="invalid code -- missing end-of-block",S.mode=Ky;break}if(S.lenbits=9,H={bits:S.lenbits},B=ry(ay,S.lens,0,S.nlen,S.lencode,0,S.work,H),S.lenbits=H.bits,B){g.msg="invalid literal/lengths set",S.mode=Ky;break}if(S.distbits=6,S.distcode=S.distdyn,H={bits:S.distbits},B=ry(oy,S.lens,S.nlen,S.ndist,S.distcode,0,S.work,H),S.distbits=H.bits,B){g.msg="invalid distances set",S.mode=Ky;break}if(S.mode=Uy,f===dy)break e;case Uy:S.mode=Vy;case Vy:if(I>=6&&b>=258){g.next_out=T,g.avail_out=b,g.next_in=_,g.avail_in=I,S.hold=A,S.bits=P,zC(g,M),T=g.next_out,C=g.output,b=g.avail_out,_=g.next_in,v=g.input,I=g.avail_in,A=S.hold,P=S.bits,S.mode===wy&&(S.back=-1);break}for(S.back=0;k=(j=S.lencode[A&(1<<S.lenbits)-1])>>>16&255,L=65535&j,!((N=j>>>24)<=P);){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if(k&&0==(240&k)){for(F=N,x=k,U=L;k=(j=S.lencode[U+((A&(1<<F+x)-1)>>F)])>>>16&255,L=65535&j,!(F+(N=j>>>24)<=P);){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}A>>>=F,P-=F,S.back+=F}if(A>>>=N,P-=N,S.back+=N,S.length=L,0===k){S.mode=Gy;break}if(32&k){S.back=-1,S.mode=wy;break}if(64&k){g.msg="invalid literal/length code",S.mode=Ky;break}S.extra=15&k,S.mode=By;case By:if(S.extra){for($=S.extra;P<$;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}S.length+=A&(1<<S.extra)-1,A>>>=S.extra,P-=S.extra,S.back+=S.extra}S.was=S.length,S.mode=Hy;case Hy:for(;k=(j=S.distcode[A&(1<<S.distbits)-1])>>>16&255,L=65535&j,!((N=j>>>24)<=P);){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if(0==(240&k)){for(F=N,x=k,U=L;k=(j=S.distcode[U+((A&(1<<F+x)-1)>>F)])>>>16&255,L=65535&j,!(F+(N=j>>>24)<=P);){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}A>>>=F,P-=F,S.back+=F}if(A>>>=N,P-=N,S.back+=N,64&k){g.msg="invalid distance code",S.mode=Ky;break}S.offset=L,S.extra=15&k,S.mode=$y;case $y:if(S.extra){for($=S.extra;P<$;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}S.offset+=A&(1<<S.extra)-1,A>>>=S.extra,P-=S.extra,S.back+=S.extra}if(S.offset>S.dmax){g.msg="invalid distance too far back",S.mode=Ky;break}S.mode=jy;case jy:if(0===b)break e;if(w=M-b,S.offset>w){if((w=S.offset-w)>S.whave&&S.sane){g.msg="invalid distance too far back",S.mode=Ky;break}w>S.wnext?(w-=S.wnext,O=S.wsize-w):O=S.wnext-w,w>S.length&&(w=S.length),D=S.window}else D=C,O=T-S.offset,w=S.length;w>b&&(w=b),b-=w,S.length-=w;do{C[T++]=D[O++]}while(--w);0===S.length&&(S.mode=Vy);break;case Gy:if(0===b)break e;C[T++]=S.length,b--,S.mode=Vy;break;case qy:if(S.wrap){for(;P<32;){if(0===I)break e;I--,A|=v[_++]<<P,P+=8}if(M-=b,g.total_out+=M,S.total+=M,M&&(g.adler=S.check=S.flags?Uv(S.check,C,M,T-M):Lv(S.check,C,M,T-M)),M=b,(S.flags?A:zswap32(A))!==S.check){g.msg="incorrect data check",S.mode=Ky;break}A=0,P=0}S.mode=Wy;case Wy:if(S.wrap&&S.flags){for(;P<32;){if(0===I)break e;I--,A+=v[_++]<<P,P+=8}if(A!==(4294967295&S.total)){g.msg="incorrect length check",S.mode=Ky;break}A=0,P=0}S.mode=zy;case zy:B=uy;break e;case Ky:B=my;break e;case Jy:return fy;default:return py}return g.next_out=T,g.avail_out=b,g.next_in=_,g.avail_in=I,S.hold=A,S.bits=P,(S.wsize||M!==g.avail_out&&S.mode<Ky&&(S.mode<qy||f!==ly))&&updatewindow(g,g.output,g.next_out,M-g.avail_out),R-=g.avail_in,M-=g.avail_out,g.total_in+=R,g.total_out+=M,S.total+=M,S.wrap&&M&&(g.adler=S.check=S.flags?Uv(S.check,C,M,g.next_out-M):Lv(S.check,C,M,g.next_out-M)),g.data_type=S.bits+(S.last?64:0)+(S.mode===wy?128:0)+(S.mode===Uy||S.mode===Ny?256:0),(0===R&&0===M||f===ly)&&B===hy&&(B=Sy),B}function inflateEnd(g){if(!g||!g.state)return py;var f=g.state;return f.window&&(f.window=null),g.state=null,hy}function inflateGetHeader(g,f){var S;return g&&g.state?0==(2&(S=g.state).wrap)?py:(S.head=f,f.done=!1,hy):py}function inflateSetDictionary(g,f){var S,v=f.length;return g&&g.state?0!==(S=g.state).wrap&&S.mode!==My?py:S.mode===My&&Lv(1,f,v,0)!==S.check?my:updatewindow(g,f,v,v)?(S.mode=Jy,fy):(S.havedict=1,hy):py}var iE={inflateReset:inflateReset,inflateReset2:inflateReset2,inflateResetKeep:inflateResetKeep,inflateInit:inflateInit,inflateInit2:inflateInit2,inflate:inflate,inflateEnd:inflateEnd,inflateGetHeader:inflateGetHeader,inflateSetDictionary:inflateSetDictionary,inflateInfo:"pako inflate (from Nodeca project)"},nE={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_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};function GZheader(){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}var rE=GZheader,sE=Object.prototype.toString;function Inflate(g){if(!(this instanceof Inflate))return new Inflate(g);this.options=YS.assign({chunkSize:16384,windowBits:0,to:""},g||{});var f=this.options;f.raw&&f.windowBits>=0&&f.windowBits<16&&(f.windowBits=-f.windowBits,0===f.windowBits&&(f.windowBits=-15)),!(f.windowBits>=0&&f.windowBits<16)||g&&g.windowBits||(f.windowBits+=32),f.windowBits>15&&f.windowBits<48&&0==(15&f.windowBits)&&(f.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new kC,this.strm.avail_out=0;var S=iE.inflateInit2(this.strm,f.windowBits);if(S!==nE.Z_OK)throw new Error(Vv[S]);this.header=new rE,iE.inflateGetHeader(this.strm,this.header)}function inflate$1(g,f){var S=new Inflate(f);if(S.push(g,!0),S.err)throw S.msg;return S.result}function inflateRaw(g,f){return(f=f||{}).raw=!0,inflate$1(g,f)}Inflate.prototype.push=function(g,f){var S,v,C,_,T,I,b=this.strm,A=this.options.chunkSize,P=this.options.dictionary,R=!1;if(this.ended)return!1;v=f===~~f?f:!0===f?nE.Z_FINISH:nE.Z_NO_FLUSH,"string"==typeof g?b.input=NC.binstring2buf(g):"[object ArrayBuffer]"===sE.call(g)?b.input=new Uint8Array(g):b.input=g,b.next_in=0,b.avail_in=b.input.length;do{if(0===b.avail_out&&(b.output=new YS.Buf8(A),b.next_out=0,b.avail_out=A),(S=iE.inflate(b,nE.Z_NO_FLUSH))===nE.Z_NEED_DICT&&P&&(I="string"==typeof P?NC.string2buf(P):"[object ArrayBuffer]"===sE.call(P)?new Uint8Array(P):P,S=iE.inflateSetDictionary(this.strm,I)),S===nE.Z_BUF_ERROR&&!0===R&&(S=nE.Z_OK,R=!1),S!==nE.Z_STREAM_END&&S!==nE.Z_OK)return this.onEnd(S),this.ended=!0,!1;b.next_out&&(0!==b.avail_out&&S!==nE.Z_STREAM_END&&(0!==b.avail_in||v!==nE.Z_FINISH&&v!==nE.Z_SYNC_FLUSH)||("string"===this.options.to?(C=NC.utf8border(b.output,b.next_out),_=b.next_out-C,T=NC.buf2string(b.output,C),b.next_out=_,b.avail_out=A-_,_&&YS.arraySet(b.output,b.output,C,_,0),this.onData(T)):this.onData(YS.shrinkBuf(b.output,b.next_out)))),0===b.avail_in&&0===b.avail_out&&(R=!0)}while((b.avail_in>0||0===b.avail_out)&&S!==nE.Z_STREAM_END);return S===nE.Z_STREAM_END&&(v=nE.Z_FINISH),v===nE.Z_FINISH?(S=iE.inflateEnd(this.strm),this.onEnd(S),this.ended=!0,S===nE.Z_OK):v!==nE.Z_SYNC_FLUSH||(this.onEnd(nE.Z_OK),b.avail_out=0,!0)},Inflate.prototype.onData=function(g){this.chunks.push(g)},Inflate.prototype.onEnd=function(g){g===nE.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=YS.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg};var aE={Inflate:Inflate,inflate:inflate$1,inflateRaw:inflateRaw,ungzip:inflate$1},oE={};(0,YS.assign)(oE,GC,aE,nE);var lE=oE;function defer$1(){let g,f,S=!0;return{isPending:()=>S,promise:new Promise(((S,v)=>{g=S,f=v})),resolve:f=>{S&&(g(f),S=!1)},reject:g=>{S&&(f(g),S=!1)}}}function sleep(g){return new Promise((f=>_setTimeout(f,g)))}function _setTimeout(g,f){return globalThis.setTimeout(g,f)}function _clearTimeout(g){globalThis.clearTimeout(g)}function wait(g,f){const S=defer$1();let v;try{v=g()}catch(g){return Promise.reject(S.reject(g))}if(f<0)return v.finally((()=>{S.resolve(v)})),S.promise;const C=_setTimeout((()=>{S.isPending()&&S.reject(new CallingCommunicationError({defaultError:D.INTERNAL.OPERATION_TIMEDOUT}))}),f);return v.catch((g=>{_clearTimeout(C),S.isPending()&&S.reject(g)})).finally((()=>{_clearTimeout(C),S.isPending()&&S.resolve(v)})),S.promise}function dictOrderGreaterFirst(g,f){var S=g.toString(),v=f.toString();return S>v?1:S<v?-1:0}var cE=dictOrderGreaterFirst;function _classCallCheck(g,f){if(!(g instanceof f))throw new TypeError("Cannot call a class as a function")}function _defineProperties(g,f){for(var S=0;S<f.length;S++){var v=f[S];v.enumerable=v.enumerable||!1,v.configurable=!0,"value"in v&&(v.writable=!0),Object.defineProperty(g,v.key,v)}}function _createClass(g,f,S){return f&&_defineProperties(g.prototype,f),S&&_defineProperties(g,S),g}function _defineProperty(g,f,S){return f in g?Object.defineProperty(g,f,{value:S,enumerable:!0,configurable:!0,writable:!0}):g[f]=S,g}var dE=function(){function PriorityQueue(){var g=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).comparator,f=void 0===g?cE:g;_classCallCheck(this,PriorityQueue),_defineProperty(this,"comparator",void 0),this.comparator=f}return _createClass(PriorityQueue,null,[{key:"from",value:function from(g,f){throw new Error("not implemented")}}]),_createClass(PriorityQueue,[{key:"clear",value:function clear(){throw new Error("not implemented")}},{key:"toArray",value:function toArray(){throw new Error("not implemented")}},{key:"push",value:function push(g){throw new Error("not implemented")}},{key:"enqueue",value:function enqueue(g){return this.push(g)}},{key:"top",value:function top(){throw new Error("not implemented")}},{key:"peek",value:function peek(){return this.top()}},{key:"pop",value:function pop(){throw new Error("not implemented")}},{key:"dequeue",value:function dequeue(){return this.pop()}},{key:"merge",value:function merge(g){throw new Error("not implemented")}},{key:"isEmpty",value:function isEmpty(){throw new Error("not implemented")}},{key:"length",get:function get(){throw new Error("not implemented")}}]),PriorityQueue}();function _typeof(g){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function _typeof(g){return typeof g}:function _typeof(g){return g&&"function"==typeof Symbol&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g},_typeof(g)}function _toConsumableArray(g){return _arrayWithoutHoles(g)||_iterableToArray(g)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}function _iterableToArray(g){if(Symbol.iterator in Object(g)||"[object Arguments]"===Object.prototype.toString.call(g))return Array.from(g)}function _arrayWithoutHoles(g){if(Array.isArray(g)){for(var f=0,S=new Array(g.length);f<g.length;f++)S[f]=g[f];return S}}function _classCallCheck$1(g,f){if(!(g instanceof f))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1(g,f){for(var S=0;S<f.length;S++){var v=f[S];v.enumerable=v.enumerable||!1,v.configurable=!0,"value"in v&&(v.writable=!0),Object.defineProperty(g,v.key,v)}}function _createClass$1(g,f,S){return f&&_defineProperties$1(g.prototype,f),S&&_defineProperties$1(g,S),g}function _possibleConstructorReturn(g,f){return!f||"object"!==_typeof(f)&&"function"!=typeof f?_assertThisInitialized(g):f}function _getPrototypeOf(g){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(g){return g.__proto__||Object.getPrototypeOf(g)},_getPrototypeOf(g)}function _assertThisInitialized(g){if(void 0===g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return g}function _inherits(g,f){if("function"!=typeof f&&null!==f)throw new TypeError("Super expression must either be null or a function");g.prototype=Object.create(f&&f.prototype,{constructor:{value:g,writable:!0,configurable:!0}}),f&&_setPrototypeOf(g,f)}function _setPrototypeOf(g,f){return _setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(g,f){return g.__proto__=f,g},_setPrototypeOf(g,f)}function _defineProperty$1(g,f,S){return f in g?Object.defineProperty(g,f,{value:S,enumerable:!0,configurable:!0,writable:!0}):g[f]=S,g}function getLargestIndex(g,f,S){var v=2*f,C=2*f+1,_=f;return v<g.length&&S(g[_],g[v])<0&&(_=v),C<g.length&&S(g[_],g[C])<0&&(_=C),_}function heapify(g,f,S){var v=getLargestIndex(g,f,S);if(v!==f){var C=g[f];g[f]=g[v],g[v]=C,heapify(g,v,S)}}function heapifyAll(g){for(var f=Math.floor(g.collection.length/2)-1;f>=0;--f)heapify(g.collection,f,g.comparator)}var hE,uE,gE,pE,mE,fE,SE,vE=function(g){function BinaryHeap(){var g,f;_classCallCheck$1(this,BinaryHeap);for(var S=arguments.length,v=new Array(S),C=0;C<S;C++)v[C]=arguments[C];return _defineProperty$1(_assertThisInitialized(f=_possibleConstructorReturn(this,(g=_getPrototypeOf(BinaryHeap)).call.apply(g,[this].concat(v)))),"collection",[]),f}return _inherits(BinaryHeap,g),_createClass$1(BinaryHeap,[{key:"clear",value:function clear(){this.collection.length=0}},{key:"toArray",value:function toArray(){return _toConsumableArray(this.collection).sort(this.comparator)}},{key:"top",value:function top(){if(0===this.length)throw new Error("invalid operation: top() called for empty BinaryHeap");return this.collection[0]}},{key:"pop",value:function pop(){if(0===this.length)throw new Error("invalid operation: pop() called for empty BinaryHeap");var g=this.collection[0];return this.collection.length>1?(this.collection[0]=this.collection.pop(),heapify(this.collection,0,this.comparator)):this.collection.pop(),g}},{key:"push",value:function push(g){this.collection.push(g);for(var f=this.collection,S=f.length-1,v=Math.floor(S/2);S>0&&this.comparator(f[v],f[S])<0;S=v,v=Math.floor(v/2)){var C=f[S];f[S]=f[v],f[v]=C}}},{key:"merge",value:function merge(g){this.collection=g instanceof BinaryHeap?this.collection.concat(g.collection):this.collection.concat(g.toArray()),heapifyAll(this),g.clear()}},{key:"isEmpty",value:function isEmpty(){return!this.collection.length}},{key:"length",get:function get(){return this.collection.length}}],[{key:"from",value:function from(g){var f=new BinaryHeap(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return f.collection=Array.from(g),heapifyAll(f),f}}]),BinaryHeap}(dE),CE=vE;class NotificationManager$1{constructor(g,f){this._tenantId=g,this.listeners=[],this._logger=f.createChild(`TelemetryLogger[${g}]`);const S=this._tenantId;f.log(`Notification Manager Notification Manager logger initialized for tenant ${S}`),this._discardedEventsBufferPQ=new CE({comparator:(g,f)=>f.latency-g.latency})}addNotificationListener(g){this.listeners.find((f=>f===g))||this.listeners.push(g)}removeNotificationListener(g){this.listeners=this.listeners.filter((f=>f!==g))}eventsSent(g){const f=JSON.stringify(g);this._logger.log(`Notification Manager sent telemetry events ${f}`),this.listeners.forEach((f=>f.eventsSent&&f.eventsSent(g)))}eventsDiscarded(g,f){this._logger.log(`Notification Manager discarded telemetry events ${JSON.stringify(g)}, reason ${f} adding to retry buffer`),g.forEach((g=>{g.latency=g.latency||Ga.Normal;const f=g;(f.sendAttempt||0)<=getAcsEcsConfig().telemetry.discardedEventsMaxRetries?this._discardedEventsBufferPQ.push(f):this._logger.log(`Notification Manager dropping event due to too many retries ${JSON.stringify(g)}`)}));const S=getAcsEcsConfig().telemetry.discardedEventsBufferMaxLength;for(;this._discardedEventsBufferPQ.length>S;)this._logger.log(` dropping event from retry buffer ${this._discardedEventsBufferPQ.dequeue()} due to overflow`);this.listeners.forEach((S=>S.eventsDiscarded&&S.eventsDiscarded(g,f)))}getDiscardedEvents(){const g=[],f=this._discardedEventsBufferPQ.length;for(let S=0;S<f;S++)g.push(this._discardedEventsBufferPQ.dequeue());return g}}class TelemetryLogManager{constructor(g,f,S,v){this._sentEventsMap=new Map,this._telemetryLoggers=new Map,this._eventsBufferMap=new Map,this._initialized=!1,this.sdkDiagnosticInformation="",this._telemetryRateLimit=new Map,this._mediaEventsReportedForTheCall={},this._logger=g.createChild("TelemetryLogManager"),this.sdkDiagnosticInformation=f,this._sdkInternaVersion=getSdkInternalVersion(),this._acsProxy=S,this._acsCustomRelayManager=v,getAcsEcsConfig().telemetry.limit.rates.forEach((g=>{this._telemetryRateLimit.set(g.eventName,{...g,windowStartTime:Date.now(),eventCount:0})}))}getSentEventsMap(){return this._sentEventsMap}getTelemetryLoggers(){return this._telemetryLoggers}getEventsBufferMap(){return this._eventsBufferMap}isInitialized(){return this._initialized}getCloudType(){return this._caConfigBag?.cloudType}getAcsResourceId(){return this._caConfigBag?.acsResourceId}getClientId(){return this._caConfigBag?.clientId}initialize(g){if(!g.cloudType)throw this._logger.error("Failed to initialize telemetry loggers, invalid cloud type provided."),new CallingCommunicationError({defaultError:D.INTERNAL.TELEMETRY_FAILED_TO_INITIALIZE_INVALID_CLOUD_TYPE});if(this._initialized)throw this._logger.error("Failed to initialize telemetry loggers, telemetry log manager is already initialized."),new CallingCommunicationError({defaultError:D.INTERNAL.TELEMETRY_FAILED_TO_INITIALIZE_ALREADY_INITIALIZED});this._telemetryLoggers.forEach(((f,S)=>{try{f.initialize(g),this._logger.log(`Initialized and flushed buffered telemetry logger for ${S}`)}catch(g){this._logger.warn(`Failed to initialize and flush buffered telemetry logger for ${S}`),this._telemetryLoggers.delete(S)}})),this._initialized=!0,this._caConfigBag=g,this._logger.log(`Telemetry log manager has been initialized for Call Client: ${this._caConfigBag.clientId}`)}clearTelemetryLoggers(){const g=this._telemetryLoggers.size;return this._telemetryLoggers=new Map,this._caConfigBag=void 0,this._initialized=!1,g}getMediaEventReportedPromise(g){if(!this._mediaEventsReportedForTheCall[g]){const f=defer();f.promise.catch(noop),this._mediaEventsReportedForTheCall[g]=f}return this._mediaEventsReportedForTheCall[g].promise}_reportMediaEventForTheCall(g){if(this._mediaEventsReportedForTheCall[g])this._mediaEventsReportedForTheCall[g].resolve();else{const f=defer();f.promise.catch(noop),f.resolve(),this._mediaEventsReportedForTheCall[g]=f}}_getEventDataWithoutPii(g){const f={};if(g.properties)for(const S of Object.keys(g.properties)){const v=g.properties[S];f[S]={value:v?.value??v,kind:v?.piiKind??0}}return f}sendEvent(g,f,S){try{const v=this._sentEventsMap.get(g.properties?.correlationId),C=v?.get(S)??0;if(void 0!==S&&C>0)return;if(S&&"attempt"!==S&&0===(v?.get("attempt")??0))return;if(this._logger.debug(`sending event=${g.name}`),this.checkIfEventIsBlocked(g)||this.shouldLimitSendingTelemetry(g.name)||this.isRateLimitExceeded(g.name))return void this._logger.debug(`event=${g.name} is blocked`);const _={name:g.name,data:g.properties};_?.name in IE&&(_.data=this._getEventDataWithoutPii(g)),void 0===_.data&&(_.data={}),_?.name===IE.mdsc_webrtc_session&&this._reportMediaEventForTheCall(_?.data?.CorrelationId),void 0!==typeof g.priority?_.latency=g.priority:_.latency=Ga.Normal;const T=getAcsEcsConfig().telemetryEvents.eventNameToPriority.eventName.indexOf(g.name);-1!==T&&(_.latency=getAcsEcsConfig().telemetryEvents.eventNameToPriority.priority[T]),_.data.sdkVersion=this._sdkInternaVersion,_.data.platformId=getPlatformId();const I=`${getPlatformId()}/${this._sdkInternaVersion}`;_.data.uiVersion=I,_.data.ui_version=I,_.data.Platform_Uiversion=I,_.data.userAgent=`${this.sdkDiagnosticInformation} ${navigator.userAgent}`,_.data.clientTimestamp=+new Date,_.data.customProxyAndRelayUsage=this.getCustomProxyAndRelayTag();const b=g.tenant;let A=this._eventsBufferMap.get(b);A||(A=this._eventsBufferMap.set(b,[]).get(b));let P=this._telemetryLoggers.get(b);if(P||(P=new TelemetryLogger(b,this._logger,A,this._acsProxy),this._telemetryLoggers.set(b,P),this._logger.log(`Created telemetry logger for ${b}`)),this._initialized){if(!P.isInitialized())try{P.initialize(this._caConfigBag),this._logger.log(`Created and initialized telemetry logger for ${b}`)}catch(g){throw this._telemetryLoggers.delete(b),A?.push(_),this._logger.error(`Failed to create and initialize telemetry logger for ${b}`),new CallingCommunicationError({defaultError:D.INTERNAL.TELEMETRY_FAILED_TO_INITIALIZE,defaultErrorMessageArgs:[b]})}f&&P.getAppInsightsCore()?.addNotificationListener(f),P.sendEvent(_);const v=g.properties?.correlationId;if(void 0!==v&&void 0!==S){const g=this._sentEventsMap.get(v)??new Map;g.set(S,(g.get(S)??0)+1),this._sentEventsMap.set(v,g)}}else A?.push(_)}catch(f){this._logger.warn(`Failed to send event ${g?.name}`)}}deleteEventMapByCorrelationId(g){this._sentEventsMap.delete(g)}async flushAllEvents(g){if(this._logger.debug(`flushing events: ${this._telemetryLoggers.size}`),-1!==getAcsEcsConfig().telemetry.telemetryFlushTimeout){const flushLogger=(f,S)=>{try{const v=defer();v.promise.catch(noop);const C=wait((async()=>(S===rf&&await this.getMediaEventReportedPromise(g),v.promise)),getAcsEcsConfig().telemetry.telemetryFlushTimeout);return f.flushEvents((()=>{this._logger.debug("events flushed"),v.resolve()})),C.then(noop)}catch(g){throw new CallingCommunicationError({defaultError:D.INTERNAL.TELEMETRY_FAILED_TO_FLUSH})}},f=[];return this._telemetryLoggers.forEach(((g,S)=>{f.push(flushLogger(g,S).catch((()=>{this._logger.warn("Failed to flush telemetry")})))})),Promise.all(f)}this._telemetryLoggers.forEach((g=>{try{g.flushEvents()}catch(g){this._logger.warn("Failed to flush telemetry")}}))}checkIfEventIsBlocked(g){const f=g.name,S=g.properties?.kindOfEvent,v=getAcsEcsConfig().telemetry.blockedEvents,C=getAcsEcsConfig().telemetry.blockedKindOfEvents;return v.includes(f)||void 0!==C.find((g=>g.name==f&&g.kindOfEvents.includes(S)))}shouldLimitSendingTelemetry(g){return getAcsEcsConfig().telemetry.limit.outSideCall.enabled&&(0===getAcsEcsConfig().telemetry.limit.outSideCall.includedEvents.length||getAcsEcsConfig().telemetry.limit.outSideCall.includedEvents.includes(g))&&!getAcsEcsConfig().telemetry.limit.outSideCall.excludedEvents.includes(g)&&TelemetryLogManager.callEndTimestamp!==Number.MAX_SAFE_INTEGER&&TelemetryLogManager.callEndTimestamp+getAcsEcsConfig().telemetry.limit.outSideCall.deltaTimeInMs-Date.now()<0}isRateLimitExceeded(g){const f=this._telemetryRateLimit.get(g);if(f){const S=Date.now();if(S-f.windowStartTime>f.windowSizeInMs&&(f.windowStartTime=S,f.eventCount=0),f.eventCount++,f.eventCount>f.maxEventPerWindow)return this._logger.info(`Telemetry event ${g} is rate limited`),!0}return!1}getCustomProxyAndRelayTag(){const g=this._acsProxy?.proxyInUse??!1,f=this._acsCustomRelayManager?.hasRelayConfig??!1;return g&&f?hS.usedProxyAndNonMsftTurn:g?hS.onlyUsedProxy:f?hS.onlyUsedNonMsftTurn:hS.noCustomProxyAndTurnUsed}}TelemetryLogManager.telemetryPayloadBytesOriginal=0,TelemetryLogManager.telemetryPayloadBytesCompressed=0,TelemetryLogManager.callEndTimestamp=0;class TelemetryLogger{constructor(g,f,S,v){this._tenantId=g,this._eventsBuffer=S,this._initialized=!1,this._networkOnline=!0,this._telemetryRetryIntervalRunning=!1,this._logger=f.createChild(`TelemetryLogger[${g}]`),this._acsProxy=v,window.addEventListener("online",(g=>{this._networkOnline=g.detail,this._networkOnline&&this._initialized&&!this._telemetryRetryIntervalRunning&&(this._logger.log("browser network back online starting telemetry send retry"),this.scheduleDiscardedTelemetryRetry())}))}initialize(g){if(this._initialized)this._logger.warn(`Telemetry logger for tenant: ${this._tenantId}, already initialized`);else try{const f=new Xp;this._appInsightsCore=new ja,this._postChannel=new Sg;const S={instrumentationKey:this._tenantId,extensions:[this._postChannel,f],disableCookiesUsage:!0},v={populateBrowserInfo:!0,populateOperatingSystemInfo:!0};void 0===S.extensionConfig&&(S.extensionConfig={}),S.extensionConfig[f.identifier]=v;const C={overrideEndpointUrl:this.getAriaCollectorUrl(g),payloadPreprocessor:getAcsEcsConfig().telemetry.gzipTelemetryPayload?(g,f)=>{this.gzipPayload(g,f)}:void 0};if(S.extensionConfig[this._postChannel.identifier]=C,Object.keys(getAcsEcsConfig().calling?.eudb?.acsCompliantEvents).length>0&&(yE={...yE,...getAcsEcsConfig().calling.eudb.acsCompliantEvents}),getAcsEcsConfig().telemetry.localStorageEnable){const g=new ud;S.extensions?.push(g);const f={storageKey:"WebSdkTelemetry"};S.extensionConfig[g.identifier]=f}this._NotificationManager=new NotificationManager$1(this._tenantId,this._logger),this._appInsightsCore.initialize(S,[],void 0,this._NotificationManager),this._caConfigBag=g,this.scheduleDiscardedTelemetryRetry(),this._initialized=!0,this._eventsBuffer.forEach((g=>{this.sendEvent(g)})),this._eventsBuffer.splice(0,this._eventsBuffer.length)}catch(g){throw this._logger.error(`Failed to initialize telemetry logger for tenant: ${this._tenantId}`),new CallingCommunicationError({defaultError:D.INTERNAL.TELEMETRY_LOGGER_INIT_FAIL})}}getCloudType(){return this._caConfigBag?.cloudType}getAcsResourceId(){return this._caConfigBag?.acsResourceId}getClientId(){return this._caConfigBag?.clientId}isInitialized(){return this._initialized}getAppInsightsCore(){return this._appInsightsCore}sendEvent(g){this._initialized&&(g?.name in yE&&this.appendEudbComplianceRegionToEvent(g),g?.data&&(g.data.clientId=this._caConfigBag?.clientId||"",0===g?.name?.indexOf("mdsc_webrtc")?g.data.metrics_AcsResourceId=this._caConfigBag?.acsResourceId||"":g.data.AcsResourceId=this._caConfigBag?.acsResourceId||"",g.data.cloudType=this._caConfigBag?.cloudType||"",g.data.identityType=this._caConfigBag?.identityType||"",g.data.mriType=this._caConfigBag?.mriType||""),this.sendAppInsightsCoreEvent(g))}scheduleDiscardedTelemetryRetry(){const g=getAcsEcsConfig().telemetry.discardedTelemetryRetryTimeout,f=setInterval((async()=>{this._networkOnline?(this._NotificationManager?.getDiscardedEvents().forEach((g=>{this.sendEvent(g)})),this._telemetryRetryIntervalRunning=!0):(this._logger.log("browser lost network access stopping telemetry send retry"),clearInterval(f),this._telemetryRetryIntervalRunning=!1)}),g)}sendAppInsightsCoreEvent(g){this._appInsightsCore?.track(g)}flushEvents(g){if(this._initialized&&this._postChannel){const f=getAcsEcsConfig().telemetry.asyncTelemetryFlush;this._postChannel.flush(f,g)}}getAriaCollectorUrl(g){const f=isEudbConfigurationsApplicable(g.identityType,g.region);let S;if(g.identityType===lm.Enterprise)S=f?em.EnterpriseEUDB:em.Enterprise;else switch(g.cloudType){case tm.Public:S=f?em.PublicEUDB:em.Public;break;case tm.GccHigh:S=em.GccHigh;break;case tm.Dod:S=em.Dod;break;case tm.AirGap08:S=em.AirGap08;break;case tm.AirGap09:S=em.AirGap09;break;default:S=em.Public}return this._acsProxy?this._acsProxy.proxyfyUrl(S):S}gzipPayload(g,f){try{TelemetryLogManager.telemetryPayloadBytesOriginal+=getSizeInBytes(g.data,this._logger),g.data=lE.gzip(g.data),g.urlString+="&content-encoding=gzip",TelemetryLogManager.telemetryPayloadBytesCompressed+=getSizeInBytes(g.data,this._logger)}catch(g){this._logger.warn("Failed to gzip with pako: ",g)}f(g)}getRegion(g){if(this._caConfigBag&&isRgnClaimApplicable(this._caConfigBag.identityType))switch(g){case"emea":case"de":return fm.EMEA;case"apac":return fm.APAC;case"noam":case"amer":return fm.NOAM;default:return this._logger.log(`Unable to map region \`${g}\`, to EudbTenantRegion`),fm.UNKNOWN}return g&&um.includes(g)?fm.EMEA:g&&gm.includes(g)?fm.APAC:g&&pm.includes(g)?fm.NOAM:(this._logger.log(`Unable to map region \`${g}\`, to EudbTenantRegion`),fm.UNKNOWN)}appendEudbComplianceRegionToEvent(g){const f=this.getTenantComplianceRegion(),S=this.getRegion(this._caConfigBag?.region);if(g.data){const v={};v[EE]=f,v[TE]=S,g.data[_E]=v}}getTenantComplianceRegion(){return this._caConfigBag&&isEudbConfigurationsApplicable(this._caConfigBag.identityType,this._caConfigBag.region)?mm.EU:mm.RoW}}!function(g){g.remote_view="remote_view",g.remote_stream="remote_stream",g.network_quality="network_quality",g.video_device_issue="video_device_issue",g.other_diagnostic="other_diagnostic",g.logger_event="logger_event",g.number_of_participants="number_of_participants",g.media_metrics_device_events="media_metrics_device_events",g.sdk_active_in_another_tab="sdk_active_in_another_tab",g.network_changed="network_changed",g.video_max_capabilities="video_max_capabilities"}(hE||(hE={})),function(g){g.acs_calling_call_attempt="acs_calling_call_attempt",g.acs_calling_call_connected="acs_calling_call_connected",g.acs_calling_call_failed="acs_calling_call_failed",g.acs_calling_call_accept_attempt="acs_calling_call_accept_attempt",g.acs_calling_call_accept_connected="acs_calling_call_accept_connected",g.acs_calling_call_accept_failed="acs_calling_call_accept_failed",g.acs_calling_call_reject_attempt="acs_calling_call_reject_attempt",g.acs_calling_call_reject_success="acs_calling_call_reject_success",g.acs_calling_call_reject_failed="acs_calling_call_reject_failed",g.acs_calling_call_hangup_attempt="acs_calling_call_hangup_attempt",g.acs_calling_call_hangup_success="acs_calling_call_hangup_success",g.acs_calling_call_hangup_failure="acs_calling_call_hangup_failure",g.acs_calling_call_progress="acs_calling_call_progress",g.acs_calling_stack_init="acs_calling_stack_init",g.acs_calling_get_device_manager="acs_calling_get_device_manager",g.acs_calling_config_fetched_attempt="acs_calling_config_fetched_attempt",g.acs_calling_config_fetched_success="acs_calling_config_fetched_success",g.acs_calling_config_fetched_failure="acs_calling_config_fetched_failure",g.acs_calling_signaling_init="acs_calling_signaling_init",g.acs_calling_call_agent="acs_calling_call_agent",g.acs_calling_call_agent_init_attempt="acs_calling_call_agent_init_attempt",g.acs_calling_call_agent_init_success="acs_calling_call_agent_init_success",g.acs_calling_call_agent_init_failure="acs_calling_call_agent_init_failure",g.acs_calling_create_view_attempt="acs_calling_create_view_attempt",g.acs_calling_create_view_success="acs_calling_create_view_success",g.acs_calling_create_view_failure="acs_calling_create_view_failure",g.acs_calling_dispose_view_attempt="acs_calling_dispose_view_attempt",g.acs_calling_dispose_view_success="acs_calling_dispose_view_success",g.acs_calling_dispose_view_failure="acs_calling_dispose_view_failure",g.acs_calling_start_video_attempt="acs_calling_start_video_attempt",g.acs_calling_start_video_success="acs_calling_start_video_success",g.acs_calling_start_video_failure="acs_calling_start_video_failure",g.acs_calling_stop_video_on_ufd_attempt="acs_calling_stop_video_on_ufd_attempt",g.acs_calling_stop_video_attempt="acs_calling_stop_video_attempt",g.acs_calling_stop_video_success="acs_calling_stop_video_success",g.acs_calling_stop_video_failure="acs_calling_stop_video_failure",g.acs_calling_call_hold_and_resume="acs_calling_call_hold_and_resume",g.acs_calling_start_screen_share="acs_calling_start_screen_share",g.acs_calling_stop_screen_share="acs_calling_stop_screen_share",g.acs_calling_audio_stream_volume="acs_calling_audio_stream_volume",g.acs_calling_call_stats="acs_calling_call_stats",g.acs_calling_call_stats_and_ufds="acs_calling_call_stats_and_ufds",g.acs_calling_participant_added_or_removed="acs_calling_participant_added_or_removed",g.acs_calling_adp_attempt="acs_calling_adp_attempt",g.acs_calling_adp_success="acs_calling_adp_success",g.acs_calling_adp_failure="acs_calling_adp_failure",g.acs_calling_client_operations="acs_calling_client_operations",g.acs_calling_device_permission_changed="acs_calling_device_permission_changed",g.acs_calling_local_audio_source_changed="acs_calling_local_audio_source_changed",g.acs_calling_start_audio_stream_track="acs_calling_start_audio_stream_track",g.acs_calling_stop_audio_stream_track="acs_calling_stop_audio_stream_track",g.acs_calling_get_remote_audio_stream_track="acs_calling_get_remote_audio_stream_track",g.acs_calling_get_raw_device_media_stream="acs_calling_get_raw_device_media_stream",g.acs_calling_media_stream="acs_calling_media_stream",g.acs_calling_page_hidden="acs_calling_page_hidden",g.acs_calling_orientation_changed="acs_calling_orientation_changed",g.acs_calling_token_expiration_changed="acs_calling_token_expiration_changed",g.acs_calling_token_expiration_changed_failure="acs_calling_token_expiration_changed_failure",g.acs_calling_token_has_no_data_location="acs_calling_token_has_no_data_location",g.acs_calling_mute_on_ufd_attempt="acs_calling_mute_on_ufd_attempt",g.acs_calling_mute_attempt="acs_calling_mute_attempt",g.acs_calling_mute_success="acs_calling_mute_success",g.acs_calling_mute_failure="acs_calling_mute_failure",g.acs_calling_unmute_attempt="acs_calling_unmute_attempt",g.acs_calling_unmute_success="acs_calling_unmute_success",g.acs_calling_unmute_failure="acs_calling_unmute_failure",g.acs_calling_start_audio_attempt="acs_calling_start_audio_attempt",g.acs_calling_start_audio_success="acs_calling_start_audio_success",g.acs_calling_start_audio_failure="acs_calling_start_audio_failure",g.acs_calling_unmute_speaker_attempt="acs_calling_unmute_speaker_attempt",g.acs_calling_unmute_speaker_success="acs_calling_unmute_speaker_success",g.acs_calling_unmute_speaker_failure="acs_calling_unmute_speaker_failure",g.acs_calling_stop_audio_attempt="acs_calling_stop_audio_attempt",g.acs_calling_stop_audio_success="acs_calling_stop_audio_success",g.acs_calling_stop_audio_failure="acs_calling_stop_audio_failure",g.acs_calling_prevent_stop_audio="acs_calling_prevent_stop_audio",g.acs_calling_captions="acs_calling_captions",g.acs_calling_mid_call_media_stats="acs_calling_mid_call_media_stats",g.acs_calling_mid_call_new_media_stats="acs_calling_mid_call_new_media_stats",g.acs_calling_mid_call_raw_media_stats="acs_calling_mid_call_raw_media_stats",g.acs_calling_datachannel="acs_calling_datachannel",g.acs_calling_datachannel_stats="acs_calling_datachannel_stats",g.acs_calling_unmixed_audio="acs_calling_unmixed_audio",g.acs_calling_livestream_stats="acs_calling_livestream_stats",g.acs_calling_livestream_raw_stats="acs_calling_livestream_raw_stats",g.acs_calling_survey="acs_calling_survey",g.mdsc_call_quality_feedback="mdsc_call_quality_feedback",g.acs_calling_switch_video_source_attempt="acs_calling_switch_video_source_attempt",g.acs_calling_switch_video_source_success="acs_calling_switch_video_source_success",g.acs_calling_switch_video_source_failure="acs_calling_switch_video_source_failure",g.acs_calling_diagnostics_attempt="acs_calling_diagnostics_attempt",g.acs_calling_diagnostics_result="acs_calling_diagnostics_result",g.acs_calling_feature_usage="acs_calling_feature_usage",g.acs_calling_middletier_gateway_fetch_policy="acs_calling_middletier_gateway_fetch_policy",g.acs_calling_middletier_gateway_emergency_content="acs_calling_middletier_gateway_emergency_content",g.acs_calling_middletier_gateway_fetch_user_policies_for_captions="acs_calling_middletier_gateway_fetch_user_policies_for_captions",g.acs_calling_middletier_gateway_api="acs_calling_middletier_gateway_api",g.acs_calling_call_client_init="acs_calling_call_client_init",g.acs_calling_tab_events="acs_calling_tab_events",g.acs_calling_lobby_events="acs_calling_lobby_events",g.acs_calling_handle_push_notification="acs_calling_handle_push_notification"}(uE||(uE={})),function(g){g.attempt="attempt",g.success="success",g.failure="failure",g.getter="getter",g.setter="setter",g.subscribe="subscribe",g.unsubscribe="unsubscribe",g.initialize="initialize",g.event="event"}(gE||(gE={})),function(g){g.lobbyAdmit="lobbyAdmit",g.lobbyAdmitAll="lobbyAdmitAll",g.lobbyReject="lobbyReject"}(pE||(pE={})),function(g){g.MuteMicrophone="MuteMicrophone",g.MuteAllRemoteParticipants="MuteAllRemoteParticipants",g.MuteSpecificParticipant="MuteSpecificParticipant",g.UnmuteMicrophone="UnmuteMicrophone",g.MuteIncomingAudio="MuteIncomingAudio",g.UnmuteIncomingAudio="UnmuteIncomingAudio"}(mE||(mE={})),function(g){g.Expected="expected",g.Unexpected="unexpected",g.Unknown="unknown"}(fE||(fE={})),function(g){g.CaptionsKindChanged="CaptionsKindChanged",g.FirstCaptionReceived="FirstCaptionReceived",g.FirstCaptionParsingError="FirstCaptionParsingError",g.InitializeCaptions="InitializeCaptions",g.LanguageChanged="LanguageChanged",g.SetSpokenLanguage="SetSpokenLanguage",g.SetCaptionLanguage="SetCaptionLanguage",g.SpokenLanguageChanged="SpokenLanguageChanged",g.StartCaptions="StartCaptions",g.StopCaptions="StopCaptions",g.UpdateEndpointMetadata="UpdateEndpointMetadata",g.UpdateIsActive="UpdateIsActive",g.StartDataChannel="StartDataChannel"}(SE||(SE={}));let yE={...uE,skypecosi_concore_web_csa_conversation_callmodality:"skypecosi_concore_web_csa_conversation_callmodality",skypecosi_concore_web_pluginless_modality_session:"skypecosi_concore_web_pluginless_modality_session",skypecosi_concore_web_pluginless_call_session:"skypecosi_concore_web_pluginless_call_session",skypecosi_concore_web_csa_conversation_httprequest:"skypecosi_concore_web_csa_conversation_httprequest"};const EE="tenantComplianceRegion",_E="acsCompliancePayload",TE="tenantRegion";var IE,bE,AE,PE,RE,ME,wE;!function(g){g.mdsc_webrtc_session="mdsc_webrtc_session",g.mdsc_webrtc_session_initial="mdsc_webrtc_session_initial"}(IE||(IE={})),function(g){g.AudioRaw="AudioRaw",g.VideoRaw="VideoRaw",g.ScreenSharingRaw="ScreenSharingRaw",g.VideoRawOrScreenSharingRaw="VideoRawOrScreenSharingRaw",g.Audio="Audio",g.Video="Video"}(bE||(bE={})),function(g){g.Local="Local",g.Remote="Remote"}(AE||(AE={})),function(g){g.getMediaStream="getMediaStream",g.setMediaStream="setMediaStream",g.startEffects="startEffects",g.stopEffects="stopEffects",g.effectConfigureUpdate="effectConfigureUpdate",g.isSupported="isSupported",g.subscribe="subscribe",g.fpsWarningThresholdReached="fpsWarningThresholdReached",g.timeForEffectsWarningReached="timeForEffectsWarningReached",g.effectsError="effectsError",g.switchSource="switchSource",g.render="render",g.watermark="watermark"}(PE||(PE={})),function(g){g.stun="stun",g.turn="turn",g.turns="turns"}(RE||(RE={})),function(g){g.tcp="tcp",g.tls="tls",g.udp="udp"}(ME||(ME={})),function(g){g.Public_App="Public_App",g.Internal_LargeMeetingVideoRendering="Internal_LargeMeetingVideoRendering",g.Internal_RemoteVideoStreamDisposed="Internal_RemoteVideoStreamDisposed"}(wE||(wE={}));var OE,DE="object"==typeof Reflect?Reflect:null,NE=DE&&"function"==typeof DE.apply?DE.apply:function ReflectApply(g,f,S){return Function.prototype.apply.call(g,f,S)};function ProcessEmitWarning(g){console&&console.warn&&console.warn(g)}OE=DE&&"function"==typeof DE.ownKeys?DE.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(g){return Object.getOwnPropertyNames(g).concat(Object.getOwnPropertySymbols(g))}:function ReflectOwnKeys(g){return Object.getOwnPropertyNames(g)};var kE=Number.isNaN||function NumberIsNaN(g){return g!=g};function EventEmitter(){EventEmitter.init.call(this)}var LE=EventEmitter,FE=once;EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var xE=10;function checkListener(g){if("function"!=typeof g)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof g)}function _getMaxListeners(g){return void 0===g._maxListeners?EventEmitter.defaultMaxListeners:g._maxListeners}function _addListener(g,f,S,v){var C,_,T;if(checkListener(S),void 0===(_=g._events)?(_=g._events=Object.create(null),g._eventsCount=0):(void 0!==_.newListener&&(g.emit("newListener",f,S.listener?S.listener:S),_=g._events),T=_[f]),void 0===T)T=_[f]=S,++g._eventsCount;else if("function"==typeof T?T=_[f]=v?[S,T]:[T,S]:v?T.unshift(S):T.push(S),(C=_getMaxListeners(g))>0&&T.length>C&&!T.warned){T.warned=!0;var I=new Error("Possible EventEmitter memory leak detected. "+T.length+" "+String(f)+" listeners added. Use emitter.setMaxListeners() to increase limit");I.name="MaxListenersExceededWarning",I.emitter=g,I.type=f,I.count=T.length,ProcessEmitWarning(I)}return g}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(g,f,S){var v={fired:!1,wrapFn:void 0,target:g,type:f,listener:S},C=onceWrapper.bind(v);return C.listener=S,v.wrapFn=C,C}function _listeners(g,f,S){var v=g._events;if(void 0===v)return[];var C=v[f];return void 0===C?[]:"function"==typeof C?S?[C.listener||C]:[C]:S?unwrapListeners(C):arrayClone(C,C.length)}function listenerCount(g){var f=this._events;if(void 0!==f){var S=f[g];if("function"==typeof S)return 1;if(void 0!==S)return S.length}return 0}function arrayClone(g,f){for(var S=new Array(f),v=0;v<f;++v)S[v]=g[v];return S}function spliceOne(g,f){for(;f+1<g.length;f++)g[f]=g[f+1];g.pop()}function unwrapListeners(g){for(var f=new Array(g.length),S=0;S<f.length;++S)f[S]=g[S].listener||g[S];return f}function once(g,f){return new Promise((function(S,v){function eventListener(){void 0!==C&&g.removeListener("error",C),S([].slice.call(arguments))}var C;"error"!==f&&(C=function errorListener(S){g.removeListener(f,eventListener),v(S)},g.once("error",C)),g.once(f,eventListener)}))}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:!0,get:function(){return xE},set:function(g){if("number"!=typeof g||g<0||kE(g))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+g+".");xE=g}}),EventEmitter.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function setMaxListeners(g){if("number"!=typeof g||g<0||kE(g))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+g+".");return this._maxListeners=g,this},EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function emit(g){for(var f=[],S=1;S<arguments.length;S++)f.push(arguments[S]);var v="error"===g,C=this._events;if(void 0!==C)v=v&&void 0===C.error;else if(!v)return!1;if(v){var _;if(f.length>0&&(_=f[0]),_ instanceof Error)throw _;var T=new Error("Unhandled error."+(_?" ("+_.message+")":""));throw T.context=_,T}var I=C[g];if(void 0===I)return!1;if("function"==typeof I)NE(I,this,f);else{var b=I.length,A=arrayClone(I,b);for(S=0;S<b;++S)NE(A[S],this,f)}return!0},EventEmitter.prototype.addListener=function addListener(g,f){return _addListener(this,g,f,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function prependListener(g,f){return _addListener(this,g,f,!0)},EventEmitter.prototype.once=function once(g,f){return checkListener(f),this.on(g,_onceWrap(this,g,f)),this},EventEmitter.prototype.prependOnceListener=function prependOnceListener(g,f){return checkListener(f),this.prependListener(g,_onceWrap(this,g,f)),this},EventEmitter.prototype.removeListener=function removeListener(g,f){var S,v,C,_,T;if(checkListener(f),void 0===(v=this._events))return this;if(void 0===(S=v[g]))return this;if(S===f||S.listener===f)0==--this._eventsCount?this._events=Object.create(null):(delete v[g],v.removeListener&&this.emit("removeListener",g,S.listener||f));else if("function"!=typeof S){for(C=-1,_=S.length-1;_>=0;_--)if(S[_]===f||S[_].listener===f){T=S[_].listener,C=_;break}if(C<0)return this;0===C?S.shift():spliceOne(S,C),1===S.length&&(v[g]=S[0]),void 0!==v.removeListener&&this.emit("removeListener",g,T||f)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function removeAllListeners(g){var f,S,v;if(void 0===(S=this._events))return this;if(void 0===S.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==S[g]&&(0==--this._eventsCount?this._events=Object.create(null):delete S[g]),this;if(0===arguments.length){var C,_=Object.keys(S);for(v=0;v<_.length;++v)"removeListener"!==(C=_[v])&&this.removeAllListeners(C);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(f=S[g]))this.removeListener(g,f);else if(void 0!==f)for(v=f.length-1;v>=0;v--)this.removeListener(g,f[v]);return this},EventEmitter.prototype.listeners=function listeners(g){return _listeners(this,g,!0)},EventEmitter.prototype.rawListeners=function rawListeners(g){return _listeners(this,g,!1)},EventEmitter.listenerCount=function(g,f){return"function"==typeof g.listenerCount?g.listenerCount(f):listenerCount.call(g,f)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?OE(this._events):[]},LE.once=FE;class BaseCallAgentFeature{constructor(g){this.disposed=!1,this.callAgent=g.callAgent,this.callClient=g.callClient,this.eventEmitter=new LE.EventEmitter}dispose(){this.disposed||(this.eventEmitter.removeAllListeners(),this.disposed=!0)}}class BaseCallClientFeature{constructor(g){this.disposed=!1,this.callClient=g.callClient,this.eventEmitter=new LE.EventEmitter}dispose(){this.disposed||(this.eventEmitter.removeAllListeners(),this.disposed=!0)}}class BaseCallFeature{constructor(g){this.disposed=!1,this.call=g.call,this.callAgent=g.callAgent,this.callInfo=g.callInfo,this.eventEmitter=new LE.EventEmitter}dispose(){this.disposed||(this.eventEmitter.removeAllListeners(),this.disposed=!0)}}class PromiseQueue{constructor(g){this._logger=g,this._queue=Promise.resolve()}add(g){this._queue||(this._queue=Promise.resolve());let f=g;const S=this._queue?.then(f);return S&&(this._queue=S?.catch((g=>{throw g instanceof CallingCommunicationError?(this._logger?.error(`Error from promiseQueue! ${JSON.stringify(g)}`),g):new Error(`Error from promiseQueue! ${JSON.stringify(g)}`)}))),S}dispose(){this._queue=null}}const sequentialize=()=>(g,f,S)=>{const v=S.value;return S.value=function(...g){return this.serialQueue.add(v.bind(this,...g))},S};class BaseVideoStreamFeature{constructor(g){this.disposed=!1,this.streamInstance=g.streamInstance,this.eventEmitter=new LE.EventEmitter,this.serialQueue=new PromiseQueue(this.streamInstance.logger)}}class BaseAudioStreamFeature{constructor(g){this.disposed=!1,this.streamInstance=g.streamInstance,this.eventEmitter=new LE.EventEmitter,this.serialQueue=new PromiseQueue(this.streamInstance.logger)}}var UE,VE;!function(g){g[g.CallClientFeature=0]="CallClientFeature",g[g.CallAgentFeature=1]="CallAgentFeature",g[g.CallFeature=2]="CallFeature"}(UE||(UE={}));class FirstPartyCallFeature extends BaseCallFeature{}class FirstPartyCallAgentFeature extends BaseCallAgentFeature{}class FirstPartyCallClientFeature extends BaseCallClientFeature{}class FirstPartyVideoStreamFeature extends BaseVideoStreamFeature{}class FirstPartyAudioStreamFeature extends BaseAudioStreamFeature{}!function(g){g.Transfer="Transfer",g.StartCaptions="StartCaptions",g.StopCaptions="StopCaptions",g.SetSpokenLanguage="SetSpokenLanguage",g.SetCaptionLanguage="SetCaptionLanguage",g.getMediaStatsCollector="getMediaStatsCollector",g.disposeAllCollectors="disposeAllCollectors"}(VE||(VE={}));class ExtensibleFeatureImpl{constructor(g,f,S){this._logger=g,this._featureCtorContext=f,this._featureInitContext=S,this._apiObjInstances=new Map}getApiObjectInstance(g){if(!this._apiObjInstances.has(g)){const f=new g(this._featureCtorContext);return(f instanceof FirstPartyCallFeature||f instanceof FirstPartyCallAgentFeature||f instanceof FirstPartyCallClientFeature||f instanceof FirstPartyVideoStreamFeature||f instanceof FirstPartyAudioStreamFeature)&&f.initialize(this._featureInitContext,this._logger),this._apiObjInstances.set(g,f),f}return this._apiObjInstances.get(g)}dispose(){for(const[,g]of this._apiObjInstances)g.dispose()}}const BE={commandUrl:"",processingModes:{closedCaptions:{state:"Inactive"},realTimeTranscript:{state:"Inactive"}},spokenLanguage:""};var HE,$E;!function(g){g.Acs="acs",g.Teams="teams",g.Unknown="unknown"}(HE||(HE={})),function(g){g.Captions="captions",g.TeamsCaptions="teams_captions"}($E||($E={}));class BaseLanguageCallFeatureImplOverTsCall{constructor(g){this._eventEmitter=g,this._dataChannelId=getAcsEcsConfig().captions.dataChannelId,this._isCaptionsBot=g=>g.id===this._captionsBotMri||g.id===this._captionsLegacyBotMri,this._getBotMetadata=g=>g?.endpoints?.endpointDetails[0]?.endpointMetadata??void 0,this._getBotDataMediaStreamSourceId=g=>{if(g?.endpoints?.endpointDetails[0]?.mediaStreams){let f=g?.endpoints?.endpointDetails[0]?.mediaStreams;if(f.length>0)for(let g in f)if("data"===f[g].type)return f[g].sourceId}},this._isCaptionsEnabled=g=>"Active"===g?.processingModes?.closedCaptions?.state,this._copyBotMetaData=g=>{const f=this._getBotMetadata(g)||BE;return JSON.parse(JSON.stringify(f))}}dispose(){this._acsMetadata=void 0}}function callFeatureFactory(g,f={activationEvent:"OnFeatureAccess"}){return{get callApiCtor(){return g},activationOptions:f,isCallFeature:!0}}function callClientFeatureFactory(g,f={activationEvent:"OnFeatureAccess"}){return{get callClientApiCtor(){return g},activationOptions:f,isCallClientFeature:!0}}function videoStreamFeatureFactory(g,f={activationEvent:"OnFeatureAccess"}){return{get videoStreamApiCtor(){return g},activationOptions:f,isVideoStreamFeature:!0}}function audioStreamFeatureFactory(g,f={activationEvent:"OnFeatureAccess"}){return{get audioStreamApiCtor(){return g},activationOptions:f,isAudioStreamFeature:!0}}function getRoundedAverage(g,f,S=100){return Math.round((g/f+Number.EPSILON)*S)/S}function sendCallFeatureUsageTelemetry(g,f,S){try{const S={correlationId:g.correlationId||"",callId:g.callId,localParticipantId:g.localParticipantId,featureName:g.featureName,featureType:g.featureType,initializationType:g.initializationType,featureDetails:g.featureDetails,additionalDetails:g.additionalDetails||{},networkInfo:g.networkInfo||[]};f.sendEvent({name:uE.acs_calling_feature_usage,tenant:tf,properties:S})}catch(f){S.debug(`Unable to send ${g.featureName} feature usage telemtery`)}}function sendCallClientFeatureUsageTelemetry(g,f,S){try{const S={featureName:g.featureName,featureType:g.featureType,initializationType:g.initializationType,featureDetails:g.featureDetails};f.sendEvent({name:uE.acs_calling_feature_usage,tenant:tf,properties:S})}catch(f){S.debug(`Unable to send ${g.featureName} feature usage telemetry`)}}const jE={0:"",1:"Success",2:"NoNgcEndpoint",3:"NetworkError",4:"MediaDroppedError",5:"BadRequest",6:"CallEstablishmentTimeout",7:"CallSetupError",8:"NoPermission",9:"Missed",10:"Declined",11:"Busy",12:"Cancelled",13:"Dropped",14:"PstnInsufficientFunds",15:"PstnSkypeoutAccountBlocked",16:"PstnCouldNotConnectToSkypeProxy",17:"PstnBlockedByUs",18:"PstnBlockedRegulatoryIndia",19:"PstnInvalidNumber",20:"PstnNumberForbidden",21:"PstnCallTerminated",22:"PstnNumberUnavailable",23:"PstnEmergencyCallDenied",24:"CallNotFound",25:"LocalError",26:"NotAcceptableHere",27:"CallForwarded",28:"CallForwardedToVoicemail",29:"SkypeTokenError",30:"CallAccepted",31:"LocalHttpStackError",32:"UnknownError",33:"PstnNoSubscriptionCover",34:"SessionNotFound",35:"SessionTimedOut",36:"PstnCreditExpired",37:"PstnCreditExpiredButEnough",38:"RetargetNotSupported",39:"EnterprisePstnInternalError",40:"EnterprisePstnUnavailable",41:"EnterprisePstnForbidden",42:"EnterprisePstnInvalidNumber",43:"EnterprisePstnMiscError",44:"Kicked",45:"NetworkRequestTimeoutError",46:"CallDoesNotExist",47:"MediaSetupFailure",48:"ServiceUnavailable",49:"SignalingError",50:"ConversationEstablishmentFailed",51:"TemporarilyUnavailable",52:"CannotConnectToNetworkError",53:"MediaRelayWhiteListingIssue",54:"NoSignalingFromPeer",55:"DeniedInLobby",56:"TimedOutInLobby",57:"CallFailedConflict",58:"DevicePermissionDenied",59:"ConfParticipantCountLimitReached",60:"ActionNotAllowed",61:"Abandoned",62:"ForbiddenDueToPolicy",63:"InsufficientCapabilitiesForCallee",64:"UserBlocked",65:"AccessDenied",66:"AnonymousJoinDisabledByPolicy",67:"NoLobbyForBroadcastJoin",68:"NotAllowedDueToInformationBarrier",69:"BroadcastLimitReached",70:"TeamParkPolicyDisabled",71:"B2bJoinDisabledByPolicy",72:"LocationBasedRoutingError",73:"ConfLobbyParticipantCountLimitReached",74:"DowngradeToStreamingClient",75:"CallRedirected",76:"CallIsEndToEndEncrypted",77:"Suspended"},convertTerminatedReasonToString=g=>{const f="UnknownError";return"number"==typeof g&&jE[g]||f},GE={0:"",1:"AddingFailed",2:"NoResponse",3:"Declined",4:"NotReachable",5:"Blocked",6:"NotFriendOrAuthorized",7:"CallLimitReached",8:"CallNotFound",9:"NetworkError",10:"MediaDroppedError",11:"OtherError",12:"PstnInsufficientFunds",13:"PstnSkypeoutAccountBlocked",14:"PstnCouldNotConnectToSkypeProxy",15:"PstnBlockedByUs",16:"PstnBlockedRegulatoryIndia",17:"PstnInvalidNumber",18:"PstnNumberForbidden",19:"Busy",20:"PstnCallTerminated",21:"PstnNumberUnavailable",22:"PstnEmergencyCallDenied",23:"Cancelled",24:"Dropped",25:"PstnNoSubscriptionCover",26:"PstnCreditExpired",27:"PstnCreditExpiredButEnough",28:"EnterprisePstnInternalError",29:"EnterprisePstnUnavailable",30:"EnterprisePstnForbidden",31:"EnterprisePstnInvalidNumber",32:"EnterprisePstnMiscError",33:"Kicked",34:"NetworkRequestTimeoutError",35:"CallDoesNotExist",36:"MediaSetupFailure",37:"ServiceUnavailable",38:"SignalingError",39:"ConversationEstablishmentFailed",40:"TemporarilyUnavailable",41:"CannotConnectToNetworkError",42:"NoSignalingFromPeer",43:"ParticipantDoesNotExist",44:"DeniedInLobby",45:"TimedOutInLobby",46:"ConfParticipantCountLimitReached",47:"Abandoned",48:"ActionNotAllowed",49:"ForbiddenDueToPolicy",50:"InsufficientCapabilitiesForCallee",51:"AccessDenied",52:"NoPermission",53:"AnonymousJoinDisabledByPolicy",54:"NoLobbyForBroadcastJoin",55:"NotAllowedDueToInformationBarrier",56:"BroadcastLimitReached",57:"B2bJoinDisabledByPolicy",58:"LocationBasedRoutingError",59:"ConfLobbyParticipantCountLimitReached",60:"LobbyUserLeft"},convertParticipantStateReasonToString=g=>{const f="UnknownError";return"number"==typeof g&&GE[g]||f},qE={0:"None",1:"Incoming Call",2:"Connecting",3:"Connected",4:"LocalHold",5:"RemoteHold",10:"InLobby",9:"EarlyMedia",6:"Disconnecting",7:"Disconnected",8:"Unknown",11:"Unknown",12:"Unknown",13:"Unknown",14:"Unknown",15:"Unknown"},WE={0:"None",1:"RealTime",2:"Streaming"};function toDtmfTone(g){switch(g){case"Num0":return 0;case"Num1":return 1;case"Num2":return 2;case"Num3":return 3;case"Num4":return 4;case"Num5":return 5;case"Num6":return 6;case"Num7":return 7;case"Num8":return 8;case"Num9":return 9;case"Star":return 10;case"Pound":return 11;case"A":return 12;case"B":return 13;case"C":return 14;case"D":return 15;case"Flash":return 16;default:throw new CallingCommunicationError({defaultError:D.CALL.INVALID_DTMF_TONE})}}function getCallEndReason(g,f){let S=0,v=0,C=Gf,_=[];return S=g.tsCall.callEndDiagnosticsInfo&&g.tsCall.callEndDiagnosticsInfo.callControllerCode||0,v=g.tsCall.callEndDiagnosticsInfo&&g.tsCall.callEndDiagnosticsInfo.callControllerSubCode||0,_=N[S]?.[v]?.resultCategories||g.tsCall.callEndDiagnosticsInfo&&g.tsCall.callEndDiagnosticsInfo.resultCategories||["Success"],C=N[S]?.[v]?.message||convertTerminatedReasonToString(f||g.tsCall?.terminatedReason||0),g.logger.error(`Call end reason=${C}, code=${S}, subCode=${v}, resultCategories=${_.toString()}`),{callEndReason:{message:C,code:S,subCode:v,resultCategories:_},callingCommunicationError:new CallingCommunicationError({defaultError:{message:C,code:S,subCode:v,resultCategories:_}})}}function getRemoteParticipantCallEndReason(g,f,S){let v=0,C=0,_=Gf,T=[];if(f?.callEndDiagnosticsInfo)v=f.callEndDiagnosticsInfo&&f.callEndDiagnosticsInfo.callControllerCode||0,C=f.callEndDiagnosticsInfo&&f.callEndDiagnosticsInfo.callControllerSubCode||0,_=N[v]?.[C]?.message||convertParticipantStateReasonToString(S||f.stateReason||0),T=N[v]?.[C]?.resultCategories||f.callEndDiagnosticsInfo&&f.callEndDiagnosticsInfo.resultCategories||["Success"];else{const f=getCallEndReason(g,S);v=f.callEndReason.code,C=f.callEndReason.subCode||0,T=f.callEndReason.resultCategories,_=f.callEndReason.message}return g.logger[0===v?"info":"error"](`Participant call end reason=${_}, code=${v}, subCode=${C}, resultCategories=${T.toString()}`),{callEndReason:{message:_,code:v,subCode:C,resultCategories:T},callingCommunicationError:new CallingCommunicationError({defaultError:{message:_,code:v,subCode:C,resultCategories:T}})}}function handleVideoOperationFailure(g,f,S){let v;switch(f?.type?f.type:BS.UnknownFailureForVideoOperation){case BS.DevicesNotFoundError:v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.DEVICES_NOT_FOUND});break;case BS.MediaStreamRequestError:v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.MEDIA_STREAM_REQUEST_ERROR});break;case BS.MediaStreamRequestTimedout:v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.MEDIA_STREAM_REQUEST_TIMEDOUT});break;case BS.PermissionsDeniedBySystem:v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.PERMISSION_DENIED_BY_SYSTEM});break;case BS.UnsupportedStream:v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.UNSUPPORTED_STREAM});break;case BS.ConstraintNotSatisfiedError:v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.CONSTRAINT_NOT_SATISFIED});break;case BS.noDeviceSelected:v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.NO_DEVICE_SELECTED});break;case BS.SourceUnavailableError:v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.SOURCE_UNAVAILABLE});break;case BS.PermissionDeniedError:case BS.permissionDeniedError:v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.PERMISSION_DENIED});break;default:v=new CallingCommunicationError(S?{defaultError:D.CALL.STOP_VIDEO_FAILED}:{defaultError:D.LOCAL_VIDEO_STREAM.UNKNOWN})}return v}function handleLobbyFailure(g,f,S){const v=void 0===f?.code?500:f?._code,C=f?.subCode||f?._subCode||0;return new CallingCommunicationError({defaultError:{message:S+", reason: "+(f?.phrase||f?.message||"unknown error"),code:v,subCode:C,resultCategories:f?.resultCategories||[]}})}function handlePublishStateFailure(g,f){return new CallingCommunicationError({defaultError:{message:f.message,code:g?.response?.status||f.code,subCode:f.subCode,resultCategories:f.resultCategories},originalError:g})}function handleFetchPoliciesFromAcsMiddleTierFailure(g,f){return new CallingCommunicationError({defaultError:{message:g?.response?.data?.operationFailure?.phrase||f.message,code:g?.response?.data?.operationFailure?.code||f.code,subCode:g?.response?.data?.operationFailure?.subCode||f.subCode,resultCategories:g?.response?.data?.operationFailure?.resultCategories||f.resultCategories},originalError:g})}function extractCommunicationServicesErrorForTelemetry(g){return{communicationServicesError:{message:g.message||"Unknown error",code:void 0===g.code?U:g.code,subCode:g.subCode||0,resultCategories:void 0===g.resultCategories||0===g.resultCategories.length?["UnexpectedClientError"]:g.resultCategories,originalErrorMessage:g[$]||""}}}function extractCallEndReasonForTelemetry(g){return{callEndReason:{message:g.message,code:void 0===g.code?U:g.code,subCode:g.subCode||0,resultCategories:void 0===g.resultCategories||0===g.resultCategories.length?["UnexpectedClientError"]:g.resultCategories}}}var __decorate=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};const zE=Date.UTC(1900,0,1),KE=3;class CaptionsCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new CaptionsCallFeatureImplOverTsCall(this.eventEmitter)}initialize(g,f){const S=generateGuid();this._impl.initialize(g.tsCall,g.call,g.callAgent,g.callAgent.getHttpRequestHelper(),g.telemetryLogManager,f,this._telemetryStartTime,S),this._logger=f,this._telemetryStartTime=+Date.now(),this._telemetryLogManager=g.telemetryLogManager,this._call=g.call}get name(){return this._sendFeatureUsage("name",gE.getter),this._captionsTelemetryType.toString()}get _captionsTelemetryType(){return"TeamsCaptions"===this._impl.kind?$E.TeamsCaptions:$E.Captions}get captions(){return this._impl.captions}on(g,f){this.eventEmitter.on(g,f)}off(g,f){this.eventEmitter.off(g,f)}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:this._captionsTelemetryType,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}}class CaptionsCommonImpl{constructor(g,f){this._eventEmitter=f,this._impl=g}async startCaptions(g){await this._impl.startCaptions(g)}async stopCaptions(){await this._impl.stopCaptions()}async setSpokenLanguage(g){await this._impl.setSpokenLanguage(g)}get supportedSpokenLanguages(){return this._impl.supportedSpokenLanguages}get isCaptionsFeatureActive(){return this._impl.isCaptionsFeatureActive}get activeSpokenLanguage(){return this._impl.activeSpokenLanguage}get kind(){return this._impl.kind}}class CaptionsImpl extends CaptionsCommonImpl{constructor(g,f){super(g,f)}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}}class TeamsCaptionsImpl extends CaptionsCommonImpl{constructor(g,f){super(g,f)}get supportedCaptionLanguages(){return this._impl.supportedCaptionLanguages}get activeCaptionLanguage(){return this._impl.activeCaptionLanguage}async setCaptionLanguage(g){await this._impl.setCaptionLanguage(g)}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}}class CaptionsCallFeatureImplOverTsCall extends BaseLanguageCallFeatureImplOverTsCall{constructor(g,f,S,v){super(g),this._botParticipantId="",this._isEnterpriseUser=!1,this._isCaptionsActive=!1,this._firstTimeActive=!1,this._ecsCaptionsEnabled=!1,this._ecsACSCaptionsEnabled=!1,this._ecsTeamsCaptionsEnabled=!1,this._ecsSpokenLanguagesEnabled=!1,this._ecsSpokenLanguages=[],this._ecsCaptionLanguagesEnabled=!1,this._ecsCaptionLanguages=[],this._ecsAmtPolicyUrlSuffix="",this._ecsCapabilitiesEnabled=!0,this._ecsSetBotMetadataWhenEmptyFixEnabled=!0,this._hasReportedCaptionParseFailure=!1,this._hasReceivedFirstCaption=!1,this._currentLanguage="",this._currentCaptionLanguage="",this._participantSequenceIdMap={},this.capabilityChangeHandler=g=>{g.newValue.startLiveMeetingCaptions&&(this._participantCapability.startLiveMeetingCaptions=this._call.getParticipantCapabilities().startLiveMeetingCaptions,this._logger.log(`participant capabilitity to startLiveMeetingCaptions feature is ${this._participantCapability}`)),g.newValue.startLiveCallingCaptions&&(this._participantCapability.startLiveCallingCaptions=this._call.getParticipantCapabilities().startLiveCallingCaptions,this._logger.log(`participant capabilitity to startLiveCallingCaptions feature is ${this._participantCapability}`)),g.newValue.setCaptionLanguage&&(this._participantCapability.setCaptionLanguage=this._call.getParticipantCapabilities().setCaptionLanguage,this._logger.log(`participant capabilitity to setCaptionLanguage feature is ${this._participantCapability}`))},this._addParticipantPromise=null,this._dataChannelHandler={onStarted:async(g,f)=>{},onStopped:async g=>{},onDataReceived:async(g,f,S)=>{let v;try{v=JSON.parse(f.toString())}catch(g){try{if(void 0===this._textDecoder)throw new Error("TextDecoder undefined.");v=JSON.parse(this._textDecoder.decode(f))}catch(g){return this._logger.error("Failed to parse Captions result",g),void(this._hasReportedCaptionParseFailure||(this._hasReportedCaptionParseFailure=!0,this._sendCaptionsEvent(SE.FirstCaptionParsingError,gE.failure,"",0,fE.Unexpected,"Could not decode data packet.")))}}if(v){let g=[];v.textTracks&&this._isCaptionInTextTracks(v)?g=v.textTracks:v.recognitionResults&&(g=v.recognitionResults),g.forEach((g=>{try{if("mt"!==g.source.toLowerCase()&&"ai"!==g.source.toLowerCase())return;const[f,v]=g.id.split("/");let C=parseInt(v,10);if(this._participantSequenceIdMap[g.userId]&&this._botParticipantId==f&&this._participantSequenceIdMap[g.userId]>C)return;this._botParticipantId=f,this._participantSequenceIdMap[g.userId]=C;const _=this._tsCall.participants.find((f=>f.id===g.userId))?.displayName||(this._internalCallAgent.getUserMri()===g.userId?this._internalCallAgent?.displayName:void 0),T={resultType:g.isFinal?"Final":"Partial",captionText:g.text,spokenText:g.originalText??g.text,timestamp:new Date(new Date(g.timestampAudioSent/1e4).getTime()+zE),speaker:{identifier:constructIdentifierKindFromMri(g.userId),displayName:_},spokenLanguage:g.spokenLanguage,captionLanguage:g.trackLanguage};if(this._currentLanguage!=g.spokenLanguage&&(this._currentLanguage=g.spokenLanguage,this._eventEmitter.emit("SpokenLanguageChanged")),!this.isCaptionsFeatureActive||this._mediaStreamSourceId!==S)return;this._hasReceivedFirstCaption||(this._hasReceivedFirstCaption=!0,this._sendCaptionsEvent(SE.FirstCaptionReceived,gE.success,"",0)),this._eventEmitter.emit("CaptionsReceived",T)}catch(g){this._logger.error("Failed to parse Captions result",g),this._hasReportedCaptionParseFailure||(this._hasReportedCaptionParseFailure=!0,this._sendCaptionsEvent(SE.FirstCaptionParsingError,gE.failure,"",0,fE.Unexpected,"Error thrown during incoming caption result mapping."))}}))}}},this._isCaptionInTextTracks=g=>{let f=!1;return g.textTracks&&g.textTracks.forEach((g=>{"Mt"===g.source&&(f=!0)})),f},this._handleBotRemoved=g=>{this._acsMetadata&&this._isCaptionsBot(g)&&(this.isCaptionsFeatureActive&&(this._isCaptionsActive=!1,this._eventEmitter.emit("CaptionsActiveChanged")),this._acsMetadata=void 0,this._firstTimeActive=!1)},this._participantCapability={startLiveMeetingCaptions:{isPresent:!0,reason:"Capable"},startLiveCallingCaptions:{isPresent:!0,reason:"Capable"},setCaptionLanguage:{isPresent:!0,reason:"Capable"}},this._telemetryStartTime=Date.now()}get isCaptionsFeatureActive(){return!!this._acsMetadata&&this._isCaptionsEnabled(this._acsMetadata)&&this._isCaptionsActive}get supportedSpokenLanguages(){return this._ecsSpokenLanguages}get supportedCaptionLanguages(){return this._ecsCaptionLanguages}get captions(){return this._captions}get kind(){return this._name===$E.TeamsCaptions?"TeamsCaptions":"Captions"}get activeSpokenLanguage(){return this._currentLanguage}get activeCaptionLanguage(){return this._currentCaptionLanguage}get isTeamsConversationType(){return Pf.indexOf(this._tsCall.conversationType)>-1}get isTeamsUserInCall(){for(let g of this._tsCall.participants)if("microsoftTeamsUser"===constructIdentifierKindFromMri(g.id).kind)return!0;return!1}get isTeamsCallKind(){return this._call.kind===g.CallKind.TeamsCall}get isTeamsCaptionsBotInCall(){for(let g of this._tsCall.participants){if("gcc"===this._tsCall.region&&g.id===getAcsEcsConfig().captions.teams.gccBotMri)return!0;if("gcc"!==this._tsCall.region&&(g.id===getAcsEcsConfig().captions.teams.botMri||g.id===getAcsEcsConfig().captions.teams.legacyBotMri))return!0}return!1}async updateParticipantTranscriptionPrefsMetadata(g,f){let S;for(let g in this._tsCall.endpoints?.endpointDetails)if(this._tsCall.endpoints?.endpointDetails[g].participantId===this._tsCall.participantId){S=this._tsCall.endpoints?.endpointDetails[g];break}const v=S?.endpointMetadata??{transcriptionPrefs:{}};g?v.transcriptionPrefs?.closedCaptions?v.transcriptionPrefs.closedCaptions=g:v.transcriptionPrefs={closedCaptions:g}:v.transcriptionPrefs?.closedCaptions&&delete v.transcriptionPrefs.closedCaptions;try{await this._tsCall.updateEndpointMetadata(JSON.stringify(v))}catch(g){this._addParticipantPromise=null;const S=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.UPDATE_ENDPOINT_METADATA});throw this._sendCaptionsEvent(SE.UpdateEndpointMetadata,gE.failure,f,this._telemetryStartTime,fE.Unexpected,S.message,S.code,S.subCode,extractCommunicationServicesErrorForTelemetry(S)),this._sendFeatureUsage("updateEndpointMetadata",gE.failure),this._logger.warn(S.message),S}}initialize(g,f,S,v,C,_,T,I){this._logger=_.createChild((()=>`CaptionsFeature::Call(id='${g.callId}', state='${g.state}')`)),this._tsCall=g,this._call=f,this._internalCallAgent=S,this._httpRequestHelper=v,this._telemetryLogManager=C,this._telemetryStartTime=T,this._isEnterpriseUser=S.isEnterpriseUser(),this._ecsCaptionsEnabled=getAcsEcsConfig().captions.enabled,this._ecsACSCaptionsEnabled=getAcsEcsConfig().captions.acs.enabled,this._ecsTeamsCaptionsEnabled=getAcsEcsConfig().captions.teams.enabled,this._ecsSetBotMetadataWhenEmptyFixEnabled=getAcsEcsConfig().captions.setBotMetadataWhenEmptyFix,this._name=this.isTeamsConversationType||this._isEnterpriseUser||this.isTeamsUserInCall||this.isTeamsCaptionsBotInCall||this.isTeamsCallKind?$E.TeamsCaptions:$E.Captions,this.updateCaptionsData(this._name),this._sendCaptionsEvent(SE.InitializeCaptions,gE.initialize,I,this._telemetryStartTime),this._initializationPromise=new Promise(((g,f)=>{this._initializeAsync(I).then((f=>g())).catch((g=>f(g)))}))}async _initializeAsync(g){try{this._textDecoder=new TextDecoder,this._tsCall.on("callStateChanged",(()=>{3===this._tsCall.state&&this._name===$E.TeamsCaptions&&"gcc"===this._tsCall.region&&(this._captionsBotMri=getAcsEcsConfig().captions.teams.gccBotMri)})),this._tsCall.on("participantAdded",(async f=>{if(this._captions&&"Captions"===this._captions.kind&&"microsoftTeamsUser"===constructIdentifierKindFromMri(f.id).kind){if(this._captionsBotMri)try{await this._tsCall.removeParticipant(this._captionsBotMri),this._acsMetadata&&(this._acsMetadata=void 0)}catch(S){const v=new CallingCommunicationError({defaultError:{message:convertParticipantStateReasonToString(S),code:f.callEndDiagnosticsInfo?.callControllerCode||0,subCode:f.callEndDiagnosticsInfo?.callControllerSubCode||0,resultCategories:f.callEndDiagnosticsInfo?.resultCategories||["UnexpectedClientError"]},originalError:S});this._sendCaptionsEvent(SE.CaptionsKindChanged,gE.failure,g,this._telemetryStartTime,fE.Unexpected,v.message,v.code,v.subCode,extractCommunicationServicesErrorForTelemetry(v))}if(this.updateCaptionsData($E.TeamsCaptions),this._ecsSetBotMetadataWhenEmptyFixEnabled){const f=this._tsCall.participants.find((g=>g.id===this._captionsBotMri));if(f){this._acsMetadata=this._copyBotMetaData(f),this._mediaStreamSourceId=f.getSourceIdForMediaType(3);try{await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._dataChannelId,this._dataChannelHandler)}catch(f){const S=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(SE.StartDataChannel,gE.failure,g,this._telemetryStartTime,fE.Expected,S.message,S.code,S.subCode,extractCommunicationServicesErrorForTelemetry(S)),this._sendFeatureUsage("startDataChannel",gE.failure)}}}this._isCaptionsActive&&(this._currentLanguage&&this._ecsSpokenLanguages.includes(this._currentLanguage)?await this._captions.startCaptions({spokenLanguage:this._currentLanguage}):await this._captions.startCaptions()),this._eventEmitter.emit("CaptionsKindChanged"),this._sendCaptionsEvent(SE.CaptionsKindChanged,gE.success,g,this._telemetryStartTime)}})),this._tsCall.on("participantAdded",(async g=>{this._isCaptionsBot(g)&&(this._acsMetadata||(this._acsMetadata=this._copyBotMetaData(g),this._mediaStreamSourceId=this._getBotDataMediaStreamSourceId(g),await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._dataChannelId,this._dataChannelHandler)))})),this._tsCall.on("participantRemoved",(async g=>{this._isCaptionsBot(g)&&this._handleBotRemoved(g)})),this._tsCall.on("participantUpdated",(async g=>{this._getBotMetadata(g)&&this._isCaptionsBot(g)&&this._acsMetadata&&(this._acsMetadata=this._copyBotMetaData(g),this._mediaStreamSourceId=this._getBotDataMediaStreamSourceId(g),!this._firstTimeActive&&this.isCaptionsFeatureActive&&(this._firstTimeActive=!0,this._eventEmitter.emit("CaptionsActiveChanged")))}));const f=this._tsCall.participants.find((g=>g.id===this._captionsBotMri||g.id===this._captionsLegacyBotMri));f&&(this._acsMetadata=this._copyBotMetaData(f),this._mediaStreamSourceId=f.getSourceIdForMediaType(3),await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._dataChannelId,this._dataChannelHandler))}catch(f){const S=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.INITIALIZE});throw this._sendCaptionsEvent(SE.InitializeCaptions,gE.failure,g,this._telemetryStartTime,fE.Unexpected,S.message,S.code,S.subCode,extractCommunicationServicesErrorForTelemetry(S)),this._logger.error(S.message),S}}updateCaptionsData(g){g===$E.Captions?(this._name=$E.Captions,this._captionsBotMri=getAcsEcsConfig().captions.acs.botMri,this._captionsLegacyBotMri=void 0,this._modeKey=getAcsEcsConfig().captions.acs.modeKey,this._modeVal=getAcsEcsConfig().captions.acs.modeVal,this._modesKey=getAcsEcsConfig().captions.acs.modesKey,this._modesVal=getAcsEcsConfig().captions.acs.modesVal,this._clientInfo=getAcsEcsConfig().captions.acs.clientInfo.ring,this._ecsACSCaptionsEnabled=getAcsEcsConfig().captions.acs.enabled,this._ecsSpokenLanguagesEnabled=getAcsEcsConfig().captions.acs.spokenLanguages.enabled,this._ecsSpokenLanguages=getAcsEcsConfig().captions.acs.spokenLanguages.languages,this._ecsCapabilitiesEnabled=getAcsEcsConfig().captions.useCapabilities,this._ecsSetBotMetadataWhenEmptyFixEnabled=getAcsEcsConfig().captions.setBotMetadataWhenEmptyFix,this._call.offParticipantCapabilitiesChanged("capabilitiesChanged",this.capabilityChangeHandler),this._logger.log("participant capabilities change event listener unregistered"),this._captions=new CaptionsImpl(this,this._eventEmitter)):g===$E.TeamsCaptions&&(this._name=$E.TeamsCaptions,"gcc"===this._tsCall.region?this._captionsBotMri=getAcsEcsConfig().captions.teams.gccBotMri:this._captionsBotMri=getAcsEcsConfig().captions.teams.botMri,this._captionsLegacyBotMri=getAcsEcsConfig().captions.teams.legacyBotMri,this._modeKey=getAcsEcsConfig().captions.teams.modeKey,this._modeVal=getAcsEcsConfig().captions.teams.modeVal,this._modesKey=getAcsEcsConfig().captions.teams.modesKey,this._modesVal=getAcsEcsConfig().captions.teams.modesVal,this._clientInfo=getAcsEcsConfig().captions.teams.clientInfo.ring,this._ecsTeamsCaptionsEnabled=getAcsEcsConfig().captions.teams.enabled,this._ecsSpokenLanguagesEnabled=getAcsEcsConfig().captions.teams.spokenLanguages.enabled,this._ecsSpokenLanguages=getAcsEcsConfig().captions.teams.spokenLanguages.languages,this._ecsCaptionLanguagesEnabled=getAcsEcsConfig().captions.teams.captionLanguages.enabled,this._ecsCaptionLanguages=getAcsEcsConfig().captions.teams.captionLanguages.languages,this._ecsAmtPolicyUrlSuffix=getAcsEcsConfig().MiddleTier.policyUrlSuffixV2,this._ecsCapabilitiesEnabled=getAcsEcsConfig().captions.useCapabilities,this._ecsSetBotMetadataWhenEmptyFixEnabled=getAcsEcsConfig().captions.setBotMetadataWhenEmptyFix,this._participantCapability.startLiveMeetingCaptions=this._call.getParticipantCapabilities().startLiveMeetingCaptions,this._logger.log(`participant capabilitity to startLiveMeetingCaptions feature is ${this._participantCapability.startLiveMeetingCaptions}`),this._participantCapability.startLiveCallingCaptions=this._call.getParticipantCapabilities().startLiveCallingCaptions,this._logger.log(`participant capabilitity to startLiveCallingCaptions feature is ${this._participantCapability.startLiveCallingCaptions}`),this._participantCapability.setCaptionLanguage=this._call.getParticipantCapabilities().setCaptionLanguage,this._logger.log(`participant capabilitity to setCaptionLanguage feature is ${this._participantCapability.setCaptionLanguage}`),this._call.onParticipantCapabilitiesChanged("capabilitiesChanged",this.capabilityChangeHandler),this._logger.log("participant capabilities change event listener registered"),this._captions=new TeamsCaptionsImpl(this,this._eventEmitter))}async startCaptions(g){this._telemetryStartTime=+Date.now();const f=generateGuid(),S=g?.spokenLanguage||vf;if(this._sendFeatureUsage("startCaptions",gE.attempt),this._sendCaptionsEvent(SE.StartCaptions,gE.attempt,f,0),this._addParticipantPromise){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.ALREADY_STARTING});return this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),void this._sendFeatureUsage("startCaptions",gE.failure)}if(await this._initializationPromise,!this._ecsCaptionsEnabled){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.DISABLED});return this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),void this._logger.error("Feature is not enabled.")}if(3!==this._tsCall.state){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.START_FAILED_CALL_NOT_CONNECTED});return this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),void this._logger.error("Captions unable to start as call state is not connected.")}if(!this._tsCall.endpoints){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.START_FAILED_CALL_ENDPOINTS_NOT_AVAILABLE});return this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),void this._logger.error("Captions unable to start as call endpoints are not available.")}if(!this._ecsSpokenLanguages.includes(S)){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.SPOKEN_LANG_UNSUPPORTED});throw this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setSpokenLanguage",gE.failure),this._logger.error("Spoken language requested is not supported."),g}if(this._name===$E.Captions&&!this._ecsACSCaptionsEnabled){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.DISABLED});return this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),void this._logger.error("Captions Feature is not enabled.")}if(this._name===$E.TeamsCaptions){if("gcc"===this._tsCall.region&&(this._captionsBotMri=getAcsEcsConfig().captions.teams.gccBotMri),!this._ecsTeamsCaptionsEnabled){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.DISABLED});return this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),void this._logger.error("Teams Captinons Feature is not enabled.")}if(this._ecsCapabilitiesEnabled){if(this._isEnterpriseUser)if(this._call.callInfo.context===jS.TeamsMeeting||this.isTeamsConversationType){if(this._participantCapability)if(this.isTeamsConversationType){if(!this._participantCapability?.startLiveMeetingCaptions.isPresent){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.MEETING_POLICY_DISABLED});throw this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),this._logger.error(g.message),g}}else if(!this._participantCapability?.startLiveCallingCaptions.isPresent){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CALLING_POLICY_DISABLED});throw this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),this._logger.error(g.message),g}}else{const g=this._internalCallAgent.getUserPolicy();if("DisabledUserOverride"!==g?.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CALLING_POLICY_DISABLED});throw this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),this._logger.error(g.message),g}}}else if(this._mtPolicy=this._internalCallAgent.mtPolicyService,this._isEnterpriseUser){try{this._mtPolicy.initialize({localParticipant:this._internalCallAgent.getUserMri(),jwtTokenProvider:await this._internalCallAgent.tokenProvider,telemetryLogManager:this._telemetryLogManager}),await this._mtPolicy.fetchUserPoliciesFromAcsMiddleTier(this._tsCall.callId,this._call.callAgent.getUserMri(),{policyUrlSuffix:this._ecsAmtPolicyUrlSuffix,userPolicies:["TeamsCallingPolicy","TeamsMeetingPolicy"],userProperties:["FeatureTypes","PoliciesMetadata"]}),this._mtCaptionsPolicyResult=JSON.parse(this._mtPolicy.getTeamsUserCaptionsPoliciesData())}catch(g){const S=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CTE_POLICY_FETCH_FAIL,originalError:g});this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Unexpected,S.message,S.code,S.subCode,extractCommunicationServicesErrorForTelemetry(S)),this._logger.error("Unable to fetch policies")}if(this._mtCaptionsPolicyResult)if(this.isTeamsConversationType){if(!this._mtCaptionsPolicyResult?.isLiveCaptionsEnabledForMeeting){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.MEETING_POLICY_DISABLED});throw this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),this._logger.error(g.message),g}}else if(!this._mtCaptionsPolicyResult?.isLiveCaptionsEnabledForCalling){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CALLING_POLICY_DISABLED});throw this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure),this._logger.error(g.message),g}}}if(this._ecsSetBotMetadataWhenEmptyFixEnabled){const g=this._tsCall.participants.find((g=>g.id===this._captionsBotMri||g.id===this._captionsLegacyBotMri));if(g&&!this._acsMetadata){this._acsMetadata=this._copyBotMetaData(g),this._mediaStreamSourceId=g.getSourceIdForMediaType(3);try{await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._dataChannelId,this._dataChannelHandler)}catch(g){const S=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(SE.StartDataChannel,gE.failure,f,this._telemetryStartTime,fE.Expected,S.message,S.code,S.subCode,extractCommunicationServicesErrorForTelemetry(S)),this._sendFeatureUsage("startDataChannel",gE.failure)}}}if(this._acsMetadata){if(this._isCaptionsEnabled(this._acsMetadata))if(this._isCaptionsActive){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure)}else this._isCaptionsActive=!0,"Captions"===this._captions.kind&&await this.updateParticipantTranscriptionPrefsMetadata(!0,f),this._sendCaptionsEvent(SE.StartCaptions,gE.success,f,this._telemetryStartTime),this._sendFeatureUsage("startCaptions",gE.success),this._eventEmitter.emit("CaptionsActiveChanged");else if("Captions"===this._captions.kind)if(this._isCaptionsActive){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("startCaptions",gE.failure)}else this._isCaptionsActive=!0,await this.updateParticipantTranscriptionPrefsMetadata(!0,f),this._sendCaptionsEvent(SE.StartCaptions,gE.success,f,this._telemetryStartTime),this._sendFeatureUsage("startCaptions",gE.success),this._eventEmitter.emit("CaptionsActiveChanged")}else try{const g={participantInvitationData:{botData:{clientInfo:this._clientInfo,consumerType:"ACS",initiatorUserToken:this._name===$E.TeamsCaptions?"":await this._internalCallAgent.tokenProvider(),spokenLanguage:S,[this._modeKey]:this._modeVal,[this._modesKey]:this._modesVal}}};"Captions"===this._captions.kind&&await this.updateParticipantTranscriptionPrefsMetadata(!0,f),this._addParticipantPromise=this._tsCall.addParticipant(this._captionsBotMri,g),await this._addParticipantPromise,this._addParticipantPromise=null,this._currentLanguage!==S&&(this._currentLanguage=S,this._eventEmitter.emit("SpokenLanguageChanged")),this._isCaptionsActive=!0,this._sendCaptionsEvent(SE.StartCaptions,gE.success,f,this._telemetryStartTime),this._sendFeatureUsage("startCaptions",gE.success)}catch(g){this._addParticipantPromise=null;const S=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.START_FAILED});throw this._sendCaptionsEvent(SE.StartCaptions,gE.failure,f,this._telemetryStartTime,fE.Unexpected,S.message,S.code,S.subCode,extractCommunicationServicesErrorForTelemetry(S)),this._sendFeatureUsage("startCaptions",gE.failure),this._logger.error(S.message),S}}async stopCaptions(){this._telemetryStartTime=+Date.now();const g=generateGuid();if(this._sendFeatureUsage("stopCaptions",gE.attempt),this._sendCaptionsEvent(SE.StopCaptions,gE.attempt,g,0),this.isCaptionsFeatureActive)"Captions"===this._captions.kind&&await this.updateParticipantTranscriptionPrefsMetadata(!1,g),this._isCaptionsActive=!1,this._sendCaptionsEvent(SE.StopCaptions,gE.success,g,this._telemetryStartTime),this._sendFeatureUsage("stopCaptions",gE.success),this._eventEmitter.emit("CaptionsActiveChanged");else{const f=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.STOP_NOT_ACTIVE});this._sendCaptionsEvent(SE.StopCaptions,gE.failure,g,this._telemetryStartTime,fE.Expected,f.message,f.code,f.subCode,extractCommunicationServicesErrorForTelemetry(f)),this._logger.warn(f.message)}this._isCaptionsActive=!1}async setSpokenLanguage(g){this._telemetryStartTime=+Date.now();const f=generateGuid();if(this._sendFeatureUsage("setSpokenLanguage",gE.attempt),this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.attempt,f,0),await this._initializationPromise,!this._acsMetadata?.commandUrl){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.UPDATE_LANGUAGE_NOT_STARTED});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setSpokenLanguage",gE.failure),this._logger.error(g.message),g}if(!this._isCaptionsActive){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.UPDATE_LANGUAGE_NOT_STARTED});return this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setSpokenLanguage",gE.failure),void this._logger.warn(g.message)}if(!this._ecsSpokenLanguagesEnabled){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.SPOKEN_LANG_DISABLED});return this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setSpokenLanguage",gE.failure),void this._logger.error(g.message)}if(g==this._currentLanguage){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.SPOKEN_LANGUAGE_ALREADY_SET});return this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),void this._sendFeatureUsage("setSpokenLanguage",gE.failure)}if(!this._ecsSpokenLanguages.includes(g)){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.SPOKEN_LANG_UNSUPPORTED});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setSpokenLanguage",gE.failure),this._logger.error(g.message),g}try{const S=await this._internalCallAgent.tokenProvider();if(!S){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.UPDATE_LANGUAGE_GET_TOKEN});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Unexpected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),g}await this._sendSetLanguageRequest(g,"",S,this._acsMetadata.commandUrl),this._currentLanguage!==g&&(this._currentLanguage=g,this._eventEmitter.emit("SpokenLanguageChanged")),this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.success,f,this._telemetryStartTime),this._sendFeatureUsage("setSpokenLanguage",gE.success)}catch(g){const S=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.UPDATE_LANGUAGE_FAILED,originalError:g});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Unexpected,S.message,S.code,S.subCode,extractCommunicationServicesErrorForTelemetry(S)),this._sendFeatureUsage("setSpokenLanguage",gE.failure),this._logger.error(S.message),S}}async setCaptionLanguage(g){this._telemetryStartTime=+Date.now();const f=generateGuid();if(this._sendFeatureUsage("setCaptionLanguage",gE.attempt),this._sendCaptionsEvent(SE.SetCaptionLanguage,gE.attempt,f,0),await this._initializationPromise,!this._acsMetadata?.commandUrl){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.UPDATE_CAPTIONS_NOT_STARTED});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setCaptionLanguage",gE.failure),this._logger.error(g.message),g}if(!this._isCaptionsActive){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.UPDATE_CAPTIONS_NOT_ACTIVE});return this._sendCaptionsEvent(SE.SetCaptionLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setCaptionLanguage",gE.failure),void this._logger.warn(g.message)}if(!this._ecsCaptionLanguagesEnabled){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CAPTIONS_LANG_DISABLED});return this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setCaptionLanguage",gE.failure),void this._logger.error(g.message)}if(this._isTranslatedCaptionsAllowed||this._tsCall.meetingDetails?.meetingCapability&&this._tsCall.meetingDetails.meetingCapability.allowTranslatedCaptions&&(this._isTranslatedCaptionsAllowed=this._tsCall.meetingDetails.meetingCapability.allowTranslatedCaptions),!this.isTeamsConversationType||!this._isTranslatedCaptionsAllowed)if(this._ecsCapabilitiesEnabled){if(this._call.callInfo.context!==jS.TeamsMeeting){const g=this._internalCallAgent.getUserProperties();if(!g?.featureTypes?.includes(SS.TeamsProMgmt)){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CAPTIONS_LANG_TEAMS_LICENSE});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setCaptionLanguage",gE.failure),this._logger.error(g.message),g}}else if(!this._participantCapability?.setCaptionLanguage.isPresent){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CAPTIONS_LANG_TEAMS_LICENSE});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setCaptionLanguage",gE.failure),this._logger.error(g.message),g}}else if(!this._mtCaptionsPolicyResult?.isTeamsProMgmtSkuAvailable){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CAPTIONS_LANG_TEAMS_LICENSE});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setCaptionLanguage",gE.failure),this._logger.error(g.message),g}if(g==this._currentCaptionLanguage){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CAPTIONS_LANG_ALREADY_SET});return this._sendCaptionsEvent(SE.SetCaptionLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),void this._sendFeatureUsage("setCaptionLanguage",gE.failure)}if(!this._ecsCaptionLanguages.includes(g)){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.CAPTIONS_LANG_UNSUPPORTED});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Expected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),this._sendFeatureUsage("setCaptionLanguage",gE.failure),this._logger.error(g.message),g}try{const S=await this._internalCallAgent.tokenProvider();if(!S){const g=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.UPDATE_CAPTIONS_GET_TOKEN});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Unexpected,g.message,g.code,g.subCode,extractCommunicationServicesErrorForTelemetry(g)),g}await this._sendSetLanguageRequest("",g,S,this._acsMetadata.commandUrl),this._currentCaptionLanguage!==g&&(this._currentCaptionLanguage=g,this._eventEmitter.emit("CaptionLanguageChanged")),this._sendCaptionsEvent(SE.SetCaptionLanguage,gE.success,f,this._telemetryStartTime),this._sendFeatureUsage("setCaptionLanguage",gE.success)}catch(g){const S=new CallingCommunicationError({defaultError:D.FEATURES.CAPTIONS.UPDATE_CAPTIONS_FAILED,originalError:g});throw this._sendCaptionsEvent(SE.SetSpokenLanguage,gE.failure,f,this._telemetryStartTime,fE.Unexpected,S.message,S.code,S.subCode,extractCommunicationServicesErrorForTelemetry(S)),this._sendFeatureUsage("setCaptionLanguage",gE.failure),this._logger.error(S.message),S}}dispose(){this._acsMetadata=void 0,this._textDecoder=void 0}_sendCaptionsEvent(g,f,S,v,C,_,T,I,b){let A={eventName:uE.acs_calling_captions,callId:this._call.id,correlationId:S,isExpected:C??"",localParticipantId:this._call.tsCall.participantId,featureType:this._name,featureDetails:{step:g},kindOfEvent:f,timestampInfo:v?{deltaTimeInMs:+Date.now()-v}:"",additionalDetails:{failureReason:_,code:T,subCode:I,...b}};try{this._telemetryLogManager.sendEvent({name:uE.acs_calling_captions,tenant:tf,properties:A})}catch(g){this._logger.debug(`Unable to send ${this._name} feature usage telemtery`)}}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this._name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}async _sendSetLanguageRequest(g,f,S,v){const C=g?{type:yf,spokenLanguage:g}:{type:yf,subtitleLanguages:[f]},_={timestamp:(new Date).toISOString(),participantMri:this._internalCallAgent.getUserMri(),participantLegId:this._tsCall.participantId,action:yf,mode:_f,actionParameters:C},T={headers:{"X-Microsoft-Skype-Chain-ID":this._tsCall.callId,Authorization:`Bearer ${S}`,"x-skypetoken":S},withCredentials:!0};return this._httpRequestHelper.sendRequestWithRetry("post",v,_,T,KE)}}__decorate([asyncOperation(VE.StartCaptions),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],CaptionsCallFeatureImplOverTsCall.prototype,"startCaptions",null),__decorate([asyncOperation(VE.StopCaptions),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",Promise)],CaptionsCallFeatureImplOverTsCall.prototype,"stopCaptions",null),__decorate([asyncOperation(VE.SetSpokenLanguage),__metadata("design:type",Function),__metadata("design:paramtypes",[String]),__metadata("design:returntype",Promise)],CaptionsCallFeatureImplOverTsCall.prototype,"setSpokenLanguage",null),__decorate([asyncOperation(VE.SetCaptionLanguage),__metadata("design:type",Function),__metadata("design:paramtypes",[String]),__metadata("design:returntype",Promise)],CaptionsCallFeatureImplOverTsCall.prototype,"setCaptionLanguage",null);class RaiseHandCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new RaiseHandCallImplOverTsCall(this.eventEmitter),this._callInfo=g.callInfo}get name(){return"RaiseHand"}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._tsCall=g.tsCall,this._impl.initialize(g.tsCall,g.callAgent,g.telemetryLogManager,f,this._callInfo)}async raiseHand(){return this._impl.raiseHand()}async lowerHand(){return this._impl.lowerHand()}async lowerHands(g){return this._impl.lowerHands(g)}lowerAllHands(){return this._impl.lowerAllHands()}getRaisedHands(){return this._sendFeatureUsage("getRaisedHands",gE.getter),this._impl.raisedHands}on(g,f){this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){this._sendFeatureUsage(g,gE.unsubscribe),this.eventEmitter.off(g,f)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"RaiseHand",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}class RaiseHandCallImplOverTsCall{constructor(g){this.typeRankComparator=(g,f)=>void 0===g.publishedState?-1:void 0===f.publishedState?1:g.publishedState.typeRank-f.publishedState.typeRank,this._eventEmitter=g,this._currentRaiseHandStates=new Map}initialize(g,f,S,v,C){this._logger=v.createChild((()=>`RaiseHandFeature::Call(id='${g.callId}')`)),this._tsCall=g,this._callInfo=C,this._telemetryLogManager=S,this._internalCallAgent=f,this._sendFeatureUsage("initialize",gE.initialize);try{let extractMRIs=g=>new Map(this.getPublishedState(g).sort(this.typeRankComparator).map((g=>[g.id,g])));this._tsCall.on("publishedStatesChanged",(async g=>{let f=extractMRIs(g),S=this._currentRaiseHandStates;this._currentRaiseHandStates=f,this._currentRaiseHandStates.forEach(((g,f)=>{S.has(f)||this._eventEmitter.emit("raisedHandEvent",{identifier:constructIdentifierKindFromMri(f)})})),S.forEach(((g,f)=>{this._currentRaiseHandStates.has(f)||this._eventEmitter.emit("loweredHandEvent",{identifier:constructIdentifierKindFromMri(f)})}))})),this._tsCall.publishedStates&&(this._currentRaiseHandStates=extractMRIs(this._tsCall.publishedStates)),this._sendFeatureUsage("initialize",gE.success)}catch(g){throw this._logger.error("Could not initialize raise hand feature.",g),this._sendFeatureUsage("initialize",gE.failure),new CallingCommunicationError({defaultError:D.FEATURES.RAISE_HAND.INITIALIZE,originalError:g})}}async raiseHand(){if(this._sendFeatureUsage("raiseHand",gE.attempt),this._callInfo.context===jS.TwoParty)throw this._logger.warn("Raise hand not supported for 1:1 calls"),this._sendFeatureUsage("raiseHand",gE.failure),new CallingCommunicationError({defaultError:D.FEATURES.RAISE_HAND.NOT_SUPPORTED_1TO1});try{if(void 0!==this.getLocalRaiseHandState())return void this._sendFeatureUsage("raiseHand",gE.failure);const g={level:"user",type:"raiseHands",content:"{}"};if(!await this._tsCall.publishState(g,w.generateCauseId()))throw new CallingCommunicationError({defaultError:D.FEATURES.RAISE_HAND.RAISE_HAND_PUBLISH_STATE});this._sendFeatureUsage("raiseHand",gE.success)}catch(g){throw this._logger.error("Could not change a participant state. Code: ",g?.response?.status),this._sendFeatureUsage("raiseHand",gE.failure),handlePublishStateFailure(g,D.FEATURES.RAISE_HAND.RAISE_HAND_FAIL)}}async lowerHand(){this._sendFeatureUsage("lowerHand",gE.attempt);try{const g=this.getLocalRaiseHandState();if(void 0===g)return void this._sendFeatureUsage("lowerHand",gE.failure);const f={stateIds:[g]};await this._tsCall.removeState(f,w.generateCauseId()),this._sendFeatureUsage("lowerHand",gE.success)}catch(g){throw this._logger.error("Could not change a participant state. Code: ",g?.response?.status),this._sendFeatureUsage("lowerHand",gE.failure),handlePublishStateFailure(g,D.FEATURES.RAISE_HAND.LOWER_HAND_FAIL)}}async lowerHands(g){this._sendFeatureUsage("lowerHands",gE.attempt);try{if(0===g.length)return void this._sendFeatureUsage("lowerHands",gE.failure);if(0===this._currentRaiseHandStates.size)return void this._sendFeatureUsage("lowerHands",gE.failure);const f=g.map((g=>getMriFromIdentifier(g))),S=this.findStateIdsForParticipantIds(f);await this._tsCall.removeState({stateIds:S},w.generateCauseId()),this._sendFeatureUsage("lowerHands",gE.success)}catch(g){throw this._logger.error("Could not change a participant state.",g),this._sendFeatureUsage("lowerHands",gE.failure),handlePublishStateFailure(g,D.FEATURES.RAISE_HAND.LOWER_REMOTEPARTICIPANTS_HANDS_FAIL)}}async lowerAllHands(){this._sendFeatureUsage("lowerAllHands",gE.attempt);try{await this._tsCall.removeStatesForEveryone({type:"raiseHands"},w.generateCauseId()),this._sendFeatureUsage("lowerAllHands",gE.success)}catch(g){throw this._logger.error("Could not change a participant state.",g),this._sendFeatureUsage("lowerAllHands",gE.failure),handlePublishStateFailure(g,D.FEATURES.RAISE_HAND.LOWER_ALL_HANDS_FAIL)}}get raisedHands(){return 0===this._currentRaiseHandStates.size?[]:Array.from(this._currentRaiseHandStates.keys()).map(((g,f)=>({identifier:constructIdentifierKindFromMri(g),order:f+1})))}getLocalRaiseHandState(){const g=this.findStateIdsForParticipantIds([this._internalCallAgent.getUserMri()]);if(g&&g.length>0)return g[0]}findStateIdsForParticipantIds(g){return g&&0!==this._currentRaiseHandStates.size?Array.from(this._currentRaiseHandStates.entries()).filter((f=>g.includes(f[0]))).map((g=>g[1]?.publishedState?.stateId)).filter((g=>!!g)):[]}getPublishedState(g){return g.typeStates.filter((g=>"raiseHands"===g.type)).map((g=>g.participantStates)).flat()}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"RaiseHand",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}}var JE;!function(g){g.turnVideoOn="turnVideoOn",g.unmuteMic="unmuteMic",g.shareScreen="shareScreen",g.removeParticipant="removeParticipant",g.hangUpForEveryOne="hangUpForEveryOne",g.addCommunicationUser="addCommunicationUser",g.addTeamsUser="addTeamsUser",g.addPhoneNumber="addPhoneNumber",g.manageLobby="manageLobby",g.spotlightParticipant="spotlightParticipant",g.removeParticipantsSpotlight="removeParticipantsSpotlight",g.blurBackground="blurBackground",g.startLiveMeetingCaptions="startLiveMeetingCaptions",g.startLiveCallingCaptions="startLiveCallingCaptions",g.setCaptionLanguage="setCaptionLanguage",g.raiseHand="raiseHand",g.pstnDialOut="pstnDialOut",g.muteOthers="muteOthers",g.useReactions="useReactions",g.viewAttendeeNames="viewAttendeeNames",g.startTogetherMode="startTogetherMode",g.joinBreakoutRooms="joinBreakoutRooms",g.forbidOthersAudio="forbidOthersAudio",g.forbidOthersVideo="forbidOthersVideo"}(JE||(JE={}));class RoomsCapabilityResolver{constructor(g){this._logger=g,this._ecsConfig=getAcsEcsConfig()}getResolvedCapabilitiesBasedOnRole(g,f){let S={...f},v=g.toLocaleLowerCase();return v!==cS.Attendee.toLocaleLowerCase()&&v!==cS.Presenter.toLocaleLowerCase()&&v!==cS.Consumer.toLocaleLowerCase()&&v!==cS.Organizer.toLocaleLowerCase()||(this._ecsConfig[gS][v][JE.turnVideoOn]?S.turnVideoOn={isPresent:this._ecsConfig[gS][v][JE.turnVideoOn],reason:uS.Capable}:S.turnVideoOn={isPresent:this._ecsConfig[gS][v][JE.turnVideoOn],reason:uS.RoleRestricted},this._ecsConfig[gS][v][JE.unmuteMic]?S.unmuteMic={isPresent:this._ecsConfig[gS][v][JE.unmuteMic],reason:uS.Capable}:S.unmuteMic={isPresent:this._ecsConfig[gS][v][JE.unmuteMic],reason:uS.RoleRestricted},this._ecsConfig[gS][v][JE.shareScreen]?S.shareScreen={isPresent:this._ecsConfig[gS][v][JE.shareScreen],reason:uS.Capable}:S.shareScreen={isPresent:this._ecsConfig[gS][v][JE.shareScreen],reason:uS.RoleRestricted},this._ecsConfig[gS][v][JE.removeParticipant]?S.removeParticipant={isPresent:this._ecsConfig[gS][v][JE.removeParticipant],reason:uS.Capable}:S.removeParticipant={isPresent:this._ecsConfig[gS][v][JE.removeParticipant],reason:uS.RoleRestricted},this._ecsConfig[gS][v][JE.muteOthers]?S.muteOthers={isPresent:this._ecsConfig[gS][v][JE.muteOthers],reason:uS.Capable}:S.muteOthers={isPresent:this._ecsConfig[gS][v][JE.muteOthers],reason:uS.RoleRestricted},this._ecsConfig[gS][v][JE.pstnDialOut]?S.pstnDialOut={isPresent:this._ecsConfig[gS][v][JE.pstnDialOut],reason:uS.Capable}:S.pstnDialOut={isPresent:this._ecsConfig[gS][v][JE.pstnDialOut],reason:uS.RoleRestricted},this._ecsConfig[gS][v][JE.addPhoneNumber]?S.addPhoneNumber={isPresent:this._ecsConfig[gS][v][JE.addPhoneNumber],reason:uS.Capable}:S.addPhoneNumber={isPresent:this._ecsConfig[gS][v][JE.addPhoneNumber],reason:uS.RoleRestricted}),S.removeParticipant={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.hangUpForEveryOne={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.addCommunicationUser={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.addTeamsUser={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.manageLobby={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.spotlightParticipant={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.removeParticipantsSpotlight={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.blurBackground={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.startLiveMeetingCaptions={isPresent:!0,reason:uS.Capable},S.startLiveCallingCaptions={isPresent:!0,reason:uS.Capable},S.setCaptionLanguage={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.raiseHand={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.useReactions={isPresent:!0,reason:uS.Capable},S.viewAttendeeNames={isPresent:!0,reason:uS.Capable},S.startTogetherMode={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.joinBreakoutRooms={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.forbidOthersAudio={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},S.forbidOthersVideo={isPresent:!1,reason:uS.CapabilityNotApplicableForTheCallType},this._logger.log(`Capabilities resolved to : ${JSON.stringify(S)} on role change to ${g}`),S}}const YE="DisableAv",QE="DisableVideo",XE="DisableAudio",ZE="Attendee",e_="attendee";class MediaAccessCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this.getLocalParticipantMediaAccess=()=>this._impl.getLocalParticipantMediaAccess(),this._impl=new MediaAccessCallImplOverTsCall(this.eventEmitter)}get name(){return"MediaAccess"}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._tsCall=g.tsCall,this._impl.initialize(g.tsCall,g.callAgent,g.call,g.telemetryLogManager,f)}getAllOthersMediaAccess(){return this._impl.getAllOthersMediaAccess()}getMeetingMediaAccess(){return this._impl.getMeetingMediaAccess()}async permitAudio(g){return this._impl.permitAudio(g)}async permitOthersAudio(){return this._impl.permitOthersAudio()}async forbidAudio(g){return this._impl.forbidAudio(g)}async forbidOthersAudio(){return this._impl.forbidOthersAudio()}async permitVideo(g){return this._impl.permitVideo(g)}async permitOthersVideo(){return this._impl.permitOthersVideo()}async forbidVideo(g){return this._impl.forbidVideo(g)}async forbidOthersVideo(){return this._impl.forbidOthersVideo()}on(g,f){if(this._sendFeatureUsage(g,gE.subscribe),"mediaAccessChanged"!==g&&"meetingMediaAccessChanged"!==g&&"localParticipantMediaAccessChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}off(g,f){if(this._sendFeatureUsage(g,gE.unsubscribe),"mediaAccessChanged"!==g&&"meetingMediaAccessChanged"!==g&&"localParticipantMediaAccessChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.off(g,f)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"MediaAccess",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}class MediaAccessCallImplOverTsCall{constructor(g){this._ecsTeamsMediaAccessEnabled=!1,this._remoteParticipantsMediaAccess=[],this.getAllOthersMediaAccess=()=>(this._remoteParticipantsMediaAccess=this._tsCall.participants.reduce(((g,f)=>{const S=this._publishedStatesMediaAccessMap.get(f.id),v=f.advancedMeetingRole===e_,C=constructIdentifierKindFromMri(f.id);return S&&v?g.push(S):!S&&v?g.push({participant:C,isAudioPermitted:!this.isMeetingCapabilityAudioRestricted(),isVideoPermitted:!this.isMeetingCapabilityVideoRestricted()}):g.push({participant:C,isAudioPermitted:!0,isVideoPermitted:!0}),g}),[]),this._remoteParticipantsMediaAccess),this.getLocalParticipantMediaAccess=()=>{const g=this._internalCallAgent.getUserMri(),f=this._publishedStatesMediaAccessMap.get(g),S=this._call.role===ZE;if(f&&S)return f;const v=constructIdentifierKindFromMri(g);return!f&&S?{participant:v,isAudioPermitted:!this.isMeetingCapabilityAudioRestricted(),isVideoPermitted:!this.isMeetingCapabilityVideoRestricted()}:{participant:v,isAudioPermitted:!0,isVideoPermitted:!0}},this.isMeetingCapabilityAudioRestricted=()=>[YE,XE].includes(this._tsCall.meetingDetails?.meetingCapability?.attendeeRestrictions),this.isMeetingCapabilityVideoRestricted=()=>[YE,QE].includes(this._tsCall.meetingDetails?.meetingCapability?.attendeeRestrictions),this.getMediaAccessMap=g=>{if(M.isEmpty(g?.typeStates))return new Map;const f=new Map;return g&&this.getPublishedState(g).forEach((g=>{g.participantStates.forEach((S=>{let v=f.get(S.id);v||(v={participantId:S.id},f.set(S.id,v)),["attendeeAudioRestricted","attendeeModalitiesUnrestricted"].includes(g.type)&&(v.isAudioPermitted=this.isAudioPermitted(g.type)),["attendeeVideoRestricted","attendeeVideoUnrestricted"].includes(g.type)&&(v.isVideoPermitted=this.isVideoPermitted(g.type))}))})),f.forEach((g=>{void 0===g.isAudioPermitted&&(g.isAudioPermitted=!this.isMeetingCapabilityAudioRestricted()),void 0===g.isVideoPermitted&&(g.isVideoPermitted=!this.isMeetingCapabilityVideoRestricted())})),new Map(Array.from(f).map((([g,f])=>[g,{participant:constructIdentifierKindFromMri(g),isAudioPermitted:!!f?.isAudioPermitted,isVideoPermitted:!!f?.isVideoPermitted}])))},this.isAudioPermitted=g=>this.isMeetingCapabilityAudioRestricted()?"attendeeModalitiesUnrestricted"===g:"attendeeAudioRestricted"!==g,this.isVideoPermitted=g=>this.isMeetingCapabilityVideoRestricted()?"attendeeVideoUnrestricted"===g:"attendeeVideoRestricted"!==g,this.checkRemoteParticipantsMediaAccessAndEmitEvent=()=>{const g=this._remoteParticipantsMediaAccess;this._publishedStatesMediaAccessMap=this.getMediaAccessMap(this._tsCall.publishedStates),this.getAllOthersMediaAccess(),M.isEqual(g,this._remoteParticipantsMediaAccess)||this._eventEmitter.emit("mediaAccessChanged",{mediaAccesses:this._remoteParticipantsMediaAccess})},this.checkLocalMediaAccessAndEmitEvent=()=>{const g=this.getLocalParticipantMediaAccess();M.isEqual(this._localMediaAccess,g)||(this._localMediaAccess=g,this._eventEmitter.emit("localParticipantMediaAccessChanged",{mediaAccess:this._localMediaAccess}))},this.isUserRoleEligible=()=>this._tsCall.advancedMeetingRole&&this._supportedUserRoles.includes(this._tsCall.advancedMeetingRole),this.isSupportedConversationType=()=>this._supportedConversationTypes.includes(this._tsCall.conversationType);const f=getAcsEcsConfig().calling.mediaAccess;this._ecsTeamsMediaAccessEnabled=f.enabled,this._supportedUserRoles=f.supportedRoles,this._supportedConversationTypes=f.supportedConversationTypes,this._supportedConversationTypesForMuteAll=f.supportedConversationTypesForMuteAll,this._eventEmitter=g,this._publishedStatesMediaAccessMap=new Map,this._attendeeRestrictions="",this._localMediaAccess=void 0}initialize(g,f,S,v,C){this._logger=C.createChild((()=>`MediaAccessCallFeature::Call(id='${g.callId}')`)),this._tsCall=g,this._call=S,this._telemetryLogManager=v,this._internalCallAgent=f,this._sendFeatureUsage("initialize",gE.initialize);try{if(!this._ecsTeamsMediaAccessEnabled)throw"feature not supported or call context is not teams meeting join";this._tsCall.on("publishedStatesChanged",(async g=>{this._logger.info("publishedStatesChanged event received");const f=this._publishedStatesMediaAccessMap;this._publishedStatesMediaAccessMap=this.getMediaAccessMap(g),M.isEqual(f,this._publishedStatesMediaAccessMap)||this._eventEmitter.emit("mediaAccessChanged",{mediaAccesses:this.getAllOthersMediaAccess()}),this.checkLocalMediaAccessAndEmitEvent()})),this._tsCall.changed((()=>{const g=this._tsCall.meetingDetails?.meetingCapability?.attendeeRestrictions;M.isEqual(this._attendeeRestrictions,g)||(this._logger.info(`Attendee restrictions change from ${this._attendeeRestrictions} to ${g}`),this._attendeeRestrictions=g,this._eventEmitter.emit("meetingMediaAccessChanged",{meetingMediaAccess:this.getMeetingMediaAccess()}),this.checkRemoteParticipantsMediaAccessAndEmitEvent(),this.checkLocalMediaAccessAndEmitEvent())})),this._tsCall.on("participantCountsUpdated",(g=>{this._logger.info("participantCountsUpdated changed event received, totalParticipants: ",g?.totalParticipants),this.checkRemoteParticipantsMediaAccessAndEmitEvent(),this.checkLocalMediaAccessAndEmitEvent()})),this._attendeeRestrictions=this._tsCall.meetingDetails?.meetingCapability?.attendeeRestrictions,this._publishedStatesMediaAccessMap=this.getMediaAccessMap(this._tsCall.publishedStates),this._localMediaAccess=this.getLocalParticipantMediaAccess(),this._sendFeatureUsage("initialize",gE.success)}catch(g){throw this._logger.error("Could not initialize media access feature.",g),this._sendFeatureUsage("initialize",gE.failure),new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_ACCESS.INITIALIZE_FAILED,originalError:g})}}async permitAudio(g){const f=generateGuid();this._sendFeatureUsage("permitAudio",gE.attempt,f),this.validateMediaAccessConditions("permitAudio",f,!1,!0,g.map((g=>getMriFromIdentifier(g))));try{const S=g.map((g=>getMriFromIdentifier(g)));this.isMeetingCapabilityAudioRestricted()?await this.addModalityState(S,"attendeeModalitiesUnrestricted",f):await this.removeModalityState(S,"attendeeAudioRestricted",f),this._sendFeatureUsage("permitAudio",gE.success,f)}catch(g){throw this._logger.error(`Could not change a participant state. Code: ${g?.response?.status} correlationId: ${f}`),this._sendFeatureUsage("permitAudio",gE.failure),handlePublishStateFailure(g,D.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async forbidAudio(g){const f=generateGuid();this._sendFeatureUsage("forbidAudio",gE.attempt,f),this.validateMediaAccessConditions("forbidAudio",f,!1,!0,g.map((g=>getMriFromIdentifier(g))));try{const S=g.map((g=>getMriFromIdentifier(g)));this.isMeetingCapabilityAudioRestricted()?await this.removeModalityState(S,"attendeeModalitiesUnrestricted",f):await this.addModalityState(S,"attendeeAudioRestricted",f),this._sendFeatureUsage("forbidAudio",gE.success,f)}catch(g){throw this._logger.error(`Could not change a participant state. Code: ${g?.response?.status} correlationId: ${f}`),this._sendFeatureUsage("forbidAudio",gE.failure),handlePublishStateFailure(g,D.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async permitOthersAudio(){const g=generateGuid();this._sendFeatureUsage("permitOthersAudio",gE.attempt,g),this.validateMediaAccessConditions("permitOthersAudio",g,!0);try{let f;f=this.isMeetingCapabilityVideoRestricted()?2:0,await this.updateAttendeeRestrictions(f,g),this._sendFeatureUsage("permitOthersAudio",gE.success,g)}catch(f){throw this._logger.error(`Could not change a participant state. Code: ${f?.response?.status} correlationId: ${g}`),this._sendFeatureUsage("permitOthersAudio",gE.failure),handlePublishStateFailure(f,D.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async forbidOthersAudio(){const g=generateGuid();this._sendFeatureUsage("forbidOthersAudio",gE.attempt,g),this.validateMediaAccessConditions("forbidOthersAudio",g,!0);try{let f;f=this.isMeetingCapabilityVideoRestricted()?3:1,await this.updateAttendeeRestrictions(f,g),this._sendFeatureUsage("forbidOthersAudio",gE.success,g)}catch(f){throw this._logger.error(`Could not change a participant state. Code: ${f?.response?.status} correlationId: ${g}`),this._sendFeatureUsage("forbidOthersAudio",gE.failure),handlePublishStateFailure(f,D.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async permitVideo(g){const f=generateGuid();this._sendFeatureUsage("permitVideo",gE.attempt,f),this.validateMediaAccessConditions("permitVideo",f,!1,!0,g.map((g=>getMriFromIdentifier(g))));try{const S=g.map((g=>getMriFromIdentifier(g)));this.isMeetingCapabilityVideoRestricted()?await this.addModalityState(S,"attendeeVideoUnrestricted",f):await this.removeModalityState(S,"attendeeVideoRestricted",f),this._sendFeatureUsage("permitVideo",gE.success,f)}catch(g){throw this._logger.error(`Could not change a participant state. Code: ${g?.response?.status} correlationId: ${f}`),this._sendFeatureUsage("permitVideo",gE.failure),handlePublishStateFailure(g,D.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async forbidVideo(g){const f=generateGuid();this._sendFeatureUsage("forbidVideo",gE.attempt,f),this.validateMediaAccessConditions("forbidVideo",f,!1,!0,g.map((g=>getMriFromIdentifier(g))));try{const S=g.map((g=>getMriFromIdentifier(g)));this.isMeetingCapabilityVideoRestricted()?await this.removeModalityState(S,"attendeeVideoUnrestricted",f):await this.addModalityState(S,"attendeeVideoRestricted",f),this._sendFeatureUsage("forbidVideo",gE.success,f)}catch(g){throw this._logger.error(`Could not change a participant state. Code: ${g?.response?.status} correlationId: ${f}`),this._sendFeatureUsage("forbidVideo",gE.failure),handlePublishStateFailure(g,D.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async permitOthersVideo(){const g=generateGuid();this._sendFeatureUsage("permitOthersVideo",gE.attempt,g),this.validateMediaAccessConditions("permitOthersVideo",g,!0);try{let f;f=this.isMeetingCapabilityAudioRestricted()?1:0,await this.updateAttendeeRestrictions(f,g),this._sendFeatureUsage("permitOthersVideo",gE.success,g)}catch(f){throw this._logger.error(`Could not change a participant state. Code: ${f?.response?.status} correlationId: ${g}`),this._sendFeatureUsage("permitOthersVideo",gE.failure),handlePublishStateFailure(f,D.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}async forbidOthersVideo(){const g=generateGuid();this._sendFeatureUsage("forbidOthersVideo",gE.attempt,g),this.validateMediaAccessConditions("forbidOthersVideo",g,!0);try{let f;f=this.isMeetingCapabilityAudioRestricted()?3:2,await this.updateAttendeeRestrictions(f,g),this._sendFeatureUsage("forbidOthersVideo",gE.success,g)}catch(f){throw this._logger.error(`Could not change a participant state. Code: ${f?.response?.status} correlationId: ${g}`),this._sendFeatureUsage("forbidOthersVideo",gE.failure),handlePublishStateFailure(f,D.FEATURES.MEDIA_ACCESS.MEDIA_ACCESS_UPDATE_FAILED)}}getMeetingMediaAccess(){return{isAudioPermitted:!this.isMeetingCapabilityAudioRestricted(),isVideoPermitted:!this.isMeetingCapabilityVideoRestricted()}}updateAttendeeRestrictions(g,f){const S={attendeeRestrictions:g};return this._tsCall.updateMeetingSettings(S,f).catch((g=>{this._logger.error(`updateAttendeeRestrictions: failed with correlationId: ${f}, error: ${JSON.stringify(g)}`)}))}getPublishedState(g){return g.typeStates.filter((g=>["attendeeVideoRestricted","attendeeAudioRestricted","attendeeVideoUnrestricted","attendeeModalitiesUnrestricted"].includes(g.type)))}addModalityState(g,f,S){return new Promise(((v,C)=>{const _={type:f,level:"user",content:"{}",participantIds:g};this._tsCall.publishState(_,S).then((()=>{v()})).catch((f=>{const v=`addModalityState: failed with error: ${JSON.stringify({...f,correlationId:S,participantIds:g})}`;this._logger.error(v),C(v)}))}))}removeModalityState(g,f,S){const v=this._tsCall.publishedStates?this.getStateIdForParticipants(this._tsCall.publishedStates,g,f):[];if(M.isEmpty(v)){const v=`removeModalityState: no valid stateIds found for participants: ${g}, publishStateType: ${f} correlationId: ${S}`;return this._logger.error(v),Promise.reject(v)}return new Promise(((g,f)=>{const C={stateIds:v};this._tsCall.removeState(C,S).then((()=>{g()})).catch((g=>{const C=`removeModalityState: failed with error: ${JSON.stringify({...g,correlationId:S,stateIds:v})}`;this._logger.error(C),f(C)}))}))}getStateIdForParticipants(g,f,S){const v=[],C=g&&g.typeStates&&g.typeStates.find((g=>g.type===S));return M.isEmpty(C?.participantStates)?(this._logger.error(`getStateIdForParticipants: no valid typeState or participantStates found for participants: ${f}`),v):(f.forEach((g=>{const f=C?.participantStates.find((f=>f&&f.id===g));M.isEmpty(f)?this._logger.error(`getStateIdForParticipants: participant: ${g} not found.`):M.isEmpty(f?.publishedState)?this._logger.error(`getStateIdForParticipants: no published state for participant: ${g}`):f?.publishedState&&v.push(f.publishedState.stateId)})),v)}validateMediaAccessConditions(g,f,S,v,C){let _;if(this._ecsTeamsMediaAccessEnabled)if(this.isUserRoleEligible())if(S||this.isSupportedConversationType())if(S&&!this._supportedConversationTypesForMuteAll.includes(this._tsCall.conversationType))this._logger.error(`Conversation type is not supported for media access all feature, conversation type: ${this._tsCall.conversationType}`),_=new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_ACCESS.UNSUPPORTED_CONVERSATION_TYPE_FOR_FORBID_PERMIT_OTHERS_MEDIA_ACCESS,defaultErrorMessageArgs:["Conversation type: ",this._tsCall.conversationType]});else if(3!==this._tsCall.state)this._logger.error("Call state is not connected."),_=new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_ACCESS.CALL_NOT_CONNECTED,defaultErrorMessageArgs:["call state: ",this._tsCall.state]});else if(M.isEmpty(C))v&&M.isEmpty(C)?(this._logger.error("Participants array is empty."),_=new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_ACCESS.INVALID_PARTICIPANTS_LIST})):this._tsCall.meetingDetails?.meetingCapability?.attendeeRestrictions||(this._logger.error("Meeting capability attendee restrictions is empty."),_=new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_ACCESS.INVALID_MEETING_CAPABILITY_ATTENDEE_RESTRICTIONS,defaultErrorMessageArgs:["Meeting capability attendeerestrictions is empty."]}));else{const g=this._tsCall.participants.find((g=>C?.includes(g.id)&&g.advancedMeetingRole!==e_));g&&(this._logger.error(`Participant is not an attendee. id: ${g.id}`),_=new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_ACCESS.ROLE_RESTRICTED,defaultErrorMessageArgs:["Participant role: ",g.advancedMeetingRole||""]}))}else this._logger.error(`Conversation type is not supported for media access feature, conversation type: ${this._tsCall.conversationType}`),_=new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_ACCESS.UNSUPPORTED_CONVERSATION_TYPE,defaultErrorMessageArgs:["Conversation type: ",this._tsCall.conversationType]});else this._logger.error("User role is not eligible for media access feature."),_=new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_ACCESS.UNSUPPORTED_ROLE,defaultErrorMessageArgs:["User role: ",this._tsCall.advancedMeetingRole||""]});else this._logger.error("Media access feature is not enabled."),_=new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_ACCESS.FEATURE_DISABLED,defaultErrorMessageArgs:["Media access feature is not enabled."]});if(_)throw this._sendFeatureUsage(g,gE.failure,f),_}_sendFeatureUsage(g,f,S){sendCallFeatureUsageTelemetry({correlationId:S,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"MediaAccess",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}}class TeamsCapabilityResolver{constructor(g,f){this._logger=g,this._ecsConfig=getAcsEcsConfig(),this._call=f}getResolvedCapabilitiesBasedOnRole(g,f){let S={...f},v=g.toLocaleLowerCase();return v!==cS.Attendee.toLocaleLowerCase()&&v!==cS.Presenter.toLocaleLowerCase()&&v!==cS.Consumer.toLocaleLowerCase()&&v!==cS.Organizer.toLocaleLowerCase()&&v!==cS.Coorganizer.toLocaleLowerCase()||(v=v.replace("-",""),f.shareScreen.reason!=uS.UserPolicyRestricted&&(this._ecsConfig[pS][v][JE.shareScreen]?S.shareScreen={isPresent:!0,reason:uS.Capable}:S.shareScreen={isPresent:!1,reason:uS.RoleRestricted}),this._ecsConfig[pS][v][JE.removeParticipant]?S.removeParticipant={isPresent:!0,reason:uS.Capable}:S.removeParticipant={isPresent:!1,reason:uS.RoleRestricted},this._ecsConfig[pS][v][JE.hangUpForEveryOne]?S.hangUpForEveryOne={isPresent:!0,reason:uS.Capable}:S.hangUpForEveryOne={isPresent:!1,reason:uS.RoleRestricted},this._ecsConfig[pS][v][JE.addCommunicationUser]?S.addCommunicationUser={isPresent:!0,reason:uS.Capable}:S.addCommunicationUser={isPresent:!1,reason:uS.RoleRestricted},this._ecsConfig[pS][v][JE.addTeamsUser]?S.addTeamsUser={isPresent:!0,reason:uS.Capable}:S.addTeamsUser={isPresent:!1,reason:uS.RoleRestricted},this._ecsConfig[pS][v][JE.addPhoneNumber]?S.addPhoneNumber={isPresent:!0,reason:uS.Capable}:S.addPhoneNumber={isPresent:!1,reason:uS.RoleRestricted},this._ecsConfig[pS][v][JE.manageLobby]?S.manageLobby={isPresent:!0,reason:uS.Capable}:S.manageLobby={isPresent:!1,reason:uS.RoleRestricted},this._ecsConfig[pS][v][JE.spotlightParticipant]?S.spotlightParticipant={isPresent:!0,reason:uS.Capable}:S.spotlightParticipant={isPresent:!1,reason:uS.RoleRestricted},this._ecsConfig[pS][v][JE.removeParticipantsSpotlight]?S.removeParticipantsSpotlight={isPresent:!0,reason:uS.Capable}:S.removeParticipantsSpotlight={isPresent:!1,reason:uS.RoleRestricted},f.blurBackground.reason!=uS.UserPolicyRestricted&&(this._ecsConfig[pS][v][JE.blurBackground]?S.blurBackground={isPresent:!0,reason:uS.Capable}:S.blurBackground={isPresent:!1,reason:uS.RoleRestricted}),f.startLiveMeetingCaptions.reason!=uS.UserPolicyRestricted&&(this._ecsConfig[pS][v][JE.startLiveMeetingCaptions]?S.startLiveMeetingCaptions={isPresent:!0,reason:uS.Capable}:S.startLiveMeetingCaptions={isPresent:!1,reason:uS.RoleRestricted}),f.startLiveCallingCaptions.reason!=uS.UserPolicyRestricted&&(this._ecsConfig[pS][v][JE.startLiveCallingCaptions]?S.startLiveCallingCaptions={isPresent:!0,reason:uS.Capable}:S.startLiveCallingCaptions={isPresent:!1,reason:uS.RoleRestricted}),f.setCaptionLanguage.reason!=uS.TeamsPremiumLicenseRestricted&&(this._ecsConfig[pS][v][JE.setCaptionLanguage]?S.setCaptionLanguage={isPresent:!0,reason:uS.Capable}:S.setCaptionLanguage={isPresent:!1,reason:uS.RoleRestricted}),f.raiseHand.reason!=uS.MeetingRestricted&&(this._ecsConfig[pS][v][JE.raiseHand]?S.raiseHand={isPresent:!0,reason:uS.Capable}:S.raiseHand={isPresent:!1,reason:uS.RoleRestricted}),f.pstnDialOut.reason!=uS.MeetingRestricted&&(this._ecsConfig[pS][v][JE.pstnDialOut]?S.pstnDialOut={isPresent:!0,reason:uS.Capable}:S.pstnDialOut={isPresent:!1,reason:uS.RoleRestricted}),f.muteOthers.reason!=uS.MeetingRestricted&&(this._ecsConfig[pS][v][JE.muteOthers]?S.muteOthers={isPresent:!0,reason:uS.Capable}:S.muteOthers={isPresent:!1,reason:uS.RoleRestricted}),f.forbidOthersAudio.reason!=uS.MeetingRestricted&&(this._ecsConfig[pS][v][JE.forbidOthersAudio]?S.forbidOthersAudio={isPresent:!0,reason:uS.Capable}:S.forbidOthersAudio={isPresent:!1,reason:uS.RoleRestricted}),f.forbidOthersVideo.reason!=uS.MeetingRestricted&&(this._ecsConfig[pS][v][JE.forbidOthersVideo]?S.forbidOthersVideo={isPresent:!0,reason:uS.Capable}:S.forbidOthersVideo={isPresent:!1,reason:uS.RoleRestricted}),f.useReactions.reason!=uS.MeetingRestricted&&(this._ecsConfig[pS][v][JE.useReactions]?S.useReactions={isPresent:!0,reason:uS.Capable}:S.useReactions={isPresent:!1,reason:uS.RoleRestricted}),f.viewAttendeeNames.reason!=uS.MeetingRestricted&&(this._ecsConfig[pS][v][JE.viewAttendeeNames]?S.viewAttendeeNames={isPresent:!0,reason:uS.Capable}:S.viewAttendeeNames={isPresent:!1,reason:uS.RoleRestricted}),f.startTogetherMode.reason!=uS.MeetingRestricted&&(this._ecsConfig[pS][v][JE.startTogetherMode]?S.startTogetherMode={isPresent:!0,reason:uS.Capable}:S.startTogetherMode={isPresent:!1,reason:uS.RoleRestricted}),f.joinBreakoutRooms.reason!=uS.UserPolicyRestricted&&(this._ecsConfig[pS][v][JE.joinBreakoutRooms]?S.joinBreakoutRooms={isPresent:!0,reason:uS.Capable}:S.joinBreakoutRooms={isPresent:!1,reason:uS.RoleRestricted})),this.resolveMicVideoAndScreenShareCapabilities(S),this._logger.log(`Capabilities resolved to : ${JSON.stringify(S)} on role change to ${g}`),S}getResolvedCapabilitiesBasedOnMeetingCapabilities(g,f){let S={...f};return this.resolveMicVideoAndScreenShareCapabilities(S),null!=g.allowRaiseHands&&(g.allowRaiseHands?S.raiseHand={isPresent:!0,reason:uS.Capable}:S.raiseHand={isPresent:!1,reason:uS.MeetingRestricted}),null!=g.allowPstnConferencing&&(g.allowPstnConferencing?S.pstnDialOut={isPresent:!0,reason:uS.Capable}:S.pstnDialOut={isPresent:!1,reason:uS.MeetingRestricted}),null!=g.allowTeamsMeetingReactions&&(g.allowTeamsMeetingReactions?S.useReactions={isPresent:!0,reason:uS.Capable}:S.useReactions={isPresent:!1,reason:uS.MeetingRestricted}),null!=g.maskIdentitiesForRole&&(g.maskIdentitiesForRole?S.viewAttendeeNames={isPresent:!1,reason:uS.MeetingRestricted}:S.viewAttendeeNames={isPresent:!0,reason:uS.Capable}),null!=g.allowTranslatedCaptions&&(g.allowTranslatedCaptions?S.setCaptionLanguage={isPresent:!0,reason:uS.Capable}:S.setCaptionLanguage={isPresent:!1,reason:uS.TeamsPremiumLicenseRestricted}),this._logger.log(`Capabilities resolved to : ${JSON.stringify(S)} on meeting details change to ${g}`),S}getResolvedCapabilitiesBasedOnUserPolicy(g,f){let S={...f};return null!=g.teamsMeetingPolicy?.screenSharingMode&&("Disabled"==g.teamsMeetingPolicy?.screenSharingMode?S.shareScreen={isPresent:!1,reason:uS.UserPolicyRestricted}:S.shareScreen={isPresent:!0,reason:uS.Capable}),null!=g.teamsMeetingPolicy?.liveCaptionsEnabledType&&("Disabled"==g.teamsMeetingPolicy?.liveCaptionsEnabledType?S.startLiveMeetingCaptions={isPresent:!1,reason:uS.UserPolicyRestricted}:S.startLiveMeetingCaptions={isPresent:!0,reason:uS.Capable}),null!=g.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling&&("Disabled"==g.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling?S.startLiveCallingCaptions={isPresent:!1,reason:uS.UserPolicyRestricted}:S.startLiveCallingCaptions={isPresent:!0,reason:uS.Capable}),null!=g.teamsMeetingPolicy?.videoFiltersMode&&("NoFilters"==g.teamsMeetingPolicy?.videoFiltersMode?S.blurBackground={isPresent:!1,reason:uS.UserPolicyRestricted}:S.blurBackground={isPresent:!0,reason:uS.Capable}),null!=g.teamsMeetingPolicy?.allowBreakoutRooms&&(g.teamsMeetingPolicy?.allowBreakoutRooms?S.joinBreakoutRooms={isPresent:!0,reason:uS.Capable}:S.joinBreakoutRooms={isPresent:!1,reason:uS.UserPolicyRestricted}),null!=g.teamsMeetingPolicy?.ipAudioMode&&("Disabled"===g.teamsMeetingPolicy?.ipAudioMode?S.unmuteMic={isPresent:!1,reason:uS.IpModeUserPolicyRestricted}:S.unmuteMic={isPresent:!0,reason:uS.Capable}),null!=g.teamsMeetingPolicy?.ipVideoMode&&("Disabled"===g.teamsMeetingPolicy?.ipVideoMode?S.turnVideoOn={isPresent:!1,reason:uS.IpModeUserPolicyRestricted}:S.turnVideoOn={isPresent:!0,reason:uS.Capable}),this.resolveMicVideoAndScreenShareCapabilities(S),this._logger.log(`Capabilities resolved to : ${JSON.stringify(S)} on user policy update to ${g}`),S}getResolvedCapabilitiesBasedOnUserProperties(g,f){let S={...f};return this._logger.log(`Capabilities resolved to : ${JSON.stringify(S)} on user properties update to ${g}`),S}getResolvedCapabilitiesBasedOnCallPublishedStates(g){const f={...g};return this.resolveMicVideoAndScreenShareCapabilities(f),this._logger.log(`Capabilities resolved to : ${JSON.stringify(f)}`),f}resolveMicVideoAndScreenShareCapabilities(g){const f=g.unmuteMic.reason===uS.IpModeUserPolicyRestricted,S=g.turnVideoOn.reason===uS.IpModeUserPolicyRestricted;if(!f||!S){const v=this._call.feature(callFeatureFactory(MediaAccessCallFeatureImpl)).getLocalParticipantMediaAccess();f||(g.unmuteMic=v.isAudioPermitted?{isPresent:!0,reason:uS.Capable}:{isPresent:!1,reason:uS.MeetingRestricted}),S||(g.turnVideoOn=v.isVideoPermitted?{isPresent:!0,reason:uS.Capable}:{isPresent:!1,reason:uS.MeetingRestricted})}g.shareScreen.reason===uS.Capable&&this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()?g.shareScreen={isPresent:!1,reason:uS.ExplicitConsentRequired}:g.shareScreen.reason!==uS.ExplicitConsentRequired||this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()||(g.shareScreen={isPresent:!0,reason:uS.Capable}),g.unmuteMic.reason===uS.Capable&&this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()?g.unmuteMic={isPresent:!1,reason:uS.ExplicitConsentRequired}:g.unmuteMic.reason!==uS.ExplicitConsentRequired||this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()||(g.unmuteMic={isPresent:!0,reason:uS.Capable}),g.turnVideoOn.reason===uS.Capable&&this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()?g.turnVideoOn={isPresent:!1,reason:uS.ExplicitConsentRequired}:g.turnVideoOn.reason!==uS.ExplicitConsentRequired||this._call.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()||(g.turnVideoOn={isPresent:!0,reason:uS.Capable})}}class CapabilityResolverImpl{constructor(g,f,S,v,C,_){this._meetingCapabilities={},this._eventEmitter=g,this._logger=f,this._callInfo=v,this._tsCall=_,this._call=S,this._callAgent=C,this._capabilities=this.initializeCapabilities(),(this._callInfo.context==jS.Rooms||this._callInfo.context==jS.TeamsMeeting)&&this.doInitialCapabilityResolutionBasedOnRole(),this._callInfo.context==jS.TeamsMeeting&&this.doInitialCapabilityResolutionBasedOnUserPolicy(),this._callInfo.context==jS.TeamsMeeting&&this.doInitialCapabilityResolutionBasedOnMeetingCapabilities(),this._callInfo.context==jS.TeamsMeeting&&this.doInitialCapabilityResolutionBasedOnCallPublishedStates()}initializeCapabilities(){return this._logger.info("initializing capabilities"),this._callInfo.context!=jS.Rooms&&this._callInfo.context!=jS.TeamsMeeting?{turnVideoOn:{isPresent:!1,reason:uS.FeatureNotSupported},unmuteMic:{isPresent:!1,reason:uS.FeatureNotSupported},shareScreen:{isPresent:!1,reason:uS.FeatureNotSupported},removeParticipant:{isPresent:!1,reason:uS.FeatureNotSupported},hangUpForEveryOne:{isPresent:!1,reason:uS.FeatureNotSupported},addCommunicationUser:{isPresent:!1,reason:uS.FeatureNotSupported},addTeamsUser:{isPresent:!1,reason:uS.FeatureNotSupported},addPhoneNumber:{isPresent:!1,reason:uS.FeatureNotSupported},manageLobby:{isPresent:!1,reason:uS.FeatureNotSupported},spotlightParticipant:{isPresent:!1,reason:uS.FeatureNotSupported},removeParticipantsSpotlight:{isPresent:!1,reason:uS.FeatureNotSupported},blurBackground:{isPresent:!1,reason:uS.FeatureNotSupported},startLiveMeetingCaptions:{isPresent:!1,reason:uS.FeatureNotSupported},startLiveCallingCaptions:{isPresent:!1,reason:uS.FeatureNotSupported},setCaptionLanguage:{isPresent:!1,reason:uS.FeatureNotSupported},raiseHand:{isPresent:!1,reason:uS.FeatureNotSupported},pstnDialOut:{isPresent:!1,reason:uS.FeatureNotSupported},muteOthers:{isPresent:!1,reason:uS.FeatureNotSupported},useReactions:{isPresent:!1,reason:uS.FeatureNotSupported},viewAttendeeNames:{isPresent:!1,reason:uS.FeatureNotSupported},startTogetherMode:{isPresent:!1,reason:uS.FeatureNotSupported},joinBreakoutRooms:{isPresent:!1,reason:uS.FeatureNotSupported},forbidOthersAudio:{isPresent:!1,reason:uS.FeatureNotSupported},forbidOthersVideo:{isPresent:!1,reason:uS.FeatureNotSupported}}:{turnVideoOn:{isPresent:!1,reason:uS.NotInitialized},unmuteMic:{isPresent:!1,reason:uS.NotInitialized},shareScreen:{isPresent:!1,reason:uS.NotInitialized},removeParticipant:{isPresent:!1,reason:uS.NotInitialized},hangUpForEveryOne:{isPresent:!1,reason:uS.NotInitialized},addCommunicationUser:{isPresent:!1,reason:uS.NotInitialized},addTeamsUser:{isPresent:!1,reason:uS.NotInitialized},addPhoneNumber:{isPresent:!1,reason:uS.NotInitialized},manageLobby:{isPresent:!1,reason:uS.NotInitialized},spotlightParticipant:{isPresent:!1,reason:uS.NotInitialized},removeParticipantsSpotlight:{isPresent:!1,reason:uS.NotInitialized},blurBackground:{isPresent:!1,reason:uS.NotInitialized},startLiveMeetingCaptions:{isPresent:!1,reason:uS.FeatureNotSupported},startLiveCallingCaptions:{isPresent:!1,reason:uS.FeatureNotSupported},setCaptionLanguage:{isPresent:!1,reason:uS.FeatureNotSupported},raiseHand:{isPresent:!1,reason:uS.NotInitialized},pstnDialOut:{isPresent:!1,reason:uS.NotInitialized},muteOthers:{isPresent:!1,reason:uS.NotInitialized},useReactions:{isPresent:!1,reason:uS.NotInitialized},joinBreakoutRooms:{isPresent:!1,reason:uS.NotInitialized},viewAttendeeNames:{isPresent:!1,reason:uS.NotInitialized},startTogetherMode:{isPresent:!1,reason:uS.NotInitialized},forbidOthersAudio:{isPresent:!1,reason:uS.NotInitialized},forbidOthersVideo:{isPresent:!1,reason:uS.NotInitialized}}}doInitialCapabilityResolutionBasedOnRole(){this.resolveCapabilitiesBasedOnRole()}doInitialCapabilityResolutionBasedOnUserPolicy(){this.getCapabilityResolver()instanceof TeamsCapabilityResolver&&this._callInfo.context!=jS.Rooms&&this.resolveCapabilitiesBasedOnUserPolicy()}doInitialCapabilityResolutionBasedOnMeetingCapabilities(){this.resolveCapabilitiesBasedOnMeetingCapabilities()}doInitialCapabilityResolutionBasedOnCallPublishedStates(){this.resolveCapabilitiesBasedOnCallPublishedStates()}getCapabilityResolver(){return this._callInfo.context?.match(jS.Rooms)?new RoomsCapabilityResolver(this._logger):(this._callInfo.context?.match(jS.TeamsMeeting),new TeamsCapabilityResolver(this._logger,this._call))}getCapabilities(){return this._capabilities}resolveCapabilitiesBasedOnRole(){if(this._callInfo.context!=jS.Rooms&&this._callInfo.context!=jS.TeamsMeeting)return;let g=this._call.role;g==cS.Unknown&&(g=this._callInfo.context==jS.Rooms?cS.Consumer:cS.Attendee);let f=this.getCapabilityResolver();if(f){let S=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=f.getResolvedCapabilitiesBasedOnRole(g,this._capabilities),!M.isEqual(S,this._capabilities)){const f=this.getChangedCapabilitiesInfo(S,this._capabilities,"RoleChanged");this._logger.info(`Capabilities has changed based on role update to ${g}, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(f)}`),this._eventEmitter.emit("capabilitiesChanged",f)}}}resolveCapabilitiesBasedOnMeetingCapabilities(){if(this._callInfo.context!=jS.TeamsMeeting)return;let g={};g={...this._tsCall.meetingDetails?.capabilities,...this._tsCall.meetingDetails?.meetingCapability,...this._tsCall.meetingDetails?.recordingConsentDetails},this._meetingCapabilities={...g};let f=this.getCapabilityResolver();if(f&&f){const S=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=f.getResolvedCapabilitiesBasedOnMeetingCapabilities(g,this._capabilities),!M.isEqual(S,this._capabilities)){const g=this.getChangedCapabilitiesInfo(S,this._capabilities,"MeetingOptionOrOrganizerPolicyChanged");this._logger.info(`Capabilities has changed due to meeting capabilities, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(g)}`),this._eventEmitter.emit("capabilitiesChanged",g)}}}resolveCapabilitiesBasedOnCallPublishedStates(){if(this._callInfo.context!==jS.TeamsMeeting)return;const g=this.getCapabilityResolver();if(g&&g){const f=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=g.getResolvedCapabilitiesBasedOnCallPublishedStates(this._capabilities),!M.isEqual(f,this._capabilities)){const g=this.getChangedCapabilitiesInfo(f,this._capabilities,"MeetingOptionOrOrganizerPolicyChanged");this._logger.info(`Capabilities has changed due to call published states, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(g)}`),this._eventEmitter.emit("capabilitiesChanged",g)}}}resolveCapabilitiesBasedOnUserPolicy(){if(this._callInfo.context!=jS.TeamsMeeting)return;let g=this._callAgent.getUserPolicy(),f=this.getCapabilityResolver();if(f&&f&&g){let S=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=f.getResolvedCapabilitiesBasedOnUserPolicy(g,this._capabilities),!M.isEqual(S,this._capabilities)){const g=this.getChangedCapabilitiesInfo(S,this._capabilities,"UserPolicyChanged");this._logger.info(`Capabilities has changed due to user policy, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(g)}`),this._eventEmitter.emit("capabilitiesChanged",g)}}}resolveCapabilitiesBasedOnUserProperties(){if(this._callInfo.context!=jS.TeamsMeeting)return;let g=this._callAgent.getUserProperties(),f=this.getCapabilityResolver();if(f&&f&&g){let S=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=f.getResolvedCapabilitiesBasedOnUserProperties(g,this._capabilities),!M.isEqual(S,this._capabilities)){const g=this.getChangedCapabilitiesInfo(S,this._capabilities,"TeamsPremiumLicenseChanged");this._logger.info(`Capabilities has changed due to Teams Premium License, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(g)}`),this._eventEmitter.emit("capabilitiesChanged",g)}}}getMeetingsCapabilitiesInternal(){return this._meetingCapabilities}getChangedCapabilitiesInfo(g,f,S){let v={},C={};return Object.keys(g).forEach((S=>{g[S].isPresent!=f[S].isPresent&&(v[S]=g[S],C[S]=f[S])})),{oldValue:v,newValue:C,reason:S}}}class CapabilitiesFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._callInfo=g.callInfo,this._impl=new CapabilitiesImplOverTsCall(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",gE.getter),"Capabilities"}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._tsCall=g.tsCall,this._impl.initialize(g.tsCall,g.callAgent,g.call,this._callInfo,g.telemetryLogManager,f),this._sendFeatureUsage("initialize",gE.initialize)}get capabilities(){return this._sendFeatureUsage("getCapabilities",gE.getter),this._impl.capabilities}on(g,f){this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){this._sendFeatureUsage(g,gE.unsubscribe),this.eventEmitter.off(g,f)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"Capabilities",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}class CapabilitiesImplOverTsCall{constructor(g){this._eventEmitter=g}get capabilities(){return this._capabilityResolver.getCapabilities()}initialize(g,f,S,v,C,_){this._logger=_.createChild((()=>`CapabilitiesFeature::Call(id='${g.callId}')`)),this._tsCall=g,this._call=S,this._callInfo=v,this._internalCallAgent=f,this._timeToInitialize=new Date,this._capabilityResolver=new CapabilityResolverImpl(this._eventEmitter,this._logger,this._call,this._callInfo,this._internalCallAgent,this._tsCall),this._call.on("roleChanged",(()=>{this._capabilityResolver.resolveCapabilitiesBasedOnRole();let g=((new Date).getTime()-this._timeToInitialize.getTime())/1e3;this._logger.info("Time difference to initialize after role set is "+g)})),this._call.onMeetingCapabilitiesChanged("meetingCapabilitiesChanged",(()=>{this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities();let g=((new Date).getTime()-this._timeToInitialize.getTime())/1e3;this._logger.info("Time difference to initialize after meeting set up is"+g)})),this._call.feature(callFeatureFactory(MediaAccessCallFeatureImpl)).on("localParticipantMediaAccessChanged",(()=>{this._capabilityResolver.resolveCapabilitiesBasedOnCallPublishedStates(),this._logger.info("Time when received localParticipantMediaAccessChanged event"+(new Date).getTime())})),this._call.explicitConsentStateImp.onConsentRestrictionChanged("consentRestrictionChanged",(()=>{this._capabilityResolver.resolveCapabilitiesBasedOnCallPublishedStates();let g=((new Date).getTime()-this._timeToInitialize.getTime())/1e3;this._logger.info("Time difference to initialize after published state change is"+g)}))}}var t_,i_,bitwise=function(g){var f=0;if(0==g.length)return f;for(var S=0;S<g.length;S++){f=(f<<5)-f+g.charCodeAt(S),f&=f}return f},binaryTransfer=function(g,f){var S="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";f=f||62;var v,C=[],_="",T=g<0?"-":"";for(g=Math.abs(g);g>=f;)v=g%f,g=Math.floor(g/f),C.push(S[v]);g>0&&C.push(S[g]);for(var I=C.length-1;I>=0;I--)_+=C[I];return T+_},dist=function(g){var f=typeof g;if("string"===f||"number"===f)return binaryTransfer(bitwise(String(g)),61).replace("-","Z");throw new Error("Unexpected input type")};!function(g){g.ping="ping",g.pong="pong"}(t_||(t_={}));class DebugInfoCallClientFeatureImpl extends FirstPartyCallClientFeature{constructor(g){super(g),this._impl=new DebugInfoImplOverTsCall;try{getSdkVersion().includes("stable")||(this._browserTabInfoImpl=new BrowserTabInfoImpl(this.eventEmitter))}catch(f){g.callClient.logger.error("Feature to detect multiple tabs is not supported on the current environment.")}}get name(){return this._sendFeatureUsage("name",gE.getter),"DebugInfo"}get lastLocalParticipantId(){return this._sendFeatureUsage("lastLocalParticipantId",gE.getter),this._impl.lastLocalParticipantId}get logs(){return this._impl.logDump}get localParticipantIdMap(){return this._impl.localParticipantIdMap}get incommingCallIdMap(){return this._impl.incommingCallIdMap}get lastCallId(){if(this._sendFeatureUsage("lastCallId",gE.getter),this.lastLocalParticipantId)return this._impl.localParticipantIdMap[this.lastLocalParticipantId].callIds.slice(-1)[0]}get diagnosticInformation(){return this._impl.diagnosticInformation}get sdkVersion(){return getSdkVersion()}get acsResourceId(){return this._impl.AcsResourceId}get clientId(){return this._impl.clientId}dumpDebugInfoAsJSONString(){try{return JSON.stringify(this.toZip())}catch(g){return`JSON.stringify threw: ${g}`}}toZip(){return{clientId:this.clientId,lastLocalParticipantId:this.lastLocalParticipantId,localParticipantIdMap:this.localParticipantIdMap,incommingCallMap:this.incommingCallIdMap,AcsResourceId:this.acsResourceId,diagnosticInformation:this.diagnosticInformation,sdkVersion:this.sdkVersion,logs:this.logs}}dumpDebugInfo(){this._sendFeatureUsage("dumpDebugInfo",gE.attempt);try{const g=lE.deflate(this.dumpDebugInfoAsJSONString(),{to:"string"}),f=dist(g);return this._sendFeatureUsage("dumpDebugInfo",gE.success),{dump:g,dumpId:`${generateGuid()}-${f}`}}catch(g){const f=`failed to deflate, error: ${g}`;return this.logger.error(f),this._sendFeatureUsage("dumpDebugInfo",gE.failure),{dump:lE.deflate(f,{to:"string"}),dumpId:generateGuid()}}}initialize(g,f){this._impl.initialize(g,f),this.logger=f,this._telemetryLogManager=g.telemetryLogManager,this._callClient=g.callClient,this._browserTabInfoImpl&&this._browserTabInfoImpl.initialize(g.callClient,f,g.telemetryLogManager),this._sendFeatureUsage("initialize",gE.initialize)}async getEnvironmentInfo(){return this._sendFeatureUsage("getEnvironmentInfo",gE.getter),await this._callClient.getEnvironmentInfoInternal()}get isAnotherCallClientActiveInSameTab(){return this._sendFeatureUsage("isAnotherCallClientActiveInSameTab",gE.getter),!!this._browserTabInfoImpl&&this._browserTabInfoImpl.isAnotherCallClientActiveInSameTab}get isCallClientActiveInAnotherTab(){return this._sendFeatureUsage("isCallClientActiveInAnotherTab",gE.getter),!!this._browserTabInfoImpl&&this._browserTabInfoImpl.isCallClientActiveInAnotherTab}on(g,f){"isCallClientActiveInAnotherTabChanged"!==g&&"isAnotherCallClientActiveInSameTabChanged"!==g&&this.logger.error(`Not able to subscribe to event ${g}, unknown event name`),this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){"isCallClientActiveInAnotherTabChanged"!==g&&"isAnotherCallClientActiveInSameTabChanged"!==g&&this.logger.error(`Not able to unsubscribe to event ${g}, unknown event name`),this._sendFeatureUsage(g,gE.unsubscribe),this.eventEmitter.off(g,f)}_sendFeatureUsage(g,f){sendCallClientFeatureUsageTelemetry({featureName:"DebugInfo",featureType:"CallClient",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:g,step:f}},this._telemetryLogManager,this.logger)}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}}class DebugInfoImplOverTsCall{get diagnosticInformation(){return this._sdkDiagnosticInformation}get logDump(){return this._logger.log("Log dump requested"),this._logger.dumpAllLogs()}get AcsResourceId(){return this._callAgent?.getAcsResourceId()}get lastLocalParticipantId(){return this._lastLocalParticipantId}get localParticipantIdMap(){return this._localParticipantIdMap}get incommingCallIdMap(){return this._incommingCallIdMap}get clientId(){return this._callAgent?.getClientId()}constructor(){this._localParticipantIdMap={},this._incommingCallIdMap={}}initialize(g,f){this._logger=f,this._callAgent=g?.callClient?.callAgent,this._sdkDiagnosticInformation=g?.callClient.sdkDiagnosticInformation,this._logger.info("waiting for call agent to be created");const bindAndSubscribeToCallAgentEvents=()=>{this._callAgent=g?.callClient.callAgent,this.subscribeToCallAgentEvents()};g?.callClient.on("callAgentCreated",bindAndSubscribeToCallAgentEvents)}dispose(){}subscribeToCallAgentEvents(){try{this._callAgent?.on("callsUpdated",(g=>{[...g.added,...g.removed].forEach((g=>{this.updateLocalParticipantIdMap(g),g.on("idChanged",(()=>{this.updateLocalParticipantIdMap(g)}))}))})),this._callAgent?.on("incomingCall",(g=>{let f=g.incomingCall;f.on("callEnded",(g=>{try{this._incommingCallIdMap[f.id]=JSON.stringify(g.callEndReason)}catch(g){this._incommingCallIdMap[f.id]="callEnd reason unknown"}}));try{this._incommingCallIdMap[f.id]=JSON.stringify(g.incomingCall.callerInfo.identifier?.kind)}catch(g){this._incommingCallIdMap[f.id]="identifier kind unknown"}}))}catch(g){this._logger.info("failed to subscribe to call agent events, due to non initialized call agent")}}updateLocalParticipantIdMap(g){try{let f=this._localParticipantIdMap[g.tsCall.participantId]?.callIds.filter((f=>f!==g.tsCall.callId)).concat([g.tsCall.callId])??[g.tsCall.callId],S=[],v=[],C=g.callEndReason?JSON.stringify(g.callEndReason):g.state,_=g.state;this._localParticipantIdMap[g.tsCall.participantId]?.callEndReasons?(this._localParticipantIdMap[g.tsCall.participantId].callEndReasons.slice(-1)[0]!==C?(this._localParticipantIdMap[g.tsCall.participantId].callEndReasons.push(C),S=this._localParticipantIdMap[g.tsCall.participantId].callEndReasons):S=this._localParticipantIdMap[g.tsCall.participantId].callEndReasons,this._localParticipantIdMap[g.tsCall.participantId].stateTransitions.slice(-1)[0]!==_?(this._localParticipantIdMap[g.tsCall.participantId].stateTransitions.push(_),v=this._localParticipantIdMap[g.tsCall.participantId].stateTransitions):v=this._localParticipantIdMap[g.tsCall.participantId].stateTransitions):(S=[C],v=[g.state]),this._localParticipantIdMap[g.tsCall.participantId]={callIds:f,callEndReasons:S,stateTransitions:v},this._logger.info(`localParticipantIdMap: ${JSON.stringify(this._localParticipantIdMap)}`),g.on("stateChanged",(()=>{"Connected"===g.state&&(this._lastLocalParticipantId=g.tsCall.participantId,this._logger.info(`last patricipant id: ${this._lastLocalParticipantId}`)),this._localParticipantIdMap[g.tsCall.participantId].stateTransitions.slice(-1)[0]!==g.state&&this.localParticipantIdMap[g.tsCall.participantId].stateTransitions.push(g.state)}))}catch(g){this._logger.error(`exception occured while updating localParticipantId map: ${g}`)}}}class BrowserTabInfoImpl{get isCallClientActiveInAnotherTab(){return this._isCallClientActiveInAnotherTab}get isAnotherCallClientActiveInSameTab(){return this._isAnotherCallClientActiveInSameTab}constructor(g){this._eventEmitter=g,this._tabGroupId=BrowserTabInfoImpl.tabId,this._isCallClientActiveInAnotherTab=!1,this._isAnotherCallClientActiveInSameTab=!1,this._areThereMultipleTabs=null,this._manyCallClientInSameTab=null,this._isTabFirstLoadFlag=!0,this._intervalId=void 0,this._timeoutId=void 0,this._channel=new BroadcastChannel(getAcsEcsConfig().debugInfo.broadcastChannelName)}initialize(g,f,S){this._callClient=g,this._logger=f,this._telemetryLogManager=S;const v=getAcsEcsConfig().debugInfo.tabsBroadcastDelay,C=getAcsEcsConfig().debugInfo.tabsUpdateDelay;this.tabsCheck(),this._channel.postMessage({action:t_.ping,tabId:BrowserTabInfoImpl.tabId,groupId:this._tabGroupId}),this._timeoutId=setTimeout((()=>{this._areThereMultipleTabs&&(this._isCallClientActiveInAnotherTab=this._areThereMultipleTabs),this._manyCallClientInSameTab&&(this._isAnotherCallClientActiveInSameTab=this._manyCallClientInSameTab),this.sendTabUpdateEvent(),this._isTabFirstLoadFlag=!1}),10),this._intervalId=setInterval((()=>{this._areThereMultipleTabs=null,this._manyCallClientInSameTab=null,this._channel.postMessage({action:t_.ping,tabId:BrowserTabInfoImpl.tabId,groupId:this._tabGroupId}),setTimeout((()=>{null===this._areThereMultipleTabs&&(this._areThereMultipleTabs=!1),null===this._manyCallClientInSameTab&&(this._manyCallClientInSameTab=!1),this.tabsUpdate()}),C)}),v)}tabsCheck(){this._channel.addEventListener("message",(g=>{g.data?.action!==t_.ping&&g.data?.action!==t_.pong||(g.data?.action===t_.ping&&(BrowserTabInfoImpl.tabId===g.data.tabId?this._manyCallClientInSameTab=!0:BrowserTabInfoImpl.tabId!==g.data.tabId&&(this._areThereMultipleTabs=!0),this._channel.postMessage({action:t_.pong,tabId:BrowserTabInfoImpl.tabId,groupId:this._tabGroupId})),g.data?.action===t_.pong&&(BrowserTabInfoImpl.tabId===g.data.tabId?this._manyCallClientInSameTab=!0:BrowserTabInfoImpl.tabId!==g.data.tabId&&(this._areThereMultipleTabs=!0),this._tabGroupId!==g.data.groupId&&(this._tabGroupId=g.data.groupId)),this.tabsUpdate())}))}sendTabUpdateToCallEvent(){this._callClient.callAgent?._calls?.forEach((g=>g?.stats?.recordEvent({name:hE.sdk_active_in_another_tab,callId:g.id,localParticipantId:g.tsCall.participantId,data:{tabId:BrowserTabInfoImpl.tabId,tabGroupId:this._tabGroupId,isCallClientActiveInAnotherTab:this._isCallClientActiveInAnotherTab,isAnotherCallClientActiveInSameTab:this._isAnotherCallClientActiveInSameTab}})))}sendTabUpdateEvent(){const g={tabId:BrowserTabInfoImpl.tabId,tabGroupId:this._tabGroupId,isCallClientActiveInAnotherTab:this._isCallClientActiveInAnotherTab,isAnotherCallClientActiveInSameTab:this._isAnotherCallClientActiveInSameTab};this._telemetryLogManager.sendEvent({name:uE.acs_calling_tab_events,tenant:tf,properties:g})}tabsUpdate(){this._isTabFirstLoadFlag||null===this._manyCallClientInSameTab||null===this._areThereMultipleTabs||this._isCallClientActiveInAnotherTab===this._areThereMultipleTabs&&this._isAnotherCallClientActiveInSameTab===this._manyCallClientInSameTab||(this._isAnotherCallClientActiveInSameTab!==this._manyCallClientInSameTab&&(this._logger.log(`isAnotherCallClientActiveInSameTab changed from ${this._isAnotherCallClientActiveInSameTab} to ${this._manyCallClientInSameTab}`),this._isAnotherCallClientActiveInSameTab=this._manyCallClientInSameTab,this._eventEmitter.emit("isAnotherCallClientActiveInSameTabChanged")),this._isCallClientActiveInAnotherTab!==this._areThereMultipleTabs&&(this._logger.log(`isCallClientActiveInAnotherTab changed from ${this._isCallClientActiveInAnotherTab} to ${this._areThereMultipleTabs}`),this._isCallClientActiveInAnotherTab=this._areThereMultipleTabs,this._eventEmitter.emit("isCallClientActiveInAnotherTabChanged")),this.sendTabUpdateEvent(),this.sendTabUpdateToCallEvent())}dispose(){this._channel.close(),void 0!==this._timeoutId&&clearTimeout(this._timeoutId),void 0!==this._intervalId&&clearInterval(this._intervalId)}}BrowserTabInfoImpl.tabId=generateGuid(),(i_=g.DiagnosticQuality||(g.DiagnosticQuality={}))[i_.Good=1]="Good",i_[i_.Poor=2]="Poor",i_[i_.Bad=3]="Bad";const n_="networkReconnect",r_="networkReceiveQuality",s_="networkSendQuality",a_="networkRelaysNotReachable",o_="noNetwork",l_="noSpeakerDevicesEnumerated",c_="noMicrophoneDevicesEnumerated",d_="microphoneNotFunctioning",h_="microphoneMuteUnexpectedly",u_="cameraStoppedUnexpectedly",g_="capturerStoppedUnexpectedly",p_="speakingWhileMicrophoneIsMuted",m_="cameraFreeze",f_="cameraStartFailed",S_="capturerStartFailed",v_="cameraStartTimedOut",C_="screenshareRecordingDisabled",y_="microphonePermissionDenied",E_="cameraPermissionDenied";function diagnosticValueToText(f,S){return"serverConnection"==S?f?"Good":"Bad":"boolean"==typeof f?f?"Bad":"Good":g.DiagnosticQuality[f]}class UserFacingDiagnosticsFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new UserFacingDiagnosticsImplOverTsCall}get name(){return this._sendFeatureUsage("name",gE.getter),"Diagnostics"}get network(){return this._sendFeatureUsage("network",gE.getter),this._impl.network}get media(){return this._sendFeatureUsage("media",gE.getter),this._impl.media}get remote(){return this._sendFeatureUsage("remote",gE.getter),this._impl.remote}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._call=g.call,this._impl.initialize(g,f),this._sendFeatureUsage("initialize",gE.initialize)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Diagnostics",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}}class UserFacingDiagnosticsImplOverTsCall{get network(){return void 0===this._network&&(this._network=new NetworkDiagnosticsImpl(this._internalApi,this._logger),this._network.bindToTsCallQualityChangedEvent()),this._network}get media(){return void 0===this._media&&(this._media=new MediaDiagnosticsImpl(this._internalApi,this._logger),this._media.bindToTsCallQualityChangedEvent()),this._media}get remote(){return void 0===this._remote&&(this._remote=new RemoteDiagnosticsImpl(this._internalApi,this._logger),this._remote.bindToTsCallPublishedStatesChangedEvent()),this._remote}initialize(g,f){this._internalApi=g,this._logger=f}dispose(){}}class UserFacingDiagnosticsImpl{constructor(f,S,v){this._name=f,this.internalApi=S,this.logger=v,this._tsUfdUnknownValue=0,this.tsToAcsNetworkQualityEventTypeMap={5:n_,2:r_,1:s_,32:a_,37:o_},this.tsToAcsMediaQualityEventTypeMap={44:l_,43:c_,9:d_,25:h_,27:p_,45:m_,33:f_,34:v_,55:C_,26:y_,47:E_},this.tsQualityToAcsQualityMap={1:g.DiagnosticQuality.Good,2:g.DiagnosticQuality.Poor,3:g.DiagnosticQuality.Bad},this.tsQualityToAcsBooleanMap={3:!0,1:!1},this.eventEmitter=new LE.EventEmitter}bindToTsCallQualityChangedEvent(){this.internalApi.tsCall.on("callQualityChanged",(f=>{try{let S;if("NetworkDiagnostics"===this._name?S=this.mapTsNetworkQualityEventType(f.type):"MediaDiagnostics"===this._name&&(S=this.mapTsMediaQualityEventType(f.type,f.mediaType)),S){if(f.value===this._tsUfdUnknownValue)return;let v,C;if("NetworkDiagnostics"===this._name){const{mappedQualityLevel:g,valueType:C}=this.mapTsNetworkQualityLevel(S,f.value);v=g,this.setLatestDiagnostic(S,{value:v,valueType:C})}else if("MediaDiagnostics"===this._name){const{mappedQualityLevel:g,valueType:C}=this.mapTsMediaQualityLevel(S,f.value);v=g,this.setLatestDiagnostic(S,{value:v,valueType:C})}if("number"!=typeof v||v!==g.DiagnosticQuality.Good&&v!==g.DiagnosticQuality.Poor&&v!==g.DiagnosticQuality.Bad){if("boolean"!=typeof v)throw this.logger.error(`Incorrect valueType mapped for diagnostic='${S}', value='${v}'`),new CallingCommunicationError({defaultError:D.FEATURES.DIAGNOSTICS.INCORRECT_VALUETYPE_MAPPED});C="DiagnosticFlag"}else C="DiagnosticQuality";const _={diagnostic:S,value:v,valueType:C};this.logger.log(`Call diagnostic changed, diagnostic='${_.diagnostic}', value='${_.value}'`);const T="DiagnosticFlag"===_.valueType&&!0===_.value,I="DiagnosticQuality"===_.valueType&&(_.value===g.DiagnosticQuality.Bad||_.value===g.DiagnosticQuality.Poor);(T||I)&&this.logger.warn(`Call diagnostic error raised!, diagnostic='${_.diagnostic}', value='${_.value}', value type='${_.valueType}'`),this.sendDiagnosticEvent({name:"UserFacingDiagnostics",callId:this.internalApi.tsCall.callId,localParticipantId:this.internalApi.tsCall.participantId,remoteParticipantId:"",diagnostic:_.diagnostic,valueText:diagnosticValueToText(_.value),valueType:_.valueType,correlationId:""}),this.eventEmitter.emit("diagnosticChanged",_)}}catch(g){this.logger.error(`${g?.message})`)}}))}mapTsNetworkQualityEventType(g){return this.tsToAcsNetworkQualityEventTypeMap[g]}mapTsNetworkQualityLevel(g,f){let S,v;switch(g){case n_:case r_:case s_:v="DiagnosticQuality",S=this.tsQualityToAcsQualityMap[f];break;case a_:case o_:v="DiagnosticFlag",S=this.tsQualityToAcsBooleanMap[f]}return{mappedQualityLevel:S,valueType:v}}mapTsMediaQualityEventType(g,f){const S=this.tsToAcsMediaQualityEventTypeMap[g];if(S===h_)switch(f){case 1:return u_;case 2:return g_}return S===f_&&2===f?S_:S}mapTsMediaQualityLevel(g,f){let S,v;switch(g){case l_:case c_:case d_:case h_:case p_:case m_:case f_:case v_:case C_:case y_:case E_:case u_:case g_:case S_:v="DiagnosticFlag",S=this.tsQualityToAcsBooleanMap[f]}return{mappedQualityLevel:S,valueType:v}}sendDiagnosticEvent(g){this.internalApi.telemetryLogManager.sendEvent({name:uE.acs_calling_call_stats_and_ufds,tenant:tf,properties:{name:g.name,callId:g.callId,localParticipantId:g.localParticipantId,remoteParticipantId:g.remoteParticipantId,diagnostic:g.diagnostic,valueText:g.valueText,valueType:g.valueType,correlationId:g.correlationId}})}}class NetworkDiagnosticsImpl extends UserFacingDiagnosticsImpl{constructor(g,f){super("NetworkDiagnostics",g,f.createChild((()=>`[UserFacingDiagnosticsFeature:NetworkDiagnostics:Call(id='${g.tsCall.callId}', state='${g.tsCall.state}')]`))),this.latestNetworkDiagnostics=new Map}setLatestDiagnostic(g,f){this.latestNetworkDiagnostics.set(g,f)}on(g,f){if("diagnosticChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.DIAGNOSTICS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}off(g,f){if("diagnosticChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.DIAGNOSTICS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.off(g,f)}getLatest(){try{return convertMapToFrozenJson(this.latestNetworkDiagnostics)}catch(g){return this.logger.error("Failed to get latest network diagnostics"),{}}}}class MediaDiagnosticsImpl extends UserFacingDiagnosticsImpl{constructor(g,f){super("MediaDiagnostics",g,f.createChild((()=>`[UserFacingDiagnosticsFeature:MediaDiagnostics:Call(id='${g.tsCall.callId}', state='${g.tsCall.state}')]`))),this.latestMediaDiagnostics=new Map}setLatestDiagnostic(g,f){this.latestMediaDiagnostics.set(g,f)}on(g,f){if("diagnosticChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.DIAGNOSTICS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}off(g,f){if("diagnosticChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.DIAGNOSTICS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.off(g,f)}getLatest(){try{return convertMapToFrozenJson(this.latestMediaDiagnostics)}catch(g){return this.logger.error("Failed to get latest media diagnostics"),{}}}}class RemoteDiagnosticsImpl extends UserFacingDiagnosticsImpl{constructor(g,f){super("RemoteDiagnostics",g,f.createChild((()=>`[UserFacingDiagnosticsFeature:RemoteDiagnosticsiagnostics:Call(id='${g.tsCall.callId}', state='${g.tsCall.state}')]`))),this._remoteDiagnosticCorrelationIdMap=new Map,this.tsQualityStringToEnumMap={NetworkSendQuality:1,NetworkRecvQuality:2,NetworkDelay:3,NetworkBandwidthLow:4,NetworkReconnect:5,NetworkPacketLoss:6,NetworkJitter:7,NetworkRateMatching:8,DeviceCaptureNotFunctioning:9,DeviceRenderNotFunctioning:10,DeviceRenderGlitches:11,DeviceLowSNR:12,DeviceLowSpeechLevel:13,DeviceClipping:14,DeviceEcho:15,DeviceNearEndToEchoRatio:16,DeviceHalfDuplexAec:17,DeviceMultipleEndpoints:18,DeviceHowling:19,DeviceRenderZeroVolume:20,DeviceRenderMute:21,NetworkSendCatastrophic:22,NetworkRecvCatastrophic:23,CpuInsufficient:24,DeviceCaptureMute:25,DeviceCaptureNotMuteButSilent:26,DeviceSpeakWhileMuted:27,VideoVbssRendered:28,NetworkEthernetInterfaceUsed:29,NetworkWlanInterfaceUsed:30,NetworkWwanInterfaceUsed:31,NetworkRelaysNotReachable:32,VideoCapturerDeviceStartFailed:33,VideoCapturerDeviceStartTimedOut:34,VideoCapturerDeviceStartFailureLackSystemRes:35,VideoCapturerDeviceStartFailureMFResConflict:36,NoNetwork:37,NetworkNotWorking:38,DeviceCaptureNotFunctioningDeviceInUse:39,DeviceRenderNotFunctioningDeviceInUse:40,DeviceCaptureNotFunctioningAudioSrvNotRunning:41,DeviceRenderNotFunctioningAudioSrvNotRunning:42,ZeroCaptureDevicesEnumerated:43,ZeroRenderDevicesEnumerated:44,VideoCaptureDeviceFreeze:45,AudioCapturePermissionDenied:46,VideoCapturePermissionDenied:47,VideoCaptureFreezeRecovered:48,DeviceRenderHowling:49,LowFarEndInput:50,ImageRenderingQuality:51,RemoteNetworkConnectivityIssue:52,PresentationAudioLoopbackDeviceState:53,AudioCaptureUltrasoundDetected:54,ScreenshareRecordingDisabled:55,MultichannelAudioBandwidth:56,MusicModeNotAvailable:57,MusicModeSupported:58,AudioCaptureMusicDetectedWithHighNS:59,AudioCaptureMusicDetectedWithLowNS:60,CameraLighting:61,DeviceCaptureVoiceActive:62,AudioLoopbackDeviceReady:63,NoRequiredVideoCodecs:64,SpatialAudioMUCHUnavailable:65,SpeechOverlapFailedInterruptionDetected:66,BackgroundSpeechSuppressed:67,BackgroundLoudSpeechSuppressed:68,ActiveSpeechDetected:69,DeviceCaptureNotFunctioningBluetoothMidCallFail:70,DeviceCaptureNotFunctioningWebcamMicMidCallFail:71,DeviceCaptureNotMuteButSilentDongle:72,DeviceRenderNotFunctioningBluetoothMidCallFail:73,ZeroCaptureDevicesEnumeratedRDP:74,ZeroRenderDevicesEnumeratedRDP:75,WrongCaptureDevicesUsedRDP:76,WrongRenderDevicesUsedRDP:77,NetworkStatusIndicator:78,LoopbackDeviceRenderNotFunctioning:79,AudioMixMUCHUnavailable:80},this.tsMediaStringToEnumMap={Audio:0,Video:1,ScreenShare:2,Data:3},this.tsQualityLevelStringToEnumMap={Good:1,Poor:2,Bad:3,Unknown:0},this._latestRemoteDiagnostics={diagnostics:[]}}bindToTsCallPublishedStatesChangedEvent(){this.internalApi.tsCall.on("publishedStatesChanged",(async g=>{const f=[],S=new Set;g.typeStates.forEach((g=>{const processRemoteDiagnostics=(g,S)=>{const v=this.getRemoteDiagnosticIndex(g);v>-1&&this._latestRemoteDiagnostics.diagnostics[v].value!==g.value?(g={...g,remoteParticipant:this._latestRemoteDiagnostics.diagnostics[v].remoteParticipant},this._latestRemoteDiagnostics.diagnostics[v]=g,f.push(g)):-1!==v||this.isGoodServerRemoteDiagnostic(g)||(g={...g,remoteParticipant:this.internalApi.call.remoteParticipants.find((g=>getMriFromIdentifier(g.identifier)===S))},this._latestRemoteDiagnostics.diagnostics.push(g),f.push(g))};"serverMediaUfd"===g.type&&(this.logger.debug(`Remote diagnostics changed, typeState='${JSON.stringify(g)}'`),g.participantStates.forEach((g=>{try{if(g.id!==this.internalApi.callAgent.getUserMri()){const f=this.createServerRemoteDiagnostic(g.id,g.publishedState?.content);processRemoteDiagnostics(f,g.id),S.add(g.id)}}catch(f){this.logger.error(`Error processing remote diagnostic: ${JSON.stringify(g)}, error: ${f?.message}`)}}))),"clientMediaUfd"===g.type&&(this.logger.debug(`Client remote diagnostics changed, typeState='${JSON.stringify(g)}'`),g.participantStates.forEach((g=>{try{if(g.id!==this.internalApi.callAgent.getUserMri()&&g.endpoints)for(const f of g.endpoints){const S=this.createClientRemoteDiagnostic(g.id,f);S&&processRemoteDiagnostics(S,g.id)}}catch(f){this.logger.error(`Error processing client remote diagnostic: ${JSON.stringify(g)}, error: ${f?.message}`)}})))})),this.removeRemoteUserDiagnostics(S),f.length>0&&(this.sendRemoteDiagnosticsTelemetry(f),this.eventEmitter.emit("diagnosticChanged",{diagnostics:f}))}))}setLatestDiagnostic(g,f){}getLatest(){return this._latestRemoteDiagnostics}on(g,f){if("diagnosticChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.DIAGNOSTICS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}off(g,f){if("diagnosticChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.DIAGNOSTICS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.off(g,f)}isGoodServerRemoteDiagnostic(g){return"serverConnection"===g.diagnostic&&!0===g.value}createServerRemoteDiagnostic(g,f){if(!f)throw new Error("Content is missing in remote diagnostic");"string"==typeof f&&(f=JSON.parse(f));return{participantId:f.participantId,rawId:g,diagnostic:f.type,value:"string"==typeof f.value&&"good"===f.value.toLowerCase(),valueType:"DiagnosticFlag"}}mergeOrIgnoreClientDiagnostics(g){const f=getAcsEcsConfig().calling.remoteDiagnostic.sourceEvents.indexOf(g);if(f>-1){const g=getAcsEcsConfig().calling.remoteDiagnostic.exposedEvents[f];return this.logger.debug(`Merging ${getAcsEcsConfig().calling.remoteDiagnostic.sourceEvents[f]} to ${g}`),g}return g}createClientRemoteDiagnostic(g,f){if(!f.publishedState.content)throw new Error("Content is missing in client remote diagnostic");const S=f.publishedState.content,v=S.type;let C=this.mapTsNetworkQualityEventType(this.tsQualityStringToEnumMap[v]);const _=S.value;let T;if(C)T=this.mapTsNetworkQualityLevel(C,this.tsQualityLevelStringToEnumMap[_]);else{const g=S.mediaType;C=this.mapTsMediaQualityEventType(this.tsQualityStringToEnumMap[v],this.tsMediaStringToEnumMap[g]),T=this.mapTsMediaQualityLevel(C,this.tsQualityLevelStringToEnumMap[_])}const I=this.mergeOrIgnoreClientDiagnostics(C);if(""===I)return;I!==C&&(C=I);return{participantId:f.id,rawId:g,diagnostic:C,value:T.mappedQualityLevel,valueType:T.valueType}}getRemoteDiagnosticIndex(g){return this._latestRemoteDiagnostics.diagnostics.findIndex((f=>f.participantId===g.participantId&&f.diagnostic===g.diagnostic))}removeRemoteUserDiagnostics(g){this._latestRemoteDiagnostics.diagnostics=this._latestRemoteDiagnostics.diagnostics.filter((f=>{const S=g.has(f.rawId);return S||this._remoteDiagnosticCorrelationIdMap.forEach(((g,S)=>{S.endsWith(`_${f.participantId}`)&&this._remoteDiagnosticCorrelationIdMap.delete(S)})),S}))}sendRemoteDiagnosticsTelemetry(f){this.logger.debug(`Sending remote diagnostics telemetry, number of diagnostics=${f.length}`),f.forEach((f=>{const S=`${f.diagnostic}_${f.participantId}`;this._remoteDiagnosticCorrelationIdMap.has(S)||this._remoteDiagnosticCorrelationIdMap.set(S,generateGuid()),this.sendDiagnosticEvent({name:"RemoteClientDiagnostics",callId:this.internalApi.tsCall.callId,localParticipantId:this.internalApi.tsCall.participantId,remoteParticipantId:f.participantId,diagnostic:f.diagnostic,valueText:diagnosticValueToText(f.value,f.diagnostic),valueType:f.valueType,correlationId:this._remoteDiagnosticCorrelationIdMap.get(S)??""}),("DiagnosticFlag"===f.valueType&&!0===f.value||"DiagnosticQuality"===f.valueType&&f.value===g.DiagnosticQuality.Good)&&this._remoteDiagnosticCorrelationIdMap.set(S,generateGuid())}))}}class DominantSpeakersCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new DominantSpeakersCallImplOverTsCall(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",gE.getter),"DominantSpeakers"}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._call=g.call,this._impl.initialize(g.tsCall,g.callAgent,g.telemetryLogManager,f),this._sendFeatureUsage("initialize",gE.initialize)}get dominantSpeakers(){return this._sendFeatureUsage("dominantSpeakers",gE.getter),this._impl.dominantSpeakers}on(g,f){this._sendFeatureUsage("dominantSpeakersChanged",gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){this._sendFeatureUsage("dominantSpeakersChanged",gE.unsubscribe),this.eventEmitter.off(g,f)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"DominantSpeakers",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}}class DominantSpeakersCallImplOverTsCall{constructor(g){this._eventEmitter=g,this.localDominantList=[]}initialize(g,f,S,v,C=!1){this._logger=v.createChild((()=>`DominantSpeakersFeature${C?"Internal":""}::Call(id='${g.callId}')`)),this._tsCall=g,this.localDominantList=this._tsCall.dominantSpeakerInfo?.speakerList||[],this._tsCallChangedListener=this._tsCall.changed((()=>{let g=!1;if(this.localDominantList.length!=this._tsCall.dominantSpeakerInfo.speakerList.length)g=!0;else for(let f in this._tsCall.dominantSpeakerInfo.speakerList)if(this._tsCall.dominantSpeakerInfo.speakerList[f]!==this.localDominantList[f]){g=!0;break}g&&(this._logger.info("Dominant speakers list change detected"),this.localDominantList=this._tsCall.dominantSpeakerInfo.speakerList,this._eventEmitter.emit("dominantSpeakersChanged"))}))}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}get dominantSpeakers(){let g=Array();return this._tsCall.dominantSpeakerInfo.speakerList.map((f=>{g.push(constructIdentifierKindFromMri(f))})),{speakersList:g,timestamp:this._tsCall.dominantSpeakerInfo.timestamp||new Date}}dispose(){this._eventEmitter.removeAllListeners(),this._tsCallChangedListener?.dispose()}}class CallingEventEmitter extends LE.EventEmitter{constructor(g,f){super(),this._options={enableLogOn:!0,enableLogOff:!0,enableLogOnce:!0,enableLogEmit:!0},this._logger=g.createChild("CallingEventEmitter"),f&&(this._options=f)}on(g,f){return!1!==this._options.enableLogOn&&this._logger.info(`event:subscribe to ${g.toString()}`),super.on(g,f)}once(g,f){return!1!==this._options.enableLogOnce&&this._logger.info(`event:subscribe once to ${g.toString()}`),super.once(g,f)}off(g,f){return!1!==this._options.enableLogOff&&this._logger.info(`event:unsubscribed ${g.toString()}`),super.off(g,f)}emit(g,...f){try{return!1!==this._options.enableLogEmit&&this._logger.info(`event:emit ${g.toString()}`),super.emit(g,...f)}catch(f){return this._logger.warn(`Application threw an error while it handled the ${g.toString()} event`),!1}}}function createMediaStatsReportInternalObject(){return{audio:{send:{},receive:{}},video:{send:{},receive:{}},screenShare:{send:{},receive:{}},dataChannel:{},transports:{},info:{}}}function getMax(g){let f=g.length>0?g[0]:0;return g.forEach((g=>{g>f&&(f=g)})),f}function getMin(g){let f=g.length>0?g[0]:0;return g.forEach((g=>{g<f&&(f=g)})),f}function getSum(g){let f=0,S=0;return g.forEach((g=>{const v=g-S,C=f+v;S=C-f-v,f=C})),f}const T_=createMediaStatsReportInternalObject;class MediaStatsCalculator{constructor(g){this._metricsProperties=g,this._originalValues={},this._aggregateValues={},this._events=[],this._currentValues={}}addStats(g,f){const S=this._metricsProperties[g];if(void 0!==S&&!0!==S.skip){if(S.events){const v=S.output_key??g;f!==this._currentValues[v]&&(this._currentValues[v]=f,this._events.push({name:v,value:f,timestamp:Date.now()}))}else{let S=this._originalValues[g];void 0===S&&(S={raw:[],beginTime:Date.now()},this._originalValues[g]=S),S.raw.push(f)}return f}}aggregate(){for(const[g,f]of Object.entries(this._originalValues)){const S=this._metricsProperties[g],v=S.output_key??g;let C=this._aggregateValues[v];void 0===C&&(C={raw:[],timestamp:new Date(f.beginTime)},S.aggregable&&(C.aggregation={count:[],sum:[],max:[],min:[]}),this._aggregateValues[v]=C);const _=f.raw;let T=_;if(S.aggregable&&C.aggregation){const g=_.filter((g=>"number"==typeof g&&!isNaN(g)));C.aggregation.count.push(g.length),C.aggregation.sum.push(getSum(g)),C.aggregation.max.push(getMax(g)),C.aggregation.min.push(getMin(g)),T=g}S.raw_data_reduction&&T.length>0&&(C.reduced=C.reduced||[],C.reduced.push(T[T.length-1])),T.forEach((g=>C.raw.push(g)))}this._originalValues={}}popAggregates(){const g=this._aggregateValues;return this._aggregateValues={},g}popEvents(){const g=this._events;return this._events=[],g}}class TelemetryCollector{constructor(g,f){if(this._aggregationInterval=0,this._dataPointsPerAggregation=0,this._disposed=!1,this._calculators=T_(),this._isActive=!1,f.aggregationInterval<1)throw new Error("invalid aggregationInterval value range");if(f.dataPointsPerAggregation<1)throw new Error("invalid dataPointsPerAggregation value range");this._metricsProperties=f.metricsPropertics,this._logger=g.createChild("TelemetryCollector"),this._eventEmitter=new CallingEventEmitter(this._logger,{enableLogEmit:!1}),this._callStateChanged=defer$1(),this._aggregationInterval=f.aggregationInterval,this._dataPointsPerAggregation=f.dataPointsPerAggregation,this._run()}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}dispose(){this._disposed||(this._disposed=!0,this._callStateChanged.resolve(!1),this._eventEmitter.removeAllListeners(),this._mediaStatsSource?.removeSink(this))}get source(){return this._mediaStatsSource}set source(g){this._mediaStatsSource=g}onReport(g){this._processMediaStatsReport(g)}onAdded(g){this._isActive!==g&&(this._isActive=g,this._callStateChanged.resolve(g))}onRemoved(){this.dispose()}pause(){this._isActive&&(this._isActive=!1,this._callStateChanged.resolve(!1))}resume(){this._isActive||(this._isActive=!0,this._callStateChanged.resolve(!0))}stop(){this.dispose()}_processMediaStatsReport(g){try{const f=[[g.audio.send,this._calculators.audio.send,this._metricsProperties.audio.send,"send"],[g.audio.receive,this._calculators.audio.receive,this._metricsProperties.audio.receive,"recv"],[g.video.send,this._calculators.video.send,this._metricsProperties.video.send,"send"],[g.video.receive,this._calculators.video.receive,this._metricsProperties.video.receive,"recv"],[g.screenShare.send,this._calculators.screenShare.send,this._metricsProperties.screenShare.send,"send"],[g.screenShare.receive,this._calculators.screenShare.receive,this._metricsProperties.screenShare.receive,"recv"],[g.dataChannel,this._calculators.dataChannel,this._metricsProperties.dataChannel,""],[g.transports,this._calculators.transports,this._metricsProperties.transports,""],[g.info,this._calculators.info,this._metricsProperties.info,""]];for(const[S,v,C,_]of f){const f=[],T=Object.keys(v);Object.keys(S).forEach((T=>{const I=S[T],b=I.id;f.push(b),void 0===v[b]&&(v[b]=new MediaStatsCalculator(C));const addStats=(g,f)=>v[b].addStats(g,f);if(Object.keys(I).forEach((g=>addStats(g,I[g]))),"send"==_||"recv"==_){const f=I.transportId;if(void 0!==f){const S=g.transports[f];void 0!==S.rtt&&addStats("pairRttInMs",S.rttInMs),void 0!==S.availableIncomingBitrate&&"recv"==_&&addStats("availableBitrate",S.availableIncomingBitrate),void 0!==S.availableOutgoingBitrate&&"send"==_&&addStats("availableBitrate",S.availableOutgoingBitrate)}}}));T.filter((g=>!f.includes(g))).forEach((g=>{delete v[g]}))}}catch(g){this._logger.error(g)}}async _run(){let g=0;const flushData=()=>{if(0===g)return;const f={audio:{send:{},receive:{}},video:{send:{},receive:{}},screenShare:{send:{},receive:{}},dataChannel:{},transports:{},info:{}},S=[[f.audio.send,this._calculators.audio.send],[f.audio.receive,this._calculators.audio.receive],[f.video.send,this._calculators.video.send],[f.video.receive,this._calculators.video.receive],[f.screenShare.send,this._calculators.screenShare.send],[f.screenShare.receive,this._calculators.screenShare.receive],[f.dataChannel,this._calculators.dataChannel],[f.transports,this._calculators.transports],[f.info,this._calculators.info]];for(const[g,f]of S)for(const[S,v]of Object.entries(f))g[S]={id:S,...v.popAggregates(),events:v.popEvents()};this._eventEmitter.emit("data",f),g=0};let f=1e3*this._aggregationInterval;for(;!this._disposed;){const S=[this._calculators.audio.send,this._calculators.audio.receive,this._calculators.video.send,this._calculators.video.receive,this._calculators.screenShare.send,this._calculators.screenShare.receive,this._calculators.dataChannel,this._calculators.info];if(this._isActive){f>0&&await wait((()=>this._callStateChanged.promise),f).catch((g=>{}));const v=Date.now();for(const g of S)for(const[,f]of Object.entries(g))f.aggregate();g++,g===this._dataPointsPerAggregation&&flushData();const C=Date.now();f=v+1e3*this._aggregationInterval-C}else flushData(),this._calculators=T_(),await this._callStateChanged.promise.catch((g=>{})),f=1e3*this._aggregationInterval;this._callStateChanged.isPending()||(this._callStateChanged=defer$1())}flushData()}}function convertAltLayouts(g){const f=[];return g.sort(((g,f)=>g.id>f.id?1:g.id<f.id?-1:0)),g.forEach((g=>{const S=/^([^.]+)\.?([^.]+)?$/.exec(g.id);if(S&&S[2]){g.id=M.toString(S[2]);const v=M.toString(S[1]);if(f.length>0&&f[f.length-1].id===v){const S=f[f.length-1].altLayouts??[];S.push(g),f[f.length-1].altLayouts=S}else f.push(g)}else f.push(g)})),f}class MediaStatsCollectorImpl{constructor(g,f){if(this._aggregationInterval=0,this._dataPointsPerAggregation=0,this._disposed=!1,this._calculators=T_(),this._isActive=!1,f.aggregationInterval<1)throw new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_STATS.INVALID_AGGREGATION_INTERVAL_RANGE});if(f.dataPointsPerAggregation<1)throw new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_STATS.INVALID_DATAPOINTS_AGGREGATION_RANGE});this._metricsProperties=f.metricsPropertics,this._logger=g.createChild("MediaStatsCollector"),this._eventEmitter=new CallingEventEmitter(this._logger,{enableLogEmit:!1}),this._callStateChanged=defer$1(),this._aggregationInterval=f.aggregationInterval,this._dataPointsPerAggregation=f.dataPointsPerAggregation,this._run()}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}dispose(){this._disposed||(this._disposed=!0,this._callStateChanged.resolve(!1),this._eventEmitter.removeAllListeners(),this._mediaStatsSource?.removeSink(this))}get source(){return this._mediaStatsSource}set source(g){this._mediaStatsSource=g}onReport(g){this._processMediaStatsReport(g)}onAdded(g){this._isActive!==g&&(this._isActive=g,this._callStateChanged.resolve(g))}onRemoved(){this.dispose()}pause(){this._isActive&&(this._isActive=!1,this._callStateChanged.resolve(!1))}resume(){this._isActive||(this._isActive=!0,this._callStateChanged.resolve(!0))}stop(){this.dispose()}_processMediaStatsReport(g){const f={audio:{send:[],receive:[]},video:{send:[],receive:[]},screenShare:{send:[],receive:[]},transports:[]};try{const S=[[g.audio.send,f.audio.send,this._calculators.audio.send,this._metricsProperties.audio.send],[g.audio.receive,f.audio.receive,this._calculators.audio.receive,this._metricsProperties.audio.receive],[g.video.send,f.video.send,this._calculators.video.send,this._metricsProperties.video.send],[g.video.receive,f.video.receive,this._calculators.video.receive,this._metricsProperties.video.receive],[g.screenShare.send,f.screenShare.send,this._calculators.screenShare.send,this._metricsProperties.screenShare.send],[g.screenShare.receive,f.screenShare.receive,this._calculators.screenShare.receive,this._metricsProperties.screenShare.receive],[g.transports,f.transports,this._calculators.transports,this._metricsProperties.transports]];let v=!1;for(const[g,f,C,_]of S){const S=[],T=Object.keys(C);Object.keys(g).forEach((T=>{const I=g[T];let b=I.id;I.groupId&&(b=`${I.groupId}.${b}`,v=!0);const A={id:b};S.push(b),void 0===C[b]&&(C[b]=new MediaStatsCalculator(_)),Object.keys(I).forEach((g=>{const f=_[g];if(f&&!0!==f.skip){const S=C[b].addStats(g,I[g]),v=f.output_key??g;A[v]=S}})),f.push(A)}));T.filter((g=>!S.includes(g))).forEach((g=>{delete C[g]}))}v&&(f.video.send=convertAltLayouts(f.video.send),f.screenShare.send=convertAltLayouts(f.screenShare.send))}catch(g){this._logger.error(g)}this._eventEmitter.emit("sampleReported",f)}async _run(){let g=0;const flushData=()=>{if(0===g)return;const f={audio:{send:[],receive:[]},video:{send:[],receive:[]},screenShare:{send:[],receive:[]},transports:[]};for(const[g,S]of Object.entries(this._calculators.audio.send))f.audio.send.push({id:g,...S.popAggregates()});for(const[g,S]of Object.entries(this._calculators.audio.receive))f.audio.receive.push({id:g,...S.popAggregates()});for(const[g,S]of Object.entries(this._calculators.video.send))f.video.send.push({id:g,...S.popAggregates()});for(const[g,S]of Object.entries(this._calculators.video.receive))f.video.receive.push({id:g,...S.popAggregates()});for(const[g,S]of Object.entries(this._calculators.screenShare.send))f.screenShare.send.push({id:g,...S.popAggregates()});for(const[g,S]of Object.entries(this._calculators.screenShare.receive))f.screenShare.receive.push({id:g,...S.popAggregates()});for(const[g,S]of Object.entries(this._calculators.transports))f.transports.push({id:g,...S.popAggregates()});f.video.send=convertAltLayouts(f.video.send),f.screenShare.send=convertAltLayouts(f.screenShare.send),this._eventEmitter.emit("summaryReported",f),g=0};let f=1e3*this._aggregationInterval;for(;!this._disposed;){const S=[this._calculators.audio.send,this._calculators.audio.receive,this._calculators.video.send,this._calculators.video.receive,this._calculators.screenShare.send,this._calculators.screenShare.receive,this._calculators.transports];if(this._isActive){f>0&&await wait((()=>this._callStateChanged.promise),f).catch((g=>{}));const v=Date.now();for(const g of S)for(const[,f]of Object.entries(g))f.aggregate();g++,g===this._dataPointsPerAggregation&&flushData();const C=Date.now();f=v+1e3*this._aggregationInterval-C}else flushData(),this._calculators=T_(),await this._callStateChanged.promise.catch((g=>{})),f=1e3*this._aggregationInterval;this._callStateChanged.isPending()||(this._callStateChanged=defer$1())}flushData()}}class AbstractTicker{constructor(){this._eventEmitter=new LE.EventEmitter,this._getCurrentTime=globalThis.performance&&"function"==typeof globalThis.performance.now?()=>globalThis.performance.now():()=>Date.now()}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}dispose(){this._eventEmitter.removeAllListeners()}}class IntervalTicker extends AbstractTicker{constructor(g){super(),this._intervalInMs=g,this._handle=0}start(){this._handle||(this._handle=globalThis.setInterval((()=>{this._eventEmitter.emit("tick")}),this._intervalInMs))}stop(){this._handle&&(globalThis.clearInterval(this._handle),this._handle=0)}dispose(){this.stop(),super.dispose()}}class ChainedTimeoutTicker extends AbstractTicker{constructor(g){super(),this._intervalInMs=g,this._callQueue=Promise.resolve(),this._state={isRunning:!1}}start(){if(this._state.isRunning)return;const g={isRunning:!0};this._state=g;const runLoop=async()=>{for(;g.isRunning;){const g=this._getCurrentTime();this._eventEmitter.emit("tick");const f=this._getCurrentTime()-g;f<this._intervalInMs&&await sleep(this._intervalInMs-f)}};this._callQueue=this._callQueue.then((()=>runLoop())).catch((()=>{}))}stop(){this._state.isRunning&&(this._state.isRunning=!1)}dispose(){this._state.isRunning=!1,super.dispose()}}class TickerFactory{static createTicker(g,f){if("interval"===g)return new IntervalTicker(f);if("timeout"===g)return new ChainedTimeoutTicker(f);throw new Error(`Invalid tickerType: ${g}`)}}class StatsPoller{constructor(g,f,S,v,C){this._call=g,this._logger=f,this._dataEventRefCount=0,this._lastFetchTime=0,this._timerDelayRatio=0,this._pendingStats=!1,this._tsCall=this._call.tsCall,this._fetchInterval=S,this._eventEmitter=new CallingEventEmitter(this._logger,{enableLogEmit:!1});const _=1e3*S;this._ticker=TickerFactory.createTicker(v,_),this._ticker.on("tick",(()=>{const g=Date.now();this._lastFetchTime>0&&(this._timerDelayRatio=(g-this._lastFetchTime)/_),this._lastFetchTime=g,this._dataEventRefCount>0&&!1===this._pendingStats&&(this._pendingStats=!0,this.getStats().then((g=>{g&&this._eventEmitter.emit("data",g)})).catch((g=>{this._logger.error(g)})).finally((()=>{this._pendingStats=!1})))}));const checkState=()=>{C.includes(this._tsCall.state)?this._start():this._stop()};this._callStateChangedHandle=this._tsCall.on("callStateChanged",(()=>{checkState()})),checkState()}dispose(){this._callStateChangedHandle.dispose(),this._ticker.dispose()}get fetchInterval(){return this._fetchInterval}get timerDelayRatio(){return this._timerDelayRatio}_start(){this._lastFetchTime=0,this._timerDelayRatio=0,this._ticker.start()}_stop(){this._ticker.stop()}on(g,f){this._dataEventRefCount++,this._eventEmitter.on(g,f)}off(g,f){this._dataEventRefCount--,this._eventEmitter.off(g,f)}}class MediaStatsPoller extends StatsPoller{constructor(g,f,S){super(g,f.createChild("MediaStatsPoller"),S.mediaStats.fetchInterval,S.mediaStats.pollingMethod,S.mediaStats.activeState),this._memoryInformationV2PendingTask=!1,this._lastCap=new Map,this._lastCpuPressureLevel=-1,this._telemetryConfig=S.telemetry.mediaStatsConfig}_recordSendMaxCapabilities(g,f){if(f)try{const S=JSON.parse(f);M.each(S,(f=>{const S=f.events,v=this._lastCap.get(g)??0,C=M.filter(M.flatten(S),(g=>"req"===g?.eventType&&g?.timestamp>v));C.length>0&&this._lastCap.set(g,M.last(C).timestamp),C.forEach((f=>{this._call.stats.recordEvent({name:hE.video_max_capabilities,callId:this._call.id,localParticipantId:this._tsCall.participantId,timestamp:f.timestamp,data:{streamType:g,eventType:f.eventType??"",capabilities:f.capabilities??{},isSimulcast:f.isSimulcast??!1}})}))}))}catch(f){this._logger.warn(`Failed to process max capabilities for streamType ${g}: ${f}`)}}async getStats(){const g=await(this._tsCall.getMediaSessionStatsAsync?.());this._telemetryConfig.enableVideoMaxCapCallStats&&g?.extensions&&(this._recordSendMaxCapabilities("Video",g.extensions.Video_send_MaxCapabilities),this._recordSendMaxCapabilities("ScreenSharing",g.extensions.Sharing_send_MaxCapabilities));const f={report:g,delayRatio:this.timerDelayRatio};if(this._telemetryConfig.enableNetworkInformation&&window.navigator.connection){const g=window.navigator.connection,S=M.get(g,"downlink"),v=M.get(g,"rtt");void 0===S&&void 0===v||(f.networkInformation={downlink:S,rtt:v})}if(this._telemetryConfig.enableMemoryInformationV1&&window.performance?.memory){const g=window.performance.memory,S=M.get(g,"jsHeapSizeLimit"),v=M.get(g,"totalJSHeapSize"),C=M.get(g,"usedJSHeapSize");void 0===S&&void 0===v&&void 0===C||(f.memoryInformationV1={jsHeapSizeLimit:S,totalJSHeapSize:v,usedJSHeapSize:C})}if(this._telemetryConfig.enableMemoryInformationV2&&window.crossOriginIsolated&&window.performance?.measureUserAgentSpecificMemory&&(this._memoryInformationV2&&(f.memoryInformationV2={jsSize:this._memoryInformationV2.jsSize,sharedSize:this._memoryInformationV2.sharedSize,domSize:this._memoryInformationV2.domSize}),this._memoryInformationV2PendingTask||(this._memoryInformationV2PendingTask=!0,window.performance.measureUserAgentSpecificMemory.call(window.performance).then((g=>{let f,S,v;M.get(g,"breakdown",[]).forEach((g=>{g.bytes>0&&(M.indexOf(g.types,"DOM")>=0&&(v=void 0===v?g.bytes:v+g.bytes),M.indexOf(g.types,"Shared")>=0&&(S=void 0===S?g.bytes:S+g.bytes),M.indexOf(g.types,"JavaScript")>=0&&(f=void 0===f?g.bytes:f+g.bytes))})),this._memoryInformationV2={jsSize:f,sharedSize:S,domSize:v}})).catch((g=>{this._memoryInformationV2=void 0})).finally((()=>{this._memoryInformationV2PendingTask=!1})))),this._telemetryConfig.enableBatteryInformation&&navigator.getBattery)try{const g=await navigator.getBattery();g&&(f.batteryInformation={charging:g.charging,level:g.level})}catch(g){}if(this._telemetryConfig.enablePressureInformation&&window.PressureObserver){if(!this._pressureObserver)try{this._pressureObserver=new window.PressureObserver((g=>{const f=g[g.length-1];this._lastCpuPressureLevel=["nominal","fair","serious","critical"].indexOf(f.state)})),await this._pressureObserver.observe("cpu",{sampleInterval:1e3})}catch(g){this._logger.error(`Failed to observe cpu pressure ${g}`)}-1!==this._lastCpuPressureLevel&&(f.pressureInformation={cpuPressureLevel:this._lastCpuPressureLevel})}if(this._telemetryConfig.enableAudioLeakInformation)try{const S=this._tsCall.isMuted||this._tsCall.isServerMuted;f.callInformation?f.callInformation.audioLeak=0:f.callInformation={audioLeak:0},S&&g?.audio.send.length&&void 0!==g.audio.send[0].audioLevel&&g.audio.send[0].audioLevel>this._telemetryConfig.audioLeakThreshold&&(navigator.mediaDevices.isRemote&&!navigator.mediaDevices.tsCallingChannel?.createdRemoteObject||(f.callInformation.audioLeak=1))}catch(g){}if(this._telemetryConfig.enableVideoLeakInformation)try{f.callInformation?f.callInformation.videoLeak=0:f.callInformation={videoLeak:0},!this._tsCall.isVideoOn&&g?.video.send.length&&(f.callInformation.videoLeak=1)}catch(g){}return f}dispose(){try{this._pressureObserver&&(this._pressureObserver.disconnect(),this._pressureObserver=void 0)}catch(g){this._logger.error(`dispose error: ${g}`)}}}var I_;!function(g){g[g.Running=0]="Running",g[g.Paused=1]="Paused",g[g.Stopped=2]="Stopped"}(I_||(I_={}));class MediaStatsSourceNode{constructor(){this._sinks=[],this._transformers=[],this._state=I_.Running}_setTransformers(g){this._transformers=g.slice()}addSink(g){g.source=this,this._sinks.push(g),g.onAdded(this._state===I_.Running)}removeSink(g){g.source===this&&(M.pull(this._sinks,g),g.source=void 0,g.onRemoved())}removeAllSinks(){const g=this._sinks;this._sinks=[],g.forEach((g=>{g.source=void 0,g.onRemoved()}))}send(g){if(this._state!==I_.Running)return;let f=g;this._transformers.length&&(f=this._transformers.reduce(((g,f)=>f.transform(g)),g)),this._sinks.forEach((g=>g.onReport(f)))}pause(){this._state===I_.Running&&(this._state=I_.Paused,this._sinks.forEach((g=>g.pause())))}resume(){this._state===I_.Paused&&(this._state=I_.Running,this._sinks.forEach((g=>g.resume())))}stop(){this._state!==I_.Stopped&&this._sinks.forEach((g=>g.stop()))}}class MediaStatsReportSourceNode extends MediaStatsSourceNode{constructor(g){super(),this._setTransformers(g)}onReport(g){if(void 0===g.report)return;const f=createMediaStatsReportInternalObject();f.metadata=f.metadata??{},f.metadata.delayRatio=g.delayRatio;const S=[],v={id:"0"};g.networkInformation&&(void 0!==g.networkInformation.downlink&&(v.networkInfoDownlink=g.networkInformation.downlink),void 0!==g.networkInformation.rtt&&(v.networkInfoRttInMs=g.networkInformation.rtt)),g.memoryInformationV1&&(void 0!==g.memoryInformationV1.jsHeapSizeLimit&&(v.jsHeapSizeLimit=g.memoryInformationV1.jsHeapSizeLimit),void 0!==g.memoryInformationV1.totalJSHeapSize&&(v.totalJSHeapSize=g.memoryInformationV1.totalJSHeapSize),void 0!==g.memoryInformationV1.usedJSHeapSize&&(v.usedJSHeapSize=g.memoryInformationV1.usedJSHeapSize)),g.memoryInformationV2&&(void 0!==g.memoryInformationV2.jsSize&&(v.jsSize=g.memoryInformationV2.jsSize),void 0!==g.memoryInformationV2.sharedSize&&(v.sharedSize=g.memoryInformationV2.sharedSize),void 0!==g.memoryInformationV2.domSize&&(v.domSize=g.memoryInformationV2.domSize)),g.batteryInformation&&(void 0!==g.batteryInformation.charging&&(v.batteryCharging=g.batteryInformation.charging?1:0),void 0!==g.batteryInformation.level&&(v.batteryLevel=g.batteryInformation.level)),g.pressureInformation&&void 0!==g.pressureInformation.cpuPressureLevel&&(v.cpuPressureLevel=g.pressureInformation.cpuPressureLevel),g.callInformation&&(void 0!==g.callInformation.audioLeak&&(v.audioLeak=g.callInformation.audioLeak),void 0!==g.callInformation.videoLeak&&(v.videoLeak=g.callInformation.videoLeak)),M.keys(v).length>1&&S.push(v);const C=[[g.report.audio.send,f.audio.send],[g.report.audio.recv,f.audio.receive],[g.report.video.send,f.video.send],[g.report.video.recv,f.video.receive],[g.report.screenShare.send,f.screenShare.send],[g.report.screenShare.recv,f.screenShare.receive],[g.report.data,f.dataChannel],[g.report.transports,f.transports],[S,f.info]],extractKV=g=>{const f={};return Object.entries(g).forEach((g=>{const S=g[0],v=g[1];"altLayouts"!==S&&null!=v&&(f[S]=v)})),f};C.forEach((g=>{const f=g[0];if(void 0!==f){const S=g[1];f.forEach((g=>{const f=M.toString(g.id);if(S[f]=extractKV(g),void 0!==g.altLayouts){g.altLayouts.forEach((g=>{const v=g.id,C=extractKV(g);C.groupId=f,S[v]=C}))}}))}})),this.send(f)}}class MediaStatsReportFilterNode extends MediaStatsSourceNode{constructor(g){super(),this._setTransformers(g)}onAdded(g){}onRemoved(){}onReport(g){this.send(g)}get source(){return this._mediaStatsSource}set source(g){this._mediaStatsSource=g}}class ParticipantMappingManager{constructor(g){this._tsCall=g,this._activeParticipantMris=new Set,this._sourceIdToParticipantInfo=new Map,this._listenerHandles=[],this._config=getAcsEcsConfig(),this._listenerHandles.push(this._tsCall.on("participantAdded",(g=>{this._activeParticipantMris.add(g.id),this._updateMapping(g)}))),this._listenerHandles.push(this._tsCall.on("participantUpdated",(g=>{this._activeParticipantMris.has(g.id)&&this._updateMapping(g)}))),this._listenerHandles.push(this._tsCall.on("participantRemoved",(g=>{this._activeParticipantMris.delete(g.id),this._removeMapping(g)}))),this._tsCall.participants?.forEach((g=>{this._activeParticipantMris.add(g.id),this._updateMapping(g)}))}_updateMapping(g){const f=g.id,S=[],v=this._config.calling.composedStreamBotIds;g.endpoints?.endpointDetails?.forEach((g=>{g.mediaStreams?.forEach((C=>{S.push(C.sourceId),this._sourceIdToParticipantInfo.set(C.sourceId,{mri:f,participantId:g.participantId,isComposedStream:v.includes(f)})}))}))}_removeMapping(g){g.endpoints?.endpointDetails?.forEach((g=>{g.mediaStreams?.forEach((g=>{this._sourceIdToParticipantInfo.delete(g.sourceId)}))}))}findParticipantInfo(g){let f=this._sourceIdToParticipantInfo.get(g);if(void 0===f&&this.isP2P()&&this._tsCall.participants.length&&this._tsCall.participants[0].endpoints?.endpointDetails.length){const g=this._tsCall.participants[0],S=g.endpoints?.endpointDetails[0];f={mri:g.id,participantId:S?.participantId??"",isComposedStream:!1}}return f}isP2P(){return 1===this._tsCall.callType}dispose(){this._activeParticipantMris.clear(),this._sourceIdToParticipantInfo.clear(),this._listenerHandles.forEach((g=>g.dispose()))}}class MediaStatsTelemetryLogger{constructor(g,f,S,v){this._tsCall=g,this._call=f,this._telemetryLogManager=S,this._config=v,this._participantMappingManager=new ParticipantMappingManager(this._tsCall)}dispose(){this._participantMappingManager.dispose()}log(g){const f=this._config.telemetry.mediaStatsConfig;[{type:"audio",direction:"send",value:g.audio.send},{type:"audio",direction:"recv",value:g.audio.receive},{type:"video",direction:"send",value:g.video.send},{type:"video",direction:"recv",value:g.video.receive},{type:"screen",direction:"send",value:g.screenShare.send},{type:"screen",direction:"recv",value:g.screenShare.receive},{type:"data",direction:"",value:g.dataChannel},{type:"transport",direction:"",value:g.transports},{type:"info",direction:"",value:g.info}].forEach((g=>{const S=Object.values(g.value);S.forEach((v=>{const C={id:v.id},_={id:v.id};Object.keys(v).forEach((g=>{const S=g;if("id"===g)return;if("events"===g){const g=v[S];return void(g.length>0&&(C.events=JSON.stringify(g)))}const T=v[S];if(f.dataToSend.raw){const g={};T?.timestamp&&(g.timestamp=T?.timestamp),f.dataToSend.raw&&(g.raw=T?.raw),_[S]=g}const I={};void 0!==T.aggregation?(T.timestamp&&(I.timestamp=T.timestamp),f.dataToSend.min&&(I.min=T.aggregation.min),f.dataToSend.max&&(I.max=T.aggregation.max),f.dataToSend.sum&&(I.sum=T.aggregation.sum),f.dataToSend.count&&(I.count=T.aggregation.count)):(T.timestamp&&(I.timestamp=T.timestamp),T.reduced?I.raw=T.reduced:T.raw&&(I.raw=T.raw)),C[S]=I}));let T="",I="";if(("video"===g.type||"screen"===g.type)&&"recv"===g.direction){const g=v;if(void 0!==g.streamId&&g.streamId.raw?.length){const f=g.streamId.raw[0],S=this._participantMappingManager.findParticipantInfo(f);T=S?.participantId??"",I=S?.isComposedStream?"ComposedVideoStream":"RemoteVideoStream"}}if(Object.keys(C).length>1){const f={mediaType:g.type,mediaDirection:g.direction,stats:C,callId:this._tsCall.callId,remoteParticipantId:T,localParticipantId:this._tsCall.participantId,videoStreamKind:I,streamCount:S.length,appliedFrameHeightMaxSentConstraint:this._call.mediaConstraintsManager.currentVideoConstraints?.send?.frameHeight?.max,appliedBitrateMaxSentConstraint:this._call.mediaConstraintsManager.currentVideoConstraints?.send?.bitrate?.max,appliedFrameRateMaxSentConstraint:this._call.mediaConstraintsManager.currentVideoConstraints?.send?.frameRate?.max,audioEffectsProcessorStats:this._call.audioEffectsProcessorStats??void 0};this._sendMidCallNewMediaStats(f)}if(f.dataToSend.raw&&Object.keys(_).length>1){const f={mediaType:g.type,mediaDirection:g.direction,stats:_,callId:this._tsCall.callId,remoteParticipantId:T,localParticipantId:this._tsCall.participantId,videoStreamKind:I,streamCount:S.length};this._sendMidCallRawMediaStats(f)}}))}))}_sendMidCallNewMediaStats(g){this._telemetryLogManager.sendEvent({name:uE.acs_calling_mid_call_new_media_stats,tenant:tf,properties:g})}_sendMidCallRawMediaStats(g){this._telemetryLogManager.sendEvent({name:uE.acs_calling_mid_call_raw_media_stats,tenant:tf,properties:g})}}function cloneReport(){return{transform:g=>M.cloneDeep(g)}}function transformStatsReport(g){return{transform:f=>([[f.audio.send,g.audio.send],[f.audio.receive,g.audio.receive],[f.video.send,g.video.send],[f.video.receive,g.video.receive],[f.screenShare.send,g.screenShare.send],[f.screenShare.receive,g.screenShare.receive],[f.dataChannel,g.dataChannel],[f.transports,g.transports],[f.info,g.info]].forEach((g=>{const f=g[0],S=g[1];M.forEach(S,((g,S)=>{!0!==g.disabled&&M.forEach(f,(f=>{let v=f[g.source];void 0!==v&&(void 0!==g.multiplier&&"number"==typeof v&&(v*=g.multiplier),g.integer&&(v=M.toInteger(v)),f[S]=v)}))}))})),f)}}function blockMetrics(g){const f=["audio.send","audio.receive","video.send","video.receive","screenShare.send","screenShare.receive","dataChannel","transports","info"];return{transform:S=>(M.forEach(f,(f=>{const v=M.get(S,f),C=M.get(g,f,[]);M.forEach(v,(g=>{C.forEach((f=>{"id"!==f&&delete g[f]}))}))})),S)}}function filterMetricsByRangeLimit(g,f){return{transform:S=>{const v=S.metadata?.delayRatio,C=g>0&&void 0!==v&&v>g;return M.forEach(f,((g,f)=>{const v=M.get(S,f);M.forEach(v,(f=>{M.forEach(g,((g,S)=>{if(C)delete f[S];else{const v=f[S];(void 0!==g.max&&v>g.max||void 0!==g.min&&v<g.min||M.isNaN(v))&&delete f[S]}}))}))})),S}}}const b_={codecName:{},bitrate:{aggregable:!0},jitterInMs:{aggregable:!0},packets:{},packetsPerSecond:{aggregable:!0},packetsLost:{},packetsLostPerSecond:{aggregable:!0},rttInMs:{aggregable:!0},frameRateInput:{aggregable:!0},frameWidthInput:{aggregable:!0},frameHeightInput:{aggregable:!0},framesEncoded:{},frameRateEncoded:{aggregable:!0},framesSent:{},frameRateSent:{aggregable:!0},frameWidthSent:{aggregable:!0},frameHeightSent:{aggregable:!0},keyFramesEncoded:{},transportId:{}},A_={codecName:{},bitrate:{aggregable:!0},jitterInMs:{aggregable:!0},packets:{},packetsPerSecond:{aggregable:!0},packetsLost:{},packetsLostPerSecond:{aggregable:!0},rttInMs:{aggregable:!0},streamId:{},jitterBufferDelayInMs:{aggregable:!0},frameRateDecoded:{aggregable:!0},frameRateReceived:{aggregable:!0},frameWidthReceived:{aggregable:!0},frameHeightReceived:{aggregable:!0},longestFreezeDurationInMs:{},totalFreezeDurationInMs:{},framesReceived:{},framesDropped:{},framesDecoded:{},keyFramesDecoded:{},transportId:{}},P_={audio:{send:{codecName:{},bitrate:{aggregable:!0},jitterInMs:{aggregable:!0},packets:{},packetsPerSecond:{aggregable:!0},packetsLost:{},packetsLostPerSecond:{aggregable:!0},rttInMs:{aggregable:!0},audioInputLevel:{aggregable:!0},transportId:{}},receive:{codecName:{},bitrate:{aggregable:!0},jitterInMs:{aggregable:!0},packets:{},packetsPerSecond:{aggregable:!0},packetsLost:{},packetsLostPerSecond:{aggregable:!0},rttInMs:{aggregable:!0},jitterBufferDelayInMs:{aggregable:!0},audioOutputLevel:{aggregable:!0},healedRatio:{aggregable:!0},transportId:{}}},video:{send:b_,receive:A_},screenShare:{send:b_,receive:A_},dataChannel:{incomingBitrate:{aggregable:!0},outgoingBitrate:{aggregable:!0},messagesSentPerSecond:{aggregable:!0},messagesReceivedPerSecond:{aggregable:!0}},transports:{rttInMs:{aggregable:!0},availableIncomingBitrate:{aggregable:!0},availableOutgoingBitrate:{aggregable:!0}},info:{}},R_={codecName:{raw_data_reduction:!0},packets:{raw_data_reduction:!0},packetsLost:{raw_data_reduction:!0},framesEncoded:{raw_data_reduction:!0},framesSent:{raw_data_reduction:!0},keyFramesEncoded:{raw_data_reduction:!0},pairRttInMs:{aggregable:!0},availableBitrate:{aggregable:!0},transportId:{skip:!0},groupId:{raw_data_reduction:!0}},M_={codecName:{raw_data_reduction:!0},streamId:{raw_data_reduction:!0},packets:{raw_data_reduction:!0},packetsLost:{raw_data_reduction:!0},jitterBufferDelayInMs:{output_key:"jitterBufferInMs"},longestFreezeDurationInMs:{skip:!0},totalFreezeDurationInMs:{raw_data_reduction:!0},framesReceived:{raw_data_reduction:!0},framesDropped:{raw_data_reduction:!0},framesDecoded:{raw_data_reduction:!0},keyFramesDecoded:{raw_data_reduction:!0},pairRttInMs:{aggregable:!0},availableBitrate:{aggregable:!0},transportId:{skip:!0}},w_={audio:{send:{codecName:{raw_data_reduction:!0},packets:{raw_data_reduction:!0},packetsLost:{raw_data_reduction:!0},pairRttInMs:{aggregable:!0},availableBitrate:{aggregable:!0},transportId:{skip:!0}},receive:{codecName:{raw_data_reduction:!0},packets:{raw_data_reduction:!0},packetsLost:{raw_data_reduction:!0},jitterBufferDelayInMs:{output_key:"jitterBufferInMs"},pairRttInMs:{aggregable:!0},availableBitrate:{aggregable:!0},transportId:{skip:!0}}},video:{send:R_,receive:M_},screenShare:{send:R_,receive:M_},dataChannel:{state:{raw_data_reduction:!0},dataChannelIdentifier:{raw_data_reduction:!0},messagesSent:{raw_data_reduction:!0},bytesSent:{raw_data_reduction:!0},messagesReceived:{raw_data_reduction:!0},bytesReceived:{raw_data_reduction:!0}},transports:{candidateType:{events:!0},relayProtocol:{events:!0}},info:{networkInfoDownlink:{aggregable:!0},networkInfoRttInMs:{aggregable:!0},totalJSHeapSize:{aggregable:!0},usedJSHeapSize:{aggregable:!0},jsHeapSizeLimit:{aggregable:!0},jsSize:{aggregable:!0},sharedSize:{aggregable:!0},domSize:{aggregable:!0},batteryCharging:{aggregable:!0},batteryLevel:{aggregable:!0},cpuPressureLevel:{aggregable:!0},audioLeak:{aggregable:!0},videoLeak:{aggregable:!0}}},O_={multiplier:1e3,integer:!0,source:"jitter"},D_={multiplier:1e3,integer:!0,source:"rtt"},N_={integer:!0,source:"jitterBufferMs"},k_={jitterInMs:O_,rttInMs:D_},L_={jitterInMs:O_,rttInMs:D_,jitterBufferDelayInMs:N_,streamId:{source:"msi"},longestFreezeDurationInMs:{multiplier:1e3,integer:!0,source:"longestFreezeDuration"},totalFreezeDurationInMs:{multiplier:1e3,integer:!0,source:"totalFreezeDuration"}},F_={audio:{send:{jitterInMs:O_,rttInMs:D_,audioInputLevel:{multiplier:65536,integer:!0,source:"audioLevel"}},receive:{jitterInMs:O_,rttInMs:D_,jitterBufferDelayInMs:N_,audioOutputLevel:{multiplier:65536,integer:!0,source:"audioLevel"}}},video:{send:k_,receive:L_},screenShare:{send:k_,receive:L_},dataChannel:{incomingBitrate:{source:"recvBitrate"},outgoingBitrate:{source:"sendBitrate"}},transports:{rttInMs:D_},info:{networkInfoDownlink:{multiplier:1e3,integer:!0,source:"networkInfoDownlink"}}};class MediaStatsManager{constructor(g,f,S,v){this._tsCall=g,this._call=f,this._logger=S,this._disposed=!1;const C=getAcsEcsConfig();this._config=C.mediaStats,this._statsPoller=new MediaStatsPoller(f,this._logger,C);const _=[transformStatsReport(M.merge(M.cloneDeep(F_),this._config.transformMetrics))];this._config.timerThrottlingFilter.enabled&&_.push(filterMetricsByRangeLimit(this._config.timerThrottlingFilter.delayRatio,this._config.timerThrottlingFilter.filterRange)),this._mediaStatsSourceNode=new MediaStatsReportSourceNode(_);const T=this._config.activeState;this._isCallActive=T.includes(this._tsCall.state),this._callStateChangedHandle=this._tsCall.on("callStateChanged",(()=>{const g=T.includes(this._tsCall.state);this._isCallActive!==g&&(this._isCallActive=g,g?this._mediaStatsSourceNode.resume():this._mediaStatsSourceNode.pause())}));const I=this._config.blockMetrics;if(Object.keys(I).length>0){const g=new MediaStatsReportFilterNode([cloneReport(),blockMetrics(I)]);this._mediaStatsSourceNode.addSink(g),this._collectorsSourceNode=g}else this._collectorsSourceNode=this._mediaStatsSourceNode;const b=C.telemetry.mediaStatsConfig;if(b.enabled){const g=new MediaStatsTelemetryLogger(this._tsCall,this._call,v,C),f=M.merge(M.cloneDeep(P_),w_,b.metricsProperties),S=new TelemetryCollector(this._logger,{aggregationInterval:b.aggregationInterval,dataPointsPerAggregation:b.dataPointsPerAggregation,metricsPropertics:f});S.on("data",(f=>g.log(f))),this._mediaStatsSourceNode.addSink(S)}this._isCallActive?this._mediaStatsSourceNode.resume():this._mediaStatsSourceNode.pause(),this._dataEventListener=g=>{this._mediaStatsSourceNode.onReport(g)},this._statsPoller.on("data",this._dataEventListener)}createCollector(g){if(this._disposed)throw new CallingCommunicationError({defaultError:D.FEATURES.MEDIA_STATS.DISPOSED});const f=this._config,S=new MediaStatsCollectorImpl(this._logger,{aggregationInterval:g?.aggregationInterval??f.aggregationInterval,dataPointsPerAggregation:g?.dataPointsPerAggregation??f.dataPointsPerAggregation,metricsPropertics:P_});return this._collectorsSourceNode.addSink(S),S}dispose(){this._disposed||(this._disposed=!0,this._statsPoller.off("data",this._dataEventListener),this._statsPoller.dispose(),this._mediaStatsSourceNode.stop(),this._callStateChangedHandle.dispose())}}class MediaStatsCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g)}get name(){return this._sendFeatureUsage("name",gE.getter),"MediaStats"}createCollector(g){this._sendFeatureUsage("createCollector",gE.attempt);const f=this._statsManager.createCollector(g);return this._sendFeatureUsage("creaetCollector",gE.success),f}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._call=g.call,this._statsManager=new MediaStatsManager(g.tsCall,this._call,this._logger,this._telemetryLogManager),this._sendFeatureUsage("initialize",gE.initialize)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"MediaStats",featureType:"Call",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._statsManager.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}}var x_,U_;(x_=g.RecordingState||(g.RecordingState={}))[x_.None=0]="None",x_[x_.Started=1]="Started",x_[x_.Paused=2]="Paused",x_[x_.Ended=3]="Ended";class RecordingCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._callInfo=g.callInfo,this._impl=new RecordingCallImplOverTsCall(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",gE.getter),"Recording"}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._call=g.call,this._impl.initialize(g.tsCall,f,this._callInfo,this._call),this._sendFeatureUsage("initialize",gE.initialize)}get isRecordingActive(){return this._sendFeatureUsage("isRecordingActive",gE.getter),this._impl.isRecordingActive}get recordings(){return this._sendFeatureUsage("recordings",gE.getter),this._impl.recordings}on(g,f){if("isRecordingActiveChanged"!==g&&"recordingsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.RECORDING.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){if("isRecordingActiveChanged"!==g&&"recordingsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.RECORDING.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._sendFeatureUsage(g,gE.unsubscribe),this.eventEmitter.off(g,f)}get isTeamsConsentRequired(){return this._sendFeatureUsage("isTeamsConsentRequired",gE.getter),this._impl.isTeamsConsentRequired}grantTeamsConsent(){return this._sendFeatureUsage("ConsentForRecording",gE.attempt),this._impl.grantTeamsConsent().then((()=>{this._sendFeatureUsage("ConsentForRecording",gE.success)})).catch((g=>{throw this._sendFeatureUsage("ConsentForRecording",gE.failure,g),g}))}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}_sendFeatureUsage(g,f,S){let v=S?extractCommunicationServicesErrorForTelemetry(S):void 0;sendCallFeatureUsageTelemetry({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Recording",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:v},this._telemetryLogManager,this._logger)}}class RecordingCallImplOverTsCall{constructor(g){this._eventEmitter=g,this._recordingBots=new Map,this._recordingBotChangedSubs=new WeakMap,this._recordingInitiatorMap=new Map,this._isRecordingActive=!1,this.grantTeamsConsent=async()=>(this._logger.info("Attempting to set consent for recording"),this._call.explicitConsentStateImp.consent(this._callInfo).catch((g=>{throw this._logger.error("Consent failure to set publish state for user"),handlePublishStateFailure(g,D.FEATURES.RECORDING.RECORDING_CONSENT_FAILURE)}))),this._updateIsCallRecorded=g=>this._isRecordingActive!==g&&(this._isRecordingActive=g,this._logger.info(`Updating isCallRecorded to ${g}`),!0),this._handleRecordingBotAdded=g=>{const handleRecordingBotChanged=()=>{let f,S=!1,v=!1;if(this._hasRecordingState(g)){if(this._recordingBots.has(g.id)){let S=this._getRecordingBotEndpoint(g);if(f=this._recordingBots.get(g.id),S&&f){f.endpoint=S;let g=S.userId?this._recordingInitiatorMap.get(S.userId):void 0;v=f.recordingInfo?.update(S,g)??!1}}else f=this._getRecordingBotInfo(g),f&&(this._logger.info("Adding recording bot"),this._recordingBots.set(g.id,f),S=!0);this._sendEvents(v?[f]:void 0,S?[f]:void 0,void 0,this._updateIsCallRecorded(this._isRecordingEnabled()))}};handleRecordingBotChanged(),this._recordingBotChangedSubs.set(g,g.changed(handleRecordingBotChanged))},this._handleRecordingBotRemoved=g=>{let f=this._recordingBots.get(g.id);this._recordingBots.delete(g.id),this._recordingBotChangedSubs.get(g)?.dispose(),this._recordingBotChangedSubs.delete(g),this._logger.info(`Updating recordingState to ${f?.endpoint?.state}`),f?.recordingInfo?.dispose(),this._sendEvents([f],void 0,[f],this._updateIsCallRecorded(this._isRecordingEnabled()))},this._sendEvents=(g,f,S,v)=>{g&&g.forEach((g=>g?.recordingInfo?.sendRecordingStateChanged()));let C=!!f&&f.length>0,_=!!S&&S.length>0;(C||_)&&this._eventEmitter.emit("recordingsUpdated",{added:this._getRecordingInfos(f),removed:this._getRecordingInfos(S)}),v&&this._eventEmitter.emit("isRecordingActiveChanged")},this._hasRecordingState=g=>g?.endpoints?.endpointDetails?.some((g=>!!g?.endpointMetadata?.__platform?.recording?.compliance?.state||!!g?.endpointMetadata?.processingModes?.recording?.state))??!1,this._getRecordingInfos=g=>{if(g)return g.map((g=>g?.recordingInfo)).filter((g=>!!g))},this._isRecordingEnabled=()=>{let g=!1;try{this._recordingBots.forEach((f=>{g||(g="Active"===f?.endpoint?.state)}))}catch(g){this._logger.info("Unable to read recording state: ",g)}return g},this._getRecordingInfoImpl=g=>{if(null==g)return;if("Active"!==g.state&&"Inactive"!==g.state)return;let f;return void 0!==g.userId&&(f=this._recordingInitiatorMap.get(g.userId)),new RecordingInfoImpl(g.state,this._eventEmitter,f)},this._getRecordingBotInfo=g=>{let f=this._getRecordingBotEndpoint(g);return f?{endpoint:f,recordingInfo:this._getRecordingInfoImpl(f)}:void 0},this._getRecordingBotEndpoint=g=>{let f=g.endpoints?.endpointDetails.map((g=>{let f=g?.endpointMetadata?.__platform?.recording?.compliance?.state,S=g?.endpointMetadata?.__platform?.recording?.compliance?.userId,v=g?.endpointMetadata?.processingModes?.recording?.state,C=g?.endpointMetadata?.processingModes?.recording?.userId;if(f||v)return{state:f??v,userId:S??C}})).filter((g=>null!=g));if(f&&0!=f.length)return f.length>1&&this._logger.log(`Unexpected: multiple recording endpoints: ${f?.map((g=>g?.state??"undefined")).join(", ")}`),f[0]}}get isRecordingActive(){return this._isRecordingActive}get recordings(){return Array.from(this._recordingBots.values()).map((g=>g?.recordingInfo)).filter((g=>!!g))}initialize(g,f,S,v){this._logger=f.createChild((()=>`RecordingFeature::Call(id='${g.callId}', state='${g.state}')`)),this._callInfo=S,this._call=v,g.on("callStateChanged",(async()=>{3===g.state&&this._initInitiatorMap(g)})),g.participants.forEach((g=>{isCallingApplication(g.id)&&this._handleRecordingBotAdded(g)})),g.on("participantAdded",(async g=>{isCallingApplication(g.id)?this._handleRecordingBotAdded(g):void 0===g||this._recordingInitiatorMap.has(g.id)||this._recordingInitiatorMap.set(g.id,g.displayName)})),g.on("participantRemoved",(async g=>{isCallingApplication(g.id)?this._handleRecordingBotRemoved(g):void 0!==g&&this._recordingInitiatorMap.has(g.id)&&this._recordingInitiatorMap.delete(g.id)})),g.on("participantUpdated",(async g=>{void 0!==g&&this._recordingInitiatorMap.has(g.id)&&this._recordingInitiatorMap.set(g.id,g.displayName)}))}get isTeamsConsentRequired(){return this._call.explicitConsentStateImp.isConsentRequiredInCall()}dispose(){let g=this._updateIsCallRecorded(!1),f=Array.from(this._recordingBots.values());f.forEach((g=>g?.recordingInfo?.dispose())),this._sendEvents(void 0,void 0,f,g)}_initInitiatorMap(g){const{participants:f}=g;[...f].forEach((g=>{isCallingApplication(g.id)||this._recordingInitiatorMap.set(g.id,g.displayName)}))}}class RecordingInfoImpl{constructor(g,f,S){this.state=this.getRecordingState(g),this._eventEmitter=f,this.displayName=S}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}update(g,f){if(null==g)return!1;let S=this.getRecordingState(g.state);return S!=this.state&&(this.state=S,void 0!==f&&(this.displayName=f),!0)}dispose(){this.state=g.RecordingState.Ended}sendRecordingStateChanged(){this._eventEmitter.emit("recordingStateChanged")}getRecordingState(f){let S=g.RecordingState.None;switch(f?.toLocaleLowerCase()){case"active":S=g.RecordingState.Started;break;case"inactive":S=g.RecordingState.Paused;break;default:S=g.RecordingState.None}return S}}(U_=g.LocalRecordingState||(g.LocalRecordingState={}))[U_.None=0]="None",U_[U_.Started=1]="Started",U_[U_.Ended=2]="Ended";const V_={ACTIVE:"active",INACTIVE:"inactive"};class LocalRecordingCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new LocalRecordingCallImplOverTsCall(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",gE.getter),"LocalRecording"}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._call=g.call,this._impl.initialize(g.tsCall,g.telemetryLogManager,f),this._sendFeatureUsage("initialize",gE.initialize)}get isRecordingActive(){return this._sendFeatureUsage("isRecordingActive",gE.getter),this._impl.isRecordingActive}get recordings(){return this._sendFeatureUsage("recordings",gE.getter),this._impl.recordings}on(g,f){if("isLocalRecordingActiveChanged"!==g&&"localRecordingsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.RECORDING.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){if("isLocalRecordingActiveChanged"!==g&&"localRecordingsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.RECORDING.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._sendFeatureUsage(g,gE.unsubscribe),this.eventEmitter.off(g,f)}_sendFeatureUsage(g,f,S){let v=S?{code:S?.code||U,subCode:S?.subCode||0,failureReason:S?.message||""}:void 0;sendCallFeatureUsageTelemetry({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"LocalRecording",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:v},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}}class LocalRecordingCallImplOverTsCall{constructor(g){this._eventEmitter=g,this._localRecordingInitiators=new Map,this._sendEvents=(g,f,S)=>{let v=!!g&&g.length>0,C=!!f&&f.length>0;(v||C)&&this._eventEmitter.emit("localRecordingsUpdated",{added:g,removed:f}),S&&this._eventEmitter.emit("isLocalRecordingActiveChanged")},this._isEnabled=getAcsEcsConfig().calling.localRecording.enabled,this._supportedConversationTypes=getAcsEcsConfig().calling.localRecording.supportedConversationTypes}get isRecordingActive(){return this._localRecordingInitiators.size>0}get recordings(){return Array.from(this._localRecordingInitiators.values())}initialize(g,f,S){if(this._logger=S.createChild((()=>`LocalRecordingFeature::Call(id='${g.callId}', state='${g.state}')`)),!this._isEnabled){const g="Local Recording feature is is disabled",f=new CallingCommunicationError({defaultError:D.FEATURES.LOCAL_RECORDING.DISABLED});throw this._logger.error(g),f}g.on("callStateChanged",(async()=>{if(3===g.state){if(!this._supportedConversationTypes.includes(g.conversationType)){const g="Local Recording feature is only available in meetings",f=new CallingCommunicationError({defaultError:D.FEATURES.LOCAL_RECORDING.ONLY_AVAILABLE_IN_MEETINGS});throw this._logger.error(g),f}this.initLocalRecordingStatus(g)}})),g.on("participantUpdated",(f=>this._onParticipantUpdatedEvent(g,f,f.endpoints?.endpointDetails)))}dispose(){let g=this._localRecordingInitiators.size>0,f=Array.from(this._localRecordingInitiators.values());f.forEach((g=>g?.dispose())),g&&(g=0==this._localRecordingInitiators.size),this._sendEvents(void 0,f,g)}hasOngoingLocalRecording(g){return g?.some((g=>(g.propertyBag?.localRecording?.value?.state||"")===V_.ACTIVE))||!1}initLocalRecordingStatus(g){const{participants:f}=g,S=[...f];this._localRecordingInitiators=new Map(S.filter((g=>this.hasOngoingLocalRecording(g.endpoints?.endpointDetails))).map((g=>[g.id,this._getLocalRecordingInfo(g)])))}_onParticipantUpdatedEvent(g,f,S){f?isCallingApplication(f.id)||(this.hasOngoingLocalRecording(S)?this._tryAddLocalRecordingInitiator(g,f):this._tryRemoveLocalRecordingInitiator(g,f)):this._logger.error(`Empty participant, skip update event processing. CallId: ${g.callId}`)}_tryAddLocalRecordingInitiator(g,f){const{callId:S}=g;if(!this._localRecordingInitiators.has(f.id)){this._logger.info(`Add local recording participant: ${f.id}, callId: ${S}`);let g=this._getLocalRecordingInfo(f);this._localRecordingInitiators.set(f.id,g),this._sendEvents([g],void 0,1==this._localRecordingInitiators.size)}}_tryRemoveLocalRecordingInitiator(g,f){const{callId:S}=g;if(this._localRecordingInitiators.has(f.id)){this._logger.info(`Remove local recording participant: ${f.id}, callId: ${S}`);let g=this._localRecordingInitiators.get(f.id);g.update(V_.INACTIVE),this._localRecordingInitiators.delete(f.id),this._sendEvents(void 0,[g],0==this._localRecordingInitiators.size)}}_getLocalRecordingInfo(g){let f=g.displayName;return new LocalRecordingInfoImpl(V_.ACTIVE,f)}}class LocalRecordingInfoImpl{constructor(g,f){this.state=this.getRecordingState(g),this.displayName=f}update(g){let f=this.getRecordingState(g);return f!=this.state&&(this.state=f,!0)}dispose(){this.state=g.LocalRecordingState.Ended}getRecordingState(f){let S=g.LocalRecordingState.None;switch(f?.toLocaleLowerCase()){case"active":S=g.LocalRecordingState.Started;break;case"inactive":S=g.LocalRecordingState.Ended;break;default:S=g.LocalRecordingState.None}return S}}class TranscriptionCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new TranscriptionCallImplOverTsCall(this.eventEmitter),this._callInfo=g.callInfo}get name(){return this._sendFeatureUsage("name",gE.getter),"Transcription"}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._call=g.call,this._impl.initialize(g.tsCall,f,this._callInfo,this._call),this._sendFeatureUsage("initialize",gE.initialize)}get isTranscriptionActive(){return this._sendFeatureUsage("isTranscriptionActive",gE.getter),this._impl.isTranscriptionActive}get isTeamsConsentRequired(){return this._sendFeatureUsage("isTeamsConsentRequired",gE.getter),this._impl.isTeamsConsentRequired}grantTeamsConsent(){return this._sendFeatureUsage("ConsentForTranscription",gE.attempt),this._impl.grantTeamsConsent().then((()=>{this._sendFeatureUsage("ConsentForTranscription",gE.success)})).catch((g=>{throw this._sendFeatureUsage("ConsentForTranscription",gE.failure,g),g}))}on(g,f){this._sendFeatureUsage("isTranscriptionActiveChanged",gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){this._sendFeatureUsage("isTranscriptionActiveChanged",gE.unsubscribe),this.eventEmitter.off(g,f)}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}_sendFeatureUsage(g,f,S){let v=S?extractCommunicationServicesErrorForTelemetry(S):void 0;sendCallFeatureUsageTelemetry({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Transcription",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:v},this._telemetryLogManager,this._logger)}}class TranscriptionCallImplOverTsCall{constructor(g){this._eventEmitter=g,this._botChangedSubs=new Map,this._isTranscriptionActive=!1,this.grantTeamsConsent=async()=>(this._logger.info("Attempting to set consent for transcription"),this._call.explicitConsentStateImp.consent(this._callInfo).catch((g=>{throw this._logger.error("Consent failure to set publish state for user"),handlePublishStateFailure(g,D.FEATURES.TRANSCRIPTION.TRANSCRIPTION_CONSENT_FAILURE)}))),this._updateIsTranscriptionActive=g=>{this._isTranscriptionActive!==g&&(this._isTranscriptionActive=g,this._logger.info(`Updating isTranscriptionActive to ${g}`),this._eventEmitter.emit("isTranscriptionActiveChanged"))},this._isCallingApplication=g=>isCallingApplication(g.id),this._handleBotRemoved=g=>{this._botChangedSubs.get(g)?.dispose(),this._botChangedSubs.delete(g),this._checkIfAbotIsTranscribing()},this._handleBotAdded=g=>{this._botChangedSubs.set(g,g.changed(this._checkIfAbotIsTranscribing)),this._checkIfAbotIsTranscribing()},this._checkIfAbotIsTranscribing=()=>{try{Array.from(this._botChangedSubs.keys()).find((g=>g.endpoints?.endpointDetails?.find((g=>"Active"===g?.endpointMetadata?.processingModes?.realTimeTranscript?.state))))?this._updateIsTranscriptionActive(!0):this._updateIsTranscriptionActive(!1)}catch(g){this._logger.warn("Unable to read transcription state: ",g)}}}get isTranscriptionActive(){return this._isTranscriptionActive}initialize(g,f,S,v){this._logger=f.createChild((()=>`TranscriptionFeature::Call(id='${g.callId}', state='${g.state}')`)),this._callInfo=S,this._call=v,g.on("participantAdded",(g=>{this._isCallingApplication(g)&&this._handleBotAdded(g)})),g.participants.forEach((g=>{this._isCallingApplication(g)&&this._handleBotAdded(g)})),g.on("participantRemoved",(g=>{this._isCallingApplication(g)&&this._handleBotRemoved(g)}))}get isTeamsConsentRequired(){return this._call.explicitConsentStateImp.isConsentRequiredInCall()}dispose(){this._updateIsTranscriptionActive(!1),this._botChangedSubs.forEach(((g,f)=>g.dispose())),this._botChangedSubs.clear()}}class TransferImpl{get state(){return this._state}get error(){return this._error}constructor(g,f,S=!0){return this._eventEmitter=new LE.EventEmitter,this._lastTsTransferState=0,this._getTransferEndReason=(g,f=0)=>{let S=f,v=0,C=g||"Unknown";this._tsCall&&(S=this._tsCall.transferDiagnosticsInfo&&this._tsCall.transferDiagnosticsInfo.callControllerCode||f,v=this._tsCall.transferDiagnosticsInfo&&this._tsCall.transferDiagnosticsInfo?.callControllerSubCode||0,C=convertTerminatedReasonToString(this._tsCall.terminatedReason));const _={code:S,subCode:v};return this._logger[0===S?"info":"error"](`Transfer end reason=${C}, code=${S}, subCode=${v}`),_},this._state="None",this._logger=f.createChild((()=>"Transfer")),this._logger.log("created"),this._tsCall=g,S?4!==g.state?(this._logger.error("Transfer end reason= call must be on hold before transfer"),this._error={code:F},void this.setTransferState(4)):(this._lastTsTransferState=this._tsCall.transferState,this.setTransferState(this._tsCall.transferState),void this._tsCall.changed((()=>{this._tsCall.transferState!==this._lastTsTransferState&&(this._logger.log(`tsCall transfer state changed=${this._tsCall.transferState}`),this._lastTsTransferState=this._tsCall.transferState,this.setTransferState(this._tsCall.transferState))}))):(this._logger.error("Transfer end reason= call was not found with this callId"),this._error={code:F},void this.setTransferState(4))}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}setTransferState(g){let f,S;const v={0:"None",1:"Transferring",2:"Transferring",3:"Transferred",4:"Failed"};v[g]?(f=v[g],"Failed"===f&&(S=this._getTransferEndReason(),this._error=S),this._logger.log(`Mapped ts transfer state:[${g}] to [${f}]`),this._setTransferState(f)):this._logger.warn(`unable to map tsCall state=[${g}] to transfer state`)}_setTransferState(g){g!==this._state&&(this._logger.log(`transfer state changed [${this._state}]=>[${this.state}]`),this._state=g,this._eventEmitter.emit("stateChanged"))}}class NetworkInfoImpl{constructor(){this.CAUSE_ID_TO_NETWORK_INFO={}}static getInstance(){return this.instance||(this.instance=new NetworkInfoImpl),this.instance}deleteNetworkInfo(g){delete this.CAUSE_ID_TO_NETWORK_INFO[g]}ifCauseIdExistsRemoveNetworkInfo(g){return this.CAUSE_ID_TO_NETWORK_INFO[g]&&0===this.CAUSE_ID_TO_NETWORK_INFO[g].length?!!this.getRemoveCauseIdToNetworkInfo(g):!!this.CAUSE_ID_TO_NETWORK_INFO[g]}getRemoveCauseIdToNetworkInfo(g){if(!getAcsEcsConfig().telemetry.sendNetworkInfo)return;const f=this.CAUSE_ID_TO_NETWORK_INFO[g];return f&&this.deleteNetworkInfo(g),f}setCauseIdToNetworkInfo(g,f){Object.keys(this.CAUSE_ID_TO_NETWORK_INFO).length>100&&(this.CAUSE_ID_TO_NETWORK_INFO={}),f?this.CAUSE_ID_TO_NETWORK_INFO[g]?this.CAUSE_ID_TO_NETWORK_INFO[g].push({url:f.url,statusCode:f.statusCode,start:f.start,end:f.end,deltaTimeInMs:f.deltaTimeInMs,causeId:f.causeId}):this.CAUSE_ID_TO_NETWORK_INFO[g]=[{url:f.url,statusCode:f.statusCode,start:f.start,end:f.end,deltaTimeInMs:f.deltaTimeInMs,causeId:f.causeId}]:this.CAUSE_ID_TO_NETWORK_INFO[g]=[]}}NetworkInfoImpl.instance=null;const B_=NetworkInfoImpl.getInstance();var __decorate$1=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$1=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class TransferCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new TransferCallImplOverTsCall(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",gE.getter),"Transfer"}transfer(g,f){return this._impl.transfer(g,f)}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._call=g.call,this._impl.initialize(g.tsCall,g.callAgent,g.telemetryLogManager,f),this._sendFeatureUsage("initialize",gE.initialize)}on(g,f){this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Transfer",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}}class TransferCallImplOverTsCall{constructor(g){this._eventEmitter=g,this._autoAccept=getAcsEcsConfig().calling.transfer.autoAccept}initialize(g,f,S,v){this._logger=v.createChild((()=>`TransferFeature::Call(id='${g.callId}', state='${g.state}')`)),this._telemetryLogManager=S,this._tsCall=g,this._callAgent=f,g.on("transferRequested",(async g=>{try{const f=this.getTransferRequestPayload(g);if(this._autoAccept){const g=await f.accept();this._eventEmitter.emit("transferAccepted",{targetCall:g})}}catch(g){this._logger.error(`Failed to handle transferRequested event: ${g?.message??"unknown error"}`)}}))}transfer(g,f){let S="safe";if(g.targetCallId?S="consultative":g.targetParticipantVoicemail&&(S="voicemail"),this._sendFeatureUsage(S,gE.attempt,f),!this.isTransferable(this._tsCall))throw this._sendFeatureUsage(S,gE.failure,f),new CallingCommunicationError({defaultError:D.FEATURES.TRANSFER.UNSUPPORTED_CALL_TYPE});const v=w.generateCauseId();B_.setCauseIdToNetworkInfo(v);try{let C;switch(S){case"safe":return C=this.transferToParticipant(g.targetParticipant,v,f),this._sendFeatureUsage(S,gE.success,f,B_.getRemoveCauseIdToNetworkInfo(v)),C;case"consultative":return C=this.transferToCall(g.targetCallId,v,f),this._sendFeatureUsage(S,gE.success,f,B_.getRemoveCauseIdToNetworkInfo(v)),C;case"voicemail":return C=this.transferToParticipantVoicemail(g.targetParticipantVoicemail,f),this._sendFeatureUsage(S,gE.success,f),C}}catch(g){if(this._sendFeatureUsage(S,gE.failure,f,B_.getRemoveCauseIdToNetworkInfo(v)),g instanceof CallingCommunicationError)throw g}throw this._sendFeatureUsage(S,gE.failure,f),new CallingCommunicationError({defaultError:D.FEATURES.TRANSFER.TARGET_NOT_RECOGNIZED})}getTransferRequestPayload(g){const f=constructIdentifierKindFromMri(g.transferContext.targetMri);if("communicationUser"===f.kind||"phoneNumber"===f.kind||"microsoftTeamsUser"===f.kind||"unknown"===f.kind||"microsoftTeamsApp"===f.kind){let f=!1;const S={accept:async()=>{let S;try{if(S=await this._callAgent.createTransferTargetCall(g.transferContext),f)return this._logger.info("Transfer accept was called when transfer action is already in progress."),S;f=!0;const v={threadId:"",messageId:void 0,transferContext:g.transferContext,mediaPeerType:0};S.startCallInternal(void 0,!1,void 0,v).catch((S=>{f=!1,g.onCompleted(7),this._logger.error("Transfer to target failed at call start")}));const callReplacementCallBack=()=>{if(f)switch(S.state){case"Connected":f=!1,g.onCompleted(1),this._logger.info("Transfer Completed"),S.off("stateChanged",(()=>{}));break;case"Disconnected":f=!1,g.onCompleted(7),this._logger.info(`Transfer call disconnected. \n                                            code = ${S.callEndReason?.code} \n                                            subcode = ${S.callEndReason?.subCode} \n                                            message = ${S.callEndReason?.message} \n                                            result categories = ${S.callEndReason?.resultCategories}`),S.off("stateChanged",(()=>{}))}};return S.on("stateChanged",callReplacementCallBack),S}catch(S){throw f=!1,g.onCompleted(7),this._logger.error("Transfer to target failed at call create"),new CallingCommunicationError({defaultError:D.FEATURES.TRANSFER.TRANSFER_TO_TARGET_FAILED,originalError:S})}}};return S}throw new CallingCommunicationError({defaultError:D.FEATURES.TRANSFER.INVALID_TARGET_TYPE,defaultErrorMessageArgs:[f]})}isTransferable(g){return 1===g.callType||g.participants.filter((g=>!isCallingApplication(g.id))).length<=2}transferToParticipant(g,f,S){const v=getMriFromIdentifier(g);let C;S&&(C={disableForwardingAndUnanswered:S.disableForwardingAndUnanswered,clientTransferContext:{customContext:processCustomContext(S)}}),4===this._tsCall.state&&this._tsCall.callSafeTransfer(v,f,C);return new TransferImpl(this._tsCall,this._logger)}transferToCall(g,f,S){const v=this._callAgent.getCallByCallId(g);if(v&&!this.isTransferable(v))throw new CallingCommunicationError({defaultError:D.FEATURES.TRANSFER.UNSUPPORTED_CALL_TYPE});let C;S&&(C={clientTransferContext:{customContext:processCustomContext(S)}}),v&&4===this._tsCall.state&&this._tsCall.callConsultativeTransfer(v,f,void 0,C);return new TransferImpl(this._tsCall,this._logger,!!v)}transferToParticipantVoicemail(g,f){const S=getMriFromIdentifier(g);if(4===this._tsCall.state){const g={transferTargetMri:S};this._tsCall.transferCallToVoicemail(g)}return new TransferImpl(this._tsCall,this._logger)}_sendFeatureUsage(g,f,S,v){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"Transfer",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:{transferConstraint:{userToUserPresent:!!S?.customContext?.userToUser,xHeadersPresent:!!S?.customContext?.xHeaders&&S.customContext.xHeaders.length>0,type:"safe"===g?"participant":"consultative"===g?"call":"voicemail"}},networkInfo:v||[]},this._telemetryLogManager,this._logger)}dispose(){}}__decorate$1([syncOperation(VE.Transfer),__metadata$1("design:type",Function),__metadata$1("design:paramtypes",[Object,Object]),__metadata$1("design:returntype",Object)],TransferCallImplOverTsCall.prototype,"transfer",null);class VideoDeviceInfoImpl{constructor(g,f,S,v){this._name=g,this._id=f,this._deviceType=S,this._deviceManager=v}get name(){return this._name}setName(g){this._name=g}get id(){return this._id}setId(g){this._id=g}get deviceType(){return this._deviceType}setDeviceType(g){this._deviceType=g}get deviceManager(){return this._deviceManager}}function loggerProperty(g,f){Reflect.defineMetadata(G,f,g)}function Deque(g){if(this._capacity=getCapacity(g),this._length=0,this._front=0,H_(g)){for(var f=g.length,S=0;S<f;++S)this[S]=g[S];this._length=f}}Deque.prototype.toArray=function Deque$toArray(){for(var g=this._length,f=new Array(g),S=this._front,v=this._capacity,C=0;C<g;++C)f[C]=this[S+C&v-1];return f},Deque.prototype.push=function Deque$push(g){var f=arguments.length,S=this._length;if(f>1){var v=this._capacity;if(S+f>v){for(var C=0;C<f;++C){this._checkCapacity(S+1),this[_=this._front+S&this._capacity-1]=arguments[C],S++,this._length=S}return S}for(var _=this._front,C=0;C<f;++C)this[_+S&v-1]=arguments[C],_++;return this._length=S+f,S+f}return 0===f?S:(this._checkCapacity(S+1),this[C=this._front+S&this._capacity-1]=g,this._length=S+1,S+1)},Deque.prototype.pop=function Deque$pop(){var g=this._length;if(0!==g){var f=this._front+g-1&this._capacity-1,S=this[f];return this[f]=void 0,this._length=g-1,S}},Deque.prototype.shift=function Deque$shift(){var g=this._length;if(0!==g){var f=this._front,S=this[f];return this[f]=void 0,this._front=f+1&this._capacity-1,this._length=g-1,S}},Deque.prototype.unshift=function Deque$unshift(g){var f=this._length,S=arguments.length;if(S>1){if(f+S>(C=this._capacity)){for(var v=S-1;v>=0;v--){this._checkCapacity(f+1);var C=this._capacity;this[T=(this._front-1&C-1^C)-C]=arguments[v],f++,this._length=f,this._front=T}return f}var _=this._front;for(v=S-1;v>=0;v--){var T;this[T=(_-1&C-1^C)-C]=arguments[v],_=T}return this._front=_,this._length=f+S,f+S}if(0===S)return f;this._checkCapacity(f+1);C=this._capacity;return this[v=(this._front-1&C-1^C)-C]=g,this._length=f+1,this._front=v,f+1},Deque.prototype.peekBack=function Deque$peekBack(){var g=this._length;if(0!==g)return this[this._front+g-1&this._capacity-1]},Deque.prototype.peekFront=function Deque$peekFront(){if(0!==this._length)return this[this._front]},Deque.prototype.get=function Deque$get(g){var f=g;if(f===(0|f)){var S=this._length;if(f<0&&(f+=S),!(f<0||f>=S))return this[this._front+f&this._capacity-1]}},Deque.prototype.isEmpty=function Deque$isEmpty(){return 0===this._length},Deque.prototype.clear=function Deque$clear(){for(var g=this._length,f=this._front,S=this._capacity,v=0;v<g;++v)this[f+v&S-1]=void 0;this._length=0,this._front=0},Deque.prototype.toString=function Deque$toString(){return this.toArray().toString()},Deque.prototype.valueOf=Deque.prototype.toString,Deque.prototype.removeFront=Deque.prototype.shift,Deque.prototype.removeBack=Deque.prototype.pop,Deque.prototype.insertFront=Deque.prototype.unshift,Deque.prototype.insertBack=Deque.prototype.push,Deque.prototype.enqueue=Deque.prototype.push,Deque.prototype.dequeue=Deque.prototype.shift,Deque.prototype.toJSON=Deque.prototype.toArray,Object.defineProperty(Deque.prototype,"length",{get:function(){return this._length},set:function(){throw new RangeError("")}}),Deque.prototype._checkCapacity=function Deque$_checkCapacity(g){this._capacity<g&&this._resizeTo(getCapacity(1.5*this._capacity+16))},Deque.prototype._resizeTo=function Deque$_resizeTo(g){var f=this._capacity;this._capacity=g;var S=this._front,v=this._length;S+v>f&&arrayMove(this,0,this,f,S+v&f-1)};var H_=Array.isArray;function arrayMove(g,f,S,v,C){for(var _=0;_<C;++_)S[_+v]=g[_+f],g[_+f]=void 0}function pow2AtLeast(g){return g>>>=0,g-=1,g|=g>>1,g|=g>>2,g|=g>>4,g|=g>>8,(g|=g>>16)+1}function getCapacity(g){if("number"!=typeof g){if(!H_(g))return 16;g=g.length}return pow2AtLeast(Math.min(Math.max(16,g),1073741824))}var $_=Deque;class DefaultLogger{static overrideDefaultLogDump(){if(DefaultLogger.logDump.isEmpty())DefaultLogger.logDump=new $_(getAcsEcsConfig()?.debugInfo?.maxLogDumpLength);else{let g=new $_(getAcsEcsConfig()?.debugInfo?.maxLogDumpLength);for(;DefaultLogger.logDump.length>0;){const f=DefaultLogger.logDump.shift();f&&g.push(f)}DefaultLogger.logDump=g}}constructor(g,f=[],S=DefaultLogger.defaultLogRedirect){this._azureLogger=g,this._namespace=f,this._logRedirectCallback=S}createChild(g){return new DefaultLogger(this._azureLogger,[...this._namespace,"string"==typeof g?()=>g:g])}createFnLogger(g,f,...S){return this.createChild(this.getPrefix(g,f)+S.join(""))}log(...g){const f=this.getMessage(g);this._azureLogger.verbose(f),this._logRedirectCallback(`log:${f}`)}debug(...g){const f=this.getMessage(g);this._azureLogger.verbose(f),this._logRedirectCallback(`debug:${f}`)}info(...g){const f=this.getMessage(g);this._azureLogger.info(f),this._logRedirectCallback(`info:${f}`)}warn(...g){const f=this.getMessage(g);this._azureLogger.warning(f),this._logRedirectCallback(`warn:${f}`)}error(...g){const f=this.getMessage(g);this._azureLogger.error(this.getMessage(g)),this._logRedirectCallback(`error::${f}`)}getMessage(...g){return`${getDateInIsoFormat()} ${this.getNamespace()} ${g.join(" ")}`}getNamespace(){return this._namespace.map((g=>g())).join(":")}getPrefix(g,f){let S="";return f&&(S+=f),g&&(S+=g),S}redirectLog(g){this._logRedirectCallback=f=>{DefaultLogger.defaultLogRedirect(f),g(f)}}dumpAllLogs(){return[...DefaultLogger.logDump.toArray()]}}DefaultLogger.logDump=new $_(Lm),DefaultLogger.defaultLogRedirect=g=>{if(getAcsEcsConfig()?.debugInfo?.enableLogDump){const sizeCheck=()=>{DefaultLogger.logDump.length>getAcsEcsConfig()?.debugInfo?.maxLogDumpLength&&DefaultLogger.logDump.shift()};if(getAcsEcsConfig()?.debugInfo?.includeList.some((f=>M.includes(g,f))))return DefaultLogger.logDump.push(g),void sizeCheck();if(!getAcsEcsConfig()?.debugInfo?.excludeList.some((f=>M.includes(g,f))))return DefaultLogger.logDump.push(g),void sizeCheck()}};var __decorate$2=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$2=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class StreamTelemetryEventSender{constructor(g){this._telemetryLogManager=g}sendMediaStreamEvent(g){this._telemetryLogManager?.sendEvent({name:uE.acs_calling_media_stream,tenant:tf,properties:{correlationId:g.correlationId,mediaType:g.mediaType,operation:g.operation,timestampInfo:g.timestampInfo,streamType:g.streamType||AE.Local,additionalDetails:g.additionalDetails||"",kindOfEvent:g.kindOfEvent||"",callId:g.callId||"",localPaticipantId:g.localParticipantId||"",createViewResolvedOnPlayEvent:g.createViewResolvedOnPlayEvent||""}})}}__decorate$2([loggerProperty,__metadata$2("design:type",Object)],StreamTelemetryEventSender.prototype,"logger",void 0);class EffectsCapabilityChecker{constructor(g,f){this._logger=g,this._environmentInfo=f,this._videoEffectsEnabled=!1,this._audioEffectsEnabled=!1,this._videoEffectsSupported=!1,this._audioEffectsSupported=!1,this._config=getAcsEcsConfig(),this._mediaConfig=getMediaConfig(),this._videoEffectsEnabled=!(!this._mediaConfig?.enableVideoEffects||!this._config?.videoEffects?.enableVideoEffects),this._audioEffectsEnabled=!!this._config?.audioEffects?.enableAudioEffects,this._videoEffectsEnabled&&(this._videoEffectsSupported=this._mediaConfig?.webcv?.useWasmEffects?this._isWasmVideoEffectSupported():this._isWebgl2EffectSupported())}async videoEffectsSupported(){if(this._videoEffectsEnabled){const g=this._mediaConfig?.webcv?.useWasmEffects?this._isWasmVideoEffectSupported():this._isWebgl2EffectSupported();this._videoEffectsSupported=g&&this._isCurrentEnvironmentSDKSupported()}else this._logger.info("Video effects are disabled."),this._videoEffectsSupported=!1;return this._videoEffectsSupported}async audioEffectsSupported(g){return this._audioEffectsEnabled?this._audioEffectsSupported=this._isBrowserEffect(g)?this._isBrowserEffectSupported(g):await this._isWasmAudioEffectSupported():(this._logger.info("Audio effects are disabled."),this._audioEffectsSupported=!1),this._audioEffectsSupported}_isBrowserEffect(g){if("string"==typeof g)switch(g){case"BrowserEchoCancellation":case"BrowserNoiseSuppression":case"BrowserAutoGainControl":return!0;default:return!1}return!1}_isBrowserEffectSupported(g){const f=window.navigator?.mediaDevices?.getSupportedConstraints?.();if(f)switch(g){case"BrowserEchoCancellation":return!!f.echoCancellation;case"BrowserNoiseSuppression":return!!f.noiseSuppression;case"BrowserAutoGainControl":return!!f.autoGainControl;default:return!1}return!1}_isCurrentEnvironmentSDKSupported(){return!!(this._environmentInfo.isSupportedBrowser&&this._environmentInfo.isSupportedBrowserVersion&&this._environmentInfo.isSupportedEnvironment&&this._environmentInfo.isSupportedPlatform)}_isWasmVideoEffectSupported(){return this._mediaConfig?.webcv?.useWasmEffects?!!window.MediaStreamTrackProcessor||(this._logger.info("WASM effects disabled, insertable streams are not supported"),!1):(this._logger.info("WASM effects disabled by WebCV feature flag"),!1)}_isWebgl2EffectSupported(){return this._isCurrentRendererSupported()&&this._isWebGL2Supported()}_isCurrentRendererSupported(){const g=this._mediaConfig?.webcv?.webGLUnsupportedRenderers??[];let f=!1;try{const S=document.createElement("canvas").getContext("webgl"),v=S?.getExtension("WEBGL_debug_renderer_info"),C=v&&S?.getParameter(v.UNMASKED_RENDERER_WEBGL);return C&&!g.some((g=>g===C))?f=!0:this._logger.info(`Unsupported renderer: ${stringifyObject(C)}`),f}catch(g){return this._logger.warn(`Error trying to check compatibility: ${JSON.stringify(g)}`),!1}}_isWebGL2Supported(){try{const g=document.createElement("canvas").getContext("webgl2");if(!g)return this._logger.info("WebGL2 context is not supported"),!1;const f=g.getSupportedExtensions(),S=this._mediaConfig?.webcv?.webGLRequiredExtensions.filter((g=>!f?.includes(g)));if(S.length>0)return this._logger.info(`Unsupported WebGL2 extensions: ${stringifyObject(S)}`),!1}catch(g){return this._logger.error(`isWebGL2Supported: ${stringifyObject(g)}`),!1}return!0}async _isWasmAudioEffectSupported(){return window.AudioWorkletNode?!!window.WebAssembly||(this._logger.info("WebAssembly is not supported"),!1):(this._logger.info("AudioWorkletNode is not supported"),!1)}}var __decorate$3=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$3=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};const j_=[{acsEffect:"Off",tsCallingEffect:0},{acsEffect:"BackgroundBlur",tsCallingEffect:1},{acsEffect:"BackgroundReplacement",tsCallingEffect:16}];class VideoEffectsFeatureImpl extends FirstPartyVideoStreamFeature{constructor(){super(...arguments),this._effect=null,this._fpsWarningEventIntervalIds=[],this._fpsWarningEventTimeoutIds=[],this._tsCallingEffectCapability=0,this._tsCallingSupportedEffects=[{acsEffect:"Off",tsCallingEffect:0}],this._activeEffects=[],this._sourceStreamSubscription=null,this._stringForUnknownInput="UNKNOWN",this.configUpdatedCallback=async g=>{const f=generateGuid(),S=this.getUsageDetailsForTelemetry("Configure method",g),v=+new Date;try{this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.effectConfigureUpdate,kindOfEvent:gE.attempt,additionalDetails:{usageDetails:S,effectsSdk:{videoEffects:{backgroundImageHasTransparentPixels:this.getBackgroundImageHasTransparentPixel()}}}});const C=this._internalDeviceManager.getTsDeviceManager();if("BackgroundReplacement"===g){const g=(this._effect?._internalHandle?.effectConfig).backgroundImageUrl;g&&await C.setBackgroundImageAsync("",g),this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.effectConfigureUpdate,timestampInfo:{deltaTimeInMs:+new Date-v},kindOfEvent:gE.success,additionalDetails:{usageDetails:S,effectsSdk:{videoEffects:{backgroundImageHasTransparentPixels:this.getBackgroundImageHasTransparentPixel()}}}})}this._logger.info("effect config was updated")}catch(g){const C=new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.EFFECT_CONFIG_UPDATE_CALLBACK_FAILED,originalError:g});this._logger.error(C.message),this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.effectConfigureUpdate,timestampInfo:{deltaTimeInMs:+new Date-v},kindOfEvent:gE.failure,additionalDetails:{failureReason:C.message,code:C.code,...extractCommunicationServicesErrorForTelemetry(C),usageDetails:S}})}},this.processingErrorCallback=async g=>{const f=generateGuid();this.eventEmitter.emit("effectsError",g);const S=this.getEffectNameForTelemetry(this._effect?.name),v=this.getUsageDetailsForTelemetry("Internal handle error",S);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.effectsError,kindOfEvent:gE.failure,additionalDetails:{failureReason:g.message,code:g.code,...extractCommunicationServicesErrorForTelemetry(g),usageDetails:v}}),await this.stopEffects()},this.effectStatusChangedCallback=(g,f)=>{if(f.length>0){const g=this._effect?.name?[this._effect.name]:f;this.eventEmitter.emit("effectsStarted",g)}else{const f=this._effect?.name?[this._effect.name]:g;this.eventEmitter.emit("effectsStopped",f)}}}initialize(g,f){this._logger=f.createChild(" - VideoEffects:"),this._telemetryLogManager=g.telemetryLogManager,this.updateEffectStatusManager()}get name(){return"VideoEffects"}get activeEffects(){return this._effectsStatusManager?.getActiveEffects?.()??this._activeEffects}on(g,f){if("effectsStarted"!==g&&"effectsStopped"!==g&&"effectsError"!==g&&"fpsWarningThresholdReached"!==g&&"timeForEffectsWarningReached"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f);const S=generateGuid();this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:S,operation:PE.subscribe,additionalDetails:{usageDetails:`Subscribed to ${g}`}})}off(g,f){if("effectsStarted"!==g&&"effectsStopped"!==g&&"effectsError"!==g&&"fpsWarningThresholdReached"!==g&&"timeForEffectsWarningReached"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.off(g,f)}async isSupported(g){const f=generateGuid(),S=+new Date,v=this.getEffectNameForTelemetry(g?.name),C=this.getUsageDetailsForTelemetry("",v);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.isSupported,kindOfEvent:gE.attempt,additionalDetails:{usageDetails:C}});try{this._logger.info(`isSupported attempted with input ${this.getEffectNameForTelemetry(g?.name)}`);const v=this.getEffectInternalCast(g);if(this.disposed)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_SOURCE});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const C=this._internalDeviceManager.getEnvironmentInfoInternal();this._supportChecker||(this._supportChecker=new EffectsCapabilityChecker(this._logger,C));const _=await this._supportChecker.videoEffectsSupported();this._logger.info(`Support check for ${v.name} resulted in: ${_}`);const T=this.getUsageDetailsForTelemetry("",v.name);return this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.isSupported,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.success,additionalDetails:{usageDetails:T}}),this._logger.info("isSupported success"),_}catch(v){const C=new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.SUPPORT_CHECK_FAILED,originalError:v});this._logger.error(C.message);const _=this.getEffectNameForTelemetry(g?.name),T=this.getUsageDetailsForTelemetry("",_);throw this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.isSupported,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.failure,additionalDetails:{failureReason:C.message,code:C.code,...extractCommunicationServicesErrorForTelemetry(C),usageDetails:T}}),C}}async startEffects(g){const f=generateGuid(),S=+new Date,v=this.getEffectNameForTelemetry(g?.name),C=this.getUsageDetailsForTelemetry("",v);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.startEffects,kindOfEvent:gE.attempt,additionalDetails:{usageDetails:C}});try{this._logger.info(`startEffects attempted with input ${this.getEffectNameForTelemetry(g?.name)}`);if(!getAcsEcsConfig().videoEffects.enableVideoEffects)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.DISABLED});if(this.disposed)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_SOURCE});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager),this.updateEffectStatusManager(),this.subscribeToStreamInstanceEvents();const v=window.performance.now();this._effect=this.getEffectInternalCast(g);if(!await this.isSupported(g))throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_EFFECT});const C=this._internalDeviceManager.getTsDeviceManager();if(!C)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.START_DEVICE_MANAGER});this.setConfigForEffects(),this.disposeEffectEventSubscriptions(),this.subscribeToEffectEvents();const _=await this._effect._internalHandle.getEffectProvider();if(!_)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.PROVIDER_UNAVAILABLE});const T=await _.getVideoEffectProvider(),I=this.streamInstance.callStackWebCVProvider;if(!I)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.WEBCV_PROVIDER_FAILED});I.videoEffectProviderDeferredPromise.resolve(T),0===this._tsCallingEffectCapability&&(this._tsCallingEffectCapability=await(C?.getDeviceEffectsCapabilityAsync(""))),this._tsCallingSupportedEffects=this.getTsCallingSupportedEffects();const b=this._tsCallingSupportedEffects.find((g=>g.acsEffect===this._effect?.name));if(!b)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_EFFECT});await(C?.setDeviceEffectsAsync("",b.tsCallingEffect)),this._effectsStatusManager.setActiveEffects([this._effect.name]),this._logger.info(`Video effects started: ${this._effect.name}`);const A=window.performance.now();this.handleEffectsInitTimeEvent(v,A),this.handleFpsWarningEvent();const P=this.getUsageDetailsForTelemetry("",this._effect.name);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.startEffects,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.success,additionalDetails:{usageDetails:P,effectsSdk:{videoEffects:{backgroundImageHasTransparentPixels:this.getBackgroundImageHasTransparentPixel()}}}}),this._logger.info("startEffects success")}catch(v){const C=new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.START_FAILED,originalError:v});this._logger?.error(C.message),this.eventEmitter.emit("effectsError",C),this.clearFpsCheckInterval();const _=this.getEffectNameForTelemetry(g?.name),T=this.getUsageDetailsForTelemetry("",_);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.startEffects,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.failure,additionalDetails:{failureReason:C.message,code:C.code,...extractCommunicationServicesErrorForTelemetry(C),usageDetails:T,effectsSdk:{videoEffects:{backgroundImageHasTransparentPixels:this.getBackgroundImageHasTransparentPixel()}}}})}}async stopEffects(){const g=generateGuid(),f=+new Date;this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:g,operation:PE.stopEffects,kindOfEvent:gE.attempt});try{if(this._logger.info("stopEffects attempted"),this.clearFpsCheckInterval(),this.disposed)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.STOP_DISPOSED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const S=this._internalDeviceManager.getTsDeviceManager();if(!S)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.STOP_DEVICE_MANAGER});this.updateEffectStatusManager();const v=this._tsCallingSupportedEffects.find((g=>"Off"===g.acsEffect));if(!v)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_EFFECT});await S.setDeviceEffectsAsync("",v.tsCallingEffect),this._effectsStatusManager?.setActiveEffects([]),this.unsubscribeFromStreamInstanceEvents();const C=this.getEffectNameForTelemetry(this._effect?.name);this._logger.info(`Video effects stopped: ${C}`),this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:g,operation:PE.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-f},kindOfEvent:gE.success}),this._logger.info("stopEffects success")}catch(S){const v=new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.STOP_FAILED,originalError:S});this._logger?.error(v.message),this.eventEmitter.emit("effectsError",v),this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:g,operation:PE.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-f},kindOfEvent:gE.failure,additionalDetails:{failureReason:v.message,code:v.code,...extractCommunicationServicesErrorForTelemetry(v)}})}}async dispose(){try{if(this._logger.info("dispose attempted"),this.disposed)return void this._logger.info("VideoEffects feature already disposed");this._effect&&await this.stopEffects(),this.eventEmitter.removeAllListeners(),this.serialQueue.dispose(),this._effectsStatusManager?.off("statusChanged",this.effectStatusChangedCallback),this.unsubscribeFromStreamInstanceEvents(),this.disposed=!0,this._logger.info("VideoEffects feature disposed")}catch(g){const f=new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.DISPOSE_FAILED,originalError:g});this._logger?.error(f.message),this.eventEmitter.emit("effectsError",f)}}getEffectsSdkVersion(){let g=this._stringForUnknownInput;return this.activeEffects.length>0&&this._effect&&this._effect._internalHandle?.getVersion&&(g=this._effect._internalHandle?.getVersion()),this.truncateToMax(g)}getActiveEffectsForTelemetry(){return this.truncateToMax(JSON.stringify(this.activeEffects))}getEffectInternalCast(g){if("BackgroundBlur"===g?.name&&this.isValidEffectInstance(g))return g;if("BackgroundReplacement"===g?.name&&this.isValidEffectInstance(g))return g;throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.INVALID_EFFECT})}isValidEffectInstance(g){let f;return("BackgroundBlur"===g.name&&void 0!==g._internalHandle||"BackgroundReplacement"===g.name&&void 0!==g._internalHandle)&&(f=g,this.hasValidInternalHandle(f._internalHandle))}hasValidInternalHandle(g){return void 0!==g.effectConfig&&void 0!==g.getEffectProvider&&void 0!==g.dispose&&void 0!==g.getStats&&void 0!==g.setConfig}getTsCallingSupportedEffects(){const g=[];return Object.values(j_).forEach((f=>{(this._tsCallingEffectCapability&f.tsCallingEffect)===f.tsCallingEffect&&g.push(f)})),g}subscribeToEffectEvents(){this._effect&&this._internalDeviceManager?(this._effect._internalHandle.on("configUpdated",this.configUpdatedCallback),this._effect._internalHandle.on("processingError",this.processingErrorCallback)):this._logger.debug("No effect instance found.")}disposeEffectEventSubscriptions(){this._effect?(this._effect._internalHandle.off("configUpdated",this.configUpdatedCallback),this._effect._internalHandle.off("processingError",this.processingErrorCallback)):this._logger.debug("No effect instance found.")}subscribeToStreamInstanceEvents(){this._sourceStreamSubscription&&(this._logger.info("Already subscribed to videoSourceChanged, removing old sub"),this.streamInstance.off("videoSourceChanged",this._sourceStreamSubscription)),this._sourceStreamSubscription=async g=>{g.source&&"Video"!==g.source.mediaStreamType&&await this.stopEffects()},this.streamInstance.on("videoSourceChanged",this._sourceStreamSubscription)}unsubscribeFromStreamInstanceEvents(){this._sourceStreamSubscription?(this.streamInstance.off("videoSourceChanged",this._sourceStreamSubscription),this._sourceStreamSubscription=null):this._logger.info("No videoSourceChanged sub active")}handleEffectsInitTimeEvent(g,f){if(!this._effect)return void this._logger.debug("No effect active");const S=generateGuid(),v=f-g,C=this._effect._internalHandle.effectConfig.effectInitTimeThresholdInMs;if(this._logger.info(`Time for effects to start: ${v}ms`),C&&v>C){this.eventEmitter.emit("timeForEffectsWarningReached",this._effect.name);const g=this.getUsageDetailsForTelemetry(`Threshold value: ${C}ms`,this._effect.name);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:S,operation:PE.timeForEffectsWarningReached,additionalDetails:{usageDetails:g}})}}handleFpsWarningEvent(){if(!this._effect)return void this._logger.debug("No effect active");this.clearFpsCheckInterval();const g=getAcsEcsConfig(),f=generateGuid(),S=g.videoEffects.waitTimeToInitiateFpsChecksInMs,v=g.videoEffects.fpsCheckIntervalTimeInMs;this._fpsWarningThresholdValue=this._effect._internalHandle.effectConfig.fpsWarningThreshold??g.videoEffects.fpsWarningThreshold;const startFpsChecker=()=>{const g=window.setInterval((()=>{const S=this._effect?._internalHandle.getStats(),v=S?.processor.fpsAvg;if(this._logger.info(`Effects avg fps check interval poll. Current Avg - ${v}`),v&&v<this._fpsWarningThresholdValue){this.eventEmitter.emit("fpsWarningThresholdReached",this._effect?.name),window.clearInterval(g),this._logger.info(`Effects fps warning threshold hit at ${v}fps`);const S=this.getUsageDetailsForTelemetry(`Fps reported: ${v}, Fps warning threshold value: ${this._fpsWarningThresholdValue}`,this._effect?.name);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.fpsWarningThresholdReached,additionalDetails:{usageDetails:S}})}}),v);this._fpsWarningEventIntervalIds.push(g)},C=window.setTimeout(startFpsChecker,S);this._fpsWarningEventTimeoutIds.push(C)}setConfigForEffects(){if(!this._effect)return void this._logger.debug("No effect active");const g=this._effect._internalHandle.configProvider.config.videoEffects??this._effect._internalHandle.configProvider.config,f=getMediaConfig(),S=getAcsEcsConfig();if(f?.enableVideoEffects&&S?.videoEffects?.enableVideoEffects&&(g.enableVideoEffects=f.enableVideoEffects&&S.videoEffects.enableVideoEffects),g.effectConfig={...g.effectConfig,effectInitTimeThresholdInMs:S.videoEffects.effectInitTimeThresholdInMs,fpsWarningThreshold:S.videoEffects.fpsWarningThreshold},f.webcv){const S=f.webcv;g.webcvConfig={...g.webcvConfig,...S}}this._effect._internalHandle.setConfig(g),this._logger.info(`Config for effects set: ${stringifyObject(g)}`)}sendFeatureUsageTelemetry(g){if(this._telemetryLogManager){g.additionalDetails={...g.additionalDetails,callState:this.streamInstance.getCall()?.state,activeEffects:JSON.stringify(this.activeEffects),effectsSdk:{...g.additionalDetails?.effectsSdk,version:this.getEffectsSdkVersion()}};try{const f={correlationId:g.correlationId,mediaType:bE.VideoRaw,streamType:AE.Local,operation:g.operation,timestampInfo:g.timestampInfo||{},kindOfEvent:g.kindOfEvent||"",additionalDetails:g.additionalDetails||"",callId:this.streamInstance.getCall()?.id||"",localParticipantId:this.streamInstance.getLocalParticipantId()||""};this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:f})}catch(f){this._logger.debug(`Unable to send ${g.operation} telemetry`)}}else this._logger.debug("Telemetry error. Instance is undefined.")}getEffectNameForTelemetry(g){let f=this._stringForUnknownInput;return g?f="string"==typeof g?g:JSON.stringify(g):this._effect?.name?f=this._effect.name:this._activeEffects?.[0]&&(f=JSON.stringify(this._activeEffects[0])),this.truncateToMax(f)}getUsageDetailsForTelemetry(g,f=""){return this.truncateToMax(`${f?`[${f}] `:""}${g}`)}clearFpsCheckInterval(){this._fpsWarningEventIntervalIds.forEach((g=>{window.clearInterval(g)})),this._fpsWarningEventTimeoutIds.forEach((g=>{window.clearTimeout(g)})),this._fpsWarningEventIntervalIds=[],this._fpsWarningEventTimeoutIds=[]}updateEffectStatusManager(){this.streamInstance.canStartEffects?(this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager),this._effectsStatusManager||(this._effectsStatusManager=this._internalDeviceManager.callStackVideoEffectsStatusManager,this._effectsStatusManager.on("statusChanged",this.effectStatusChangedCallback)),this._activeEffects=this._effectsStatusManager.getActiveEffects()):this._logger.warn("Cannot update status manager, current source is not supported.")}truncateToMax(g){const f=getAcsEcsConfig().videoEffects.maxStringLengthForTelemetry;return g.length>f?(this._logger?.info("Truncating video effects info for telemetry"),g.substring(0,f-2)+".."):g}getBackgroundImageHasTransparentPixel(){try{if("BackgroundReplacement"===this._effect?.name&&void 0!==this._effect._internalHandle?.imageLoader?.loadedImageHasTransparentPixels)return this._effect._internalHandle.imageLoader?.loadedImageHasTransparentPixels}catch(g){return null}return null}}__decorate$3([sequentialize(),__metadata$3("design:type",Function),__metadata$3("design:paramtypes",[Object]),__metadata$3("design:returntype",Promise)],VideoEffectsFeatureImpl.prototype,"startEffects",null),__decorate$3([sequentialize(),__metadata$3("design:type",Function),__metadata$3("design:paramtypes",[]),__metadata$3("design:returntype",Promise)],VideoEffectsFeatureImpl.prototype,"stopEffects",null);var G_,__decorate$4=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$4=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class LocalVideoStream{constructor(g){if(this._disposed=!1,this._call=new Set,this._canStartEffects=!1,this.kind="LocalVideoStream",this._renderers=[],this._rawStreamCloneCache=new Set,this._disposeRenderer=g=>{this.logger.log("disposing renderer");try{g.dispose(),this.logger.log("renderer disposed")}catch(g){this.logger.log("failed to dispose renderer")}},!(g instanceof VideoDeviceInfoImpl||g instanceof MediaStream))throw new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.WRONG_STREAM_TYPE});const S=f.createClientLogger("ACS-calling");this.logger=new DefaultLogger(S,[()=>`LocalVideoStream:${g.id}`]),this.logger.info("created"),this._eventEmitter=new CallingEventEmitter(this.logger),this.setSource(g,!0),this._localStreamTelemetryEventSender=new StreamTelemetryEventSender(this._telemetryLogManager)}on(g,f){if("videoSourceChanged"!==g)throw new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("videoSourceChanged"!==g)throw new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}get source(){return this._source}get mediaStreamType(){return this._mediaStreamType}get telemetryLogManager(){return this._telemetryLogManager}get callStackWebCVProvider(){return this.source?.deviceManager?.callStackWebCvProvider??null}get callStackEffectsStatusManager(){return this.source?.deviceManager?.callStackVideoEffectsStatusManager??null}get canStartEffects(){return this._canStartEffects}async switchSource(g){const f=this.logger.createFnLogger(kS.SwitchSource),S=+new Date,v=generateGuid(),C={timestampInfo:{attemptTimestamp:S},correlationId:v,operation:PE.switchSource,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",kindOfEvent:gE.attempt,mediaType:bE.Video,streamType:AE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(C),!(g instanceof VideoDeviceInfoImpl)){const g=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.SWITCH_SOURCE_WRONG_TYPE}),f={correlationId:v,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:PE.switchSource,additionalDetails:{failureReason:g.message,code:x,...extractCommunicationServicesErrorForTelemetry(g)},timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.failure,mediaType:bE.Video,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(f),g}if(this._source===g){const g=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.SWITCH_SAME_SOURCE}),f={correlationId:v,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:PE.switchSource,additionalDetails:{failureReason:g.message,code:g.code,...extractCommunicationServicesErrorForTelemetry(g)},timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.failure,mediaType:bE.Video,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(f),g}try{if("RawMedia"===this._mediaStreamType){Array.from(this._call.values()).some((g=>g.localVideoStream===this))&&g.deviceManager.getTsDeviceManager().unsetRawMediaStream?.(1)}g.deviceManager.getTsDeviceManager().selectDevices({camera:g.id}),this.setSource(g);const f={correlationId:v,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",mediaType:bE.Video,operation:PE.switchSource,timestampInfo:{deltaTimeInMs:+new Date-S},streamType:AE.Local,kindOfEvent:gE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(f)}catch(g){const C=handleVideoOperationFailure(f,g),_={correlationId:v,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:PE.switchSource,additionalDetails:{failureReason:C.message,code:x,...extractCommunicationServicesErrorForTelemetry(C)},timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.failure,mediaType:bE.Video,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(_),C}}dispose(){this.logger.log("Disposing LocalVideoStream."),this._disposed?this.logger.log("already disposed"):(this.disposeRawStream(),this._renderers.forEach((g=>this._disposeRenderer(g))),this._renderers=[],this._extensibleApi?.dispose(),this._eventEmitter.removeAllListeners(),this._disposed=!0)}async getMediaStream(){const g=generateGuid();let f=+new Date;const S={correlationId:g,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",timestampInfo:{attemptTimestamp:f},operation:PE.getMediaStream,kindOfEvent:gE.attempt,mediaType:bE.VideoRaw,streamType:AE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(S),this.subscribeToRawStreamChangedIfNeeded(),this._mediaStreamSource){const S={correlationId:g,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",mediaType:bE.VideoRaw,operation:PE.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-f},streamType:AE.Local,kindOfEvent:gE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(S);const v=this._mediaStreamSource.clone();return this._cacheCloneStream(v),v}try{let S;if("ScreenSharing"===this._source.deviceType?S=2:"UsbCamera"!==this._source.deviceType&&"CaptureAdapter"!==this._source.deviceType&&"Virtual"!==this._source.deviceType||(S=1),!S)throw new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.CANT_GET_DEVICE_TYPE});this._rawStream||(this._rawStream=this.source.deviceManager.getRawDeviceMediaStream(S));const v={correlationId:g,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",mediaType:bE.VideoRaw,operation:PE.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-f},streamType:AE.Local,kindOfEvent:gE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(v);const C=(await(this._rawStream?.getMediaStream())).clone();return this._cacheCloneStream(C),C}catch(S){let v;v="ScreenSharing"===this._source.deviceType?new CallingCommunicationError({defaultError:D.CALL.SS_RAW_STREAM_GET,originalError:S}):new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:S});const C={timestampInfo:{deltaTimeInMs:+new Date-f},correlationId:g,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:PE.getMediaStream,additionalDetails:{failureReason:v.message,code:v.code,...extractCommunicationServicesErrorForTelemetry(v)},kindOfEvent:gE.failure,mediaType:bE.VideoRaw,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(C),v}}async setMediaStream(g){const f=generateGuid();let S,v=+new Date,C=!1,_=!1,T=bE.VideoRawOrScreenSharingRaw;for(let g of this._call){const f=g;if(f.localScreenSharingStream===this||f.localVideoStream===this){S=f.deviceManager,_=!0,f.localVideoStream===this?(C=!0,T=bE.VideoRaw):f.localScreenSharingStream===this&&(C=!1,T=bE.ScreenSharingRaw);break}}const I={timestampInfo:{attemptTimestamp:v},correlationId:f,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:PE.setMediaStream,kindOfEvent:gE.attempt,mediaType:T,streamType:AE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(I),!(g instanceof MediaStream)){const g=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.SET_MEDIA_STREAM_WRONG_TYPE}),S={timestampInfo:{deltaTimeInMs:+new Date-v},correlationId:f,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:PE.setMediaStream,additionalDetails:{failureReason:g.message,code:g.code,...extractCommunicationServicesErrorForTelemetry(g)},kindOfEvent:gE.failure,mediaType:T,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(S),g}if(this.setSource(g),getAcsEcsConfig()?.calling?.allowAccessRawMediaStream)try{if(_){const f=S?.getTsDeviceManager();if(!f?.setRawMediaStream)throw new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.SET_MEDIA_STREAM_UNDEFINED_FUNC});C?f.setRawMediaStream(g,1):f.setRawMediaStream(g,2)}this._renderers.forEach((f=>{f.setSourceObject(g)}));const I={timestampInfo:{deltaTimeInMs:+new Date-v},correlationId:f,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:PE.setMediaStream,kindOfEvent:gE.success,mediaType:T,streamType:AE.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(I)}catch(g){const S=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.SET_MEDIA_STREAM,originalError:g}),C={correlationId:f,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:PE.setMediaStream,additionalDetails:{failureReason:S.message,code:S.code,...extractCommunicationServicesErrorForTelemetry(S)},timestampInfo:{deltaTimeInMs:+new Date-v},kindOfEvent:gE.failure,mediaType:T,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(C),S}}addCall(g){this._call.add(g)}removeCall(g){this._call.delete(g)}feature(g){return this._extensibleApi||(this._extensibleApi=new ExtensibleFeatureImpl(this.logger,{streamInstance:this},{streamInstance:this,telemetryLogManager:this.telemetryLogManager})),this._extensibleApi.getApiObjectInstance(g.videoStreamApiCtor)}registerRenderer(g){this._renderers.push(g)}unregisterRenderer(g){const f=this._renderers.indexOf(g);-1!==f&&this._renderers.splice(f,1)}getStreamMetadata(){let g,f,S=this.getCall();this._source instanceof VideoDeviceInfoImpl?(g=this.source.deviceManager,f=this.source.deviceType):this._mediaStreamSource instanceof MediaStream&&S&&(g=S.deviceManager);let v=-1;return S&&("Video"===this._mediaStreamType||"RawMedia"===this.mediaStreamType&&S.localVideoStream===this?v=S.tsCall.mediaStreams[0][0]?.id||-1:("ScreenSharing"===this._mediaStreamType||"RawMedia"===this.mediaStreamType&&S.localScreenSharingStream===this)&&(v=S.tsCall.mediaStreams[1][0]?.id||-1)),{source:"local",sourceId:v,streamType:this.mediaStreamType,deviceType:f||"",callId:S?.id||"",localParticipantId:S?.tsCall.participantId||"",deviceManagerPermissionState:g?JSON.stringify({cameraPermission:g.getVideoDevicePermission(),microphonePermission:g.getAudioDevicePermission()}):"",acsResourceId:g?.getAcsResourceId()||"",clientId:g?.getClientId()||""}}getLocalParticipantId(){let g="";const f=this.getCall();return f&&(g=f.tsCall.participantId),g}getCall(){for(const g of this._call)if(g.localVideoStreams.includes(this))return g}getEffectsCurrentStateRecord(){try{const g=this.feature(videoStreamFeatureFactory(VideoEffectsFeatureImpl)),f=g.getEffectsSdkVersion();return{activeEffects:g.getActiveEffectsForTelemetry(),effectsSdk:{version:f}}}catch(g){return void this.logger.warn(`Error while getting current effect state on LocalAudioStream for telemetry: ${g}`)}}setSource(g,f=!1){if(g instanceof VideoDeviceInfoImpl)this._telemetryLogManager=g.deviceManager.telemetryLogManager,this._source=g,this._mediaStreamType="ScreenSharing"===g.deviceType?"ScreenSharing":"Video",this._mediaStreamSource=void 0,this._rawStream=void 0,this._canStartEffects=!0;else{try{1===globalThis[Lf]&&(this._telemetryLogManager=globalThis[kf])}catch(g){this.logger.error("Failed to retrive telemetry logger for localVideoStream")}this._source={name:"CustomMediaStream",id:generateGuid(),deviceType:"Virtual"},this._mediaStreamSource=g,this._mediaStreamType="RawMedia",this._canStartEffects=!1}f||this._eventEmitter.emit("videoSourceChanged",{source:this})}subscribeToRawStreamChangedIfNeeded(){this._source instanceof VideoDeviceInfoImpl&&!this._videoSourceChangedSub&&(this._videoSourceChangedSub=this._rawStream?.changed((()=>{this._eventEmitter.emit("videoSourceChanged",{source:this})})))}_cacheCloneStream(g){this._rawStreamCloneCache.add(g)}disposeRawStream(){this._rawStream&&this._rawStream.dispose();for(const g of Array.from(this._rawStreamCloneCache))g?.getTracks?.().forEach((g=>g.stop()));this._rawStreamCloneCache.clear(),this._videoSourceChangedSub?.dispose(),this._videoSourceChangedSub=void 0}}__decorate$4([loggerProperty,__metadata$4("design:type",Object)],LocalVideoStream.prototype,"logger",void 0),__decorate$4([asyncOperation(kS.SwitchSource),__metadata$4("design:type",Function),__metadata$4("design:paramtypes",[Object]),__metadata$4("design:returntype",Promise)],LocalVideoStream.prototype,"switchSource",null),__decorate$4([asyncOperation(kS.GetMediaStream),__metadata$4("design:type",Function),__metadata$4("design:paramtypes",[]),__metadata$4("design:returntype",Promise)],LocalVideoStream.prototype,"getMediaStream",null),__decorate$4([asyncOperation(kS.SetMediaStream),__metadata$4("design:type",Function),__metadata$4("design:paramtypes",[MediaStream]),__metadata$4("design:returntype",Promise)],LocalVideoStream.prototype,"setMediaStream",null),__decorate$4([syncOperation(kS.Feature),__metadata$4("design:type",Function),__metadata$4("design:paramtypes",[Object]),__metadata$4("design:returntype","function"==typeof(G_="undefined"!=typeof TFeature&&TFeature)?G_:Object)],LocalVideoStream.prototype,"feature",null);class AudioDeviceInfoImpl{constructor(g,f,S,v,C){this._name=g,this._id=f,this._isSystemDefault=S,this._deviceType=v,this._deviceManager=C}get name(){return this._name}setName(g){this._name=g}get id(){return this._id}setId(g){this._id=g}get isSystemDefault(){return this._isSystemDefault}setIsSystemDefault(g){this._isSystemDefault=g}get deviceType(){return this._deviceType}setDeviceType(g){this._deviceType=g}get deviceManager(){return this._deviceManager}}var __decorate$5=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$5=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class VolumeImpl{constructor(g,f,S,v,C){this._workQueue=Promise.resolve(),this.logger=g.createChild("volume indicator"),this._eventEmitter=new CallingEventEmitter(this.logger,{enableLogEmit:!1}),this._isInitialized=!1,this._level=0,this._streamType=f,this._callId=v,this._localParticipantId=C,this._telemetryLogManager=S}get isInitialized(){return this._isInitialized}initialize(g){if(void 0===g)throw this.logger.error("failed to getMediaStreamTrack"),new CallingCommunicationError({defaultError:D.CALL.VOLUME_TRACK});const f=generateGuid(),S=+new Date;try{this.sendVolumeEvent({eventName:uE.acs_calling_audio_stream_volume,correlationId:f,callId:this._callId||"",localParticipantId:this._localParticipantId||"",streamType:this._streamType,kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),this.bindToAudioStreamVolume(g),this.sendVolumeEvent({eventName:uE.acs_calling_audio_stream_volume,correlationId:f,callId:this._callId||"",localParticipantId:this._localParticipantId||"",streamType:this._streamType,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:+new Date-S},additionalDetails:""})}catch(g){const v=new CallingCommunicationError({defaultError:D.CALL.VOLUME_INIT,originalError:g});throw this.logger.error(v.message),this.sendVolumeEvent({eventName:uE.acs_calling_audio_stream_volume,correlationId:f,callId:this._callId||"",localParticipantId:this._localParticipantId||"",streamType:this._streamType,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-S},additionalDetails:{failureReason:v.message,code:v.code,subCode:v.subCode,...extractCommunicationServicesErrorForTelemetry(v)}}),v}}bindToAudioStreamVolume(g){let[f,S]=this.setupVolumeCalculator(g);this._level=f();let v=setInterval((()=>{let g=f();g!==this._level&&(this._level=g,this._eventEmitter.emit("levelChanged"))}),getAcsEcsConfig()?.volumeIndicator?.microphoneVolumeSampleIntervalMs);this._volumeCallBackInterval=v,this._audioContext=S}setupVolumeCalculator(g){const f=new MediaStream(g),S=new AudioContext,v=S.createMediaStreamSource(f),C=S.createAnalyser();v.connect(C),C.fftSize=getAcsEcsConfig().volumeIndicator.fftSize,C.minDecibels=getAcsEcsConfig().volumeIndicator.minDecibels,C.maxDecibels=getAcsEcsConfig().volumeIndicator.maxDecibels,C.smoothingTimeConstant=getAcsEcsConfig().volumeIndicator.smoothingConstant;const _=new Uint8Array(C.frequencyBinCount);return[()=>{try{C.getByteFrequencyData(_);let g=0;for(const f of _)g+=f;const f=g/_.length;return f*getAcsEcsConfig().volumeIndicator.normalisedMaxVolume/getAcsEcsConfig().volumeIndicator.maxAvailableVolume}catch(g){return this.logger.error("error in calculating audio stream volume"),0}},S]}dispose(){this._isInitialized=!1,this._level=0,this._eventEmitter.removeAllListeners();try{this._audioContext?.close().catch((g=>{this.logger.error("unable to close AudioContext")}))}catch(g){this.logger.error("unable to close MicrophoneAudioContext")}this._volumeCallBackInterval&&clearInterval(this._volumeCallBackInterval)}on(g,f){if("levelChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL.VOLUME_EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("levelChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL.VOLUME_EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}get level(){return this._level}getVolumeIndicator(g){const executeSerialisedAsync=()=>{if(!this.isInitialized)try{this.initialize(g),this._isInitialized=!0}catch(g){const f=new CallingCommunicationError({defaultError:D.CALL.VOLUME_GET,originalError:g});throw this.logger.error(f.message),f}return this},f=this._workQueue.then((()=>executeSerialisedAsync()));return this._workQueue=f.then(noop,noop),f}sendVolumeEvent(g){try{this._telemetryLogManager?.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this.logger.debug("Unable to send screen share telemetry")}}}__decorate$5([loggerProperty,__metadata$5("design:type",Object)],VolumeImpl.prototype,"logger",void 0);class BrowserAudioEffectsHelper{constructor(g,f,S){this._effectsStatusManager=g,this._logger=f,this._localAudioStream=S,this._currentActiveBrowserEffects={},this._updateCurrentActive()}async setBrowserAudioEffects(g,f,S){try{await this._updateCurrentActive(f);const v={autoGainControl:void 0!==S.autoGainControl?S.autoGainControl:this._currentActiveBrowserEffects.autoGainControl,echoCancellation:void 0!==S.echoCancellation?S.echoCancellation:this._currentActiveBrowserEffects.echoCancellation,noiseSuppression:void 0!==S.noiseSuppression?S.noiseSuppression:this._currentActiveBrowserEffects.noiseSuppression},C=this._calculateFlags(v);this._logger.info(`Setting browser audio processing flags to ${C}`),await g.setAudioProcessingFlags(C)}catch(g){throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.AUDIO_FLAGS,originalError:g})}}async _updateCurrentActive(g){try{const f=g??this._effectsStatusManager.getActiveEffects();if(!this._localAudioStream.canStartEffects)throw new Error("Cannot proceed to update current browser audio effects, most likely source is not supported for audio effects");const S=await this._localAudioStream.getMediaStream(),v=S?.getAudioTracks()?.[0];if(!v)throw new Error("Could not get MediaStreamTrack from the LocalAudioStream");const C=v.getSettings();let _=!!C?.autoGainControl,T=!!C?.noiseSuppression,I=!!C?.echoCancellation;this._currentActiveBrowserEffects={},("BrowserAutoGainControl"===f?.autoGainControl?.[0]||_)&&(this._currentActiveBrowserEffects.autoGainControl=!0),("BrowserEchoCancellation"===f?.echoCancellation?.[0]||I)&&(this._currentActiveBrowserEffects.echoCancellation=!0),("BrowserNoiseSuppression"===f?.noiseSuppression?.[0]||T)&&(this._currentActiveBrowserEffects.noiseSuppression=!0)}catch(g){throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.AUDIO_FLAGS,originalError:g})}}_calculateFlags(g){let f=0;return g.autoGainControl&&(f+=1),g.echoCancellation&&(f+=2),g.noiseSuppression&&(f+=4),f}}var __decorate$6=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$6=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class AudioEffectsFeatureImpl extends FirstPartyAudioStreamFeature{constructor(){super(...arguments),this._wasmVqeInitialized=!1,this._activeEffects={echoCancellation:[],noiseSuppression:[],autoGainControl:[]},this._currentEffects={},this._previousTsWasmEffectType=0,this._currentTsWasmEffectType=0,this._stringForUnknownInput="UNKNOWN",this._audioEffectsProcessorStats=null,this._sourceStreamSubscription=null,this.effectStatusChangedCallback=(g,f,S)=>{this._logger?.debug(`Effects status changed from ${JSON.stringify(g)} to ${JSON.stringify(f)} with operationType: ${S}`),"start"!==S&&"initialize"!==S||this.eventEmitter.emit("effectsStarted",f),"stop"===S&&this.eventEmitter.emit("effectsStopped",f)},this.configUpdatedCallback=async g=>{this._logger?.info("configUpdated callback, no-op.")},this.processingErrorCallback=async g=>{const f=generateGuid();this._logger?.info("processingError callback"),this.eventEmitter.emit("effectsError",g);const S=this.getEffectsNameForTelemetry(this.activeEffects),v=this.getUsageDetailsForTelemetry("Internal handle error",S);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.stopEffects,kindOfEvent:gE.failure,additionalDetails:{failureReason:g.message,...extractCommunicationServicesErrorForTelemetry(g),usageDetails:v}}),await this.stopEffects({echoCancellation:!0,noiseSuppression:!0})},this.subscribeToStatUpdates=async()=>{const g=this.getAnyActiveWasmEffect();if(!g)return;const f=await g._internalHandle.getEffectProvider(),S=await(f?.getAudioEffectProvider());let v=null;S&&(this._audioEffectProviderSub=S?.on?.("onMetricsUpdated",(()=>{try{v=S?.getStats&&S.getStats(),v&&(this._audioEffectsProcessorStats={activeAudioEffects:JSON.stringify(this.activeEffects),audioEffectsSpeechProcessingStats:{localAudioInputSpeechRMS_dBFS:v?.speechLevels?.nearEndInputRMS_dBFS,localAudioOutputSpeechRMS_dBFS:v?.speechLevels?.nearEndOutputRMS_dBFS,localAudioInputNoiseRMS_dBFS:v?.noiseLevels?.nearEndInputRMS_dBFS,localAudioOutputNoiseRMS_dBFS:v?.noiseLevels?.nearEndOutputRMS_dBFS,remoteAudioInputSpeechRMS_dBFS:v?.speechLevels?.farEndInputRMS_dBFS,remoteAudioOutputSpeechRMS_dBFS:v?.speechLevels?.farEndOutputRMS_dBFS},rawStats:JSON.stringify(v)}),this.eventEmitter.emit("effectsProcessorStatsUpdated",this._audioEffectsProcessorStats)}catch(g){this._logger?.warn(`Could not emit audio effect processor stat event: ${g}`)}})),this._logger?.info("Subscribed to audioEffectsProvider stat updates"))},this.unsubscribeFromStatUpdates=()=>{this.getAnyActiveWasmEffect()?this._logger?.info("There is a wasm audio effect still active, skipping stat unsubscribe"):this._audioEffectProviderSub?.dispose&&(this._audioEffectProviderSub.dispose(),this._audioEffectProviderSub=()=>{},this._audioEffectsProcessorStats=null,this._logger?.info("Unsubscribed from audioEffectsProvider stat updates"))}}initialize(g,f){this._logger=f.createChild(" - AudioEffects:"),this._telemetryLogManager=g.telemetryLogManager,this.updateAudioEffectsStatusManager()}get name(){return"AudioEffects"}get activeEffects(){return this._effectsStatusManager?.getActiveEffects?.()??this._activeEffects}on(g,f){if("effectsStarted"!==g&&"effectsStopped"!==g&&"effectsError"!==g&&"effectsProcessorStatsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}off(g,f){if("effectsStarted"!==g&&"effectsStopped"!==g&&"effectsError"!==g&&"effectsProcessorStatsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.off(g,f)}async isSupported(g){const f=generateGuid(),S=+new Date,v=this.getUsageDetailsForTelemetry("",this.getEffectsNameForTelemetry(g));this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.isSupported,kindOfEvent:gE.attempt,additionalDetails:{usageDetails:v}});try{if(this._logger?.info(`isSupported attempted with input ${g}`),this.disposed)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.SOURCE_UNSUPPORTED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const v=this._internalDeviceManager.getEnvironmentInfoInternal();this._supportChecker||(this._supportChecker=new EffectsCapabilityChecker(this._logger,v));let C=!1;if("object"==typeof g){const f=this.getEffectInternalCast(g);C=await this._supportChecker.audioEffectsSupported(f),this._logger?.info(`Support check for ${f.name} resulted in: ${C}`)}else"string"==typeof g&&(C=await this._supportChecker.audioEffectsSupported(g),this._logger?.info(`Support check for ${g} resulted in: ${C}`));const _=this.getEffectsNameForTelemetry(g),T=this.getUsageDetailsForTelemetry("",_);return this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.isSupported,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.success,additionalDetails:{usageDetails:T}}),this._logger?.info("isSupported success"),C}catch(v){const C=new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.SUPPORT_CHECK_FAILED,originalError:v});this._logger?.error(C.message);const _=this.getEffectsNameForTelemetry(g),T=this.getUsageDetailsForTelemetry("",_);throw this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.isSupported,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.failure,additionalDetails:{failureReason:C.message,code:C.code,...extractCommunicationServicesErrorForTelemetry(C),usageDetails:T}}),C}}async startEffects(g){const f=generateGuid(),S=+new Date,v=this.getUsageDetailsForTelemetry("",JSON.stringify(this.getEffectsConfigForTelemetry(g)));this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.startEffects,kindOfEvent:gE.attempt,additionalDetails:{usageDetails:v}});try{this._logger?.info(`startEffects attempted with input ${JSON.stringify(this.getEffectsConfigForTelemetry(g))}`);const v=getAcsEcsConfig();if(!v?.audioEffects?.enableAudioEffects)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.DISABLED});if(this.disposed)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.SOURCE_UNSUPPORTED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const C=this._internalDeviceManager.getTsDeviceManager();if(!C)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.START_DEVICE_MANAGER});await this.updateAudioEffectsStatusManager(),this.subscribeToStreamInstanceEvents(),this.disposeEffectEventSubscriptions(),this.subscribeToEffectEvents();let _=this.activeEffects;g?.autoGainControl&&(_=await this.startStopAutoGainControl(C,_,!0,g.autoGainControl)),g?.echoCancellation&&(_=await this.startStopEchoCancellation(C,_,!0,g.echoCancellation)),g?.noiseSuppression&&(_=await this.startStopNoiseSuppression(C,_,!0,g.noiseSuppression)),this._currentTsWasmEffectType!==this._previousTsWasmEffectType&&(this._logger?.info(`Setting tsDeviceManager setAudioEffectsAsync API with ${this._currentTsWasmEffectType}`),await C.setAudioEffectsAsync("",this._currentTsWasmEffectType)),this._effectsStatusManager?.setActiveEffects(_,"start"),await this.subscribeToStatUpdates();const T=JSON.stringify(_),I=this.getUsageDetailsForTelemetry("",T);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.startEffects,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.success,additionalDetails:{usageDetails:I}}),this._logger?.info("startEffects success")}catch(v){const C=new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.START_FAILED,originalError:v});this._logger?.error(C.message),this.eventEmitter.emit("effectsError",C);const _=JSON.stringify(this.getEffectsConfigForTelemetry(g)),T=this.getUsageDetailsForTelemetry("",_);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.startEffects,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.failure,additionalDetails:{failureReason:C.message,code:C.code,...extractCommunicationServicesErrorForTelemetry(C),usageDetails:T}})}}async stopEffects(g){const f=generateGuid(),S=+new Date,v=this.getUsageDetailsForTelemetry("",JSON.stringify(this.getEffectsConfigForTelemetry(g)));this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.stopEffects,kindOfEvent:gE.attempt,additionalDetails:{usageDetails:v}});try{if(this._logger?.info(`stopEffects attempted with input ${JSON.stringify(this.getEffectsConfigForTelemetry(g))}`),this.disposed)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.STOP_DISPOSED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const v=this._internalDeviceManager.getTsDeviceManager();if(!v)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.STOP_DEVICE_MANAGER});await this.updateAudioEffectsStatusManager();let C=this.activeEffects;g?.autoGainControl&&(C=await this.startStopAutoGainControl(v,C,!1)),g?.echoCancellation&&(C=await this.startStopEchoCancellation(v,C,!1)),g?.noiseSuppression&&(C=await this.startStopNoiseSuppression(v,C,!1)),this._currentTsWasmEffectType!==this._previousTsWasmEffectType&&(this._logger?.info(`Setting tsDeviceManager setAudioEffectsAsync API with ${this._currentTsWasmEffectType}`),await v.setAudioEffectsAsync("",this._currentTsWasmEffectType)),this._effectsStatusManager?.setActiveEffects(C,"stop"),this.unsubscribeFromStatUpdates(),this.unsubscribeFromStreamInstanceEvents();const _=JSON.stringify(C),T=this.getUsageDetailsForTelemetry("",_);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.success,additionalDetails:{usageDetails:T}}),this._logger?.info("stopEffects success")}catch(v){const C=new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.STOP_FAILED,originalError:v});this._logger?.error(C.message),this.eventEmitter.emit("effectsError",C);const _=JSON.stringify(this.getEffectsConfigForTelemetry(g)),T=this.getUsageDetailsForTelemetry("",_);this.sendFeatureUsageTelemetry({eventName:uE.acs_calling_media_stream,correlationId:f,operation:PE.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-S},kindOfEvent:gE.failure,additionalDetails:{failureReason:C.message,code:C.code,...extractCommunicationServicesErrorForTelemetry(C),usageDetails:T}})}}async dispose(){const stopEffectsIfStreamNotDisposed=async()=>{try{const g=this._internalDeviceManager?.getTsDeviceManager();if(g){let f=await this.startStopAutoGainControl(g,this._activeEffects,!1);f=await this.startStopEchoCancellation(g,f,!1),await this.startStopNoiseSuppression(g,f,!1)}}catch(g){this._logger?.info(`Error stopping effects before disposing: ${g.message}`)}};try{if(this._logger?.info("dispose attempt"),this.disposed)return void this._logger?.info("AudioEffects feature already disposed");await stopEffectsIfStreamNotDisposed(),this.unsubscribeFromStatUpdates(),this.unsubscribeFromStreamInstanceEvents(),this._currentEffects={},this._effectsStatusManager?.setActiveEffects({echoCancellation:[],noiseSuppression:[],autoGainControl:[]},"dispose"),this.eventEmitter.removeAllListeners(),this.serialQueue.dispose(),this._effectsStatusManager?.off("statusChanged",this.effectStatusChangedCallback),this.disposed=!0,this._logger?.info("AudioEffects feature disposed")}catch(g){const f=new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.DISPOSE_FAILED,originalError:g});this._logger?.error(f.message),this.eventEmitter.emit("effectsError",f)}}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}getEffectsSdkVersion(){let g=this._stringForUnknownInput;const f=this.getAnyActiveWasmEffect();return f&&f._internalHandle?.getVersion&&(g=f._internalHandle.getVersion()),this.truncateToMax(g)}getActiveEffectsForTelemetry(){return this.truncateToMax(JSON.stringify(this.activeEffects))}async updateAudioEffectsStatusManager(){if(this.streamInstance.canStartEffects){if(this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager),!this._effectsStatusManager)if(this._effectsStatusManager=this._internalDeviceManager.callStackAudioEffectsStatusManager,this._effectsStatusManager.on("statusChanged",this.effectStatusChangedCallback),this.streamInstance.canStartEffects){const g=await this.streamInstance.getMediaStream(),f=g?.getAudioTracks()?.[0],S=f?.getSettings();this._effectsStatusManager?.setActiveEffects({autoGainControl:S.autoGainControl?["BrowserAutoGainControl"]:[],echoCancellation:S.echoCancellation?["BrowserEchoCancellation"]:[],noiseSuppression:S.noiseSuppression?["BrowserNoiseSuppression"]:[]},"initialize")}else this._logger?.debug("Cannot process initial browser audio effects status, most likely LocalAudioStream source is not AudioDeviceInfo");this._activeEffects=this._effectsStatusManager.getActiveEffects(),this._browserAudioEffectsManager||(this._browserAudioEffectsManager=new BrowserAudioEffectsHelper(this._effectsStatusManager,this._logger,this.streamInstance))}else this._logger?.warn("Cannot update status manager, current source is not supported.")}async initializeWasmVqeInStack(g){if(this._wasmVqeInitialized)return void this._logger?.info("WasmVqe initialized already");if(!this._internalDeviceManager)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.FAILED_TO_GET_DM});const f=await g._internalHandle.getEffectProvider();if(!f)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.PROVIDER_UNAVAILABLE});const S=await f.getAudioEffectProvider(),v=this.streamInstance.callStackWasmVqeProvider;if(!v)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.AEC_PROVIDER_MISSING});v.providerValue=S,this._wasmVqeInitialized=!0}getEffectInternalCast(g){if("EchoCancellation"===g?.name&&this.isValidEffectInstance(g))return g;if("DeepNoiseSuppression"===g?.name&&this.isValidEffectInstance(g))return g;throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT})}isValidEffectInstance(g){let f;return("EchoCancellation"===g.name&&g._internalHandle||!("DeepNoiseSuppression"!==g.name||!g._internalHandle))&&(f=g,this.hasValidInternalHandle(f._internalHandle))}hasValidInternalHandle(g){return!!(g.getEffectProvider&&g.dispose&&g.setConfig&&g.handleProcessingError)}updateCurrentTsWasmAudioEffectType(g,f,S){const v=S??this._effectsStatusManager?.getActiveEffects();let C=!!v?.echoCancellation?.includes("EchoCancellation"),_=!!v?.noiseSuppression?.includes("DeepNoiseSuppression");switch(g){case"EchoCancellation":C=f;break;case"DeepNoiseSuppression":_=f}this._previousTsWasmEffectType=this._currentTsWasmEffectType,this._currentTsWasmEffectType=C&&_?16:C?4:_?2:0}subscribeToStreamInstanceEvents(){this._sourceStreamSubscription&&(this._logger?.info("Already subscribed to audioSourceChanged before, removing old sub"),this.streamInstance.off("audioSourceChanged",this._sourceStreamSubscription)),this._sourceStreamSubscription=async g=>{g.source&&"Audio"!==g.source.mediaStreamType&&await this.stopEffects({echoCancellation:!0,noiseSuppression:!0})},this.streamInstance.on("audioSourceChanged",this._sourceStreamSubscription)}unsubscribeFromStreamInstanceEvents(){this._sourceStreamSubscription?(this.streamInstance.off("audioSourceChanged",this._sourceStreamSubscription),this._sourceStreamSubscription=null):this._logger?.info("No audioSourceChanged sub active")}subscribeToEffectEvents(){"object"==typeof this._currentEffects.echoCancellation&&(this._currentEffects.echoCancellation?._internalHandle.on("configUpdated",this.configUpdatedCallback),this._currentEffects.echoCancellation?._internalHandle.on("processingError",this.processingErrorCallback)),"object"==typeof this._currentEffects.noiseSuppression&&(this._currentEffects.noiseSuppression?._internalHandle.on("configUpdated",this.configUpdatedCallback),this._currentEffects.noiseSuppression?._internalHandle.on("processingError",this.processingErrorCallback))}disposeEffectEventSubscriptions(){"object"==typeof this._currentEffects.echoCancellation&&(this._currentEffects.echoCancellation?._internalHandle.off("configUpdated",this.configUpdatedCallback),this._currentEffects.echoCancellation?._internalHandle.off("processingError",this.processingErrorCallback)),"object"==typeof this._currentEffects.noiseSuppression&&(this._currentEffects.noiseSuppression?._internalHandle.off("configUpdated",this.configUpdatedCallback),this._currentEffects.noiseSuppression?._internalHandle.off("processingError",this.processingErrorCallback))}setConfigForEffects(g){const f=g._internalHandle.configProvider.config.audioEffects,S=getMediaConfig(),v=getAcsEcsConfig();S?.wasmvqe?.enableVqe&&v?.audioEffects?.enableAudioEffects&&(f.enableAudioEffects=S?.wasmvqe?.enableVqe&&v.audioEffects.enableAudioEffects),g._internalHandle.setConfig(f),this._logger?.info(`Config for audio effects set: ${stringifyObject(f)}`)}async startStopAutoGainControl(g,f,S,v){try{if(S&&v){if(!await this.isSupported(v)){const g=this.getEffectsNameForTelemetry(v);throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.UNSUPPORTED_EFFECT,defaultErrorMessageArgs:[JSON.stringify(g)]})}if("BrowserAutoGainControl"!==v)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT_GAINCONTROL});return await(this._browserAudioEffectsManager?.setBrowserAudioEffects(g,f,{autoGainControl:!0})),this._logger?.info("Browser auto gain control started"),this._currentEffects.autoGainControl=v,f.autoGainControl=[v],f}switch(f?.autoGainControl?.[0]??""){case"":case"BrowserAutoGainControl":await(this._browserAudioEffectsManager?.setBrowserAudioEffects(g,f,{autoGainControl:!1})),this._logger?.info("Browser auto gain control stopped")}return f.autoGainControl=[],this._currentEffects.autoGainControl=void 0,f}catch(g){throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.SET_AUTO_GAIN_CONTROL,defaultErrorMessageArgs:[S],originalError:g})}}async startStopEchoCancellation(g,f,S,v){try{if(S&&v){if(!await this.isSupported(v)){const g=this.getEffectsNameForTelemetry(v);throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.UNSUPPORTED_EFFECT,defaultErrorMessageArgs:[JSON.stringify(g)]})}if("string"==typeof v&&"BrowserEchoCancellation"===v)"EchoCancellation"===f.echoCancellation[0]&&(await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType("EchoCancellation",!1,f),f.echoCancellation=[]),await(this._browserAudioEffectsManager?.setBrowserAudioEffects(g,f,{echoCancellation:!0})),this._logger?.info("Browser echo cancellation started"),this._currentEffects.echoCancellation=v,f.echoCancellation=[v];else{if("object"!=typeof v)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT_ECHO});this._currentEffects.echoCancellation=this.getEffectInternalCast(v),this.setConfigForEffects(this._currentEffects.echoCancellation),await this.initializeWasmVqeInStack(this._currentEffects.echoCancellation),this.updateCurrentTsWasmAudioEffectType(this._currentEffects.echoCancellation.name,!0,f),f.echoCancellation=[this._currentEffects.echoCancellation.name]}return f}switch(f?.echoCancellation?.[0]??""){case"":case"BrowserEchoCancellation":await(this._browserAudioEffectsManager?.setBrowserAudioEffects(g,f,{echoCancellation:!1})),this._logger?.info("Browser echo cancellation stopped");break;case"EchoCancellation":await this.initializeWasmVqeInStack(this._currentEffects.echoCancellation),this.updateCurrentTsWasmAudioEffectType("EchoCancellation",!1,f)}return f.echoCancellation=[],this._currentEffects.echoCancellation=void 0,f}catch(g){throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.SET_ECHO_CANCELLATION,defaultErrorMessageArgs:[S],originalError:g})}}async startStopNoiseSuppression(g,f,S,v){try{if(S&&v){if(!await this.isSupported(v)){const g=this.getEffectsNameForTelemetry(v);throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.UNSUPPORTED_EFFECT,defaultErrorMessageArgs:[JSON.stringify(g)]})}if("string"==typeof v&&"BrowserNoiseSuppression"===v)"DeepNoiseSuppression"===f.noiseSuppression[0]&&(await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType("DeepNoiseSuppression",!1,f),f.noiseSuppression=[]),await(this._browserAudioEffectsManager?.setBrowserAudioEffects(g,f,{noiseSuppression:!0})),this._logger?.info("Browser noise cancellation started"),f.noiseSuppression=[v],this._currentEffects.noiseSuppression=v;else{if("object"!=typeof v)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT_NOISE_SUPP});this._currentEffects.noiseSuppression=this.getEffectInternalCast(v),this.setConfigForEffects(this._currentEffects.noiseSuppression),await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType(this._currentEffects.noiseSuppression.name,!0,f),f.noiseSuppression=[this._currentEffects.noiseSuppression.name]}return f}switch(f?.noiseSuppression?.[0]??""){case"":case"BrowserNoiseSuppression":await(this._browserAudioEffectsManager?.setBrowserAudioEffects(g,f,{noiseSuppression:!1})),this._logger?.info("Browser noise suppression stopped");break;case"DeepNoiseSuppression":await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType("DeepNoiseSuppression",!1,f)}return f.noiseSuppression=[],this._currentEffects.noiseSuppression=void 0,f}catch(g){throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.SET_NOISE_SUPPRESSION,defaultErrorMessageArgs:[S],originalError:g})}}sendFeatureUsageTelemetry(g){if(this._telemetryLogManager){g.additionalDetails={...g.additionalDetails,callState:this.streamInstance.getCall()?.state,activeEffects:JSON.stringify(this.activeEffects),effectsSdk:{version:this.getEffectsSdkVersion()}};try{const f={correlationId:g.correlationId,mediaType:bE.AudioRaw,streamType:AE.Local,operation:g.operation,timestampInfo:g.timestampInfo||{},kindOfEvent:g.kindOfEvent||"",additionalDetails:g.additionalDetails||"",callId:this.streamInstance.getCall()?.id||"",localParticipantId:this.streamInstance.getLocalParticipantId()||""};this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:f})}catch(f){this._logger?.debug(`Unable to send ${g.operation} telemetry`)}}else this._logger?.debug("Telemetry error. Instance is undefined.")}getAnyActiveWasmEffect(){let g=null;for(const f of Object.values(this._currentEffects))f&&"object"==typeof f&&(g=f);return g}getEffectsConfigForTelemetry(g){let f=!1;"boolean"!=typeof g?.autoGainControl&&"boolean"!=typeof g?.echoCancellation&&"boolean"!=typeof g?.noiseSuppression||(f=!0);let S={};return S=f?{autoGainControl:g?.autoGainControl&&"boolean"==typeof g?.autoGainControl?g?.autoGainControl:void 0,echoCancellation:g?.echoCancellation&&"boolean"==typeof g?.echoCancellation?g?.echoCancellation:void 0,noiseSuppression:g?.noiseSuppression&&"boolean"==typeof g?.noiseSuppression?g?.noiseSuppression:void 0}:{autoGainControl:this.getEffectsNameForTelemetry(g?.autoGainControl),echoCancellation:this.getEffectsNameForTelemetry(g?.echoCancellation),noiseSuppression:this.getEffectsNameForTelemetry(g?.noiseSuppression)},Object.keys(S).forEach((g=>{""!==S[g]&&void 0!==S[g]||delete S[g]})),S}getEffectsNameForTelemetry(g){return g?"string"==typeof g?this.truncateToMax(g):g?.name&&"string"==typeof g?.name?this.truncateToMax(g.name):(this._logger?.warn("Invalid effect object found"),this._stringForUnknownInput):""}getUsageDetailsForTelemetry(g,f){const S=`${f?`[${f}]`:""}:${g??""}`;return this.truncateToMax(S)}truncateToMax(g){const f=getAcsEcsConfig().audioEffects.maxStringLengthForTelemetry;return g.length>f?(this._logger?.info("Truncating audio effects info for telemetry"),g.substring(0,f-2)+".."):g}}__decorate$6([sequentialize(),__metadata$6("design:type",Function),__metadata$6("design:paramtypes",[Object]),__metadata$6("design:returntype",Promise)],AudioEffectsFeatureImpl.prototype,"startEffects",null),__decorate$6([sequentialize(),__metadata$6("design:type",Function),__metadata$6("design:paramtypes",[Object]),__metadata$6("design:returntype",Promise)],AudioEffectsFeatureImpl.prototype,"stopEffects",null);var q_,W_,z_,__decorate$7=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$7=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class LocalAudioStream{constructor(g){this._calls=new Set,this.canStartEffects=!1;const S=f.createClientLogger("ACS-calling");if(this.logger=new DefaultLogger(S,[()=>`LocalAudioStream for default device with source: ${!!g}`]),this._eventEmitter=new CallingEventEmitter(this.logger),this._disposed=!1,!(g instanceof AudioDeviceInfoImpl||g instanceof MediaStream))throw new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.WRONG_STREAM_TYPE});if(g instanceof AudioDeviceInfoImpl&&"Microphone"!==g.deviceType)throw new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.SOURCE_WRONG_TYPE});this.setSource(g,!0),this._localStreamTelemetryEventSender=new StreamTelemetryEventSender(this._telemetryLogManager),this._volumeIndicator=new VolumeImpl(this.logger,"LocalAudioStream",this._telemetryLogManager),this.logger.info("created")}on(g,f){if("audioSourceChanged"!==g)throw new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("audioSourceChanged"!==g)throw new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}feature(g){return this._extensibleApi||(this._extensibleApi=new ExtensibleFeatureImpl(this.logger,{streamInstance:this},{streamInstance:this,telemetryLogManager:this.telemetryLogManager})),this._extensibleApi.getApiObjectInstance(g.audioStreamApiCtor)}get mediaStreamType(){return this._mediaStreamType}get source(){return this._source}get telemetryLogManager(){return this._telemetryLogManager}get callStackWasmVqeProvider(){return this.source?.deviceManager?.callStackWasmVqeProvider??null}get callStackEffectsStatusManager(){return this.source?.deviceManager?.callStackAudioEffectsStatusManager??null}addCall(g){this._calls.add(g)}removeCall(g){this._calls.delete(g)}getCall(){for(const g of this._calls)if(g.localAudioStreams.includes(this))return g}getLocalParticipantId(){let g="";const f=this.getCall();return f&&(g=f.tsCall.participantId),g}async getMediaStream(){const g=generateGuid(),f=+new Date,S={timestampInfo:{attemptTimestamp:f},correlationId:g,operation:PE.getMediaStream,kindOfEvent:gE.attempt,mediaType:bE.AudioRaw,streamType:AE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(S),this.subscribeToRawStreamChangedIfNeeded(),this._mediaStreamSource){const S={correlationId:g,mediaType:bE.AudioRaw,operation:PE.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-f},streamType:AE.Local,kindOfEvent:gE.success};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(S),this._mediaStreamSource}if(this._source instanceof AudioDeviceInfoImpl)try{this._rawStream||(this._rawStream=this._source.deviceManager.getRawDeviceMediaStream(0));const S=await(this._rawStream?.getMediaStream()),v={correlationId:g,mediaType:bE.AudioRaw,operation:PE.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-f},streamType:AE.Local,kindOfEvent:gE.success};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(v),S}catch(v){const S=new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.GET_MEDIA_STREAM,originalError:v}),C={correlationId:g,operation:PE.getMediaStream,additionalDetails:{failureReason:S.message,code:S.code,...extractCommunicationServicesErrorForTelemetry(S)},timestampInfo:{deltaTimeInMs:+new Date-f},kindOfEvent:gE.failure,mediaType:bE.AudioRaw,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(C),S}const v=new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.GET_MEDIA_STREAM}),C={timestampInfo:{deltaTimeInMs:+new Date-f},correlationId:g,operation:PE.getMediaStream,additionalDetails:{failureReason:v.message,code:x,...extractCommunicationServicesErrorForTelemetry(v)},kindOfEvent:gE.failure,mediaType:bE.AudioRaw,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(C),v}async setMediaStream(g){const f=generateGuid();let S=+new Date;const v={timestampInfo:{attemptTimestamp:S},correlationId:f,operation:PE.setMediaStream,kindOfEvent:gE.attempt,mediaType:bE.AudioRaw,streamType:AE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(v),!(g instanceof MediaStream)){const g=new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.SET_MEDIA_STREAM_WRONG_TYPE}),v={timestampInfo:{deltaTimeInMs:+new Date-S},correlationId:f,operation:PE.setMediaStream,additionalDetails:{failureReason:g.message,code:g.code,...extractCommunicationServicesErrorForTelemetry(g)},kindOfEvent:gE.failure,mediaType:bE.AudioRaw,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(v),g}this._mediaStreamSource=new MediaStream(g.getAudioTracks()),this.setSource(this._mediaStreamSource),this._volumeIndicator.dispose();const C={correlationId:f,mediaType:bE.AudioRaw,operation:PE.setMediaStream,timestampInfo:{deltaTimeInMs:+new Date-S},streamType:AE.Local,kindOfEvent:gE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(C)}async switchSource(g){const f=+new Date,S=generateGuid(),v={timestampInfo:{attemptTimestamp:f},correlationId:S,operation:PE.switchSource,kindOfEvent:gE.attempt,mediaType:bE.Audio,streamType:AE.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(v),g instanceof AudioDeviceInfoImpl&&"Microphone"!==g.deviceType){const g=new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.SWITCH_SOURCE_WRONG_TYPE}),v={timestampInfo:{deltaTimeInMs:+new Date-f},correlationId:S,operation:PE.switchSource,additionalDetails:{failureReason:g.message,code:g.code,...extractCommunicationServicesErrorForTelemetry(g)},kindOfEvent:gE.failure,mediaType:bE.Audio,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(v),g}if(this._source===g){const g=new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.SWITCH_SAME_SOURCE}),v={timestampInfo:{deltaTimeInMs:+new Date-f},correlationId:S,operation:PE.switchSource,additionalDetails:{failureReason:g.message,code:g.code,...extractCommunicationServicesErrorForTelemetry(g)},kindOfEvent:gE.failure,mediaType:bE.Audio,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(v),g}try{this._source.deviceManager.selectMicrophone(g),this.setSource(g),this._volumeIndicator.dispose();const v={correlationId:S,mediaType:bE.Audio,operation:PE.switchSource,timestampInfo:{deltaTimeInMs:+new Date-f},streamType:AE.Local,kindOfEvent:gE.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(v)}catch(g){const v=new CallingCommunicationError({defaultError:D.LOCAL_AUDIO_STREAM.UNKNOWN,originalError:g}),C={timestampInfo:{deltaTimeInMs:+new Date-f},correlationId:S,operation:PE.switchSource,additionalDetails:{failureReason:v.message,code:v.code,...extractCommunicationServicesErrorForTelemetry(v)},kindOfEvent:gE.failure,mediaType:bE.Audio,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(C),v}}dispose(){this.logger.log("LocalAudioStream disposing"),this._disposed?this.logger.log("Already disposed"):(this.disposeRawStream(),this._volumeIndicator.dispose(),this._extensibleApi?.dispose(),this._eventEmitter.removeAllListeners(),this._disposed=!0,this.logger.log("LocalAudioStream disposed"))}async getVolume(){return this._volumeIndicator.isInitialized?this._volumeIndicator:this._volumeIndicator.getVolumeIndicator(await this.getMediaStream())}subscribeToRawStreamChangedIfNeeded(){this._source instanceof AudioDeviceInfoImpl&&!this._audioSourceChangedSub&&(this._audioSourceChangedSub=this._rawStream?.changed((()=>{this._volumeIndicator.dispose(),this._eventEmitter.emit("audioSourceChanged",{source:this})})))}disposeRawStream(){this._audioSourceChangedSub?.dispose(),this._rawStream?.dispose(),this._audioSourceChangedSub=void 0}getStreamMetadata(){const g=this.source.deviceManager;return{source:"local",streamType:this.mediaStreamType,deviceType:this.source.deviceType,deviceManagerPermissionState:JSON.stringify({cameraPermission:g.getVideoDevicePermission(),microphonePermission:g.getAudioDevicePermission()}),acsResourceId:g.getAcsResourceId()||"",clientId:g.getClientId()}}getEffectsCurrentStateRecord(){try{const g=this.feature(audioStreamFeatureFactory(AudioEffectsFeatureImpl)),f=g.getEffectsSdkVersion();return{activeEffects:g.getActiveEffectsForTelemetry(),effectsSdk:{version:f}}}catch(g){return void this.logger.warn(`Error while getting current effect state on LocalAudioStream for telemetry: ${g}`)}}setSource(g,f=!1){if(g instanceof AudioDeviceInfoImpl)this._telemetryLogManager=g.deviceManager.telemetryLogManager,this._source=g,this._mediaStreamType="Audio",this._mediaStreamSource=void 0,this._rawStream=void 0,this.canStartEffects=!0;else{try{1===globalThis[Lf]&&(this._telemetryLogManager=globalThis[kf])}catch(g){this.logger.error("Failed to retrive telemetry logger for localAudioStream")}this._source={name:"CustomMediaStream",id:generateGuid(),deviceType:"Virtual",isSystemDefault:!1},this._mediaStreamSource=g,this._mediaStreamType="RawMedia",this.canStartEffects=!1}f||this._eventEmitter.emit("audioSourceChanged",{source:this})}}__decorate$7([loggerProperty,__metadata$7("design:type",Object)],LocalAudioStream.prototype,"logger",void 0),__decorate$7([syncOperation(LS.Feature),__metadata$7("design:type",Function),__metadata$7("design:paramtypes",[Object]),__metadata$7("design:returntype","function"==typeof(q_="undefined"!=typeof TFeature&&TFeature)?q_:Object)],LocalAudioStream.prototype,"feature",null),__decorate$7([asyncOperation(LS.GetMediaStream),__metadata$7("design:type",Function),__metadata$7("design:paramtypes",[]),__metadata$7("design:returntype",Promise)],LocalAudioStream.prototype,"getMediaStream",null),__decorate$7([asyncOperation(LS.SetMediaStream),__metadata$7("design:type",Function),__metadata$7("design:paramtypes",[MediaStream]),__metadata$7("design:returntype",Promise)],LocalAudioStream.prototype,"setMediaStream",null),__decorate$7([asyncOperation(LS.SwitchSource),__metadata$7("design:type",Function),__metadata$7("design:paramtypes",[Object]),__metadata$7("design:returntype",Promise)],LocalAudioStream.prototype,"switchSource",null),function(g){g[g.JITTER=0]="JITTER",g[g.RTT=1]="RTT",g[g.PACKETS_LOSS=2]="PACKETS_LOSS",g[g.BIT_RATE=3]="BIT_RATE",g[g.BANDWIDTH=4]="BANDWIDTH"}(W_||(W_={})),function(g){g[g.AUDIO=0]="AUDIO",g[g.VIDEO=1]="VIDEO"}(z_||(z_={}));const K_="Unknown";var J_,Y_;function collectMediaStatsForCreateView(g,f,S,v){const C=getAcsEcsConfig()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength,_=getAcsEcsConfig()?.rendering.remoteVideo.createViewSendMediaStatsInitialMaxLength,T=["bitrate","packetsPerSecond","packetsLostPerSecond","jitterInMs","rttInMs","pairRttInMs","healedRatio","lossRate"],I=["bitrate","packetsPerSecond","packetsLostPerSecond","jitterInMs","rttInMs","pairRttInMs","frameRateDecoded","frameRateReceived","frameWidthReceived","frameHeightReceived","longestFreezeDurationInMs","totalFreezeDurationInMs","framesReceived","framesDropped","framesDecoded","keyFramesDecoded"],b=I;if(S.audio.receive.length>0){const v=S.audio.receive[0];g.audio=g.audio??{},f.audio=f.audio??{},T.forEach((S=>{const T=S;if(void 0!==v[T]&&g.audio){const f=v[T];if(void 0===g.audio[T])g.audio[T]=[f];else{const S=g.audio[T]?.length;S>=C&&g.audio[T]?.shift(),g.audio[T]?.push(f)}}if(void 0!==v[T]&&f.audio){const g=v[T];if(void 0===f.audio[T])f.audio[T]=[g];else{const S=f.audio[T]?.length;S<_&&f.audio[T]?.push(g)}}}))}if(S.video.receive.length>0){const T=S.video.receive.find((g=>g.streamId===v));void 0!==T&&(g.video=g.video??{},f.video=f.video??{},I.forEach((S=>{const v=S;if(void 0!==T[v]&&g.video){const f=T[v];if(void 0===g.video[v])g.video[v]=[f];else{const S=g.video[v]?.length;S>=C&&g.video[v]?.shift(),g.video[v]?.push(f)}}if(void 0!==T[v]&&f.video){const g=T[v];if(void 0===f.video[v])f.video[v]=[g];else{const S=f.video[v]?.length;S<_&&f.video[v]?.push(g)}}})))}if(S.screenShare.receive.length>0){const T=S.screenShare.receive.find((g=>g.streamId===v));void 0!==T&&(g.screenShare=g.screenShare??{},f.screenShare=f.screenShare??{},b.forEach((S=>{const v=S;if(void 0!==T[v]&&g.screenShare){const f=T[v];if(void 0===g.screenShare[v])g.screenShare[v]=[f];else{const S=g.screenShare[v]?.length;S>=C&&g.screenShare[v]?.shift(),g.screenShare[v]?.push(f)}}if(void 0!==T[v]&&f.screenShare){const g=T[v];if(void 0===f.screenShare[v])f.screenShare[v]=[g];else{const S=f.screenShare[v]?.length;S<_&&f.screenShare[v]?.push(g)}}})))}}function calculateFirstAverage(g){if(g?.count.length&&g?.count[0]){return getRoundedAverage(g.sum[0],g.count[0])}return NaN}function calculateFirstSum(g){return g?.count.length&&g?.count[0]?g.sum[0]:NaN}!function(g){g.Supported="Supported",g.NotSupported="NotSupported",g.Unknown="Unknown"}(J_||(J_={})),function(g){g.CompleteTest="CompleteTest",g.StartTest="StartTest",g.DeviceAccess="DeviceAccess",g.DeviceEnumerations="DeviceEnumerations",g.InCallDiagnostics="InCallDiagnostics",g.BrowserSupport="BrowserSupport"}(Y_||(Y_={}));class PreCallDiagnosticsFeatureImpl extends FirstPartyCallClientFeature{constructor(g){super(g),this._impl=new PreCallDiagnosticsImpl}initialize(g,f){const S=g.callClient;this._logger=f;const v={diagnostics:{tags:["diagnostics"]}},C=S.createInstance(v);this._telemetryLogManager=C.telemetryLogManager,this._impl.intialize(S,C,f,this._telemetryLogManager),this._sendFeatureUsage("initialize",gE.initialize)}get name(){return this._sendFeatureUsage("name",gE.getter),"PreCallDiagnostics"}startTest(g,f){return this._impl.startTest(g,f)}_sendFeatureUsage(g,f){sendCallClientFeatureUsageTelemetry({featureName:"PreCallDiagnostics",featureType:"CallClient",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",gE.attempt),this.disposed?this._sendFeatureUsage("dispose",gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",gE.success))}}class PreCallDiagnosticsImpl{constructor(){this._printableObjectAll=!0,this._completeTestInfo={name:"",succeeded:!0},this._diagnosticsTestRunIds=[],this._callMediaStatistics=defer(),this._inCallDiagnostics={connected:!1,diagnostics:{audio:{jitter:K_,packetLoss:K_,rtt:K_},video:{jitter:K_,packetLoss:K_,rtt:K_}},bandWidth:K_},this._diagnosticsMediaTelemetry={jitter:{audio:{inbound:0,outbound:0},video:{inbound:0,outbound:0}},rtt:{audio:0,video:0},packets:{audioSent:0,audioSentLost:0,audioReceived:0,audioReceivedLost:0,videoSent:0,videoSentLost:0,videoReceived:0,videoReceivedLost:0},bandWidth:0},this._isCreatingNewCallAgent=!1}intialize(g,f,S,v){this._internalCallClient=f,this._mainCallClient=g,this._logger=S,this._telemetryLogManager=v}async getDevices(g,f){let S=[];try{switch(f){case"Speaker":S=await g.getSpeakers();break;case"Microphone":S=await g.getMicrophones();break;default:S=await g.getCameras()}}catch(g){this._logger.warn("Failed to get speakers")}return S}async startTest(g,f){this._sendFeatureUsage("startTest",gE.attempt),this._currentTestRunId=generateGuid(),this._diagnosticsTestRunIds.push(this._currentTestRunId),this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:Y_.CompleteTest}}),this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:Y_.StartTest}});try{this._internalDeviceManager=await this._internalCallClient.getDeviceManager();const g=this._internalCallClient.callAgent,f=await this._mainCallClient.getDeviceManager(),S=await(g?.tsStack?.getDeviceManagerAsync?.());await(S?.selectDevicesAsync?.({speaker:f.selectedSpeaker?.id,microphone:f.selectedMicrophone?.id}));const v=await this._internalCallClient.getDeviceManager(),C={mic:(await this.getDevices(v,"Microphone")).length,speaker:(await this.getDevices(v,"Speaker")).length};this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.StartTest,!0,`Device selection successful. Result: ${getPrintableObject(C,this._printableObjectAll)}`)})}catch(g){const f=new CallingCommunicationError({defaultError:D.FEATURES.PRECALL_DIAGNOSTICS.SET_DEVICE_FAIL,originalError:g});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.StartTest,!1,"Device selection failed."),additionalDetails:{...extractCommunicationServicesErrorForTelemetry(f)}}),this._logger.warn(g),this._sendFeatureUsage("startTest",gE.failure),f}try{return this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.StartTest,!0,"StartTest succeeded")}),this._sendFeatureUsage("startTest",gE.success),f?{deviceAccess:f.deviceAccess?this.deviceAccess():void 0,deviceEnumeration:f.deviceEnumeration?this.deviceEnumeration():void 0,inCallDiagnostics:f.inCallDiagnostics?this.getInCallDiagnostics(g):void 0,browserSupport:f.browserSupport?this.getBrowserSupport():void 0,callMediaStatistics:f.callMediaStatistics?this.getcallMediaStatistics():void 0,id:this._currentTestRunId}:{deviceAccess:this.deviceAccess(),deviceEnumeration:this.deviceEnumeration(),inCallDiagnostics:this.getInCallDiagnostics(g),browserSupport:this.getBrowserSupport(),callMediaStatistics:this.getcallMediaStatistics(),id:this._currentTestRunId}}catch(g){const f=new CallingCommunicationError({defaultError:D.FEATURES.PRECALL_DIAGNOSTICS.GET_DIAGNOSTICS_INFO,originalError:g});throw this._logger.error(f.message),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.StartTest,!1,"StartTest failed."),additionalDetails:{...extractCommunicationServicesErrorForTelemetry(f)}}),this._sendFeatureUsage("startTest",gE.failure),f}}async getBrowserSupport(){let g;this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:Y_.BrowserSupport}});try{const f=await this._mainCallClient.getEnvironmentInfoInternal();g={browser:f.isSupportedBrowser?J_.Supported:J_.NotSupported,os:f.isSupportedPlatform?J_.Supported:J_.NotSupported},this.updateTestInfo(Y_.BrowserSupport,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Browser support successful. Result: ${getPrintableObject(g,this._printableObjectAll)}`,name:Y_.BrowserSupport}})}catch(f){g={browser:J_.Unknown,os:J_.Unknown},this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.BrowserSupport,!1,`Browser support failed. Error: ${getPrintableObject(f)}`)}),this._logger.error(`Browser support failed: ${f}`)}return new Promise((f=>f(g)))}async renderHiddenVideoElement(g,f){let S,v=g.tsCall,C=v.mediaStreams;try{await new Promise(((g,f)=>{S=v.changed((()=>{void 0!==C[0]&&C[0].length>0&&C[0][0].isAvailable&&(g(),S?.dispose(),this.updateTestInfo(Y_.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:"Call mediaStreams successful.",name:Y_.InCallDiagnostics}}))})),setTimeout((()=>{this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.InCallDiagnostics,!1,"Call mediaStreams failed. Error: Timeout")}),f(new CallingCommunicationError({defaultError:D.FEATURES.PRECALL_DIAGNOSTICS.VIDEO_STREAM_TIMEOUT}))}),1e3*this._diagnosticsEcsConfig.CALL.MEDIASTREAM_TIMEOUT_IN_SEC)}));let _=v.mediaStreams[0][0],T=document.getElementById("_hiddenSelfRemoteStream");T&&T.remove(),T=document.createElement("div"),T.id="_hiddenSelfRemoteStream",T.style.position="relative",T.style.height="0px",T.style.width="0px";const I=document.createElement("div");I.style.position="absolute",I.style.height=this._diagnosticsEcsConfig.CALL.VIDEO_SIZE.heigth+"px",I.style.width=this._diagnosticsEcsConfig.CALL.VIDEO_SIZE.width+"px",I.style.bottom="0px",I.style.left="-2000px",T.appendChild(I),document.getElementsByTagName("body")[0].appendChild(T),this.updateTestInfo(Y_.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Video element rendering successful. CallId: ${g.id}, localParticipantId: ${f}`,name:Y_.InCallDiagnostics}}),await _.start(I)}catch(g){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.InCallDiagnostics,!1,`Call mediaStreams failed. Error: ${getPrintableObject(g)}`)}),this._logger.warn("Failed to render hidden video element")}}sineWaveAudioStream(){const g=new window.AudioContext,f=g.createMediaStreamDestination(),S=g.createOscillator();S.type="sine",S.frequency.value=500,S.connect(f),S.start();const{stream:v}=f;return new LocalAudioStream(v)}async receiveAndPlayCallAudio(g,f){try{const S=new window.AudioContext,v=new MediaStream;S.createMediaStreamSource(v).connect(S.destination),this.updateTestInfo(Y_.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Call mediaStreams audio track succeeded. CallId: ${g.id}, localParticipantId: ${f}`,name:Y_.InCallDiagnostics}})}catch(g){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.InCallDiagnostics,!1,`Call mediaStreams audio track failed. Error: ${getPrintableObject(g)}`)}),this._logger.warn("Failed to send audio to call.")}}async getcallMediaStatistics(){return this._callMediaStatistics.promise}setEcsConfig(){this._diagnosticsEcsConfig=getAcsEcsConfig()?.calling?.callDiagnostics}async getInCallDiagnostics(g){this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:Y_.InCallDiagnostics}}),this.setEcsConfig();const f={groupId:this._diagnosticsEcsConfig.CALL.GROUP_ID},S=await this.getDevices(this._internalDeviceManager,"Camera");let v,C="";0!==S.length&&(v=[new LocalVideoStream(S[0])]);const _={videoOptions:{localVideoStreams:v},audioOptions:{muted:!1,localAudioStreams:[this.sineWaveAudioStream()]}};let T;try{T=await(this._mainCallClient.callAgent?.getExistingCallAgentWithToken(g)),T?this._internalCallClient.setCallAgent(T):(this._isCreatingNewCallAgent=!0,await this._internalCallClient.createCallAgent(g)),this.updateTestInfo(Y_.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:"Create CallAgent successful.",name:Y_.InCallDiagnostics}})}catch(g){const f=new CallingCommunicationError({defaultError:D.FEATURES.PRECALL_DIAGNOSTICS.GET_CALL_AGENT,originalError:g});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.InCallDiagnostics,!1,f.message),additionalDetails:{...extractCommunicationServicesErrorForTelemetry(f)}}),this._logger.error(f.message),f}const I=this._internalCallClient.callAgent?.join(f,_);if(I){try{await this.waitCallConnected(I),C=I.tsCall.participantId,this.updateTestInfo(Y_.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:"Call connected successfully",name:Y_.InCallDiagnostics}})}catch(g){const f=new CallingCommunicationError({defaultError:D.FEATURES.PRECALL_DIAGNOSTICS.CONNECT_FAIL,originalError:g});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.InCallDiagnostics,!1,f.message),additionalDetails:{...extractCommunicationServicesErrorForTelemetry(f)}}),this._logger.error(f.message),f}try{this.updateTestInfo(Y_.InCallDiagnostics,!0),await this.renderHiddenVideoElement(I,C)}catch(g){const f=new CallingCommunicationError({defaultError:D.FEATURES.PRECALL_DIAGNOSTICS.RENDER_VIDEO,originalError:g});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.InCallDiagnostics,!1,f.message),additionalDetails:{...extractCommunicationServicesErrorForTelemetry(f)}}),f}this.receiveAndPlayCallAudio(I,C);const g=I.feature(callFeatureFactory(MediaStatsCallFeatureImpl,{activationEvent:"OnExtendedObjectConstructor"}));this._callMediaStatistics.resolve(g);g.createCollector({aggregationInterval:this._diagnosticsEcsConfig.CALL.AGGREGATION.INTERVAL,dataPointsPerAggregation:this._diagnosticsEcsConfig.CALL.AGGREGATION.DATAPOINTS}).on("summaryReported",(g=>this.gatherCallStatistics(g)));try{await sleep(1e3*this._diagnosticsEcsConfig.CALL.DURATION_IN_SEC),await I.hangUp({forEveryone:!0}),this.updateTestInfo(Y_.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Call hangup successful. Result: ${getPrintableObject(this._inCallDiagnostics,this._printableObjectAll)}`,name:Y_.InCallDiagnostics}})}catch(g){const f=new CallingCommunicationError({defaultError:D.FEATURES.PRECALL_DIAGNOSTICS.HANGUP_FAIL,originalError:g});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.InCallDiagnostics,!1,f.message),additionalDetails:{...extractCommunicationServicesErrorForTelemetry(f)}}),this._logger.error(f.message),f}this.dispose()}return this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:this._completeTestInfo.succeeded,result:this._completeTestInfo.result||"InCallDiagnostics succeeded.",name:Y_.CompleteTest}}),this._inCallDiagnostics}async waitCallConnected(g){await new Promise((async(f,S)=>{g.on("stateChanged",(()=>{"Connected"==g.state&&(this._inCallDiagnostics.connected=!0,f()),"Disconnected"==g.state&&S("Call disconnected")}));const v=this._diagnosticsEcsConfig.CALL.CONNECT_TIMEOUT_IN_SEC;await sleep(1e3*v),S(new CallingCommunicationError({defaultError:D.FEATURES.PRECALL_DIAGNOSTICS.CALL_CONNECT_TIMEOUT,defaultErrorMessageArgs:[v]}))}))}qualityGrade(g,f,S){return g<=f?"Good":g>=S?"Bad":"Average"}bandwidthQualityGrade(g,f,S){return g>=f?"Good":g<=S?"Bad":"Average"}getQualityGradeForMetric(g,f,S){switch(g){case W_.JITTER:return S===z_.AUDIO?this.qualityGrade(f,this._diagnosticsEcsConfig.AUDIO.JITTER.GOOD,this._diagnosticsEcsConfig.AUDIO.JITTER.AVERAGE):this.qualityGrade(f,this._diagnosticsEcsConfig.VIDEO.JITTER.GOOD,this._diagnosticsEcsConfig.VIDEO.JITTER.AVERAGE);case W_.RTT:return S===z_.AUDIO?this.qualityGrade(f,this._diagnosticsEcsConfig.AUDIO.RTT.GOOD,this._diagnosticsEcsConfig.AUDIO.RTT.AVERAGE):this.qualityGrade(f,this._diagnosticsEcsConfig.VIDEO.RTT.GOOD,this._diagnosticsEcsConfig.VIDEO.RTT.AVERAGE);case W_.PACKETS_LOSS:return S===z_.AUDIO?this.qualityGrade(f,this._diagnosticsEcsConfig.AUDIO.PACKETS_LOSS_PERCENTAGE.GOOD,this._diagnosticsEcsConfig.AUDIO.PACKETS_LOSS_PERCENTAGE.AVERAGE):this.qualityGrade(f,this._diagnosticsEcsConfig.VIDEO.PACKETS_LOSS_PERCENTAGE.GOOD,this._diagnosticsEcsConfig.VIDEO.PACKETS_LOSS_PERCENTAGE.AVERAGE);case W_.BANDWIDTH:return this.bandwidthQualityGrade(f,this._diagnosticsEcsConfig.BANDWIDTH.GOOD,this._diagnosticsEcsConfig.BANDWIDTH.AVERAGE);default:return K_}}gatherCallStatistics(g){try{const f=g.audio.receive.length?g.audio.receive[0]:void 0,S=g.audio.send.length?g.audio.send[0]:void 0,v=g.video.receive.length?g.video.receive[0]:void 0,C=g.video.send.length?g.video.send[0]:void 0,_=g.transports.length?g.transports[0]:void 0;this._diagnosticsMediaTelemetry.jitter.audio.inbound=calculateFirstAverage(f?.jitterInMs?.aggregation),this._diagnosticsMediaTelemetry.jitter.audio.outbound=calculateFirstAverage(S?.jitterInMs?.aggregation);const T=Math.max(this._diagnosticsMediaTelemetry.jitter.audio?.inbound,this._diagnosticsMediaTelemetry.jitter.audio?.outbound);this._inCallDiagnostics.diagnostics.audio.jitter=this.getQualityGradeForMetric(W_.JITTER,T,z_.AUDIO),this._diagnosticsMediaTelemetry.rtt.audio=calculateFirstAverage(S?.rttInMs?.aggregation),this._inCallDiagnostics.diagnostics.audio.rtt=this.getQualityGradeForMetric(W_.JITTER,this._diagnosticsMediaTelemetry.rtt.audio,z_.AUDIO),this._diagnosticsMediaTelemetry.packets.audioSent=calculateFirstSum(S?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.audioSentLost=calculateFirstSum(S?.packetsLostPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.audioReceived=calculateFirstSum(f?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.audioReceivedLost=calculateFirstSum(f?.packetsLostPerSecond?.aggregation);const I=this._diagnosticsMediaTelemetry.packets.audioSent-this._diagnosticsMediaTelemetry.packets.audioSentLost,b=this._diagnosticsMediaTelemetry.packets.audioReceived-this._diagnosticsMediaTelemetry.packets.audioReceivedLost,A=Math.max(I,b)/this._diagnosticsMediaTelemetry.packets.audioSent*100;this._inCallDiagnostics.diagnostics.audio.packetLoss=this.getQualityGradeForMetric(W_.PACKETS_LOSS,A,z_.AUDIO),this._diagnosticsMediaTelemetry.jitter.video.inbound=calculateFirstAverage(v?.jitterInMs?.aggregation),this._diagnosticsMediaTelemetry.jitter.video.outbound=calculateFirstAverage(C?.jitterInMs?.aggregation);const P=Math.max(this._diagnosticsMediaTelemetry.jitter.video.inbound,this._diagnosticsMediaTelemetry.jitter.video.outbound);this._inCallDiagnostics.diagnostics.video.jitter=this.getQualityGradeForMetric(W_.JITTER,P,z_.VIDEO),this._diagnosticsMediaTelemetry.rtt.video=calculateFirstAverage(C?.rttInMs?.aggregation),this._inCallDiagnostics.diagnostics.video.rtt=this.getQualityGradeForMetric(W_.RTT,this._diagnosticsMediaTelemetry.rtt.video,z_.VIDEO),this._diagnosticsMediaTelemetry.packets.videoSent=calculateFirstSum(C?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.videoSentLost=calculateFirstSum(C?.packetsLostPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.videoReceived=calculateFirstSum(v?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.videoReceivedLost=calculateFirstSum(v?.packetsLostPerSecond?.aggregation);const R=this._diagnosticsMediaTelemetry.packets.videoSent-this._diagnosticsMediaTelemetry.packets.videoSentLost,M=this._diagnosticsMediaTelemetry.packets.videoReceived-this._diagnosticsMediaTelemetry.packets.videoReceivedLost,w=Math.max(R,M)/this._diagnosticsMediaTelemetry.packets.videoSent*100;this._inCallDiagnostics.diagnostics.video.packetLoss=this.getQualityGradeForMetric(W_.PACKETS_LOSS,w,z_.VIDEO),this._diagnosticsMediaTelemetry.bandWidth=calculateFirstAverage(_?.availableOutgoingBitrate?.aggregation),this._inCallDiagnostics.bandWidth=this.getQualityGradeForMetric(W_.BANDWIDTH,this._diagnosticsMediaTelemetry.bandWidth,z_.AUDIO)}catch(g){const f=new CallingCommunicationError({defaultError:D.FEATURES.PRECALL_DIAGNOSTICS.VIDEO_MEDIASTATS,originalError:g});this._logger.error("Failed to get audio call media stats:",f.message),this._callMediaStatistics.reject(f)}}async deviceAccess(){this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:Y_.DeviceAccess}});const g=this._internalDeviceManager.askDevicePermission({audio:!0,video:!0});try{const f=await g;this.updateTestInfo(Y_.DeviceAccess,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Device Access successful. Result: ${getPrintableObject(f,this._printableObjectAll)}`,name:Y_.DeviceAccess}})}catch(g){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.DeviceAccess,!1,"Device Access failed.")})}return g}async deviceEnumeration(){const g={microphone:K_,camera:K_,speaker:K_};this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:Y_.DeviceEnumerations}});try{const f=0!==(await this.getDevices(this._internalDeviceManager,"Microphone")).length,S=0!==(await this.getDevices(this._internalDeviceManager,"Camera")).length,v=0!==(await this.getDevices(this._internalDeviceManager,"Speaker")).length;g.microphone=f?"Available":"NotAvailable",g.camera=S?"Available":"NotAvailable",g.speaker=v?"Available":"NotAvailable",this.updateTestInfo(Y_.DeviceEnumerations,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Device Enumeration successful. Result: ${getPrintableObject(g,this._printableObjectAll)}`,name:Y_.DeviceEnumerations}})}catch(g){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(Y_.DeviceEnumerations,!1,"Device Enumeration failed.")}),this._logger.error(`Couldn't find mic, camera, or speaker: ${g}`)}return g}telemetryLogAttemptEvents(g){this._telemetryLogManager.sendEvent({name:uE.acs_calling_diagnostics_attempt,tenant:tf,properties:{name:g.testAttemptDetails.name,diagnosticsTestRunId:g.diagnosticsTestRunId}})}telemetryLogResultEvents(g){this._telemetryLogManager.sendEvent({name:uE.acs_calling_diagnostics_result,tenant:tf,properties:{name:g.testResultDetails.name,diagnosticsTestRunId:g.diagnosticsTestRunId,succeeded:g.testResultDetails.succeeded,result:g.testResultDetails.result,additionalDetails:g.additionalDetails||{}}})}updateTestInfo(g,f,S){return this._completeTestInfo.succeeded&&(this._completeTestInfo={succeeded:f,name:g,result:S}),{succeeded:f,name:g,result:S||""}}_sendFeatureUsage(g,f){sendCallClientFeatureUsageTelemetry({featureName:"PreCallDiagnostics",featureType:"CallClient",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this._isCreatingNewCallAgent&&this._internalCallClient.callAgent?.dispose()}}class Debounce{constructor(g,f){this._debounce=void 0,this._updateFunction=g,this._timeout=f}debounce(){this._debounce?(clearTimeout(this._debounce),this._debounce=setTimeout((()=>{this._updateFunction(),this._debounce=void 0}),this._timeout)):(this._updateFunction(),this._debounce=setTimeout((()=>{this._debounce=void 0}),this._timeout))}flush(){this._debounce&&(clearTimeout(this._debounce),this._debounce=void 0,this._updateFunction())}}class RemoteVideoStreamCommonImpl{constructor(g,f,S,v,C,_){this._isReceiving=!1,this._mediaStreamType="Video",this._renderers=[],this._disposed=!1,this._size={height:0,width:0},this._setType=g=>{0===g.type?this._mediaStreamType="Video":1===g.type?this._mediaStreamType="ScreenSharing":2===g.type&&(this._mediaStreamType="LiveStream")},this._disposeRenderer=g=>{this.logger.log("disposing renderer");try{g.dispose(wE.Internal_RemoteVideoStreamDisposed),this.logger.log("renderer disposed")}catch(g){this.logger.log("failed to dispose renderer")}},this.tsStream=g,this._setType(this.tsStream),this.logger=f.createChild((()=>`Stream:{id=${this.tsStream.id}}:{type=${this._mediaStreamType}}`)),this.telemetryLogManager=C,this.kind=_,this._eventEmitter=new CallingEventEmitter(this.logger),this.call=S,this._tsParticipantId=v,this.sendRemoteVideoStreamTelemetry(),this._debounceSize=this.createDebounceSize(),this._debounceIsReceiving=new Debounce((()=>{const g=this._renderers?.filter((g=>!!g?.isRendering)).length>0;this._isReceiving!==g&&(this._isReceiving=g,this.logger.info(`isReceiving changed to ${this._isReceiving}`),this._eventEmitter.emit("isReceivingChanged"),this.sendRemoteVideoStreamTelemetry())}),getAcsEcsConfig().rendering.remoteVideo.debounceTimeout),this._registeredViewIdsMaxLength=getAcsEcsConfig().rendering.remoteVideo.registeredViewIdsMaxLength,this.logger.info("created")}on(g,f){if("sizeChanged"!==g&&"isReceivingChanged"!==g)throw new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("sizeChanged"!==g&&"isReceivingChanged"!==g)throw new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}get id(){return this.tsStream.id}get isReceiving(){return this._isReceiving}get tsParticipantId(){return this._tsParticipantId}get remoteParticipantId(){return this.tsStream.participantId??""}get mediaStreamType(){return this._mediaStreamType}get size(){return{height:this._size.height,width:this._size.width}}updateSize(){this._debounceSize.debounce()}updateIsReceiving(){this._debounceIsReceiving.debounce()}flushIsReceiving(){this._debounceIsReceiving.flush()}registerRenderer(g){this._renderers.push(g),this.logger.info(`Renderer registered, view id: ${g.viewId}`)}unregisterRenderer(g){const f=this._renderers.indexOf(g);-1!==f&&(this._renderers.splice(f,1),this.logger.info(`Renderer un-registered, view id: ${g.viewId}`))}dispose(){this.logger.log("dispose"),this._disposed?this.logger.log("already disposed"):(this._disposed=!0,this._streamChangedHandler&&this._streamChangedHandler.dispose(),this._renderers.forEach((g=>this._disposeRenderer(g))),this._renderers=[],this._eventEmitter.removeAllListeners())}getRegisteredViewIds(){let g=this._renderers.map((g=>g.viewId));return this._registeredViewIdsMaxLength&&(g=g.slice(0,this._registeredViewIdsMaxLength)),g.join(", ")}sendRemoteVideoStreamTelemetry(){this.call.stats.recordEvent({name:hE.remote_stream,callId:this.call.id,localParticipantId:this.call.tsCall.participantId,data:{...this.getStreamMetadata()}})}createDebounceSize(){return new Debounce((()=>{let g={height:0,width:0};this._renderers?.forEach((f=>{f?.isRendering&&f.size.height>g.height&&f.size.width>g.width&&(g.height=f.size.height,g.width=f.size.width)}),getAcsEcsConfig().rendering.remoteVideo.debounceTimeout),this._size.height===g.height&&this._size.width===g.width||(this._size.height=g.height,this._size.width=g.width,this.logger.info(`stream size changed to { height: ${this._size.height}, width: ${this._size.width} }`),this._eventEmitter.emit("sizeChanged"),this.sendRemoteVideoStreamTelemetry())}),getAcsEcsConfig().rendering.remoteVideo.debounceTimeout)}}class LiveStreamStatsCalculator{constructor(g){this._statsInfo=g,this._originalValues={},this._aggregateValues={}}isDiffMethod(g){return"diff"==g||"last2"==g||"rate"===g}addStats(g,f){const S=this._statsInfo[g];let v=this._originalValues[g];if(void 0===v&&(v={raw:[],calc:[],lastTime:Date.now(),beginTime:Date.now()},this._originalValues[g]=v),this.isDiffMethod(S.calculation_method)){v.raw.push(f);const g=Date.now(),C=v.lastTime;if(v.lastTime=g,v.raw.length>1){f=v.raw[v.raw.length-1]-v.raw[v.raw.length-2],"rate"===S.calculation_method&&(f=f/(g-C)*1e3),void 0!==S.multiplier&&(f*=S.multiplier),!0===S.integer&&(f|=0),v.calc.push(f)}else"rate"===S.calculation_method&&(f=0)}else void 0!==S.multiplier&&"number"==typeof f&&(f*=S.multiplier),!0===S.integer&&(f|=0),v.raw.push(f);return f}aggregate(){const g={};for(const[f,S]of Object.entries(this._originalValues)){const v=this._statsInfo[f];if(void 0===v||!1===v.show)continue;this.isDiffMethod(v.calculation_method)&&S.raw.length>0&&(g[f]={raw:[S.raw[S.raw.length-1]],calc:[],lastTime:S.lastTime,beginTime:0});let C=this._aggregateValues[f];void 0===C&&(C={raw:[],timestamp:new Date(S.beginTime)},v.aggregation_needed&&(C.aggregation={count:[],sum:[],max:[],min:[]}),this._aggregateValues[f]=C);const _=S.calc?.length?S.calc:S.raw;let T=_;if(v.aggregation_needed&&C.aggregation){const g=_.filter((g=>"number"==typeof g&&!isNaN(g)));C.aggregation.count.push(g.length),C.aggregation.sum.push(getSum(g)),C.aggregation.max.push(getMax(g)),C.aggregation.min.push(getMin(g)),T=g}v.raw_data_reduction&&T.length>0&&(C.reduced=C.reduced||[],C.reduced.push(T[T.length-1])),T.forEach((g=>C.raw.push(g)))}this._originalValues=g}popAggregates(){const g={};for(const[f,S]of Object.entries(this._aggregateValues)){g[this._statsInfo[f].name??f]=S}return this._aggregateValues={},g}}class LiveStreamStatsCollectorImpl{constructor(g,f,S){if(this._tsCall=g,this._aggregationInterval=0,this._dataPointsPerAggregation=0,this._disposed=!1,this._calculators=new Map,S.aggregationInterval<1)throw new CallingCommunicationError({defaultError:D.FEATURES.LIVE_STREAM.INVALID_AGGREGATION_INTERVAL_RANGE});if(S.dataPointsPerAggregation<1)throw new CallingCommunicationError({defaultError:D.FEATURES.LIVE_STREAM.INVALID_DATAPOINTS_AGGREGATION_RANGE});this._logger=f.createChild("LiveStreamStatsCollector"),this._eventEmitter=new CallingEventEmitter(this._logger,{enableLogEmit:!1}),this._callStateChanged=defer$1(),this._statsPoller=S.statsPoller,this._statsInfo=S.statsInfo,this._aggregationInterval=S.aggregationInterval,this._dataPointsPerAggregation=S.dataPointsPerAggregation,this._isInternal=S.isInternal,this._dataEventListener=g=>{void 0!==g&&this._processData(g)},this._statsPoller.on("data",this._dataEventListener);const v=[3,10];let C=v.includes(this._tsCall.state);this._callStateChangedHandle=this._tsCall.on("callStateChanged",(()=>{C!==v.includes(this._tsCall.state)&&(C=!C,this._callStateChanged.resolve(C))})),this._run()}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}dispose(){this._disposed||(this._disposed=!0,this._callStateChangedHandle.dispose(),this._callStateChanged.resolve(!1),this._statsPoller.off("data",this._dataEventListener),this._eventEmitter.emit("dispose"),this._eventEmitter.removeAllListeners())}_processData(g){const f={},S=Object.keys(g);0!==S.length&&(S.forEach((S=>{const v=g[S],C={};let _=this._calculators.get(S);_||(_=new LiveStreamStatsCalculator(this._statsInfo),this._calculators.set(S,_));for(const[g,f]of Object.entries(v)){const S=this._statsInfo[g];if(S&&!1!==S.show&&(this._isInternal||!S.is_internal)){const v=_.addStats(g,f);C[S.name??g]=v}}f[S]=C})),Object.keys(f).length>0&&this._eventEmitter.emit("sampleReported",f))}async _run(){let g=0;const filterReducedRaw=g=>(Object.keys(g).forEach((f=>{g[f].reduced&&!this._isInternal&&delete g[f].reduced})),g),flushData=()=>{if(0===this._calculators.size||0===g)return;const f=[],S={};this._calculators.forEach(((g,v)=>{const C=filterReducedRaw(g.popAggregates());0===Object.keys(C).length?f.push(v):(C.reduced&&!this._isInternal&&delete C.reduced,S[v]=C)}));try{this._eventEmitter.emit("summaryReported",S)}catch(g){this._logger.error(`summary event: ${g}`)}f.forEach((g=>{this._calculators.delete(g)})),g=0},f=[3,10];let S=1e3*this._aggregationInterval;for(;!this._disposed;){if(f.includes(this._tsCall.state)){S>0&&await wait((()=>this._callStateChanged.promise),S).catch((g=>{}));const f=Date.now();this._calculators.size>0&&(this._calculators.forEach((g=>{g.aggregate()})),g++,g===this._dataPointsPerAggregation&&flushData());const v=Date.now();S=f+1e3*this._aggregationInterval-v}else flushData(),this._calculators.clear(),await this._callStateChanged.promise.catch((g=>{})),S=1e3*this._aggregationInterval;this._callStateChanged.isPending()||(this._callStateChanged=defer$1())}flushData()}}class LiveStreamStatsPoller extends StatsPoller{constructor(g,f,S,v){super(g,f.createChild("LiveStreamStatsPoller"),S.liveStreamStats.fetchInterval,S.liveStreamStats.pollingMethod,S.liveStreamStats.activeState),this._liveStreams=v}async getStats(){const g={};return this._liveStreams.forEach(((f,S)=>{try{const S=f.tsStream.getStats();if(S){const f=S.id.toString(),v={id:f};"number"==typeof S.player_downloadBitrate&&(v.videoBitrate=S.player_downloadBitrate),"number"==typeof S.player_audioDownloadBitrate&&(v.audioBitrate=S.player_audioDownloadBitrate),"number"==typeof S.player_totalDownloadedBytes&&(v.downloadBitrate=S.player_totalDownloadedBytes,v.totalDownloadBytes=S.player_totalDownloadedBytes),"number"==typeof S.player_videoBufferLength&&(v.bufferLengthInMs=Math.round(1e3*S.player_videoBufferLength)),void 0!==S.player_mediaHeight&&(v.videoHeight=S.player_mediaHeight),void 0!==S.player_mediaWidth&&(v.videoWidth=S.player_mediaWidth),void 0!==S.player_playerHeight&&(v.playerHeight=S.player_playerHeight),void 0!==S.player_playerWidth&&(v.playerWidth=S.player_playerWidth),"number"==typeof S.player_mediaDelay&&(v.mediaDelayInMs=Math.round(1e3*S.player_mediaDelay)),"number"==typeof S.player_currentPlayPosition&&(v.currentPlayPosition=Math.round(1e3*S.player_currentPlayPosition)/1e3),g[f]=v}}catch(g){this._logger.error(`fetch live stream stats failed: ${g}`)}})),Object.keys(g).length>0?g:void 0}}class LiveStreamStatsTelemetryLogger{constructor(g,f,S){this._tsCall=g,this._telemetryLogManager=f,this._config=S}log(g){Object.entries(g).forEach((([g,f])=>{const S={id:g},v={id:g};if(Object.entries(f).forEach((([g,f])=>{const C=g,_={};if(this._config.dataToSend.raw){const g={};f?.timestamp&&(g.timestamp=f.timestamp),f?.raw&&(g.raw=f?.raw),void 0===g.raw&&delete v[C],v[C]=g}void 0!==f?.aggregation?(f?.timestamp&&(_.timestamp=f?.timestamp),this._config.dataToSend.min&&(_.min=f?.aggregation.min),this._config.dataToSend.max&&(_.max=f?.aggregation.max),this._config.dataToSend.sum&&(_.sum=f?.aggregation.sum),this._config.dataToSend.count&&(_.count=f?.aggregation.count),f?.aggregation.sum&&f?.aggregation.count&&(_.average=getSum(f?.aggregation.sum)/getSum(f?.aggregation.count))):(f?.timestamp&&(_.timestamp=f.timestamp),f?.reduced?_.raw=f?.reduced:void 0!==f?.raw&&(_.raw=f?.raw)),S[C]=_})),Object.keys(S).length>1){const g={stats:S,callId:this._tsCall.callId||"",localParticipantId:this._tsCall.participantId||""};this._sendLiveStreamStatsEvent(g)}if(this._config.dataToSend.raw&&Object.keys(v).length>1){const g={stats:v,callId:this._tsCall.callId||"",localParticipantId:this._tsCall.participantId||""};this._sendLiveStreamRawStatsEvent(g)}}))}_sendLiveStreamStatsEvent(g){this._telemetryLogManager.sendEvent({name:uE.acs_calling_livestream_stats,tenant:tf,properties:g})}_sendLiveStreamRawStatsEvent(g){this._telemetryLogManager.sendEvent({name:uE.acs_calling_livestream_raw_stats,tenant:tf,properties:g})}}class LiveStreamStatsManager{constructor(g,f,S,v){this._logger=f,this._collectors=[],this._disposed=!1,this._externalStatsInfo={};const C=getAcsEcsConfig(),_=C.telemetry.liveStreamStatsConfig;this._config=C.liveStreamStats,this._tsCall=g.tsCall,this._statsPoller=new LiveStreamStatsPoller(g,this._logger,C,v);const T={...oS,..._.additionalStats};if(Object.entries(T).filter((([,g])=>!g.is_internal)).forEach((([g,f])=>{this._externalStatsInfo[g]=f})),_.enabled){const g=new LiveStreamStatsCollectorImpl(this._tsCall,this._logger,{statsPoller:this._statsPoller,aggregationInterval:_.aggregationInterval,dataPointsPerAggregation:_.dataPointsPerAggregation,statsInfo:T,isInternal:!0}),f=new LiveStreamStatsTelemetryLogger(this._tsCall,S,_);g.on("summaryReported",(g=>{f.log(g)})),this._collectors.push(g)}}createStatsCollector(g){if(this._disposed)throw new CallingCommunicationError({defaultError:D.FEATURES.LIVE_STREAM.DISPOSED});const f=this._config,S=new LiveStreamStatsCollectorImpl(this._tsCall,this._logger,{statsPoller:this._statsPoller,aggregationInterval:g?.aggregationInterval??f.aggregationInterval,dataPointsPerAggregation:g?.dataPointsPerAggregation??f.dataPointsPerAggregation,statsInfo:this._externalStatsInfo,isInternal:!1});return S.on("dispose",(()=>{this._collectors=this._collectors.filter((g=>g!==S))})),this._collectors.push(S),S}dispose(){this._disposed||(this._disposed=!0,this._collectors.forEach((g=>{g.dispose()})))}}class BotStreamCommonCallFeature{constructor(g,f){this._featureName=g,this._targetBotIds=f,this._streamIdToStreamMap=new Map}initialize(g,f,S,v,C){this._logger=C.createChild((()=>`${this._featureName}::Call(id='${g.callId}')`)),this._telemetryLogManager=v,this._call=S,this._tsCall=g,this._callAgent=f,this.observeBotParticipantsAlreadyInCall(),this._tsCall.on("participantAdded",(async g=>{this.observeBotParticipantJustJoinedCall(g)})),this._tsCall.on("participantRemoved",(async g=>{this.removeStreamOfTheBotJustRemovedFromCall(g)}))}disposeAllBotStreams(){this._streamIdToStreamMap.forEach((g=>g.dispose())),this._streamIdToStreamMap.clear()}updateBotIds(g){this._targetBotIds=g}observeBotParticipantsAlreadyInCall(){this._tsCall.participants.forEach((g=>{this.isExpectedBotParticipant(g)&&(this._logger.info(`${this._featureName} Bot already in the call`),this.observeBotParticipant(g))}))}observeBotParticipantJustJoinedCall(g){this.isExpectedBotParticipant(g)&&(this._logger.info(`${this._featureName} Bot added`),this.observeBotParticipant(g))}removeStreamOfTheBotJustRemovedFromCall(g){if(this.isExpectedBotParticipant(g)){this._logger.info(`${this._featureName} Bot removed`);const f=[];this.removeAllStreams(g,f),this.checkVideoStreamAddedOrRemoved([],f)}}observeBotParticipant(g){g.changed((()=>{this._logger.info(`${this._featureName} Bot - changed event triggered. state: ${g.state}`),this._mapStreams(g)})),this._logger.info(`Composition Bot state: ${g.state}`),this._mapStreams(g)}_mapStreams(g){const f=[],S=[],mapStreamsOfType=v=>{if(g)if(isNonEmptyArray(g.streams&&g.streams[v])){let C=g.streams[v];this._logger.log(`Stream Type: ${v}`),C.forEach((S=>{if(void 0===S.id&&(S.id=-1),!this._streamIdToStreamMap.get(S.id)){const v=this.createConcreteVideoStream(S,g.id);this._logger.log(`${this._featureName} stream created, type==${v.mediaStreamType} id=${S.id}`),f.push(v)}})),this._streamIdToStreamMap.forEach((f=>{f.tsParticipantId!==g.id||C.some((g=>g.id===f.id))||S.push(f)}))}else this.removeAllStreams(g,S)};this.getStreamTypes().forEach((g=>mapStreamsOfType(g))),this.checkVideoStreamAddedOrRemoved(f,S)}removeAllStreams(g,f){this._streamIdToStreamMap.forEach((S=>{S.tsParticipantId===g.id&&f.push(S)}))}checkVideoStreamAddedOrRemoved(g,f){if(g.length>0||f.length>0){const handleNewStream=g=>{this._streamIdToStreamMap.set(g.id,g)},handleRemovedStream=g=>{const f=this._streamIdToStreamMap.get(g.id);f&&(this._logger.log(`stream removed, type==${f.mediaStreamType} id=${g.id}`),this._streamIdToStreamMap.delete(g.id),f.dispose())};g.forEach(handleNewStream),f.forEach(handleRemovedStream),this.emitVideoStreamsUpdatedEvent({added:g,removed:f})}}isExpectedBotParticipant(g){return this._targetBotIds.includes(g.id)}}class LiveStreamCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new LiveStreamCallFeatureImplOverTsCall(this.eventEmitter,this.name)}get name(){return"LiveStream"}initialize(g,f){this._impl.initialize(g.tsCall,g.callAgent,g.call,g.telemetryLogManager,f)}dispose(){this._impl.dispose(),super.dispose()}get liveStreams(){return this._impl.liveStreams}get participantCount(){return this._impl.streamingClientCount}on(g,f){if("liveStreamsUpdated"!==g&&"participantCountChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.LIVE_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}off(g,f){if("liveStreamsUpdated"!==g&&"participantCount"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.LIVE_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.off(g,f)}createStatsCollector(g){return this._impl.createStatsCollector(g)}}class LiveStreamCallFeatureImplOverTsCall extends BotStreamCommonCallFeature{constructor(g,f){super(f,getAcsEcsConfig().calling.liveStreamingBotIds),this._eventEmitter=g}initialize(g,f,S,v,C){super.initialize(g,f,S,v,C),this._statsManager=new LiveStreamStatsManager(S,C,v,this._streamIdToStreamMap),this._tsCall.participantCounts&&null!=this._tsCall.participantCounts.streamingClients&&(this._participantCount=this._tsCall.participantCounts.streamingClients),this._tsCall.on("participantCountsUpdated",(()=>{if(this._tsCall.participantCounts&&this._participantCount!==this._tsCall.participantCounts.streamingClients){const g=this._participantCount;this._participantCount=this._tsCall.participantCounts.streamingClients,this._logger.log(`tsCall participantCount changed from ${g} to ${this._participantCount}`),this._eventEmitter.emit("participantCountChanged")}}))}dispose(){super.disposeAllBotStreams(),this._statsManager.dispose()}createStatsCollector(g){return this._statsManager.createStatsCollector(g)}get liveStreams(){return[...this._streamIdToStreamMap.values()].map((g=>g))}get streamingClientCount(){return this._participantCount??0}createConcreteVideoStream(g,f){return new LiveVideoStreamImpl(g,this._logger,this._call,this._callAgent,f,this._telemetryLogManager)}getStreamTypes(){return[2]}emitVideoStreamsUpdatedEvent(g){return this._eventEmitter.emit("liveStreamsUpdated",g)}}class LiveVideoStreamImpl extends RemoteVideoStreamCommonImpl{constructor(g,f,S,v,C,_){super(g,f,S,C,_,"LiveVideoStream")}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:"remote",isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this.getRegisteredViewIds(),height:this._size.height,width:this._size.width,isDisposed:this._disposed}}}class ComposedStreamCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new ComposedStreamCallFeatureImplOverTsCall(this.eventEmitter,this.name)}get name(){return"ComposedStream"}initialize(g,f){this._impl.initialize(g.tsCall,g.callAgent,g.call,g.telemetryLogManager,f)}dispose(){this._impl.dispose(),super.dispose()}get composedStreams(){return this._impl.composedStreams}on(g,f){this.eventEmitter.on(g,f)}off(g,f){this.eventEmitter.off(g,f)}}class ComposedStreamCallFeatureImplOverTsCall extends BotStreamCommonCallFeature{constructor(g,f){super(f,getAcsEcsConfig().calling.composedStreamBotIds),this._eventEmitter=g}initialize(g,f,S,v,C){super.initialize(g,f,S,v,C)}dispose(){super.disposeAllBotStreams()}get composedStreams(){return[...this._streamIdToStreamMap.values()].map((g=>g))}createConcreteVideoStream(g,f){return new ComposedVideoStreamImpl(g,this._logger,this._call,this._callAgent,f,this._telemetryLogManager)}getStreamTypes(){return[0]}emitVideoStreamsUpdatedEvent(g){return this._eventEmitter.emit("composedStreamsUpdated",g)}}class ComposedVideoStreamImpl extends RemoteVideoStreamCommonImpl{constructor(g,f,S,v,C,_){super(g,f,S,C,_,"ComposedVideoStream")}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:"remote",isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this.getRegisteredViewIds(),height:this._size.height,width:this._size.width,isDisposed:this._disposed}}}class ParticipantMappingManager$1{constructor(g){this._tsCall=g,this._activeParticipantMris=new Set,this._participantMriToSourceId=new Map,this._sourceIdToParticipantMri=new Map,this._sourceIdToParticipantId=new Map,this._listenerHandles=[],this._eventEmitter=new LE.EventEmitter,this._listenerHandles.push(this._tsCall.on("participantAdded",(g=>{this._activeParticipantMris.add(g.id),this._updateMapping(g),this._eventEmitter.emit("participantAdded",g.id)}))),this._listenerHandles.push(this._tsCall.on("participantUpdated",(g=>{this._activeParticipantMris.has(g.id)&&this._updateMapping(g)&&this._eventEmitter.emit("participantUpdated",g.id)}))),this._listenerHandles.push(this._tsCall.on("participantRemoved",(g=>{this._activeParticipantMris.delete(g.id),this._removeMapping(g),this._eventEmitter.emit("participantRemoved",g.id)}))),this._tsCall.participants.forEach((g=>{this._activeParticipantMris.add(g.id),this._updateMapping(g)}))}_updateMapping(g){const f=g.id,S=[];g.endpoints?.endpointDetails?.forEach((g=>{const f=g.mediaStreams?.find((g=>"data"===g.type));f&&(S.push(f.sourceId),this._sourceIdToParticipantId.set(f.sourceId,g.participantId))}));const v=this._participantMriToSourceId.get(f);return S.sort(),!M.isEqual(S,v)&&(this._participantMriToSourceId.set(f,S),S.forEach((g=>{this._sourceIdToParticipantMri.set(g,f)})),!0)}_removeMapping(g){const f=g.id,S=this._participantMriToSourceId.get(f)||[];this._participantMriToSourceId.delete(f),S.forEach((g=>{this._sourceIdToParticipantMri.delete(g),this._sourceIdToParticipantId.delete(g)}))}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}findParticipantMri(g){let f=this._sourceIdToParticipantMri.get(g);return void 0===f&&this.isP2P()&&this._tsCall.participants.length&&(f=this._tsCall.participants[0].id),f}findParticipantId(g){let f=this._sourceIdToParticipantId.get(g);if(void 0===f&&this.isP2P()&&this._tsCall.participants.length&&this._tsCall.participants[0].endpoints?.endpointDetails.length){const g=this._tsCall.participants[0].endpoints?.endpointDetails[0];f=g.participantId}return f}findSourceIds(g){return this._participantMriToSourceId.get(g)??[]}isP2P(){return 1===this._tsCall.callType}dispose(){this._activeParticipantMris.clear(),this._participantMriToSourceId.clear(),this._sourceIdToParticipantMri.clear(),this._sourceIdToParticipantId.clear(),this._listenerHandles.forEach((g=>g.dispose())),this._eventEmitter.removeAllListeners()}}const Q_=2147483648,X_=65535,Z_=1024,eT=255,tT=8,iT=64,nT=4294967295,rT="Normal",sT="Durable",aT=.4,oT=.8;function invalidEventSubscription(g,f){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[f,g]})}function wrongArgumentType(g,f){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.WRONG_ARGUMENT_TYPE,defaultErrorMessageArgs:[g,f]})}function wrongArgumentValue(g,f){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.WRONG_ARGUMENT_VALUE,defaultErrorMessageArgs:[g,f]})}function dataChannelHasBeenDisposed(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.DISPOSED})}function senderIsNotReady(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.SENDER_NOT_READY})}function noAvailableChannelId(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.NO_AVAILABLE_CHANNEL_ID})}function invalidChannelId(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.INVALID_CHANNEL_ID})}function tooManyParticipants(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.TOO_MANY_PARTICIPANTS})}function noValidParticipants(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.NO_VALID_PARTICIPANT})}function messageDataIsEmpty(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.MSG_DATA_EMPTY})}function messageDataSizeIsTooLarge(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.MSG_DATA_TOO_LARGE})}function invalidMessageLength(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.INVALID_MSG_LENGTH})}function sendBufferIsFull(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.BUFFER_FULL})}function senderIsClosed(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.SENDER_CLOSED})}function noAvailableReliableDataId(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.NO_AVAILABLE_RELIABLE_CHANNEL})}function noAvailableUnreliableDataId(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.NO_AVAILABLE_UNRELIABLE_CHANNEL})}function channelHasBeenAllocated(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.CHANNEL_ALREADY_ALLOCATED})}function channelNotFound(g){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.CANT_FIND_CHANNEL_ID,defaultErrorMessageArgs:[g]})}function trafficLimited(){return new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.TRAFFIC_LIMITED})}function getErrorString(g){return g?.message??"Unknown"}function logError(g,f,S){const v=S.value;return S.value=function(...g){try{return v?.apply(this,g)}catch(g){throw this?._logger?.error(`${f}: ${getErrorString(g)}`),g}},S}function logErrorAsync(g,f,S){const v=S.value;return S.value=async function(...g){try{return await(v?.apply(this,g))}catch(g){throw this?._logger?.error(`${f}: ${getErrorString(g)}`),g}},S}class Message{constructor(){this._firstByte=0,this._channelVersion=0,this._channelId=0,this._sequenceNumber=0}static parse(g){if(g.length<Message.headerLength)throw invalidMessageLength();const f=new DataView(g.buffer),S=f.getUint8(0),v=f.getUint8(1),C=f.getUint16(2),_=f.getUint32(4),T=g.slice(Message.headerLength),I=new Message;return I._firstByte=S,I._channelVersion=v,I._channelId=C,I._sequenceNumber=_,I._data=T,I._serializedData=g,I}static create(g,f,S,v){const C=new Message,_=new Uint8Array(Message.headerLength+v.length),T=new DataView(_.buffer);return f&=255,g&=65535,S>>>=0,T.setUint8(0,0),T.setUint8(1,f),T.setUint16(2,g),T.setUint32(4,S),_.set(v,Message.headerLength),C._channelVersion=f,C._channelId=g,C._sequenceNumber=S,C._data=v,C._serializedData=_,C}get channelId(){return this._channelId}set channelId(g){this._channelId=g}get channelVersion(){return this._channelVersion}get sequenceNumber(){return this._sequenceNumber}get data(){return this._data}get serializedData(){return this._serializedData}isInternal(){return 0!=(128&this._firstByte)}isEmpty(){return 0===this._data.length}}var lT;Message.headerLength=tT,(lT=g.DataChannelState||(g.DataChannelState={}))[lT.Initializing=0]="Initializing",lT[lT.Initialized=1]="Initialized",lT[lT.Started=2]="Started",lT[lT.Stopped=3]="Stopped",lT[lT.Destroyed=4]="Destroyed";class DataChannelAdapter{constructor(f,S){this._eventEmitter=new LE.EventEmitter,this._state=g.DataChannelState.Initializing,this._tsCall=f,this._dataId=S}async initialize(){const f={onStarted:async(f,S,v)=>{this._dataSendFunction=S,this._getStats=v,this._state=g.DataChannelState.Started,this._eventEmitter.emit("stateChanged",this._state)},onStopped:async f=>{this._dataSendFunction=void 0,this._getStats=void 0,this._state=g.DataChannelState.Stopped,this._eventEmitter.emit("stateChanged",this._state)},onDataReceived:async(g,f,S)=>{const v={sourceId:S,data:f};this._eventEmitter.emit("message",v)}};await(this._tsCall.dataChannelAdapter?.addHandler(this._dataId,f)),this._state<g.DataChannelState.Initialized&&(this._state=g.DataChannelState.Initialized)}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}send(g,f){return this._dataSendFunction?this._dataSendFunction(g,f):Promise.reject(senderIsNotReady())}getStats(){return this._getStats?this._getStats():Promise.resolve({bufferSize:0,remainingBytes:0,remainingPackets:0})}get state(){return this._state}dispose(){if(this._state===g.DataChannelState.Destroyed)return;const f=this._state;this._state=g.DataChannelState.Destroyed,this._dataSendFunction=void 0,this._getStats=void 0,f!==g.DataChannelState.Initializing&&this._tsCall.dataChannelAdapter?.removeHandler(this._dataId).catch(noop),this._eventEmitter.emit("stateChanged",this._state),this._eventEmitter.removeAllListeners()}}class DataChannelProcessor{constructor(g,f,S){const v=g.dataId;this._logger=S.createChild(`DataChannelProcessor(${v})`),this._eventEmitter=new CallingEventEmitter(this._logger,{enableLogOn:!1,enableLogOff:!1,enableLogOnce:!1,enableLogEmit:!1}),this._bufferFullErrorMessage=`dataId ${v} send queue is full`,this._dataChannelAdapter=new DataChannelAdapter(f,v),this._dataChannelAdapter.on("message",(g=>{try{const f=g.sourceId,S=Message.parse(g.data),v={sourceId:f,message:S};S.isInternal()?this._eventEmitter.emit("internalMessage",v):this._eventEmitter.emit("message",v)}catch(g){this._logger.error(`process message error: ${getErrorString(g)}`)}}))}async initialize(){await this._dataChannelAdapter.initialize()}async send(g){try{if(void 0===g.recipients)throw noValidParticipants();if(g.recipients.length>iT)throw tooManyParticipants();await this._dataChannelAdapter.send(g.data,g.recipients)}catch(g){throw g?.message===this._bufferFullErrorMessage?sendBufferIsFull():new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.SEND_FAIL,originalError:g})}}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}dispose(){this._eventEmitter.removeAllListeners(),this._dataChannelAdapter.dispose()}}class RecipientsManager{constructor(g){this._sourceIds=[],this._participantMappingManager=g,this._participantMapping=new Map,g.on("participantAdded",(g=>{if(this._participantMapping.has(g)){const f=this._participantMappingManager.findSourceIds(g);this._participantMapping.set(g,f),this._updateSourceIds()}})),g.on("participantUpdated",(g=>{if(this._participantMapping.has(g)){const f=this._participantMappingManager.findSourceIds(g);this._participantMapping.set(g,f),this._updateSourceIds()}})),g.on("participantRemoved",(g=>{this._participantMapping.has(g)&&(this._participantMapping.set(g,[]),this._updateSourceIds())}))}get sourceIds(){if(this._participantMappingManager.isP2P()||!(this._participantMapping.size>0)||0!==this._sourceIds.length)return this._sourceIds}setParticipants(g){const f=[];g.forEach((g=>{validateIdentifier(g),f.push(getMriFromIdentifier(g))})),this._participantMapping.clear(),f.forEach((g=>{const f=this._participantMappingManager.findSourceIds(g);this._participantMapping.set(g,f)})),this._updateSourceIds()}_updateSourceIds(){this._sourceIds=Array.from(this._participantMapping.values()).flat()}}var cT,__decorate$8=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$8=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};!function(g){g[g.Open=0]="Open",g[g.Closed=1]="Closed",g[g.Destroyed=2]="Destroyed"}(cT||(cT={}));class DataChannelSenderImpl{constructor(g,f,S,v,C,_){this._state=cT.Open;const T=getAcsEcsConfig().dataChannel;this._eventEmitter=new LE.EventEmitter,this._channelId=g,this._channelVersion=f,this._sequenceNumber=Math.floor(Math.random()*(nT+1)),this._recipientsManager=new RecipientsManager(v),this._dataChannelMonitor=C,this._sendMessageFunction=S,this._maxMessageSize=T.maxMessageSize,this._logger=_.createChild(`DataChannelSender(${g},${f})`),this._logger.info("opened")}get channelId(){return this._channelId}get maxMessageSize(){return this._maxMessageSize}setParticipants(g){if(!Array.isArray(g))throw wrongArgumentType("participants","CommunicationIdentifier[]");if(g.length>iT)throw tooManyParticipants();this._recipientsManager.setParticipants(g),this._logger.info(`participant size: ${g.length}`)}async sendMessage(g){if(this._dataChannelMonitor.updateAttemptStats(g.length),!(g instanceof Uint8Array))throw wrongArgumentType("data","Uint8Array");if(this._state===cT.Closed)throw senderIsClosed();if(0===g.length)throw messageDataIsEmpty();if(g.length>this._maxMessageSize)throw messageDataSizeIsTooLarge();const f=this._recipientsManager.sourceIds;await this._sendMessage(g,f),this._dataChannelMonitor.updateCommitStats(g.length)}close(){this._state<cT.Closed&&(this._sendMessage(new Uint8Array,[]).catch(noop),this._state=cT.Closed,this._eventEmitter.emit("close"),this._logger.info("closed"),this._dataChannelMonitor.close())}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}dispose(){this.close(),this._state!==cT.Destroyed&&(this._eventEmitter.removeAllListeners(),this._state=cT.Destroyed,this._logger.info("disposed"))}get channelVersion(){return this._channelVersion}get state(){return this._state}async _sendMessage(g,f){const S=Message.create(this._channelId,this._channelVersion,this._sequenceNumber,g);this._sequenceNumber=(this._sequenceNumber+1)%(nT+1);const v={channelId:this._channelId,channelVersion:this._channelVersion,recipients:f,data:S.serializedData};await this._sendMessageFunction(v)}}__decorate$8([logError,__metadata$8("design:type",Function),__metadata$8("design:paramtypes",[Array]),__metadata$8("design:returntype",void 0)],DataChannelSenderImpl.prototype,"setParticipants",null),__decorate$8([logErrorAsync,__metadata$8("design:type",Function),__metadata$8("design:paramtypes",[Uint8Array]),__metadata$8("design:returntype",Promise)],DataChannelSenderImpl.prototype,"sendMessage",null),__decorate$8([logError,__metadata$8("design:type",Function),__metadata$8("design:paramtypes",[]),__metadata$8("design:returntype",void 0)],DataChannelSenderImpl.prototype,"close",null),__decorate$8([logError,__metadata$8("design:type",Function),__metadata$8("design:paramtypes",[]),__metadata$8("design:returntype",void 0)],DataChannelSenderImpl.prototype,"dispose",null);class Node$1{constructor(g){this.value=g,this.next=void 0}}class Queue{constructor(){this.length=0,this.front=void 0,this.rear=void 0}enqueue(g){const f=new Node$1(g);this.front?(this.rear.next=f,this.rear=f):(this.front=f,this.rear=f),this.length++}dequeue(){if(!this.front)return;const g=this.front;return this.front===this.rear?(this.front=void 0,this.rear=void 0):this.front=this.front.next,this.length--,g.value}peek(){return this.front?.value}size(){return this.length}back(){return this.rear?.value}isEmpty(){return 0===length}clear(){this.front=void 0,this.rear=void 0,this.length=0}}var dT,__decorate$9=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$9=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};!function(g){g[g.Open=0]="Open",g[g.Closed=1]="Closed",g[g.Destroyed=2]="Destroyed"}(dT||(dT={}));class DataChannelReceiverImpl{constructor(g,f,S,v,C,_){this._receiveBuffers=new Queue,this._remainingBytes=0,this._state=dT.Open,this._channelVersion=0;const T=getAcsEcsConfig().dataChannel;this._logger=_.createChild(`DataChannelReceiver(${g},${v},${S})`),this._eventEmitter=new CallingEventEmitter(this._logger,{enableLogEmit:!1}),this._maxBufferSize=T.maxReceiveBufferSize,this._dataChannelMonitor=C,this._channelId=g,this._senderParticipantIdentifier=constructIdentifierKindFromMri(f),this._channelVersion=v,this._lastMessageTimestamp=Date.now(),this._logger.info("created.")}get channelId(){return this._channelId}get senderParticipantIdentifier(){return this._senderParticipantIdentifier}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}readMessage(){const g=this._receiveBuffers.dequeue();return g?.data&&(this._remainingBytes-=g.data.length),g}dispose(){this._state!==dT.Destroyed&&(this.close(),this._state=dT.Destroyed,this._receiveBuffers.clear(),this._eventEmitter.removeAllListeners())}close(){this._state===dT.Open&&(this._state=dT.Closed,this._eventEmitter.emit("close"),this._dataChannelMonitor.close())}get channelVersion(){return this._channelVersion}get lastMessageTimestamp(){return this._lastMessageTimestamp}get state(){return this._state}appendMessage(g){if(this._dataChannelMonitor.updateAttemptStats(g.data.length),this._state!==dT.Open)return;if(0===g.data.length)return void this.close();if(this._lastMessageTimestamp=Date.now(),this._remainingBytes+g.data.length>this._maxBufferSize)return;const f={sequenceNumber:g.sequenceNumber,data:g.data};this._receiveBuffers.enqueue(f),this._remainingBytes+=g.data.length,this._eventEmitter.emit("messageReady"),this._dataChannelMonitor.updateCommitStats(g.data.length)}}function logSenderOptions(g){const f=[];return void 0!==g.bitrateInKbps&&f.push(`bitrateInKbps=${g.bitrateInKbps}`),void 0!==g.channelId&&f.push(`channelId=${g.channelId}`),void 0!==g.participants&&f.push(`participants size=${g.participants.length}`),void 0!==g.priority&&f.push(`priority=${g.priority}`),void 0!==g.reliability&&f.push(`reliability=${g.reliability}`),f.join(",")}function compareChannelVersion(g,f){if(g===f)return 0;if(-1===f)return 1;const S=g-f;return S>0?S<eT/2?1:-1:-S>eT/2?1:-1}function nextChannelVersion(g){return g===eT?0:g+1}__decorate$9([logError,__metadata$9("design:type",Function),__metadata$9("design:paramtypes",[]),__metadata$9("design:returntype",Object)],DataChannelReceiverImpl.prototype,"readMessage",null),__decorate$9([logError,__metadata$9("design:type",Function),__metadata$9("design:paramtypes",[Message]),__metadata$9("design:returntype",void 0)],DataChannelReceiverImpl.prototype,"appendMessage",null);class DataChannelReceiversManager{constructor(g,f,S){this._timeoutHandle=0;const v=getAcsEcsConfig().dataChannel;this._eventEmitter=new LE.EventEmitter,this._participantMappingManager=g,this._dataChannelMonitor=f,this._logger=S,this._receivers=new Map,this._lastestVersion=new Map,this._receiveTimeoutInMs=v.receiveTimeoutInMs}_checkTimeoutReceivers(){Array.from(this._receivers.keys()).forEach((g=>{const f=this._receivers.get(g);if(void 0!==f){Date.now()-f.lastMessageTimestamp>=this._receiveTimeoutInMs&&f.close()}})),this._receivers.size>0&&(this._timeoutHandle=window.setTimeout((()=>{this._timeoutHandle=0,this._checkTimeoutReceivers()}),Math.ceil(this._receiveTimeoutInMs/2)))}appendMessage(g){const f=`${g.sourceId},${g.message.channelId}`,S=`${g.sourceId},${g.message.channelId},${g.message.channelVersion}`;let v=this._lastestVersion.get(f),C=this._receivers.get(S);const _=g.message;if(void 0===C){if(void 0!==v){if(-1===compareChannelVersion(_.channelVersion,v))return}if(this._lastestVersion.set(f,_.channelVersion),_.isEmpty())return;if(0===this._eventEmitter.listenerCount("dataChannelReceiverCreated"))return;const T=this._participantMappingManager.findParticipantMri(g.sourceId)??"",I=this._participantMappingManager.findParticipantId(g.sourceId)??"",b=this._dataChannelMonitor.createReceiverMonitor(_.channelId,_.channelVersion,I);if(""===T)return void this._logger.info(`Unable to find corresponding sender mri, ignoring the message. channelId:${_.channelId}, sourceId:${g.sourceId}`);this._logger.info(`channelId:${_.channelId} message from ${I}, sourceId:${g.sourceId}, channelVersion:${_.channelVersion}`),C=new DataChannelReceiverImpl(_.channelId,T,g.sourceId,_.channelVersion,b,this._logger),C.on("close",(()=>{this._receivers.delete(S)})),this._receivers.set(S,C),this._eventEmitter.emit("dataChannelReceiverCreated",C),0===this._timeoutHandle&&this._checkTimeoutReceivers()}C.appendMessage(_),_.isEmpty()&&this._receivers.delete(S)}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}dispose(){window.clearTimeout(this._timeoutHandle),this._timeoutHandle=0,this._receivers.forEach(((g,f)=>{g.dispose()})),this._lastestVersion.clear(),this._receivers.clear(),this._eventEmitter.removeAllListeners()}}const hT=X_-Z_+1;class RandomPickStrategy{constructor(g){this._channelIdsInUse=g}findAvailableChannelId(){if(this._channelIdsInUse.size>=hT)throw noAvailableChannelId();const genId=()=>Math.floor(Math.random()*hT)+Z_;let g;for(;(g=genId())&&this._channelIdsInUse.has(g););return g}}class ShuffleArrayStrategy{constructor(g){this._availableChannelIds=[],this._channelIdsInUse=g,this._initArray()}findAvailableChannelId(){if(0===this._availableChannelIds.length){if(this._channelIdsInUse.size>=hT)throw noAvailableChannelId();this._initArray()}return this._availableChannelIds.pop()}_initArray(){const g=Array.from(this._channelIdsInUse,(g=>g)).sort();let f=0,S=0;for(;f<=X_&&S<g.length;)f<g[S]?(this._availableChannelIds.push(f),f++):(f>g[S]||f++,S++);for(;f<=X_;)this._availableChannelIds.push(f),f++;this._availableChannelIds=M.shuffle(this._availableChannelIds)}}class RandomChannelIdManager{constructor(){this._channelIdsInUse=new Set,this._highWaterMark=Math.ceil(hT*oT),this._lowWaterMark=Math.floor(hT*aT),this._strategy=new RandomPickStrategy(this._channelIdsInUse)}addChannelId(g){g>=Z_&&g<=X_&&(this._channelIdsInUse.add(g),this._channelIdsInUse.size>=this._highWaterMark&&this._strategy instanceof RandomPickStrategy&&(this._strategy=new ShuffleArrayStrategy(this._channelIdsInUse)))}removeChannelId(g){this._channelIdsInUse.delete(g),this._channelIdsInUse.size<this._lowWaterMark&&this._strategy instanceof ShuffleArrayStrategy&&(this._strategy=new RandomPickStrategy(this._channelIdsInUse))}findAvailableChannelId(){return this._strategy.findAvailableChannelId()}}class DurableDataIdResourceManager{constructor(g){this._dataIds=[],this._channelIds=new Map,g.forEach((g=>{this._dataIds.push({dataId:g.dataId,bandwidth:g.bandwidth,allocatedBandwidth:0})}))}allocate(g){const f=M.maxBy(this._dataIds,(f=>1-(f.allocatedBandwidth+g.bitrate)/f.bandwidth));if(void 0===f)throw noAvailableReliableDataId();return f.allocatedBandwidth+=g.bitrate,this._channelIds.set(g.channelId,{dataId:f.dataId,allocatedBandwidth:g.bitrate}),f.dataId}deallocate(g){const f=this._channelIds.get(g);if(void 0!==f){const S=this._dataIds.find((g=>g.dataId===f.dataId));void 0!==S&&(S.allocatedBandwidth-=f.allocatedBandwidth),this._channelIds.delete(g)}}getDataIds(g){const f=this._channelIds.get(g);return void 0!==f?[f.dataId]:[]}}function isPowerOf2(g){if(g.find((g=>!Number.isInteger(Math.log2(g)))))return!1;for(let f=1;f<g.length;f++)if(g[f]!==2*g[f-1])return!1;return!0}class DataIdSelectionNullStrategy{getDataIds(g){throw noAvailableUnreliableDataId()}getAllSum(){return 0}}class DataIdSelectionPower2Strategy{constructor(g){this._acsDataIdConfigs=[],this._bandwidthList=[],this._acsDataIdConfigs=g,g.forEach((g=>{this._bandwidthList.push(g.bandwidth/1e3)})),this._allSum=M.sumBy(g,(g=>g.bandwidth))}getDataIds(g){let f=[];const S=Math.ceil(g/1e3);if(S>=this._allSum)f=this._acsDataIdConfigs.map((g=>g.dataId));else{const g=this._bandwidthList[0]-1;let v=0;0!=(S&g)&&(v=this._bandwidthList.findIndex((g=>0==(g&S))),-1!==v&&(f.push(this._acsDataIdConfigs[v].dataId),v++));for(let g=v;g<this._bandwidthList.length;g++)this._bandwidthList[g]&S&&f.push(this._acsDataIdConfigs[g].dataId)}return f}getAllSum(){return this._allSum}}function powerSet(g){const f=[[]];return g.forEach((g=>{const S=[];f.forEach((f=>{S.push([...f,g])})),f.push(...S)})),f}class DataIdSelectionPowerSetSumStrategy{constructor(g){this._bandwidthMap=new Map,this._bandwidthMap.set(0,[]);powerSet(g).forEach((g=>{const f=M.sumBy(g,(g=>g.bandwidth)),S=this._bandwidthMap.get(f);(void 0===S||g.length<S.length)&&this._bandwidthMap.set(f,g.map((g=>g.dataId)))})),this._bandwidthList=Array.from(this._bandwidthMap.keys()).sort(((g,f)=>g-f))}getDataIds(g){const f=M.sortedIndex(this._bandwidthList,g),S=this._bandwidthList[f]??this._bandwidthList[this._bandwidthList.length-1];return this._bandwidthMap.get(S)||[]}getAllSum(){return M.last(this._bandwidthList)||0}}class BandwidthTable{constructor(g){(g=M.sortBy(g,(g=>g.bandwidth))).length?isPowerOf2(g.map((g=>g.bandwidth/1e3)))?this._dataIdSelectionStrategy=new DataIdSelectionPower2Strategy(g):this._dataIdSelectionStrategy=new DataIdSelectionPowerSetSumStrategy(g):this._dataIdSelectionStrategy=new DataIdSelectionNullStrategy}getDataIds(g){return this._dataIdSelectionStrategy.getDataIds(g)}getAllSum(){return this._dataIdSelectionStrategy.getAllSum()}}class LossyDataIdResourceManager{constructor(g){this._totalNormalPriorityBandwidth=0,this._totalHighPriorityBandwidth=0,this._configs=new Map,this._currentNormalPriorityDataIds=[],this._currentHighPriorityDataIds=[],this._normalPriorityTable=new BandwidthTable(g.filter((g=>"normal"===g.priority))),this._highPriorityTable=new BandwidthTable(g.filter((g=>"high"===g.priority)))}allocate(g){this._configs.set(g.channelId,g),"Normal"===g.priority?this._totalNormalPriorityBandwidth+=g.bitrate:"High"===g.priority&&(this._totalHighPriorityBandwidth+=g.bitrate),this._updateDataIds()}deallocate(g){const f=this._configs.get(g);void 0!==f&&(this._configs.delete(g),"Normal"===f.priority?this._totalNormalPriorityBandwidth-=f.bitrate:"High"===f.priority&&(this._totalHighPriorityBandwidth-=f.bitrate),this._updateDataIds())}getDataIds(g){const f=this._configs.get(g);if(void 0!==f){if("Normal"===f.priority)return this._currentNormalPriorityDataIds;if("High"===f.priority)return this._currentHighPriorityDataIds}return[]}_updateDataIds(){const g=this._highPriorityTable.getAllSum(),f=this._totalHighPriorityBandwidth-g;if(f>0){const g=this._totalNormalPriorityBandwidth+f;this._currentNormalPriorityDataIds=this._normalPriorityTable.getDataIds(g),this._currentHighPriorityDataIds=this._highPriorityTable.getDataIds(this._totalHighPriorityBandwidth).concat(this._currentNormalPriorityDataIds)}else this._currentNormalPriorityDataIds=this._normalPriorityTable.getDataIds(this._totalNormalPriorityBandwidth),this._currentHighPriorityDataIds=this._highPriorityTable.getDataIds(this._totalHighPriorityBandwidth)}}class DataIdMappingManager{constructor(g){const f=g.filter((g=>"reliable"===g.category)),S=g.filter((g=>"unicast"===g.category)),v=g.filter((g=>"broadcast"===g.category));this._reliableDataIdManager=new DurableDataIdResourceManager(f),this._unicastDataIdManager=new LossyDataIdResourceManager(S),this._broadcastDataIdManager=new LossyDataIdResourceManager(v),this._configs=new Map}allocate(g){let f=-1;if(this._configs.has(g.channelId))throw channelHasBeenAllocated();try{"Durable"===g.reliability?f=this._reliableDataIdManager.allocate(g):(this._unicastDataIdManager.allocate(g),this._broadcastDataIdManager.allocate(g)),this._configs.set(g.channelId,g)}catch(f){throw"Durable"===g.reliability?this._reliableDataIdManager.deallocate(g.channelId):(this._unicastDataIdManager.deallocate(g.channelId),this._broadcastDataIdManager.deallocate(g.channelId)),f}return f}deallocate(g){const f=this._configs.get(g);void 0!==f&&("Durable"===f.reliability?this._reliableDataIdManager.deallocate(g):(this._unicastDataIdManager.deallocate(g),this._broadcastDataIdManager.deallocate(g)),this._configs.delete(g))}getDataIdToSend(g,f,S){const v=this._configs.get(g);if(void 0!==v)return"Durable"===v.reliability?this._reliableDataIdManager.getDataIds(g):S?this._broadcastDataIdManager.getDataIds(g):this._unicastDataIdManager.getDataIds(g);throw channelNotFound(g)}}class DataChannelSendRecvMonitor{constructor(g){this._attemptCount=0,this._attemptBytes=0,this._commitCount=0,this._commitBytes=0,this._dataChannelTelemetryLogger=g,this._openTime=new Date,this._closeTime=this._openTime}updateAttemptStats(g){this._attemptCount++,this._attemptBytes+=g}updateCommitStats(g){this._commitCount++,this._commitBytes+=g}close(){this._closeTime=new Date}}class DataChannelSenderMonitor extends DataChannelSendRecvMonitor{constructor(g,f,S,v){super(v),this._channelId=g,this._channelVersion=f,this._correlationId=S}close(){super.close();const g={direction:"send",channelId:this._channelId,channelVersion:this._channelVersion,openTime:this._openTime,closeTime:this._closeTime,attemptCount:this._attemptCount,attemptBytes:this._attemptBytes,commitCount:this._commitCount,commitBytes:this._commitBytes,correlationId:this._correlationId};this._dataChannelTelemetryLogger.sendStatsEvent(g)}}class DataChannelReceiverMonitor extends DataChannelSendRecvMonitor{constructor(g,f,S,v){super(v),this._channelId=g,this._channelVersion=f,this._remoteParticipantId=S}close(){super.close();const g={direction:"recv",channelId:this._channelId,channelVersion:this._channelVersion,openTime:this._openTime,closeTime:this._closeTime,attemptCount:this._attemptCount,attemptBytes:this._attemptBytes,commitCount:this._commitCount,commitBytes:this._commitBytes,remoteParticipantId:this._remoteParticipantId};this._dataChannelTelemetryLogger.sendStatsEvent(g)}}class DataChannelMonitor{constructor(g){this._dataChannelTelemetryLogger=g}createSenderMonitor(g,f,S){return new DataChannelSenderMonitor(g,f,S,this._dataChannelTelemetryLogger)}createReceiverMonitor(g,f,S){return new DataChannelReceiverMonitor(g,f,S,this._dataChannelTelemetryLogger)}}class PacketRateLimiter{constructor(g){this._timeBucket=0,this._maxPacketRate=0,this._packetCount=0,this._maxPacketRate=g}canSend(g){let f=Math.ceil(g/1200);const S=window.performance.now();return Math.floor(S/1e3)==this._timeBucket&&(f+=this._packetCount),f<=this._maxPacketRate}update(g){let f=Math.ceil(g/1200);const S=window.performance.now(),v=Math.floor(S/1e3);v!==this._timeBucket&&(this._timeBucket=v,this._packetCount=0),this._packetCount+=f}}class BitrateLimiter{constructor(g){this._endTime=0,this._maxDataRate=0,this._maxDataRate=g/8}canSend(g){if(0===this._maxDataRate)return!0;const f=window.performance.now(),S=(this._endTime-f)/1e3;return!(S>0)||S+g/this._maxDataRate<=1}update(g){const f=window.performance.now(),S=this._maxDataRate?g/this._maxDataRate*1e3:0;this._endTime<f?this._endTime=f+S:this._endTime+=S}changeBitrate(g){this._maxDataRate=g/8}}class BitrateCalculator{constructor(){this._totalBytes=0,this._lastUpdateTime=window.performance.now(),this._lastUpdateBytes=0,this._currentBitrate=0}getBitrate(){return this._currentBitrate}update(g){this._totalBytes+=g}calculateBitrate(){const g=window.performance.now();g-this._lastUpdateTime>0&&(this._currentBitrate=8*(this._totalBytes-this._lastUpdateBytes)/(g-this._lastUpdateTime)),this._lastUpdateTime=g,this._lastUpdateBytes=this._totalBytes}}class SendTrafficLimiter{constructor(g,f){this._availableBytes=0,this._reducedBytes=0,this._lastUpdateTime=window.performance.now(),this._packetRateLimiter=new PacketRateLimiter(f),this._receiveBitrate=new BitrateCalculator,this._bitrateTimer=window.setInterval((()=>{this._receiveBitrate.calculateBitrate();const f=window.performance.now(),S=(f-this._lastUpdateTime)/1e3;this._availableBytes=g/8*S,this._reducedBytes=.8*this._receiveBitrate.getBitrate()/8*S,this._lastUpdateTime=f}),1e3)}canSend(g,f){return f?!!this._packetRateLimiter.canSend(g)&&this._availableBytes-this._reducedBytes>=g:this._availableBytes>=g}updateSendBytes(g,f){f&&this._packetRateLimiter.update(g),this._availableBytes-=g}updateReceiveBytes(g){this._receiveBitrate.update(g)}dispose(){window.clearInterval(this._bitrateTimer)}}var uT,gT;!function(g){g[g.Initializing=0]="Initializing",g[g.Initialized=1]="Initialized",g[g.Destroyed=2]="Destroyed"}(uT||(uT={}));class DataChannelManager{constructor(g,f,S){this._state=uT.Initializing,this._initializedDefer=defer$1();const v=getAcsEcsConfig();this._logger=f,this._tsCall=g,this._dataChannelTelemtryLogger=S,this._participantMappingManager=new ParticipantMappingManager$1(g),this._dataChannelMonitor=new DataChannelMonitor(S),this._senders=new Map,this._receiversManager=new DataChannelReceiversManager(this._participantMappingManager,this._dataChannelMonitor,f),this._processors=new Map,this._channelVersions=new Map,this._randomChannelIdManager=new RandomChannelIdManager,this._dataIds=new Map,v.dataChannel.dataIdConfigs.forEach((g=>{const f=this._dataIds.get(g.dataId)??[];f.push(g.raw?{dataId:g.dataId,raw:g.raw}:{dataId:g.dataId,raw:g.raw,bandwidth:g.bandwidth??0,priority:g.priority??"normal",category:g.category??"reliable"}),this._dataIds.set(g.dataId,f)})),this._rateLimiters=new Map,this._sendTrafficLimiter=new SendTrafficLimiter(v.dataChannel.maxSendBandwidth,v.dataChannel.maxBroadcastPacketRate),this._enableBroadcastLimitOnReliableChannel=v.dataChannel.enableBroadcastLimitOnReliableChannel}async initialize(){const createProcessor=async g=>{const f=new DataChannelProcessor(g,this._tsCall,this._logger);return f.on("message",(f=>{const S=f.message;g.raw?S.channelId=g.dataId+Q_:this._sendTrafficLimiter.updateReceiveBytes(S.data.length);try{this._receiversManager.appendMessage(f)}catch(f){this._logger.error(`Failed to appendMessage on dataId ${g.dataId}: ${getErrorString(f)}`)}})),await f.initialize(),f},g=[],f=new Map,S=Array.from(this._dataIds.keys());for(let v=0;v<S.length;v++){const C=S[v],_=this._dataIds.get(C)[0];try{const g=await createProcessor(_);f.set(C,g)}catch(f){g.push(C),this._dataIds.delete(C)}}const v=M.flatten(Array.from(this._dataIds.values())).filter((g=>!g.raw));this._dataIdMappingManager=new DataIdMappingManager(v),this._state===uT.Initializing?(this._processors=f,v.forEach((g=>{this._rateLimiters.has(g.dataId)||this._rateLimiters.set(g.dataId,new BitrateLimiter(g.bandwidth))})),g.length&&this._dataChannelTelemtryLogger.sendCreateProcessorEvent({kindOfEvent:"failure",dataIds:g}),this._state=uT.Initialized,this._initializedDefer.resolve()):f.forEach((g=>{g.dispose()}))}createSender(g,f){let S=g.channelId,v=!1;if(S>=Q_){if(!0!==this._dataIds.get(S-Q_)?.[0].raw)throw invalidChannelId();v=!0}else{if(S<0||S>X_)throw invalidChannelId();0===S&&(S=this._randomChannelIdManager.findAvailableChannelId())}this._senders.get(S)?.close();const C=nextChannelVersion(this._channelVersions.get(S)??-1);let _=S>=Q_?S-Q_:-1,T=!1;-1===_&&this._state===uT.Initialized&&(_=this._dataIdMappingManager.allocate({channelId:S,reliability:g.reliability,priority:g.priority,bitrate:1e3*g.bitrateInKbps}),T=!0);const sendFunction=async f=>{const C=f.data.length;if(-1===_&&!T){if(C===tT)return;await this._initializedDefer.promise,T||(_=this._dataIdMappingManager.allocate({channelId:S,reliability:g.reliability,priority:g.priority,bitrate:1e3*g.bitrateInKbps}),T=!0)}const I=0===f.recipients?.length&&!this._participantMappingManager.isP2P();if(-1!==_)if(this._enableBroadcastLimitOnReliableChannel&&I&&!v){if(!this._sendTrafficLimiter.canSend(C,I))throw trafficLimited();const g=this._processors.get(_);await(g?.send(f)),this._sendTrafficLimiter.updateSendBytes(C,I)}else{const g=this._processors.get(_);await(g?.send(f))}else{const v=this._dataIdMappingManager.getDataIdToSend(S,C,I);try{const S=!this._sendTrafficLimiter.canSend(C,I);if(S&&"High"!==g.priority)throw trafficLimited();if(0===v.length)throw noAvailableUnreliableDataId();for(let g=0;g<v.length;g++)try{const _=v[g],T=this._dataIds.get(_)[0];if(S&&"normal"===T.priority)continue;const b=this._rateLimiters.get(_);if(b?.canSend(C)??!0){const g=this._processors.get(_);return await(g?.send(f)),b?.update(C),void this._sendTrafficLimiter.updateSendBytes(C,I)}}catch(g){}throw trafficLimited()}catch(g){this._logger.error(`Failed to send channelId ${S} message: ${getErrorString(g)}`)}}},I=this._dataChannelMonitor.createSenderMonitor(S,C,f),b=new DataChannelSenderImpl(S,C,sendFunction,this._participantMappingManager,I,this._logger);return b.on("close",(()=>{T&&this._dataIdMappingManager.deallocate(S),this._randomChannelIdManager.removeChannelId(S),this._senders.delete(S),setTimeout((()=>b.dispose()),0)})),void 0!==g.participants&&b.setParticipants(g.participants),this._senders.set(S,b),this._randomChannelIdManager.addChannelId(S),this._channelVersions.set(S,C),b}getDataStreamIdsFromParticipant(g){return this._participantMappingManager.findSourceIds(g.id)}on(g,f){"dataChannelReceiverCreated"===g&&this._receiversManager.on("dataChannelReceiverCreated",f)}off(g,f){"dataChannelReceiverCreated"===g&&this._receiversManager.off("dataChannelReceiverCreated",f)}dispose(){this._state!==uT.Destroyed&&(this._state=uT.Destroyed,this._initializedDefer.isPending()&&this._initializedDefer.reject(dataChannelHasBeenDisposed()),this._senders.forEach((g=>{g.dispose()})),this._receiversManager.dispose(),this._processors.forEach((g=>{g.dispose()})),this._sendTrafficLimiter.dispose(),this._participantMappingManager.dispose())}}class DataChannelTelemetryLogger{constructor(g,f){this._tsCall=g,this._telemetryLogManager=f}sendStatsEvent(g){const f={...{callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId},...g};this._telemetryLogManager.sendEvent({name:uE.acs_calling_datachannel_stats,tenant:tf,properties:f})}sendCreateSenderEvent(g){const f={...{callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,operation:"createSender"},...g};this._telemetryLogManager.sendEvent({name:uE.acs_calling_datachannel,tenant:tf,properties:f})}sendCreateProcessorEvent(g){const f={...{callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,operation:"createProcessor"},...g};this._telemetryLogManager.sendEvent({name:uE.acs_calling_datachannel,tenant:tf,properties:f})}}class DataChannelCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g)}createDataChannelSender(g){const f=generateGuid(),S=getAcsEcsConfig();try{if(void 0!==g.bitrateInKbps&&"number"!=typeof g.bitrateInKbps)throw wrongArgumentType("bitrateInKbps","number");if(void 0!==g.channelId&&"number"!=typeof g.channelId)throw wrongArgumentType("channelId","number");if(void 0!==g.participants&&!Array.isArray(g.participants))throw wrongArgumentType("participants","CommunicationIdentifier[]");if(void 0!==g.priority&&-1===["High","Normal"].indexOf(g.priority))throw wrongArgumentValue("priority","High,Normal");if(void 0!==g.reliability&&-1===["Durable","Lossy"].indexOf(g.reliability))throw wrongArgumentValue("reliability","Durable,Lossy");const v={bitrateInKbps:Math.ceil(g.bitrateInKbps??S.dataChannel.defaultBitrate/1e3),channelId:g.channelId??0,participants:g.participants??[],priority:g.priority??rT,reliability:g.reliability??sT};this._logger.info(`createDataChannelSender: ${logSenderOptions(g)}`),this._sendFeatureUsage("createDataChannelSender",gE.attempt),this._dataChannelTelemetryLogger.sendCreateSenderEvent({kindOfEvent:"attempt",correlationId:f,senderOptions:{channelId:g.channelId,bitrateInKbps:g.bitrateInKbps,participantsSize:g.participants?.length,priority:g.priority,reliability:g.reliability}});const C=this._dataChannelManager.createSender(v,f);return this._dataChannelTelemetryLogger.sendCreateSenderEvent({kindOfEvent:"success",correlationId:f,senderOptions:{channelId:C.channelId,bitrateInKbps:v.bitrateInKbps,participantsSize:v.participants?.length,priority:v.priority,reliability:v.reliability}}),this._logger.info(`The sender is created. channel id=${C.channelId}`),this._sendFeatureUsage("createDataChannelSender",gE.success),C}catch(g){const S=new CallingCommunicationError({defaultError:D.FEATURES.DATA_CHANNEL.FAILED_TO_CREATE_SENDER,originalError:g});throw this._logger.info(`Failed to create the sender: ${S.message}`),this._sendFeatureUsage("createDataChannelSender",gE.failure),this._dataChannelTelemetryLogger.sendCreateSenderEvent({kindOfEvent:"failure",correlationId:f,failureReason:S.message,additionalDetails:{...extractCommunicationServicesErrorForTelemetry(S)}}),S}}async createDataChannelAdapter(g){const f=new DataChannelAdapter(this._tsCall,g);return await f.initialize(),f}initialize(g,f){this._tsCall=g.tsCall,this._logger=f.createChild("DataChannelCallFeature"),this._telemetryLogManager=g.telemetryLogManager,this._dataChannelTelemetryLogger=new DataChannelTelemetryLogger(this._tsCall,this._telemetryLogManager);const S=new DataChannelManager(this._tsCall,this._logger,this._dataChannelTelemetryLogger);this._dataChannelManager=S,this._dataChannelManager.initialize().then((()=>{this._sendFeatureUsage("initialize",gE.initialize)})).catch((g=>{this._logger.error(`initialize:${getErrorString(g)}`)}))}get name(){return this._sendFeatureUsage("name",gE.getter),"DataChannel"}dispose(){this.disposed||(this._dataChannelManager?.dispose(),super.dispose())}getDataStreamIdsFromParticipant(g){return g.tsRemoteParticipant?this._dataChannelManager.getDataStreamIdsFromParticipant(g.tsRemoteParticipant):[]}on(g,f){if("dataChannelReceiverCreated"!==g)throw invalidEventSubscription(g,"subscribe");this._sendFeatureUsage(g,gE.subscribe),"dataChannelReceiverCreated"===g&&this._dataChannelManager?.on("dataChannelReceiverCreated",f)}off(g,f){if("dataChannelReceiverCreated"!==g)throw invalidEventSubscription(g,"unsubscribe");this._sendFeatureUsage(g,gE.unsubscribe),"dataChannelReceiverCreated"===g&&this._dataChannelManager?.off("dataChannelReceiverCreated",f)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"DataChannel",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}}class SpotlightCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new SpotlightCallImplOverTsCall(this.eventEmitter),this._isSpotlightFeatureEnabled=getAcsEcsConfig().calling.spotlight.enabled,this._callInfo=g.callInfo}get name(){return"Spotlight"}initialize(g,f){this._logger=f,this._logger.info(`Spotlight feature enable flag: ${this._isSpotlightFeatureEnabled}`),this._isSpotlightFeatureEnabled?(this._telemetryLogManager=g.telemetryLogManager,this._tsCall=g.tsCall,this._impl.initialize(g.tsCall,g.callAgent,g.telemetryLogManager,f,this._callInfo)):this._logger.warn("Calls to spotlight APIs will perform no action or return default values where applicable")}async startSpotlight(g){this._isSpotlightFeatureEnabled&&this.validateIdentifierParam(g)&&await this._impl.startSpotlight(g)}async stopSpotlight(g){this._isSpotlightFeatureEnabled&&this.validateIdentifierParam(g)&&await this._impl.stopSpotlight(g)}async stopAllSpotlight(){this._isSpotlightFeatureEnabled&&await this._impl.stopAllSpotlight()}getSpotlightedParticipants(){return this._isSpotlightFeatureEnabled?(this._sendFeatureUsage("getSpotlightedParticipants",gE.getter),this._impl.spotlightedParticipants):[]}get maxParticipantsToSpotlight(){return this._isSpotlightFeatureEnabled?(this._sendFeatureUsage("maxSpotlightSupportedState",gE.getter),this._impl.maxSpotlightStateSupported):0}on(g,f){this._isSpotlightFeatureEnabled&&(this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f))}off(g,f){this._isSpotlightFeatureEnabled&&(this._sendFeatureUsage(g,gE.unsubscribe),this.eventEmitter.off(g,f))}validateIdentifierParam(g=[]){try{return g.forEach((g=>validateIdentifier(g))),!0}catch(g){return!1}}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}class SpotlightCallImplOverTsCall{constructor(g){this.typeRankComparator=(g,f)=>void 0===g.publishedState?-1:void 0===f.publishedState?1:g.publishedState.typeRank-f.publishedState.typeRank,this._eventEmitter=g,this._currentSpotlightStates=new Map;const f=getAcsEcsConfig().calling.spotlight;this._maxSpotlightStateSupported=f.maxSpotlightParticipants,this._supportedUserRoles=f.supportedRoles,this._meetingTypes=f.meetingTypes}initialize(g,f,S,v,C){this._logger=v.createChild((()=>`SpotlightFeature::Call(id='${g.callId}')`)),this._tsCall=g,this._callInfo=C,this._telemetryLogManager=S,this._internalCallAgent=f;const _="initialize";this._sendFeatureUsage(_,gE.initialize);try{let extractMRIs=g=>new Map(this.getPublishedState(g).sort(this.typeRankComparator).map(((g,f)=>[g.id,{spotlightStateId:g.publishedState?.stateId,index:f+1}])));this._tsCall.on("publishedStatesChanged",(async g=>{let f=extractMRIs(g),S=[];f.forEach(((g,f)=>{this._currentSpotlightStates.has(f)||S.push({identifier:constructIdentifierKindFromMri(f),order:g?.index})}));let v=[];this._currentSpotlightStates.forEach(((g,S)=>{f.has(S)||v.push({identifier:constructIdentifierKindFromMri(S)})})),this._currentSpotlightStates=f,(S.length||v.length)&&this._eventEmitter.emit("spotlightChanged",{added:S,removed:v})})),this._tsCall.publishedStates&&(this._currentSpotlightStates=extractMRIs(this._tsCall.publishedStates)),this._sendFeatureUsage(_,gE.success)}catch(g){this.handleSpotlightFailure(_,g)}}async startSpotlight(g){const f="startSpotlight";try{this._sendFeatureUsage(f,gE.attempt);let S=this.getIdentifiersMri(g).filter((g=>!this._currentSpotlightStates.has(g)));if(!S.length)throw new CallingCommunicationError({defaultError:D.FEATURES.SPOTLIGHT.ALREADY_SPOTLIGHTED});this.validateStartSpotlightConditions(S);const v={level:"user",type:"spotlight",content:"{}",participantIds:S};if(!await this._tsCall.publishState(v,w.generateCauseId()))throw new CallingCommunicationError({defaultError:D.FEATURES.SPOTLIGHT.START_SPOTLIGHT_FAILED});this._sendFeatureUsage(f,gE.success)}catch(g){this.handleSpotlightFailure(f,g)}}async stopSpotlight(g){const f="stopSpotlight";this._tsCall.publishedStates||this._logger.warn(`${f}: no participants is currently Spotlighted`);try{this._sendFeatureUsage(f,gE.attempt);let S=this.getIdentifiersMri(g);this.validateStopSpotlightConditions(S);const v=this.findStateIdsForParticipantIds(S);await this._tsCall.removeState({stateIds:v},w.generateCauseId()),this._sendFeatureUsage(f,gE.success)}catch(g){this.handleSpotlightFailure(f,g)}}async stopAllSpotlight(){const g="stopAllSpotlight";try{this._sendFeatureUsage(g,gE.attempt),this.validateStopSpotlightConditions([]),await this._tsCall.removeStatesForEveryone({type:"spotlight"},w.generateCauseId()),this._sendFeatureUsage(g,gE.success)}catch(f){this.handleSpotlightFailure(g,f)}}get spotlightedParticipants(){return this._tsCall.publishedStates?Array.from(this._currentSpotlightStates.keys()).map((g=>({identifier:constructIdentifierKindFromMri(g),order:this._currentSpotlightStates.get(g)?.index}))):[]}get maxSpotlightStateSupported(){return this._maxSpotlightStateSupported}findStateIdsForParticipantIds(g){return g.length&&this._tsCall.publishedStates?g.map((g=>this._currentSpotlightStates.get(g)?.spotlightStateId||"")).filter((g=>g.length)):[]}getPublishedState(g){return g.typeStates.filter((g=>"spotlight"===g.type)).map((g=>g.participantStates)).flat()}isUserRoleEligible(){const g=this._tsCall.advancedMeetingRole;return!!g&&!!this._supportedUserRoles.find((f=>f===g))}isRoleBasedConversationType(){const g=this._tsCall.conversationType;return!!g&&!!this._meetingTypes.find((f=>f===g))}getIdentifiersMri(g){return g&&g?.length?g.map((g=>getMriFromIdentifier(g))):[this._internalCallAgent.getUserMri()]}validateStartSpotlightConditions(g){const f="startSpotlight";if(this._callInfo.context===jS.TwoParty)throw this._logger.warn("Spotlight not supported for 1:1 calls"),this._sendFeatureUsage(f,gE.failure),new CallingCommunicationError({defaultError:D.FEATURES.SPOTLIGHT.NOT_SUPPORTED_1TO1});if(this.spotlightedParticipants.length+g.length>this._maxSpotlightStateSupported)throw new CallingCommunicationError({defaultError:D.FEATURES.SPOTLIGHT.SPOTLIGHT_LIGHT_MAX_REACHED,defaultErrorMessageArgs:[this._maxSpotlightStateSupported]});if(this.isRoleBasedConversationType()&&!this.isUserRoleEligible())throw new CallingCommunicationError({defaultError:D.FEATURES.SPOTLIGHT.UNSUPPORTED_ROLE_TYPE,defaultErrorMessageArgs:["Start",this._tsCall.conversationType]})}validateStopSpotlightConditions(g){if(!(1===g.length&&g[0]===this._internalCallAgent.getUserMri())&&this.isRoleBasedConversationType()&&!this.isUserRoleEligible())throw new CallingCommunicationError({defaultError:D.FEATURES.SPOTLIGHT.UNSUPPORTED_ROLE_TYPE,defaultErrorMessageArgs:["Stop",this._tsCall.conversationType]})}handleSpotlightFailure(g,f){throw this._logger.error(JSON.stringify(f)),this._sendFeatureUsage(g,gE.failure,f),f}_sendFeatureUsage(g,f,S){let v=S?{code:S?.code||U,subCode:S?.subCode||0,failureReason:S?.message||"",...extractCommunicationServicesErrorForTelemetry(S)}:void 0;sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"Spotlight",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:v},this._telemetryLogManager,this._logger)}}class CallSurveyFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new CallSurveyFeatureImplOverTsCall}initialize(g,f){this._impl.initialize(g.tsCall,g.callAgent,g.call,g.telemetryLogManager,f)}get name(){return"CallSurvey"}dispose(){super.dispose()}submitSurvey(g){return this._impl.submitSurvey(g)}}class CallSurveyFeatureImplOverTsCall{initialize(g,f,S,v,C){this._tsCall=g,this._call=S,this._telemetryLogManager=v,this._logger=C,this.updateCallSurveyInfo();const callStateChangedHandler=()=>{7===this._tsCall?.state&&(this._logger.debug("Call disconnected. Releasing call and tsCall references."),this.updateCallSurveyInfo(),this._tsCall=void 0,this._call=void 0)};this._tsCall.on("callStateChanged",callStateChangedHandler)}async submitSurvey(g){const f=+new Date,S=generateGuid();this.updateCallSurveyInfo(),this.sendEndOfCallEvent("attempt",S);const v=this.validateSurvey(g);if(v){const g=new CallingCommunicationError({defaultError:D.FEATURES.CALL_SURVEY.INVALID_SURVEY,defaultErrorMessageArgs:[v]});throw this.sendEndOfCallEvent("failure",S,f,{failureReason:v,code:k,...extractCommunicationServicesErrorForTelemetry(g),isExpected:!0}),g}return new Promise(((v,C)=>{const _=this.createCallSurveyInternal(g);this.registerNotificationEventListener(_,S,f,v,C),this.sendEndOfCallEvent("success",S,f,void 0,_)}))}registerNotificationEventListener(g,f,S,v,C){const _={id:f,callId:g.callId,localParticipantId:g.localParticipantId,overallRating:g.overallRating,audioRating:g.audioRating,videoRating:g.videoRating,screenshareRating:g.screenshareRating};CallSurveyFeatureImplOverTsCall.NOTIFICATION_LISTENER.eventsSent=g=>{g.find((g=>g.name===uE.acs_calling_survey&&g.data?.correlationId===f&&"success"===g.data?.kindOfEvent))&&v(_)},CallSurveyFeatureImplOverTsCall.NOTIFICATION_LISTENER.eventsDiscarded=(g,v)=>{if(g.find((g=>g.name===uE.acs_calling_survey&&g.data?.correlationId===f&&"success"===g.data?.kindOfEvent))){const g=new CallingCommunicationError({defaultError:D.FEATURES.CALL_SURVEY.SUBMIT_TIMEOUT});this.sendEndOfCallEvent("failure",f,S,{failureReason:g.message,code:g.code,...extractCommunicationServicesErrorForTelemetry(g)}),C(g)}}}updateCallSurveyInfo(){const g=this.createCallSurveyInfo();g&&(this._callSurveyInfo=g)}createCallSurveyInfo(){return this._call&&this._tsCall?{callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,callMode:this._tsCall.callMode,isEnterpriseTeamsCall:this._call.isEnterpriseTeamsCall}:void this._logger.warn(`Call: ${this._call} or tsCall: ${this._tsCall} is not available to create call survey info.`)}sendEndOfCallEvent(g,f,S,v,C){try{const _={eventName:uE.acs_calling_survey,callId:this._callSurveyInfo?.callId,localParticipantId:this._callSurveyInfo?.localParticipantId,correlationId:f,kindOfEvent:g,timestampInfo:{deltaTimeInMs:0},additionalDetails:v};if(S){const g=+new Date;_.timestampInfo.deltaTimeInMs=g-S}"success"===g&&C?(_.overallRating=C.overallRating,_.audioRating=C.audioRating,_.videoRating=C.videoRating,_.screenshareRating=C.screenshareRating,this._telemetryLogManager.sendEvent({name:uE.acs_calling_survey,tenant:tf,priority:Ga.Immediate,properties:_},CallSurveyFeatureImplOverTsCall.NOTIFICATION_LISTENER),getAcsEcsConfig().calling.teamsCallQualityFeedback.enabled&&this._callSurveyInfo?.isEnterpriseTeamsCall&&this.acsCallSurveyToMediaCallQualityFeedback(C,f)):this._telemetryLogManager.sendEvent({name:_.eventName,tenant:tf,properties:_})}catch(g){this._logger.debug("Unable to send call survey telemetry")}}acsCallSurveyToMediaCallQualityFeedback(g,f){const S=this.getFiveStarRating(g.overallRating);if(void 0===S)return void this._logger.info("Call survey has no valid overall rating. Skipping media call quality feedback.");const v=this.getAllCallIssues(g),C={acs_correlation_id:f,call_mos_score_questionary_id:105,clientType:"ACSWebSDK",call_id:g.callId,participant_id:g.localParticipantId,call_mos_score:S-1,call_mos_score_tracking_reason:"random",call_mos_score_problem_tokens:v,call_mos_score_never_expires:!1};void 0!==this._callSurveyInfo?.callMode&&(C.call_mode=this._callSurveyInfo.callMode),this._telemetryLogManager.sendEvent({name:uE.mdsc_call_quality_feedback,tenant:getAcsEcsConfig().calling.teamsCallQualityFeedback.tenantId,priority:Ga.Immediate,properties:C})}getAllCallIssues(g){const f=[];return g.overallRating?.issues?.forEach((g=>f.push(CallSurveyFeatureImplOverTsCall.ACS_OVERALL_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE[g]))),g.audioRating?.issues?.forEach((g=>f.push(CallSurveyFeatureImplOverTsCall.ACS_AUDIO_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE[g]))),g.videoRating?.issues?.forEach((g=>f.push(CallSurveyFeatureImplOverTsCall.ACS_VIDEO_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE[g]))),g.screenshareRating?.issues?.forEach((g=>f.push(CallSurveyFeatureImplOverTsCall.ACS_SCREENSHARE_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE[g]))),f.length>0?"checks="+f.join("%20"):""}getFiveStarRating(g){if(g?.scale){const f=g.score-g.scale.lowerBound+1,S=g.scale.upperBound-g.scale.lowerBound+1,v=Math.round(5*f/S);return v<1?1:v}return g?.score}createCallSurveyInternal(g){const f={callId:this._callSurveyInfo?.callId,localParticipantId:this._callSurveyInfo?.localParticipantId};return g&&(f.overallRating=g.overallRating,f.audioRating=g.audioRating,f.videoRating=g.videoRating,f.screenshareRating=g.screenshareRating),f}validateSurvey(g){let f="";return f=this.validateOverallRating(g.overallRating),f+=this.validateAudioRating(g.audioRating),f+=this.validateVideoRating(g.videoRating),f+=this.validateScreenshareRating(g.screenshareRating),""!==f||g.overallRating||g.audioRating||g.videoRating||g.screenshareRating||(f="At least one survey rating is required."),""===f&&(f=this.validateCallSurveyTypes(g)),f.trim()}validateOverallRating(g){if(!g)return"";let f="";return this.isValidFiveStarRating(g)?g.scale&&!this.isRatingValueMatchesRatingScale(g.score,g.scale)?f=this.ratingOutOfRangeMessage(CallSurveyFeatureImplOverTsCall.OVERALL_RATING_SCORE,g):g.scale&&!this.isValidQualityThreshold(g.scale)?f=this.thresholdOutOfRangeMessage("overallRating.scale.lowScoreThreshold",g):g.scale&&!this.isValidRatingScale(g.scale)&&(f=this.ratingScaleOutOfRangeMessage("overallRating.scale",g)):f=this.defaultRatingScaleMessage(CallSurveyFeatureImplOverTsCall.OVERALL_RATING_SCORE),f}validateAudioRating(g){if(!g)return"";let f="";return this.isValidFiveStarRating(g)?g.scale&&!this.isRatingValueMatchesRatingScale(g.score,g.scale)?f=this.ratingOutOfRangeMessage(CallSurveyFeatureImplOverTsCall.AUDIO_RATING_SCORE,g):g.scale&&!this.isValidQualityThreshold(g.scale)?f=this.thresholdOutOfRangeMessage("audioRating.scale.lowScoreThreshold",g):g.scale&&!this.isValidRatingScale(g.scale)&&(f=this.ratingScaleOutOfRangeMessage("audioRating.scale",g)):f=this.defaultRatingScaleMessage(CallSurveyFeatureImplOverTsCall.AUDIO_RATING_SCORE),f}validateVideoRating(g){if(!g)return"";let f="";return this.isValidFiveStarRating(g)?g.scale&&!this.isRatingValueMatchesRatingScale(g.score,g.scale)?f=this.ratingOutOfRangeMessage(CallSurveyFeatureImplOverTsCall.VIDEO_RATING_SCORE,g):g.scale&&!this.isValidQualityThreshold(g.scale)?f=this.thresholdOutOfRangeMessage("videoRating.scale.lowScoreThreshold",g):g.scale&&!this.isValidRatingScale(g.scale)&&(f=this.ratingScaleOutOfRangeMessage("videoRating.scale",g)):f=this.defaultRatingScaleMessage(CallSurveyFeatureImplOverTsCall.VIDEO_RATING_SCORE),f}validateScreenshareRating(g){if(!g)return"";let f="";return this.isValidFiveStarRating(g)?g.scale&&!this.isRatingValueMatchesRatingScale(g.score,g.scale)?f=this.ratingOutOfRangeMessage(CallSurveyFeatureImplOverTsCall.SCREEN_SHARE_RATING_SCORE,g):g.scale&&!this.isValidQualityThreshold(g.scale)?f=this.thresholdOutOfRangeMessage("screenshareRating.scale.lowScoreThreshold",g):g.scale&&!this.isValidRatingScale(g.scale)&&(f=this.ratingScaleOutOfRangeMessage("screenshareRating.scale",g)):f=this.defaultRatingScaleMessage(CallSurveyFeatureImplOverTsCall.SCREEN_SHARE_RATING_SCORE),f}validateCallSurveyTypes(g){let f="";return g.overallRating&&(f=this.valueShouldBeNumber(CallSurveyFeatureImplOverTsCall.OVERALL_RATING_SCORE,g.overallRating.score),g.overallRating.issues&&(this.isArray(g.overallRating.issues)?g.overallRating.issues.some((g=>CallSurveyFeatureImplOverTsCall.OVERALL_ISSUES[g]!==g))&&(f+="overallRating.issues array should be of type OverallIssue. "):f+="overallRating.issues should be of type Array<OverallIssue>. "),f+=this.ratingScaleShouldNotHaveUnexpectedProperties("overallRating.scale",g.overallRating.scale),f+=this.ratingShouldNotHaveUnexpectedProperties("overallRating",g.overallRating)),g.audioRating&&(f+=this.valueShouldBeNumber(CallSurveyFeatureImplOverTsCall.AUDIO_RATING_SCORE,g.audioRating.score),g.audioRating.issues&&(this.isArray(g.audioRating.issues)?g.audioRating.issues.some((g=>CallSurveyFeatureImplOverTsCall.AUDIO_ISSUES[g]!==g))&&(f+="audioRating.issues array should be of type AudioIssue. "):f+="audioRating.issues should be of type Array<AudioIssue>. "),f+=this.ratingScaleShouldNotHaveUnexpectedProperties("audioRating.scale",g.audioRating.scale),f+=this.ratingShouldNotHaveUnexpectedProperties("audioRating",g.audioRating)),g.videoRating&&(f+=this.valueShouldBeNumber(CallSurveyFeatureImplOverTsCall.VIDEO_RATING_SCORE,g.videoRating.score),g.videoRating.issues&&(this.isArray(g.videoRating.issues)?g.videoRating.issues.some((g=>CallSurveyFeatureImplOverTsCall.VIDEO_ISSUES[g]!==g))&&(f+="videoRating.issues array should be of type VideoIssue. "):f+="videoRating.issues should be of type Array<VideoIssue>. "),f+=this.ratingScaleShouldNotHaveUnexpectedProperties("videoRating.scale",g.videoRating.scale),f+=this.ratingShouldNotHaveUnexpectedProperties("videoRating",g.videoRating)),g.screenshareRating&&(f+=this.valueShouldBeNumber(CallSurveyFeatureImplOverTsCall.SCREEN_SHARE_RATING_SCORE,g.screenshareRating.score),g.screenshareRating.issues&&(this.isArray(g.screenshareRating.issues)?g.screenshareRating.issues.some((g=>CallSurveyFeatureImplOverTsCall.SCREENSHARE_ISSUES[g]!==g))&&(f+="screenshareRating.issues array should be of type ScreenshareIssue. "):f+="screenshareRating.issues should be of type Array<ScreenshareIssue>. "),f+=this.ratingScaleShouldNotHaveUnexpectedProperties("screenshareRating.scale",g.screenshareRating.scale),f+=this.ratingShouldNotHaveUnexpectedProperties("screenshareRating",g.screenshareRating)),f}isNumber(g){return null!==g&&"number"==typeof g}isArray(g){return null!==g&&Array.isArray(g)}isValidFiveStarRating(g){return null==g||void 0!==g.scale||g.score>=1&&g.score<=5}isRatingValueMatchesRatingScale(g,f){return g>=f.lowerBound&&g<=f.upperBound}isValidQualityThreshold(g){return g.lowScoreThreshold>=g.lowerBound&&g.lowScoreThreshold<=g.upperBound}isValidRatingScale(g){return g.lowerBound>=0&&g.upperBound<=100}valueShouldBeNumber(g,f){return this.isNumber(f)?"":`${g} should be of type number. `}ratingScaleShouldNotHaveUnexpectedProperties(g,f){let S="";if(!f)return S;for(const v in f)void 0===CallSurveyFeatureImplOverTsCall.RATING_SCALE_KEYS[v]&&(S+=`${g} should not have ${v}. `);return S}ratingShouldNotHaveUnexpectedProperties(g,f){let S="";if(!f)return S;for(const v in f)void 0===CallSurveyFeatureImplOverTsCall.CALL_RATING_KEYS[v]&&(S+=`${g} should not have ${v}. `);return S}defaultRatingScaleMessage(g){return`In default scale ${g} should be 1 to 5. `}ratingOutOfRangeMessage(g,f){return`${g}: ${f.score} should be between ${f.scale?.lowerBound} and ${f.scale?.upperBound}. `}thresholdOutOfRangeMessage(g,f){return`${g}: ${f.scale?.lowScoreThreshold} should be between ${f.scale?.lowerBound} and ${f.scale?.upperBound}. `}ratingScaleOutOfRangeMessage(g,f){return`${g} lowerBound: ${f.scale?.lowerBound} and upperBound: ${f.scale?.upperBound} should be between 0 and 100. `}}CallSurveyFeatureImplOverTsCall.OVERALL_RATING_SCORE="overallRating.score",CallSurveyFeatureImplOverTsCall.AUDIO_RATING_SCORE="audioRating.score",CallSurveyFeatureImplOverTsCall.VIDEO_RATING_SCORE="videoRating.score",CallSurveyFeatureImplOverTsCall.SCREEN_SHARE_RATING_SCORE="screenshareRating.score",CallSurveyFeatureImplOverTsCall.NOTIFICATION_LISTENER={},CallSurveyFeatureImplOverTsCall.OVERALL_ISSUES={CallCannotInvite:"CallCannotInvite",CallCannotJoin:"CallCannotJoin",CallEndedUnexpectedly:"CallEndedUnexpectedly",HadToRejoin:"HadToRejoin",OtherIssues:"OtherIssues"},CallSurveyFeatureImplOverTsCall.AUDIO_ISSUES={AudioInterruption:"AudioInterruption",AudioNoise:"AudioNoise",AudioStoppedUnexpectedly:"AudioStoppedUnexpectedly",DistortedSpeech:"DistortedSpeech",Echo:"Echo",LowVolume:"LowVolume",NoLocalAudio:"NoLocalAudio",NoRemoteAudio:"NoRemoteAudio",OtherIssues:"OtherIssues"},CallSurveyFeatureImplOverTsCall.VIDEO_ISSUES={AudioVideoOutOfSync:"AudioVideoOutOfSync",DarkVideoReceived:"DarkVideoReceived",Freezes:"Freezes",LowQuality:"LowQuality",NoVideoReceived:"NoVideoReceived",NoVideoSent:"NoVideoSent",OtherIssues:"OtherIssues",StoppedUnexpectedly:"StoppedUnexpectedly"},CallSurveyFeatureImplOverTsCall.SCREENSHARE_ISSUES={CannotPresent:"CannotPresent",Freezes:"Freezes",LargeDelay:"LargeDelay",LowQuality:"LowQuality",NoContentLocal:"NoContentLocal",NoContentRemote:"NoContentRemote",OtherIssues:"OtherIssues",StoppedUnexpectedly:"StoppedUnexpectedly"},CallSurveyFeatureImplOverTsCall.CALL_RATING_KEYS={score:"score",issues:"issues",scale:"scale"},CallSurveyFeatureImplOverTsCall.RATING_SCALE_KEYS={lowerBound:"lowerBound",upperBound:"upperBound",lowScoreThreshold:"lowScoreThreshold"},CallSurveyFeatureImplOverTsCall.ACS_OVERALL_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE={CallCannotInvite:502,CallCannotJoin:501,CallEndedUnexpectedly:501,HadToRejoin:501,OtherIssues:501},CallSurveyFeatureImplOverTsCall.ACS_AUDIO_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE={AudioInterruption:108,AudioNoise:104,AudioStoppedUnexpectedly:106,DistortedSpeech:107,Echo:103,LowVolume:105,NoLocalAudio:101,NoRemoteAudio:102,OtherIssues:109},CallSurveyFeatureImplOverTsCall.ACS_VIDEO_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE={AudioVideoOutOfSync:207,DarkVideoReceived:206,Freezes:204,LowQuality:203,NoVideoReceived:201,NoVideoSent:202,OtherIssues:208,StoppedUnexpectedly:205},CallSurveyFeatureImplOverTsCall.ACS_SCREENSHARE_ISSUES_TO_TEAMS_CQF_PROBLEM_TOKEN_CODE={CannotPresent:402,Freezes:405,LargeDelay:407,LowQuality:404,NoContentLocal:401,NoContentRemote:402,OtherIssues:408,StoppedUnexpectedly:406};class AudioZonesCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new AudioZonesImpl(this.eventEmitter,this.name)}get name(){return"AudioZones"}initialize(g,f){this._impl.initialize(g.tsCall,g.callAgent,g.call,g.telemetryLogManager,f)}updateAudioZone(g,f){return this._impl.updateAudioZone(g,f)}dispose(){this._impl.dispose(),super.dispose()}get meetingGroupDetails(){return this._impl.meetingGroupDetails}on(g,f){this.eventEmitter.on(g,f)}off(g,f){this.eventEmitter.off(g,f)}}class AudioZonesImpl{constructor(g,f){this._eventEmitter=g,this._featureName=f}initialize(g,f,S,v,C){this._logger=C.createChild((()=>`${this._featureName}::Call(id='${g.callId}')`)),this._tsCall=g,this.updateMeetingGroupDetails(),this._tsCall.changed((()=>{this._logger.log("tsCall changed"),this.updateMeetingGroupDetails()}))}updateAudioZone(g,f){const S=generateGuid();return this._logger.log(`updateAudioZone toGroup=${g}, fromGroup=${f}, causeId=${S}`),this._tsCall.updateMeetingGroups(S,{scope:4,toGroup:g,fromGroup:f})}dispose(){this._meetingGroupDetails=void 0}get meetingGroupDetails(){return this._meetingGroupDetails}updateMeetingGroupDetails(){const g=this._tsCall.meetingDetails?.meetingGroups??void 0;M.isEqual(g,this._meetingGroupDetails)||(this._meetingGroupDetails=g,this._eventEmitter.emit("meetingGroupDetailsChanged"))}}class OptimalVideoCountCallFeatureImpl extends FirstPartyCallFeature{_sendOVCTelemetryEvent(g){if(!this._telemetryLogManager)return;const f={callId:this._call?.id||"",localParticipantId:this._tsCall?.participantId||"",featureName:"OptimalVideoCount",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{step:g}};this._telemetryLogManager.sendEvent({name:uE.acs_calling_feature_usage,tenant:tf,properties:f})}get optimalVideoCount(){return this._sendOVCTelemetryEvent(gE.getter),this._tsCall?.optimalVideoCount?this._tsCall.optimalVideoCount:1}constructor(g){super(g),this.name="OptimalVideoCount",this._impl=new OptimalVideoCountCallFeatureImplOverTsCall(this.name,this.eventEmitter,this.optimalVideoCount)}initialize(g,f){this._impl.initialize(g.tsCall,g.callAgent,g.call,g.telemetryLogManager,f),this._tsCall=g.tsCall,this._telemetryLogManager=g.telemetryLogManager,this._call=g.call}on(g,f){if("optimalVideoCountChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.OPTIMAL_VIDEO_COUNT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._sendOVCTelemetryEvent(gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){if("optimalVideoCountChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.OPTIMAL_VIDEO_COUNT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._sendOVCTelemetryEvent(gE.unsubscribe),this.eventEmitter.off(g,f)}}class OptimalVideoCountCallFeatureImplOverTsCall{constructor(g,f,S){this._featureName=g,this._eventEmitter=f,this._optimalVideoCount=S}initialize(g,f,S,v,C){this._tsCall=g,this._logger=C,this._logger?.createChild((()=>`${this._featureName}::Call(id='${this._tsCall?.callId}')`)),this._tsCall.changed((()=>this.ovcChanged(g)))}ovcChanged(g){g?.optimalVideoCount&&g.optimalVideoCount!==this._optimalVideoCount&&(this._logger.log(`tsCall optimalVideoCount changed from ${this._optimalVideoCount} to ${g?.optimalVideoCount}`),this._eventEmitter.emit("optimalVideoCountChanged"))}}function invalidEventSubscription$1(g,f){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.EVENT_SUBSCIBE_UNSUBSCRIBE,defaultErrorMessageArgs:[f,g]})}function unmixedAudioIsNotAvailable(){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.UNAVAILABLE})}function getErrorString$1(g){return M.isString(g)?g:g?.message??"Unknown"}function rethrowError(g){throw g instanceof CallingCommunicationError?g:new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.UNKNOWN_ERROR})}function hasPendingOpertion(){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.PENDING_OPERATION})}function notSupportP2P(){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.UNSUPPORTED_OPERATION})}function unmixedAudioHasBeenEnabled(){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.ENABLED})}function unmixedAudioHasBeenDisabled(){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.DISABLED})}function unmixedAudioHasBeenDisposed(){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.DISPOSED})}function invalidState(g){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.INVALID_STATE,defaultErrorMessageArgs:[g]})}function failedToInitialize(g){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.FAILED_TO_INITIALIZE,originalError:g})}function failedToEnable(g,f){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.FAILED_TO_ENABLE,defaultErrorMessageArgs:[f.audioContextState||"undefined",f.unmixedAudioState||"undefined"],originalError:g})}function failedToDisable(g,f){return new CallingCommunicationError({defaultError:D.FEATURES.UNMIXED_AUDIO.FAILED_TO_DISABLE,defaultErrorMessageArgs:[f.audioContextState||"undefined",f.unmixedAudioState||"undefined"],originalError:g})}class ParticipantMappingManager$2{constructor(g){this._tsCall=g,this._sourceIdMapping=new Map,this._participantIdMapping=new Map,this._listenerHandles=[],this._listenerHandles.push(this._tsCall.on("participantAdded",(g=>{this._updateMapping(g)}))),this._listenerHandles.push(this._tsCall.on("participantUpdated",(g=>{this._updateMapping(g)}))),this._listenerHandles.push(this._tsCall.on("participantRemoved",(g=>{this._removeMapping(g)}))),this._tsCall.participants.forEach((g=>{this._updateMapping(g)}))}_updateMapping(g){g.endpoints?.endpointDetails?.forEach((f=>{const S=f.mediaStreams?.find((g=>"audio"===g.type));if(S){const v={sourceId:S.sourceId,participantId:f.participantId,mri:g.id};this._sourceIdMapping.set(S.sourceId,v),this._participantIdMapping.set(f.participantId,v)}}))}_removeMapping(g){g.endpoints?.endpointDetails?.forEach((g=>{const f=g.mediaStreams?.find((g=>"audio"===g.type));f&&(this._sourceIdMapping.delete(f.sourceId),this._participantIdMapping.delete(g.participantId))}))}findParticipantInfoBySourceId(g){return this._sourceIdMapping.get(g)}findParticipantInfoByParticipantId(g){return this._participantIdMapping.get(g)}dispose(){this._sourceIdMapping.clear(),this._participantIdMapping.clear(),this._listenerHandles.forEach((g=>g.dispose()))}}class UnmixedAudioTelemetryLogger{constructor(g,f){this._tsCall=g,this._telemetryLogManager=f}sendActionEvent(g){const f={...{callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId},...g};this._telemetryLogManager.sendEvent({name:uE.acs_calling_unmixed_audio,tenant:tf,properties:f})}}class UnmixedAudioActionTelemetryLogger{constructor(g,f){this._unmixedAudioTelemetryLogger=g,this._action=f,this._correlationId=generateGuid()}logAttempt(){this._unmixedAudioTelemetryLogger.sendActionEvent({action:this._action,kindOfEvent:"attempt",correlationId:this._correlationId})}logSuccess(){this._unmixedAudioTelemetryLogger.sendActionEvent({action:this._action,kindOfEvent:"success",correlationId:this._correlationId})}logFailure(g,f){this._unmixedAudioTelemetryLogger.sendActionEvent({action:this._action,kindOfEvent:"failure",correlationId:this._correlationId,failureReason:g.message,...f,additionalDetails:{...extractCommunicationServicesErrorForTelemetry(g)}})}}class StatePromise{constructor(g,f){this._waitTimeoutInMs=g,this._expectedState=f,this._result=defer(),this._wait=wait((()=>this._result.promise),this._waitTimeoutInMs)}updateState(g){this._result.isPending()&&(g===this._expectedState?this._result.resolve():this._result.reject(new Error(`Unexpected active state: ${g}`)))}get waitState(){return this._expectedState}async wait(){await this._wait}cancel(){this._result.isPending()&&this._result.reject(new Error("Operation cancelled"))}}class UnmixedAudioContext{constructor(g,f){this._logger=g.createChild(`AudioContext:${f}`),this._eventEmitter=new LE.EventEmitter;const S=new AudioContext,stateChangeHandler=()=>{this._logger.info(`The AudioContext:${f} state changed to ${S.state}`),this._eventEmitter.emit("stateChanged"),"closed"===S.state&&(S.removeEventListener("statechange",stateChangeHandler),this._eventEmitter.removeAllListeners())};S.addEventListener("statechange",stateChangeHandler),this._audioContext=S}async resume(g=0){if("closed"===this._audioContext.state)throw invalidState(this._audioContext.state);if("running"===this._audioContext.state)return;const f=new StatePromise(g,!0);return this._audioContext.resume().then((()=>{f.updateState(!0),this._logger.info("resumed")})).catch((g=>{this._logger.info(`Failed to resume: ${getErrorString$1(g)}`),f.updateState(!1)})),f.wait()}async close(){"closed"!==this._audioContext.state&&await this._audioContext.close().then((()=>{this._logger.info("closed")})).catch((g=>{this._logger.info(`Failed to close: ${getErrorString$1(g)}`)}))}get state(){return this._audioContext.state}get value(){return this._audioContext}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}}function getStateString(g){switch(g){case gT.Uninitialized:return"Uninitialized";case gT.Initializing:return"Initializing";case gT.Initialized:return"Initialized";case gT.Destroyed:return"Destroyed";case gT.Aborted:return"Aborted"}}!function(g){g[g.Uninitialized=0]="Uninitialized",g[g.Initializing=1]="Initializing",g[g.Initialized=2]="Initialized",g[g.Destroyed=3]="Destroyed",g[g.Aborted=4]="Aborted"}(gT||(gT={}));class UnmixedAudioManager{constructor(g,f,S,v){this._state=gT.Uninitialized,this._listenerHandles=[],this._audioContextSeq=0,this._activeState=!1,this._pendingOperation=!1,this._initializedDefer=defer();try{this._tsCall=g,this._logger=f.createChild("UnmixedAudioManager"),this._eventEmitter=new CallingEventEmitter(this._logger,{enableLogEmit:!1}),this._unmixedAudioTelemetryLogger=S,this._participantManager=new ParticipantMappingManager$2(g),this._destinationStreamInfoMap=new Map,this._destinationStreamInfoList=new Array(v.maxStreamSize),this._sourceStreamInfoList=new Array(v.maxStreamSize),this._maxStreamSize=v.maxStreamSize,this._operationTimeoutInMs=v.operationTimeoutInMs,this._skipProviderStateCheck=v.skipProviderStateCheck}catch(g){throw this._state=gT.Aborted,f.info(`Failed to create UnmixedAudioManager: ${getErrorString$1(g)}`),failedToInitialize(g)}}async initialize(){if(this._state!==gT.Uninitialized)throw invalidState(getStateString(this._state));this._initializedDefer.isPending()||(this._initializedDefer=defer());const g=new UnmixedAudioActionTelemetryLogger(this._unmixedAudioTelemetryLogger,"initialize");this._state=gT.Initializing;try{if(g.logAttempt(),!this._tsCall.getUnmixedAudioProvider)throw unmixedAudioIsNotAvailable();if(this._tsUnmixedAudioProvider=this._tsUnmixedAudioProvider??await this._tsCall.getUnmixedAudioProvider(),!this._tsUnmixedAudioProvider)throw unmixedAudioIsNotAvailable();this._audioContext||(this._audioContext=new UnmixedAudioContext(this._logger,this._audioContextSeq++),this._audioContext.on("stateChanged",(()=>{this._updateActiveState()}))),0===this._listenerHandles.length&&(this._listenerHandles.push(this._tsUnmixedAudioProvider.on("onStreamSourcesUpdated",(g=>{this._state===gT.Initialized?this._onStreamSourcesUpdatedHandler(g):this._logger.error(`Cannot attach _onStreamSourcesUpdatedHandler listener - this._state:${this._state}`)}))),this._listenerHandles.push(this._tsUnmixedAudioProvider.on("onActiveStateChanged",(()=>{this._state===gT.Initialized?this._updateActiveState():this._logger.error(`Cannot attach _updateActiveState listener - this._state:${this._state}`)})))),g.logSuccess(),this._logger.info(`Initialized with maxStreamSize ${this._maxStreamSize}. The AudioContext state is ${this._getAudioContextState()}. tsUnmixedAudioProvider state is: [active: ${this._tsUnmixedAudioProvider.active} configured: ${this._tsUnmixedAudioProvider.configured}]`),this._state=gT.Initialized,this._initializedDefer.resolve(),this._updateActiveState()}catch(f){this._state=gT.Uninitialized;const S=getErrorString$1(f);this._logger.error(`Failed to initialize: ${S}`);const v=failedToInitialize(f);g.logFailure(v),this._initializedDefer.reject(v)}return this._initializedDefer.promise}async enableUnmixedAudio(){const g=new UnmixedAudioActionTelemetryLogger(this._unmixedAudioTelemetryLogger,"enable");try{if(![gT.Uninitialized,gT.Initializing,gT.Initialized].includes(this._state))throw invalidState(getStateString(this._state));if(1===this._tsCall.callType)throw notSupportP2P();if(this._pendingOperation)throw hasPendingOpertion();if(this.isUnmixedAudioEnabled&&(this._skipProviderStateCheck||"active"===this._getUnmixedAudioProviderState())&&"running"===this._getAudioContextState())throw unmixedAudioHasBeenEnabled();this._pendingOperation=!0,g.logAttempt(),this._state===gT.Uninitialized?await this.initialize():this._state===gT.Initializing&&await this._initializedDefer.promise,void 0!==this._audioContext&&"closed"!==this._getAudioContextState()||(this._cleaupAudioNodes(),this._audioContext=new UnmixedAudioContext(this._logger,this._audioContextSeq++),this._audioContext.on("stateChanged",(()=>{this._updateActiveState()})));const f=[["resume AudioContext","running"===this._getAudioContextState()?void 0:this._audioContext.resume(this._operationTimeoutInMs)],["enable spatial audio config",this.isUnmixedAudioEnabled?void 0:this._enableSpatialAudio(!0)]];await this._runTasks(f),this._pendingOperation=!1,g.logSuccess(),this._logger.info(`UnmixedAudio is enabled. The AudioContext state is ${this._getAudioContextState()}.`),this._updateActiveState()}catch(f){const S=this._getAudioContextState(),v=this._getUnmixedAudioProviderState(),C=getErrorString$1(f);this._logger.error(`Failed to enable unmixed audio: ${C}. isEnabled=${this.isUnmixedAudioEnabled}, AudioContext=${S}, UnmixedAudio=${v}`);const _={audioContextState:S,unmixedAudioState:v},T=failedToEnable(f,_);!1===this._pendingOperation&&rethrowError(T),g.logFailure(T,_),this._pendingOperation=!1,rethrowError(T)}}async disableUnmixedAudio(){const g=new UnmixedAudioActionTelemetryLogger(this._unmixedAudioTelemetryLogger,"disable");try{if(![gT.Initializing,gT.Initialized].includes(this._state))throw invalidState(getStateString(this._state));if(1===this._tsCall.callType)throw notSupportP2P();if(this._pendingOperation)throw hasPendingOpertion();if(!this.isUnmixedAudioEnabled)throw unmixedAudioHasBeenDisabled();this._pendingOperation=!0,g.logAttempt(),this._state===gT.Initializing&&await this._initializedDefer.promise;const f=[["disable spatial audio config",this._enableSpatialAudio(!1)]];await this._runTasks(f),this._pendingOperation=!1,g.logSuccess(),this._logger.info("UnmixedAudio is disabled")}catch(f){const S=this._getAudioContextState(),v=this._getUnmixedAudioProviderState(),C=getErrorString$1(f);this._logger.info(`Failed to disable unmixed audio: ${C}. isEnabled=${this.isUnmixedAudioEnabled}, AudioContext=${S}, UnmixedAudio=${v}`);const _={audioContextState:S,unmixedAudioState:v},T=failedToDisable(f,_);!1===this._pendingOperation&&rethrowError(T),g.logFailure(T,_),this._pendingOperation=!1,rethrowError(T)}}get isUnmixedAudioActive(){return this._state===gT.Initialized&&("active"===this._getUnmixedAudioProviderState()&&"running"===this._getAudioContextState())}get isUnmixedAudioEnabled(){return this._state===gT.Initialized&&(this._tsUnmixedAudioProvider?.configured??!1)}getAudioSourceIdsFromParticipantIds(g){return g.map((g=>this._participantManager.findParticipantInfoByParticipantId(g.participantId)?.sourceId)).filter((g=>void 0!==g))}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}dispose(){this._state!==gT.Destroyed&&(this._state=gT.Destroyed,this._initializedDefer.isPending()&&this._initializedDefer.reject(unmixedAudioHasBeenDisposed()),this._listenerHandles.forEach((g=>g.dispose())),this._cleaupAudioNodes(),this._participantManager.dispose(),this._audioContext?.close(),this._eventEmitter.removeAllListeners())}_getAudioContextState(){return this._audioContext?.state??"unavailable"}_getUnmixedAudioProviderState(){return this._tsUnmixedAudioProvider?this._tsUnmixedAudioProvider.active?"active":"inactive":"unavailable"}_cleaupAudioNodes(){this._sourceStreamInfoList.forEach(((g,f)=>{const S=this._destinationStreamInfoList[f];void 0!==g&&void 0!==S&&g.audioNode.disconnect(S.audioNode),this._sourceStreamInfoList[f]=void 0,this._destinationStreamInfoList[f]=void 0})),this._destinationStreamInfoMap.clear()}_onStreamSourcesUpdatedHandler(g){const f=this._audioContext?.value;if(void 0===f||"running"!==f.state)return void this._logger.warn(`Dropping onStreamSourcesUpdated event because audioContext.state is ${f?.state}`);const S=[];for(let v=0;v<this._maxStreamSize;v++){const C=v<g.length?g[v]:0,_=C?this._participantManager.findParticipantInfoBySourceId(C):void 0;let T=this._destinationStreamInfoList[v],I=this._sourceStreamInfoList[v];if(void 0===_)void 0!==T&&void 0!==I&&(I.audioNode.disconnect(T.audioNode),this._destinationStreamInfoList[v]=void 0);else{const g=this._tsUnmixedAudioProvider?.streams[v]??void 0;if(void 0!==I&&I.mediaStream!==g&&(void 0!==T&&I.audioNode.disconnect(T.audioNode),I=void 0,this._sourceStreamInfoList[v]=void 0),!g)continue;let C=!1;void 0!==I&&void 0!==T&&_.participantId!==T.participantId&&(I.audioNode.disconnect(T.audioNode),T=void 0,this._destinationStreamInfoList[v]=void 0),void 0===T&&(T=this._destinationStreamInfoMap.get(_.participantId),void 0===T&&(T={participantId:_.participantId,identifier:constructIdentifierKindFromMri(_.mri),audioNode:f.createMediaStreamDestination()},this._destinationStreamInfoMap.set(_.participantId,T)),this._destinationStreamInfoList[v]=T,C=!0),void 0===I&&(I={mediaStream:g,audioNode:f.createMediaStreamSource(g)},this._sourceStreamInfoList[v]=I,C=!0),C&&I.audioNode.connect(T.audioNode),S.push({id:_.sourceId,stream:T.audioNode.stream,participantId:_.participantId,identifier:T.identifier})}}this._eventEmitter.emit("participantSpeaking",{speakers:S})}async _enableSpatialAudio(g){await this._tsCall.setAudioMidcallConfigJson({enableSpatialAudio:g})}async _runTasks(g){let f;if((await Promise.allSettled(g.map((g=>g[1])))).forEach(((S,v)=>{"rejected"===S.status&&(this._logger.info(`Failed to ${g[v][0]}: ${getErrorString$1(S.reason)}}`),f=S)})),void 0!==f)throw f.reason}_updateActiveState(){const g=this.isUnmixedAudioActive;g!==this._activeState&&(this._activeState=g,this._eventEmitter.emit("activeStateChanged"))}}class UnmixedAudioCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g)}initialize(g,f){const S=getAcsEcsConfig().unmixedAudio;this._tsCall=g.tsCall,this._logger=f.createChild("UnmixedAudioCallFeature"),this._telemetryLogManager=g.telemetryLogManager;const v=new UnmixedAudioTelemetryLogger(this._tsCall,this._telemetryLogManager);this._unmixedAudioManager=new UnmixedAudioManager(this._tsCall,this._logger,v,S),this._unmixedAudioManager.initialize().then((()=>{this._sendFeatureUsage("initialize",gE.initialize)})).catch((g=>{}))}get name(){return this._sendFeatureUsage("name",gE.getter),"UnmixedAudio"}dispose(){this.disposed||(this._unmixedAudioManager.dispose(),super.dispose())}enableUnmixedAudio(){return this._unmixedAudioManager.enableUnmixedAudio()}disableUnmixedAudio(){return this._unmixedAudioManager.disableUnmixedAudio()}get isUnmixedAudioActive(){return this._unmixedAudioManager.isUnmixedAudioActive}get isUnmixedAudioEnabled(){return this._unmixedAudioManager.isUnmixedAudioEnabled}getAudioStreamIdsFromParticipant(g){return this._unmixedAudioManager.getAudioSourceIdsFromParticipantIds(g.endpointDetails)}on(g,f){if("participantSpeaking"!==g&&"activeStateChanged"!==g)throw invalidEventSubscription$1(g,"subscribe");this._sendFeatureUsage(g,gE.subscribe),this._unmixedAudioManager.on(g,f)}off(g,f){if("participantSpeaking"!==g&&"activeStateChanged"!==g)throw invalidEventSubscription$1(g,"unsubscribe");this._sendFeatureUsage(g,gE.unsubscribe),this._unmixedAudioManager.off(g,f)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"UnmixedAudio",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}}class TeamsMeetingAudioConferencingCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new TeamsMeetingConferencingCallFeatureImplOverTsCall}get name(){return"TeamsMeetingAudioConferencing"}initialize(g,f){this._impl.initialize(g.tsCall,g.callAgent,g.telemetryLogManager,f)}async getTeamsMeetingAudioConferencingDetails(){return this._impl.getTeamsMeetingAudioConferencingDetails()}dispose(){this.disposed||super.dispose()}}class TeamsMeetingConferencingCallFeatureImplOverTsCall{constructor(){this._isEnabled=getAcsEcsConfig().calling.teamsMeetingAudioConferencing.enabled,this._supportedConversationTypes=getAcsEcsConfig().calling.teamsMeetingAudioConferencing.supportedConversationTypes}initialize(g,f,S,v){this._logger=v.createChild((()=>`teamsMeetingAudioConferencing::Call(id='${g.callId}')`)),this._tsCall=g,this._telemetryLogManager=S,this._internalCallAgent=f;const C="initialize";if(this.sendFeatureUsage(C,gE.initialize),!this.isSupportedConversationType()){const g=new CallingCommunicationError({defaultError:D.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.ONLY_AVAILABLE_IN_MEETINGS});throw this._logger.error(g.message),this.sendFeatureUsage(C,gE.failure,g),g}this.sendFeatureUsage(C,gE.success)}getTeamsMeetingAudioConferencingDetails(){const g="getTeamsMeetingAudioConferencingDetails";if(this.sendFeatureUsage(g,gE.attempt),!this._isEnabled){const f=new CallingCommunicationError({defaultError:D.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.DISABLED});return this._logger.error(f.message),this.sendFeatureUsage(g,gE.failure,f),Promise.reject(f)}if(!this.isSupportedConversationType()){const f=new CallingCommunicationError({defaultError:D.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.ONLY_AVAILABLE_IN_MEETINGS});return this._logger.error(f.message),this.sendFeatureUsage(g,gE.failure,f),Promise.reject(f)}let f;if(3!==this._tsCall.state)return f=new CallingCommunicationError({defaultError:D.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.UNAVAILABLE_BEFORE_JOINING}),10===this._tsCall.state&&(f=new CallingCommunicationError({defaultError:D.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.UNVAILABLE_IN_LOBBY})),this.sendFeatureUsage(g,gE.failure,f),this._logger.error(f.message),Promise.reject(f);let S={phoneConferenceId:"",phoneNumbers:[]};try{const f=this._tsCall?.meetingDetails?.pstnDetails?.acpMcuInfo?.settings,v=this._tsCall?.meetingDetails?.pstnDetails?.meetingInvitePhoneNumbers;if(f||v){const g=f?.participantPasscode||"",C=v?.flatMap((g=>{const getFormattedPhoneNumber=()=>{const f=g.isTollFree?void 0:constructIdentifierKindFromMri($f+g.number),S=g.isTollFree?constructIdentifierKindFromMri($f+g.number):void 0;return{cityName:g?.cityName,countryName:g?.countryName,tollPhoneNumber:f,tollFreePhoneNumber:S}};return g.number?getFormattedPhoneNumber():[]}))||[];if(null===C||0===C.length){const g={cityName:void 0,countryName:void 0,tollPhoneNumber:f?.tollNumber&&constructIdentifierKindFromMri($f+f?.tollNumber),tollFreePhoneNumber:f?.tollFreeNumber&&constructIdentifierKindFromMri($f+f?.tollFreeNumber)};C.push(g)}S={phoneConferenceId:g,phoneNumbers:C},this._logger.info("Teams meeting audio conferencing details was retrieved successfully")}return this.sendFeatureUsage(g,gE.success),Promise.resolve(S)}catch(f){const S=new CallingCommunicationError({defaultError:D.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.GET_DETAILS_FAILED,originalError:f});throw this.sendFeatureUsage(g,gE.failure,S),S}}isSupportedConversationType(){const g=this._tsCall.conversationType;let f=this._supportedConversationTypes.find((f=>f===g));return this._logger.info(`TeamsMeetingAudioConferencingDetails::ConversationType = \n            ${g}. ConversationType is supported = ${f}`),f}sendFeatureUsage(g,f,S){let v=S?{code:S?.code||U,subCode:S?.subCode||0,failureReason:S?.message||"",...extractCommunicationServicesErrorForTelemetry(S)}:void 0;sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"TeamsMeetingAudioConferencing",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:v},this._telemetryLogManager,this._logger)}}var pT,mT=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.TraceLevel=void 0,function(g){g[g.Error=10]="Error",g[g.Warning=15]="Warning",g[g.Info=50]="Info"}(f.TraceLevel||(f.TraceLevel={}))})),fT=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.MessageTrackingOption=f.ConnectionState=f.ServiceGeneratedClientIdName=f.SystemCommandsStateName=f.ConfigurationName=f.SystemSessionStateName=f.StateSubscriptionsName=void 0,f.StateSubscriptionsName="ConfigStateSubscriptions",f.SystemSessionStateName="systemSessionState",f.ConfigurationName="config",f.SystemCommandsStateName="systemCommands",f.ServiceGeneratedClientIdName="serviceGeneratedClientId",function(g){g[g.Disconnected=0]="Disconnected",g[g.Connected=1]="Connected",g[g.Connecting=2]="Connecting"}(f.ConnectionState||(f.ConnectionState={})),function(g){g[g.All=0]="All",g[g.Last=1]="Last",g[g.None=2]="None"}(f.MessageTrackingOption||(f.MessageTrackingOption={}))})),ST=function bind(g,f){return function wrap(){return g.apply(f,arguments)}},vT=Object.prototype.toString,CT=(pT=Object.create(null),function(g){var f=vT.call(g);return pT[f]||(pT[f]=f.slice(8,-1).toLowerCase())});function kindOfTest(g){return g=g.toLowerCase(),function isKindOf(f){return CT(f)===g}}function isArray$2(g){return Array.isArray(g)}function isUndefined$1(g){return void 0===g}function isBuffer(g){return null!==g&&!isUndefined$1(g)&&null!==g.constructor&&!isUndefined$1(g.constructor)&&"function"==typeof g.constructor.isBuffer&&g.constructor.isBuffer(g)}var yT=kindOfTest("ArrayBuffer");function isArrayBufferView(g){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(g):g&&g.buffer&&yT(g.buffer)}function isString$1(g){return"string"==typeof g}function isNumber$1(g){return"number"==typeof g}function isObject$1(g){return null!==g&&"object"==typeof g}function isPlainObject$1(g){if("object"!==CT(g))return!1;var f=Object.getPrototypeOf(g);return null===f||f===Object.prototype}function isEmptyObject(g){return g&&0===Object.keys(g).length&&Object.getPrototypeOf(g)===Object.prototype}var ET=kindOfTest("Date"),_T=kindOfTest("File"),TT=kindOfTest("Blob"),IT=kindOfTest("FileList");function isFunction$1(g){return"[object Function]"===vT.call(g)}function isStream(g){return isObject$1(g)&&isFunction$1(g.pipe)}function isFormData(g){var f="[object FormData]";return g&&("function"==typeof FormData&&g instanceof FormData||vT.call(g)===f||isFunction$1(g.toString)&&g.toString()===f)}var bT=kindOfTest("URLSearchParams");function trim(g){return g.trim?g.trim():g.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}function isStandardBrowserEnv(){var g;return("undefined"==typeof navigator||"ReactNative"!==(g=navigator.product)&&"NativeScript"!==g&&"NS"!==g)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function forEach(g,f){if(null!=g)if("object"!=typeof g&&(g=[g]),isArray$2(g))for(var S=0,v=g.length;S<v;S++)f.call(null,g[S],S,g);else for(var C in g)Object.prototype.hasOwnProperty.call(g,C)&&f.call(null,g[C],C,g)}function merge(){var g={};function assignValue(f,S){isPlainObject$1(g[S])&&isPlainObject$1(f)?g[S]=merge(g[S],f):isPlainObject$1(f)?g[S]=merge({},f):isArray$2(f)?g[S]=f.slice():g[S]=f}for(var f=0,S=arguments.length;f<S;f++)forEach(arguments[f],assignValue);return g}function extend$1(g,f,S){return forEach(f,(function assignValue(f,v){g[v]=S&&"function"==typeof f?ST(f,S):f})),g}function stripBOM(g){return 65279===g.charCodeAt(0)&&(g=g.slice(1)),g}function inherits(g,f,S,v){g.prototype=Object.create(f.prototype,v),g.prototype.constructor=g,S&&Object.assign(g.prototype,S)}function toFlatObject(g,f,S,v){var C,_,T,I={};if(f=f||{},null==g)return f;do{for(_=(C=Object.getOwnPropertyNames(g)).length;_-- >0;)T=C[_],v&&!v(T,g,f)||I[T]||(f[T]=g[T],I[T]=!0);g=!1!==S&&Object.getPrototypeOf(g)}while(g&&(!S||S(g,f))&&g!==Object.prototype);return f}function endsWith(g,f,S){g=String(g),(void 0===S||S>g.length)&&(S=g.length),S-=f.length;var v=g.indexOf(f,S);return-1!==v&&v===S}function toArray(g){if(!g)return null;if(isArray$2(g))return g;var f=g.length;if(!isNumber$1(f))return null;for(var S=new Array(f);f-- >0;)S[f]=g[f];return S}var AT,PT=(AT="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(g){return AT&&g instanceof AT});function forEachEntry(g,f){for(var S,v=(g&&g[Symbol.iterator]).call(g);(S=v.next())&&!S.done;){var C=S.value;f.call(g,C[0],C[1])}}function matchAll(g,f){for(var S,v=[];null!==(S=g.exec(f));)v.push(S);return v}var RT=kindOfTest("HTMLFormElement"),MT=function resolver(g){return function(f,S){return g.call(f,S)}}(Object.prototype.hasOwnProperty),wT={isArray:isArray$2,isArrayBuffer:yT,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString$1,isNumber:isNumber$1,isObject:isObject$1,isPlainObject:isPlainObject$1,isEmptyObject:isEmptyObject,isUndefined:isUndefined$1,isDate:ET,isFile:_T,isBlob:TT,isFunction:isFunction$1,isStream:isStream,isURLSearchParams:bT,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,extend:extend$1,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:CT,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,isTypedArray:PT,isFileList:IT,forEachEntry:forEachEntry,matchAll:matchAll,isHTMLForm:RT,hasOwnProperty:MT};function AxiosError(g,f,S,v,C){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=g,this.name="AxiosError",f&&(this.code=f),S&&(this.config=S),v&&(this.request=v),C&&(this.response=C)}wT.inherits(AxiosError,Error,{toJSON:function toJSON(){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:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var OT=AxiosError.prototype,DT={};["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((function(g){DT[g]={value:g}})),Object.defineProperties(AxiosError,DT),Object.defineProperty(OT,"isAxiosError",{value:!0}),AxiosError.from=function(g,f,S,v,C,_){var T=Object.create(OT);return wT.toFlatObject(g,T,(function filter(g){return g!==Error.prototype})),AxiosError.call(T,g.message,f,S,v,C),T.cause=g,T.name=g.name,_&&Object.assign(T,_),T};var NT=AxiosError,kT="object"==typeof self?self.FormData:window.FormData;function isVisitable(g){return wT.isPlainObject(g)||wT.isArray(g)}function removeBrackets(g){return wT.endsWith(g,"[]")?g.slice(0,-2):g}function renderKey(g,f,S){return g?g.concat(f).map((function each(g,f){return g=removeBrackets(g),!S&&f?"["+g+"]":g})).join(S?".":""):f}function isFlatArray(g){return wT.isArray(g)&&!g.some(isVisitable)}var LT=wT.toFlatObject(wT,{},null,(function filter(g){return/^is[A-Z]/.test(g)}));function isSpecCompliant(g){return g&&wT.isFunction(g.append)&&"FormData"===g[Symbol.toStringTag]&&g[Symbol.iterator]}function toFormData(g,f,S){if(!wT.isObject(g))throw new TypeError("target must be an object");f=f||new(kT||FormData);var v=(S=wT.toFlatObject(S,{metaTokens:!0,dots:!1,indexes:!1},!1,(function defined(g,f){return!wT.isUndefined(f[g])}))).metaTokens,C=S.visitor||defaultVisitor,_=S.dots,T=S.indexes,I=(S.Blob||"undefined"!=typeof Blob&&Blob)&&isSpecCompliant(f);if(!wT.isFunction(C))throw new TypeError("visitor must be a function");function convertValue(g){if(null===g)return"";if(wT.isDate(g))return g.toISOString();if(!I&&wT.isBlob(g))throw new NT("Blob is not supported. Use a Buffer instead.");return wT.isArrayBuffer(g)||wT.isTypedArray(g)?I&&"function"==typeof Blob?new Blob([g]):Buffer.from(g):g}function defaultVisitor(g,S,C){var I=g;if(g&&!C&&"object"==typeof g)if(wT.endsWith(S,"{}"))S=v?S:S.slice(0,-2),g=JSON.stringify(g);else if(wT.isArray(g)&&isFlatArray(g)||wT.isFileList(g)||wT.endsWith(S,"[]")&&(I=wT.toArray(g)))return S=removeBrackets(S),I.forEach((function each(g,v){!wT.isUndefined(g)&&f.append(!0===T?renderKey([S],v,_):null===T?S:S+"[]",convertValue(g))})),!1;return!!isVisitable(g)||(f.append(renderKey(C,S,_),convertValue(g)),!1)}var b=[],A=Object.assign(LT,{defaultVisitor:defaultVisitor,convertValue:convertValue,isVisitable:isVisitable});function build(g,S){if(!wT.isUndefined(g)){if(-1!==b.indexOf(g))throw Error("Circular reference detected in "+S.join("."));b.push(g),wT.forEach(g,(function each(g,v){!0===(!wT.isUndefined(g)&&C.call(f,g,wT.isString(v)?v.trim():v,S,A))&&build(g,S?S.concat(v):[v])})),b.pop()}}if(!wT.isObject(g))throw new TypeError("data must be an object");return build(g),f}var FT=toFormData;function encode(g){var f={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(g).replace(/[!'\(\)~]|%20|%00/g,(function replacer(g){return f[g]}))}function AxiosURLSearchParams(g,f){this._pairs=[],g&&FT(g,this,f)}var xT=AxiosURLSearchParams.prototype;xT.append=function append(g,f){this._pairs.push([g,f])},xT.toString=function toString(g){var f=g?function(f){return g.call(this,f,encode)}:encode;return this._pairs.map((function each(g){return f(g[0])+"="+f(g[1])}),"").join("&")};var UT=AxiosURLSearchParams;function encode$1(g){return encodeURIComponent(g).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var VT=function buildURL(g,f,S){if(!f)return g;var v=g.indexOf("#");-1!==v&&(g=g.slice(0,v));var C,_=S&&S.encode||encode$1,T=S&&S.serialize;return(C=T?T(f,S):wT.isURLSearchParams(f)?f.toString():new UT(f,S).toString(_))&&(g+=(-1===g.indexOf("?")?"?":"&")+C),g};function InterceptorManager(){this.handlers=[]}InterceptorManager.prototype.use=function use(g,f,S){return this.handlers.push({fulfilled:g,rejected:f,synchronous:!!S&&S.synchronous,runWhen:S?S.runWhen:null}),this.handlers.length-1},InterceptorManager.prototype.eject=function eject(g){this.handlers[g]&&(this.handlers[g]=null)},InterceptorManager.prototype.clear=function clear(){this.handlers&&(this.handlers=[])},InterceptorManager.prototype.forEach=function forEach(g){wT.forEach(this.handlers,(function forEachHandler(f){null!==f&&g(f)}))};var BT=InterceptorManager,HT=function normalizeHeaderName(g,f){wT.forEach(g,(function processHeader(S,v){v!==f&&v.toUpperCase()===f.toUpperCase()&&(g[f]=S,delete g[v])}))},$T={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},jT={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:UT,FormData:FormData,Blob:Blob},protocols:["http","https","file","blob","url","data"]},GT=function toURLEncodedForm(g,f){return FT(g,new jT.classes.URLSearchParams,Object.assign({visitor:function(g,f,S,v){return v.defaultVisitor.apply(this,arguments)}},f))};function parsePropPath(g){return wT.matchAll(/\w+|\[(\w*)]/g,g).map((function(g){return"[]"===g[0]?"":g[1]||g[0]}))}function arrayToObject(g){var f,S,v={},C=Object.keys(g),_=C.length;for(f=0;f<_;f++)v[S=C[f]]=g[S];return v}function formDataToJSON(g){function buildPath(g,f,S,v){var C=g[v++],_=Number.isFinite(+C),T=v>=g.length;return C=!C&&wT.isArray(S)?S.length:C,T?(wT.hasOwnProperty(S,C)?S[C]=[S[C],f]:S[C]=f,!_):(S[C]&&wT.isObject(S[C])||(S[C]=[]),buildPath(g,f,S[C],v)&&wT.isArray(S[C])&&(S[C]=arrayToObject(S[C])),!_)}if(wT.isFormData(g)&&wT.isFunction(g.entries)){var f={};return wT.forEachEntry(g,(function(g,S){buildPath(parsePropPath(g),S,f,0)})),f}return null}var qT=formDataToJSON,WT=function settle(g,f,S){var v=S.config.validateStatus;S.status&&v&&!v(S.status)?f(new NT("Request failed with status code "+S.status,[NT.ERR_BAD_REQUEST,NT.ERR_BAD_RESPONSE][Math.floor(S.status/100)-4],S.config,S.request,S)):g(S)},zT=wT.isStandardBrowserEnv()?function standardBrowserEnv(){return{write:function write(g,f,S,v,C,_){var T=[];T.push(g+"="+encodeURIComponent(f)),wT.isNumber(S)&&T.push("expires="+new Date(S).toGMTString()),wT.isString(v)&&T.push("path="+v),wT.isString(C)&&T.push("domain="+C),!0===_&&T.push("secure"),document.cookie=T.join("; ")},read:function read(g){var f=document.cookie.match(new RegExp("(^|;\\s*)("+g+")=([^;]*)"));return f?decodeURIComponent(f[3]):null},remove:function remove(g){this.write(g,"",Date.now()-864e5)}}}():{write:function write(){},read:function read(){return null},remove:function remove(){}},KT=function isAbsoluteURL(g){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(g)},JT=function combineURLs(g,f){return f?g.replace(/\/+$/,"")+"/"+f.replace(/^\/+/,""):g},YT=function buildFullPath(g,f){return g&&!KT(f)?JT(g,f):f},QT=["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"],XT=function parseHeaders(g){var f,S,v,C={};return g?(wT.forEach(g.split("\n"),(function parser(g){if(v=g.indexOf(":"),f=wT.trim(g.slice(0,v)).toLowerCase(),S=wT.trim(g.slice(v+1)),f){if(C[f]&&QT.indexOf(f)>=0)return;C[f]="set-cookie"===f?(C[f]?C[f]:[]).concat([S]):C[f]?C[f]+", "+S:S}})),C):C},ZT=wT.isStandardBrowserEnv()?function standardBrowserEnv(){var g,f=/(msie|trident)/i.test(navigator.userAgent),S=document.createElement("a");function resolveURL(g){var v=g;return f&&(S.setAttribute("href",v),v=S.href),S.setAttribute("href",v),{href:S.href,protocol:S.protocol?S.protocol.replace(/:$/,""):"",host:S.host,search:S.search?S.search.replace(/^\?/,""):"",hash:S.hash?S.hash.replace(/^#/,""):"",hostname:S.hostname,port:S.port,pathname:"/"===S.pathname.charAt(0)?S.pathname:"/"+S.pathname}}return g=resolveURL(window.location.href),function isURLSameOrigin(f){var S=wT.isString(f)?resolveURL(f):f;return S.protocol===g.protocol&&S.host===g.host}}():function isURLSameOrigin(){return!0};function CanceledError(g,f,S){NT.call(this,null==g?"canceled":g,NT.ERR_CANCELED,f,S),this.name="CanceledError"}wT.inherits(CanceledError,NT,{__CANCEL__:!0});var eI=CanceledError,tI=function parseProtocol(g){var f=/^([-+\w]{1,25})(:?\/\/|:)/.exec(g);return f&&f[1]||""},iI=function xhrAdapter(g){return new Promise((function dispatchXhrRequest(f,S){var v,C=g.data,_=g.headers,T=g.responseType,I=g.withXSRFToken;function done(){g.cancelToken&&g.cancelToken.unsubscribe(v),g.signal&&g.signal.removeEventListener("abort",v)}wT.isFormData(C)&&wT.isStandardBrowserEnv()&&delete _["Content-Type"];var b=new XMLHttpRequest;if(g.auth){var A=g.auth.username||"",P=g.auth.password?unescape(encodeURIComponent(g.auth.password)):"";_.Authorization="Basic "+btoa(A+":"+P)}var R=YT(g.baseURL,g.url);function onloadend(){if(b){var v="getAllResponseHeaders"in b?XT(b.getAllResponseHeaders()):null,C={data:T&&"text"!==T&&"json"!==T?b.response:b.responseText,status:b.status,statusText:b.statusText,headers:v,config:g,request:b};WT((function _resolve(g){f(g),done()}),(function _reject(g){S(g),done()}),C),b=null}}if(b.open(g.method.toUpperCase(),VT(R,g.params,g.paramsSerializer),!0),b.timeout=g.timeout,"onloadend"in b?b.onloadend=onloadend:b.onreadystatechange=function handleLoad(){b&&4===b.readyState&&(0!==b.status||b.responseURL&&0===b.responseURL.indexOf("file:"))&&setTimeout(onloadend)},b.onabort=function handleAbort(){b&&(S(new NT("Request aborted",NT.ECONNABORTED,g,b)),b=null)},b.onerror=function handleError(){S(new NT("Network Error",NT.ERR_NETWORK,g,b)),b=null},b.ontimeout=function handleTimeout(){var f=g.timeout?"timeout of "+g.timeout+"ms exceeded":"timeout exceeded",v=g.transitional||$T;g.timeoutErrorMessage&&(f=g.timeoutErrorMessage),S(new NT(f,v.clarifyTimeoutError?NT.ETIMEDOUT:NT.ECONNABORTED,g,b)),b=null},wT.isStandardBrowserEnv()&&(I&&wT.isFunction(I)&&(I=I(g)),I||!1!==I&&ZT(R))){var M=g.xsrfHeaderName&&g.xsrfCookieName&&zT.read(g.xsrfCookieName);M&&(_[g.xsrfHeaderName]=M)}"setRequestHeader"in b&&wT.forEach(_,(function setRequestHeader(g,f){void 0===C&&"content-type"===f.toLowerCase()?delete _[f]:b.setRequestHeader(f,g)})),wT.isUndefined(g.withCredentials)||(b.withCredentials=!!g.withCredentials),T&&"json"!==T&&(b.responseType=g.responseType),"function"==typeof g.onDownloadProgress&&b.addEventListener("progress",g.onDownloadProgress),"function"==typeof g.onUploadProgress&&b.upload&&b.upload.addEventListener("progress",g.onUploadProgress),(g.cancelToken||g.signal)&&(v=function(f){b&&(S(!f||f.type?new eI(null,g,b):f),b.abort(),b=null)},g.cancelToken&&g.cancelToken.subscribe(v),g.signal&&(g.signal.aborted?v():g.signal.addEventListener("abort",v))),C||!1===C||0===C||""===C||(C=null);var w=tI(R);w&&-1===jT.protocols.indexOf(w)?S(new NT("Unsupported protocol "+w+":",NT.ERR_BAD_REQUEST,g)):b.send(C)}))},nI={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(g,f){!wT.isUndefined(g)&&wT.isUndefined(g["Content-Type"])&&(g["Content-Type"]=f)}function getDefaultAdapter(){var g;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(g=iI),g}function stringifySafely(g,f,S){if(wT.isString(g))try{return(f||JSON.parse)(g),wT.trim(g)}catch(g){if("SyntaxError"!==g.name)throw g}return(S||JSON.stringify)(g)}var rI={transitional:$T,adapter:getDefaultAdapter(),transformRequest:[function transformRequest(g,f){HT(f,"Accept"),HT(f,"Content-Type");var S,v=f&&f["Content-Type"]||"",C=v.indexOf("application/json")>-1,_=wT.isObject(g);if(_&&wT.isHTMLForm(g)&&(g=new FormData(g)),wT.isFormData(g))return C?JSON.stringify(qT(g)):g;if(wT.isArrayBuffer(g)||wT.isBuffer(g)||wT.isStream(g)||wT.isFile(g)||wT.isBlob(g))return g;if(wT.isArrayBufferView(g))return g.buffer;if(wT.isURLSearchParams(g))return setContentTypeIfUnset(f,"application/x-www-form-urlencoded;charset=utf-8"),g.toString();if(_){if(-1!==v.indexOf("application/x-www-form-urlencoded"))return GT(g,this.formSerializer).toString();if((S=wT.isFileList(g))||v.indexOf("multipart/form-data")>-1){var T=this.env&&this.env.FormData;return FT(S?{"files[]":g}:g,T&&new T,this.formSerializer)}}return _||C?(setContentTypeIfUnset(f,"application/json"),stringifySafely(g)):g}],transformResponse:[function transformResponse(g){var f=this.transitional||rI.transitional,S=f&&f.forcedJSONParsing,v="json"===this.responseType;if(g&&wT.isString(g)&&(S&&!this.responseType||v)){var C=!(f&&f.silentJSONParsing)&&v;try{return JSON.parse(g)}catch(g){if(C){if("SyntaxError"===g.name)throw NT.from(g,NT.ERR_BAD_RESPONSE,this,null,this.response);throw g}}}return g}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:jT.classes.FormData,Blob:jT.classes.Blob},validateStatus:function validateStatus(g){return g>=200&&g<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};wT.forEach(["delete","get","head"],(function forEachMethodNoData(g){rI.headers[g]={}})),wT.forEach(["post","put","patch"],(function forEachMethodWithData(g){rI.headers[g]=wT.merge(nI)}));var sI=rI,aI=function transformData(g,f,S,v){var C=this||sI;return wT.forEach(v,(function transform(v){g=v.call(C,g,f,S)})),g},oI=function isCancel(g){return!(!g||!g.__CANCEL__)};function throwIfCancellationRequested(g){if(g.cancelToken&&g.cancelToken.throwIfRequested(),g.signal&&g.signal.aborted)throw new eI}var lI=function dispatchRequest(g){return throwIfCancellationRequested(g),g.headers=g.headers||{},g.data=aI.call(g,g.data,g.headers,null,g.transformRequest),HT(g.headers,"Accept"),HT(g.headers,"Content-Type"),g.headers=wT.merge(g.headers.common||{},g.headers[g.method]||{},g.headers),wT.forEach(["delete","get","head","post","put","patch","common"],(function cleanHeaderConfig(f){delete g.headers[f]})),(g.adapter||sI.adapter)(g).then((function onAdapterResolution(f){return throwIfCancellationRequested(g),f.data=aI.call(g,f.data,f.headers,f.status,g.transformResponse),f}),(function onAdapterRejection(f){return oI(f)||(throwIfCancellationRequested(g),f&&f.response&&(f.response.data=aI.call(g,f.response.data,f.response.headers,f.response.status,g.transformResponse))),Promise.reject(f)}))},cI=function mergeConfig(g,f){f=f||{};var S={};function getMergedValue(g,f){return wT.isPlainObject(g)&&wT.isPlainObject(f)?wT.merge(g,f):wT.isEmptyObject(f)?wT.merge({},g):wT.isPlainObject(f)?wT.merge({},f):wT.isArray(f)?f.slice():f}function mergeDeepProperties(S){return wT.isUndefined(f[S])?wT.isUndefined(g[S])?void 0:getMergedValue(void 0,g[S]):getMergedValue(g[S],f[S])}function valueFromConfig2(g){if(!wT.isUndefined(f[g]))return getMergedValue(void 0,f[g])}function defaultToConfig2(S){return wT.isUndefined(f[S])?wT.isUndefined(g[S])?void 0:getMergedValue(void 0,g[S]):getMergedValue(void 0,f[S])}function mergeDirectKeys(S){return S in f?getMergedValue(g[S],f[S]):S in g?getMergedValue(void 0,g[S]):void 0}var v={url:valueFromConfig2,method:valueFromConfig2,data:valueFromConfig2,baseURL:defaultToConfig2,transformRequest:defaultToConfig2,transformResponse:defaultToConfig2,paramsSerializer:defaultToConfig2,timeout:defaultToConfig2,timeoutMessage:defaultToConfig2,withCredentials:defaultToConfig2,withXSRFToken:defaultToConfig2,adapter:defaultToConfig2,responseType:defaultToConfig2,xsrfCookieName:defaultToConfig2,xsrfHeaderName:defaultToConfig2,onUploadProgress:defaultToConfig2,onDownloadProgress:defaultToConfig2,decompress:defaultToConfig2,maxContentLength:defaultToConfig2,maxBodyLength:defaultToConfig2,beforeRedirect:defaultToConfig2,transport:defaultToConfig2,httpAgent:defaultToConfig2,httpsAgent:defaultToConfig2,cancelToken:defaultToConfig2,socketPath:defaultToConfig2,responseEncoding:defaultToConfig2,validateStatus:mergeDirectKeys};return wT.forEach(Object.keys(g).concat(Object.keys(f)),(function computeConfigValue(g){var f=v[g]||mergeDeepProperties,C=f(g);wT.isUndefined(C)&&f!==mergeDirectKeys||(S[g]=C)})),S},dI={version:"0.28.1"},hI=dI.version,uI={};["object","boolean","number","function","string","symbol"].forEach((function(g,f){uI[g]=function validator(S){return typeof S===g||"a"+(f<1?"n ":" ")+g}}));var gI={};function assertOptions(g,f,S){if("object"!=typeof g)throw new NT("options must be an object",NT.ERR_BAD_OPTION_VALUE);for(var v=Object.keys(g),C=v.length;C-- >0;){var _=v[C],T=f[_];if(T){var I=g[_],b=void 0===I||T(I,_,g);if(!0!==b)throw new NT("option "+_+" must be "+b,NT.ERR_BAD_OPTION_VALUE)}else if(!0!==S)throw new NT("Unknown option "+_,NT.ERR_BAD_OPTION)}}uI.transitional=function transitional(g,f,S){function formatMessage(g,f){return"[Axios v"+hI+"] Transitional option '"+g+"'"+f+(S?". "+S:"")}return function(S,v,C){if(!1===g)throw new NT(formatMessage(v," has been removed"+(f?" in "+f:"")),NT.ERR_DEPRECATED);return f&&!gI[v]&&(gI[v]=!0,console.warn(formatMessage(v," has been deprecated since v"+f+" and will be removed in the near future"))),!g||g(S,v,C)}};var pI={assertOptions:assertOptions,validators:uI},mI=pI.validators;function Axios(g){this.defaults=g,this.interceptors={request:new BT,response:new BT}}Axios.prototype.request=function request(g,f){"string"==typeof g?(f=f||{}).url=g:f=g||{},(f=cI(this.defaults,f)).method?f.method=f.method.toLowerCase():this.defaults.method?f.method=this.defaults.method.toLowerCase():f.method="get";var S=f.transitional;void 0!==S&&pI.assertOptions(S,{silentJSONParsing:mI.transitional(mI.boolean),forcedJSONParsing:mI.transitional(mI.boolean),clarifyTimeoutError:mI.transitional(mI.boolean)},!1);var v=f.paramsSerializer;void 0!==v&&pI.assertOptions(v,{encode:mI.function,serialize:mI.function},!0),wT.isFunction(v)&&(f.paramsSerializer={serialize:v});var C=[],_=!0;this.interceptors.request.forEach((function unshiftRequestInterceptors(g){"function"==typeof g.runWhen&&!1===g.runWhen(f)||(_=_&&g.synchronous,C.unshift(g.fulfilled,g.rejected))}));var T,I=[];if(this.interceptors.response.forEach((function pushResponseInterceptors(g){I.push(g.fulfilled,g.rejected)})),!_){var b=[lI,void 0];for(Array.prototype.unshift.apply(b,C),b=b.concat(I),T=Promise.resolve(f);b.length;)T=T.then(b.shift(),b.shift());return T}for(var A=f;C.length;){var P=C.shift(),R=C.shift();try{A=P(A)}catch(g){R(g);break}}try{T=lI(A)}catch(g){return Promise.reject(g)}for(;I.length;)T=T.then(I.shift(),I.shift());return T},Axios.prototype.getUri=function getUri(g){g=cI(this.defaults,g);var f=YT(g.baseURL,g.url);return VT(f,g.params,g.paramsSerializer)},wT.forEach(["delete","get","head","options"],(function forEachMethodNoData(g){Axios.prototype[g]=function(f,S){return this.request(cI(S||{},{method:g,url:f,data:(S||{}).data}))}})),wT.forEach(["post","put","patch"],(function forEachMethodWithData(g){function generateHTTPMethod(f){return function httpMethod(S,v,C){return this.request(cI(C||{},{method:g,headers:f?{"Content-Type":"multipart/form-data"}:{},url:S,data:v}))}}Axios.prototype[g]=generateHTTPMethod(),Axios.prototype[g+"Form"]=generateHTTPMethod(!0)}));var fI=Axios;function CancelToken(g){if("function"!=typeof g)throw new TypeError("executor must be a function.");var f;this.promise=new Promise((function promiseExecutor(g){f=g}));var S=this;this.promise.then((function(g){if(S._listeners){for(var f=S._listeners.length;f-- >0;)S._listeners[f](g);S._listeners=null}})),this.promise.then=function(g){var f,v=new Promise((function(g){S.subscribe(g),f=g})).then(g);return v.cancel=function reject(){S.unsubscribe(f)},v},g((function cancel(g,v,C){S.reason||(S.reason=new eI(g,v,C),f(S.reason))}))}CancelToken.prototype.throwIfRequested=function throwIfRequested(){if(this.reason)throw this.reason},CancelToken.prototype.subscribe=function subscribe(g){this.reason?g(this.reason):this._listeners?this._listeners.push(g):this._listeners=[g]},CancelToken.prototype.unsubscribe=function unsubscribe(g){if(this._listeners){var f=this._listeners.indexOf(g);-1!==f&&this._listeners.splice(f,1)}},CancelToken.source=function source(){var g;return{token:new CancelToken((function executor(f){g=f})),cancel:g}};var SI=CancelToken,vI=function spread(g){return function wrap(f){return g.apply(null,f)}},CI=function isAxiosError(g){return wT.isObject(g)&&!0===g.isAxiosError};function createInstance(g){var f=new fI(g),S=ST(fI.prototype.request,f);return wT.extend(S,fI.prototype,f),wT.extend(S,f),S.create=function create(f){return createInstance(cI(g,f))},S}var yI=createInstance(sI);yI.Axios=fI,yI.CanceledError=eI,yI.CancelToken=SI,yI.isCancel=oI,yI.VERSION=dI.version,yI.toFormData=FT,yI.AxiosError=NT,yI.Cancel=yI.CanceledError,yI.all=function all(g){return Promise.all(g)},yI.spread=vI,yI.isAxiosError=CI,yI.formToJSON=function(g){return qT(wT.isHTMLForm(g)?new FormData(g):g)};var EI=yI,_I=yI;EI.default=_I;for(var TI=EI,II=createCommonjsModule((function(g){var f="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(f){var S=new Uint8Array(16);g.exports=function whatwgRNG(){return f(S),S}}else{var v=new Array(16);g.exports=function mathRNG(){for(var g,f=0;f<16;f++)0==(3&f)&&(g=4294967296*Math.random()),v[f]=g>>>((3&f)<<3)&255;return v}}})),bI=[],AI=0;AI<256;++AI)bI[AI]=(AI+256).toString(16).substr(1);function bytesToUuid(g,f){var S=f||0,v=bI;return[v[g[S++]],v[g[S++]],v[g[S++]],v[g[S++]],"-",v[g[S++]],v[g[S++]],"-",v[g[S++]],v[g[S++]],"-",v[g[S++]],v[g[S++]],"-",v[g[S++]],v[g[S++]],v[g[S++]],v[g[S++]],v[g[S++]],v[g[S++]]].join("")}var PI,RI,MI=bytesToUuid,wI=0,OI=0;function v1(g,f,S){var v=f&&S||0,C=f||[],_=(g=g||{}).node||PI,T=void 0!==g.clockseq?g.clockseq:RI;if(null==_||null==T){var I=II();null==_&&(_=PI=[1|I[0],I[1],I[2],I[3],I[4],I[5]]),null==T&&(T=RI=16383&(I[6]<<8|I[7]))}var b=void 0!==g.msecs?g.msecs:(new Date).getTime(),A=void 0!==g.nsecs?g.nsecs:OI+1,P=b-wI+(A-OI)/1e4;if(P<0&&void 0===g.clockseq&&(T=T+1&16383),(P<0||b>wI)&&void 0===g.nsecs&&(A=0),A>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");wI=b,OI=A,RI=T;var R=(1e4*(268435455&(b+=122192928e5))+A)%4294967296;C[v++]=R>>>24&255,C[v++]=R>>>16&255,C[v++]=R>>>8&255,C[v++]=255&R;var M=b/4294967296*1e4&268435455;C[v++]=M>>>8&255,C[v++]=255&M,C[v++]=M>>>24&15|16,C[v++]=M>>>16&255,C[v++]=T>>>8|128,C[v++]=255&T;for(var w=0;w<6;++w)C[v+w]=_[w];return f||MI(C)}var DI=v1;function v4(g,f,S){var v=f&&S||0;"string"==typeof g&&(f="binary"===g?new Array(16):null,g=null);var C=(g=g||{}).random||(g.rng||II)();if(C[6]=15&C[6]|64,C[8]=63&C[8]|128,f)for(var _=0;_<16;++_)f[v+_]=C[_];return f||MI(C)}var NI=v4,kI=NI;kI.v1=DI,kI.v4=NI;var LI=kI,FI=createCommonjsModule((function(g,f){var S=C&&C.__assign||function(){return S=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},S.apply(this,arguments)};function errorToString(g,f){if(void 0===f&&(f=!0),null==g)return"";if("string"==typeof g)return g;try{return JSON.stringify(g,circularReplacer(buildErrorJsonReplacer(f)))}catch(g){return"Stringifying error failed"}}Object.defineProperty(f,"__esModule",{value:!0}),f.errorToString=void 0,f.errorToString=errorToString;var buildErrorJsonReplacer=function(g){return void 0===g&&(g=!1),function(f,v){return v instanceof Error?S({name:v.name,message:v.message,stack:g?[]:("string"==typeof v.stack?v.stack:"").split("\n").map((function(g){return g.trim()})).filter((function(g){return!!g}))},v):v}},circularReplacer=function(g){var f=new WeakSet;return function(S,v){if("object"==typeof v&&null!==v){if(f.has(v))return;f.add(v)}return g(S,v)}}})),xI=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.EvictingQueue=void 0;var S=function(){function EvictingQueue(g){this.maxSize=g,this._store=[]}return Object.defineProperty(EvictingQueue.prototype,"store",{get:function(){return this._store},enumerable:!1,configurable:!0}),Object.defineProperty(EvictingQueue.prototype,"size",{get:function(){return this._store.length},enumerable:!1,configurable:!0}),EvictingQueue.prototype.enqueue=function(g){this._store.length>=this.maxSize&&this._store.shift(),this._store.push(g)},EvictingQueue.prototype.dequeue=function(){return this._store.shift()},EvictingQueue.prototype.clear=function(){this._store=[]},EvictingQueue.prototype.forEach=function(g){this._store.forEach(g)},EvictingQueue}();f.EvictingQueue=S})),UI=createCommonjsModule((function(g,f){var S=C&&C.__awaiter||function(g,f,S,v){function adopt(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function fulfilled(g){try{step(v.next(g))}catch(g){C(g)}}function rejected(g){try{step(v.throw(g))}catch(g){C(g)}}function step(g){g.done?S(g.value):adopt(g.value).then(fulfilled,rejected)}step((v=v.apply(g,f||[])).next())}))},v=C&&C.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function verb(g){return function(f){return step([g,f])}}function step(_){if(S)throw new TypeError("Generator is already executing.");for(;T;)try{if(S=1,v&&(C=2&_[0]?v.return:_[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,_[1])).done)return C;switch(v=0,C&&(_=[2&_[0],C.value]),_[0]){case 0:case 1:C=_;break;case 4:return T.label++,{value:_[1],done:!1};case 5:T.label++,v=_[1],_=[0];continue;case 7:_=T.ops.pop(),T.trys.pop();continue;default:if(!(C=T.trys,(C=C.length>0&&C[C.length-1])||6!==_[0]&&2!==_[0])){T=0;continue}if(3===_[0]&&(!C||_[1]>C[0]&&_[1]<C[3])){T.label=_[1];break}if(6===_[0]&&T.label<C[1]){T.label=C[1],C=_;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(_);break}C[2]&&T.ops.pop(),T.trys.pop();continue}_=f.call(g,T)}catch(g){_=[6,g],v=0}finally{S=C=0}if(5&_[0])throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}};Object.defineProperty(f,"__esModule",{value:!0}),f.SimpleSyncCell=void 0;var _=function(){function SimpleSyncCell(g,f,S,v,C){this.m_id=g,this.m_sender=f,this.m_shouldEmitEventForAllMessages=S,this.aggregation=C,this.m_events=new LE.EventEmitter,this.m_emitUnacknowledgedEventFor=null!=v?v:fT.MessageTrackingOption.None}return SimpleSyncCell.prototype.on=function(g,f){return this.m_events.on(g,f),this},SimpleSyncCell.prototype.off=function(g,f){return this.m_events.off(g,f),this},SimpleSyncCell.prototype.removeAllListeners=function(g){return this.m_events.removeAllListeners(g),this},SimpleSyncCell.prototype.id=function(){return this.m_id},SimpleSyncCell.prototype.messageTrackingOption=function(){return this.m_emitUnacknowledgedEventFor},SimpleSyncCell.prototype.getAsync=function(){return S(this,void 0,void 0,(function(){return v(this,(function(g){return[2,this.m_value]}))}))},SimpleSyncCell.prototype.setAsync=function(g){return S(this,void 0,void 0,(function(){var f;return v(this,(function(S){return this.m_value=g,f={messageId:LI.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"cell",operation:"set",value:JSON.stringify(this.m_value)},this.m_sender.sendStateMessage(f),[2]}))}))},SimpleSyncCell.prototype.delete=function(){this.m_value=void 0;var g={messageId:LI.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"cell",operation:"delete",value:""};this.m_sender.sendStateMessage(g)},SimpleSyncCell.prototype.handleStateMessage=function(g){switch(g.operation){case"set":return void((JSON.stringify(this.m_value)!==g.value||this.m_shouldEmitEventForAllMessages)&&(this.m_value=JSON.parse(g.value),this.m_events.emit("valueChanged",this.m_value,g)));case"delete":return this.m_value=void 0,void this.m_events.emit("valueDeleted",this.m_value,g);default:return}},SimpleSyncCell.prototype.handleUnacknowledgedMessage=function(g){this.m_events.emit("valueUnacknowledged",g)},SimpleSyncCell.prototype.beginAggregatedStateUpdating=function(){var g;null===(g=this.aggregation)||void 0===g||g.beginAggregatedStateUpdating()},SimpleSyncCell.prototype.endAggregatedStateUpdating=function(){var g;null===(g=this.aggregation)||void 0===g||g.endAggregatedStateUpdating()},SimpleSyncCell}();f.SimpleSyncCell=_})),VI=createCommonjsModule((function(g,f){function isPrefixDeleteMessage(g){return"delete"===g.operation&&"prefix"===g.value}Object.defineProperty(f,"__esModule",{value:!0}),f.isPrefixDeleteMessage=void 0,f.isPrefixDeleteMessage=isPrefixDeleteMessage})),BI=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.SimpleSyncMap=void 0;var S=function(){function SimpleSyncMap(g,f,S,v,C){this.m_id=g,this.m_sender=f,this.m_shouldEmitEventForAllMessages=S,this.aggregation=C,this.m_events=new LE.EventEmitter,this.m_map=new Map,this.m_emitUnacknowledgedEventFor=null!=v?v:fT.MessageTrackingOption.None}return SimpleSyncMap.prototype.on=function(g,f){return this.m_events.on(g,f),this},SimpleSyncMap.prototype.off=function(g,f){return this.m_events.off(g,f),this},SimpleSyncMap.prototype.removeAllListeners=function(g){return this.m_events.removeAllListeners(g),this},SimpleSyncMap.prototype.id=function(){return this.m_id},SimpleSyncMap.prototype.messageTrackingOption=function(){return this.m_emitUnacknowledgedEventFor},SimpleSyncMap.prototype.get=function(g){return this.m_map.get(g)},SimpleSyncMap.prototype.set=function(g,f){this.m_map.set(g,f);var S={messageId:LI.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"map",operation:"set",property:g,value:JSON.stringify(f)};this.m_sender.sendStateMessage(S)},SimpleSyncMap.prototype.delete=function(g){var f={messageId:LI.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"map",operation:"delete",property:g,value:""};this.performLocalDelete(f),this.m_sender.sendStateMessage(f)},SimpleSyncMap.prototype.deleteWithPrefix=function(g){var f={messageId:LI.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"map",operation:"delete",property:g,value:"prefix"};this.performLocalDelete(f),this.m_sender.sendStateMessage(f)},SimpleSyncMap.prototype.forEach=function(g){this.m_map.forEach(g)},SimpleSyncMap.prototype.handleStateMessage=function(g){switch(g.operation){case"set":return void this.handleSet(g);case"delete":return void this.handleDelete(g);default:return}},SimpleSyncMap.prototype.handleSet=function(g){if(!g.property)throw new Error("property is missing for a map.");(JSON.stringify(this.m_map.get(g.property))!==g.value||this.m_shouldEmitEventForAllMessages)&&(this.m_map.set(g.property,JSON.parse(g.value)),this.m_events.emit("valueChanged",g.property,g))},SimpleSyncMap.prototype.handleDelete=function(g){this.performLocalDelete(g),VI.isPrefixDeleteMessage(g)?this.m_events.emit("valuesDeletedWithPrefix",g.property,g):this.m_events.emit("valueDeleted",g.property||"",g)},SimpleSyncMap.prototype.handleUnacknowledgedMessage=function(g){this.m_events.emit("valueUnacknowledged",g)},SimpleSyncMap.prototype.beginAggregatedStateUpdating=function(){var g;null===(g=this.aggregation)||void 0===g||g.beginAggregatedStateUpdating()},SimpleSyncMap.prototype.endAggregatedStateUpdating=function(){var g;null===(g=this.aggregation)||void 0===g||g.endAggregatedStateUpdating()},SimpleSyncMap.prototype.performLocalDelete=function(g){var f=this;if(g.property){var S=g.property;VI.isPrefixDeleteMessage(g)?this.m_map.forEach((function(g,v){v.startsWith(S)&&f.m_map.delete(v)})):this.m_map.delete(g.property)}else this.m_map.clear()},SimpleSyncMap}();f.SimpleSyncMap=S})),HI=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.SimpleServicePerformanceTelemetry=f.SimpleServiceTelemetry=void 0;var S=function(){function SimpleServiceTelemetry(g,f,S){this.backendService="SimpleService",this.clientId=g,this.sessionId=f,this.wsReconnectCount=0,this.wsState=fT.ConnectionState[fT.ConnectionState.Disconnected],this.maxRoundtripRaw=S||0,this.roundtripTelemetry=new v,this.messageHandleTelemetry=new v,this.offlineCacheTelemetry={cachedCount:0,resentCount:0,expiredCount:0,rejectedCount:0},this.maxRoundtripRaw>0&&(this.roundtripRaw=[]),this.messagePendingAckCount=0,this.unacknowledgedMessagesCount=0,this.messageRequested={},this.messageReceived={},this.messageAcknowledged={}}return SimpleServiceTelemetry.prototype.addRoundtripLatency=function(g){this.roundtripRaw&&this.roundtripRaw.length<this.maxRoundtripRaw&&this.roundtripRaw.push(g),this.roundtripTelemetry.addLatency(g)},SimpleServiceTelemetry.prototype.addMessageHandleLatency=function(g){this.messageHandleTelemetry.addLatency(g)},SimpleServiceTelemetry.prototype.incrementAcknowledgedCount=function(g){this.incrementMessageCount(this.messageAcknowledged,g)},SimpleServiceTelemetry.prototype.incrementRequestedCount=function(g){this.incrementMessageCount(this.messageRequested,g)},SimpleServiceTelemetry.prototype.incrementReceivedCount=function(g){this.incrementMessageCount(this.messageReceived,g)},SimpleServiceTelemetry.prototype.incrementMessageCount=function(g,f){var S=g[f],v=void 0===S?1:S+1;g[f]=v},SimpleServiceTelemetry}();f.SimpleServiceTelemetry=S;var v=function(){function SimpleServicePerformanceTelemetry(){this.count=0,this.minValue=0,this.maxValue=0,this.avgValue=0}return SimpleServicePerformanceTelemetry.prototype.addLatency=function(g){this.count+=1,this.avgValue=this.avgValue+(g-this.avgValue)/this.count,this.minValue=this.count>1?Math.min(g,this.minValue):g,this.maxValue=Math.max(this.maxValue,g)},SimpleServicePerformanceTelemetry}();f.SimpleServicePerformanceTelemetry=v})),$I=createCommonjsModule((function(g,f){var S=C&&C.__awaiter||function(g,f,S,v){function adopt(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function fulfilled(g){try{step(v.next(g))}catch(g){C(g)}}function rejected(g){try{step(v.throw(g))}catch(g){C(g)}}function step(g){g.done?S(g.value):adopt(g.value).then(fulfilled,rejected)}step((v=v.apply(g,f||[])).next())}))},v=C&&C.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function verb(g){return function(f){return step([g,f])}}function step(_){if(S)throw new TypeError("Generator is already executing.");for(;T;)try{if(S=1,v&&(C=2&_[0]?v.return:_[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,_[1])).done)return C;switch(v=0,C&&(_=[2&_[0],C.value]),_[0]){case 0:case 1:C=_;break;case 4:return T.label++,{value:_[1],done:!1};case 5:T.label++,v=_[1],_=[0];continue;case 7:_=T.ops.pop(),T.trys.pop();continue;default:if(!(C=T.trys,(C=C.length>0&&C[C.length-1])||6!==_[0]&&2!==_[0])){T=0;continue}if(3===_[0]&&(!C||_[1]>C[0]&&_[1]<C[3])){T.label=_[1];break}if(6===_[0]&&T.label<C[1]){T.label=C[1],C=_;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(_);break}C[2]&&T.ops.pop(),T.trys.pop();continue}_=f.call(g,T)}catch(g){_=[6,g],v=0}finally{S=C=0}if(5&_[0])throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}};Object.defineProperty(f,"__esModule",{value:!0}),f.StateServiceWebSocketConnection=void 0;var _=function(){function StateServiceWebSocketConnection(g,f){var C=this;this.onopen=null,this.onclose=null,this.onerror=null,this.onmessage=null,this.onlog=null,this.ws=new WebSocket(g),this.settings=f,this.ws.onopen=function(g){return S(C,void 0,void 0,(function(){return v(this,(function(f){switch(f.label){case 0:return this.onopen&&this.onopen(g),[4,this.sendSetupMessages()];case 1:return f.sent(),[2]}}))}))},this.ws.onclose=function(g){C.onclose&&C.onclose(g)},this.ws.onerror=function(g){C.onerror&&C.onerror(g)},this.ws.onmessage=function(g){C.onmessage&&C.onmessage(g)}}return StateServiceWebSocketConnection.CreateAsync=function(g,f){return S(this,void 0,void 0,(function(){return v(this,(function(S){return[2,new StateServiceWebSocketConnection(g,f)]}))}))},Object.defineProperty(StateServiceWebSocketConnection.prototype,"name",{get:function(){return"WebSocket"},enumerable:!1,configurable:!0}),Object.defineProperty(StateServiceWebSocketConnection.prototype,"readyState",{get:function(){return this.ws.readyState},enumerable:!1,configurable:!0}),Object.defineProperty(StateServiceWebSocketConnection.prototype,"isOpen",{get:function(){return this.ws.readyState===WebSocket.OPEN},enumerable:!1,configurable:!0}),Object.defineProperty(StateServiceWebSocketConnection.prototype,"shouldSendPings",{get:function(){return!0},enumerable:!1,configurable:!0}),StateServiceWebSocketConnection.prototype.close=function(){this.ws.close()},StateServiceWebSocketConnection.prototype.send=function(g){this.ws.send(g)},StateServiceWebSocketConnection.prototype.sendSetupMessages=function(){return S(this,void 0,void 0,(function(){var g,f,S,C,_,T,I=this;return v(this,(function(v){switch(v.label){case 0:return(f=this.settings.getAuthTokenAsync)?[4,this.settings.getAuthTokenAsync()]:[3,2];case 1:f=v.sent(),v.label=2;case 2:return g=f,S=this.settings,C=S.metadata,_=S.subscriptions,T={authToken:g,metadata:C,subscriptions:_},this.settings.createSetupMessage(T).forEach((function(g){return I.send(g)})),[2]}}))}))},StateServiceWebSocketConnection}();f.StateServiceWebSocketConnection=_})),jI=createCommonjsModule((function(g,f){var S=C&&C.__awaiter||function(g,f,S,v){function adopt(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function fulfilled(g){try{step(v.next(g))}catch(g){C(g)}}function rejected(g){try{step(v.throw(g))}catch(g){C(g)}}function step(g){g.done?S(g.value):adopt(g.value).then(fulfilled,rejected)}step((v=v.apply(g,f||[])).next())}))},v=C&&C.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function verb(g){return function(f){return step([g,f])}}function step(_){if(S)throw new TypeError("Generator is already executing.");for(;T;)try{if(S=1,v&&(C=2&_[0]?v.return:_[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,_[1])).done)return C;switch(v=0,C&&(_=[2&_[0],C.value]),_[0]){case 0:case 1:C=_;break;case 4:return T.label++,{value:_[1],done:!1};case 5:T.label++,v=_[1],_=[0];continue;case 7:_=T.ops.pop(),T.trys.pop();continue;default:if(!(C=T.trys,(C=C.length>0&&C[C.length-1])||6!==_[0]&&2!==_[0])){T=0;continue}if(3===_[0]&&(!C||_[1]>C[0]&&_[1]<C[3])){T.label=_[1];break}if(6===_[0]&&T.label<C[1]){T.label=C[1],C=_;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(_);break}C[2]&&T.ops.pop(),T.trys.pop();continue}_=f.call(g,T)}catch(g){_=[6,g],v=0}finally{S=C=0}if(5&_[0])throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}},_=C&&C.__values||function(g){var f="function"==typeof Symbol&&Symbol.iterator,S=f&&g[f],v=0;if(S)return S.call(g);if(g&&"number"==typeof g.length)return{next:function(){return g&&v>=g.length&&(g=void 0),{value:g&&g[v++],done:!g}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")},T=C&&C.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(f,"__esModule",{value:!0}),f.SimpleStateServiceProxy=void 0;var I=T(TI),b=[2e3,2e3,3e3,3e3,5e3],A=4321,P=function(){function SimpleStateServiceProxy(g,f,S,v,C,_){var T;this.m_events=new LE.EventEmitter,this.m_clientId="",this.m_connectionState=fT.ConnectionState.Disconnected,this.m_handlers=new Map,this.m_connection=null,this.m_clientIds=new Set,this.m_initTimeoutDurationInMS=0,this.m_retryAttempts=0,this.m_sessionRetryAttempts=0,this.m_maxSessionRetries=0,this.m_outboundMessageInfo=new Map,this.m_initPromise={promise:null,resolve:null,reject:null},this.m_messageBuffer=[],this.m_batchWaitTimeMS=20,this.m_batchMessageTypeName="list",this.m_closeConnectionTimer=null,this.m_lastCloseCode=0,this.m_lastCloseReason="",this.m_offlineMessageCache=[],this.m_unacknowledgedMessages=new Map,this.m_sessionId=g,this.m_logger=v,this.m_connectionAliveTimeAfterLoseFocusInMS=C.websocketAliveTimeAfterLoseFocusInMS,this.m_useServiceGeneratedClientId=C.useServiceGeneratedClientId||!1,this.m_wsUrl=S+"?docId="+this.m_sessionId+"&clientType="+f,C.correlationId&&(this.m_wsUrl+="&cid="+C.correlationId),C.isAutomation&&(this.m_wsUrl+="&automation=true"),C.autoRoutingEnabled&&(this.m_wsUrl+="&routing=true"),this.m_useServiceGeneratedClientId||(this.m_clientId=C.customClientId||LI.v4(),this.m_wsUrl+="&clientId="+this.m_clientId),this.m_deltasBaseUrl=S.replace("wss://","https://").replace("ws://","http://"),this.setupSystemClientsCell(),this.setUpSystemCommandsCell(),this.setupServiceGeneratedClientIdCell(),this.m_useServiceGeneratedClientId&&(this.m_clientIdEvictingQueue=new xI.EvictingQueue(20)),this.m_telemetry=new HI.SimpleServiceTelemetry(this.m_clientId,this.m_sessionId,C.maxRoundtripRaw),this.m_verbose=C.verbose||!1,this.m_batchedRequestsEnabled=C.batchedRequestsEnabled,this.m_initTimeoutDurationInMS=C.initTimeoutDurationInMs||0,this.m_pingTimeoutInMs=C.pingTimeoutInMs,this.m_pongTimeoutInMs=C.pongTimeoutInMs,this.m_user=_,this.m_metadata=C.metadata,this.m_retryIntervalsInMs=C.retryIntervalsInMs||b,this.m_maxSessionRetries=C.maxSessionRetries,this.m_offlineMessageCacheEnabled=C.offlineMessageCacheEnabled,this.m_maxOfflineMessageCacheTimeInMs=C.maxOfflineMessageCacheTimeInMs,this.m_maxOfflineMessageCacheLength=C.maxOfflineMessageCacheLength,this.m_allowReconnectOnMessageSend=C.allowReconnectOnSendMessage||!1,this.m_unacknowledgedMaxTimeInMs=null!==(T=C.unacknowledgeMessageTimeoutInMs)&&void 0!==T?T:0,this.m_subscriptions=C.subscriptions,this.m_connectionSettings={getAuthTokenAsync:this.getAuthToken.bind(this),createSetupMessage:this.createSetupMessage.bind(this),metadata:this.m_metadata,subscriptions:this.m_subscriptions}}return Object.defineProperty(SimpleStateServiceProxy.prototype,"lastCloseReason",{get:function(){return this.m_lastCloseReason},enumerable:!1,configurable:!0}),SimpleStateServiceProxy.prototype.senderId=function(){return this.m_clientId},SimpleStateServiceProxy.prototype.countOfOutboundMessagesNotRoundTrippedYet=function(){return this.m_outboundMessageInfo.size},SimpleStateServiceProxy.prototype.canRetry=function(){return this.m_connectionState===fT.ConnectionState.Disconnected&&this.m_lastCloseCode!==A},SimpleStateServiceProxy.prototype.getServiceTelemetry=function(){return this.m_telemetry.wsState=fT.ConnectionState[this.getConnectionState()],this.m_telemetry.messagePendingAckCount=this.m_outboundMessageInfo.size,this.m_telemetry},SimpleStateServiceProxy.prototype.activeClientCount=function(){return this.m_clientIds.size},SimpleStateServiceProxy.prototype.activeClientIds=function(){return this.m_clientIds},SimpleStateServiceProxy.prototype.clientId=function(){return this.m_clientId},SimpleStateServiceProxy.prototype.getConnectionState=function(){return this.m_connectionState},SimpleStateServiceProxy.prototype.on=function(g,f){return this.m_events.on(g,f),this},SimpleStateServiceProxy.prototype.connectAsync=function(){return S(this,void 0,void 0,(function(){var g=this;return v(this,(function(f){return this.m_initPromise.promise=new Promise((function(f,S){g.m_initPromise.resolve=f,g.m_initPromise.reject=S})),this.setConnectionState(fT.ConnectionState.Connecting),[2,new Promise((function(f,C){return S(g,void 0,void 0,(function(){var g,S=this;return v(this,(function(v){switch(v.label){case 0:return g=this,[4,$I.StateServiceWebSocketConnection.CreateAsync(this.m_wsUrl,this.m_connectionSettings)];case 1:return g.m_connection=v.sent(),this.m_connection.onopen=function(){S.handleConnectionOpen(),S.startInitTimeoutTimerWithRetry(S.m_initTimeoutDurationInMS,S.m_initPromise.reject),f()},this.m_connection.onerror=function(g){var v;S.m_logger.sendTraceTag(590213388,mT.TraceLevel.Error,"SimpleStateServiceProxy::connect - "+(null===(v=S.m_connection)||void 0===v?void 0:v.name)+" onerror. {sessionId: "+S.m_sessionId+", ClientId: "+S.m_clientId+", Error: "+JSON.stringify(g)+"}"),S.retryConnection((function(g){var f,v="failed to reconnect after "+(null===(f=S.m_connection)||void 0===f?void 0:f.name)+" error: "+FI.errorToString(g);S.m_logger.sendTraceTag(579463185,mT.TraceLevel.Error,v),C(v)}),!1,(function(){return f()}))},this.m_connection.onlog=function(g){var f;S.m_logger.sendTraceTag(556909603,g.detail.level,"SimpleStateServiceProxy::log - "+(null===(f=S.m_connection)||void 0===f?void 0:f.name)+" {sessionId: "+S.m_sessionId+", ClientId: "+S.m_clientId+", Message: "+g.detail.message+"}")},this.m_connection.onclose=function(g){var v,_;S.m_logger.sendTraceTag(590213389,mT.TraceLevel.Error,"SimpleStateServiceProxy::connect - "+(null===(v=S.m_connection)||void 0===v?void 0:v.name)+" onclose. {sessionId: "+S.m_sessionId+", ClientId: "+S.m_clientId+", Code: "+g.code+", Reason: "+g.reason+"}"),S.m_lastCloseCode=g.code,S.m_lastCloseReason=g.reason,g.code!==A?S.retryConnection((function(g){var f="failed to reconnect after service side disconnect: "+FI.errorToString(g);S.m_logger.sendTraceTag(579463186,mT.TraceLevel.Error,f),C(f)}),!1,(function(){return f()})):(S.setConnectionState(fT.ConnectionState.Disconnected),S.m_logger.sendTraceTag(588009741,mT.TraceLevel.Error,"SimpleStateServiceProxy::connect - "+(null===(_=S.m_connection)||void 0===_?void 0:_.name)+" onclose. Not retryable close code. {sessionId: "+S.m_sessionId+", ClientId: "+S.m_clientId+"}"))},this.m_connection.onmessage=function(g){var f;try{S.handleConnectionMessage(g)}catch(g){S.m_logger.sendTraceTag(590213390,mT.TraceLevel.Error,"SimpleStateServiceProxy::onmessage - "+(null===(f=S.m_connection)||void 0===f?void 0:f.name)+" error. {sessionId: "+S.m_sessionId+", ClientId: "+S.m_clientId+", Error: "+FI.errorToString(g)+"}")}},[2]}}))}))}))]}))}))},SimpleStateServiceProxy.prototype.close=function(){var g;this.m_logger.sendTraceTag(590213400,mT.TraceLevel.Info,"SimpleStateServiceProxy::close. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),this.closeAndClearConnection(),this.m_retryTimer&&(clearTimeout(this.m_retryTimer),this.m_retryTimer=null),this.m_unacknowledgedMessages.clear(),this.clearPingPongTimer(),this.clearOfflineMessageCacheTimer(),this.clearInitTimeoutTimer(),this.clearUnacknowledgedTimer(),null===(g=this.m_clientIdEvictingQueue)||void 0===g||g.clear(),0!==this.countOfOutboundMessagesNotRoundTrippedYet()&&(this.m_events.emit("messageFailedToRoundTripOnClose",this.m_outboundMessageInfo.size),this.m_outboundMessageInfo.clear())},SimpleStateServiceProxy.prototype.sendStateMessage=function(g){this.sendStateMessageImpl(g)},SimpleStateServiceProxy.prototype.createMapAsync=function(g,f,C,_){return S(this,void 0,void 0,(function(){var S;return v(this,(function(v){return S=new BI.SimpleSyncMap(g,this,f,C,_),this.m_handlers.set(g,S),[2,S]}))}))},SimpleStateServiceProxy.prototype.getMapAsync=function(g){return S(this,void 0,void 0,(function(){var f;return v(this,(function(S){return(f=this.m_handlers.get(g))?[2,f]:[2,null]}))}))},SimpleStateServiceProxy.prototype.waitMapAsync=function(g,f,C,_){return S(this,void 0,void 0,(function(){var S;return v(this,(function(v){switch(v.label){case 0:return[4,this.m_initPromise.promise];case 1:return v.sent(),[4,this.getMapAsync(g)];case 2:return(S=v.sent())?[3,4]:[4,this.createMapAsync(g,f,C,_)];case 3:S=v.sent(),v.label=4;case 4:return[2,S]}}))}))},SimpleStateServiceProxy.prototype.createCellAsync=function(g,f,C,_){return S(this,void 0,void 0,(function(){var S;return v(this,(function(v){return S=new UI.SimpleSyncCell(g,this,f,C,_),this.m_handlers.set(g,S),[2,S]}))}))},SimpleStateServiceProxy.prototype.getCellAsync=function(g){return S(this,void 0,void 0,(function(){var f;return v(this,(function(S){return(f=this.m_handlers.get(g))?[2,f]:[2,null]}))}))},SimpleStateServiceProxy.prototype.waitCellAsync=function(g,f,C,_){return S(this,void 0,void 0,(function(){var S;return v(this,(function(v){switch(v.label){case 0:return this.m_logger.sendTraceTag(520161040,mT.TraceLevel.Info,"SimpleStateServiceProxy::waitCellAsync - awaiting initPromise "+g),[4,this.m_initPromise.promise];case 1:return v.sent(),this.m_logger.sendTraceTag(520161039,mT.TraceLevel.Info,"SimpleStateServiceProxy::waitCellAsync - getCellAsync "+g),[4,this.getCellAsync(g)];case 2:return(S=v.sent())?[3,4]:(this.m_logger.sendTraceTag(520161038,mT.TraceLevel.Info,"SimpleStateServiceProxy::waitCellAsync - createCellAsync "+g),[4,this.createCellAsync(g,f,C,_)]);case 3:S=v.sent(),v.label=4;case 4:return[2,S]}}))}))},SimpleStateServiceProxy.prototype.onFocusChanged=function(g){var f=this;g?(window.clearTimeout(this.m_closeConnectionTimer),this.m_connection||(this.m_logger.sendTraceTag(590213392,mT.TraceLevel.Info,"SimpleStateServiceProxy::onFocusChanged - retryConnection due to getting focus again. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),this.retryConnection((function(g){f.m_logger.sendTraceTag(579463187,mT.TraceLevel.Error,"failed to reconnect after regaining focus: "+FI.errorToString(g))}),!0))):this.m_closeConnectionTimer=window.setTimeout((function(){var g;f.m_connection&&(f.m_logger.sendTraceTag(590213391,mT.TraceLevel.Info,"SimpleStateServiceProxy::onFocusChanged - "+(null===(g=f.m_connection)||void 0===g?void 0:g.name)+" close due to losing focus. {sessionId: "+f.m_sessionId+", ClientId: "+f.m_clientId+"}"),f.m_connection.onclose=function(){},f.m_connection.close(),f.m_connection=null)}),this.m_connectionAliveTimeAfterLoseFocusInMS)},SimpleStateServiceProxy.prototype.getHistoryAsync=function(g,f){return S(this,void 0,void 0,(function(){var S,C;return v(this,(function(v){switch(v.label){case 0:return(S=new URL(this.m_deltasBaseUrl)).searchParams.append("action","deltas"),S.searchParams.append("docId",this.m_sessionId),S.searchParams.append("cid",this.m_clientId),S.searchParams.append("objectId",g),f&&S.searchParams.append("property",f),[4,I.default.get(S.toString())];case 1:return(C=v.sent().data).forEach((function(g){return g.value=JSON.parse(g.value)})),[2,C]}}))}))},SimpleStateServiceProxy.prototype.getHistoryWithPaginationAsync=function(g,f,C){return S(this,void 0,void 0,(function(){var S,_;return v(this,(function(v){switch(v.label){case 0:return(S=new URL(this.m_deltasBaseUrl)).searchParams.append("action","deltas"),S.searchParams.append("docId",this.m_sessionId),S.searchParams.append("cid",this.m_clientId),S.searchParams.append("objectId",g),S.searchParams.append("pagination","true"),C&&S.searchParams.append("cursor",C),f&&S.searchParams.append("property",f),[4,I.default.get(S.toString())];case 1:return(_=v.sent().data).messages.forEach((function(g){return g.value=JSON.parse(g.value)})),[2,_]}}))}))},SimpleStateServiceProxy.prototype.setupSystemClientsCell=function(){var g=this;this.m_clientsCell=new UI.SimpleSyncCell("systemClients",this),this.m_handlers.set(this.m_clientsCell.id(),this.m_clientsCell),this.m_clientsCell.on("valueChanged",(function(f){g.m_clientIds=new Set(f),g.m_events.emit("activeClientCountChanged")}))},SimpleStateServiceProxy.prototype.setUpSystemCommandsCell=function(){var g=this;this.m_systemCommandsCell=new UI.SimpleSyncCell(fT.SystemCommandsStateName,this),this.m_handlers.set(this.m_systemCommandsCell.id(),this.m_systemCommandsCell),this.m_systemCommandsCell.on("valueChanged",(function(f){return S(g,void 0,void 0,(function(){var g,S,C;return v(this,(function(v){switch(v.label){case 0:return"refreshToken"===f?[3,1]:[3,6];case 1:if(!this.m_user||!this.m_user.getForceRefreshedTokenAsync)return[3,5];v.label=2;case 2:return v.trys.push([2,4,,5]),[4,this.m_user.getForceRefreshedTokenAsync()];case 3:return g=v.sent(),S={},g&&(S.authorization=g.token,S.authProvider=g.authProvider,S.mri=g.mri||"",S.huid=g.hashedUserEmail||""),this.sendConfigMessage(S),[3,5];case 4:return C=v.sent(),this.m_logger.sendTraceTag(574107847,mT.TraceLevel.Error,"Error getting force refreshed auth token: "+FI.errorToString(C)),[3,5];case 5:return[3,7];case 6:return this.m_logger.sendTraceTag(574107848,mT.TraceLevel.Error,"Unknown system command cell value: "+f),[3,7];case 7:return[2]}}))}))}))},SimpleStateServiceProxy.prototype.setupServiceGeneratedClientIdCell=function(){var g=this;this.m_serviceGeneratedClientIdCell=new UI.SimpleSyncCell(fT.ServiceGeneratedClientIdName,this),this.m_handlers.set(this.m_serviceGeneratedClientIdCell.id(),this.m_serviceGeneratedClientIdCell),this.m_serviceGeneratedClientIdCell.on("valueChanged",(function(f){g.m_logger.sendTraceTag(520161037,mT.TraceLevel.Info,"SimpleStateServiceProxy::serviceGeneratedClientId changed to "+f+"}"),g.setClientId(f,!0),g.processClientIdQueue(),g.m_useServiceGeneratedClientId&&(g.processOfflineMessageCache(!0),g.clearOfflineMessageCacheTimer())})),this.m_logger.sendTraceTag(509743689,mT.TraceLevel.Info,"SimpleStateServiceProxy::setupServiceGeneratedClientIdCell completed.")},SimpleStateServiceProxy.prototype.handleConnectionOpen=function(){var g;this.m_logger.sendTraceTag(590213387,mT.TraceLevel.Info,"SimpleStateServiceProxy::connect - "+(null===(g=this.m_connection)||void 0===g?void 0:g.name)+" onopen. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),this.m_retryAttempts=0,this.setConnectionState(fT.ConnectionState.Connected),this.startPingTimer(),this.m_useServiceGeneratedClientId||(this.processOfflineMessageCache(!1),this.clearOfflineMessageCacheTimer())},SimpleStateServiceProxy.prototype.setConnectionState=function(g){this.m_connectionState!==g&&(this.m_connectionState=g,g===fT.ConnectionState.Disconnected&&this.m_useServiceGeneratedClientId&&this.setClientId("",!1),this.m_events.emit("connectionStateChanged"))},SimpleStateServiceProxy.prototype.setClientId=function(g,f){this.m_clientId!==g&&(this.m_clientId=g,f&&this.m_events.emit("clientIdChanged"))},SimpleStateServiceProxy.prototype.processClientIdQueue=function(){var g=this;this.m_clientIdEvictingQueue&&this.m_clientIdEvictingQueue.forEach((function(f){f.senderId=g.m_clientId,g.sendConnectionMessage(f,!0)}))},SimpleStateServiceProxy.prototype.sendGetInitialSystemStateMessages=function(){try{var g={messageId:LI.v4(),senderId:this.senderId(),objectId:fT.SystemSessionStateName,type:"",operation:"get",value:""};this.sendStateMessage(g);var f={messageId:LI.v4(),senderId:this.senderId(),objectId:fT.ServiceGeneratedClientIdName,type:"",operation:"get",value:""};this.sendStateMessage(f),this.m_logger.sendTraceTag(509141838,mT.TraceLevel.Info,"SimpleStateServiceProxy::sendGetInitialSystemStateMessages - sent messages.")}catch(g){this.m_logger.sendTraceTag(509141837,mT.TraceLevel.Error,"SimpleStateServiceProxy::sendGetInitialSystemStateMessages - caught error "+g)}},SimpleStateServiceProxy.prototype.createSetupMessage=function(g){var f=g.authToken,S=g.metadata,v=g.subscriptions,C=[];if(f||S){var _={};f&&(_.authorization=f.token,_.authProvider=f.authProvider,_.mri=f.mri||"",_.huid=f.hashedUserEmail||""),S&&(_.metadata=JSON.stringify(S));var T={messageId:LI.v4(),senderId:this.senderId(),objectId:fT.ConfigurationName,type:"",operation:"",value:JSON.stringify(_)};C.push(JSON.stringify(T))}if(v){T={messageId:LI.v4(),senderId:this.senderId(),objectId:fT.StateSubscriptionsName,type:"",operation:"",value:JSON.stringify(v)};C.push(JSON.stringify(T))}return C},SimpleStateServiceProxy.prototype.sendConfigMessage=function(g){var f={messageId:LI.v4(),senderId:this.senderId(),objectId:fT.ConfigurationName,type:"",operation:"",value:JSON.stringify(g)};this.sendStateMessage(f)},SimpleStateServiceProxy.prototype.retryConnection=function(g,f,C){var _=this;if(this.clearPingPongTimer(),this.clearInitTimeoutTimer(),this.m_retryAttempts>=this.m_retryIntervalsInMs.length||this.m_sessionRetryAttempts>=this.m_maxSessionRetries)return this.setConnectionState(fT.ConnectionState.Disconnected),this.m_logger.sendTraceTag(590213393,mT.TraceLevel.Error,"SimpleStateServiceProxy::retryConnection reached max retry attempts. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),void(g&&g(new Error("reached max retry attempts")));if(this.setConnectionState(fT.ConnectionState.Connecting),f||this.m_connection&&!this.m_retryTimer){var T=this.m_retryIntervalsInMs[this.m_retryAttempts];this.m_retryAttempts+=1,this.m_sessionRetryAttempts+=1,this.m_telemetry.wsReconnectCount+=1,this.closeAndClearConnection(),this.m_retryTimer=setTimeout((function(){return S(_,void 0,void 0,(function(){var f;return v(this,(function(S){switch(S.label){case 0:this.m_logger.sendTraceTag(590213395,mT.TraceLevel.Info,"SimpleStateServiceProxy::retryConnection. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),this.m_retryTimer=null,S.label=1;case 1:return S.trys.push([1,3,,4]),[4,this.connectAsync()];case 2:return S.sent(),C&&C(),[3,4];case 3:return f=S.sent(),this.setConnectionState(fT.ConnectionState.Disconnected),this.m_logger.sendTraceTag(590213396,mT.TraceLevel.Error,"SimpleStateServiceProxy::retryConnection failed. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}, "+FI.errorToString(f)),this.m_retryAttempts>=this.m_retryIntervalsInMs.length&&g(f),[3,4];case 4:return[2]}}))}))}),T)}else this.m_logger.sendTraceTag(590213394,mT.TraceLevel.Info,"SimpleStateServiceProxy::retryConnection skipped. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", NullConnection: "+(null===this.m_connection)+", NullRetryTimer: "+(null===this.m_retryTimer)+"}")},SimpleStateServiceProxy.prototype.startPingTimer=function(){var g=this;this.m_connection&&this.m_connection.shouldSendPings&&(this.m_pingTimeoutInMs<=0||this.m_pongTimeoutInMs<=0||(this.clearPingPongTimer(),this.m_pingTimer=setTimeout((function(){return S(g,void 0,void 0,(function(){return v(this,(function(g){return this.sendPingMessage(),this.m_pingTimer=null,[2]}))}))}),this.m_pingTimeoutInMs)))},SimpleStateServiceProxy.prototype.sendPingMessage=function(){var g=this;this.m_connection&&(this.m_connection.isOpen?(this.m_verbose&&this.m_logger.sendTraceTag(559952470,mT.TraceLevel.Info,"SimpleStateServiceProxy::sendPingMessage. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", __ping__"),this.m_connection.send("__ping__"),this.clearPongTimer(),this.m_pongTimer=setTimeout((function(){return S(g,void 0,void 0,(function(){var g=this;return v(this,(function(f){return this.retryConnection((function(f){g.m_logger.sendTraceTag(579463188,mT.TraceLevel.Error,"failed to reconnect after missing ping: "+FI.errorToString(f))}),!1),this.m_pongTimer=null,[2]}))}))}),this.m_pongTimeoutInMs)):(this.retryConnection((function(f){g.m_logger.sendTraceTag(579463189,mT.TraceLevel.Error,"failed to reconnect after closed connection: "+FI.errorToString(f))}),!1),this.clearPongTimer()))},SimpleStateServiceProxy.prototype.clearPingPongTimer=function(){this.clearPingTimer(),this.clearPongTimer()},SimpleStateServiceProxy.prototype.clearPingTimer=function(){this.m_pingTimer&&(clearTimeout(this.m_pingTimer),this.m_pingTimer=null)},SimpleStateServiceProxy.prototype.clearPongTimer=function(){this.m_pongTimer&&(clearTimeout(this.m_pongTimer),this.m_pongTimer=null)},SimpleStateServiceProxy.prototype.handleConnectionMessage=function(g){if("string"==typeof g.data){if(this.startPingTimer(),"__pong__"===g.data)return void(this.m_verbose&&this.m_logger.sendTraceTag(559952471,mT.TraceLevel.Info,"SimpleStateServiceProxy::handleConnectionMessage. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", __pong__"));var f=Date.now();try{var S=JSON.parse(g.data);Array.isArray(S)&&S.length>0?this.handleAggregatedStateMessages(S):this.handleStateMessage(S),this.m_telemetry.addMessageHandleLatency(Date.now()-f),S.objectId===fT.SystemSessionStateName?(this.m_logger.sendTraceTag(520161036,mT.TraceLevel.Info,"SimpleStateServiceProxy::handleConnectionMessage - systemSessionState - initPromise resolved."),this.m_initPromise.resolve(),this.clearInitTimeoutTimer()):S.objectId===fT.ServiceGeneratedClientIdName&&this.m_logger.sendTraceTag(509743688,mT.TraceLevel.Info,"SimpleStateServiceProxy::handleConnectionMessage - serviceGeneratedClientId received.")}catch(g){this.m_logger.sendTraceTag(578102302,mT.TraceLevel.Error,"handleConnectionMessage: "+FI.errorToString(g))}}else this.m_logger.sendTraceTag(590213397,mT.TraceLevel.Error,"SimpleStateServiceProxy::handleConnectionMessage - Unknown data type. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", Type: "+typeof g.data+"}")},SimpleStateServiceProxy.prototype.handleAggregatedStateMessages=function(g){var f,S,v=this;if(g&&0!==g.length){var C=g.map((function(g){return JSON.parse(g)})),T={};C.forEach((function(g){return T[g.objectId]=1+(T[g.objectId]||0)})),Object.keys(T).forEach((function(g){if(T[g]>1){var f=v.m_handlers.get(g);f&&f.beginAggregatedStateUpdating&&f.beginAggregatedStateUpdating()}}));try{for(var I=_(C),b=I.next();!b.done;b=I.next()){var A=b.value;this.handleStateMessage(A)}}catch(g){f={error:g}}finally{try{b&&!b.done&&(S=I.return)&&S.call(I)}finally{if(f)throw f.error}}Object.keys(T).forEach((function(g){if(T[g]>1){var f=v.m_handlers.get(g);f&&f.endAggregatedStateUpdating&&f.endAggregatedStateUpdating()}}))}},SimpleStateServiceProxy.prototype.handleStateMessage=function(g){var f=this;if(this.m_verbose&&this.m_logger.sendTraceTag(590213398,mT.TraceLevel.Info,"SimpleStateServiceProxy::handleStateMessage. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", ObjectId: "+g.objectId+", MessageId: "+g.messageId+"}"),"list"===g.type){JSON.parse(g.value).forEach((function(g){f.handleStateMessage(g)}))}else{if(this.m_user&&this.m_user.validateMessage&&!this.m_user.validateMessage(g))return void this.m_logger.sendTraceTag(588009742,mT.TraceLevel.Error,"SimpleStateServiceProxy::handleStateMessage rejected message: {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", ObjectId: "+g.objectId+", MessageId: "+g.messageId+"}");var S=this.getHandlerForMessage(g);if(g.senderId===this.senderId()&&(this.acknowledgeMessage(g,S),this.m_telemetry.incrementAcknowledgedCount(g.objectId)),this.measureMessageRoundTripLatency(g),this.m_telemetry.incrementReceivedCount(g.objectId),S)return void S.handleStateMessage(g)}},SimpleStateServiceProxy.prototype.getAuthToken=function(){return S(this,void 0,void 0,(function(){var g,f;return v(this,(function(S){switch(S.label){case 0:if(!this.m_user||!this.m_user.getAuthTokenAsync)return[3,4];S.label=1;case 1:return S.trys.push([1,3,,4]),[4,this.m_user.getAuthTokenAsync()];case 2:return g=S.sent(),[3,4];case 3:return f=S.sent(),this.m_logger.sendTraceTag(578102469,mT.TraceLevel.Error,"Error getting auth token: "+FI.errorToString(f)),[3,4];case 4:return[2,g]}}))}))},SimpleStateServiceProxy.prototype.getHandlerForMessage=function(g){var f=this.m_handlers.get(g.objectId);return f||("cell"===g.type?f=new UI.SimpleSyncCell(g.objectId,this):"map"===g.type?f=new BI.SimpleSyncMap(g.objectId,this):this.m_logger.sendTraceTag(559204164,mT.TraceLevel.Error,"SimpleStateServiceProxy::handleStateMessage - Unknown message type. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", Type: "+g.type+"}"),f&&this.m_handlers.set(g.objectId,f),f)},SimpleStateServiceProxy.prototype.sendStateMessageImpl=function(g){var f,S=this;if(this.m_verbose&&this.m_logger.sendTraceTag(590213403,mT.TraceLevel.Info,"SimpleStateServiceProxy::sendStateMessageImpl. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", ObjectId: "+g.objectId+", MessageId: "+g.messageId+"}"),g.objectId!==fT.StateSubscriptionsName&&g.objectId!==fT.ConfigurationName){if(this.m_outboundMessageInfo.set(g.messageId,Date.now()),this.m_telemetry.incrementRequestedCount(g.objectId),this.m_unacknowledgedMaxTimeInMs>0){var v=null===(f=this.getHandlerForMessage(g))||void 0===f?void 0:f.messageTrackingOption();if(v&&v!==fT.MessageTrackingOption.None){var C=this.getUnacknowledgedMessagesMapKey(g,v);this.m_unacknowledgedMessages.set(C,{message:g,timestamp:Date.now()}),this.startUnacknowledgeMessageTimer()}}if(this.m_useServiceGeneratedClientId&&this.m_clientIdEvictingQueue&&!this.m_clientId&&"get"!==g.operation)return this.m_logger.sendTraceTag(508348254,mT.TraceLevel.Info,"SimpleStateServiceProxy::enqueueMessage "+JSON.stringify(g)),void this.m_clientIdEvictingQueue.enqueue(g)}this.m_user&&this.m_user.patchMessage&&this.m_user.patchMessage(g),this.m_batchedRequestsEnabled?(this.m_messageBuffer.push(g),this.m_processBufferTimer||(this.m_processBufferTimer=setTimeout((function(){S.processMessageBuffer()}),this.m_batchWaitTimeMS))):this.sendConnectionMessage(g,!0)},SimpleStateServiceProxy.prototype.createListMessage=function(g){if(0!==g.length)return 1===g.length?g[0]:{value:JSON.stringify(g),type:this.m_batchMessageTypeName,operation:"",messageId:LI.v4(),objectId:"batch",senderId:this.senderId()}},SimpleStateServiceProxy.prototype.processMessageBuffer=function(){var g=this.m_messageBuffer.length,f=this.m_messageBuffer.splice(0,g),S=this.createListMessage(f);this.m_processBufferTimer&&clearTimeout(this.m_processBufferTimer),this.m_processBufferTimer=null,S&&this.sendConnectionMessage(S,!0)},SimpleStateServiceProxy.prototype.processOfflineMessageCache=function(g){var f=this;this.m_offlineMessageCacheEnabled&&(this.m_offlineMessageCache.forEach((function(S){g&&(S.message.senderId=f.m_clientId),f.sendConnectionMessage(S.message,!1),f.m_telemetry.offlineCacheTelemetry.resentCount+=1})),this.m_offlineMessageCache=[])},SimpleStateServiceProxy.prototype.purgeOfflineMessageCache=function(){var g=this;if(this.m_offlineMessageCacheEnabled&&this.m_maxOfflineMessageCacheTimeInMs){var f=Date.now(),S=this.m_offlineMessageCache.filter((function(S){return g.m_maxOfflineMessageCacheTimeInMs&&S.timestamp+g.m_maxOfflineMessageCacheTimeInMs>=f}));this.m_telemetry.offlineCacheTelemetry.expiredCount+=this.m_offlineMessageCache.length-S.length,this.m_offlineMessageCache=S,0===this.m_offlineMessageCache.length&&this.clearOfflineMessageCacheTimer()}},SimpleStateServiceProxy.prototype.clearOfflineMessageCacheTimer=function(){this.m_offlineMessageCacheEnabled&&this.m_offlineMessageCacheTimer&&(clearInterval(this.m_offlineMessageCacheTimer),this.m_offlineMessageCacheTimer=null)},SimpleStateServiceProxy.prototype.getUnacknowledgedMessagesMapKey=function(g,f){return f===fT.MessageTrackingOption.None?"":f===fT.MessageTrackingOption.All?g.messageId:g.objectId},SimpleStateServiceProxy.prototype.startUnacknowledgeMessageTimer=function(){var g=this;this.m_unacknowledgedMaxTimeInMs>0&&!this.m_unacknowledgedTimer&&(this.m_unacknowledgedTimer=setInterval((function(){g.notifyUnacknowledgedMessages(),g.m_unacknowledgedMessages.size<=0&&g.clearUnacknowledgedTimer()}),this.m_unacknowledgedMaxTimeInMs/2))},SimpleStateServiceProxy.prototype.acknowledgeMessage=function(g,f){if(g.senderId===this.senderId()&&f&&!(this.m_unacknowledgedMessages.size<=0)){var S=this.getUnacknowledgedMessagesMapKey(g,f.messageTrackingOption()),v=this.m_unacknowledgedMessages.get(S);v&&g.messageId===v.message.messageId&&this.m_unacknowledgedMessages.delete(S)}},SimpleStateServiceProxy.prototype.notifyUnacknowledgedMessages=function(){var g=this,f=Date.now();this.m_unacknowledgedMessages.forEach((function(S,v){if(S.timestamp+g.m_unacknowledgedMaxTimeInMs<f){var C=g.getHandlerForMessage(S.message);null==C||C.handleUnacknowledgedMessage(S.message),g.m_unacknowledgedMessages.delete(v),g.m_telemetry.unacknowledgedMessagesCount+=1}}))},SimpleStateServiceProxy.prototype.clearUnacknowledgedTimer=function(){this.m_unacknowledgedTimer&&(clearInterval(this.m_unacknowledgedTimer),this.m_unacknowledgedTimer=null)},SimpleStateServiceProxy.prototype.startInitTimeoutTimerWithRetry=function(g,f){var S=this;this.startInitTimeoutTimer(g,(function(){S.m_logger.sendTraceTag(509141836,mT.TraceLevel.Error,"SimpleStateServiceProxy::startInitTimeoutTimer - failed to init after "+g+" ms; requesting get messages and retrying"),S.sendGetInitialSystemStateMessages(),S.startInitTimeoutTimer(g,f)}))},SimpleStateServiceProxy.prototype.startInitTimeoutTimer=function(g,f){g>0&&(this.clearInitTimeoutTimer(),this.m_initTimeoutTimer=setTimeout((function(){f("Initialization timed out after "+g+" ms")}),g))},SimpleStateServiceProxy.prototype.clearInitTimeoutTimer=function(){this.m_initTimeoutTimer&&clearTimeout(this.m_initTimeoutTimer)},SimpleStateServiceProxy.prototype.sendConnectionMessage=function(g,f){var S,v,C=this;if(this.m_allowReconnectOnMessageSend&&this.m_connectionState===fT.ConnectionState.Disconnected&&(this.updateRetryAttempts(),this.retryConnection((function(g){C.m_logger.sendTraceTag(559428289,mT.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - failed to reconnect with error: "+FI.errorToString(g)+" ")}),!1)),this.m_offlineMessageCacheEnabled&&f){if(!this.m_connection||this.m_connectionState!==fT.ConnectionState.Connected)return!this.m_maxOfflineMessageCacheLength||this.m_offlineMessageCache.length>=this.m_maxOfflineMessageCacheLength?(this.m_telemetry.offlineCacheTelemetry.rejectedCount+=1,void this.m_logger.sendTraceTag(570807006,mT.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - Dropping message because offline cache is full. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", Status: "+(null===(S=this.m_connection)||void 0===S?void 0:S.readyState)+"}")):(!this.m_offlineMessageCacheTimer&&this.m_maxOfflineMessageCacheTimeInMs&&(this.m_offlineMessageCacheTimer=setInterval((function(){C.purgeOfflineMessageCache()}),this.m_maxOfflineMessageCacheTimeInMs/2)),this.m_offlineMessageCache.push({message:g,timestamp:Date.now()}),void(this.m_telemetry.offlineCacheTelemetry.cachedCount+=1))}else{if(!this.m_connection)return void this.m_logger.sendTraceTag(590213401,mT.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - connection is not set. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}");if(!this.m_connection.isOpen)return void this.m_logger.sendTraceTag(590213402,mT.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - "+this.m_connection.name+" status is not open. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", Status: "+this.m_connection.readyState+"}")}null===(v=this.m_connection)||void 0===v||v.send(JSON.stringify(g))},SimpleStateServiceProxy.prototype.closeAndClearConnection=function(){if(this.m_connection){if(this.m_connection.onclose=function(){},this.m_connection.isOpen)this.m_connection.close();else{var g=this.m_connection;g.onopen=function(){return g.close()}}this.m_connection=null}},SimpleStateServiceProxy.prototype.updateRetryAttempts=function(){this.m_retryAttempts>=this.m_retryIntervalsInMs.length&&(this.m_retryAttempts=0),this.m_sessionRetryAttempts>=this.m_maxSessionRetries&&(this.m_sessionRetryAttempts=0)},SimpleStateServiceProxy.prototype.measureMessageRoundTripLatency=function(g){if(g.senderId===this.senderId())try{var f=this.m_outboundMessageInfo.get(g.messageId);if(void 0!==f){this.m_outboundMessageInfo.delete(g.messageId);var S=Date.now()-f;this.m_events.emit("messageRoundTripped",{clientId:this.m_clientId,sessionId:this.m_sessionId,messageId:g.messageId,objectId:g.objectId,operation:g.operation,latencyInMs:S}),this.m_telemetry.addRoundtripLatency(S)}else this.m_verbose&&this.m_logger.sendTraceTag(590213404,mT.TraceLevel.Info,"SimpleStateServiceProxy::measureMessageRoundTripLatency. Failed to find outbound message info for {SessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", ObjectId: "+g.objectId+", MessageId: "+g.messageId+"}")}catch(f){this.m_logger.sendTraceTag(590213405,mT.TraceLevel.Error,"SimpleStateServiceProxy::measureMessageRoundTripLatency - Exception thrown error. {SessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", MessageId: "+g.messageId+", Error: "+f.message+"}")}},SimpleStateServiceProxy}();f.SimpleStateServiceProxy=P})),GI=createCommonjsModule((function(g,f){var S=C&&C.__awaiter||function(g,f,S,v){function adopt(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function fulfilled(g){try{step(v.next(g))}catch(g){C(g)}}function rejected(g){try{step(v.throw(g))}catch(g){C(g)}}function step(g){g.done?S(g.value):adopt(g.value).then(fulfilled,rejected)}step((v=v.apply(g,f||[])).next())}))},v=C&&C.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function verb(g){return function(f){return step([g,f])}}function step(_){if(S)throw new TypeError("Generator is already executing.");for(;T;)try{if(S=1,v&&(C=2&_[0]?v.return:_[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,_[1])).done)return C;switch(v=0,C&&(_=[2&_[0],C.value]),_[0]){case 0:case 1:C=_;break;case 4:return T.label++,{value:_[1],done:!1};case 5:T.label++,v=_[1],_=[0];continue;case 7:_=T.ops.pop(),T.trys.pop();continue;default:if(!(C=T.trys,(C=C.length>0&&C[C.length-1])||6!==_[0]&&2!==_[0])){T=0;continue}if(3===_[0]&&(!C||_[1]>C[0]&&_[1]<C[3])){T.label=_[1];break}if(6===_[0]&&T.label<C[1]){T.label=C[1],C=_;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(_);break}C[2]&&T.ops.pop(),T.trys.pop();continue}_=f.call(g,T)}catch(g){_=[6,g],v=0}finally{S=C=0}if(5&_[0])throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}};function createStateServiceProxyAsync(g,f,C,_,T,I){return S(this,void 0,void 0,(function(){var S;return v(this,(function(v){switch(v.label){case 0:return[4,(S=new jI.SimpleStateServiceProxy(g,f,C,_,T,I)).connectAsync()];case 1:return v.sent(),[2,S]}}))}))}Object.defineProperty(f,"__esModule",{value:!0}),f.createStateServiceProxyAsync=void 0,f.createStateServiceProxyAsync=createStateServiceProxyAsync})),qI=createCommonjsModule((function(g,f){var S=C&&C.__createBinding||(Object.create?function(g,f,S,v){void 0===v&&(v=S),Object.defineProperty(g,v,{enumerable:!0,get:function(){return f[S]}})}:function(g,f,S,v){void 0===v&&(v=S),g[v]=f[S]}),v=C&&C.__exportStar||function(g,f){for(var v in g)"default"===v||f.hasOwnProperty(v)||S(f,g,v)};Object.defineProperty(f,"__esModule",{value:!0}),v(mT,f),v(fT,f),v(GI,f)}));class ReactionLogger{constructor(g){this.enableConsoleLog=getAcsEcsConfig().calling.reaction.enableStateServiceConsoleLogs,this._logger=g}sendTraceTag(g,f,S){this.enableConsoleLog&&this._logger.info(`Tag: ${g}, Leve: ${f}, Message: ${S}`)}}class ReactionFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new ReactionImplOverStateService(this.eventEmitter),this._isReactionFeatureEnabled=getAcsEcsConfig().calling.reaction.enabled,this._callInfo=g.callInfo}get name(){return"Reaction"}initialize(g,f){this._tsCall=g.tsCall,this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._logger.info(`Meeting Reaction feature enable flag: ${this._isReactionFeatureEnabled}`),this._isReactionFeatureEnabled&&3===g.tsCall.state?this._impl.initialize(g.tsCall,g.callAgent,g.call,g.telemetryLogManager,f,this._callInfo):g.tsCall.on("callStateChanged",(()=>{this._isReactionFeatureEnabled&&3===g.tsCall.state?this._impl.initialize(g.tsCall,g.callAgent,g.call,g.telemetryLogManager,f,this._callInfo):this._logger.warn("Calls to reaction APIs will perform no action or return default values where applicable")}))}async sendReaction(g){let f=generateGuid();if(this._sendFeatureUsage("sendReaction",gE.attempt,void 0,f),3!=this._tsCall.state||this.callInfo.context===jS.TwoParty){const g=new CallingCommunicationError({defaultError:3!=this._tsCall.state?D.FEATURES.REACTION.CALL_NOT_CONNECTED:D.FEATURES.REACTION.NOT_SUPPORTED_1TO1_CTE});throw this._sendFeatureUsage("sendReaction",gE.failure,g,f),g}await this._impl.sendReaction(g,f)}on(g,f){if("reaction"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.REACTION.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});if(!this._isReactionFeatureEnabled){const g=new CallingCommunicationError({defaultError:D.FEATURES.REACTION.EVENT_SUBSCRIBE_FAIL_POLICY});throw this._sendFeatureUsage("receiveReaction",gE.failure,g),g}this._sendFeatureUsage("receiveReaction",gE.subscribe),this._impl.on(g,f)}off(g,f){if("reaction"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.REACTION.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});if(!this._isReactionFeatureEnabled){const g=new CallingCommunicationError({defaultError:D.FEATURES.REACTION.EVENT_UNSUBSCRIBE_FAIL_POLICY});throw this._sendFeatureUsage("receiveReaction",gE.failure,g),g}this._sendFeatureUsage("receiveReaction",gE.unsubscribe),this._impl.off(g,f)}dispose(){this.disposed||(this._impl.dispose(),super.dispose())}_sendFeatureUsage(g,f,S,v){let C=S?{code:S?.code||U,subCode:S?.subCode||0,failureReason:S?.message||"",...extractCommunicationServicesErrorForTelemetry(S)}:void 0;sendCallFeatureUsageTelemetry({correlationId:v,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:C},this._telemetryLogManager,this._logger)}}class ReactionImplOverStateService{constructor(g){this._wsUrl="",this.name="Reaction",this.capabilityChangeHandler=g=>{g.newValue.useReactions&&(this._participantCapability=this._call.getParticipantCapabilities().useReactions,this._logger.log(`participant capabilitity to useReactions feature is ${this._participantCapability}`))},this._eventEmitter=g,this._participantCapability={isPresent:!0,reason:"Capable"},this._isReactionFeatureEnabled=getAcsEcsConfig().calling.reaction.enabled}initialize(g,f,S,v,C,_){void 0===this._proxy||this._proxy?.getConnectionState()===qI.ConnectionState.Disconnected?(this._logger=C.createChild((()=>`ReactionImplOverStateService::Call(id='${this._tsCall.callId}')`)),this._internalCallAgent=f,this._tsCall=g,this._call=S,this._callInfo=_,this._docId=this._tsCall.callId,this._wsUrl=this.getEndpointUrl(),this._telemetryLogManager=v,this._sendAttempOrFailureFeatureUsage("initialize",gE.attempt),this.start()):C.info("State Service Proxy already has an active connection."),this._callInfo.context==jS.TeamsMeeting&&(this._participantCapability=this._call.getParticipantCapabilities().useReactions,this._logger.log(`participant capabilitity to useReactions feature is ${this._participantCapability}`),this._call.onParticipantCapabilitiesChanged("capabilitiesChanged",this.capabilityChangeHandler),this._logger.log("participant capabilities change event listener registered"))}async start(){const g=getAcsEcsConfig().calling.reaction.StateServiceProxySettings,f=qf,S={getAuthTokenAsync:this.getAuthToken.bind(this)};try{this._proxy=await qI.createStateServiceProxyAsync(this._docId,f,this._wsUrl,new ReactionLogger(this._logger),g,S)}catch(g){return this._logger.error("Could not create state service proxy",g),void this._sendAttempOrFailureFeatureUsage("initialize",gE.failure,new CallingCommunicationError({defaultError:D.FEATURES.REACTION.STATE_SERVICE_CONNECT_FAIL,originalError:g}))}try{this._reactionsMap=await this._proxy.createMapAsync("reactions",!0)}catch(g){return this._logger.error("Could not create state service proxy reaction map",g),void this._sendAttempOrFailureFeatureUsage("initialize",gE.failure,new CallingCommunicationError({defaultError:D.FEATURES.REACTION.MAP_CREATE_FAIL,originalError:g}))}this._sendSuccessFeatureUsage("initialize",gE.success),this._reactionsMap?.on("valueChanged",this.onReactionsReceived.bind(this))}async getAuthToken(){const g={token:await this._internalCallAgent.tokenProvider(),authProvider:"SKYPE",mri:this._internalCallAgent.getUserMri()};return Promise.resolve(g)}async sendReaction(g,f){if(!this._isReactionFeatureEnabled||!this._participantCapability.isPresent){const g=new CallingCommunicationError({defaultError:D.FEATURES.REACTION.SEND_FAIL_POLICY});throw this._sendAttempOrFailureFeatureUsage("sendReaction",gE.failure,g,f),g}if(!this._reactionsMap){this._logger.error("Reaction Map has not yet been initialized.");const g=new CallingCommunicationError({defaultError:D.FEATURES.REACTION.NOT_INIT_YET});throw this._sendAttempOrFailureFeatureUsage("sendReaction",gE.failure,g,f),g}try{return this._reactionsMap?.set(this._internalCallAgent.getUserMri(),{name:g.reactionType}),void this._sendSuccessFeatureUsage("sendReaction",gE.success,f,g.reactionType)}catch(g){this._logger.error("Unable to send reaction",g);const S=new CallingCommunicationError({defaultError:D.FEATURES.REACTION.SEND_REACTION_FAIL,originalError:g});throw this._sendAttempOrFailureFeatureUsage("sendReaction",gE.failure,S,f),S}}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}async onReactionsReceived(g){if(3===this._tsCall.state&&this._participantCapability.isPresent){const f=generateGuid();this._sendAttempOrFailureFeatureUsage("receiveReaction",gE.attempt,void 0,f);try{const S={reactionType:(await(this._reactionsMap?.get(g))).name};this._eventEmitter.emit("reaction",{identifier:g,reactionMessage:S}),this._sendSuccessFeatureUsage("receiveReaction",gE.success,f,S.reactionType)}catch(g){this._logger.error("Unable to parse reaction",g);let S=new CallingCommunicationError({defaultError:D.FEATURES.REACTION.RECEIVE_REACTION_FAIL,originalError:g});this._sendAttempOrFailureFeatureUsage("receiveReaction",gE.failure,S,f)}}}dispose(){void 0!==this._telemetryLogManager&&(this._proxy?.getConnectionState()===qI.ConnectionState.Connected?(this._reactionsMap?.removeAllListeners("valueChanged"),this._proxy.close(),this._sendSuccessFeatureUsage("dispose",gE.success),this._call.offParticipantCapabilitiesChanged("capabilitiesChanged",this.capabilityChangeHandler)):this._sendSuccessFeatureUsage("dispose",gE.failure))}_sendAttempOrFailureFeatureUsage(g,f,S,v){let C=S?{code:S?.code||U,subCode:S?.subCode||0,failureReason:S?.message||"",...extractCommunicationServicesErrorForTelemetry(S)}:void 0;sendCallFeatureUsageTelemetry({correlationId:v,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:C},this._telemetryLogManager,this._logger)}_sendSuccessFeatureUsage(g,f,S,v){let C;C="initialize"===g||"dispose"==g?void 0:{reactionConstraint:{reactionType:v}},sendCallFeatureUsageTelemetry({correlationId:S,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:C},this._telemetryLogManager,this._logger)}getEndpointUrl(){const g=this._internalCallAgent._caConfigBag,f=g&&isEudbConfigurationsApplicable(g.identityType,g.region);var S=getAcsEcsConfig().PowerPointStateServiceUrl.public.amer;switch(g?.cloudType){case tm.Public:f&&(S=getAcsEcsConfig().PowerPointStateServiceUrl.public.eu);break;case tm.GccHigh:S=getAcsEcsConfig().PowerPointStateServiceUrl.gcch;break;case tm.AirGap08:S=getAcsEcsConfig().PowerPointStateServiceUrl.ag08;break;case tm.AirGap09:S=getAcsEcsConfig().PowerPointStateServiceUrl.ag09;break;case tm.Dod:S=getAcsEcsConfig().PowerPointStateServiceUrl.dod;break;default:S=getAcsEcsConfig().PowerPointStateServiceUrl.public.amer}return`wss://${new URL(S).hostname}/StateServiceHandler.ashx`}}class ContentSharingSession{get contentSharingSession(){return this._contentSharingSession}constructor(g){this._contentSharingSession=g}getFileDetails(){if(this.contentSharingSession){return JSON.parse(atob(this.contentSharingSession.contentSharingIdentity))}}}const WI="azure_communication_calling_pptLive";class PPTLiveCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new PPTLiveCallImplOverTsCall(this.eventEmitter)}on(g,f){this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){this._sendFeatureUsage(g,gE.unsubscribe),this.eventEmitter.off(g,f)}get isActive(){return this._impl.isActive}get target(){return this._impl.target}get activePresenterId(){return this._impl.activePresenterId}get name(){return"PPTLive"}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._tsCall=g.tsCall,this._impl.initialize(g.tsCall,g.callAgent,g.telemetryLogManager,f)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:g,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}class PPTLiveCallImplOverTsCall{constructor(g){this._isActive=!1,this._isInitializingPPTLive=!1,this._updateIsActive=g=>this._isActive!==g&&(this._isActive=g,this._logger.info(`Updating isActive to ${g}`),!0),this._eventEmitter=g,this._target=document.createElement("div"),this._target.id=WI,this._target.style.width="100%",this._target.style.height="100%"}initialize(g,f,S,v){this._logger=v.createChild((()=>`PPTLive::Call(id='${g.callId}')`)),this._tsCall=g,this._internalCallAgent=f,this._telemetryLogManager=S,this._tsCall.on("contentSharingChanged",(()=>{this._checkContentSharingSession(this._tsCall.contentSharingSessions)})),this._tsCall.on("callStateChanged",(()=>{this._updatePPTLive(this._tsCall.state)}))}get isActive(){return this._isActive}get target(){return this._target}get activePresenterId(){return this._activePresenterId}_checkContentSharingSession(g){if(this._contentSharing&&0===g.length)this._updateIsActive(!1),this._contentSharing=void 0,this._target.innerHTML="",this._isInitializingPPTLive=!1,this._eventEmitter.emit("isActiveChanged"),this._sendFeatureUsage("endedPPTLive",gE.success);else if(!this._contentSharing&&0!==g.length){if(!getAcsEcsConfig().calling.pptlive.enabled)return;this._contentSharing=new ContentSharingSession(g[0]),this._updatePPTLive(this._tsCall.state),this._sendFeatureUsage("startedPPTLive",gE.attempt,this._contentSharing?.contentSharingSession?.contentSharingGuid)}}async _updatePPTLive(g){this._fileDetails=this._contentSharing?.getFileDetails(),this._fileDetails&&"ppt"===this._fileDetails.type&&3===g&&await this._startPPTLive(this._target)}_updateActivePresenter(){this._tsCall.participants.forEach((g=>{const f=constructIdentifierKindFromMri(g.id);2===g.contentSharingRole&&(this._activePresenterId=f)}))}_sendFeatureUsage(g,f,S){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"PPTLive",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:{pptLiveConstraint:{contentId:S}}},this._telemetryLogManager,this._logger)}_observeDivMount(){const g=new MutationObserver((async f=>{if(this._isActive&&!this._isInitializingPPTLive)for(const S of f)for(let f=0;f<S.addedNodes.length;f++){const v=S.addedNodes[f];if(v.nodeType===Node.ELEMENT_NODE){if(v.matches(`#${WI}`)){await this._startPPTLive(this._target),g.disconnect();break}}}else g.disconnect()}));g.observe(document.body,{childList:!0,subtree:!0})}_initViewerWithExperiment(g,f,S,v,C,_,T,I,b,A,P,R,M,w,O){const D={getAuthTokenAsync:!1,getForceRefreshedTokenAsync:!1},N=window.Microsoft,OnInitSuccess=g=>{g.GoToSlide(f,[],""),this._isInitializingPPTLive=!1,this._observeDivMount(),this._sendFeatureUsage("startedPPTLive",gE.success,this._contentSharing?.contentSharingSession?.contentSharingGuid)},OnInitFailure=g=>{this._isInitializingPPTLive=!1;var f="Category: "+g.Category+"\nMessage: "+g.Message+"\nExtraInfo: "+g.ExtraInfo;this._sendFeatureUsage("startedPPTLive",gE.failure,this._contentSharing?.contentSharingSession?.contentSharingGuid),this._logger.error(f)},k=getAcsEcsConfig().calling.pptlive,L={entryPoint:"null"},F={Container:g,SessionInformation:{DocumentClickTime:new Date,HostInitTime:new Date,UiLocale:R,DataLocale:R,IsPresenter:!1,WdParams:{wdModernSlideShowInTeams:k.wdParams.wdModernSlideShowInTeams,wdPresenterViewInTeams:k.wdParams.wdPresenterViewInTeams,wdForceModernSlideShowInTeams:k.wdParams.wdForceModernSlideShowInTeams,isMovePrivateViewingToPPTEnabled:k.wdParams.isMovePrivateViewingToPPTEnabled},PptFeatureGates:k.featureGates,ParticipantId:I,EnableStateServiceInPreviewerFeatures:JSON.parse(k.enableStateServiceInPreviewerFeatures),StateServiceSettings:{stateServiceProxySettings:k.stateServiceProxySettings,regionalEndpointUrl:this._getEndpointUrl(),authEnabled:!1,rosterCheckEnabled:!1,stateServiceUser:D},ContentId:M,EndpointId:T,CallId:w,HostName:"ACSWeb",HostSessionId:b},WopiPrecheckInfo:{FileName:v,FileGetUrl:_,FileSize:C,CustomFontCatalogUrl:O,BundleInfo:{MajorVersion:S,Url:A},CreateNewInfo:null},ApplicationCustomSettings:{TakeFocusOnBoot:k.appSettings.takeFocusOnBoot,EnableAdvanceOnClick:k.appSettings.enableAdvanceOnClick,EnableAdvanceOnTap:k.appSettings.enableAdvanceOnTap},Diagnostics:L,FnOnInitializeSuccess:OnInitSuccess,FnOnInitializeFailure:OnInitFailure};P&&(F.ApplicationCustomSettings.EnableWacFallback=!1,F.ApplicationUrl=P),N.Office.PowerPoint.Bootstrap.Prefetch(),N.Office.PowerPoint.Bootstrap.InitializeWopiPending(F),this._updateActivePresenter(),this._updateIsActive(!0),this._eventEmitter.emit("isActiveChanged"),this._sendFeatureUsage("startedPPTLive",gE.initialize,this._contentSharing?.contentSharingSession?.contentSharingGuid)}async _startPPTLive(g){this._fileDetails?.bootstrapperUrl&&(this._isInitializingPPTLive=!0,g.innerHTML="",await this._loadDynamicModule(this._fileDetails.bootstrapperUrl).then((()=>{this._fileDetails&&this._initViewerWithExperiment(g,Number(this._contentSharing?.contentSharingSession?.contentSharingState),this._fileDetails.majorVersion,this._fileDetails.name,this._fileDetails.fileSize,this._fileDetails.fileGetUrl,this._tsCall.endpointId,this._tsCall.participantId,generateGuid(),this._fileDetails.contentBundleUrl,this._fileDetails.wacUrl,navigator.language,this._fileDetails.id,this._tsCall.callId,this._fileDetails.customFontCatalogUrl)})).catch((()=>{this._sendFeatureUsage("startedPPTLive",gE.failure,this._contentSharing?.contentSharingSession?.contentSharingGuid)})))}_getEndpointUrl(){const g=this._internalCallAgent._caConfigBag,f=g&&isEudbConfigurationsApplicable(g.identityType,g.region);let S=getAcsEcsConfig().PowerPointStateServiceUrl.public.amer;switch(g?.cloudType){case tm.Public:f&&(S=getAcsEcsConfig().PowerPointStateServiceUrl.public.eu);break;case tm.GccHigh:S=getAcsEcsConfig().PowerPointStateServiceUrl.gcch;break;case tm.AirGap08:S=getAcsEcsConfig().PowerPointStateServiceUrl.ag08;break;case tm.AirGap09:S=getAcsEcsConfig().PowerPointStateServiceUrl.ag09;break;case tm.Dod:S=getAcsEcsConfig().PowerPointStateServiceUrl.dod;break;default:S=getAcsEcsConfig().PowerPointStateServiceUrl.public.amer}return S}async _loadDynamicModule(g){return new Function(`return (async () => await import('${g}'))()`)()}}const zI=1.778,KI=255,JI=2,YI=1280,QI=720;var XI;!function(g){g.sceneChanged="sceneChanged",g.seatingChanged="seatingChanged"}(XI||(XI={}));for(var ZI=byteLength,eb=toByteArray,tb=fromByteArray,ib=[],nb=[],rb="undefined"!=typeof Uint8Array?Uint8Array:Array,sb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ab=0,ob=sb.length;ab<ob;++ab)ib[ab]=sb[ab],nb[sb.charCodeAt(ab)]=ab;function getLens(g){var f=g.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var S=g.indexOf("=");return-1===S&&(S=f),[S,S===f?0:4-S%4]}function byteLength(g){var f=getLens(g),S=f[0],v=f[1];return 3*(S+v)/4-v}function _byteLength(g,f,S){return 3*(f+S)/4-S}function toByteArray(g){var f,S,v=getLens(g),C=v[0],_=v[1],T=new rb(_byteLength(g,C,_)),I=0,b=_>0?C-4:C;for(S=0;S<b;S+=4)f=nb[g.charCodeAt(S)]<<18|nb[g.charCodeAt(S+1)]<<12|nb[g.charCodeAt(S+2)]<<6|nb[g.charCodeAt(S+3)],T[I++]=f>>16&255,T[I++]=f>>8&255,T[I++]=255&f;return 2===_&&(f=nb[g.charCodeAt(S)]<<2|nb[g.charCodeAt(S+1)]>>4,T[I++]=255&f),1===_&&(f=nb[g.charCodeAt(S)]<<10|nb[g.charCodeAt(S+1)]<<4|nb[g.charCodeAt(S+2)]>>2,T[I++]=f>>8&255,T[I++]=255&f),T}function tripletToBase64(g){return ib[g>>18&63]+ib[g>>12&63]+ib[g>>6&63]+ib[63&g]}function encodeChunk(g,f,S){for(var v,C=[],_=f;_<S;_+=3)v=(g[_]<<16&16711680)+(g[_+1]<<8&65280)+(255&g[_+2]),C.push(tripletToBase64(v));return C.join("")}function fromByteArray(g){for(var f,S=g.length,v=S%3,C=[],_=16383,T=0,I=S-v;T<I;T+=_)C.push(encodeChunk(g,T,T+_>I?I:T+_));return 1===v?(f=g[S-1],C.push(ib[f>>2]+ib[f<<4&63]+"==")):2===v&&(f=(g[S-2]<<8)+g[S-1],C.push(ib[f>>10]+ib[f>>4&63]+ib[f<<2&63]+"=")),C.join("")}nb["-".charCodeAt(0)]=62,nb["_".charCodeAt(0)]=63;var lb={byteLength:ZI,toByteArray:eb,fromByteArray:tb},read=function(g,f,S,v,C){var _,T,I=8*C-v-1,b=(1<<I)-1,A=b>>1,P=-7,R=S?C-1:0,M=S?-1:1,w=g[f+R];for(R+=M,_=w&(1<<-P)-1,w>>=-P,P+=I;P>0;_=256*_+g[f+R],R+=M,P-=8);for(T=_&(1<<-P)-1,_>>=-P,P+=v;P>0;T=256*T+g[f+R],R+=M,P-=8);if(0===_)_=1-A;else{if(_===b)return T?NaN:1/0*(w?-1:1);T+=Math.pow(2,v),_-=A}return(w?-1:1)*T*Math.pow(2,_-v)},write=function(g,f,S,v,C,_){var T,I,b,A=8*_-C-1,P=(1<<A)-1,R=P>>1,M=23===C?Math.pow(2,-24)-Math.pow(2,-77):0,w=v?0:_-1,O=v?1:-1,D=f<0||0===f&&1/f<0?1:0;for(f=Math.abs(f),isNaN(f)||f===1/0?(I=isNaN(f)?1:0,T=P):(T=Math.floor(Math.log(f)/Math.LN2),f*(b=Math.pow(2,-T))<1&&(T--,b*=2),(f+=T+R>=1?M/b:M*Math.pow(2,1-R))*b>=2&&(T++,b/=2),T+R>=P?(I=0,T=P):T+R>=1?(I=(f*b-1)*Math.pow(2,C),T+=R):(I=f*Math.pow(2,R-1)*Math.pow(2,C),T=0));C>=8;g[S+w]=255&I,w+=O,I/=256,C-=8);for(T=T<<C|I,A+=C;A>0;g[S+w]=255&T,w+=O,T/=256,A-=8);g[S+w-O]|=128*D},cb={read:read,write:write},db=createCommonjsModule((function(g,f){const S="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;f.Buffer=Buffer,f.SlowBuffer=SlowBuffer,f.INSPECT_MAX_BYTES=50;const v=2147483647;function typedArraySupport(){try{const g=new Uint8Array(1),f={foo:function(){return 42}};return Object.setPrototypeOf(f,Uint8Array.prototype),Object.setPrototypeOf(g,f),42===g.foo()}catch(g){return!1}}function createBuffer(g){if(g>v)throw new RangeError('The value "'+g+'" is invalid for option "size"');const f=new Uint8Array(g);return Object.setPrototypeOf(f,Buffer.prototype),f}function Buffer(g,f,S){if("number"==typeof g){if("string"==typeof f)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(g)}return from(g,f,S)}function from(g,f,S){if("string"==typeof g)return fromString(g,f);if(ArrayBuffer.isView(g))return fromArrayView(g);if(null==g)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof g);if(isInstance(g,ArrayBuffer)||g&&isInstance(g.buffer,ArrayBuffer))return fromArrayBuffer(g,f,S);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(g,SharedArrayBuffer)||g&&isInstance(g.buffer,SharedArrayBuffer)))return fromArrayBuffer(g,f,S);if("number"==typeof g)throw new TypeError('The "value" argument must not be of type number. Received type number');const v=g.valueOf&&g.valueOf();if(null!=v&&v!==g)return Buffer.from(v,f,S);const C=fromObject(g);if(C)return C;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof g[Symbol.toPrimitive])return Buffer.from(g[Symbol.toPrimitive]("string"),f,S);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof g)}function assertSize(g){if("number"!=typeof g)throw new TypeError('"size" argument must be of type number');if(g<0)throw new RangeError('The value "'+g+'" is invalid for option "size"')}function alloc(g,f,S){return assertSize(g),g<=0?createBuffer(g):void 0!==f?"string"==typeof S?createBuffer(g).fill(f,S):createBuffer(g).fill(f):createBuffer(g)}function allocUnsafe(g){return assertSize(g),createBuffer(g<0?0:0|checked(g))}function fromString(g,f){if("string"==typeof f&&""!==f||(f="utf8"),!Buffer.isEncoding(f))throw new TypeError("Unknown encoding: "+f);const S=0|byteLength(g,f);let v=createBuffer(S);const C=v.write(g,f);return C!==S&&(v=v.slice(0,C)),v}function fromArrayLike(g){const f=g.length<0?0:0|checked(g.length),S=createBuffer(f);for(let v=0;v<f;v+=1)S[v]=255&g[v];return S}function fromArrayView(g){if(isInstance(g,Uint8Array)){const f=new Uint8Array(g);return fromArrayBuffer(f.buffer,f.byteOffset,f.byteLength)}return fromArrayLike(g)}function fromArrayBuffer(g,f,S){if(f<0||g.byteLength<f)throw new RangeError('"offset" is outside of buffer bounds');if(g.byteLength<f+(S||0))throw new RangeError('"length" is outside of buffer bounds');let v;return v=void 0===f&&void 0===S?new Uint8Array(g):void 0===S?new Uint8Array(g,f):new Uint8Array(g,f,S),Object.setPrototypeOf(v,Buffer.prototype),v}function fromObject(g){if(Buffer.isBuffer(g)){const f=0|checked(g.length),S=createBuffer(f);return 0===S.length||g.copy(S,0,0,f),S}return void 0!==g.length?"number"!=typeof g.length||numberIsNaN(g.length)?createBuffer(0):fromArrayLike(g):"Buffer"===g.type&&Array.isArray(g.data)?fromArrayLike(g.data):void 0}function checked(g){if(g>=v)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+v.toString(16)+" bytes");return 0|g}function SlowBuffer(g){return+g!=g&&(g=0),Buffer.alloc(+g)}function byteLength(g,f){if(Buffer.isBuffer(g))return g.length;if(ArrayBuffer.isView(g)||isInstance(g,ArrayBuffer))return g.byteLength;if("string"!=typeof g)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof g);const S=g.length,v=arguments.length>2&&!0===arguments[2];if(!v&&0===S)return 0;let C=!1;for(;;)switch(f){case"ascii":case"latin1":case"binary":return S;case"utf8":case"utf-8":return utf8ToBytes(g).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*S;case"hex":return S>>>1;case"base64":return base64ToBytes(g).length;default:if(C)return v?-1:utf8ToBytes(g).length;f=(""+f).toLowerCase(),C=!0}}function slowToString(g,f,S){let v=!1;if((void 0===f||f<0)&&(f=0),f>this.length)return"";if((void 0===S||S>this.length)&&(S=this.length),S<=0)return"";if((S>>>=0)<=(f>>>=0))return"";for(g||(g="utf8");;)switch(g){case"hex":return hexSlice(this,f,S);case"utf8":case"utf-8":return utf8Slice(this,f,S);case"ascii":return asciiSlice(this,f,S);case"latin1":case"binary":return latin1Slice(this,f,S);case"base64":return base64Slice(this,f,S);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,f,S);default:if(v)throw new TypeError("Unknown encoding: "+g);g=(g+"").toLowerCase(),v=!0}}function swap(g,f,S){const v=g[f];g[f]=g[S],g[S]=v}function bidirectionalIndexOf(g,f,S,v,C){if(0===g.length)return-1;if("string"==typeof S?(v=S,S=0):S>2147483647?S=2147483647:S<-2147483648&&(S=-2147483648),numberIsNaN(S=+S)&&(S=C?0:g.length-1),S<0&&(S=g.length+S),S>=g.length){if(C)return-1;S=g.length-1}else if(S<0){if(!C)return-1;S=0}if("string"==typeof f&&(f=Buffer.from(f,v)),Buffer.isBuffer(f))return 0===f.length?-1:arrayIndexOf(g,f,S,v,C);if("number"==typeof f)return f&=255,"function"==typeof Uint8Array.prototype.indexOf?C?Uint8Array.prototype.indexOf.call(g,f,S):Uint8Array.prototype.lastIndexOf.call(g,f,S):arrayIndexOf(g,[f],S,v,C);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(g,f,S,v,C){let _,T=1,I=g.length,b=f.length;if(void 0!==v&&("ucs2"===(v=String(v).toLowerCase())||"ucs-2"===v||"utf16le"===v||"utf-16le"===v)){if(g.length<2||f.length<2)return-1;T=2,I/=2,b/=2,S/=2}function read(g,f){return 1===T?g[f]:g.readUInt16BE(f*T)}if(C){let v=-1;for(_=S;_<I;_++)if(read(g,_)===read(f,-1===v?0:_-v)){if(-1===v&&(v=_),_-v+1===b)return v*T}else-1!==v&&(_-=_-v),v=-1}else for(S+b>I&&(S=I-b),_=S;_>=0;_--){let S=!0;for(let v=0;v<b;v++)if(read(g,_+v)!==read(f,v)){S=!1;break}if(S)return _}return-1}function hexWrite(g,f,S,v){S=Number(S)||0;const C=g.length-S;v?(v=Number(v))>C&&(v=C):v=C;const _=f.length;let T;for(v>_/2&&(v=_/2),T=0;T<v;++T){const v=parseInt(f.substr(2*T,2),16);if(numberIsNaN(v))return T;g[S+T]=v}return T}function utf8Write(g,f,S,v){return blitBuffer(utf8ToBytes(f,g.length-S),g,S,v)}function asciiWrite(g,f,S,v){return blitBuffer(asciiToBytes(f),g,S,v)}function base64Write(g,f,S,v){return blitBuffer(base64ToBytes(f),g,S,v)}function ucs2Write(g,f,S,v){return blitBuffer(utf16leToBytes(f,g.length-S),g,S,v)}function base64Slice(g,f,S){return 0===f&&S===g.length?lb.fromByteArray(g):lb.fromByteArray(g.slice(f,S))}function utf8Slice(g,f,S){S=Math.min(g.length,S);const v=[];let C=f;for(;C<S;){const f=g[C];let _=null,T=f>239?4:f>223?3:f>191?2:1;if(C+T<=S){let S,v,I,b;switch(T){case 1:f<128&&(_=f);break;case 2:S=g[C+1],128==(192&S)&&(b=(31&f)<<6|63&S,b>127&&(_=b));break;case 3:S=g[C+1],v=g[C+2],128==(192&S)&&128==(192&v)&&(b=(15&f)<<12|(63&S)<<6|63&v,b>2047&&(b<55296||b>57343)&&(_=b));break;case 4:S=g[C+1],v=g[C+2],I=g[C+3],128==(192&S)&&128==(192&v)&&128==(192&I)&&(b=(15&f)<<18|(63&S)<<12|(63&v)<<6|63&I,b>65535&&b<1114112&&(_=b))}}null===_?(_=65533,T=1):_>65535&&(_-=65536,v.push(_>>>10&1023|55296),_=56320|1023&_),v.push(_),C+=T}return decodeCodePointsArray(v)}f.kMaxLength=v,Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.buffer}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.byteOffset}}),Buffer.poolSize=8192,Buffer.from=function(g,f,S){return from(g,f,S)},Object.setPrototypeOf(Buffer.prototype,Uint8Array.prototype),Object.setPrototypeOf(Buffer,Uint8Array),Buffer.alloc=function(g,f,S){return alloc(g,f,S)},Buffer.allocUnsafe=function(g){return allocUnsafe(g)},Buffer.allocUnsafeSlow=function(g){return allocUnsafe(g)},Buffer.isBuffer=function isBuffer(g){return null!=g&&!0===g._isBuffer&&g!==Buffer.prototype},Buffer.compare=function compare(g,f){if(isInstance(g,Uint8Array)&&(g=Buffer.from(g,g.offset,g.byteLength)),isInstance(f,Uint8Array)&&(f=Buffer.from(f,f.offset,f.byteLength)),!Buffer.isBuffer(g)||!Buffer.isBuffer(f))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(g===f)return 0;let S=g.length,v=f.length;for(let C=0,_=Math.min(S,v);C<_;++C)if(g[C]!==f[C]){S=g[C],v=f[C];break}return S<v?-1:v<S?1:0},Buffer.isEncoding=function isEncoding(g){switch(String(g).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Buffer.concat=function concat(g,f){if(!Array.isArray(g))throw new TypeError('"list" argument must be an Array of Buffers');if(0===g.length)return Buffer.alloc(0);let S;if(void 0===f)for(f=0,S=0;S<g.length;++S)f+=g[S].length;const v=Buffer.allocUnsafe(f);let C=0;for(S=0;S<g.length;++S){let f=g[S];if(isInstance(f,Uint8Array))C+f.length>v.length?(Buffer.isBuffer(f)||(f=Buffer.from(f)),f.copy(v,C)):Uint8Array.prototype.set.call(v,f,C);else{if(!Buffer.isBuffer(f))throw new TypeError('"list" argument must be an Array of Buffers');f.copy(v,C)}C+=f.length}return v},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function swap16(){const g=this.length;if(g%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let f=0;f<g;f+=2)swap(this,f,f+1);return this},Buffer.prototype.swap32=function swap32(){const g=this.length;if(g%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let f=0;f<g;f+=4)swap(this,f,f+3),swap(this,f+1,f+2);return this},Buffer.prototype.swap64=function swap64(){const g=this.length;if(g%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let f=0;f<g;f+=8)swap(this,f,f+7),swap(this,f+1,f+6),swap(this,f+2,f+5),swap(this,f+3,f+4);return this},Buffer.prototype.toString=function toString(){const g=this.length;return 0===g?"":0===arguments.length?utf8Slice(this,0,g):slowToString.apply(this,arguments)},Buffer.prototype.toLocaleString=Buffer.prototype.toString,Buffer.prototype.equals=function equals(g){if(!Buffer.isBuffer(g))throw new TypeError("Argument must be a Buffer");return this===g||0===Buffer.compare(this,g)},Buffer.prototype.inspect=function inspect(){let g="";const S=f.INSPECT_MAX_BYTES;return g=this.toString("hex",0,S).replace(/(.{2})/g,"$1 ").trim(),this.length>S&&(g+=" ... "),"<Buffer "+g+">"},S&&(Buffer.prototype[S]=Buffer.prototype.inspect),Buffer.prototype.compare=function compare(g,f,S,v,C){if(isInstance(g,Uint8Array)&&(g=Buffer.from(g,g.offset,g.byteLength)),!Buffer.isBuffer(g))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof g);if(void 0===f&&(f=0),void 0===S&&(S=g?g.length:0),void 0===v&&(v=0),void 0===C&&(C=this.length),f<0||S>g.length||v<0||C>this.length)throw new RangeError("out of range index");if(v>=C&&f>=S)return 0;if(v>=C)return-1;if(f>=S)return 1;if(this===g)return 0;let _=(C>>>=0)-(v>>>=0),T=(S>>>=0)-(f>>>=0);const I=Math.min(_,T),b=this.slice(v,C),A=g.slice(f,S);for(let g=0;g<I;++g)if(b[g]!==A[g]){_=b[g],T=A[g];break}return _<T?-1:T<_?1:0},Buffer.prototype.includes=function includes(g,f,S){return-1!==this.indexOf(g,f,S)},Buffer.prototype.indexOf=function indexOf(g,f,S){return bidirectionalIndexOf(this,g,f,S,!0)},Buffer.prototype.lastIndexOf=function lastIndexOf(g,f,S){return bidirectionalIndexOf(this,g,f,S,!1)},Buffer.prototype.write=function write(g,f,S,v){if(void 0===f)v="utf8",S=this.length,f=0;else if(void 0===S&&"string"==typeof f)v=f,S=this.length,f=0;else{if(!isFinite(f))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");f>>>=0,isFinite(S)?(S>>>=0,void 0===v&&(v="utf8")):(v=S,S=void 0)}const C=this.length-f;if((void 0===S||S>C)&&(S=C),g.length>0&&(S<0||f<0)||f>this.length)throw new RangeError("Attempt to write outside buffer bounds");v||(v="utf8");let _=!1;for(;;)switch(v){case"hex":return hexWrite(this,g,f,S);case"utf8":case"utf-8":return utf8Write(this,g,f,S);case"ascii":case"latin1":case"binary":return asciiWrite(this,g,f,S);case"base64":return base64Write(this,g,f,S);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,g,f,S);default:if(_)throw new TypeError("Unknown encoding: "+v);v=(""+v).toLowerCase(),_=!0}},Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const C=4096;function decodeCodePointsArray(g){const f=g.length;if(f<=C)return String.fromCharCode.apply(String,g);let S="",v=0;for(;v<f;)S+=String.fromCharCode.apply(String,g.slice(v,v+=C));return S}function asciiSlice(g,f,S){let v="";S=Math.min(g.length,S);for(let C=f;C<S;++C)v+=String.fromCharCode(127&g[C]);return v}function latin1Slice(g,f,S){let v="";S=Math.min(g.length,S);for(let C=f;C<S;++C)v+=String.fromCharCode(g[C]);return v}function hexSlice(g,f,S){const v=g.length;(!f||f<0)&&(f=0),(!S||S<0||S>v)&&(S=v);let C="";for(let v=f;v<S;++v)C+=I[g[v]];return C}function utf16leSlice(g,f,S){const v=g.slice(f,S);let C="";for(let g=0;g<v.length-1;g+=2)C+=String.fromCharCode(v[g]+256*v[g+1]);return C}function checkOffset(g,f,S){if(g%1!=0||g<0)throw new RangeError("offset is not uint");if(g+f>S)throw new RangeError("Trying to access beyond buffer length")}function checkInt(g,f,S,v,C,_){if(!Buffer.isBuffer(g))throw new TypeError('"buffer" argument must be a Buffer instance');if(f>C||f<_)throw new RangeError('"value" argument is out of bounds');if(S+v>g.length)throw new RangeError("Index out of range")}function wrtBigUInt64LE(g,f,S,v,C){checkIntBI(f,v,C,g,S,7);let _=Number(f&BigInt(4294967295));g[S++]=_,_>>=8,g[S++]=_,_>>=8,g[S++]=_,_>>=8,g[S++]=_;let T=Number(f>>BigInt(32)&BigInt(4294967295));return g[S++]=T,T>>=8,g[S++]=T,T>>=8,g[S++]=T,T>>=8,g[S++]=T,S}function wrtBigUInt64BE(g,f,S,v,C){checkIntBI(f,v,C,g,S,7);let _=Number(f&BigInt(4294967295));g[S+7]=_,_>>=8,g[S+6]=_,_>>=8,g[S+5]=_,_>>=8,g[S+4]=_;let T=Number(f>>BigInt(32)&BigInt(4294967295));return g[S+3]=T,T>>=8,g[S+2]=T,T>>=8,g[S+1]=T,T>>=8,g[S]=T,S+8}function checkIEEE754(g,f,S,v,C,_){if(S+v>g.length)throw new RangeError("Index out of range");if(S<0)throw new RangeError("Index out of range")}function writeFloat(g,f,S,v,C){return f=+f,S>>>=0,C||checkIEEE754(g,f,S,4),cb.write(g,f,S,v,23,4),S+4}function writeDouble(g,f,S,v,C){return f=+f,S>>>=0,C||checkIEEE754(g,f,S,8),cb.write(g,f,S,v,52,8),S+8}Buffer.prototype.slice=function slice(g,f){const S=this.length;(g=~~g)<0?(g+=S)<0&&(g=0):g>S&&(g=S),(f=void 0===f?S:~~f)<0?(f+=S)<0&&(f=0):f>S&&(f=S),f<g&&(f=g);const v=this.subarray(g,f);return Object.setPrototypeOf(v,Buffer.prototype),v},Buffer.prototype.readUintLE=Buffer.prototype.readUIntLE=function readUIntLE(g,f,S){g>>>=0,f>>>=0,S||checkOffset(g,f,this.length);let v=this[g],C=1,_=0;for(;++_<f&&(C*=256);)v+=this[g+_]*C;return v},Buffer.prototype.readUintBE=Buffer.prototype.readUIntBE=function readUIntBE(g,f,S){g>>>=0,f>>>=0,S||checkOffset(g,f,this.length);let v=this[g+--f],C=1;for(;f>0&&(C*=256);)v+=this[g+--f]*C;return v},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(g,f){return g>>>=0,f||checkOffset(g,1,this.length),this[g]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(g,f){return g>>>=0,f||checkOffset(g,2,this.length),this[g]|this[g+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function readUInt16BE(g,f){return g>>>=0,f||checkOffset(g,2,this.length),this[g]<<8|this[g+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(g,f){return g>>>=0,f||checkOffset(g,4,this.length),(this[g]|this[g+1]<<8|this[g+2]<<16)+16777216*this[g+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(g,f){return g>>>=0,f||checkOffset(g,4,this.length),16777216*this[g]+(this[g+1]<<16|this[g+2]<<8|this[g+3])},Buffer.prototype.readBigUInt64LE=defineBigIntMethod((function readBigUInt64LE(g){validateNumber(g>>>=0,"offset");const f=this[g],S=this[g+7];void 0!==f&&void 0!==S||boundsError(g,this.length-8);const v=f+256*this[++g]+65536*this[++g]+this[++g]*2**24,C=this[++g]+256*this[++g]+65536*this[++g]+S*2**24;return BigInt(v)+(BigInt(C)<<BigInt(32))})),Buffer.prototype.readBigUInt64BE=defineBigIntMethod((function readBigUInt64BE(g){validateNumber(g>>>=0,"offset");const f=this[g],S=this[g+7];void 0!==f&&void 0!==S||boundsError(g,this.length-8);const v=f*2**24+65536*this[++g]+256*this[++g]+this[++g],C=this[++g]*2**24+65536*this[++g]+256*this[++g]+S;return(BigInt(v)<<BigInt(32))+BigInt(C)})),Buffer.prototype.readIntLE=function readIntLE(g,f,S){g>>>=0,f>>>=0,S||checkOffset(g,f,this.length);let v=this[g],C=1,_=0;for(;++_<f&&(C*=256);)v+=this[g+_]*C;return C*=128,v>=C&&(v-=Math.pow(2,8*f)),v},Buffer.prototype.readIntBE=function readIntBE(g,f,S){g>>>=0,f>>>=0,S||checkOffset(g,f,this.length);let v=f,C=1,_=this[g+--v];for(;v>0&&(C*=256);)_+=this[g+--v]*C;return C*=128,_>=C&&(_-=Math.pow(2,8*f)),_},Buffer.prototype.readInt8=function readInt8(g,f){return g>>>=0,f||checkOffset(g,1,this.length),128&this[g]?-1*(255-this[g]+1):this[g]},Buffer.prototype.readInt16LE=function readInt16LE(g,f){g>>>=0,f||checkOffset(g,2,this.length);const S=this[g]|this[g+1]<<8;return 32768&S?4294901760|S:S},Buffer.prototype.readInt16BE=function readInt16BE(g,f){g>>>=0,f||checkOffset(g,2,this.length);const S=this[g+1]|this[g]<<8;return 32768&S?4294901760|S:S},Buffer.prototype.readInt32LE=function readInt32LE(g,f){return g>>>=0,f||checkOffset(g,4,this.length),this[g]|this[g+1]<<8|this[g+2]<<16|this[g+3]<<24},Buffer.prototype.readInt32BE=function readInt32BE(g,f){return g>>>=0,f||checkOffset(g,4,this.length),this[g]<<24|this[g+1]<<16|this[g+2]<<8|this[g+3]},Buffer.prototype.readBigInt64LE=defineBigIntMethod((function readBigInt64LE(g){validateNumber(g>>>=0,"offset");const f=this[g],S=this[g+7];void 0!==f&&void 0!==S||boundsError(g,this.length-8);const v=this[g+4]+256*this[g+5]+65536*this[g+6]+(S<<24);return(BigInt(v)<<BigInt(32))+BigInt(f+256*this[++g]+65536*this[++g]+this[++g]*2**24)})),Buffer.prototype.readBigInt64BE=defineBigIntMethod((function readBigInt64BE(g){validateNumber(g>>>=0,"offset");const f=this[g],S=this[g+7];void 0!==f&&void 0!==S||boundsError(g,this.length-8);const v=(f<<24)+65536*this[++g]+256*this[++g]+this[++g];return(BigInt(v)<<BigInt(32))+BigInt(this[++g]*2**24+65536*this[++g]+256*this[++g]+S)})),Buffer.prototype.readFloatLE=function readFloatLE(g,f){return g>>>=0,f||checkOffset(g,4,this.length),cb.read(this,g,!0,23,4)},Buffer.prototype.readFloatBE=function readFloatBE(g,f){return g>>>=0,f||checkOffset(g,4,this.length),cb.read(this,g,!1,23,4)},Buffer.prototype.readDoubleLE=function readDoubleLE(g,f){return g>>>=0,f||checkOffset(g,8,this.length),cb.read(this,g,!0,52,8)},Buffer.prototype.readDoubleBE=function readDoubleBE(g,f){return g>>>=0,f||checkOffset(g,8,this.length),cb.read(this,g,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(g,f,S,v){if(g=+g,f>>>=0,S>>>=0,!v){checkInt(this,g,f,S,Math.pow(2,8*S)-1,0)}let C=1,_=0;for(this[f]=255&g;++_<S&&(C*=256);)this[f+_]=g/C&255;return f+S},Buffer.prototype.writeUintBE=Buffer.prototype.writeUIntBE=function writeUIntBE(g,f,S,v){if(g=+g,f>>>=0,S>>>=0,!v){checkInt(this,g,f,S,Math.pow(2,8*S)-1,0)}let C=S-1,_=1;for(this[f+C]=255&g;--C>=0&&(_*=256);)this[f+C]=g/_&255;return f+S},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,1,255,0),this[f]=255&g,f+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,2,65535,0),this[f]=255&g,this[f+1]=g>>>8,f+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,2,65535,0),this[f]=g>>>8,this[f+1]=255&g,f+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,4,4294967295,0),this[f+3]=g>>>24,this[f+2]=g>>>16,this[f+1]=g>>>8,this[f]=255&g,f+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,4,4294967295,0),this[f]=g>>>24,this[f+1]=g>>>16,this[f+2]=g>>>8,this[f+3]=255&g,f+4},Buffer.prototype.writeBigUInt64LE=defineBigIntMethod((function writeBigUInt64LE(g,f=0){return wrtBigUInt64LE(this,g,f,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeBigUInt64BE=defineBigIntMethod((function writeBigUInt64BE(g,f=0){return wrtBigUInt64BE(this,g,f,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeIntLE=function writeIntLE(g,f,S,v){if(g=+g,f>>>=0,!v){const v=Math.pow(2,8*S-1);checkInt(this,g,f,S,v-1,-v)}let C=0,_=1,T=0;for(this[f]=255&g;++C<S&&(_*=256);)g<0&&0===T&&0!==this[f+C-1]&&(T=1),this[f+C]=(g/_>>0)-T&255;return f+S},Buffer.prototype.writeIntBE=function writeIntBE(g,f,S,v){if(g=+g,f>>>=0,!v){const v=Math.pow(2,8*S-1);checkInt(this,g,f,S,v-1,-v)}let C=S-1,_=1,T=0;for(this[f+C]=255&g;--C>=0&&(_*=256);)g<0&&0===T&&0!==this[f+C+1]&&(T=1),this[f+C]=(g/_>>0)-T&255;return f+S},Buffer.prototype.writeInt8=function writeInt8(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,1,127,-128),g<0&&(g=255+g+1),this[f]=255&g,f+1},Buffer.prototype.writeInt16LE=function writeInt16LE(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,2,32767,-32768),this[f]=255&g,this[f+1]=g>>>8,f+2},Buffer.prototype.writeInt16BE=function writeInt16BE(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,2,32767,-32768),this[f]=g>>>8,this[f+1]=255&g,f+2},Buffer.prototype.writeInt32LE=function writeInt32LE(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,4,2147483647,-2147483648),this[f]=255&g,this[f+1]=g>>>8,this[f+2]=g>>>16,this[f+3]=g>>>24,f+4},Buffer.prototype.writeInt32BE=function writeInt32BE(g,f,S){return g=+g,f>>>=0,S||checkInt(this,g,f,4,2147483647,-2147483648),g<0&&(g=4294967295+g+1),this[f]=g>>>24,this[f+1]=g>>>16,this[f+2]=g>>>8,this[f+3]=255&g,f+4},Buffer.prototype.writeBigInt64LE=defineBigIntMethod((function writeBigInt64LE(g,f=0){return wrtBigUInt64LE(this,g,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeBigInt64BE=defineBigIntMethod((function writeBigInt64BE(g,f=0){return wrtBigUInt64BE(this,g,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeFloatLE=function writeFloatLE(g,f,S){return writeFloat(this,g,f,!0,S)},Buffer.prototype.writeFloatBE=function writeFloatBE(g,f,S){return writeFloat(this,g,f,!1,S)},Buffer.prototype.writeDoubleLE=function writeDoubleLE(g,f,S){return writeDouble(this,g,f,!0,S)},Buffer.prototype.writeDoubleBE=function writeDoubleBE(g,f,S){return writeDouble(this,g,f,!1,S)},Buffer.prototype.copy=function copy(g,f,S,v){if(!Buffer.isBuffer(g))throw new TypeError("argument should be a Buffer");if(S||(S=0),v||0===v||(v=this.length),f>=g.length&&(f=g.length),f||(f=0),v>0&&v<S&&(v=S),v===S)return 0;if(0===g.length||0===this.length)return 0;if(f<0)throw new RangeError("targetStart out of bounds");if(S<0||S>=this.length)throw new RangeError("Index out of range");if(v<0)throw new RangeError("sourceEnd out of bounds");v>this.length&&(v=this.length),g.length-f<v-S&&(v=g.length-f+S);const C=v-S;return this===g&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(f,S,v):Uint8Array.prototype.set.call(g,this.subarray(S,v),f),C},Buffer.prototype.fill=function fill(g,f,S,v){if("string"==typeof g){if("string"==typeof f?(v=f,f=0,S=this.length):"string"==typeof S&&(v=S,S=this.length),void 0!==v&&"string"!=typeof v)throw new TypeError("encoding must be a string");if("string"==typeof v&&!Buffer.isEncoding(v))throw new TypeError("Unknown encoding: "+v);if(1===g.length){const f=g.charCodeAt(0);("utf8"===v&&f<128||"latin1"===v)&&(g=f)}}else"number"==typeof g?g&=255:"boolean"==typeof g&&(g=Number(g));if(f<0||this.length<f||this.length<S)throw new RangeError("Out of range index");if(S<=f)return this;let C;if(f>>>=0,S=void 0===S?this.length:S>>>0,g||(g=0),"number"==typeof g)for(C=f;C<S;++C)this[C]=g;else{const _=Buffer.isBuffer(g)?g:Buffer.from(g,v),T=_.length;if(0===T)throw new TypeError('The value "'+g+'" is invalid for argument "value"');for(C=0;C<S-f;++C)this[C+f]=_[C%T]}return this};const _={};function E(g,f,S){_[g]=class extends S{constructor(){super(),Object.defineProperty(this,"message",{value:f.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${g}]`,this.stack,delete this.name}get code(){return g}set code(g){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:g,writable:!0})}toString(){return`${this.name} [${g}]: ${this.message}`}}}function addNumericalSeparator(g){let f="",S=g.length;const v="-"===g[0]?1:0;for(;S>=v+4;S-=3)f=`_${g.slice(S-3,S)}${f}`;return`${g.slice(0,S)}${f}`}function checkBounds(g,f,S){validateNumber(f,"offset"),void 0!==g[f]&&void 0!==g[f+S]||boundsError(f,g.length-(S+1))}function checkIntBI(g,f,S,v,C,T){if(g>S||g<f){const v="bigint"==typeof f?"n":"";let C;throw C=T>3?0===f||f===BigInt(0)?`>= 0${v} and < 2${v} ** ${8*(T+1)}${v}`:`>= -(2${v} ** ${8*(T+1)-1}${v}) and < 2 ** ${8*(T+1)-1}${v}`:`>= ${f}${v} and <= ${S}${v}`,new _.ERR_OUT_OF_RANGE("value",C,g)}checkBounds(v,C,T)}function validateNumber(g,f){if("number"!=typeof g)throw new _.ERR_INVALID_ARG_TYPE(f,"number",g)}function boundsError(g,f,S){if(Math.floor(g)!==g)throw validateNumber(g,S),new _.ERR_OUT_OF_RANGE(S||"offset","an integer",g);if(f<0)throw new _.ERR_BUFFER_OUT_OF_BOUNDS;throw new _.ERR_OUT_OF_RANGE(S||"offset",`>= ${S?1:0} and <= ${f}`,g)}E("ERR_BUFFER_OUT_OF_BOUNDS",(function(g){return g?`${g} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),E("ERR_INVALID_ARG_TYPE",(function(g,f){return`The "${g}" argument must be of type number. Received type ${typeof f}`}),TypeError),E("ERR_OUT_OF_RANGE",(function(g,f,S){let v=`The value of "${g}" is out of range.`,C=S;return Number.isInteger(S)&&Math.abs(S)>2**32?C=addNumericalSeparator(String(S)):"bigint"==typeof S&&(C=String(S),(S>BigInt(2)**BigInt(32)||S<-(BigInt(2)**BigInt(32)))&&(C=addNumericalSeparator(C)),C+="n"),v+=` It must be ${f}. Received ${C}`,v}),RangeError);const T=/[^+/0-9A-Za-z-_]/g;function base64clean(g){if((g=(g=g.split("=")[0]).trim().replace(T,"")).length<2)return"";for(;g.length%4!=0;)g+="=";return g}function utf8ToBytes(g,f){let S;f=f||1/0;const v=g.length;let C=null;const _=[];for(let T=0;T<v;++T){if(S=g.charCodeAt(T),S>55295&&S<57344){if(!C){if(S>56319){(f-=3)>-1&&_.push(239,191,189);continue}if(T+1===v){(f-=3)>-1&&_.push(239,191,189);continue}C=S;continue}if(S<56320){(f-=3)>-1&&_.push(239,191,189),C=S;continue}S=65536+(C-55296<<10|S-56320)}else C&&(f-=3)>-1&&_.push(239,191,189);if(C=null,S<128){if((f-=1)<0)break;_.push(S)}else if(S<2048){if((f-=2)<0)break;_.push(S>>6|192,63&S|128)}else if(S<65536){if((f-=3)<0)break;_.push(S>>12|224,S>>6&63|128,63&S|128)}else{if(!(S<1114112))throw new Error("Invalid code point");if((f-=4)<0)break;_.push(S>>18|240,S>>12&63|128,S>>6&63|128,63&S|128)}}return _}function asciiToBytes(g){const f=[];for(let S=0;S<g.length;++S)f.push(255&g.charCodeAt(S));return f}function utf16leToBytes(g,f){let S,v,C;const _=[];for(let T=0;T<g.length&&!((f-=2)<0);++T)S=g.charCodeAt(T),v=S>>8,C=S%256,_.push(C),_.push(v);return _}function base64ToBytes(g){return lb.toByteArray(base64clean(g))}function blitBuffer(g,f,S,v){let C;for(C=0;C<v&&!(C+S>=f.length||C>=g.length);++C)f[C+S]=g[C];return C}function isInstance(g,f){return g instanceof f||null!=g&&null!=g.constructor&&null!=g.constructor.name&&g.constructor.name===f.name}function numberIsNaN(g){return g!=g}const I=function(){const g="0123456789abcdef",f=new Array(256);for(let S=0;S<16;++S){const v=16*S;for(let C=0;C<16;++C)f[v+C]=g[S]+g[C]}return f}();function defineBigIntMethod(g){return"undefined"==typeof BigInt?BufferBigIntNotDefined:g}function BufferBigIntNotDefined(){throw new Error("BigInt not supported")}}));
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */const getSeatingCoordinates=(g,f)=>{const S=new Map,v=JSON.parse(uncompressSeatingData(g))?.seating;return v.forEach((g=>{const v=g?.mri,C=calculateUserBoxState({x:g?.x,y:g?.y,w:g?.w,h:g?.h},f);S.set(v,C)})),S},uncompressSeatingData=g=>{try{const f=lE.ungzip(db.Buffer.from(g,"base64"));return(new TextDecoder).decode(f)}catch(g){throw g}},calculateUserBoxState=(g,f)=>{const{sceneX:S,sceneY:v,sceneWidth:C,sceneHeight:_}=calculateAspectRatioFit(f),T=calculateOriginalSeatPosition(g.x,g.y,g.w,g.h,C,_),I=getAcsEcsConfig().calling.togetherMode.mainVideo.scaledHeightRatio,b=getAcsEcsConfig().calling.togetherMode.mainVideo.scaledWidthRatio;return{top:v+T.y+T.h*(1-I),left:S+T.x+T.w*(1-b)/JI,width:T.w*b,height:T.h*I}},calculateAspectRatioFit=g=>{const f=g.width,S=g.height,v=zI,C=Math.max(f-S*v,0)/JI,_=Math.max(S-f/v,0)/JI;return{sceneX:C,sceneY:_,sceneWidth:f-C*JI,sceneHeight:S-_*JI}},calculateOriginalSeatPosition=(g,f,S,v,C,_)=>({x:g/KI*C,y:f/KI*_,w:S/KI*C,h:v/KI*_});class TogetherModeCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new TogetherModeCallImplOverTsCall(this.eventEmitter,this.name,getAcsEcsConfig().calling.togetherMode.botId)}get name(){return"TeamsMeetingTogetherMode"}initialize(g,f){this._impl.initialize(g.tsCall,g.callAgent,g.call,g.telemetryLogManager,f)}dispose(){this._impl.dispose(),super.dispose()}on(g,f){if("togetherModeStreamsUpdated"!==g&&"togetherModeSceneUpdated"!==g&&"togetherModeSeatingUpdated"!==g)throw new CallingCommunicationError({defaultError:D.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}off(g,f){if("togetherModeStreamsUpdated"!==g&&"togetherModeSceneUpdated"!==g&&"togetherModeSeatingUpdated"!==g)throw new CallingCommunicationError({defaultError:D.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}get togetherModeStream(){return this._impl.togetherModeStream}get togetherModeSeatingMap(){return this._impl.seatingCooridnates}set sceneSize(g){this._impl.sceneSize=g}get sceneSize(){return this._impl.sceneSize}async start(){await this._impl.start()}}class TogetherModeCallImplOverTsCall extends BotStreamCommonCallFeature{constructor(g,f,S){super(f,[S]),this._eventEmitter=g,this._togetherModeBotId=S,this._lastSeatingMapData="",this._seatingCoordinates=new Map,this._dataChannelId=getAcsEcsConfig().calling.togetherMode.dataChannelId,this._supportedConversationTypes=getAcsEcsConfig().calling.togetherMode.supportedConversationTypes,this._lastdataChannelMessage={},this._botSceneSize={width:YI,height:QI}}initialize(g,f,S,v,C){"gcc"===g.region&&this.updateTogethermodeBotId(getAcsEcsConfig().calling.togetherMode.gccBotId),super.initialize(g,f,S,v,C),g.on("callStateChanged",(()=>{if(3===g.state){const f=this.isGccBotInCall();("gcc"===g.region||f)&&(this.updateTogethermodeBotId(getAcsEcsConfig().calling.togetherMode.gccBotId),f&&this.observeBotParticipantsAlreadyInCall())}})),this._dataChannelAdapter=new DataChannelAdapter(g,this._dataChannelId),this._dataChannelAdapter.on("message",(g=>{this.handleDataChannelMessageReceived(g)})),this._dataChannelAdapter.on("stateChanged",(g=>{this.handleDataChannelStateChanged(g)})),this._dataChannelAdapter.initialize(),this._sendFeatureUsage("initialize",gE.initialize)}dispose(){this._dataChannelAdapter?.off("message",(()=>{})),this._dataChannelAdapter?.off("stateChanged",(()=>{})),super.disposeAllBotStreams(),this._dataChannelAdapter?.dispose()}get togetherModeStream(){return[...this._streamIdToStreamMap.values()].map((g=>g))}get seatingCooridnates(){return this._seatingCoordinates}set sceneSize(g){this._botSceneSize=g;const f=this.decodeMessageData(this._lastdataChannelMessage?.data);this.updateSeatingCoordinatesAndEmitEvent(f?.payload,f?.eventType)}get sceneSize(){return this._botSceneSize}async start(){const g="start";try{this.validateCanStartTogetherMode()}catch(f){return this._sendFeatureUsage(g,gE.failure,f),void this._logger.error(`[${this._featureName}]: Validation failed. ${JSON.stringify(f)}`)}if(this.isTogetherModeBotInCall())this._logger.warn("Together mode is already active");else{this._sendFeatureUsage(g,gE.attempt),this._logger.info(`[${this._featureName}]: Adding together mode bot to call`);try{await this._tsCall.addParticipant(this._togetherModeBotId)}catch(f){const S=new CallingCommunicationError({defaultError:D.FEATURES.TOGETHER_MODE.ADD_TOGETHER_MODE_BOT_FAILED,originalError:f});throw this._sendFeatureUsage(g,gE.failure,S),S}const f={level:"user",type:"togetherMode",content:"{}",participantIds:[this._togetherModeBotId]};try{await this._tsCall.publishState(f,w.generateCauseId())}catch(f){const S=handlePublishStateFailure(f,D.FEATURES.TOGETHER_MODE.PUBLISH_TOGETHER_MODE_STATE_FAILED);throw this._sendFeatureUsage(g,gE.failure,S),S}this._sendFeatureUsage(g,gE.success)}}createConcreteVideoStream(g,f){return new TogetherModeVideoStreamImpl(g,this._logger,this._call,f,this._telemetryLogManager)}getStreamTypes(){return[0]}emitVideoStreamsUpdatedEvent(g){return this._eventEmitter.emit("togetherModeStreamsUpdated",g)}handleDataChannelMessageReceived(g){if(!g?.data)return;const f="messageReceived";try{this._sendFeatureUsage(f,gE.attempt),this._lastdataChannelMessage=g;const S=this.decodeMessageData(g.data);if(!S?.payload?.seating)return this._logger.info("Received data does not contain seating information. Ignoring the event"),void this._sendFeatureUsage(f,gE.success);if(S.payload.seating===this._lastSeatingMapData)return this._logger.info("Seating map data is the same as the last received data. Ignoring the event"),void this._sendFeatureUsage(f,gE.success);this._lastSeatingMapData=S.payload.seating,this.updateSeatingCoordinatesAndEmitEvent(S.payload,S.eventType),this._sendFeatureUsage(f,gE.success)}catch(g){const S=new CallingCommunicationError({defaultError:D.FEATURES.TOGETHER_MODE.SEAT_MAP_CALCULATION_FAILED,originalError:g});this._sendFeatureUsage(f,gE.failure,S)}}decodeMessageData(g){return g?JSON.parse((new TextDecoder).decode(g)):null}updateSeatingCoordinatesAndEmitEvent(g,f){if(f===XI.sceneChanged||f===XI.seatingChanged){const S=f===XI.sceneChanged?"togetherModeSceneUpdated":"togetherModeSeatingUpdated";this._seatingCoordinates=getSeatingCoordinates(g?.seating,this._botSceneSize),getAcsEcsConfig().calling.togetherMode.forceSeatMapRequest&&this.requestSeatMap(),"togetherModeSceneUpdated"===S&&this._eventEmitter.emit("togetherModeSeatingUpdated",this._seatingCoordinates),this._eventEmitter.emit(S,this._seatingCoordinates)}}validateCanStartTogetherMode(){if(!this._callAgent.isEnterpriseUser()||!getAcsEcsConfig().calling.togetherMode.enable)throw new CallingCommunicationError({defaultError:D.FEATURES.TOGETHER_MODE.UNSUPPORTED_USER_KIND});if(!this.isSupportedConversationType())throw new CallingCommunicationError({defaultError:D.FEATURES.TOGETHER_MODE.UNSUPPORTED_CONVERSATION_TYPE})}handleDataChannelStateChanged(f){f===g.DataChannelState.Started&&this.requestSeatMap()}requestSeatMap(){try{const g={eventType:"seatMapping",payload:{seqId:1}};this._dataChannelAdapter?.send((new TextEncoder).encode(JSON.stringify(g)))}catch(g){throw new CallingCommunicationError({defaultError:D.FEATURES.TOGETHER_MODE.REQUEST_INITIAL_SEAT_MAPPING_FAILED,originalError:g})}}updateTogethermodeBotId(g){this._togetherModeBotId=g,super.updateBotIds([g])}isGccBotInCall(){for(let g of this._tsCall.participants)if(g.id===getAcsEcsConfig().calling.togetherMode.gccBotId)return!0;return!1}isTogetherModeBotInCall(){for(let g of this._tsCall.participants)if(g.id===this._togetherModeBotId)return!0;return!1}isSupportedConversationType(){const g=this._tsCall.conversationType;return!!g&&!!this._supportedConversationTypes.find((f=>f===g))}_sendFeatureUsage(g,f,S){const v=S&&extractCommunicationServicesErrorForTelemetry(S);sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"TogetherMode",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:v},this._telemetryLogManager,this._logger)}}class TogetherModeVideoStreamImpl extends RemoteVideoStreamCommonImpl{constructor(g,f,S,v,C){super(g,f,S,v,C,"TogetherModeVideoStream"),this._isAvailable=!1;const handleIsAvailable=()=>{this.setIsAvailable(this.tsStream.isAvailable)};this._streamChangedHandler=this.tsStream.changed((()=>{handleIsAvailable()})),handleIsAvailable()}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}setIsAvailable(g){g!==this._isAvailable&&(this._isAvailable=!!g,this.logger.log(`isAvailable changed to ${this._isAvailable}`),this._eventEmitter.emit("isAvailableChanged",this._isAvailable),super.sendRemoteVideoStreamTelemetry())}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:"remote",isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,isAvailable:this._isAvailable,viewIdsRegistered:this.getRegisteredViewIds(),height:this._size.height,width:this._size.width,isDisposed:this._disposed}}get isAvailable(){return this._isAvailable}}class BreakoutRoomImpl{constructor(g,f,S,v,C,_,T,I){this._logger=v.createChild((()=>"BreakoutRooms")),this._logger.log("created"),this._tsCall=g,this._mainMeeting=S,this._callAgent=f,this._telemetryLogManager=_,this.state="closed",this._eventEmitter=C,this.threadId="",this._breakoutRoomsCallFeature=T,this._breakoutRoomsService=I,this._hangUpCallDelayInMilliSeconds=getAcsEcsConfig().calling.breakoutRooms.hangUpCallDelayInMilliSeconds}async join(){try{if("open"!==this.state)throw this._logger.error("Breakout room is not open."),new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.JOIN_FAILED_ROOM_CLOSED,originalError:"Cannot join the breakout room as it is closed."});return await this.holdMainMeetingCall(),await this.joinBreakoutRoomCall()}catch(g){throw this._logger.error("Breakout Room join failed",g),this._sendFeatureUsage("BreakoutRoomJoinError",gE.failure),this._logger?.error(g),g}}async returnToMainMeeting(){try{return"open"==this.state&&(this._breakoutRoomsService.isMainMeetingRejoin=!0),"Connected"===this.call?.state&&this.handleBreakoutRoomCallHangUp(this.call),this._mainMeeting.isSubscribedCall&&"None"==this._mainMeeting.state&&(await this.hangUpSubscribedCall(),await sleep(this._hangUpCallDelayInMilliSeconds)),this.isBreakoutRoomManager()?(this._logger?.info("Resuming main meeting."),await this.resumeMainMeeting()):await this.rejoinMainMeeting()}catch(g){throw this._logger.error("Rejoin main meeting failed.",g),this._sendFeatureUsage("RejoinMainMeetingError",gE.failure),new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.RETURN_TO_MAINMEETING_FAILED,originalError:g})}}async hangUp(g){null!=g&&setTimeout((()=>{this.handleBreakoutRoomCallHangUp(g)}),this._hangUpCallDelayInMilliSeconds)}async handleBreakoutRoomCallHangUp(g){"Connected"===g?.state&&await(g?.hangUp().then((()=>{this._logger.info("Breakout room call hang up success.")})).catch((g=>{throw this._logger.error("Error in hanging up the breakout room call.",g),new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.HANGUP_EXISTING_BREAKOUT_ROOM_FAILED,originalError:g})})))}getBreakoutRoomCall(g){return this._callAgent.calls.find((f=>f.id==g))}async rejoinMainMeeting(){let g;if(!this._mainMeeting.isSubscribedCall&&"Connected"===this._mainMeeting.state)throw this._logger?.error("Cannot return to  main meeting as the user is already in main meeting."),new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.ALREADY_IN_MAINMEETING,originalError:"Cannot return to main meeting as the user is already in main meeting."});return this._logger?.info("Returning to main meeting."),this._breakoutRoomsService.mainMeetingjoinLink&&(g=this._callAgent.join({meetingLink:this._breakoutRoomsService.mainMeetingjoinLink}),this._logger.info("joined mainmeeting , callId :",g.id),this._sendFeatureUsage("RejoinMainMeetingSuccess",gE.success)),Promise.resolve(g)}async joinBreakoutRoomCall(){try{if(null==this.url)throw new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.BREAKOUT_ROOM_URL_DOESNOT_EXIST,originalError:"Cannot join the breakout room as the BreakoutRoom is not created."});this.call=this._callAgent.join({meetingLink:this.url});const g={type:"join",data:this.call};this.emitBreakoutRoomsUpdated(g),this._logger.info("Joined breakout room. callId :",this.call.id),this._sendFeatureUsage("BreakoutRoomJoin",gE.success),this.call.on("stateChanged",(()=>{switch(this.call?.state){case"Disconnected":this._logger.info("Breakout room is disconnected."),!this._breakoutRoomsService.isNewBreakoutRoomAssigned&&this.hangUpSubscribedCall(),this._breakoutRoomsService.breakoutRoomCallId=void 0,this._breakoutRoomsService.breakoutRoomsCallFeatureImpl?.dispose();break;case"Connected":!this._mainMeeting.isSubscribedCall&&this.hangUpMainMeeting(),this._previousBreakoutRoomId=this._breakoutRoomsService.breakoutRoomCallId,this._breakoutRoomsService.isNewBreakoutRoomAssigned&&this._previousBreakoutRoomId&&this.hangUp(this.getBreakoutRoomCall(this._previousBreakoutRoomId)),this._breakoutRoomsService.breakoutRoomCallId=this.call.id}}))}catch(g){throw this._logger.error("Breakout room join failed",g),new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.JOIN_FAILED,originalError:g})}return Promise.resolve(this.call)}emitBreakoutRoomsUpdated(g){!this._mainMeeting.isSubscribedCall&&this._eventEmitter.emit("breakoutRoomsUpdated",g),this._mainMeeting.isSubscribedCall&&this._eventEmitter.emit("breakoutRoomsUpdatedInternal",g)}async holdMainMeetingCall(){this._mainMeeting.isSubscribedCall||"Connected"!=this._mainMeeting.state||this._mainMeeting.hold().catch((g=>{throw this._logger.error("Main meeting hold failed",g),new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.MAINMEETING_HOLD_FAILED,originalError:g})}))}async resumeMainMeeting(){try{if(this.isBreakoutRoomManager()&&(this._logger?.info("Resuming main meeting"),"LocalHold"===this._mainMeeting.state))return this._mainMeeting.resume().then((()=>{this._logger?.info("Main meeting is resumed"),this._sendFeatureUsage("MainMeetingResumeSuccess",gE.success);let g=this._callAgent.calls.find((g=>g.id==this._mainMeeting.id));if(g)return g;throw new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.MAINMEETING_RESUME_FAILED,originalError:"Main meeting call not found."})})).catch((g=>{const f=new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.MAINMEETING_RESUME_FAILED,originalError:g});throw this._logger?.error("Error in resuming main meeting",f),this._sendFeatureUsage("MainMeetingResumeError",gE.failure),f}))}catch(g){throw g}throw new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.MAINMEETING_RESUME_FAILED,originalError:"Main meeting resume failed."})}async hangUpSubscribedCall(){this._mainMeeting.isSubscribedCall&&(this._mainMeeting.on("stateChanged",(async()=>{"Disconnected"===this._mainMeeting.state&&(this._breakoutRoomsService.isNewBreakoutRoomAssigned=!1,this._mainMeeting.dispose())})),this._mainMeeting.hangUp().then((()=>{this._breakoutRoomsService.isMainMeetingRejoin=!0,this._logger?.info("Subscribed call is disconnected"),this._sendFeatureUsage("SubscribedCallHangupSuccess",gE.success)})).catch((g=>{this._logger?.error("Not able to disconnect subscribed call",g),this._sendFeatureUsage("SubscribedCallHangupError",gE.failure)})))}async hangUpMainMeeting(){try{if(!this.isBreakoutRoomManager()){let g=this._callAgent.getCallByCallId(this._mainMeeting.id);const f=g&&JSON.parse(await g.getJoinBlob()),S=f?.conversationUrl;if(!S)throw new CallingCommunicationError({defaultError:D.CALL.GET_SERVER_CALL_ID});if(g){const f={meetingUrl:S,threadId:g.threadId,callId:g.callId,participantId:g.participantId,messageId:g.messageId};this._mainMeeting.on("stateChanged",(async()=>{if("Disconnected"===this._mainMeeting.state)return this._mainMeeting.dispose(),await this.joinMainMeetingWithoutModalities(f)})),await this._mainMeeting.hangUp()}}}catch(g){this._sendFeatureUsage("MainMeetingHangupError",gE.failure),this._logger?.error("Error in hangingup main meeting ",g)}}isBreakoutRoomManager(){if(this._callAgent.isEnterpriseUser()){if(this._mainMeeting?.role==cS.Organizer||this._mainMeeting?.role==cS.Coorganizer)return!0;const g=this._callAgent.getUserMri(),f=this._tsCall.meetingDetails?.breakoutDetails?.mainMeetingProperties?.breakoutRoomManagers||this._tsCall.meetingDetails?.breakoutDetails?.breakoutRoomProperties?.breakoutRoomManagers;if(null==f||0==f?.length)return!1;return!!f.find((f=>f.id===g))}return!1}async joinMainMeetingWithoutModalities(g){this._callAgent.subscribeCallWithoutModality(g).then((g=>{if(g.isSubscribedCall=!0,this._mainMeeting=g,g){let f=this._callAgent.getCallByCallId(g.id);f&&(this._breakoutRoomsCallFeature.initialize({tsCall:f,call:g,callAgent:this._callAgent,telemetryLogManager:this._telemetryLogManager},this._logger),this._breakoutRoomsCallFeature.on("breakoutRoomsUpdatedInternal",(g=>{this._breakoutRoomsService.breakoutRoomsCallFeatureImpl?.emitBreakoutRoomsEvents(g)})))}this._logger?.info("Joined main meeting without modalities successfully"),this._sendFeatureUsage("SubscribedCallJoinSuccess",gE.success)})).catch((g=>{throw this._logger?.error("Error in joining the  main meeting without modalities",g),this._sendFeatureUsage("SubscribedCallJoinFailed",gE.failure),g}))}_sendFeatureUsage(g,f,S){let v=S?extractCommunicationServicesErrorForTelemetry(S):void 0;sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"BreakoutRooms",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:v},this._telemetryLogManager,this._logger)}}function isLongMeetingUrl(g){const f=new URL(g),S=f.pathname.split("/"),v=decodeURIComponent(S[3]);return!!(f.searchParams.get("context")??void 0)&&!!v}function isShortMeetingUrl(g,f){let S=!0;try{const f=new URL(g);if(getAcsEcsConfig().teamsMeetingShortUrlJoin.validatePattern){const g=new RegExp(getAcsEcsConfig().teamsMeetingShortUrlJoin.regexPattern);S=!!f.toString().trim().match(g)}}catch(g){f.error(`Teams Meeting url validation failed with error= ${JSON.stringify(g)}`),S=!1}return S}function isTflMeetingLink(g,f){return f.some((f=>g.includes(f.trim().toLocaleLowerCase())))}function parseLongMeetingLink(g){try{const f=new URL(g),S=f.pathname.split("/"),v=decodeURIComponent(S[3]),C=S[4],_=JSON.parse(decodeURIComponent(f.search.replace("?context=",""))),T=_.Oid;return{threadId:v,messageId:C,organizerId:T,tenantId:_.Tid}}catch(g){throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INVALID_MEETING_LINK,originalError:g})}}function base64UrlEncoding(g){let f=btoa(g).replace(/=/g,"");f=f.replace(/\+/g,"-"),f=f.replace(/\//g,"_");for(const g of f)if(g.match(/[^A-Za-z0-9-_]/))throw new CallingCommunicationError({defaultError:D.CALL.SERVER_CALL_ID});return f}class BreakoutRoomsUpdatesManagerImpl{constructor(g,f,S,v,C,_,T,I){this._autoMoveInMs=getAcsEcsConfig().calling.breakoutRooms.autoMoveInMilliSeconds,this._eventEmitter=T,this._tsCall=g,this._currentCall=S,this._telemetryLogManager=v,this._callAgent=f,this._logger=C,this._breakoutRoomsCallFeature=_,this.breakoutRoomsService=I,this.breakoutRoom=new BreakoutRoomImpl(this._tsCall,this._callAgent,this._currentCall,this._logger,T,this._telemetryLogManager,this._breakoutRoomsCallFeature,this.breakoutRoomsService)}initialize(g){g.changed((()=>{this._logger.log("tsCall changed event with breakoutroom details"),this.updateBreakoutDetails()}))}get breakoutRoomAssigned(){return this._breakoutRoomAssigned=this._breakoutRoomAssignedInternal,this._breakoutRoomAssigned}get breakoutRooms(){return this._breakoutRooms=this._breakoutRoomsInternal,this._breakoutRooms}get breakoutRoomSettings(){return this._breakoutRoomSettings=this._breakoutRoomSettingsInternal,this._breakoutRoomSettings}emitBreakoutRoomsEvents(g){this._eventEmitter.emit("breakoutRoomsUpdated",g)}updateBreakoutDetails(){try{if(this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms&&this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms.length>0){if(this.hasBreakoutRooomsAssigned(this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms[0])||this.hasBreakoutRooomsAssignmentChanged(this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms[0])){this._logger?.info("breakoutroom is assigned");const g=this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms[0]??null;if(null!=this._breakoutRoomAssignedInternal&&(this._logger?.info("New breakout room is assigned"),this.breakoutRoomsService.isNewBreakoutRoomAssigned=this._breakoutRoomAssignedInternal?.url!=g?.meetingJoinUrl,this.breakoutRoomsService.isNewBreakoutRoomAssigned&&(this.breakoutRoomsService.breakoutRoomCallId=this._breakoutRoomAssignedInternal?.call?.id)),g){this._breakoutRoomAssignedInternal=this.updateAssignedBreakoutRoomDetails(g);const f={type:"assignedBreakoutRooms",data:this.breakoutRoomAssigned};this.emitBreakoutRoomsUpdated(f)}this.canJoinBreakoutRoom()&&this.joinBreakoutRoom(),this._currentCall.isSubscribedCall&&this._breakoutRoomAssignedInternal&&!this.breakoutRoomsService.isNewBreakoutRoomAssigned&&this.breakoutRoomsService.breakoutRoomCallId&&(this._breakoutRoomAssignedInternal.call=this._callAgent.calls.find((g=>g.id===this.breakoutRoomsService.breakoutRoomCallId)),this.breakoutRoomsService.breakoutRoomCallId=void 0),this.breakoutRoomsService.isMainMeetingRejoin&&(this.breakoutRoomsService.isMainMeetingRejoin=!1)}this.hasBreakoutRoomsStateChanged(this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms[0])&&(this._logger?.info("breakoutroom state changed"),this.handleBreakoutRoomStateChanged())}if(this._breakoutRoomAssignedInternal&&null==this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms||0==this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms?.length){this._breakoutRoomAssignedInternal=void 0;const g={type:"assignedBreakoutRooms",data:this.breakoutRoomAssigned};this.emitBreakoutRoomsUpdated(g)}if(this.hasAllBreakoutRoomsAvailable(this._tsCall.breakoutDetails?.mainMeetingProperties?.allBreakoutRooms)){this._logger?.info("all breakoutrooms available"),this.parseBreakoutRooms(this._tsCall.breakoutDetails?.mainMeetingProperties?.allBreakoutRooms);const g={type:"breakoutRooms",data:this.breakoutRooms};this._eventEmitter.emit("breakoutRoomsUpdated",g)}if(this._tsCall.meetingDetails?.breakoutDetails?.breakoutRoomProperties&&this.hasbreakoutRoomSettingsAvailable(this._tsCall.meetingDetails?.breakoutDetails?.breakoutRoomProperties)||this.hasbreakoutRoomSettingsUpdated(this._tsCall.meetingDetails?.breakoutDetails?.breakoutRoomProperties)){this._logger?.info("breakoutroom settings are available"),this.updateBreakoutRoomSettings(),this.breakoutRoomsService.breakoutRoomsCallFeatureImpl=this._breakoutRoomsCallFeature;const g={type:"breakoutRoomsSettings",data:this.breakoutRoomSettings};this._currentCall.isBreakoutRoomCall=!0,this._eventEmitter.emit("breakoutRoomsUpdated",g)}}catch(g){throw this._logger.error("Could not Update Breakout details.",g),this._sendFeatureUsage("UpdateBreakoutDetails",gE.failure),new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.BREAKOUT_ROOMS_UPDATEFAILED,originalError:g})}}updateAssignedBreakoutRoomDetails(g){let f=this.breakoutRoom;return this.assignBreakoutRoomProperties(g,f),f}assignBreakoutRoomProperties(g,f){f.autoMoveParticipantToBreakoutRoom=g?.allowMoveParticipantsAutomatically,f.displayName=g?.name,f.url=g?.meetingJoinUrl,f.threadId=g?.meetingJoinUrl&&parseLongMeetingLink(g?.meetingJoinUrl)?.threadId||"",f.state=g?.isOpen?"open":"closed"}emitBreakoutRoomsUpdated(g){!this._currentCall.isSubscribedCall&&this._eventEmitter.emit("breakoutRoomsUpdated",g),this._currentCall.isSubscribedCall&&this._eventEmitter.emit("breakoutRoomsUpdatedInternal",g)}canJoinBreakoutRoom(){return"open"==this._breakoutRoomAssignedInternal?.state&&this._breakoutRoomAssignedInternal?.autoMoveParticipantToBreakoutRoom&&(this._currentCall.isSubscribedCall&&this.breakoutRoomsService.isNewBreakoutRoomAssigned||!this._currentCall.isSubscribedCall&&!this.breakoutRoomsService.isMainMeetingRejoin)}async handleBreakoutRoomStateChanged(){if(this._breakoutRoomAssignedInternal&&this._breakoutRoomAssignedInternal?.state){this._breakoutRoomAssignedInternal.state=this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms&&this._tsCall.breakoutDetails?.mainMeetingProperties?.assignedBreakoutRooms[0]?.isOpen?"open":"closed",this._logger?.info("breakoutroom state is changed to ",this._breakoutRoomAssignedInternal?.state);const g={type:"assignedBreakoutRooms",data:this.breakoutRoomAssigned};this.emitBreakoutRoomsUpdated(g),"open"===this._breakoutRoomAssignedInternal?.state&&this._breakoutRoomAssignedInternal?.autoMoveParticipantToBreakoutRoom?this.joinBreakoutRoom():"closed"===this._breakoutRoomAssignedInternal?.state&&(this.breakoutRoomsService.isMainMeetingRejoin=!1,await this._breakoutRoomAssignedInternal.hangUp(this._breakoutRoomAssignedInternal.call))}}joinBreakoutRoom(){try{this._logger?.info("joining breakout room call"),setTimeout((()=>{this._breakoutRoomAssignedInternal?.join().then((g=>{this._breakoutRoomAssignedInternal&&(this._breakoutRoomAssignedInternal.call=g),this._logger?.info("Breakout room call joined successfully")}))}),this._autoMoveInMs)}catch(g){throw this._logger?.error(g),g}}hasbreakoutRoomSettingsAvailable(g){return null!=g&&void 0===this._breakoutRoomSettingsInternal}hasbreakoutRoomSettingsUpdated(g){return null!=g&&null==this._breakoutRoomSettingsInternal||g?.roomEndTime!=this._breakoutRoomSettingsInternal?.roomEndTime||g?.additionalData?.allowJoinBackToMainMeeting!=this._breakoutRoomSettingsInternal?.disableReturnToMainMeeting}updateBreakoutRoomSettings(){this._breakoutRoomSettingsInternal={disableReturnToMainMeeting:!("true"===this._tsCall.meetingDetails?.breakoutDetails?.additionalData?.allowJoinBackToMainMeeting.toLowerCase())},this._tsCall.meetingDetails?.breakoutDetails?.breakoutRoomProperties?.roomEndTime&&(this._breakoutRoomSettingsInternal.roomEndTime=this._tsCall.meetingDetails?.breakoutDetails?.breakoutRoomProperties?.roomEndTime),this.breakoutRoomsService.mainMeetingjoinLink=this._tsCall.meetingDetails?.breakoutDetails?.breakoutRoomProperties?.mainMeetingJoinUrl}parseBreakoutRooms(g){this._breakoutRoomsInternal=g.map((g=>{let f=new BreakoutRoomImpl(this._tsCall,this._callAgent,this._currentCall,this._logger,this._eventEmitter,this._telemetryLogManager,this._breakoutRoomsCallFeature,this.breakoutRoomsService);return this.assignBreakoutRoomProperties(g,f),f.invitees=g.invitees.map((g=>constructIdentifierKindFromMri(g.id))),f}))}hasAllBreakoutRoomsAvailable(g){return!!(g?.length>0&&0==this._breakoutRoomsInternal?.length||g?.length!=this._breakoutRooms?.length||this.hasAllBreakoutRoomsPropertiesChanged(g)||this._breakoutRoomsInternal&&this._breakoutRoomsInternal?.length>0&&0==g?.length)}hasAllBreakoutRoomsPropertiesChanged(g){return!!(g&&g.length>0&&this._breakoutRooms&&this._breakoutRooms.length>0)&&g.some((g=>{const f=this._breakoutRoomsInternal?.find((f=>g.displayName===f.displayName));return!f||g.isOpen!==("open"===f.state)}))}hasBreakoutRooomsAssigned(g){return(null==this._breakoutRoomAssignedInternal?.url||""==this._breakoutRoomAssignedInternal?.url)&&void 0!==g?.meetingJoinUrl||this._breakoutRoomAssignedInternal?.displayName!=g?.name}hasBreakoutRooomsAssignmentChanged(g){return!!(this._breakoutRoomAssignedInternal?.url&&g&&void 0!==g?.meetingJoinUrl&&this._breakoutRoomAssignedInternal?.url!=g?.meetingJoinUrl||this._breakoutRoomAssignedInternal?.autoMoveParticipantToBreakoutRoom!=g?.allowMoveParticipantsAutomatically)}hasBreakoutRoomsStateChanged(g){return!(!this._breakoutRoomAssignedInternal||this.isBreakoutRoomOpen()==g.isOpen)}isBreakoutRoomOpen(){return"open"===this._breakoutRoomAssignedInternal?.state}_sendFeatureUsage(g,f,S){let v=S?extractCommunicationServicesErrorForTelemetry(S):void 0;sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"BreakoutRooms",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:v},this._telemetryLogManager,this._logger)}}class BreakoutRoomsService{constructor(g){this._eventEmitter=g}emit(g,f){!g&&this._eventEmitter.emit("breakoutRoomsUpdated",f),g&&this._eventEmitter.emit("breakoutRoomsUpdatedInternal",f)}subscribe(g){this._eventEmitter.on("breakoutRoomsUpdatedInternal",g)}static getInstance(g){return BreakoutRoomsService.instance||(BreakoutRoomsService.instance=new BreakoutRoomsService(g)),BreakoutRoomsService.instance}dispose(){BreakoutRoomsService.instance=void 0}}class BreakoutRoomsCallFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new BreakoutRoomsCallImplOverTsCall(this.eventEmitter,this),this.breakoutRoomsService=BreakoutRoomsService.getInstance(this.eventEmitter)}get name(){return"BreakoutRooms"}initialize(g,f){this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._tsCall=g.tsCall,this._impl.initialize(this._tsCall,g.callAgent,g.call,g.telemetryLogManager,f,this.breakoutRoomsService)}get assignedBreakoutRooms(){return this._impl.breakoutRoomAssigned}get breakoutRooms(){return this._impl.breakoutRooms}get breakoutRoomsSettings(){return this._impl.breakoutRoomSettings}emitBreakoutRoomsEvents(g){this._impl.emitBreakoutRoomsEvents(g)}on(g,f){this._sendFeatureUsage(g,gE.subscribe),this.eventEmitter.on(g,f)}off(g,f){this._sendFeatureUsage(g,gE.unsubscribe),this.eventEmitter.off(g,f)}_sendFeatureUsage(g,f){sendCallFeatureUsageTelemetry({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"BreakoutRooms",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}class BreakoutRoomsCallImplOverTsCall{constructor(g,f){this._isEnabled=getAcsEcsConfig().calling.breakoutRooms.enabled,this._supportedConversationTypes=getAcsEcsConfig().calling.breakoutRooms.supportedConversationTypes,this._eventEmitter=g,this._breakoutRoomsCallFeature=f}initialize(g,f,S,v,C,_){this._logger=C.createChild((()=>`BreakoutRoomsFeature::Call(id='${g.callId}')`)),this._tsCall=g,this._internalCallAgent=f;const T="initialize";if(this._breakoutRoomsImpl=new BreakoutRoomsUpdatesManagerImpl(g,f,S,v,C,this._breakoutRoomsCallFeature,this._eventEmitter,_),this._breakoutRoomsImpl._sendFeatureUsage(T,gE.attempt),!this._isEnabled){const g="Breakoutrooms feature is is disabled",f=new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.DISABLED});throw this._breakoutRoomsImpl._sendFeatureUsage(T,gE.failure,f),this._logger.error(g),f}if(3===this._tsCall.state&&!this._supportedConversationTypes.includes(g.conversationType)){const g="Breakout rooms feature is only available in meetings",f=new CallingCommunicationError({defaultError:D.FEATURES.BREAKOUT_ROOMS.ONLY_AVAILABLE_IN_MEETINGS});throw this._breakoutRoomsImpl._sendFeatureUsage(T,gE.failure,f),this._logger.error(g),f}this._breakoutRoomsImpl.initialize(this._tsCall),this._breakoutRoomsImpl._sendFeatureUsage(T,gE.success)}get breakoutRoomAssigned(){return this._breakoutRoomsImpl.breakoutRoomAssigned}get breakoutRooms(){return this._breakoutRoomsImpl.breakoutRooms}get breakoutRoomSettings(){return this._breakoutRoomsImpl.breakoutRoomSettings}emitBreakoutRoomsEvents(g){return this._breakoutRoomsImpl.emitBreakoutRoomsEvents(g)}}const hb=24,ub=3e3,gb=300,pb=2e3;var mb;!function(g){g.Initialize="initialize",g.Dispose="dispose",g.RealTimeTextReceived="realTimeTextReceived",g.SendRealTimeText="sendRealTimeText",g.StartDataChannel="startDataChannel",g.LockTimerToDataChannel="lockTimerToDataChannel",g.SendTimerToDataChannel="sendTimerToDataChannel",g.FinalizedSendRealTimeText="finalizedSendRealTimeText",g.RealTimeTextStarted="realTimeTextStarted"}(mb||(mb={}));class RealTimeTextFeatureImpl extends FirstPartyCallFeature{constructor(g){super(g),this._impl=new RealTimeTextFeatureImplOverTsCall(this.eventEmitter)}initialize(g,f){const S=generateGuid();this._logger=f,this._telemetryLogManager=g.telemetryLogManager,this._call=g.call,this._sendFeatureUsage(mb.Initialize,gE.initialize,S),this._impl.initialize(g.tsCall,g.call,g.callAgent,g.telemetryLogManager,f,S)}get name(){return"RealTimeText"}async sendRealTimeText(g,f){await this._impl.sendRealTimeText(g,f)}on(g,f){this.eventEmitter.on(g,f)}off(g,f){this.eventEmitter.off(g,f)}dispose(){this._sendFeatureUsage(mb.Dispose,gE.attempt),this.disposed?this._sendFeatureUsage(mb.Dispose,gE.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage(mb.Dispose,gE.success))}_sendFeatureUsage(g,f,S){sendCallFeatureUsageTelemetry({correlationId:S,callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f}},this._telemetryLogManager,this._logger)}}class RealTimeTextFeatureImplOverTsCall{constructor(g){this._eventEmitter=g,this._dataChannelInitialized=!1,this._firstMessageReceivedOrSent=!1,this._entries=new Map,this.sequenceId=0,this._userMri="",this._nextMessage="",this._rttSendTimerToDataChannel=()=>{const g=generateGuid();this._sendTimer=setTimeout((async()=>{this._sendFeatureUsage(mb.SendTimerToDataChannel,gE.attempt,g),this._nextMessage.includes("\n")&&this._lockTimer&&(clearTimeout(this._lockTimer),this._lockTimer=null),await this._purgeMessage(g,mb.SendTimerToDataChannel)}),gb)},this._rttLockTimerToDataChannel=()=>{const g=generateGuid();this._lockTimer&&(clearTimeout(this._lockTimer),this._lockTimer=null),this._lockTimer=setTimeout((async()=>{this._sendFeatureUsage(mb.LockTimerToDataChannel,gE.attempt,g);let f=this._entries.get(this._userMri)?.text??"";(""!==f.trim()||this._entries.get(this._userMri)&&"Final"!==this._entries.get(this._userMri)?.resultType)&&(this._nextMessage=f+"\n",await this._purgeMessage(g,mb.LockTimerToDataChannel))}),ub)},this._dataChannelHandler=g=>{let f,{sourceId:S,data:v}=g;const C=generateGuid();try{this._sendFeatureUsage(mb.RealTimeTextReceived,gE.attempt,C),f=JSON.parse(v.toString())}catch(g){try{if(void 0===this._textDecoder)throw new Error("TextDecoder undefined.");f=JSON.parse(this._textDecoder.decode(v))}catch(g){this._logger.error("Failed to parse RealTimeText message");throw new CallingCommunicationError({defaultError:D.FEATURES.REAL_TIME_TEXT.REAL_TIME_TEXT_MESSAGE_PARSE_FAILED})}try{if(f&&S){let g=f.s,v=this._participantMappingManager?.findParticipantMri(S);if(!v){throw new CallingCommunicationError({defaultError:D.FEATURES.REAL_TIME_TEXT.REAL_TIME_TEXT_MESSAGE_CONTAINS_NO_SPEAKER})}this._updateEntries(v,g),this._sendFirstMessageReceivedOrSentTelemetry(),this._sendFeatureUsage(mb.RealTimeTextReceived,gE.success,C)}}catch(g){const f=new CallingCommunicationError({originalError:g,defaultError:D.FEATURES.REAL_TIME_TEXT.REAL_TIME_TEXT_MESSAGE_HANDLER_FAILED});throw this._sendFeatureUsage(mb.RealTimeTextReceived,gE.failure,C,f),f}}},this._updateEntries=(g,f)=>{try{let S,v=this._entries.get(g),{composedText:C,isFinal:_}=this._generateRealTimeTextMessage(f,v&&"Final"!==v.resultType?v.text:"");const T=new Date,I=_?"Final":"Partial";if(v)S={...v,sequenceId:"Final"===v.resultType?this.sequenceId++:v.sequenceId,text:C,updatedTimestamp:T,resultType:I};else{const f=this._tsCall.participants.find((f=>f.id===g))?.displayName||(this._internalCallAgent.getUserMri()===g?this._internalCallAgent?.displayName:void 0);S={sequenceId:this.sequenceId++,text:C,sender:{identifier:constructIdentifierKindFromMri(g),displayName:f,endpointDetails:[]},receivedTimestamp:T,updatedTimestamp:T,resultType:I,isLocal:this._internalCallAgent.getUserMri()===g}}this._entries.set(g,S),this._eventEmitter.emit("realTimeTextReceived",this._entries.get(g)),"Final"===this._entries.get(g)?.resultType&&this._entries.delete(g)}catch(g){throw new CallingCommunicationError({originalError:g,defaultError:D.FEATURES.REAL_TIME_TEXT.REAL_TIME_TEXT_MESSAGE_ENTRY_UPDATE_FAILED})}},this._generateRealTimeTextMessage=(g,f)=>{let S=f;for(const f of g)switch(f){case"\b":S=S.slice(0,-1);break;case"\n":return{composedText:S,isFinal:!0};default:S+=f}return{composedText:S,isFinal:!1}}}initialize(g,f,S,v,C,_){this._logger=C,this._tsCall=g,this._call=f,this._internalCallAgent=S,this._telemetryLogManager=v;try{this._userMri=this._internalCallAgent.getUserMri(),this._rttDataChannelAdapter=new DataChannelAdapter(g,hb),this._participantMappingManager=new ParticipantMappingManager$1(g),this._textDecoder=new TextDecoder,this._textEncoder=new TextEncoder,this.startDataChannel(_)}catch(g){const f=new CallingCommunicationError({originalError:g,defaultError:D.FEATURES.REAL_TIME_TEXT.INITIALIZE_FAILED});throw this._sendFeatureUsage(mb.Initialize,gE.failure,_,f),f}}startDataChannel(g){try{this._rttDataChannelAdapter||(this._rttDataChannelAdapter=new DataChannelAdapter(this._tsCall,hb)),this._dataChannelInitialized||(this._rttDataChannelAdapter.initialize().then((()=>{this._dataChannelInitialized=!0})),this._rttDataChannelAdapter.off("message",this._dataChannelHandler),this._rttDataChannelAdapter.on("message",this._dataChannelHandler))}catch(f){const S=new CallingCommunicationError({originalError:f,defaultError:D.FEATURES.REAL_TIME_TEXT.START_REAL_TIME_TEXT_FAILED});throw this._sendFeatureUsage(mb.StartDataChannel,gE.failure,g,S),S}}async sendRealTimeText(g,f){const S=generateGuid();this.startDataChannel(S);let v=mb.SendRealTimeText;f&&(v=mb.FinalizedSendRealTimeText),this._sendFeatureUsage(v,gE.attempt,S);try{if(""===g&&(!this._entries.get(this._userMri)||"Final"===this._entries.get(this._userMri)?.resultType))return;if(!f&&g===this._entries.get(this._userMri)?.text)return;if(g.length>pb){throw new CallingCommunicationError({defaultError:D.FEATURES.REAL_TIME_TEXT.MESSAGE_LENGTH_EXCEEDS_MAX_INPUT_LENGTH})}this._nextMessage=f?g+="\n":g,f?(this._lockTimer&&(clearTimeout(this._lockTimer),this._lockTimer=null),this._sendTimer&&(clearTimeout(this._sendTimer),this._sendTimer=null),await this._purgeMessage(S,v)):(this._rttLockTimerToDataChannel(),this._sendTimer||this._rttSendTimerToDataChannel()),this._sendFeatureUsage(v,gE.success,S)}catch(g){const f=new CallingCommunicationError({originalError:g,defaultError:D.FEATURES.REAL_TIME_TEXT.SEND_REAL_TIME_TEXT_MESSAGE_FAILED});throw this._sendFeatureUsage(v,gE.failure,S,f),f}}async _purgeMessage(g,f){const S=encodeMessage(this._entries.get(this._userMri)?.text??"",this._nextMessage);if(""!==S){if(void 0===this._textEncoder)throw new Error("TextEncoder undefined.");let v=this._textEncoder.encode(JSON.stringify({s:S}));this._updateEntries(this._internalCallAgent.getUserMri(),S);try{await(this._rttDataChannelAdapter?.send(v)),this._sendFirstMessageReceivedOrSentTelemetry()}catch(S){const v=new CallingCommunicationError({defaultError:D.FEATURES.REAL_TIME_TEXT.SEND_DATA_CHANNEL_MESSAGE_FAILED});throw this._sendFeatureUsage(f,gE.failure,g),v}this._nextMessage="",S.includes("\n")?(this._lockTimer&&(clearTimeout(this._lockTimer),this._lockTimer=null),this._entries.delete(this._userMri)):this._rttLockTimerToDataChannel(),this._sendTimer&&(clearTimeout(this._sendTimer),this._sendTimer=null),this._sendFeatureUsage(f,gE.success,g)}}dispose(){this._textDecoder=void 0}_sendFeatureUsage(g,f,S,v){const C=v&&extractCommunicationServicesErrorForTelemetry(v);sendCallFeatureUsageTelemetry({correlationId:S,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"RealTimeText",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:g,step:f},additionalDetails:C},this._telemetryLogManager,this._logger)}_sendFirstMessageReceivedOrSentTelemetry(){this._firstMessageReceivedOrSent||(this._sendFeatureUsage(mb.RealTimeTextStarted,gE.event),this._firstMessageReceivedOrSent=!0)}}const encodeMessage=(g,f)=>{let S="";const v=Math.min(g?.length,f.length);let C=-1;for(let _=0;_<v;_++)g[_]!==f[_]&&-1===C&&(C=_),-1!==C&&(S+="\b");for(let f=v;f<g.length;f++)S+="\b";return S+=-1===C?f.substring(v):f.substring(C),S},fb={Recording:callFeatureFactory(RecordingCallFeatureImpl),Transfer:callFeatureFactory(TransferCallFeatureImpl),Transcription:callFeatureFactory(TranscriptionCallFeatureImpl),Captions:callFeatureFactory(CaptionsCallFeatureImpl),RaiseHand:callFeatureFactory(RaiseHandCallFeatureImpl),LocalRecording:callFeatureFactory(LocalRecordingCallFeatureImpl),Reaction:callFeatureFactory(ReactionFeatureImpl),Spotlight:callFeatureFactory(SpotlightCallFeatureImpl),PPTLive:callFeatureFactory(PPTLiveCallFeatureImpl),BreakoutRooms:callFeatureFactory(BreakoutRoomsCallFeatureImpl),Capabilities:callFeatureFactory(CapabilitiesFeatureImpl),DominantSpeakers:callFeatureFactory(DominantSpeakersCallFeatureImpl),LiveStream:callFeatureFactory(LiveStreamCallFeatureImpl),ComposedStream:callFeatureFactory(ComposedStreamCallFeatureImpl),CallSurvey:callFeatureFactory(CallSurveyFeatureImpl),UserFacingDiagnostics:callFeatureFactory(UserFacingDiagnosticsFeatureImpl),MediaStats:callFeatureFactory(MediaStatsCallFeatureImpl,{activationEvent:"OnExtendedObjectConstructor"}),DebugInfo:callClientFeatureFactory(DebugInfoCallClientFeatureImpl,{activationEvent:"OnExtendedObjectConstructor"}),PreCallDiagnostics:callClientFeatureFactory(PreCallDiagnosticsFeatureImpl),VideoEffects:videoStreamFeatureFactory(VideoEffectsFeatureImpl),AudioEffects:audioStreamFeatureFactory(AudioEffectsFeatureImpl),DataChannel:callFeatureFactory(DataChannelCallFeatureImpl),OptimalVideoCount:callFeatureFactory(OptimalVideoCountCallFeatureImpl),UnmixedAudio:callFeatureFactory(UnmixedAudioCallFeatureImpl),AudioZones:callFeatureFactory(AudioZonesCallFeatureImpl),TeamsMeetingAudioConferencing:callFeatureFactory(TeamsMeetingAudioConferencingCallFeatureImpl),TogetherMode:callFeatureFactory(TogetherModeCallFeatureImpl),MediaAccess:callFeatureFactory(MediaAccessCallFeatureImpl),RealTimeText:callFeatureFactory(RealTimeTextFeatureImpl)};function getRegisteredFeatures(g){switch(g){case UE.CallClientFeature:return Object.entries(fb).filter((g=>!0===g[1].isCallClientFeature)).map((g=>g[1]));case UE.CallAgentFeature:return Object.entries(fb).filter((g=>!0===g[1].isCallAgentFeature)).map((g=>g[1]));case UE.CallFeature:return Object.entries(fb).filter((g=>!0===g[1].isCallFeature)).map((g=>g[1]))}}class CallStats{constructor(g,f){this._eventBag=[],this.resetEventBag=()=>{this._eventBag=[]},this._logger=g.createChild("CallStats"),this._telemetryLogManager=f}recordEvent(g){try{if(getAcsEcsConfig()?.telemetry?.callStatsFlushTimeout<0)return;if(getAcsEcsConfig()?.telemetry?.blockedEvents?.indexOf(g.name)>-1)return;const f={timestamp:+new Date,...g};this._logger.debug(`CallStat recorded=${g.name}`),this._eventBag.push(f),this.scheduleTelemetryFlush()}catch(g){this._logger.debug("Failed to record call stats")}}flushEvents(){if(this._logger.debug(`CallStats sending telemetry, number of events=${this._eventBag.length}`),0!==this._eventBag.length)try{const g=this._eventBag.reduce(((g,f)=>(g[f.localParticipantId]?g[f.localParticipantId].events.push({name:f.name,timestamp:f.timestamp,...f.data}):g[f.localParticipantId]={callId:f.callId,localParticipantId:f.localParticipantId,events:[{name:f.name,timestamp:f.timestamp,...f.data}]},g)),{});Object.keys(g).forEach((f=>{this._telemetryLogManager.sendEvent({name:uE.acs_calling_call_stats,tenant:tf,properties:{...g[f]}})})),this.resetEventBag()}catch(g){this._logger.debug("Failed to send call stats")}}scheduleTelemetryFlush(){this._callStatSendTimeout||(this._callStatSendTimeout=window.setTimeout((()=>{this.flushEvents(),this._callStatSendTimeout=void 0}),getAcsEcsConfig().telemetry.callStatsFlushTimeout))}}function validateCallConnected(g,f){if("Connected"===f)return;let S;if(g==PS.MuteAllRemoteParticipants)S=D.CALL.MUTE_ALL_PARTICIPANTS_CALL_NOT_CONNECTED;else if(g==PS.StopAudio)S=D.CALL.STOP_AUDIO_STREAM_CALL_NOT_CONNECTED;else if(g==PS.AddParticipant)S=D.CALL.ADD_PARTICIPANT_CALL_NOT_CONNECTED;else{if(g!=PS.RemoveParticipant)return;S=D.CALL.REMOVE_PARTICIPANT_CALL_NOT_CONNECTED}throw new CallingCommunicationError({defaultError:S})}class VolumeProxy{constructor(g){this._volumeIndicator=g,this._eventEmitter=new LE}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}get level(){return this._volumeIndicator.level}async setSource(g){this._mediaStream!==g&&(this._mediaStream&&this._volumeIndicator.dispose(),g&&(this._mediaStream=g,await this._volumeIndicator.getVolumeIndicator(g),this._volumeIndicator.on("levelChanged",(()=>{this._eventEmitter.emit("levelChanged")}))))}dispose(){this._eventEmitter.removeAllListeners()}}var __decorate$a=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$a=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class RemoteAudioStreamImpl{constructor(g,S,v,C){this._workQueue=Promise.resolve();const _=f.createClientLogger("ACS-calling");this.logger=new DefaultLogger(_,[()=>"RemoteAudioStream for media stream"]),this._source=g,this._disposed=!1,this._volumeIndicator=new VolumeImpl(this.logger,"RemoteAudioStream",S,v,C),g.changed((async()=>{this._volumeProxy&&(this._workQueue=this._workQueue.then((async()=>{await(this._volumeProxy?.setSource(await this._source.getMediaStream()))})).catch((g=>{this.logger.log(`source changed but failed to update volume indicator: ${g?.message??"unknown error"}`)})))})),this.logger.info("created")}async getMediaStream(){return await this._source.getMediaStream()}get source(){return this._source}dispose(){this.logger.log("dispose"),this._disposed?this.logger.log("already disposed"):(this._volumeIndicator.dispose(),this._disposed=!0)}async getVolume(){if(!this._volumeProxy){const g=new VolumeProxy(this._volumeIndicator),f=this._workQueue.then((async()=>{await g.setSource(await this._source.getMediaStream())}));this._workQueue=f.catch(noop),await f,this._volumeProxy=g}return this._volumeProxy}}__decorate$a([loggerProperty,__metadata$a("design:type",Object)],RemoteAudioStreamImpl.prototype,"logger",void 0);var Sb=createCommonjsModule((function(g,f){!function(S,v){var C="1.0.38",_="",T="?",I="function",b="undefined",A="object",P="string",R="major",M="model",w="name",O="type",D="vendor",N="version",k="architecture",L="console",F="mobile",x="tablet",U="smarttv",V="wearable",B="embedded",H=500,$="Amazon",j="Apple",G="ASUS",q="BlackBerry",W="Browser",z="Chrome",K="Firefox",J="Google",Y="Huawei",Q="LG",X="Microsoft",Z="Motorola",ee="Opera",te="Samsung",ie="Sharp",ne="Sony",re="Xiaomi",se="Zebra",ae="Facebook",oe="Chromium OS",le="Mac OS",extend=function(g,f){var S={};for(var v in g)f[v]&&f[v].length%2==0?S[v]=f[v].concat(g[v]):S[v]=g[v];return S},enumerize=function(g){for(var f={},S=0;S<g.length;S++)f[g[S].toUpperCase()]=g[S];return f},has=function(g,f){return typeof g===P&&-1!==lowerize(f).indexOf(lowerize(g))},lowerize=function(g){return g.toLowerCase()},majorize=function(g){return typeof g===P?g.replace(/[^\d\.]/g,_).split(".")[0]:v},trim=function(g,f){if(typeof g===P)return g=g.replace(/^\s\s*/,_),typeof f===b?g:g.substring(0,H)},rgxMapper=function(g,f){for(var S,C,_,T,b,P,R=0;R<f.length&&!b;){var M=f[R],w=f[R+1];for(S=C=0;S<M.length&&!b&&M[S];)if(b=M[S++].exec(g))for(_=0;_<w.length;_++)P=b[++C],typeof(T=w[_])===A&&T.length>0?2===T.length?typeof T[1]==I?this[T[0]]=T[1].call(this,P):this[T[0]]=T[1]:3===T.length?typeof T[1]!==I||T[1].exec&&T[1].test?this[T[0]]=P?P.replace(T[1],T[2]):v:this[T[0]]=P?T[1].call(this,P,T[2]):v:4===T.length&&(this[T[0]]=P?T[3].call(this,P.replace(T[1],T[2])):v):this[T]=P||v;R+=2}},strMapper=function(g,f){for(var S in f)if(typeof f[S]===A&&f[S].length>0){for(var C=0;C<f[S].length;C++)if(has(f[S][C],g))return S===T?v:S}else if(has(f[S],g))return S===T?v:S;return g},ce={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},de={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[N,[w,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[N,[w,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[w,N],[/opios[\/ ]+([\w\.]+)/i],[N,[w,ee+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[N,[w,ee+" GX"]],[/\bopr\/([\w\.]+)/i],[N,[w,ee]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[N,[w,"Baidu"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim)\s?(?:browser)?[\/ ]?([\w\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[w,N],[/\bddg\/([\w\.]+)/i],[N,[w,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[N,[w,"UC"+W]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[N,[w,"WeChat"]],[/konqueror\/([\w\.]+)/i],[N,[w,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[N,[w,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[N,[w,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[N,[w,"Smart Lenovo "+W]],[/(avast|avg)\/([\w\.]+)/i],[[w,/(.+)/,"$1 Secure "+W],N],[/\bfocus\/([\w\.]+)/i],[N,[w,K+" Focus"]],[/\bopt\/([\w\.]+)/i],[N,[w,ee+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[N,[w,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[N,[w,"Dolphin"]],[/coast\/([\w\.]+)/i],[N,[w,ee+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[N,[w,"MIUI "+W]],[/fxios\/([-\w\.]+)/i],[N,[w,K]],[/\bqihu|(qi?ho?o?|360)browser/i],[[w,"360 "+W]],[/(oculus|sailfish|huawei|vivo)browser\/([\w\.]+)/i],[[w,/(.+)/,"$1 "+W],N],[/samsungbrowser\/([\w\.]+)/i],[N,[w,te+" Internet"]],[/(comodo_dragon)\/([\w\.]+)/i],[[w,/_/g," "],N],[/metasr[\/ ]?([\d\.]+)/i],[N,[w,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[w,"Sogou Mobile"],N],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345Explorer)[\/ ]?([\w\.]+)/i],[w,N],[/(lbbrowser)/i,/\[(linkedin)app\]/i],[w],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[w,ae],N],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[w,N],[/\bgsa\/([\w\.]+) .*safari\//i],[N,[w,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[N,[w,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[N,[w,z+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[w,z+" WebView"],N],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[N,[w,"Android "+W]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[w,N],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[N,[w,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[N,w],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[w,[N,strMapper,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[w,N],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[w,"Netscape"],N],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[N,[w,K+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[w,N],[/(cobalt)\/([\w\.]+)/i],[w,[N,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[k,"amd64"]],[/(ia32(?=;))/i],[[k,lowerize]],[/((?:i[346]|x)86)[;\)]/i],[[k,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[k,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[k,"armhf"]],[/windows (ce|mobile); ppc;/i],[[k,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[k,/ower/,_,lowerize]],[/(sun4\w)[;\)]/i],[[k,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[k,lowerize]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[M,[D,te],[O,x]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[M,[D,te],[O,F]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[M,[D,j],[O,F]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[M,[D,j],[O,x]],[/(macintosh);/i],[M,[D,j]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[M,[D,ie],[O,F]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[M,[D,Y],[O,x]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[M,[D,Y],[O,F]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[M,/_/g," "],[D,re],[O,F]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[M,/_/g," "],[D,re],[O,x]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[M,[D,"OPPO"],[O,F]],[/\b(opd2\d{3}a?) bui/i],[M,[D,"OPPO"],[O,x]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[M,[D,"Vivo"],[O,F]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[M,[D,"Realme"],[O,F]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[M,[D,Z],[O,F]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[M,[D,Z],[O,x]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[M,[D,Q],[O,x]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[M,[D,Q],[O,F]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[M,[D,"Lenovo"],[O,x]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[M,/_/g," "],[D,"Nokia"],[O,F]],[/(pixel c)\b/i],[M,[D,J],[O,x]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[M,[D,J],[O,F]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[M,[D,ne],[O,F]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[M,"Xperia Tablet"],[D,ne],[O,x]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[M,[D,"OnePlus"],[O,F]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[M,[D,$],[O,x]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[M,/(.+)/g,"Fire Phone $1"],[D,$],[O,F]],[/(playbook);[-\w\),; ]+(rim)/i],[M,D,[O,x]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[M,[D,q],[O,F]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[M,[D,G],[O,x]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[M,[D,G],[O,F]],[/(nexus 9)/i],[M,[D,"HTC"],[O,x]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[D,[M,/_/g," "],[O,F]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[M,[D,"Acer"],[O,x]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[M,[D,"Meizu"],[O,F]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[M,[D,"Ulefone"],[O,F]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[D,M,[O,F]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[D,M,[O,x]],[/(surface duo)/i],[M,[D,X],[O,x]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[M,[D,"Fairphone"],[O,F]],[/(u304aa)/i],[M,[D,"AT&T"],[O,F]],[/\bsie-(\w*)/i],[M,[D,"Siemens"],[O,F]],[/\b(rct\w+) b/i],[M,[D,"RCA"],[O,x]],[/\b(venue[\d ]{2,7}) b/i],[M,[D,"Dell"],[O,x]],[/\b(q(?:mv|ta)\w+) b/i],[M,[D,"Verizon"],[O,x]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[M,[D,"Barnes & Noble"],[O,x]],[/\b(tm\d{3}\w+) b/i],[M,[D,"NuVision"],[O,x]],[/\b(k88) b/i],[M,[D,"ZTE"],[O,x]],[/\b(nx\d{3}j) b/i],[M,[D,"ZTE"],[O,F]],[/\b(gen\d{3}) b.+49h/i],[M,[D,"Swiss"],[O,F]],[/\b(zur\d{3}) b/i],[M,[D,"Swiss"],[O,x]],[/\b((zeki)?tb.*\b) b/i],[M,[D,"Zeki"],[O,x]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[D,"Dragon Touch"],M,[O,x]],[/\b(ns-?\w{0,9}) b/i],[M,[D,"Insignia"],[O,x]],[/\b((nxa|next)-?\w{0,9}) b/i],[M,[D,"NextBook"],[O,x]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[D,"Voice"],M,[O,F]],[/\b(lvtel\-)?(v1[12]) b/i],[[D,"LvTel"],M,[O,F]],[/\b(ph-1) /i],[M,[D,"Essential"],[O,F]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[M,[D,"Envizen"],[O,x]],[/\b(trio[-\w\. ]+) b/i],[M,[D,"MachSpeed"],[O,x]],[/\btu_(1491) b/i],[M,[D,"Rotor"],[O,x]],[/(shield[\w ]+) b/i],[M,[D,"Nvidia"],[O,x]],[/(sprint) (\w+)/i],[D,M,[O,F]],[/(kin\.[onetw]{3})/i],[[M,/\./g," "],[D,X],[O,F]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[M,[D,se],[O,x]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[M,[D,se],[O,F]],[/smart-tv.+(samsung)/i],[D,[O,U]],[/hbbtv.+maple;(\d+)/i],[[M,/^/,"SmartTV"],[D,te],[O,U]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[D,Q],[O,U]],[/(apple) ?tv/i],[D,[M,j+" TV"],[O,U]],[/crkey/i],[[M,z+"cast"],[D,J],[O,U]],[/droid.+aft(\w+)( bui|\))/i],[M,[D,$],[O,U]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[M,[D,ie],[O,U]],[/(bravia[\w ]+)( bui|\))/i],[M,[D,ne],[O,U]],[/(mitv-\w{5}) bui/i],[M,[D,re],[O,U]],[/Hbbtv.*(technisat) (.*);/i],[D,M,[O,U]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[D,trim],[M,trim],[O,U]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[O,U]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[D,M,[O,L]],[/droid.+; (shield) bui/i],[M,[D,"Nvidia"],[O,L]],[/(playstation [345portablevi]+)/i],[M,[D,ne],[O,L]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[M,[D,X],[O,L]],[/((pebble))app/i],[D,M,[O,V]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[M,[D,j],[O,V]],[/droid.+; (glass) \d/i],[M,[D,J],[O,V]],[/droid.+; (wt63?0{2,3})\)/i],[M,[D,se],[O,V]],[/(quest( \d| pro)?)/i],[M,[D,ae],[O,V]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[D,[O,B]],[/(aeobc)\b/i],[M,[D,$],[O,B]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[M,[O,F]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[M,[O,x]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[O,x]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[O,F]],[/(android[-\w\. ]{0,9});.+buil/i],[M,[D,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[N,[w,"Edge"+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[N,[w,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[w,N],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[N,w]],os:[[/microsoft (windows) (vista|xp)/i],[w,N],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[w,[N,strMapper,ce]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[N,strMapper,ce],[w,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[N,/_/g,"."],[w,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[w,le],[N,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[N,w],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[w,N],[/\(bb(10);/i],[N,[w,q]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[N,[w,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[N,[w,K+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[N,[w,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[N,[w,"watchOS"]],[/crkey\/([\d\.]+)/i],[N,[w,z+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[w,oe],N],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[w,N],[/(sunos) ?([\w\.\d]*)/i],[[w,"Solaris"],N],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[w,N]]},UAParser=function(g,f){if(typeof g===A&&(f=g,g=v),!(this instanceof UAParser))return new UAParser(g,f).getResult();var C=typeof S!==b&&S.navigator?S.navigator:v,T=g||(C&&C.userAgent?C.userAgent:_),L=C&&C.userAgentData?C.userAgentData:v,U=f?extend(de,f):de,V=C&&C.userAgent==T;return this.getBrowser=function(){var g={};return g[w]=v,g[N]=v,rgxMapper.call(g,T,U.browser),g[R]=majorize(g[N]),V&&C&&C.brave&&typeof C.brave.isBrave==I&&(g[w]="Brave"),g},this.getCPU=function(){var g={};return g[k]=v,rgxMapper.call(g,T,U.cpu),g},this.getDevice=function(){var g={};return g[D]=v,g[M]=v,g[O]=v,rgxMapper.call(g,T,U.device),V&&!g[O]&&L&&L.mobile&&(g[O]=F),V&&"Macintosh"==g[M]&&C&&typeof C.standalone!==b&&C.maxTouchPoints&&C.maxTouchPoints>2&&(g[M]="iPad",g[O]=x),g},this.getEngine=function(){var g={};return g[w]=v,g[N]=v,rgxMapper.call(g,T,U.engine),g},this.getOS=function(){var g={};return g[w]=v,g[N]=v,rgxMapper.call(g,T,U.os),V&&!g[w]&&L&&L.platform&&"Unknown"!=L.platform&&(g[w]=L.platform.replace(/chrome os/i,oe).replace(/macos/i,le)),g},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 T},this.setUA=function(g){return T=typeof g===P&&g.length>H?trim(g,H):g,this},this.setUA(T),this};UAParser.VERSION=C,UAParser.BROWSER=enumerize([w,N,R]),UAParser.CPU=enumerize([k]),UAParser.DEVICE=enumerize([M,D,O,L,F,U,x,V,B]),UAParser.ENGINE=UAParser.OS=enumerize([w,N]),g.exports&&(f=g.exports=UAParser),f.UAParser=UAParser;var he=typeof S!==b&&(S.jQuery||S.Zepto);if(he&&!he.ua){var ue=new UAParser;he.ua=ue.getResult(),he.ua.get=function(){return ue.getUA()},he.ua.set=function(g){ue.setUA(g);var f=ue.getResult();for(var S in f)he.ua[S]=f[S]}}}("object"==typeof window?window:C)}));const vb=[{name:"edge",engine:"Edge",key:"Edge"},{name:"edgeanaheim",engine:"Chromium",key:"Edg"},{name:"chromium",engine:"Chromium",key:"Chromium"},{name:"opera",engine:"Chromium",key:"OPR"},{name:"yandexbrowser",engine:"Chromium",key:"YaBrowser"},{name:"electron",engine:"Chromium",key:"Electron"},{name:"chrome",engine:"Chromium",key:"Chrome"},{name:"firefox",engine:"Firefox",key:"Firefox"},{name:"safari",engine:"Safari",key:"Safari"},{name:"applewebview",engine:"Safari",key:"Mac OS X"},{name:"ie",engine:"MSIE",key:"Trident"}],Cb="0.0",yb="unknown";function getFormFactor(g){return/iPhone|iPad|iPod|Android|Mobi/i.test(g)?"Mobile":"Desktop"}function isAndroid(g){const f=!/like android/i.test(g),S=/android/i.test(g);return f&&S}let Eb=new Sb.UAParser;function getEnvironmentDetails(){Eb||(Eb=new Sb.UAParser);return Eb.getResult()}function getPlatformName(){const g=getEnvironmentDetails().ua;return-1!==g.indexOf("Edge")?"edge":-1!==g.indexOf("Electron")?"electron":-1!==g.indexOf("Chrome")?"chrome":-1!==g.indexOf("Firefox")?"firefox":-1!==g.indexOf("Safari")?"safari":-1!==g.indexOf("Mac OS X")?"applewebview":-1!==g.indexOf("Trident")?"ie":"unknown"}function updateBrowserName(g,f){return"edge"!==g&&"edgeanaheim"!==g||((f.includes("Edg/")||f.includes("EdgA/")||f.includes("EdgiOS/"))&&(g="edgeanaheim"),f.includes("Edge/")&&(g="edge")),g}function getBrowserName(g,f){const S=f.find((({key:f})=>g.includes(f)));if(!S)return yb;let v=S.name;return v=updateBrowserName(v,getEnvironmentDetails().ua),v}function updateBrowserEngine(g,f){return"ios"===getOS()&&(f="Safari"),f}function getBrowserEngine(g,f){const S=f.find((({name:f})=>f===g));if(!S)return yb;let v=S.engine;return v=updateBrowserEngine(g,v),v}function getBrowserVersion(){const g=getEnvironmentDetails();return"WebKit"===g.browser.name&&-1!==g.ua.indexOf("Mac OS X")?g.os.version??Cb:void 0!==g.browser.version?g.browser.version:Cb}function getBrowserInfo(){const g=getEnvironmentDetails(),f=g.ua,S=getBrowserName(g.browser.name,vb);return{name:S,engine:getBrowserEngine(S,vb),version:getBrowserVersion(),formFactor:getFormFactor(f)}}function getOS(){const g=getEnvironmentDetails().ua;return/windows phone/i.test(g)?"windowsphone":/windows /i.test(g)?"windows":/macintosh/i.test(g)?"mac":/(ipod|iphone|ipad)/i.test(g)?"ios":isAndroid(g)?"android":/(web|hpw)[o0]s/i.test(g)?"webos":/tizen/i.test(g)?"tizen":/headlesschrome(?:\/([\w\.]+)| )/i.test(g)?"headlesschrome":/linux/i.test(g)?"linux":/CrOS/.test(g)?"chrome":"other"}function getInternalEnvInfo(){const g=getBrowserInfo();return`${`os=${getOS()};`} ${`osVer=${getOSVersion()};`} ${`browser=${g.name};`} ${`browserVer=${g.version};`} ${`formFactor=${g.formFactor};`}`}function getOSVersion(){const g=getEnvironmentDetails();return void 0!==g.os.version?g.os.version:Cb}function isDigitMade(g){return/^\d+$/.test(g)}function checkVersionSupport(g,S){g=g.replace(/,/g,".").trim(),S=S.replace(/,/g,".").trim();let v=g.split("."),C=S.split("."),_=0;try{if(!v.every(isDigitMade)||!C.every(isDigitMade))return-2;for(;v.length<C.length;)v.push("0");for(;C.length<v.length;)C.push("0");let g=v.map(Number),f=C.map(Number);for(var T=0;T<g.length;T++)if(g[T]!==f[T]){if(g[T]>f[T])return 1;if(g[T]<f[T])return-1}}catch(g){f.AzureLogger.log(`Error in browser check version support: ${g}`)}return _}function checkOsSupport(g){let f=getAcsEcsConfig()?.environments;return!!f.hasOwnProperty(g)}function checkOsBrowserSupport(g,f){let S=getAcsEcsConfig()?.environments;return!(!checkOsSupport(g)||!S[g].hasOwnProperty(f))&&S[g][f].isSupportedOnSdkVersion}function getMinBrowserVersion(g,f){let S=getAcsEcsConfig()?.environments;return S.hasOwnProperty(g)&&S[g].hasOwnProperty(f)?S[g][f].minVersion:Cb}function getEnvironmentInfos(){let g,f,S=!1;const v=getEnvironmentDetails(),C=getOS(),_=getBrowserInfo().name,T=getBrowserInfo().version,I=checkOsSupport(C),b=checkOsBrowserSupport(C,_);if(b){checkVersionSupport(T,getMinBrowserVersion(C,_))>=0&&(S=!0)}return f={platform:v.os.name,browser:v.browser.name,browserVersion:v.browser.version},g={environment:f,isSupportedPlatform:I,isSupportedBrowser:b,isSupportedBrowserVersion:S,isSupportedEnvironment:I&&b&&S},g}var __decorate$b=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$b=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class MediaConstraintsManager{get currentVideoConstraints(){return this._currentVideoConstraints}constructor(g,f,S){this._tsCall=g,this._currentVideoConstraints={send:{frameHeight:{max:void 0},frameRate:{max:void 0},bitrate:{max:void 0}}},this._logger=f.createChild("MediaConstraintsManager"),this._telemetryLogManager=S}async setVideoConstraints(g,f,S,v){const C=this.getTelemetryPayload({video:g}),sendSuccessOrFailureTelemetryEvent=g=>{let C=g?{failureReason:g?g.message:void 0,code:g?g.code:void 0,...extractCommunicationServicesErrorForTelemetry(g)}:void 0;sendCallFeatureUsageTelemetry({correlationId:S,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"SetConstraints",featureType:"Call",initializationType:"None",timestampInfo:{deltaTimeInMs:+new Date-v},featureDetails:{name:"setConstraints",step:g?gE.failure:gE.success,stage:f},additionalDetails:{constraints:this.getTelemetryPayload({video:this._currentVideoConstraints}),...C}},this._telemetryLogManager,this._logger)};try{sendCallFeatureUsageTelemetry({correlationId:S,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"SetConstraints",featureType:"Call",initializationType:"None",timestampInfo:"",featureDetails:{name:"setConstraints",step:gE.attempt,stage:f},additionalDetails:{constraints:C}},this._telemetryLogManager,this._logger);if(!getAcsEcsConfig().calling.constraints.enabled)throw this._logger.error("Setting call constraints is disabled"),new CallingCommunicationError({defaultError:D.CALL.MEDIA_CONSTRAINTS_DISABLED});this._updateVideoConstraintsCache(g);const v={outgoingVideoLimit:{maxResolution:this._currentVideoConstraints.send?.frameHeight?.max,maxFramerate:this._currentVideoConstraints.send?.frameRate?.max,maxBitrate:this._currentVideoConstraints.send?.bitrate?.max}},_=this._tsCall.setCallConstraints?.(v);if("mid-call"!==f)_?.then((()=>{this._logger.info(`Successfully set call constraints at call ${f} - ${JSON.stringify(this._currentVideoConstraints)}`),sendSuccessOrFailureTelemetryEvent()})).catch((g=>{this._logger.error(`Error setting call constraints at call ${f}`);const S=new CallingCommunicationError({defaultError:D.CALL.SET_CONSTRAINTS_START_OR_ACCEPT,defaultErrorMessageArgs:[f],originalError:g});sendSuccessOrFailureTelemetryEvent(S)}));else try{await _,this._logger.info(`Successfully set call constraints during ${f} - ${JSON.stringify(this._currentVideoConstraints)}`),sendSuccessOrFailureTelemetryEvent()}catch(g){throw new CallingCommunicationError({defaultError:D.CALL.SET_CONSTRAINTS_MID_CALL,originalError:g})}return this._currentVideoConstraints}catch(g){const S=new CallingCommunicationError({defaultError:D.CALL.SET_CONSTRAINTS,defaultErrorMessageArgs:[f],originalError:g});throw sendSuccessOrFailureTelemetryEvent(S),S}}getTelemetryPayload(g){return{video:{send:{frameHeight:{max:g.video?.send?.frameHeight?.max},frameRate:{max:g.video?.send?.frameRate?.max},bitrate:{max:g.video?.send?.bitrate?.max}}}}}_updateVideoConstraintsCache(g){const f=getAcsEcsConfig(),S=f.calling.constraints.maxOutgoingResolution,v=f.calling.constraints.maxOutgoingFrameRate,C=f.calling.constraints.maxOutgoingVideoBitrate,_=g?.send?.frameHeight?.max??this._currentVideoConstraints.send?.frameHeight?.max,T=g?.send?.frameRate?.max??this._currentVideoConstraints.send?.frameRate?.max,I=g?.send?.bitrate?.max??this._currentVideoConstraints.send?.bitrate?.max;this._currentVideoConstraints={send:{frameHeight:{max:this._getConstraintValue(S,"maxOutgoingResolution",_)},frameRate:{max:this._getConstraintValue(v,"maxOutgoingFrameRate",T)},bitrate:{max:this._getConstraintValue(C,"maxOutgoingBitrate",I)}}}}_getConstraintValue(g,f,S){return"number"==typeof S?S<1?void this._logger.info(`Received ${f} as 0 or less, removing ${f} constraint`):(g>0&&S>g&&(this._logger.info(`${f} value ${S} is larger than ${g}, resetting to ${g}`),S=g),S):void this._logger.warn(`Received invalid ${f} value, removing ${f} constraint`)}}__decorate$b([loggerProperty,__metadata$b("design:type",Object)],MediaConstraintsManager.prototype,"_logger",void 0);var __decorate$c=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$c=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class LobbyImpl{constructor(g,f,S,v){this.logger=S.createChild("Lobby"),this._tsCall=g,this._eventEmitter=new CallingEventEmitter(this.logger),this._participants=new Map,this._call=f,this._telemetryLogManager=v,this._lobbySupportedConversationTypes=getAcsEcsConfig().calling.lobbyAdmitAndReject.supportedConversationTypes,this._isLobbyEnabled=getAcsEcsConfig().calling.lobbyAdmitAndReject.enabled,this._hasExpectedError=!1,this._isLobbyEnabled&&(this.getInLobbyParticipants(f.remoteParticipants),this._remoteParticipantUpdatedListener=g=>{if(0!==g.added.length&&g.added.forEach((g=>{"InLobby"===g.state&&this.addLobbyParticipant(g),g.on("stateChanged",(()=>{"InLobby"===g.state?this.addLobbyParticipant(g):"Connected"===g.state&&this.removeLobbyParticipant(g)}))})),0!==g.removed.length){if(0===this._call.remoteParticipants.length)return void this.removeAllLobbyParticipants();g.removed.forEach((g=>{this.removeLobbyParticipant(g)}))}},this._call.on("remoteParticipantsUpdated",this._remoteParticipantUpdatedListener))}on(g,f){if("lobbyParticipantsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.LOBBY.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("lobbyParticipantsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.LOBBY.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}async admit(g,f){if(!this._isLobbyEnabled)return void this.logger.warn("Lobby is not enabled");const S=generateGuid(),v=+new Date;this._sendLobbyAdmitAndRejectUsage("Start admit participant",pE.lobbyAdmit,S,gE.attempt,void 0);try{validateIdentifier(g),this.validateLobbyOperation(g),await this._tsCall.admitParticipant(getMriFromIdentifier(g));const f=+new Date;this._sendLobbyAdmitAndRejectUsage("Lobby participant admitted successfully",pE.lobbyAdmit,S,gE.success,f-v)}catch(g){let f=fE.Unexpected;this._hasExpectedError&&(f=fE.Expected,this._hasExpectedError=!1),this.handleLobbyAdmitAndRejectFailure("Failed to admit participant from lobby",g,S,v,pE.lobbyAdmit,f)}}async reject(g,f){if(!this._isLobbyEnabled)return void this.logger.warn("Lobby is not enabled");const S=generateGuid(),v=+new Date;this._sendLobbyAdmitAndRejectUsage("Start reject participant",pE.lobbyReject,S,gE.attempt,void 0);try{validateIdentifier(g),this.validateLobbyOperation(g),await this._tsCall.removeParticipant(getMriFromIdentifier(g));const f=+new Date;this._sendLobbyAdmitAndRejectUsage("Lobby participant rejected successfully",pE.lobbyReject,S,gE.success,f-v)}catch(g){let f=fE.Unexpected;this._hasExpectedError&&(f=fE.Expected,this._hasExpectedError=!1),this.handleLobbyAdmitAndRejectFailure("Failed to reject participant from lobby",g,S,v,pE.lobbyReject,f)}}async admitAll(g){const f=generateGuid(),S=+new Date;let v,C=0,_=0;if(!this._isLobbyEnabled)return this.logger.warn("Lobby is not enabled"),{successCount:C,failureCount:_};this._sendLobbyAdmitAndRejectUsage("Start admit all participants",pE.lobbyAdmitAll,f,gE.attempt,void 0);try{this.validateLobbyOperation(),await this._tsCall.admit({scope:"all"},w.generateCauseId()).then((g=>{if(v=g,g.result){const f=JSON.parse(g.result);C=f.successCount,_=f.failureCount}}));const g=+new Date;if(0!==_)return this._sendLobbyAdmitAndRejectUsage(`${C} participants are admitted successfully, ${_} participants admit failed. TransactionEnd: ${v}`,pE.lobbyAdmitAll,f,gE.success,g-S),{successCount:C,failureCount:_};this._sendLobbyAdmitAndRejectUsage("All participants are admitted successfully",pE.lobbyAdmitAll,f,gE.success,g-S)}catch(g){let v=fE.Unexpected;this._hasExpectedError&&(v=fE.Expected,this._hasExpectedError=!1),this.handleLobbyAdmitAndRejectFailure("Failed to admit all participants from lobby",g,f,S,pE.lobbyAdmitAll,v)}return{successCount:C,failureCount:_}}get participants(){return this._isLobbyEnabled?Array.from(this._participants.values()):(this.logger.warn("Lobby is not enabled"),[])}getInLobbyParticipants(g){g.forEach((g=>{if("InLobby"===g.state){const f=getMriFromIdentifier(g.identifier);this._participants.set(f,g)}}))}removeAllLobbyParticipants(){if(0===this._participants.size)return;const g=Array.from(this._participants.values());this._participants.clear(),this.logger.info("All participants are removed from lobby"),this._eventEmitter.emit("lobbyParticipantsUpdated",{added:[],removed:g})}removeLobbyParticipant(g){const f=getMriFromIdentifier(g.identifier);this._participants.has(f)&&(this.logger.info(`${S.getIdentifierKind(g.identifier).kind} is removed from lobby`),this._participants.delete(f),this._eventEmitter.emit("lobbyParticipantsUpdated",{added:[],removed:[g]}))}addLobbyParticipant(g){const f=getMriFromIdentifier(g.identifier);this._participants.has(f)||(this.logger.info(`${S.getIdentifierKind(g.identifier).kind} is added to lobby`),this._participants.set(f,g),this._eventEmitter.emit("lobbyParticipantsUpdated",{added:[g],removed:[]}))}validateLobbyOperation(g){const f=this._tsCall.conversationType?this._tsCall.conversationType:"oneToOneCall";if(this.logger.info("Current conversation type is: ",f),!this._lobbySupportedConversationTypes.find((g=>g===f)))throw this._hasExpectedError=!0,new CallingCommunicationError({defaultError:D.LOBBY.CONV_UNSUPPORTED});if(g){let f=this._call.remoteParticipants.find((f=>getMriFromIdentifier(f.identifier)===getMriFromIdentifier(g)));if(f&&"Connected"===f.state)throw this._hasExpectedError=!0,new CallingCommunicationError({defaultError:D.LOBBY.ALREADY_IN_MEETING,defaultErrorMessageArgs:[S.getIdentifierKind(g).kind]});if(f&&"InLobby"!==f.state||!f)throw this._hasExpectedError=!0,new CallingCommunicationError({defaultError:D.LOBBY.NOT_IN_LOBBY,defaultErrorMessageArgs:[S.getIdentifierKind(g).kind]})}if(this._call.role!==cS.Presenter&&this._call.role!==cS.Organizer&&this._call.role!==cS.Coorganizer)throw this._hasExpectedError=!0,new CallingCommunicationError({defaultError:D.LOBBY.UNAUTHORIZED_ADMIT_REJECT})}handleLobbyAdmitAndRejectFailure(g,f,S,v,C,_){const T=+new Date,I=handleLobbyFailure(this.logger,f,g);throw this._sendLobbyAdmitAndRejectUsage(I.message,C,S,gE.failure,T-v,_,f),I}_sendLobbyAdmitAndRejectUsage(g,f,S,v,C,_,T){v===gE.failure?this.logger.error(g):this.logger.info(g),this.sendLobbyAdmitAndRejectEvent({eventName:uE.acs_calling_lobby_events,callId:this._call.id,localParticipantId:this._tsCall.participantId,correlationId:S,kindOfEvent:v,operation:f,isExpected:_??"",timestampInfo:C?{deltaTimeInMs:C}:"",additionalDetails:T?{failureReason:T.message,code:T.code,subCode:T.subCode,...extractCommunicationServicesErrorForTelemetry(T)}:""})}sendLobbyAdmitAndRejectEvent(g){try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this.logger.debug("Unable to send lobby admit and reject telemetry")}}}function getMmrRdpState(){const g=window.navigator.mediaDevices;if(g?.isRemote){const f=g?.MSRDC_MMR_Shim?.remoteObjectManager?.isConnected;if(!0===f)return"connected";if(!1===f)return"disconnected"}return""}function getMMRInfo(){const g=window.navigator.mediaDevices,f={isMMREnabled:g?.isRemote??!1};return f.isMMREnabled&&(g?.mmrClientVersion&&(f.mmrClientVersion=g.mmrClientVersion),g?.mmrExtensionVersion&&(f.mmrExtensionVersion=g.mmrExtensionVersion),g?.mmrHostVersion&&(f.mmrHostVersion=g.mmrHostVersion),g?.activityId&&(f.mmrActivityId=g.activityId),g?.connectionId&&(f.mmrConnectionId=g.connectionId),f.mmrRdpState=getMmrRdpState()),f}__decorate$c([loggerProperty,__metadata$c("design:type",Object)],LobbyImpl.prototype,"logger",void 0),__decorate$c([asyncOperation(PS.LobbyAdmitParticipant),__metadata$c("design:type",Function),__metadata$c("design:paramtypes",[Object,Object]),__metadata$c("design:returntype",Promise)],LobbyImpl.prototype,"admit",null),__decorate$c([asyncOperation(PS.LobbyRejectParticipant),__metadata$c("design:type",Function),__metadata$c("design:paramtypes",[Object,Object]),__metadata$c("design:returntype",Promise)],LobbyImpl.prototype,"reject",null),__decorate$c([asyncOperation(PS.LobbyAdmitAll),__metadata$c("design:type",Function),__metadata$c("design:paramtypes",[Object]),__metadata$c("design:returntype",Promise)],LobbyImpl.prototype,"admitAll",null);class MmrRdpConnectionManager{constructor(g){this._lastState="",this._callback=g=>{const f=g?.detail?.state??"";f?f!==this._lastState&&(this._logger.info(`connection state is ${f}`),this._eventEmitter.emit("stateChange",f),this._lastState=f):this._logger.info("connection state is unknown")},this._logger=g.createChild("MmrRdpConnectionManager"),this._eventEmitter=new LE.EventEmitter;const f=window.navigator.mediaDevices;f?.isRemote&&(f?.addEventListener("rdpClientConnectionStateChanged",this._callback),this._logger.info("listener registered"))}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}get state(){return getMmrRdpState()}dispose(){const g=window.navigator.mediaDevices;g?.isRemote&&(g?.removeEventListener("rdpClientConnectionStateChanged",this._callback),this._logger.info("event listener unregistered")),this._eventEmitter.removeAllListeners()}}var __decorate$d=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$d=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class RemoteVideoStreamImpl extends RemoteVideoStreamCommonImpl{constructor(g,f,S,v,C,_,T){const I=C.id;super(g,f,S,I,_,"RemoteVideoStream"),this._remoteParticipantIdentifier=T,this._isAvailable=!1,this.setIsAvailable=g=>{g!==this._isAvailable&&(this._isAvailable=!!g,this.logger.log(`isAvailable changed to ${this._isAvailable}`),this._eventEmitter.emit("isAvailableChanged",this._isAvailable),this.call.isHandlingLargeMeetingVideoRendering&&this.call.handleDominantSpeakersVideos(),super.sendRemoteVideoStreamTelemetry())};const handleIsAvailable=()=>{if("Video"===this.mediaStreamType&&S.isHandlingLargeMeetingVideoRendering){for(const g of S.getTopNDominantSpeakersWithVideoOn())if(this.tsStream.isAvailable&&getMriFromIdentifier(g.identifier)===getMriFromIdentifier(this._remoteParticipantIdentifier))return void this.setIsAvailable(!0);this.setIsAvailable(!1)}else 7!==C.state?(3===C.state&&b.dispose(),this.setIsAvailable(this.tsStream.isAvailable)):this.setIsAvailable(!1)};this._streamChangedHandler=this.tsStream.changed((()=>{handleIsAvailable()}));const b=C.changed((()=>{handleIsAvailable()}));handleIsAvailable()}on(g,f){if("isAvailableChanged"!==g&&"sizeChanged"!==g&&"isReceivingChanged"!==g)throw new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("isAvailableChanged"!==g&&"sizeChanged"!==g&&"isReceivingChanged"!==g)throw new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}get isAvailable(){return this._isAvailable}async getMediaStream(){const g=generateGuid(),f=+new Date,S={correlationId:g,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId},operation:PE.getMediaStream,mediaType:this.getMediaType(),streamType:AE.Remote,timestampInfo:{attemptTimestamp:f},kindOfEvent:gE.attempt,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};this.sendMediaStreamEvent(S);try{if(!this.tsStream.getRawStream)throw new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.GET_RAW_MEDIA_STREAM});if(!this.tsStream.isAvailable)throw new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.RAWMEDIA_LVS_NOT_AVAILABLE});const S=this.tsStream.getRawStream(),v=new Promise((async(g,f)=>{const v=setTimeout((()=>{C.dispose(),f(new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.SUBSCRIBE_MEDIA_STREAM_TIMEOUT}))}),getAcsEcsConfig().rendering.remoteVideo.getMediaStreamTimeout),C=S.changed((()=>{tryToResolveGetStreamPromise()})),tryToResolveGetStreamPromise=async()=>{try{const f=await S.getMediaStream();if(!f)return void this.logger.warn("MediaStream is not yet ready.");clearTimeout(v),C.dispose(),g(f)}catch(g){this.logger.warn(`MediaStream is not yet ready, error=${g?.message||"unknown"}`)}};tryToResolveGetStreamPromise()})),C=await v,_=C.getVideoTracks()[0];if(!_)throw new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.GET_TRACK});const T=new Promise(((g,f)=>{const resolveUnmutedPromise=()=>{_.removeEventListener("unmute",resolveUnmutedPromise,!1),g()};_.addEventListener("unmute",resolveUnmutedPromise,!1),_.muted?setTimeout((()=>{_.removeEventListener("unmute",resolveUnmutedPromise,!1),f(new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.TRACK_UNMUTED_TIMEOUT}))}),getAcsEcsConfig().rendering.remoteVideo.getMediaStreamTimeout):resolveUnmutedPromise()}));await T;const I={correlationId:g,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId},operation:PE.getMediaStream,mediaType:this.getMediaType(),streamType:AE.Remote,timestampInfo:{deltaTimeInMs:+new Date-f},kindOfEvent:gE.success,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};return this.sendMediaStreamEvent(I),C}catch(S){const v={correlationId:g,operation:PE.getMediaStream,mediaType:this.getMediaType(),streamType:AE.Remote,additionalDetails:{failureReason:S?.message||"",code:S.code||U,...extractCommunicationServicesErrorForTelemetry(S),remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId},timestampInfo:{deltaTimeInMs:+new Date-f},kindOfEvent:gE.failure,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};throw this.sendMediaStreamEvent(v),new CallingCommunicationError({defaultError:D.REMOTE_VIDEO_STREAM.GET_MEDIA_STREAM,originalError:S})}}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:"remote",rank:this.tsStream.rank,isAvailable:this.tsStream.isAvailable,acsIsAvailable:this._isAvailable,isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this._renderers.map((g=>g.viewId)).join(", "),height:this._size.height,width:this._size.width,isDisposed:this._disposed,optimalVideoCount:this.call?.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:this.call?.activeRemoteVideoStreamViews?.size||0}}dispose(){this.setIsAvailable(!1),super.dispose()}getMediaType(){return"ScreenSharing"===this.mediaStreamType?bE.ScreenSharingRaw:bE.VideoRaw}sendMediaStreamEvent(g){this.telemetryLogManager.sendEvent({name:uE.acs_calling_media_stream,tenant:tf,properties:{timestampInfo:g.timestampInfo,correlationId:g.correlationId,additionalDetails:g.additionalDetails||"",kindOfEvent:g.kindOfEvent||"",mediaType:g.mediaType,streamType:g.streamType,operation:g.operation,localParticipantId:g.localParticipantId||"",callId:g.callId||""}})}}__decorate$d([asyncOperation(xS.GetMediaStream),__metadata$d("design:type",Function),__metadata$d("design:paramtypes",[]),__metadata$d("design:returntype",Promise)],RemoteVideoStreamImpl.prototype,"getMediaStream",null);const _b={2:"#050505",4:"#0a0a0a",6:"#0f0f0f",8:"#141414",10:"#1a1a1a",12:"#1f1f1f",14:"#242424",16:"#292929",18:"#2e2e2e",20:"#333333",22:"#383838",24:"#3d3d3d",26:"#424242",28:"#474747",30:"#4d4d4d",32:"#525252",34:"#575757",36:"#5c5c5c",38:"#616161",40:"#666666",42:"#6b6b6b",44:"#707070",46:"#757575",48:"#7a7a7a",50:"#808080",52:"#858585",54:"#8a8a8a",56:"#8f8f8f",58:"#949494",60:"#999999",62:"#9e9e9e",64:"#a3a3a3",66:"#a8a8a8",68:"#adadad",70:"#b3b3b3",72:"#b8b8b8",74:"#bdbdbd",76:"#c2c2c2",78:"#c7c7c7",80:"#cccccc",82:"#d1d1d1",84:"#d6d6d6",86:"#dbdbdb",88:"#e0e0e0",90:"#e6e6e6",92:"#ebebeb",94:"#f0f0f0",96:"#f5f5f5",98:"#fafafa"},Tb={5:"rgba(255, 255, 255, 0.05)",10:"rgba(255, 255, 255, 0.1)",20:"rgba(255, 255, 255, 0.2)",30:"rgba(255, 255, 255, 0.3)",40:"rgba(255, 255, 255, 0.4)",50:"rgba(255, 255, 255, 0.5)",60:"rgba(255, 255, 255, 0.6)",70:"rgba(255, 255, 255, 0.7)",80:"rgba(255, 255, 255, 0.8)",90:"rgba(255, 255, 255, 0.9)"},Ib={5:"rgba(0, 0, 0, 0.05)",10:"rgba(0, 0, 0, 0.1)",20:"rgba(0, 0, 0, 0.2)",30:"rgba(0, 0, 0, 0.3)",40:"rgba(0, 0, 0, 0.4)",50:"rgba(0, 0, 0, 0.5)",60:"rgba(0, 0, 0, 0.6)",70:"rgba(0, 0, 0, 0.7)",80:"rgba(0, 0, 0, 0.8)",90:"rgba(0, 0, 0, 0.9)"},bb="#ffffff",Ab="#000000",Pb={shade50:"#200205",shade40:"#3b0509",shade30:"#6e0811",shade20:"#960b18",shade10:"#b10e1c",primary:"#c50f1f",tint10:"#cc2635",tint20:"#d33f4c",tint30:"#dc626d",tint40:"#eeacb2",tint50:"#f6d1d5",tint60:"#fdf3f4"},Rb={shade50:"#031403",shade40:"#052505",shade30:"#094509",shade20:"#0c5e0c",shade10:"#0e700e",primary:"#107c10",tint10:"#218c21",tint20:"#359b35",tint30:"#54b054",tint40:"#9fd89f",tint50:"#c9eac9",tint60:"#f1faf1"},Mb={red:{shade50:"#210809",shade40:"#3f1011",shade30:"#751d1f",shade20:"#9f282b",shade10:"#bc2f32",primary:"#d13438",tint10:"#d7494c",tint20:"#dc5e62",tint30:"#e37d80",tint40:"#f1bbbc",tint50:"#f8dadb",tint60:"#fdf6f6"},green:Rb,darkOrange:{shade50:"#230900",shade40:"#411200",shade30:"#7a2101",shade20:"#a62d01",shade10:"#c43501",primary:"#da3b01",tint10:"#de501c",tint20:"#e36537",tint30:"#e9835e",tint40:"#f4bfab",tint50:"#f9dcd1",tint60:"#fdf6f3"},yellow:{shade50:"#282400",shade40:"#4c4400",shade30:"#817400",shade20:"#c0ad00",shade10:"#e4cc00",primary:"#fde300",tint10:"#fde61e",tint20:"#fdea3d",tint30:"#feee66",tint40:"#fef7b2",tint50:"#fffad6",tint60:"#fffef5"},berry:{shade50:"#1f091d",shade40:"#3a1136",shade30:"#6d2064",shade20:"#932b88",shade10:"#af33a1",primary:"#c239b3",tint10:"#c94cbc",tint20:"#d161c4",tint30:"#da7ed0",tint40:"#edbbe7",tint50:"#f5daf2",tint60:"#fdf5fc"},lightGreen:{shade50:"#031a02",shade40:"#063004",shade30:"#0b5a08",shade20:"#0e7a0b",shade10:"#11910d",primary:"#13a10e",tint10:"#27ac22",tint20:"#3db838",tint30:"#5ec75a",tint40:"#a7e3a5",tint50:"#cef0cd",tint60:"#f2fbf2"},marigold:{shade50:"#251a00",shade40:"#463100",shade30:"#835b00",shade20:"#b27c00",shade10:"#d39300",primary:"#eaa300",tint10:"#edad1c",tint20:"#efb839",tint30:"#f2c661",tint40:"#f9e2ae",tint50:"#fcefd3",tint60:"#fefbf4"}},wb={darkRed:{shade50:"#130204",shade40:"#230308",shade30:"#420610",shade20:"#590815",shade10:"#690a19",primary:"#750b1c",tint10:"#861b2c",tint20:"#962f3f",tint30:"#ac4f5e",tint40:"#d69ca5",tint50:"#e9c7cd",tint60:"#f9f0f2"},cranberry:Pb,pumpkin:{shade50:"#200d03",shade40:"#3d1805",shade30:"#712d09",shade20:"#9a3d0c",shade10:"#b6480e",primary:"#ca5010",tint10:"#d06228",tint20:"#d77440",tint30:"#df8e64",tint40:"#efc4ad",tint50:"#f7dfd2",tint60:"#fdf7f4"},peach:{shade50:"#291600",shade40:"#4d2a00",shade30:"#8f4e00",shade20:"#c26a00",shade10:"#e67e00",primary:"#ff8c00",tint10:"#ff9a1f",tint20:"#ffa83d",tint30:"#ffba66",tint40:"#ffddb3",tint50:"#ffedd6",tint60:"#fffaf5"},gold:{shade50:"#1f1900",shade40:"#3a2f00",shade30:"#6c5700",shade20:"#937700",shade10:"#ae8c00",primary:"#c19c00",tint10:"#c8a718",tint20:"#d0b232",tint30:"#dac157",tint40:"#ecdfa5",tint50:"#f5eece",tint60:"#fdfbf2"},brass:{shade50:"#181202",shade40:"#2e2103",shade30:"#553e06",shade20:"#745408",shade10:"#89640a",primary:"#986f0b",tint10:"#a47d1e",tint20:"#b18c34",tint30:"#c1a256",tint40:"#e0cea2",tint50:"#efe4cb",tint60:"#fbf8f2"},brown:{shade50:"#170e07",shade40:"#2b1a0e",shade30:"#50301a",shade20:"#6c4123",shade10:"#804d29",primary:"#8e562e",tint10:"#9c663f",tint20:"#a97652",tint30:"#bb8f6f",tint40:"#ddc3b0",tint50:"#edded3",tint60:"#faf7f4"},forest:{shade50:"#0c1501",shade40:"#162702",shade30:"#294903",shade20:"#376304",shade10:"#427505",primary:"#498205",tint10:"#599116",tint20:"#6ba02b",tint30:"#85b44c",tint40:"#bdd99b",tint50:"#dbebc7",tint60:"#f6faf0"},seafoam:{shade50:"#002111",shade40:"#003d20",shade30:"#00723b",shade20:"#009b51",shade10:"#00b85f",primary:"#00cc6a",tint10:"#19d279",tint20:"#34d889",tint30:"#5ae0a0",tint40:"#a8f0cd",tint50:"#cff7e4",tint60:"#f3fdf8"},darkGreen:{shade50:"#021102",shade40:"#032003",shade30:"#063b06",shade20:"#085108",shade10:"#0a5f0a",primary:"#0b6a0b",tint10:"#1a7c1a",tint20:"#2d8e2d",tint30:"#4da64d",tint40:"#9ad29a",tint50:"#c6e7c6",tint60:"#f0f9f0"},lightTeal:{shade50:"#001d1f",shade40:"#00373a",shade30:"#00666d",shade20:"#008b94",shade10:"#00a5af",primary:"#00b7c3",tint10:"#18bfca",tint20:"#32c8d1",tint30:"#58d3db",tint40:"#a6e9ed",tint50:"#cef3f5",tint60:"#f2fcfd"},teal:{shade50:"#001516",shade40:"#012728",shade30:"#02494c",shade20:"#026467",shade10:"#037679",primary:"#038387",tint10:"#159195",tint20:"#2aa0a4",tint30:"#4cb4b7",tint40:"#9bd9db",tint50:"#c7ebec",tint60:"#f0fafa"},steel:{shade50:"#000f12",shade40:"#001b22",shade30:"#00333f",shade20:"#004555",shade10:"#005265",primary:"#005b70",tint10:"#0f6c81",tint20:"#237d92",tint30:"#4496a9",tint40:"#94c8d4",tint50:"#c3e1e8",tint60:"#eff7f9"},blue:{shade50:"#001322",shade40:"#002440",shade30:"#004377",shade20:"#005ba1",shade10:"#006cbf",primary:"#0078d4",tint10:"#1a86d9",tint20:"#3595de",tint30:"#5caae5",tint40:"#a9d3f2",tint50:"#d0e7f8",tint60:"#f3f9fd"},royalBlue:{shade50:"#000c16",shade40:"#00172a",shade30:"#002c4e",shade20:"#003b6a",shade10:"#00467e",primary:"#004e8c",tint10:"#125e9a",tint20:"#286fa8",tint30:"#4a89ba",tint40:"#9abfdc",tint50:"#c7dced",tint60:"#f0f6fa"},cornflower:{shade50:"#0d1126",shade40:"#182047",shade30:"#2c3c85",shade20:"#3c51b4",shade10:"#4760d5",primary:"#4f6bed",tint10:"#637cef",tint20:"#778df1",tint30:"#93a4f4",tint40:"#c8d1fa",tint50:"#e1e6fc",tint60:"#f7f9fe"},navy:{shade50:"#00061d",shade40:"#000c36",shade30:"#001665",shade20:"#001e89",shade10:"#0023a2",primary:"#0027b4",tint10:"#173bbd",tint20:"#3050c6",tint30:"#546fd2",tint40:"#a3b2e8",tint50:"#ccd5f3",tint60:"#f2f4fc"},lavender:{shade50:"#120f25",shade40:"#221d46",shade30:"#3f3682",shade20:"#5649b0",shade10:"#6656d1",primary:"#7160e8",tint10:"#8172eb",tint20:"#9184ee",tint30:"#a79cf1",tint40:"#d2ccf8",tint50:"#e7e4fb",tint60:"#f9f8fe"},purple:{shade50:"#0f0717",shade40:"#1c0e2b",shade30:"#341a51",shade20:"#46236e",shade10:"#532982",primary:"#5c2e91",tint10:"#6b3f9e",tint20:"#7c52ab",tint30:"#9470bd",tint40:"#c6b1de",tint50:"#e0d3ed",tint60:"#f7f4fb"},grape:{shade50:"#160418",shade40:"#29072e",shade30:"#4c0d55",shade20:"#671174",shade10:"#7a1589",primary:"#881798",tint10:"#952aa4",tint20:"#a33fb1",tint30:"#b55fc1",tint40:"#d9a7e0",tint50:"#eaceef",tint60:"#faf2fb"},lilac:{shade50:"#1c0b1f",shade40:"#35153a",shade30:"#63276d",shade20:"#863593",shade10:"#9f3faf",primary:"#b146c2",tint10:"#ba58c9",tint20:"#c36bd1",tint30:"#cf87da",tint40:"#e6bfed",tint50:"#f2dcf5",tint60:"#fcf6fd"},pink:{shade50:"#24091b",shade40:"#441232",shade30:"#80215d",shade20:"#ad2d7e",shade10:"#cd3595",primary:"#e43ba6",tint10:"#e750b0",tint20:"#ea66ba",tint30:"#ef85c8",tint40:"#f7c0e3",tint50:"#fbddf0",tint60:"#fef6fb"},magenta:{shade50:"#1f0013",shade40:"#390024",shade30:"#6b0043",shade20:"#91005a",shade10:"#ac006b",primary:"#bf0077",tint10:"#c71885",tint20:"#ce3293",tint30:"#d957a8",tint40:"#eca5d1",tint50:"#f5cee6",tint60:"#fcf2f9"},plum:{shade50:"#13000c",shade40:"#240017",shade30:"#43002b",shade20:"#5a003b",shade10:"#6b0045",primary:"#77004d",tint10:"#87105d",tint20:"#98246f",tint30:"#ad4589",tint40:"#d696c0",tint50:"#e9c4dc",tint60:"#faf0f6"},beige:{shade50:"#141313",shade40:"#252323",shade30:"#444241",shade20:"#5d5958",shade10:"#6e6968",primary:"#7a7574",tint10:"#8a8584",tint20:"#9a9594",tint30:"#afabaa",tint40:"#d7d4d4",tint50:"#eae8e8",tint60:"#faf9f9"},mink:{shade50:"#0f0e0e",shade40:"#1c1b1a",shade30:"#343231",shade20:"#474443",shade10:"#54514f",primary:"#5d5a58",tint10:"#706d6b",tint20:"#84817e",tint30:"#9e9b99",tint40:"#cecccb",tint50:"#e5e4e3",tint60:"#f8f8f8"},platinum:{shade50:"#111314",shade40:"#1f2426",shade30:"#3b4447",shade20:"#505c60",shade10:"#5f6d71",primary:"#69797e",tint10:"#79898d",tint20:"#89989d",tint30:"#a0adb2",tint40:"#cdd6d8",tint50:"#e4e9ea",tint60:"#f8f9fa"},anchor:{shade50:"#090a0b",shade40:"#111315",shade30:"#202427",shade20:"#2b3135",shade10:"#333a3f",primary:"#394146",tint10:"#4d565c",tint20:"#626c72",tint30:"#808a90",tint40:"#bcc3c7",tint50:"#dbdfe1",tint60:"#f6f7f8"}},Ob={cranberry:Pb,green:Rb,orange:{shade50:"#271002",shade40:"#4a1e04",shade30:"#8a3707",shade20:"#bc4b09",shade10:"#de590b",primary:"#f7630c",tint10:"#f87528",tint20:"#f98845",tint30:"#faa06b",tint40:"#fdcfb4",tint50:"#fee5d7",tint60:"#fff9f5"}},Db=["darkRed","cranberry","pumpkin","peach","gold","brass","brown","forest","seafoam","darkGreen","lightTeal","teal","steel","blue","royalBlue","cornflower","navy","lavender","purple","grape","lilac","pink","magenta","plum","beige","mink","platinum","anchor"],Nb={success:"green",warning:"orange",danger:"cranberry"},kb=["red","green","darkOrange","yellow","berry","lightGreen","marigold"].reduce(((g,f)=>{const S=f.slice(0,1).toUpperCase()+f.slice(1),v={[`colorPalette${S}Background1`]:Mb[f].tint60,[`colorPalette${S}Background2`]:Mb[f].tint40,[`colorPalette${S}Background3`]:Mb[f].primary,[`colorPalette${S}Foreground1`]:Mb[f].shade10,[`colorPalette${S}Foreground2`]:Mb[f].shade30,[`colorPalette${S}Foreground3`]:Mb[f].primary,[`colorPalette${S}BorderActive`]:Mb[f].primary,[`colorPalette${S}Border1`]:Mb[f].tint40,[`colorPalette${S}Border2`]:Mb[f].primary};return Object.assign(g,v)}),{});kb.colorPaletteYellowForeground1=Mb.yellow.shade30,kb.colorPaletteRedForegroundInverted=Mb.red.tint20,kb.colorPaletteGreenForegroundInverted=Mb.green.tint20,kb.colorPaletteYellowForegroundInverted=Mb.yellow.tint40;const Lb=Db.reduce(((g,f)=>{const S=f.slice(0,1).toUpperCase()+f.slice(1),v={[`colorPalette${S}Background2`]:wb[f].tint40,[`colorPalette${S}Foreground2`]:wb[f].shade30,[`colorPalette${S}BorderActive`]:wb[f].primary};return Object.assign(g,v)}),{}),Fb={...kb,...Lb},xb=Object.entries(Nb).reduce(((g,[f,S])=>{const v=f.slice(0,1).toUpperCase()+f.slice(1),C={[`colorStatus${v}Background1`]:Ob[S].tint60,[`colorStatus${v}Background2`]:Ob[S].tint40,[`colorStatus${v}Background3`]:Ob[S].primary,[`colorStatus${v}Foreground1`]:Ob[S].shade10,[`colorStatus${v}Foreground2`]:Ob[S].shade30,[`colorStatus${v}Foreground3`]:Ob[S].primary,[`colorStatus${v}ForegroundInverted`]:Ob[S].tint30,[`colorStatus${v}BorderActive`]:Ob[S].primary,[`colorStatus${v}Border1`]:Ob[S].tint40,[`colorStatus${v}Border2`]:Ob[S].primary};return Object.assign(g,C)}),{});xb.colorStatusDangerBackground3Hover=Ob[Nb.danger].shade10,xb.colorStatusDangerBackground3Pressed=Ob[Nb.danger].shade20,xb.colorStatusWarningForeground1=Ob[Nb.warning].shade20,xb.colorStatusWarningForeground3=Ob[Nb.warning].shade20,xb.colorStatusWarningBorder2=Ob[Nb.warning].shade20;const generateColorTokens=g=>({colorNeutralForeground1:_b[14],colorNeutralForeground1Hover:_b[14],colorNeutralForeground1Pressed:_b[14],colorNeutralForeground1Selected:_b[14],colorNeutralForeground2:_b[26],colorNeutralForeground2Hover:_b[14],colorNeutralForeground2Pressed:_b[14],colorNeutralForeground2Selected:_b[14],colorNeutralForeground2BrandHover:g[80],colorNeutralForeground2BrandPressed:g[70],colorNeutralForeground2BrandSelected:g[80],colorNeutralForeground3:_b[38],colorNeutralForeground3Hover:_b[26],colorNeutralForeground3Pressed:_b[26],colorNeutralForeground3Selected:_b[26],colorNeutralForeground3BrandHover:g[80],colorNeutralForeground3BrandPressed:g[70],colorNeutralForeground3BrandSelected:g[80],colorNeutralForeground4:_b[44],colorNeutralForegroundDisabled:_b[74],colorNeutralForegroundInvertedDisabled:Tb[40],colorBrandForegroundLink:g[70],colorBrandForegroundLinkHover:g[60],colorBrandForegroundLinkPressed:g[40],colorBrandForegroundLinkSelected:g[70],colorNeutralForeground2Link:_b[26],colorNeutralForeground2LinkHover:_b[14],colorNeutralForeground2LinkPressed:_b[14],colorNeutralForeground2LinkSelected:_b[14],colorCompoundBrandForeground1:g[80],colorCompoundBrandForeground1Hover:g[70],colorCompoundBrandForeground1Pressed:g[60],colorBrandForeground1:g[80],colorBrandForeground2:g[70],colorBrandForeground2Hover:g[60],colorBrandForeground2Pressed:g[30],colorNeutralForeground1Static:_b[14],colorNeutralForegroundStaticInverted:bb,colorNeutralForegroundInverted:bb,colorNeutralForegroundInvertedHover:bb,colorNeutralForegroundInvertedPressed:bb,colorNeutralForegroundInvertedSelected:bb,colorNeutralForegroundInverted2:bb,colorNeutralForegroundOnBrand:bb,colorNeutralForegroundInvertedLink:bb,colorNeutralForegroundInvertedLinkHover:bb,colorNeutralForegroundInvertedLinkPressed:bb,colorNeutralForegroundInvertedLinkSelected:bb,colorBrandForegroundInverted:g[100],colorBrandForegroundInvertedHover:g[110],colorBrandForegroundInvertedPressed:g[100],colorBrandForegroundOnLight:g[80],colorBrandForegroundOnLightHover:g[70],colorBrandForegroundOnLightPressed:g[50],colorBrandForegroundOnLightSelected:g[60],colorNeutralBackground1:bb,colorNeutralBackground1Hover:_b[96],colorNeutralBackground1Pressed:_b[88],colorNeutralBackground1Selected:_b[92],colorNeutralBackground2:_b[98],colorNeutralBackground2Hover:_b[94],colorNeutralBackground2Pressed:_b[86],colorNeutralBackground2Selected:_b[90],colorNeutralBackground3:_b[96],colorNeutralBackground3Hover:_b[92],colorNeutralBackground3Pressed:_b[84],colorNeutralBackground3Selected:_b[88],colorNeutralBackground4:_b[94],colorNeutralBackground4Hover:_b[98],colorNeutralBackground4Pressed:_b[96],colorNeutralBackground4Selected:bb,colorNeutralBackground5:_b[92],colorNeutralBackground5Hover:_b[96],colorNeutralBackground5Pressed:_b[94],colorNeutralBackground5Selected:_b[98],colorNeutralBackground6:_b[90],colorNeutralBackgroundInverted:_b[16],colorNeutralBackgroundStatic:_b[20],colorNeutralBackgroundAlpha:Tb[50],colorNeutralBackgroundAlpha2:Tb[80],colorSubtleBackground:"transparent",colorSubtleBackgroundHover:_b[96],colorSubtleBackgroundPressed:_b[88],colorSubtleBackgroundSelected:_b[92],colorSubtleBackgroundLightAlphaHover:Tb[70],colorSubtleBackgroundLightAlphaPressed:Tb[50],colorSubtleBackgroundLightAlphaSelected:"transparent",colorSubtleBackgroundInverted:"transparent",colorSubtleBackgroundInvertedHover:Ib[10],colorSubtleBackgroundInvertedPressed:Ib[30],colorSubtleBackgroundInvertedSelected:Ib[20],colorTransparentBackground:"transparent",colorTransparentBackgroundHover:"transparent",colorTransparentBackgroundPressed:"transparent",colorTransparentBackgroundSelected:"transparent",colorNeutralBackgroundDisabled:_b[94],colorNeutralBackgroundInvertedDisabled:Tb[10],colorNeutralStencil1:_b[90],colorNeutralStencil2:_b[98],colorNeutralStencil1Alpha:Ib[10],colorNeutralStencil2Alpha:Ib[5],colorBackgroundOverlay:Ib[40],colorScrollbarOverlay:Ib[50],colorBrandBackground:g[80],colorBrandBackgroundHover:g[70],colorBrandBackgroundPressed:g[40],colorBrandBackgroundSelected:g[60],colorCompoundBrandBackground:g[80],colorCompoundBrandBackgroundHover:g[70],colorCompoundBrandBackgroundPressed:g[60],colorBrandBackgroundStatic:g[80],colorBrandBackground2:g[160],colorBrandBackground2Hover:g[150],colorBrandBackground2Pressed:g[130],colorBrandBackground3Static:g[60],colorBrandBackground4Static:g[40],colorBrandBackgroundInverted:bb,colorBrandBackgroundInvertedHover:g[160],colorBrandBackgroundInvertedPressed:g[140],colorBrandBackgroundInvertedSelected:g[150],colorNeutralCardBackground:_b[98],colorNeutralCardBackgroundHover:bb,colorNeutralCardBackgroundPressed:_b[96],colorNeutralCardBackgroundSelected:_b[92],colorNeutralCardBackgroundDisabled:_b[94],colorNeutralStrokeAccessible:_b[38],colorNeutralStrokeAccessibleHover:_b[34],colorNeutralStrokeAccessiblePressed:_b[30],colorNeutralStrokeAccessibleSelected:g[80],colorNeutralStroke1:_b[82],colorNeutralStroke1Hover:_b[78],colorNeutralStroke1Pressed:_b[70],colorNeutralStroke1Selected:_b[74],colorNeutralStroke2:_b[88],colorNeutralStroke3:_b[94],colorNeutralStrokeSubtle:_b[88],colorNeutralStrokeOnBrand:bb,colorNeutralStrokeOnBrand2:bb,colorNeutralStrokeOnBrand2Hover:bb,colorNeutralStrokeOnBrand2Pressed:bb,colorNeutralStrokeOnBrand2Selected:bb,colorBrandStroke1:g[80],colorBrandStroke2:g[140],colorBrandStroke2Hover:g[120],colorBrandStroke2Pressed:g[80],colorBrandStroke2Contrast:g[140],colorCompoundBrandStroke:g[80],colorCompoundBrandStrokeHover:g[70],colorCompoundBrandStrokePressed:g[60],colorNeutralStrokeDisabled:_b[88],colorNeutralStrokeInvertedDisabled:Tb[40],colorTransparentStroke:"transparent",colorTransparentStrokeInteractive:"transparent",colorTransparentStrokeDisabled:"transparent",colorNeutralStrokeAlpha:Ib[5],colorNeutralStrokeAlpha2:Tb[20],colorStrokeFocus1:bb,colorStrokeFocus2:Ab,colorNeutralShadowAmbient:"rgba(0,0,0,0.12)",colorNeutralShadowKey:"rgba(0,0,0,0.14)",colorNeutralShadowAmbientLighter:"rgba(0,0,0,0.06)",colorNeutralShadowKeyLighter:"rgba(0,0,0,0.07)",colorNeutralShadowAmbientDarker:"rgba(0,0,0,0.20)",colorNeutralShadowKeyDarker:"rgba(0,0,0,0.24)",colorBrandShadowAmbient:"rgba(0,0,0,0.30)",colorBrandShadowKey:"rgba(0,0,0,0.25)"}),Ub={borderRadiusNone:"0",borderRadiusSmall:"2px",borderRadiusMedium:"4px",borderRadiusLarge:"6px",borderRadiusXLarge:"8px",borderRadiusCircular:"10000px"},Vb={curveAccelerateMax:"cubic-bezier(0.9,0.1,1,0.2)",curveAccelerateMid:"cubic-bezier(1,0,1,1)",curveAccelerateMin:"cubic-bezier(0.8,0,0.78,1)",curveDecelerateMax:"cubic-bezier(0.1,0.9,0.2,1)",curveDecelerateMid:"cubic-bezier(0,0,0,1)",curveDecelerateMin:"cubic-bezier(0.33,0,0.1,1)",curveEasyEaseMax:"cubic-bezier(0.8,0,0.2,1)",curveEasyEase:"cubic-bezier(0.33,0,0.67,1)",curveLinear:"cubic-bezier(0,0,1,1)"},Bb={durationUltraFast:"50ms",durationFaster:"100ms",durationFast:"150ms",durationNormal:"200ms",durationGentle:"250ms",durationSlow:"300ms",durationSlower:"400ms",durationUltraSlow:"500ms"},Hb={fontSizeBase100:"10px",fontSizeBase200:"12px",fontSizeBase300:"14px",fontSizeBase400:"16px",fontSizeBase500:"20px",fontSizeBase600:"24px",fontSizeHero700:"28px",fontSizeHero800:"32px",fontSizeHero900:"40px",fontSizeHero1000:"68px"},$b={lineHeightBase100:"14px",lineHeightBase200:"16px",lineHeightBase300:"20px",lineHeightBase400:"22px",lineHeightBase500:"28px",lineHeightBase600:"32px",lineHeightHero700:"36px",lineHeightHero800:"40px",lineHeightHero900:"52px",lineHeightHero1000:"92px"},jb={fontWeightRegular:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700},Gb={fontFamilyBase:"'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif",fontFamilyMonospace:"Consolas, 'Courier New', Courier, monospace",fontFamilyNumeric:"Bahnschrift, 'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif"},qb={none:"0",xxs:"2px",xs:"4px",sNudge:"6px",s:"8px",mNudge:"10px",m:"12px",l:"16px",xl:"20px",xxl:"24px",xxxl:"32px"},Wb={spacingHorizontalNone:qb.none,spacingHorizontalXXS:qb.xxs,spacingHorizontalXS:qb.xs,spacingHorizontalSNudge:qb.sNudge,spacingHorizontalS:qb.s,spacingHorizontalMNudge:qb.mNudge,spacingHorizontalM:qb.m,spacingHorizontalL:qb.l,spacingHorizontalXL:qb.xl,spacingHorizontalXXL:qb.xxl,spacingHorizontalXXXL:qb.xxxl},zb={spacingVerticalNone:qb.none,spacingVerticalXXS:qb.xxs,spacingVerticalXS:qb.xs,spacingVerticalSNudge:qb.sNudge,spacingVerticalS:qb.s,spacingVerticalMNudge:qb.mNudge,spacingVerticalM:qb.m,spacingVerticalL:qb.l,spacingVerticalXL:qb.xl,spacingVerticalXXL:qb.xxl,spacingVerticalXXXL:qb.xxxl},Kb={strokeWidthThin:"1px",strokeWidthThick:"2px",strokeWidthThicker:"3px",strokeWidthThickest:"4px"};function createShadowTokens(g,f,S=""){return{[`shadow2${S}`]:`0 0 2px ${g}, 0 1px 2px ${f}`,[`shadow4${S}`]:`0 0 2px ${g}, 0 2px 4px ${f}`,[`shadow8${S}`]:`0 0 2px ${g}, 0 4px 8px ${f}`,[`shadow16${S}`]:`0 0 2px ${g}, 0 8px 16px ${f}`,[`shadow28${S}`]:`0 0 8px ${g}, 0 14px 28px ${f}`,[`shadow64${S}`]:`0 0 8px ${g}, 0 32px 64px ${f}`}}const Jb=(g=>{const f=generateColorTokens(g);return{...Ub,...Hb,...$b,...Gb,...jb,...Kb,...Wb,...zb,...Bb,...Vb,...f,...Fb,...xb,...createShadowTokens(f.colorNeutralShadowAmbient,f.colorNeutralShadowKey),...createShadowTokens(f.colorBrandShadowAmbient,f.colorBrandShadowKey,"Brand")}})({10:"#061724",20:"#082338",30:"#0a2e4a",40:"#0c3b5e",50:"#0e4775",60:"#0f548c",70:"#115ea3",80:"#0f6cbd",90:"#2886de",100:"#479ef5",110:"#62abf5",120:"#77b7f7",130:"#96c6fa",140:"#b4d6fa",150:"#cfe4fa",160:"#ebf3fc"});let Yb=1;class WatermarkOverlayProvider{constructor(g,f,S,v,C){this._container=g,this._videoStream=f,this._viewId=S,this._streamTelemetryEventSender=C,this._watermarkCapability=null,this.WATERMARK_TEXT_COMMON_STYLES={fontFamily:Jb.fontFamilyBase,fontWeight:"bold",stroke:"black",strokeOpacity:"0.1",fill:Jb.colorNeutralStrokeOnBrand2},this.WATERMARK_CONTAINER_STYLES={position:"absolute",pointerEvents:"none",width:"100%",height:"100%",top:"0",left:"0"},this.TEXT_ROTATION=30,this.SHADOW_OPACITY_RATIO=3,this.RANGE_MAX=100,this.BORDER_SIZE=18,this.BORDER_SIZE_FRAC=1/this.BORDER_SIZE,this.SPACE_USE=.9,this.MAX_BORDER=2,this.SINGLE_PATTERN_FONT_SIZE_FACTOR=.07,this._svgContainerHidden="",this._svgWatermarkUseTextScale=0,this._svgWatermarkUseTextBorderSize=0,this._svgTextTiledScaledSize=0,this._svgTextTiledScaledStrokeWidth=0,this._svgFirstPatternWidth=0,this._svgFirstPatternHeight=0,this._svgSecondPatternWidth=0,this._svgSecondPatternHeight=0,this._svgSecondPatternOffsetX=0,this._svgSecondPatternOffsetY=0,this._computeTextDiagonal=createTextDiagonalCalculation(this.TEXT_ROTATION),this._isApple=!1,this._getScaledPatternDimensions=(g,f,S,v)=>({width:g*(S+1.1),height:f*(v+1.1)}),this._call=this._videoStream.call,this._logger=v.createChild("WatermarkOverlayProvider"+Yb++);const _=this._call.getMeetingCapabilitiesInternal();if(!_){this._logger.warn("No watermark capabilities found. Likely not received from service.");const g=new CallingCommunicationError({defaultError:D.VIEW.NO_WATERMARK_CAPABILITY_RECEIVED}),f=generateGuid();return void this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:f,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:PE.watermark,kindOfEvent:gE.failure,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote,additionalDetails:{failureReason:g.message,code:g.code,...extractCommunicationServicesErrorForTelemetry(g),watermark:{...this._getWatermarkUsageTelemetryPayload()}}})}this._watermarkCapability=_.waterMarkCapability;const T=this._call.deviceManager.getOSNameInternal();this._isApple="ios"===T||"mac"===T,this._resizeObserver=new ResizeObserver((g=>{for(const f of g)if(f.contentRect?.width>1){const g=f.contentRect.width,S=f.contentRect.height;this._updateWatermarkScalingValues(g,S)}})),this._resizeObserver.observe(this._container)}attach(){const g=generateGuid(),f=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn("No watermark capabilities found. No-op.");if("Video"!==this._videoStream.mediaStreamType&&"ScreenSharing"!==this._videoStream.mediaStreamType)throw new Error("Unsupported media type for watermark");this._watermarkIsReceivingSub=()=>{this._videoStream.isReceiving&&(this._generateWatermark(this._videoStream.mediaStreamType,g),this._updateWatermarkScalingValues(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height))},this._videoStream.on("isReceivingChanged",this._watermarkIsReceivingSub)}catch(S){const v=new CallingCommunicationError({defaultError:D.VIEW.WATERMARK_ATTACH_FAIL,originalError:S});throw this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:g,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-f},operation:PE.watermark,kindOfEvent:gE.failure,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote,additionalDetails:{failureReason:v.message,code:v.code,...extractCommunicationServicesErrorForTelemetry(v),watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),v}}dispose(){this._resizeObserver&&this._resizeObserver.disconnect(),this._mutationObserver&&this._mutationObserver.disconnect(),this._audioOnlyCallback&&this._call.offWatermarkAudioOnlyFallbackTriggeredChanged("watermarkAudioOnlyFallbackTriggeredChanged",this._audioOnlyCallback),this._svgContainer&&(this._container.removeChild(this._svgContainer),this._svgContainer=void 0,this._svgContainerHidden=""),this._watermarkIsReceivingSub&&this._videoStream.off("isReceivingChanged",this._watermarkIsReceivingSub),this._logger.info(`watermark overlay provider disposed for viewid: ${this._viewId}`)}_updateWatermarkScalingValues(g,f){"Single"===this._getSelectedWatermarkPattern()?this._updateWatermarkUseTextScalingSingle(g,f):"Tiled"===this._getSelectedWatermarkPattern()&&this._updateWatermarkPatternScalingTiled(g,f)}_generateWatermark(g,f){const S=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn("No watermark capabilities found. No-op.");if(this._call.watermarkAudioOnlyFallbackTriggered)return this._logger.warn("Watermark audio only fallback was triggered, disposing remote stream"),void this._videoStream.dispose();let v;if("Video"===g&&this._watermarkCapability.enabledForVideo)v=this._watermarkCapability.videoSettings;else{if("ScreenSharing"!==g||!this._watermarkCapability.enabledForVbss)return void this._logger.info(`No watermark operations to be done on viewId: ${this._viewId}`);v=this._watermarkCapability.vbssSettings}if(this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:f,callId:this._call.id,timestampInfo:{attemptTimestamp:S},operation:PE.watermark,kindOfEvent:gE.attempt,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),!v||!v.opacity||!v.pattern||"number"!=typeof v.opacity||"string"!=typeof v.pattern)throw this._logger.debug("Unexpected watermark settings"),new CallingCommunicationError({defaultError:D.VIEW.WATERMARK_UNEXPECTED_VALUES});const C=this._getClampedUsername();let _;if("Single"===v.pattern)_=this._generateSinglePatternWatermark(C,v);else{if("Tiled"!==v.pattern)throw this._logger.debug("Unexpected watermark pattern setting"),new CallingCommunicationError({defaultError:D.VIEW.WATERMARK_UNEXPECTED_VALUES});_=this._generateTiledPatternWatermark(C,v)}this._svgContainerHidden=_.outerHTML,this._container.appendChild(_),this._audioOnlyCallback=()=>{this._call.watermarkAudioOnlyFallbackTriggered&&(this._logger.debug("Watermark audio only fallback triggered by one of the renderers"),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:f,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:PE.watermark,kindOfEvent:gE.event,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}))},this._call.onWatermarkAudioOnlyFallbackTriggeredChanged("watermarkAudioOnlyFallbackTriggeredChanged",this._audioOnlyCallback),this._mutationObserver=new MutationObserver((g=>{this._svgContainer?.outerHTML!==this._svgContainerHidden&&(this._logger.debug("watermark mutation detected, falling back to audio only!"),this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:f,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:PE.watermark,kindOfEvent:gE.event,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}))})),this._mutationObserver.observe(this._container,{attributes:!0,subtree:!0,childList:!0}),this._logger.info(`watermark attached for viewId: ${this._viewId}`),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:f,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-S},operation:PE.watermark,kindOfEvent:gE.success,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}})}catch(g){const v=new CallingCommunicationError({defaultError:D.VIEW.WATERMARK_ATTACH_FAIL,originalError:g});throw this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:f,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-S},operation:PE.watermark,kindOfEvent:gE.failure,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote,additionalDetails:{failureReason:v.message,code:v.code,...extractCommunicationServicesErrorForTelemetry(v),watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}),v}}_triggerAudioOnlyFallback(){this._logger.debug(`audio only fallback triggered by viewId ${this._viewId}`),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._call.setWatermarkAudioOnlyFallbackTriggered(!0)}_addStyleAttributesToSvgElement(g,f){for(const[S,v]of Object.entries(f))g.style[`${S}`]=v}_generateSinglePatternWatermark(g,f){const S=this._getWatermarkContainer(f);this._svgContainer=S;const v=f.opacity/this.RANGE_MAX,C=v/this.SHADOW_OPACITY_RATIO,_=generateGuid(),T=`url(#${_})`,I=document.createElementNS("http://www.w3.org/2000/svg","defs"),b=this._getSvgFilter(_,C),A=document.createElementNS("http://www.w3.org/2000/svg","text");A.id=generateGuid(),this._addStyleAttributesToSvgElement(A,this.WATERMARK_TEXT_COMMON_STYLES),A.setAttribute("filter",T),A.setAttribute("text-anchor","middle"),A.setAttribute("dominant-baseline","middle"),A.setAttribute("fill-opacity",`${v}`),A.style.transform="rotate(-30deg)";const P=document.createTextNode(g);A.appendChild(P),this._svgTextDefElement=A,I.appendChild(b),I.appendChild(A);const R=document.createElementNS("http://www.w3.org/2000/svg","use");return R.id=generateGuid(),this._svgWatermarkUseTagSinglePattern=R,R.setAttribute("href",`#${this._svgTextDefElement.id}`),R.setAttribute("x","50%"),R.setAttribute("y","50%"),R.setAttribute("width","100%"),R.setAttribute("height","100%"),R.setAttribute("font-size",`${this._svgWatermarkUseTextScale}`),R.setAttribute("stroke-width",`${this._svgWatermarkUseTextBorderSize}`),S.appendChild(I),S.appendChild(R),this._updateWatermarkUseTextScalingSingle(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),S}_updateWatermarkUseTextScalingSingle(g,f){if(this._svgContainer&&this._svgWatermarkUseTagSinglePattern){const S=this._computeTextDiagonal(g,f);return this._svgWatermarkUseTextScale=this.SPACE_USE*S*this.SINGLE_PATTERN_FONT_SIZE_FACTOR,this._svgWatermarkUseTextBorderSize=Math.max(1,Math.min(this.MAX_BORDER,this._svgWatermarkUseTextScale*this.BORDER_SIZE_FRAC)),this._svgWatermarkUseTagSinglePattern.setAttribute("font-size",`${this._svgWatermarkUseTextScale}`),this._svgWatermarkUseTagSinglePattern.setAttribute("stroke-width",`${this._svgWatermarkUseTextBorderSize}`),void(this._svgContainerHidden=this._svgContainer.outerHTML)}this._logger.warn("svg watermark element missing, cannot update")}_updateWatermarkPatternScalingTiled(g,f){if(this._svgContainer&&this._svgTextDefElement&&this._svgFirstPattern&&this._svgSecondPattern){const S=calculateWatermarkPatternScaling(g,f,this._isApple);this._svgTextTiledScaledSize=S.scaledFontSize,this._svgTextTiledScaledStrokeWidth=S.scaledBorderSize,this._svgTextDefElement.setAttribute("font-size",`${this._svgTextTiledScaledSize}`),this._svgTextDefElement.setAttribute("stroke-width",`${this._svgTextTiledScaledStrokeWidth}`);const v=this._svgTextDefElement.getBoundingClientRect().width,C=this._svgTextDefElement.getBoundingClientRect().height,{width:_,height:T}=this._getScaledPatternDimensions(v,C,S.scaledHorizontalGap,S.scaledVerticalGap),I=.5*_,b=.5*T;return this._svgFirstPatternWidth=_,this._svgFirstPatternHeight=T,this._svgSecondPatternWidth=_,this._svgSecondPatternHeight=T,this._svgSecondPatternOffsetX=I,this._svgSecondPatternOffsetY=b,this._svgFirstPattern.setAttribute("width",`${this._svgFirstPatternWidth}`),this._svgFirstPattern.setAttribute("height",`${this._svgFirstPatternHeight}`),this._svgSecondPattern.setAttribute("width",`${this._svgSecondPatternWidth}`),this._svgSecondPattern.setAttribute("height",`${this._svgSecondPatternHeight}`),this._svgSecondPattern.setAttribute("x",`${this._svgSecondPatternOffsetX}`),this._svgSecondPattern.setAttribute("y",`${this._svgSecondPatternOffsetY}`),void(this._svgContainerHidden=this._svgContainer.outerHTML)}this._logger.warn("svg watermark element missing, cannot update")}_generateTiledPatternWatermark(g,f){const S=this._getWatermarkContainer(f);this._svgContainer=S;const v=f.opacity/this.RANGE_MAX,C=v/this.SHADOW_OPACITY_RATIO,_=generateGuid(),T=generateGuid(),I=generateGuid(),b=`url(#${_})`,A=document.createElementNS("http://www.w3.org/2000/svg","defs"),P=this._getSvgFilter(_,C),R=document.createElementNS("http://www.w3.org/2000/svg","text");this._svgTextDefElement=R,R.id=generateGuid(),this._addStyleAttributesToSvgElement(R,this.WATERMARK_TEXT_COMMON_STYLES),R.setAttribute("filter",b),R.setAttribute("dominant-baseline","hanging"),R.setAttribute("fill-opacity",`${v}`),R.setAttribute("font-size",`${this._svgTextTiledScaledSize}`),R.setAttribute("stroke-width",`${this._svgTextTiledScaledStrokeWidth}`);const M=document.createTextNode(g);R.appendChild(M);const w=document.createElementNS("http://www.w3.org/2000/svg","pattern");this._svgFirstPattern=w,w.id=T,w.setAttribute("patternUnits","userSpaceOnUse"),w.setAttribute("patternTransform","rotate(-30)"),w.setAttribute("width",`${this._svgFirstPatternWidth}`),w.setAttribute("height",`${this._svgFirstPatternHeight}`);const O=document.createElementNS("http://www.w3.org/2000/svg","use");O.setAttribute("href",`#${this._svgTextDefElement.id}`),w.appendChild(O);const D=document.createElementNS("http://www.w3.org/2000/svg","pattern");this._svgSecondPattern=D,D.id=I,D.setAttribute("patternUnits","userSpaceOnUse"),D.setAttribute("patternTransform","rotate(-30)"),D.setAttribute("width",`${this._svgSecondPatternWidth}`),D.setAttribute("height",`${this._svgSecondPatternHeight}`),D.setAttribute("x",`${this._svgSecondPatternOffsetX}`),D.setAttribute("y",`${this._svgSecondPatternOffsetY}`);const N=O.cloneNode(!0);D.appendChild(N),A.appendChild(P),A.appendChild(R),A.appendChild(w),A.appendChild(D);const k=this._getRect(0,0,100,100,T),L=this._getRect(0,0,100,100,I);return S.appendChild(A),S.appendChild(k),S.appendChild(L),this._updateWatermarkPatternScalingTiled(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),S}_getWatermarkContainer(g){const f=document.createElementNS("http://www.w3.org/2000/svg","svg");return this._addStyleAttributesToSvgElement(f,this.WATERMARK_CONTAINER_STYLES),f.setAttribute("xmlns","http://www.w3.org/2000/svg"),f}_getSvgFilter(g,f){const S=document.createElementNS("http://www.w3.org/2000/svg","filter");S.id=g;const v=document.createElementNS("http://www.w3.org/2000/svg","feDropShadow");return v.setAttribute("dx","0.5"),v.setAttribute("dy","0.5"),v.setAttribute("stdDeviation","1"),v.setAttribute("flood-color","black"),v.setAttribute("flood-opacity",`${f}`),S.appendChild(v),S}_getRect(g,f,S,v,C){const _=document.createElementNS("http://www.w3.org/2000/svg","rect");return _.setAttribute("x",`${g}%`),_.setAttribute("y",`${f}%`),_.setAttribute("width",`${S}%`),_.setAttribute("height",`${v}%`),_.setAttribute("fill",`url(#${C})`),_}_getClampedUsername(){let g="";const f=this._call.callAgent,S=getAcsEcsConfig().calling.watermark,v=S.watermarkMaxUsernameLength,C=S.watermarkEmptyDisplayNamePlaceholder;if(f?.isEnterpriseUser()){let S=f.getUserProperties()?.sipUri;S&&"string"==typeof S&&(g=S.replace("sip:",""))}else g=f?.displayName??"",g||(g=C);return clampEmail(g,v)}_getSelectedWatermarkPattern(){return"Video"===this._videoStream.mediaStreamType&&this._watermarkCapability?.enabledForVideo&&this._watermarkCapability?.videoSettings?.pattern?this._watermarkCapability.videoSettings.pattern:"ScreenSharing"===this._videoStream.mediaStreamType&&this._watermarkCapability?.enabledForVbss&&this._watermarkCapability?.vbssSettings?.pattern?this._watermarkCapability.vbssSettings.pattern:""}_getWatermarkUsageTelemetryPayload(g=""){return{endpointSupportsWatermark:this._call.callAgent.isWatermarkSupported(),audioOnlyFallbackTriggered:this._call.watermarkAudioOnlyFallbackTriggered,audioOnlyFallbackTriggeredByViewId:g,watermarkUsage:{video:{enabled:this._watermarkCapability?.enabledForVideo,opacity:this._watermarkCapability?.videoSettings.opacity,pattern:this._watermarkCapability?.videoSettings.pattern},screenshare:{enabled:this._watermarkCapability?.enabledForVbss,opacity:this._watermarkCapability?.vbssSettings.opacity,pattern:this._watermarkCapability?.vbssSettings.pattern}},viewId:this._viewId}}}var __decorate$e=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$e=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};let Qb=1;class RemoteStreamRenderer{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get viewId(){return this._viewId}get size(){return{height:this._size.height,width:this._size.width}}constructor(g,f,S,v,C,_,T){this._target=g,this._viewId=f,this._videoStream=S,this._onDisposedCallback=C,this._createViewSteps=_,this._eventEmitter=new LE.EventEmitter,this._isRendering=!1,this._scalingMode="Stretch",this._isMirrored=!1,this._createViewResolvedOnPlayEvent=!1,this._hasRenderingEvent=!1,this._hasPlayEvent=!1,this._size={height:0,width:0},this._disposed=!1,this.resolveRenderingPendingPromise=(g=!1)=>{this._renderingDeferred?.isPending()&&(this._renderingDeferred.resolve(),g&&(this.logger.log(`video element play event was fired and promise was resolved and isRendering is: ${this._tsRenderer?.isRendering}`),this._createViewResolvedOnPlayEvent=!0)),g?this._hasPlayEvent||(this._hasPlayEvent=!0,this._createViewSteps.isPlayedTimestamp=Date.now(),this._createViewSteps.isPlayedTimeDeltaSinceAttemptMs=void 0===this._createViewSteps.attemptTimestamp?0:this._createViewSteps.isPlayedTimestamp-this._createViewSteps.attemptTimestamp):!this._hasRenderingEvent&&this._isRendering&&(this._hasRenderingEvent=!0,this._createViewSteps.isRenderedTimestamp=Date.now(),this._createViewSteps.isRenderedTimeDeltaSinceAttemptMs=void 0===this._createViewSteps.attemptTimestamp?0:this._createViewSteps.isRenderedTimestamp-this._createViewSteps.attemptTimestamp)},this._handleTsRendererChanged=g=>{if(this.logger.debug(`rendering state is ${this._isRendering}, changed to ${this._tsRenderer?.isRendering}`),this._tsRenderer)if(this._tsRenderer.isRendering!==this._isRendering&&(this._isRendering=this._tsRenderer.isRendering,this._videoStream.updateIsReceiving(),this._isRendering&&this.resolveRenderingPendingPromise(),g.log(`isRendering change to ${this._isRendering}`)),this._tsRenderer.isRendering){const g=this._tsRenderer.streamSize?.height||Ym.HEIGHT,f=this._tsRenderer.streamSize?.width||Ym.WIDTH;g===this._size.height&&f===this._size.width||this.setAndUpdateSize(),this.resolveRenderingPendingPromise()}else this._size.height=0,this._size.width=0,this._videoStream.updateSize();this.sendRendererTelemetry()},this.sendRendererTelemetry=()=>{if(this._tsRenderer)try{const g={isRendering:this._tsRenderer.isRendering,streamWidth:this._tsRenderer.streamSize.width,streamHeight:this._tsRenderer.streamSize.height,isVideoAttached:this._target.isConnected,rendererWidth:this._target?.offsetWidth,rendererHeight:this._target?.offsetHeight};if(this.previousStats){if(shallowEqual(this.previousStats,g))return}else this.previousStats=g;this.previousStats=g;const f=this._videoStream.getStreamMetadata(),{callId:S,localParticipantId:v,isDisposed:C,viewIdsRegistered:_,height:T,width:I,...b}=f,A={...g,...b,viewId:this._viewId,disposed:this._disposed};this._videoStream.call.stats.recordEvent({name:hE.remote_view,callId:S,localParticipantId:v,data:A})}catch(g){}},this._unsubscribeAvailabilityCallback=()=>{this._availableCallback&&("RemoteVideoStream"===this._videoStream.kind&&this._videoStream?.off("isAvailableChanged",this._availableCallback),this._availableCallback=void 0)},this._disposeTsRendererChangedObservable=()=>{this._tsRendererChanged&&(this._tsRendererChanged.dispose(),this._tsRendererChanged=void 0)},this._attemptToDisposeTsRenderer=()=>{if(this._tsRenderer){this.logger.debug("disposing underlying remote renderer");try{this._tsRenderer?.dispose(),this._tsRenderer=void 0}catch(g){throw this.logger.warn(`underlying remote renderer dispose failed with ${g?.message} error`),new CallingCommunicationError({defaultError:D.VIEW.REMOTE_RENDERER_DISPOSE_FAIL})}}},this.logger=v.createChild("RemoteStreamRenderer"+Qb++),this.logger.log("created"),void 0!==T?.scalingMode&&(this._scalingMode=T.scalingMode),void 0!==T?.isMirrored&&(this._isMirrored=T.isMirrored),this._remoteStreamTelemetryEventSender=new StreamTelemetryEventSender(this._videoStream.telemetryLogManager),this._watermarkOverlayProvider=new WatermarkOverlayProvider(this._target,this._videoStream,this._viewId,this.logger,this._remoteStreamTelemetryEventSender),this._watermarkOverlayProvider.attach()}async start(){const g=generateGuid(),f=+new Date,S=this.logger.createFnLogger(US.Start),v={timestampInfo:{attemptTimestamp:f},correlationId:g,operation:PE.render,kindOfEvent:gE.attempt,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote};if(this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(v),this._disposed)throw this.logger.warn("already disposed"),new CallingCommunicationError({defaultError:D.VIEW.START_ALREADY_DISPOSED});try{S.info(`scalingMode=${toTsScalingMode(this._scalingMode)}`),this._videoStream.registerRenderer(this),this._renderingDeferred=defer$1(),this._renderingDeferred.promise.catch(noop),"RemoteVideoStream"===this._videoStream.kind&&(this._availableCallback=()=>{this._videoStream.isAvailable||(S.warn("stream isAvailable changed to false, attempting to reject operation"),this._renderingDeferred?.isPending()&&!this._disposed&&this._renderingDeferred?.reject(new CallingCommunicationError({defaultError:D.VIEW.STREAM_BECAME_UNAVAILABLE})))},this._videoStream.on("isAvailableChanged",this._availableCallback)),this._createViewSteps.startSubscriptionTimestamp=Date.now(),this._createViewSteps.startSubscriptionTimeDeltaSinceAttemptMs=void 0===this._createViewSteps.attemptTimestamp?0:this._createViewSteps.startSubscriptionTimestamp-this._createViewSteps.attemptTimestamp,this._videoStream.tsStream.start(this._target,{scalingMode:toTsScalingMode(this._scalingMode),transparent:!1}).then((g=>{if(this._createViewSteps.rendererIsAvailableTimestamp=Date.now(),this._createViewSteps.rendererIsAvailableTimeDeltaSinceAttemptMs=void 0===this._createViewSteps.attemptTimestamp?0:this._createViewSteps.rendererIsAvailableTimestamp-this._createViewSteps.attemptTimestamp,this._isMirrored&&(this._target.style.transform="rotateY(180deg)",this._target.style.webkitTransform="rotateY(180deg)"),this._tsRenderer=g,this.logger.info("subscribed to video, waiting for the first frame"),this._disposed)throw this.logger.warn("already disposed, dispose underlying renderer"),this._attemptToDisposeTsRenderer(),new CallingCommunicationError({defaultError:D.VIEW.START_ALREADY_DISPOSED});if(this.logger.info(`current state of rendering is ${this._tsRenderer.isRendering}`),this.sendRendererTelemetry(),-1!==getAcsEcsConfig().rendering.remoteVideo.createViewTimeout&&setTimeout((()=>{if(this._renderingDeferred?.isPending())try{this._renderingDeferred.reject(new CallingCommunicationError({defaultError:D.VIEW.TIMEOUT}))}catch(g){noop()}}),getAcsEcsConfig().rendering.remoteVideo.createViewTimeout),getAcsEcsConfig().rendering.remoteVideo.speedupCreateViewWithPlayEvent){const g=this._target&&this._target.children.length>0&&this._target.children[0];g?g.addEventListener("play",this.videoPlayEventListener.bind(this)):this.logger.warn("video element was not found while trying to listen to play event")}this._tsRendererChanged=this._tsRenderer.changed((()=>this._handleTsRendererChanged(S))),this._tsRenderer.isRendering&&(this._isRendering=!0,this._videoStream.updateIsReceiving(),this.setAndUpdateSize(),this.resolveRenderingPendingPromise())})).catch((g=>{if(this.logger.info("Failed to subscribe to video"),this._renderingDeferred?.isPending()){const f=new CallingCommunicationError({defaultError:D.VIEW.SUBSCRIBE,originalError:g});this._renderingDeferred.reject(f)}})),await this._renderingDeferred.promise,this._videoStream.flushIsReceiving(),this._unsubscribeAvailabilityCallback(),getAcsEcsConfig().rendering.remoteVideo.forceCheckIfVideoWasAttachedToDom&&this._checkIfVideoWasAttachedToDom();const v={timestampInfo:{deltaTimeInMs:+new Date-f},correlationId:g,operation:PE.render,kindOfEvent:gE.success,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};return this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(v),this}catch(S){this.logger.warn(`Failed to render, message=${S}`);try{this.dispose()}catch(g){this.logger.warn(`dispose failed with ${g?.message} error`)}const v=new CallingCommunicationError({defaultError:D.VIEW.START,originalError:S});if(v.message!==D.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&v.message!==D.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){const S={timestampInfo:{deltaTimeInMs:+new Date-f},correlationId:g,operation:PE.render,additionalDetails:{failureReason:v.message,code:x,...extractCommunicationServicesErrorForTelemetry(v)},kindOfEvent:gE.failure,mediaType:this._videoStream.mediaStreamType,streamType:AE.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(S)}throw v}}videoPlayEventListener(){this.logger.log("video element play event was fired"),this.resolveRenderingPendingPromise(!0)}setAndUpdateSize(){try{this._size.width=this._tsRenderer?.streamSize.width||Ym.WIDTH,this._size.height=this._tsRenderer?.streamSize.height||Ym.HEIGHT,this._videoStream.updateSize()}catch(g){this.logger.error(`Failed to update video stream size with error ${g}`)}}async setScalingMode(g){if(!this._tsRenderer)throw new CallingCommunicationError({defaultError:D.VIEW.SCALING_MODE});await this._tsRenderer.setScalingMode(toTsScalingMode(g)),this._scalingMode=g}dispose(g=wE.Public_App){if(this._disposed)throw new CallingCommunicationError({defaultError:D.VIEW.RENDERER_DISPOSE_ALREADY_DISPOSED});if(this._disposed=!0,this._disposeTsRendererChangedObservable(),this._unsubscribeAvailabilityCallback(),this._attemptToDisposeTsRenderer(),this._renderingDeferred?.isPending()){let f;switch(g){case wE.Internal_LargeMeetingVideoRendering:f=D.VIEW.LARGE_MEETING_VIEW_DISPOSED;break;case wE.Internal_RemoteVideoStreamDisposed:f=D.VIEW.REMOTE_VIDEO_STREAM_DISPOSED;break;default:f=D.VIEW.APP_VIEW_DISPOSED}this._renderingDeferred.reject(new CallingCommunicationError({defaultError:f}))}if(this._target){const g=this._target.children&&this._target.children.length>0&&this._target.children[0];g&&g.removeEventListener("play",this.videoPlayEventListener),this._target.remove()}try{g!==wE.Public_App&&this._onDisposedCallback(g)}catch(g){this.logger.debug(`dispose callback failed with ${g?.message} error`)}this._watermarkOverlayProvider.dispose(),this._videoStream.unregisterRenderer(this),this._size.height=0,this._size.width=0,this._videoStream.updateSize(),this._isRendering=!1,this._videoStream.updateIsReceiving(),this._eventEmitter.removeAllListeners(),this._renderingDeferred=void 0}_checkIfVideoWasAttachedToDom(){if(getAcsEcsConfig().rendering.remoteVideo.checkIfVideoAttachedToDom_poll){let g=getAcsEcsConfig().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalMaxTries;const check=()=>{this._target.isConnected||g<=0?this.sendRendererTelemetry():(g--,g>=0&&setTimeout((()=>check),getAcsEcsConfig().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalTime))};check()}else setTimeout((()=>{this._target.isConnected&&this.sendRendererTelemetry()}),getAcsEcsConfig().rendering.remoteVideo.checkIfVideoAttachedToDom_timeout)}}__decorate$e([loggerProperty,__metadata$e("design:type",Object)],RemoteStreamRenderer.prototype,"logger",void 0),__decorate$e([asyncOperation(US.Start),__metadata$e("design:type",Function),__metadata$e("design:paramtypes",[]),__metadata$e("design:returntype",Promise)],RemoteStreamRenderer.prototype,"start",null),__decorate$e([syncOperation(US.Dispose),__metadata$e("design:type",Function),__metadata$e("design:paramtypes",[String]),__metadata$e("design:returntype",void 0)],RemoteStreamRenderer.prototype,"dispose",null);var __decorate$f=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$f=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class LocalStreamRenderer{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}constructor(g,f,S,v,C){this._target=g,this._videoStream=f,this._onDisposed=v,this._eventEmitter=new LE.EventEmitter,this._isRendering=!1,this._scalingMode="Stretch",this._isMirrored=!0,this._disposed=!1,this.logger=S.createChild("LocalStreamRenderer"),this.logger.log("created"),void 0!==C?.scalingMode&&(this._scalingMode=C.scalingMode),void 0!==C?.isMirrored?this._isMirrored=C.isMirrored:"ScreenSharing"===this._videoStream.mediaStreamType&&(this._isMirrored=!1),this._localStreamTelemetryEventSender=new StreamTelemetryEventSender(this._videoStream.telemetryLogManager)}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}async start(){const g=generateGuid(),f=this.logger.createFnLogger(US.Start),S=+new Date,v={timestampInfo:{attemptTimestamp:S},correlationId:g,operation:PE.render,kindOfEvent:gE.attempt,mediaType:this._videoStream.mediaStreamType,streamType:AE.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(v);try{if(f.info("attempting to select new device as a source"),this._videoStream.source instanceof VideoDeviceInfoImpl&&"Video"===this._videoStream.mediaStreamType){const g=this._videoStream.source.deviceManager.getTsDeviceManager();g.selectDevices({camera:this._videoStream.source.id}),f.info("device selected"),f.info("creating preview"),this._tsRenderer=await g.createPreview(this._target,{kind:"camera"},{scalingMode:toTsScalingMode(this._scalingMode),transparent:!1,ignoreMirroring:!1,disposeRendererWhenStreamisNotAvailable:()=>!0})}else{if("RawMedia"!==this._videoStream.mediaStreamType&&"ScreenSharing"!==this._videoStream.mediaStreamType)throw new CallingCommunicationError({defaultError:D.VIEW.UNKNOWN_STREAM_TYPE});this._rawMediaOrSS_previewVideo=document.createElement("video"),this._rawMediaOrSS_previewVideo.style.width="100%",this._rawMediaOrSS_previewVideo.style.height="100%",this._rawMediaOrSS_previewVideo.style.objectFit="contain",this._rawMediaOrSS_previewVideo.setAttribute("playsinline","true"),this._rawMediaOrSS_previewVideo.disablePictureInPicture=!0,this._rawMediaOrSS_previewVideo.autoplay=!0,this._rawMediaOrSS_previewVideo.srcObject=await this._videoStream.getMediaStream(),this._rawMediaOrSS_previewVideo.play(),this._target.appendChild(this._rawMediaOrSS_previewVideo)}this._isMirrored&&(this._target.style.transform="rotateY(180deg)",this._target.style.webkitTransform="rotateY(180deg)"),this._videoStream.registerRenderer(this);const v={timestampInfo:{deltaTimeInMs:+new Date-S},correlationId:g,operation:PE.render,kindOfEvent:gE.success,mediaType:this._videoStream.mediaStreamType,streamType:AE.Local};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(v),this}catch(v){this.dispose();const C=handleVideoOperationFailure(f,v),_={timestampInfo:{deltaTimeInMs:+new Date-S},correlationId:g,operation:PE.render,additionalDetails:{failureReason:C.message,code:C.code,subCode:C.subCode,...extractCommunicationServicesErrorForTelemetry(C)},kindOfEvent:gE.failure,mediaType:this._videoStream.mediaStreamType,streamType:AE.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(_),C}}setScalingMode(g){if(this._tsRenderer)this._tsRenderer.setScalingMode(toTsScalingMode(g)),this._scalingMode=g;else{if(!this._rawMediaOrSS_previewVideo)throw new CallingCommunicationError({defaultError:D.VIEW.SCALING_MODE});switch(g){case"Stretch":this._rawMediaOrSS_previewVideo.style.objectFit="fill";break;case"Crop":this._rawMediaOrSS_previewVideo.style.objectFit="cover";break;default:this._rawMediaOrSS_previewVideo.style.objectFit="contain"}}}setSourceObject(g){this.disposeScreenSharingMediaStream();const f=this._target.querySelector("video");f&&(f.srcObject=g,f.play())}dispose(){if(!this._disposed){if(this._tsRenderer)try{this.logger.log("disposing underlying local renderer"),this._tsRenderer.dispose(),this._tsRenderer=void 0}catch(g){throw this.logger.warn(`underlying local renderer dispose failed with ${g?.message} error`),new CallingCommunicationError({defaultError:D.VIEW.LOCAL_RENDERER_DISPOSE_FAIL})}this.disposeScreenSharingMediaStream(),this._target.remove(),this._onDisposed&&this._onDisposed(this),this._eventEmitter.removeAllListeners(),this._disposed=!0}}disposeScreenSharingMediaStream(){if(this._videoStream.getCall()?.localScreenSharingStream){const g=this._target.querySelector("video"),f=g?.srcObject;f&&(f.getVideoTracks().forEach((g=>{g.stop()})),g.srcObject=null,this.logger.info("disposed of ScreenSharing MediaStream"))}}}__decorate$f([loggerProperty,__metadata$f("design:type",Object)],LocalStreamRenderer.prototype,"logger",void 0),__decorate$f([asyncOperation(VS.Start),__metadata$f("design:type",Function),__metadata$f("design:paramtypes",[]),__metadata$f("design:returntype",Promise)],LocalStreamRenderer.prototype,"start",null),__decorate$f([syncOperation(VS.SetScalingMode),__metadata$f("design:type",Function),__metadata$f("design:paramtypes",[String]),__metadata$f("design:returntype",void 0)],LocalStreamRenderer.prototype,"setScalingMode",null),__decorate$f([syncOperation(VS.SetSourceObject),__metadata$f("design:type",Function),__metadata$f("design:paramtypes",[MediaStream]),__metadata$f("design:returntype",void 0)],LocalStreamRenderer.prototype,"setSourceObject",null),__decorate$f([syncOperation(VS.Dispose),__metadata$f("design:type",Function),__metadata$f("design:paramtypes",[]),__metadata$f("design:returntype",void 0)],LocalStreamRenderer.prototype,"dispose",null);var __decorate$g=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$g=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};let Xb=1;class VideoStreamRendererViewImpl{get scalingMode(){return this._streamRenderer.scalingMode}get isMirrored(){return this._streamRenderer.isMirrored}get disposed(){return this._disposed}constructor(g,f,S,v,C){if(this._videoStream=g,this._viewId=S,this._options=C,this._disposed=!1,this._deleteActiveRemoteVideoStreamView=(g,f)=>{if(g.call.activeRemoteVideoStreamViews?.has(g.id)){let S=g.call.activeRemoteVideoStreamViews?.get(g.id);S?.delete(f),0==S?.size&&g.call.activeRemoteVideoStreamViews?.delete(g.id)}},this.logger=f.createChild("VideoStreamRendererView"+Xb++),this.target=document.createElement("div"),this.target.style.width="100%",this.target.style.height="100%",this._videoStream instanceof RemoteVideoStreamCommonImpl)this._streamRenderer=new RemoteStreamRenderer(this.target,this._viewId,this._videoStream,this.logger,(g=>{this._disposed?noop():this.dispose(g)}),v,this._options);else{if(!(this._videoStream instanceof LocalVideoStream))throw new CallingCommunicationError({defaultError:D.VIEW.VIEW_WRONG_STREAM_TYPE});this._streamRenderer=new LocalStreamRenderer(this.target,this._videoStream,this.logger,(()=>this.dispose),this._options)}this._telemetryLogManager=this._videoStream.telemetryLogManager,this.logger.info("created")}async render(){const g=this.logger.createFnLogger(this._videoStream instanceof RemoteVideoStreamCommonImpl?DS.RenderRemoteStream:DS.RenderLocalStream);if(this._disposed)throw g.log("failed, stream disposed!"),new CallingCommunicationError({defaultError:D.VIEW.RENDER_FAIL_STREAM_DISPOSED});try{await this._streamRenderer.start()}catch(f){g.error("failed");try{this.dispose()}catch(g){this.logger.warn(`Failed to dispose, message=${g.message}`)}throw f}}async updateScalingMode(g){if(this._disposed)throw new CallingCommunicationError({defaultError:D.VIEW.SCALING_MODE_DISPOSED});if("Crop"!==g&&"Fit"!==g&&"Stretch"!==g)throw new CallingCommunicationError({defaultError:D.VIEW.SCALING_MODE_WRONG_VAL});try{await this._streamRenderer.setScalingMode(g)}catch(g){throw new CallingCommunicationError({defaultError:D.VIEW.SCALING_MODE,originalError:g})}}dispose(g=wE.Public_App){if(this._disposed)throw new CallingCommunicationError({defaultError:D.VIEW.VIEW_ALREADY_DISPOSED});this._disposed=!0;const f=+new Date,S=generateGuid();try{g===wE.Public_App&&this.sendDisposeViewEvent({eventName:uE.acs_calling_dispose_view_attempt,correlationId:S,timestampInfo:{attemptTimestamp:f}}),this._videoStream instanceof RemoteVideoStreamImpl&&this._deleteActiveRemoteVideoStreamView(this._videoStream,this._viewId),this.logger.debug("attempt to dispose stream renderer"),this._streamRenderer.dispose(g),this.target?.remove();const v=+new Date;g===wE.Public_App&&this.sendDisposeViewEvent({eventName:uE.acs_calling_dispose_view_success,correlationId:S,timestampInfo:{deltaTimeInMs:v-f}})}catch(v){const C=new CallingCommunicationError({defaultError:D.VIEW.DISPOSE_FAIL,originalError:v});if(g===wE.Public_App){const g=+new Date;this.sendDisposeViewEvent({eventName:uE.acs_calling_dispose_view_failure,correlationId:S,timestampInfo:{deltaTimeInMS:g-f}},C)}throw C}}sendDisposeViewEvent(g,f){try{let S,v;f&&(S="string"==typeof f?.message?f?.message:"",v={...extractCommunicationServicesErrorForTelemetry(f)}),this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:{...this._videoStream.getStreamMetadata(),viewId:this._viewId,correlationId:g.correlationId,timestampInfo:g.timestampInfo,failureReason:S,additionalDetails:v}})}catch(g){this.logger.debug("Unable to send telemtery")}}}function collectLiveStreamStatsForCreateView(g,f,S,v){const C=["audioBitrate","videoBitrate","downloadBitrate","bufferLengthInMs","videoHeight","videoWidth","currentPlayPosition"],_=f[S.toString()];void 0!==_&&C.forEach((f=>{const S=f,C=f;if(void 0!==_[S]){const f=_[S];if(void 0===g[C])g[C]=[f];else{const S=g[C]?.length;S>=v&&g[C]?.shift(),g[C]?.push(f)}}}))}__decorate$g([loggerProperty,__metadata$g("design:type",Object)],VideoStreamRendererViewImpl.prototype,"logger",void 0),__decorate$g([asyncOperation(DS.Render),__metadata$g("design:type",Function),__metadata$g("design:paramtypes",[]),__metadata$g("design:returntype",Promise)],VideoStreamRendererViewImpl.prototype,"render",null),__decorate$g([asyncOperation(DS.UpdateScalingMode),__metadata$g("design:type",Function),__metadata$g("design:paramtypes",[String]),__metadata$g("design:returntype",Promise)],VideoStreamRendererViewImpl.prototype,"updateScalingMode",null),__decorate$g([syncOperation(DS.Dispose),__metadata$g("design:type",Function),__metadata$g("design:paramtypes",[String]),__metadata$g("design:returntype",void 0)],VideoStreamRendererViewImpl.prototype,"dispose",null);class CreateViewTelemetryHelper{get createViewStats(){return this._createViewStats}get initialCreateViewStats(){return this._initialCreateViewStats}constructor(g,f,S,v,C){this._statsCollector=g,this._streamId=f,this._logger=S,this._call=v,this._attemptTimestamp=C,this._createViewFailureStats={},this._createViewStats={},this._initialCreateViewStats={},this._statsCollector.on("sampleReported",(g=>{collectMediaStatsForCreateView(this.createViewStats,this.initialCreateViewStats,g,this._streamId)}))}getCreateViewFailureStats(){try{let g=0,f=NaN;void 0!==this.createViewStats.video?.framesDropped&&void 0!==this.initialCreateViewStats.video?.framesDropped&&(g=this.createViewStats.video?.framesDropped.length,f=this.createViewStats.video?.framesDropped[g-1]-this.initialCreateViewStats.video?.framesDropped[0]);let S=NaN;void 0!==this.createViewStats.video?.framesReceived&&void 0!==this.initialCreateViewStats.video?.framesReceived&&(g=this.createViewStats.video.framesReceived.length,S=this.createViewStats.video.framesReceived[g-1]-this.initialCreateViewStats.video?.framesReceived[0]);let v=NaN;void 0!==this.createViewStats.video?.framesDecoded&&void 0!==this.initialCreateViewStats.video?.framesDecoded&&(g=this.createViewStats.video.framesDecoded.length,v=this.createViewStats.video.framesDecoded[g-1]-this.initialCreateViewStats.video?.framesDecoded[0]);let C=NaN;void 0!==this.createViewStats.video?.keyFramesDecoded&&void 0!==this.initialCreateViewStats.video?.keyFramesDecoded&&(g=this.createViewStats.video.keyFramesDecoded.length,C=this.createViewStats.video.keyFramesDecoded[g-1]-this.initialCreateViewStats.video?.keyFramesDecoded[0]);let _=0;!isNaN(f)&&S>0&&(_=Number((f/S*100).toFixed(7)));let T=!1;S>0&&0===v&&(T=!0);let I=!1;!isNaN(v)&&!isNaN(C)&&v>0&&v===C&&(I=!0);const b=[],A=this._call.networkQualityUfdEventDetails,P=getAcsEcsConfig().rendering.remoteVideo.createViewFailureNetworkUfdCheckWindowInMs;A.forEach((g=>{Math.abs(g.timestampInfo-this._attemptTimestamp)<=P&&b.push(g)}));const R=0===S;this._createViewFailureStats.video={framesDroppedPercentage:_,framesReceivedButNothingDecoded:T,onlyKeyFramesDecoded:I,networkQualityEventsDuringAttempt:b,zeroFramesReceived:R}}catch(g){this._logger.debug("Error calculating create view failure stats!")}return this._createViewFailureStats}}class CreateViewLiveStreamTelemetryHelper{constructor(g,f){this._liveStreamStatsCollector=g,this._streamId=f,this._liveStreamStats={},this._initialLiveStreamStats={};const S=getAcsEcsConfig()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength;this._liveStreamStatsCollector.on("sampleReported",(g=>{collectLiveStreamStatsForCreateView(this._liveStreamStats,g,this._streamId,S),M.isEmpty(this._initialLiveStreamStats)&&(this._initialLiveStreamStats=this._liveStreamStats)}))}get initialCreateViewLiveStreamStats(){return this._initialLiveStreamStats}get createViewLiveStreamStats(){return this._liveStreamStats}}var __decorate$h=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$h=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class VideoStreamRenderer{get _createViewStats(){return"RemoteVideoStream"!==this._videoStream.kind&&"ComposedVideoStream"!==this._videoStream.kind||!this._createViewTelemetryHelper?"LiveVideoStream"===this._videoStream.kind&&this._createViewLiveStreamTelemetryHelper?this._createViewLiveStreamTelemetryHelper.createViewLiveStreamStats:{}:this._createViewTelemetryHelper.createViewStats}constructor(g){if(this.size={height:0,width:0},this.views=new Map,this.disposed=!1,this._attemptToDisposeView=g=>{try{g?.dispose()}catch(g){this.logger.warn(g?.message||"Failed to dispose, unknown error")}},this._addActiveRemoteVideoStreamView=(g,f,S)=>{if(g.call.activeRemoteVideoStreamViews?.has(g.id)){let v=g.call.activeRemoteVideoStreamViews?.get(g.id);v&&v.set(f,S)}else{let v=new Map;v.set(f,S),g.call.activeRemoteVideoStreamViews?.set(g.id,v)}},!(g instanceof LocalVideoStream||g instanceof RemoteVideoStreamCommonImpl||g instanceof RemoteVideoStreamImpl))throw new CallingCommunicationError({defaultError:D.VIEW.RENDERER_WRONG_STREAM_TYPE});const S=f.createClientLogger("ACS");this._videoStream=g,this._telemetryLogManager=g.telemetryLogManager,this.logger=new DefaultLogger(S,g instanceof LocalVideoStream?[()=>`VideoStreamRenderer:LocalVideoStream:${R.pii.Omit(g?.source?.id)}`]:[()=>`VideoStreamRenderer:${g.kind}:${g?.id}`]),this.logger.info("created")}async createView(g){if(this.disposed)throw new CallingCommunicationError({defaultError:D.VIEW.RENDERER_DISPOSED});const f={},S=+new Date,v=generateGuid(),C=generateGuid();let _,T;try{if(f.attemptTimestamp=S,this.sendCreateViewEvent({eventName:uE.acs_calling_create_view_attempt,viewId:v,correlationId:C,timestampInfo:{attemptTimestamp:S},isMirrored:g?.isMirrored,scalingMode:g?.scalingMode,stepsInfo:f}),"RemoteVideoStream"===this._videoStream.kind&&!this._videoStream.isAvailable)throw new CallingCommunicationError({defaultError:D.VIEW.ISAVAILABLE_FALSE});if("RemoteVideoStream"===this._videoStream.kind&&"ScreenSharing"!==this._videoStream.mediaStreamType&&getAcsEcsConfig()?.calling.applyViewLimit&&getMediaConfig()?.numVideoChannelsGvc){const g=getMediaConfig().numVideoChannelsGvc,f=this._videoStream;if(!f.call.activeRemoteVideoStreamViews?.has(f.id)&&f.call.activeRemoteVideoStreamViews?.size>=g)throw new CallingCommunicationError({defaultError:D.VIEW.MAX_NUM_OF_VIEWS_REACHED,defaultErrorMessageArgs:[g]})}if(getAcsEcsConfig()?.rendering.remoteVideo.createViewSendMediaStats)if("RemoteVideoStream"===this._videoStream.kind||"ComposedVideoStream"===this._videoStream.kind){const g=this._videoStream,f=g.call;T=g.call.feature(fb.MediaStats).createCollector();const v=g.id;this._createViewTelemetryHelper=new CreateViewTelemetryHelper(T,v,this.logger,f,S)}else if("LiveVideoStream"===this._videoStream.kind){const g=this._videoStream;T=g.call.feature(fb.LiveStream).createStatsCollector();const f=g.id;this._createViewLiveStreamTelemetryHelper=new CreateViewLiveStreamTelemetryHelper(T,f)}_=new VideoStreamRendererViewImpl(this._videoStream,this.logger,v,f,g),this.views.set(v,_),await _.render(),"RemoteVideoStream"===this._videoStream.kind&&"ScreenSharing"!==this._videoStream.mediaStreamType&&this._addActiveRemoteVideoStreamView(this._videoStream,v,_);const I=+new Date;return this.sendCreateViewEvent({eventName:uE.acs_calling_create_view_success,viewId:v,correlationId:C,timestampInfo:{deltaTimeInMs:I-S},stepsInfo:f}),_}catch(g){const T=new CallingCommunicationError({defaultError:D.VIEW.CREATE_VIEW_FAILED,originalError:g});if(this.views.delete(v),this._attemptToDisposeView(_),T.message!==D.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&T.message!==D.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){const g=Date.now();this.sendCreateViewEvent({eventName:uE.acs_calling_create_view_failure,viewId:v,correlationId:C,timestampInfo:{deltaTimeInMs:g-S},stepsInfo:f},T)}throw T}finally{T?.dispose()}}async sendCreateViewEvent(g,f){try{let S={},v={},C={};if(getAcsEcsConfig()?.rendering.remoteVideo.createViewSendMediaStats&&(g.eventName===uE.acs_calling_create_view_failure||g.eventName===uE.acs_calling_create_view_success)){if("RemoteVideoStream"===this._videoStream.kind){const g=this._videoStream.call,f=await(g.tsCall.getMediaSessionStatsAsync?.());S={videoSubscriptionEvents:f?.extensions?.Video_SubscriptionEvents,screenSharingSubscriptionEvents:f?.extensions?.Sharing_SubscriptionEvents,videoSendMaxCapabilities:f?.extensions?.Video_send_MaxCapabilities,screenSharingSendMaxCapabilities:f?.extensions?.Sharing_send_MaxCapabilities,iceConnectedStateTime:f?.metrics?.IceConnectedStateTime,relayCandidate:f?.extensions?.RelayCandidate,videoRecvTimeToFirstFrame:f?.extensions?.Video_recv_TimeToFirstFrame,screenSharingRecvTimeToFirstFrame:f?.extensions?.Sharing_recv_TimeToFirstFrame,optimalVideoCount:g.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:g.activeRemoteVideoStreamViews?.size||0}}g.eventName===uE.acs_calling_create_view_failure&&(C=this._createViewTelemetryHelper?.getCreateViewFailureStats()??{},v=this._createViewStats)}S.visibilityState=document.visibilityState,void 0!==g.isMirrored&&(S.isMirrored=g.isMirrored),void 0!==g.scalingMode&&(S.scalingMode=g.scalingMode),g.eventName!==uE.acs_calling_create_view_failure&&g.eventName!==uE.acs_calling_create_view_success||"RemoteVideoStream"!==this._videoStream.kind&&"ComposedVideoStream"!==this._videoStream.kind||M.forOwn(g.stepsInfo,((g,f)=>{void 0!==g&&(S[f]=g)}));let _="",T={};f&&(_="string"==typeof f?.message?f?.message:"",T={...extractCommunicationServicesErrorForTelemetry(f)}),this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:{viewId:g.viewId,correlationId:g.correlationId,timestampInfo:g.timestampInfo,...this._videoStream.getStreamMetadata(),failureReason:_,additionalProperties:S,additionalDetails:T,stats:v,createViewFailureDebugStats:C,videoStreamKind:this._videoStream.kind}})}catch(g){this.logger.debug("Unable to send telemtery")}}dispose(){if(this.disposed)throw new CallingCommunicationError({defaultError:D.VIEW.RENDERER_ALREADY_DISPOSED});this.disposed=!0,this.views.forEach(this._attemptToDisposeView),this.views.clear()}}__decorate$h([loggerProperty,__metadata$h("design:type",Object)],VideoStreamRenderer.prototype,"logger",void 0),__decorate$h([asyncOperation(NS.CreateView),__metadata$h("design:type",Function),__metadata$h("design:paramtypes",[Object]),__metadata$h("design:returntype",Promise)],VideoStreamRenderer.prototype,"createView",null),__decorate$h([syncOperation(NS.Dispose),__metadata$h("design:type",Function),__metadata$h("design:paramtypes",[]),__metadata$h("design:returntype",void 0)],VideoStreamRenderer.prototype,"dispose",null);var __decorate$i=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$i=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class RemoteParticipantImpl{get identifier(){return this._identifier}get endpointDetails(){return this._tsParticipant?.endpoints?.endpointDetails.map((g=>({participantId:g.participantId,deviceType:g.deviceType,clientEndpointCapabilities:g.clientEndpointCapabilities,endpointMetadata:g.endpointMetadata})))||[]}get state(){return this._state}get videoStreams(){return[...this._mappedStreams.values()]}get isMuted(){return this._isMuted}get isSpeaking(){return this._isSpeaking}get callEndReason(){return this._callEndReason}get displayName(){return this._displayName}get role(){return this._role}constructor(g,f,S,v,C){this._mappedStreams=new Map,this._state="Idle",this._lastTsParticipantState=0,this._isMuted=!1,this._isSpeaking=!1,this._displayName="",this._role="Unknown",this.acsToTsStreamType=g=>"Video"===g?0:"ScreenSharing"===g?1:void 0,this._identifier=g,this.logger=f.createChild((()=>`RemoteParticipant{${this._identifier.kind}}`)),this._telemetryLogManager=C,this._eventEmitter=new CallingEventEmitter(this.logger),this._callAgent=v,this._call=S,this.logger.log("created"),this._renderers={Video:{renderingState:{}},ScreenSharing:{renderingState:{}}}}on(g,f){if("stateChanged"!==g&&"isMutedChanged"!==g&&"isSpeakingChanged"!==g&&"displayNameChanged"!==g&&"roleChanged"!==g&&"videoStreamsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.REMOTE_PARTICIPANT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("stateChanged"!==g&&"isMutedChanged"!==g&&"isSpeakingChanged"!==g&&"displayNameChanged"!==g&&"roleChanged"!==g&&"videoStreamsUpdated"!==g)throw new CallingCommunicationError({defaultError:D.REMOTE_PARTICIPANT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}async mute(){const g=getAcsEcsConfig();if(!g.calling.enableMuteOthers)throw new CallingCommunicationError({defaultError:D.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_DISABLED});if(!this._call.tsCall.conversationType&&this._call.callInfo.context===jS.TwoParty)throw new CallingCommunicationError({defaultError:D.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_1_TO_1_UNSUPPORTED});if(!["Connected","Hold"].some((g=>g===this._state)))throw new CallingCommunicationError({defaultError:D.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_NONCONNECTED_UNSUPPORTED});const f=this.logger.createFnLogger(RS.Mute),S=+new Date,v=generateGuid();if(this.sendAudioEvent({eventName:uE.acs_calling_mute_attempt,eventType:mE.MuteSpecificParticipant,timestampInfo:{attemptTimestamp:S},correlationId:v,step:"mid-call"}),!g.calling.allowMutePstnRemoteParticipant&&"phoneNumber"===this._identifier.kind){const g=+new Date,C=D.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_PSTN_UNSUPPORTED;f.warn(C.message);const _=new CallingCommunicationError({defaultError:C});throw this.sendAudioEvent({eventName:uE.acs_calling_mute_failure,eventType:mE.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:g-S},correlationId:v,step:"mid-call"},_),_}try{f.info("remote mute specific"),void 0!==this._tsParticipant?await this._call.tsCall.muteParticipants(1,[this._tsParticipant]):f.warn("no participant to mute in attempt to mute specific remote participant"),f.info("remote mute specific success");const g=+new Date;this.sendAudioEvent({eventName:uE.acs_calling_mute_success,eventType:mE.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:g-S},correlationId:v,step:"mid-call"})}catch(g){const C=new CallingCommunicationError({defaultError:D.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_FAILED,originalError:g});f.error(C.message);const _=+new Date;throw this.sendAudioEvent({eventName:uE.acs_calling_mute_failure,eventType:mE.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:_-S},correlationId:v,step:"mid-call"},C),C}}_dispose(){this.logger.log("dispose"),this._participantChangedHandler&&this._participantChangedHandler.dispose(),this._mappedStreams.forEach((g=>g.dispose())),this._eventEmitter.emit("stateChanged",this._state),this._eventEmitter.removeAllListeners(),this._disposeVideo(0),this._disposeVideo(1)}get tsRemoteParticipant(){return this._tsParticipant}get kind(){return"RemoteParticipant"}setCallEndReason(g){this._callEndReason=g}observeParticipant(g){this._tsParticipant||(this._tsParticipant=g,this._displayName=g.displayName,this._isMuted=g.isServerMuted,this._participantChangedHandler=this._tsParticipant.changed((()=>{if(this._tsParticipant&&this._tsParticipant.state!==this._lastTsParticipantState&&(this._lastTsParticipantState=this._tsParticipant.state,this._mapTsParticipantState(this._tsParticipant.state)),this._mapStreams(),this._tsParticipant&&this._tsParticipant.isServerMuted!==this._isMuted&&(this._isMuted=this._tsParticipant.isServerMuted,this._eventEmitter.emit("isMutedChanged")),this._tsParticipant&&this._tsParticipant.displayName&&this._tsParticipant.displayName!==this._displayName&&(this._displayName=g.displayName,this._eventEmitter.emit("displayNameChanged")),this._tsParticipant&&this._tsParticipant.advancedMeetingRole!==this._lastTsParticipantAdvancedRole&&(this._lastTsParticipantAdvancedRole=g.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole)),this._tsParticipant){const g=0!==this._tsParticipant.voiceLevel;g!==this._isSpeaking&&(this._isSpeaking=g,this._eventEmitter.emit("isSpeakingChanged"))}})),this._mapTsParticipantState(this._tsParticipant.state),this._mapStreams(),this._lastTsParticipantAdvancedRole=this._tsParticipant.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole),this._displayName||!S.isMicrosoftTeamsAppIdentifier(this._identifier)&&!S.isMicrosoftTeamsUserIdentifier(this._identifier)||this.getRemoteParticipantProperties().then((g=>{g?.displayName&&(this._displayName=g.displayName,this._eventEmitter.emit("displayNameChanged"))})).catch((g=>{this.logger.error(`Failed to get remote participant properties: ${g}`)})))}setParticipantState(g){g!==this._state&&(this.logger.log(`state changed ${this._state}=>${this.state}`),this._state=g,"Disconnected"==this._state?this._dispose():this._eventEmitter.emit("stateChanged",this._state))}async stopRenderingVideo(){this._disposeVideo(0)}async renderVideo(g,f){if("function"==typeof g)return this._updateRenderingState(g,"Video",f);return await this._renderStreamForParticipant(g,0,f)}async _updateRenderingState(g,f,S){if("function"==typeof g){let v;const C="Video"===f?0:1;this._tsParticipant&&(v=S?.stream?S.stream:new RemoteVideoStreamImpl(this._tsParticipant.streams[C][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier),v.on("isReceivingChanged",(()=>{this._renderers[f].renderingState.isFrozen=!v.isReceiving,g(this._renderers[f].renderingState)})),v.on("isAvailableChanged",(async()=>{this._renderers[f].renderingState.isStreaming!==v?.isAvailable&&(this._renderers[f].renderingState.isStreaming=v.isAvailable,this._renderers[f].renderingState.isStreaming&&!this._renderers[f].renderer&&(this._renderers[f].renderer=this._renderers[f]?.renderer?this._renderers[f].renderer:new VideoStreamRenderer(v),this._renderers[f].view||(this._renderers[f].view=await(this._renderers[f].renderer?.createView(S?.viewOptions))),this._renderers[f].renderingState.videoTarget=this._renderers[f].view?.target)),g(this._renderers[f].renderingState)})))}}async renderScreenShare(g,f){if("function"==typeof g)return this._updateRenderingState(g,"ScreenSharing",f);return this._renderStreamForParticipant(g,1,f)}async _renderStreamForParticipant(g,f,S){if(this._tsParticipant){const v=0===f?"Video":"ScreenSharing",C=S?.stream?S.stream:new RemoteVideoStreamImpl(this._tsParticipant.streams[f][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);return C.isAvailable&&(this._renderers[v].view=await this._appendVideo(g,f,C,S?.viewOptions)),C.on("isAvailableChanged",(async()=>{C.isAvailable?this._renderers[v].view=await this._appendVideo(g,f,C,S?.viewOptions):this._renderers[v]?.view&&this._renderers[v].view?.target&&this._renderers[v].view?.target.parentNode?.removeChild(this._renderers[v].view?.target)})),Promise.resolve({stream:C,view:this._renderers[v]?.view})}return Promise.reject()}async _appendVideo(g,f,S,v){try{const C=0===f?"Video":"ScreenSharing";if(0===f&&(this._renderers[C]?.renderer||(this._renderers[C].renderer=this._renderers[C]?.renderer?this._renderers[C].renderer:new VideoStreamRenderer(S),this._renderers[C].view=await(this._renderers[C].renderer?.createView(v))),this._renderers[C].view))return g.appendChild(this._renderers[C].view?.target||document.createElement("emptyNode")),Promise.resolve(this._renderers[C].view)}catch(g){return Promise.reject(g)}return Promise.reject()}async _disposeVideo(g){const f=0===g?"Video":"ScreenSharing";this._renderers[f].view?.dispose(),this._renderers[f].renderer?.dispose(),this._renderers[f]={renderingState:{}}}_setParticipantRole(g){let f=advancedMeetingRoleToParticipantRole(getAcsEcsConfig(),g);"Unknown"===f?this.logger.log(`tsParticipant advancedMeetingRole=${g} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${g}=>${f}`),this._role!=f&&(this.logger.log(`role changed ${this._role}=>${g}`),this._role=f,this._eventEmitter.emit("roleChanged"))}_mapTsParticipantState(g){let f;const S={0:"Idle",1:"Connecting",2:"Ringing",3:"Connected",4:"Disconnected",5:"Hold",7:"InLobby",6:"EarlyMedia"};S[g]?(f=S[g],this.logger.log(`mapped tsParticipant ${g}=>${this._state}`),this.setParticipantState(f)):this.logger.log(`unable to map tsCall state=${g} to call state`)}_mapStreams(){const g=[],f=[],handleNewStream=g=>{this._mappedStreams.set(g.id,g)},handleRemovedStream=g=>{const f=this._mappedStreams.get(g.id);f&&(this.logger.log(`stream removed, type==${f.mediaStreamType} id=${g.id}`),this._mappedStreams.delete(g.id),f.dispose())},mapStreamsOfType=S=>{if(this._tsParticipant)if(this._tsParticipant.streams&&isNonEmptyArray(this._tsParticipant.streams[S])){let v=[];this._tsParticipant&&(v=this._tsParticipant.streams[S]),v.forEach((f=>{if(!this._mappedStreams.get(f.id)){const S=new RemoteVideoStreamImpl(f,this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);this.logger.log(`stream created, type==${S.mediaStreamType} id=${f.id}`),g.push(S)}})),this._mappedStreams.forEach((g=>{if(this.acsToTsStreamType(g.mediaStreamType)===S){v.some((f=>f.id===g.id))||f.push(g)}}))}else this._mappedStreams.forEach((g=>{this.acsToTsStreamType(g.mediaStreamType)===S&&f.push(g)}))};mapStreamsOfType(0),mapStreamsOfType(1),(g.length>0||f.length>0)&&(g.forEach(handleNewStream),f.forEach(handleRemovedStream),this._eventEmitter.emit("videoStreamsUpdated",{added:g,removed:f}))}sendAudioEvent(g,f){try{let S,v;f&&(S=f.message,v=extractCommunicationServicesErrorForTelemetry(f));const C={callId:this._call.id,timestampInfo:g.timestampInfo,correlationId:g.correlationId,step:g.step||"",failureReason:S||"",additionalDetails:{...v}};void 0!==g.eventType&&(C.eventType=g.eventType),this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:C})}catch(g){this.logger.debug("Unable to send mute others audio telemetry")}}getRemoteParticipantProperties(){return new Promise((g=>{const f={policyUrlSuffix:getAcsEcsConfig().MiddleTier.policyUrlSuffixV2,userPolicies:["TeamsMeetingPolicy"],userProperties:["displayName"]};this._callAgent.mtPolicyService.requestUserPoliciesFromAcsMiddleTier(this._call.id,getMriFromIdentifier(this.identifier),f,this._callAgent.getUserMri()).then((f=>{g(f.userAggregatedPolicySettingData?.userProperties)}))}))}}__decorate$i([loggerProperty,__metadata$i("design:type",Object)],RemoteParticipantImpl.prototype,"logger",void 0),__decorate$i([asyncOperation(RS.Mute),__metadata$i("design:type",Function),__metadata$i("design:paramtypes",[]),__metadata$i("design:returntype",Promise)],RemoteParticipantImpl.prototype,"mute",null);class SelectedDeviceManager{constructor(g){this._deviceManager=g,this._eventEmitter=new LE.EventEmitter,this._selectedDeviceListeners=new Map,this._selectedDevices=new Map,this._deviceInfoMapper=this._deviceManager.deviceInfoMapper;const createSelectedDeviceListener=g=>()=>{const f=this._selectedDevices.get(g),S=(()=>"Speaker"===g?this._deviceManager.selectedSpeaker:"Microphone"===g?this._deviceManager.selectedMicrophone:void 0)(),v=void 0===S?void 0:{id:this._deviceInfoMapper.getDeviceId(S.id),name:this._deviceInfoMapper.scrubDeviceLabel(S.name)};this._selectedDevices.set(g,v),this._eventEmitter.emit("selectedDeviceChanged",{selectedDeviceType:g,oldDevice:f,newDevice:v})},f=createSelectedDeviceListener("Speaker");this._selectedDeviceListeners.set("Speaker",f),this._deviceManager.on("selectedSpeakerChanged",f),f();const S=createSelectedDeviceListener("Microphone");this._selectedDeviceListeners.set("Microphone",S),this._deviceManager.on("selectedMicrophoneChanged",S),S()}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}selectedDevice(g){return this._selectedDevices.get(g)}dispose(){const g=this._selectedDeviceListeners.get("Speaker");g&&this._deviceManager.off("selectedSpeakerChanged",g);const f=this._selectedDeviceListeners.get("Microphone");f&&this._deviceManager.off("selectedMicrophoneChanged",f),this._eventEmitter.removeAllListeners()}}function getCallProgressCommonPayload(f,S,v,C){const _=C===lS.RoomCall||f.kind===g.CallKind.Call&&"Incoming"==f.direction&&!f.tsCall.groupId&&!!f.tsCall.meetingData?.meetingCode&&!f.tsCall.threadId,T=!_&&C===lS.TeamsMeetingLink||C===lS.TeamsMeetingId||C===lS.TeamsCoordinates||"Incoming"==f.direction&&!f.tsCall.groupId&&!!f.tsCall.meetingData&&!!f.tsCall.threadId,I={audio:"",video:""},b=f.localAudioStreams?.[0];b&&(I.audio=b.getEffectsCurrentStateRecord()??"");const A=f.localVideoStreams?.[0];return A&&(I.video=A.getEffectsCurrentStateRecord()??""),{timestampInfo:{attemptTimestamp:+new Date},correlationId:v,localParticipantId:f.tsCall.participantId||"",isAcsTeamsCall:f.isAcsTeamsCall,callId:f.tsCall.callId||"",callType:f.tsCall.callType||"",callDirection:f.direction,state:"Ringing"===f.state?"Ringing":qE[f.tsCall.state],groupJoin:!!f.tsCall.groupId,roomJoin:_,meetingJoin:T,callEndDiagnosticsInfo:f.tsCall.callEndDiagnosticsInfo||{},isSupportedEnvironment:S?.runningEnvironmentInfo?.isSupportedEnvironment,effectsStateInfo:I,hostRegion:f.tsCall.region||"",diagnosticInfo:{...f.tsCall.callEndDiagnosticsInfo,telemetryPayloadBytesOriginal:TelemetryLogManager.telemetryPayloadBytesOriginal,telemetryPayloadBytesCompressed:TelemetryLogManager.telemetryPayloadBytesCompressed}}}function sendCallProgressEvent(g,f,S){try{"state-changed"===S.step&&"Connecting"===S.newState&&(TelemetryLogManager.telemetryPayloadBytesOriginal=0,TelemetryLogManager.telemetryPayloadBytesCompressed=0),g.sendEvent({name:uE.acs_calling_call_progress,tenant:tf,properties:S})}catch(g){f.error(`Failed to send event: ${uE.acs_calling_call_progress} step: ${S.step}`)}}var __decorate$j=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$j=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class CallInfoCommonImpl{get threadId(){return this._threadId}get roomId(){return this._roomId}get groupId(){return this._groupId}get participantId(){return this._tsCall.participantId}get isPstnInterop(){return this._isPstnInterop}get isTeamsInterop(){return this._isTeamsInterop}get callScenario(){if(this._tsCall.callQueueInfo)return $S.CallQueue;if("unknown"!==this.transferorKind){if("transfer"===this._tsCall.incomingCallType)return $S.TransferToParticipant;if("replaces"===this._tsCall.incomingCallType)return $S.TransferToCall}return"Incoming"===this.direction?"AcceptCall":"Outgoing"===this.direction&&"Rooms"==this.context?$S.JoinRoom:"Outgoing"===this.direction&&"TeamsMeeting"==this.context?$S.JoinTeamMeeting:"Outgoing"===this.direction&&"GroupIdCall"==this.context?$S.JoinWithGroupId:$S.PlaceCall}get context(){return 1==this._tsCall.callType||this._currentCallContext==jS.TwoParty?jS.TwoParty:this._tsCall.groupId?jS.GroupIdCall:"groupCall"==this._tsCall.conversationType||this._currentCallContext==jS.MultiParty?jS.MultiParty:this._config?.roomId||this._roomId||this._tsCall.meetingData?.meetingCode?.startsWith("994")||this._tsCall.meetingData?.meetingCode?.startsWith("995")||this._tsCall.meetingData?.meetingCode?.startsWith("996")?jS.Rooms:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.passcode||"scheduledMeeting"==this._tsCall.conversationType?jS.TeamsMeeting:(this._tsCall.callType,jS.MultiParty)}get transferorKind(){return this._tsCall.transferorMri?constructIdentifierKindFromMri(this._tsCall.transferorMri||"").kind:""}get direction(){return this._config?.isIncoming?IS.Incoming:IS.Outgoing}get initiatorKind(){return constructIdentifierKindFromMri(this._tsCall.callerMri?this._tsCall.callerMri:"").kind}get targetKind(){if(this._tsCall.groupId)return this._tsCall.groupId;if(this._config?.roomId)return this._config.roomId;if(this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.meetingCode)return"TeamsMeetingJoinLink";if(this._tsCall.transferorMri)return"Transferee";if(1===this._tsCall.participants.length){return constructIdentifierKindFromMri(this._tsCall.participants[0].id).kind}return this._tsCall.participants.filter((g=>g.id!==this._tsCall.callerMri)).map((g=>constructIdentifierKindFromMri(g.id).kind)).toString()}constructor(g,f={}){this._tsCall=g,this._threadId=this._tsCall.threadId;const S=this._tsCall.groupId;this._groupId=!S||S.startsWith("19:")||S.startsWith("99:")?void 0:S,this._roomId=f?.config?.roomId,this._config=f.config,this._isPstnInterop=!1,this._isTeamsInterop=!1}setThreadId(g){this._threadId=g}initialize(g,f,S){this._logger=f,this._eventEmitter=g,this._threadId=this._tsCall.threadId,this._tsCallChangedListener=this._tsCall.changed((()=>this.threadIdChanged(this._tsCall))),this._p2pCallListener=this._tsCall.changed((()=>this.p2pCallHandler())),this._isPstnInterop=this.isPSTNUserInCall,this._isTeamsInterop=this.isTeamsUserInCall,this._participantUpdatedListener=this._tsCall.on("participantCountsUpdated",(()=>{this.interoperabilityChangeHandler(),this.p2pCallEscalationHandler()}))}async getServerCallId(){const g=JSON.parse(await this._tsCall.getJoinBlob()),f=g?.conversationUrl;if(!f)throw new CallingCommunicationError({defaultError:D.CALL.GET_SERVER_CALL_ID});return base64UrlEncoding(f)}p2pCallHandler(){null==this._currentCallContext&&1==this._tsCall.callType&&(this._currentCallContext=jS.TwoParty)}p2pCallEscalationHandler(){this._currentCallContext==jS.TwoParty&&getTotalNotBotParticipantCount(this._tsCall)>2&&(this._currentCallContext=jS.MultiParty,this._eventEmitter.emit("callInfoChanged"),this._p2pCallListener?.dispose())}get isTeamsUserInCall(){if(!this._tsCall.participants)return!1;for(const g of this._tsCall.participants)if("microsoftTeamsUser"===constructIdentifierKindFromMri(g.id).kind)return!0;return!1}get isPSTNUserInCall(){if(!this._tsCall.participants)return!1;for(const g of this._tsCall.participants)if("phoneNumber"===constructIdentifierKindFromMri(g.id).kind)return!0;return!1}interoperabilityChangeHandler(){!this._isPstnInterop&&this.isPSTNUserInCall&&(this._isPstnInterop=!0,this._eventEmitter.emit("callInfoChanged")),!this._isTeamsInterop&&this.isTeamsUserInCall&&(this._isTeamsInterop=!0,this._eventEmitter.emit("callInfoChanged"))}threadIdChanged(g){this._tsCall.threadId!==this._threadId&&(this._logger.log(`threadId changed from ${this._threadId} to ${g?.threadId}`),this._threadId=this._tsCall.threadId,this._eventEmitter.emit("threadIdChanged"))}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}onCallInfoChanged(g,f){this._eventEmitter.on(g,f)}offCallInfoChanged(g,f){this._eventEmitter.off(g,f)}dispose(){this._tsCallChangedListener?.dispose(),this._eventEmitter.removeAllListeners(),this._p2pCallListener?.dispose(),this._participantUpdatedListener?.dispose()}}__decorate$j([asyncOperation(MS.GetServerCallId),__metadata$j("design:type",Function),__metadata$j("design:paramtypes",[]),__metadata$j("design:returntype",Promise)],CallInfoCommonImpl.prototype,"getServerCallId",null);class ExplicitConsentCallStateManager{constructor(g,f,S,v,C){this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,this._isExplicitConsentEnabled=!1,this._isInitialized=!1,this._isExplicitConsentEnabled=getAcsEcsConfig().calling.explicitConsentFeatureEnabled.enabled,this.initialize(g,f,S,v,C)}dispose(){this._isInitialized=!1,this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,ExplicitConsentCallStateManager.instance=null}isConsentRequiredInCall(){if(!this._isExplicitConsentEnabled)return!1;let g=this._recordingConsentEnabled&&!this._localParticipantConsentPublishState;return this._logger.info("ExplicitConsentCallStateManager: isConsentRequiredInCall: Recording Consent Enabled: "+this._recordingConsentEnabled+" Local Participant Consent Publish State: "+this._localParticipantConsentPublishState),this._logger.log("ExplicitConsentCallStateManager: isConsentRequiredInCall: "+g),g}async consent(g){if(this._isExplicitConsentEnabled){if(g.context===jS.TwoParty)throw this._logger.warn("Consent for recording is not supported for 1:1 calls"),new CallingCommunicationError({defaultError:D.CALL.CONSENT_NOT_SUPPORTED_1TO1});if(!this.isConsentRequiredInCall())throw new CallingCommunicationError({defaultError:D.CALL.CONSENT_ALREADY_SET_OR_NOT_REQUIRED});try{const g={level:"user",type:"consentToRecording",content:"{}"};if(!await this._tsCall.publishState(g,w.generateCauseId()))throw this._logger.error("Consent failure to set publish state for user"),new CallingCommunicationError({defaultError:D.CALL.FAILED_TO_SET_CONSENT});this._logger.log("ExplicitConsentCallStateManager: Consent for the call provided successfully")}catch(g){throw this._logger.error("Consent failure to set publish state for user on service side"),g}}}areCoreCapabilitiesConsentRestricted(){if(!this._isExplicitConsentEnabled)return!1;let g=this._consentActivelyRequired&&!this._localParticipantConsentPublishState;return this._logger.info("ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: Consent Actively Required: "+this._consentActivelyRequired+" Local Participant Consent Publish State: "+this._localParticipantConsentPublishState),this._logger.log("ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: "+g),g}offConsentRestrictionChanged(g,f){if("consentRestrictionChanged"!==g)throw new Error("ExplicitConsentCallStateManager: OffConsentRestrictionChanged - Invalid event");this._logger.log("ExplicitConsentCallStateManager: Unsubscribing to consentRestrictionChanged event"),this._eventEmitter.off(g,f)}onConsentRestrictionChanged(g,f){if("consentRestrictionChanged"!==g)throw new Error("ExplicitConsentCallStateManager: onConsentRestrictionChanged - Invalid event");this._logger.log("ExplicitConsentCallStateManager: Subscribing to consentRestrictionChanged event"),this._eventEmitter.on(g,f)}handleConsentCapabilitiesChanges(){this._eventEmitter.emit("consentRestrictionChanged"),this.areCoreCapabilitiesConsentRestricted()&&(!this._call.isMuted&&this._tsCall.mute().catch((g=>{this._logger.error("ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping mic",g)})),this._call.isLocalVideoStarted&&this._tsCall.stopVideo().catch((g=>{this._logger.error("ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping video",g)})),this._call.isScreenSharingOn&&this._tsCall.stopScreenSharing().catch((g=>{this._logger.error("ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping screen sharing",g)})),this._logger.log("ExplicitConsentCallStateManager: Handle Capabilities changes: Core capabilities are turned off"))}initialize(g,f,S,v,C){this._isExplicitConsentEnabled&&(this._isInitialized||(this._logger=C.createChild((()=>`Explicit Consent::Call(id='${g.callId}', state='${g.state}')`)),this._tsCall=g,this._callAgent=S,this._eventEmitter=v,this._call=f,g.changed((()=>{if(!0===g.meetingDetails?.recordingConsentDetails?.explicitRecordingConsentEnabled){this._recordingConsentEnabled=!0;const f=!0===g.meetingDetails?.recordingConsentDetails?.consentActivelyRequired;f!==this._consentActivelyRequired&&(this._consentActivelyRequired=f,this.handleConsentCapabilitiesChanges())}})),g.on("publishedStatesChanged",(async g=>{this._localParticipantConsentPublishState=!1,this._handleConsentStateChange(g)})),this._isInitialized=!0))}_handleConsentStateChange(g){if(!0!==this._localParticipantConsentPublishState){const S=this._callAgent.getUserMri();var f=!1;g&&this._getPublishedState(g).forEach((g=>{g.participantStates.forEach((g=>{if(g.id===S)return this._logger.log("ExplicitConsentCallStateManager: Handle Consent State changes: Local participant has provided the consent"),void(f=!0)}))})),this._localParticipantConsentPublishState=f,f&&this._eventEmitter.emit("consentRestrictionChanged")}}_getPublishedState(g){return g.typeStates.filter((g=>["consentToRecording"].includes(g.type)))}}ExplicitConsentCallStateManager.instance=null;var Zb,__decorate$k=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$k=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class QualityEventLogManager{constructor(g){this._lastRecovered=new Date,this._shouldNotifyError=!0,this._shouldNotifyRecovery=!0,this._interval=0,this._interval=g}updateLastRecoveredTime(g){this._lastRecovered=new Date(g.getTime()+this._interval),this._shouldNotifyError=!0,this._shouldNotifyRecovery=!1}shouldNotifyError(g){const f=this._lastRecovered<g&&this._shouldNotifyError;return f&&(this._shouldNotifyError=!1,this._shouldNotifyRecovery=!0),f}shouldNotifyRecovery(g){const f=this._shouldNotifyRecovery;return f&&this.updateLastRecoveredTime(g),f}}class CallCommonImpl{get id(){return this._id}get callerInfo(){return{identifier:this._callerIdentity,displayName:this._callerDisplayName}}get transferorInfo(){if(this._transferorIdentity)return{identifier:this._transferorIdentity,displayName:this._transferorDisplayName}}get state(){return this._state}get role(){return this._role}get callEndReason(){return this._callEndReason}get kind(){return this._kind}get direction(){return this._direction}get isMuted(){return this._isMuted}get isScreenSharingOn(){return this._isScreenSharingOn}get isLocalVideoStarted(){return this._isLocalVideoStarted}get localVideoStreams(){return this._localVideoStreams}get localAudioStreams(){return this._localAudioStreams}get isIncomingAudioMuted(){return this._isIncomingAudioMuted}get remoteParticipants(){return this._remoteParticipants}get totalParticipantCount(){return this._totalParticipantCount}get lobby(){return this._lobby}get isAcsTeamsCall(){return this._isAcsTeamsCall}get isIPAudioEnabled(){return this.callInfo.context===jS.TwoParty||this._allowIPAudio}get isIPVideoEnabled(){return this.callInfo.context===jS.TwoParty||this._allowIPVideo}get isEnterpriseTeamsCall(){return this._isEnterpriseTeamsCall}subscribeToGetRemoteAudioStream(){if(!this._rawAudioStreamChangedSubscription)try{const g=this.tsCall.getIncomingRawAudioStream(),populateRemoteAudioStreamCollection=async()=>{try{if(0===this._remoteAudioStreams.length){if(!await g.getMediaStream())throw new CallingCommunicationError({defaultError:D.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_UNDEFINED});this._remoteAudioStreams.push(new RemoteAudioStreamImpl(g,this._telemetryLogManager,this.id,this.tsCall.participantId)),this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:this._remoteAudioStreams,removed:[]})}else if(await g.getMediaStream())this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:[],removed:[]});else{const g=this._remoteAudioStreams[0];g.dispose(),this._remoteAudioStreams=[],this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:[],removed:[g]})}}catch(g){throw new CallingCommunicationError({defaultError:D.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_RETURNED_ERROR,originalError:g})}};this._rawAudioStreamChangedSubscription=g.changed((()=>{this.logger.info(`Changed fired ${this.tsCall.state}, ${this.state}`),populateRemoteAudioStreamCollection().catch(noop)})),populateRemoteAudioStreamCollection().catch((()=>{this.logger.info("Failed to update remote audio stream collection, retrying on changed")}))}catch(g){this.logger.info("Failed to get raw audio stream from the stack")}}get remoteAudioStreams(){if(!getAcsEcsConfig().calling.allowAccessRawMediaStream)throw new CallingCommunicationError({defaultError:D.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_DISABLED});return this._remoteAudioStreams}get deviceManager(){return this._callAgent.deviceManager}get mediaConstraintsManager(){return this._mediaConstraintsManager}get isHandlingLargeMeetingVideoRendering(){return this._isHandlingLargeMeetingVideoRendering}get callInfo(){return this._callInfo}get networkQualityUfdEventDetails(){return this._networkQualityUfdEventDetails}get acsProxy(){return this._callAgent.acsProxy}get acsCustomRelayManager(){return this._callAgent.acsCustomRelayManager}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}get callAgent(){return this._callAgent}get iceServers(){return this._getIceServersCalledOnce||(this._getIceServersCalledOnce=!0,this._iceServers=this.tsCall.getMediaSessionStats()?.extensions?.IceServers),this._iceServers}get watermarkAudioOnlyFallbackTriggered(){return this._watermarkAudioOnlyFallbackTriggered}setWatermarkAudioOnlyFallbackTriggered(g){this._watermarkAudioOnlyFallbackTriggered=g,this._eventEmitter.emit("watermarkAudioOnlyFallbackTriggeredChanged")}constructor(g,f,S,v,C,_){this._callAgent=f,this._isMuted=!1,this._isMuted_correlationIdCache=generateGuid(),this._isIncomingAudioMuted=!1,this._isIncomingAudioMuted_correlationIdCache=generateGuid(),this._isScreenSharingOn=!1,this._isLocalVideoStarted=!1,this._localVideoStreams=[],this._localAudioStreams=[],this._remoteAudioStreams=[],this._totalParticipantCount=1,this._isDeviceNotFunctioningMuted=!1,this.__attemptedToRecoverMicNotFunctioningBySDK=!1,this._isMicrophoneMuted=!1,this._disposed=!1,this._lastTsCallState=0,this._isSpeakerMuted=!1,this._callMode=0,this._role=Gf,this._lastTsCallMeetingDetails={},this._isHandlingLargeMeetingVideoRendering=!1,this._joinContextDescription=lS.Unknown,this._remoteParticipantsChangedListeners=[],this._localRingingStateSet=!1,this._networkQualityUfdEventDetails=[],this._audioEffectsProcessorStats=null,this._getIceServersCalledOnce=!1,this._watermarkAudioOnlyFallbackTriggered=!1,this._transportStateTimestamp=new Map,this._isAcsTeamsCall=!1,this._isEnterpriseTeamsCall=this._callAgent.isEnterpriseUser(),this._isTeamsMultipersonaUser=this._callAgent.isTeamsMultipersonaUser(),this._mriToRemoteParticipantMap=new Map,this._remoteParticipants=[],this._state="None",this._transportState="None",this._allowIPAudio=!0,this._allowIPVideo=!0,this.localVideoStream=void 0,this.localScreenSharingStream=void 0,this._handleMuteChanges=()=>{const g=[jS.Rooms,jS.GroupIdCall,jS.MultiParty,jS.TeamsMeeting].some((g=>g===this._callInfo.context)),f=this.tsCall.conversationType||g?!!(this.tsCall.isMuted||10!==this.tsCall.state&&this.tsCall.isServerMuted||this._isDeviceNotFunctioningMuted):!(!this.tsCall.isMuted&&!this._isDeviceNotFunctioningMuted);if(this._isMuted!=f){this.logger.info(`isMuted changed from ${this._isMuted} to ${f}`);const g=[];this.tsCall.isMuted&&g.push("isMicrophoneMuted"),this.tsCall.isServerMuted&&(g.push("isServerMuted"),[3,4,5].some((g=>g===this.tsCall.state))&&this._eventEmitter.emit("mutedByOthers"),this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&this.explicitConsentStateImp.handleConsentCapabilitiesChanges()),this._isDeviceNotFunctioningMuted&&g.push("isDeviceNotFunctioningMuted");let S="";g.length>=1&&(S=g.join(", ")),f&&(this._isMuted_correlationIdCache=generateGuid()),sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,this._isMuted_correlationIdCache,this._joinContextDescription),step:"isMuted-changed",oldIsMuted:this._isMuted,newIsMuted:f,reason:S}),this._isMuted=f,this._eventEmitter.emit("isMutedChanged")}},this.audioSourceChanged=async g=>{if(this._telemetryLogManager.sendEvent({name:uE.acs_calling_local_audio_source_changed,tenant:tf,properties:{callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:+new Date,correlationId:generateGuid(),localAudioStream:g.source?.source instanceof MediaStream?"MediaStream":"Device"}}),g.source instanceof AudioDeviceInfoImpl){this.localAudioStreams[0]&&"RawMedia"===this.localAudioStreams[0].mediaStreamType&&this.stopAudioInternal(!0);const f=await(this._callAgent.tsStack?.getDeviceManagerAsync?.());await(f?.selectDevicesAsync?.({microphone:g.source.id}))}else await this.startAudioInternal(g.source,!0)},this._handleIncomingAudioMuteChanges=()=>{const g=this._isSpeakerMuted;this._isIncomingAudioMuted!=g&&(this.logger.info(`newIncomingAudioMuted changed from ${this._isIncomingAudioMuted} to ${g}`),g&&(this._isIncomingAudioMuted_correlationIdCache=generateGuid()),sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,this._isIncomingAudioMuted_correlationIdCache,this._joinContextDescription),step:"isIncomingAudioMuted-changed",oldIsMuted:this._isIncomingAudioMuted,newIsMuted:g,reason:""}),this._isIncomingAudioMuted=g,this._eventEmitter.emit("isIncomingAudioMutedChanged"))},this._id=g.callId,this.tsCall=S,this._direction=g.isIncoming?"Incoming":"Outgoing",this._config=g,this.logger=this._callAgent.logger.createChild((()=>`Call:${this._id}:${this._state}`)),this._telemetryLogManager=v,this.stats=new CallStats(this.logger,this._telemetryLogManager),this._eventEmitter=new CallingEventEmitter(this.logger),this.activeRemoteVideoStreamViews=new Map,this.isSubscribedCall=!1,this.isBreakoutRoomCall=!1,this._mediaMetricsDeviceEvents={},this._kind=C,this._optimalVideoCount=1,this._ufdsCorrelationIdCache=initializeUfdsCorrelationIdCache(),this._callInfo=new CallInfoCommonImpl(S,{config:g}),this._callInfo.initialize(this._eventEmitter,this.logger,this._telemetryLogManager),this._speakingWhileMutedManager=new QualityEventLogManager(getAcsEcsConfig().telemetry.speakingWhileMutedThrottleInterval),getAcsEcsConfig().calling.mediaMetricsDeviceEventsEnabled&&(this._dmDevicesChangedSub=this._callAgent.tsStack?.getDeviceManager().on("devicesChanged",(()=>{this.setOrUpdateMediaMetricsDeviceEvents()}))),this._extensibleApi=new ExtensibleFeatureImpl(this.logger,{call:this,callAgent:this._callAgent,callInfo:this._callInfo},{tsCall:this.tsCall,callAgent:this._callAgent,call:this,telemetryLogManager:this._telemetryLogManager}),this.explicitConsentStateImp=new ExplicitConsentCallStateManager(this.tsCall,this,f,this._eventEmitter,this.logger),this._capabilityResolver=new CapabilityResolverImpl(this._eventEmitter,this.logger,this,this._callInfo,f,S),this._lobby=new LobbyImpl(this.tsCall,this,this.logger,this._telemetryLogManager);const T=getRegisteredFeatures(UE.CallFeature);for(const g of T)"OnExtendedObjectConstructor"===g.activationOptions.activationEvent&&this.feature(g);this._mmrRdpConnectionManager=new MmrRdpConnectionManager(this.logger),getAcsEcsConfig().telemetry.sendNetworkChangedTelemetry&&this._sendNetworkChangedTelemetry(),getAcsEcsConfig().telemetry.deviceChangedEvents.enabled&&(this._selectedDeviceManager=new SelectedDeviceManager(this.deviceManager),this._setupSelectedDeviceChangedTelemetry()),this._mediaConstraintsManager=new MediaConstraintsManager(this.tsCall,this.logger,this._telemetryLogManager),this._isAcsTeamsCall=_??!1,this.feature(fb.MediaAccess).on("localParticipantMediaAccessChanged",(g=>{this.logger.info(`Call common, time when received localParticipantMediaAccessChanged event: ${(new Date).getTime()}, isAudioPermitted=${g.mediaAccess.isAudioPermitted}, isVideoPermitted=${g.mediaAccess.isVideoPermitted}`),!1===g.mediaAccess.isVideoPermitted&&this.localVideoStream&&this.stopVideo(this.localVideoStream)}))}async accept(g={}){const f=g.audioOptions?.muted??!1,S=this.getLocalVideoStreamFromCallOptions(g),v=this.getLocalAudioStreamFromCallOptions(g),C=+new Date,_=generateGuid(),T=this._callAgent.getEcsConfigIds(),I=parseCustomContext(this.tsCall),b={joinContextDescription:"",additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),muted:f,withVideo:this.isIPVideoEnabled&&!!S,withAudio:this.isIPAudioEnabled&&v?.mediaStreamType?v?.mediaStreamType:"",...getMMRInfo(),AcsCallingSDKWeb_ecsConfigId:T.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:T.SkypeWebMedia,customContext:{userToUserPresent:!!I?.userToUser,xHeadersPresent:!!I?.xHeaders&&I.xHeaders.length>0}},additionalDetails:{}},handleError=(g,f,T)=>{const I=+new Date,A={...b};let P;if(f){const{callEndReason:f,callingCommunicationError:S}=getCallEndReason(this,g);A.additionalDetails.callEndReason=f,P=S}else P=new CallingCommunicationError({defaultError:D.CALL.ACCEPT_INCOMING_CALL,originalError:g}),A.additionalDetails.communicationServicesError=extractCommunicationServicesErrorForTelemetry(P).communicationServicesError;if(this.sendCallStageEvent({eventName:uE.acs_calling_call_accept_failed,correlationId:_,timestampInfo:{deltaTimeInMs:I-C},additionalPayload:A},P,void 0,T?B_.getRemoveCauseIdToNetworkInfo(T):void 0),S){const g=+new Date;P=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND}),this.logger.error(P.message),this.sendVideoEvent({correlationId:_,eventName:uE.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:g-C},localVideoStream:S,step:"accept",isScreenSharingOnFlag:this._isScreenSharingOn},P),this.removeLocalVideoStream(S)}return v&&this.removeLocalAudioStream(v),P};try{if(g?.videoOptions?.constraints){const f=this._mediaConstraintsManager.getTelemetryPayload({video:g?.videoOptions?.constraints});b.additionalProperties.constraints=f}this.sendCallStageEvent({eventName:uE.acs_calling_call_accept_attempt,correlationId:_,timestampInfo:{attemptTimestamp:C},additionalPayload:b});const T={...b};if(S&&await this.setLocalVideoStream(S),this.setLocalAudioStream(v),S&&this.sendVideoEvent({eventName:uE.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:C},correlationId:_,step:"accept",isScreenSharingOnFlag:this._isScreenSharingOn}),1!==this.tsCall.state)throw new CallingCommunicationError({defaultError:D.CALL.ACCEPT_NOT_RINGING});try{if(g?.videoOptions?.constraints){const f=await this._mediaConstraintsManager.setVideoConstraints(g?.videoOptions?.constraints,"accept",_,C),S=this._mediaConstraintsManager.getTelemetryPayload({video:f});T.additionalProperties.constraints=S}}catch(g){const f=new CallingCommunicationError({defaultError:D.CALL.ACCEPT_VIDEO_CONSTRAINTS,originalError:g});this.logger.error(`${f.message}`)}const I={withVideo:!!S&&this.isIPVideoEnabled,muted:f};if(f&&(I.muteFlags=1),getAcsEcsConfig()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(I.mediaConfiguration={connectionType:"NoDirectConnection"}),v&&await this.startAudioInternal(v,!0).catch((g=>{this.logger.error(`Failed to start localAudioStream, message=${g?.message}`)})),"RawMedia"===S?.mediaStreamType)try{await this._setRawStream(S,1)}catch(g){const f=+new Date,v=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:g});this.sendVideoEvent({correlationId:_,eventName:uE.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:f-C},localVideoStream:S,step:"accept",isScreenSharingOnFlag:this._isScreenSharingOn},v),this.removeLocalVideoStream(S)}const A=w.generateCauseId();return B_.setCauseIdToNetworkInfo(A),this.tsCall.accept(I,A).then((async()=>{const g=+new Date;S&&this.shallRemoveLvsAfterConnectedSuccessfully(S,"accept",_,g,C),v&&this.shallRemoveLasAfterConnectedSuccessfully(v,"accept",_,g,C),this.sendCallStageEvent({eventName:uE.acs_calling_call_accept_connected,correlationId:_,timestampInfo:{deltaTimeInMs:g-C},additionalPayload:T},void 0,void 0,B_.getRemoveCauseIdToNetworkInfo(A))})).catch((g=>{handleError(g,!0,A)})),this}catch(g){throw handleError(g,!1)}}async reject(){const g=+new Date,f=generateGuid();this.sendCallStageEvent({eventName:uE.acs_calling_call_reject_attempt,correlationId:f,timestampInfo:{attemptTimestamp:g}});const S=this._callAgent.getEcsConfigIds(),v={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:S.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:S.SkypeWebMedia},additionalDetails:{}};if(1!==this.tsCall.state){const S=new CallingCommunicationError({defaultError:D.CALL.REJECT_NOT_RINGING});v.additionalDetails.communicationServicesError=extractCommunicationServicesErrorForTelemetry(S).communicationServicesError;const C=+new Date;throw this.sendCallStageEvent({eventName:uE.acs_calling_call_reject_failed,correlationId:f,timestampInfo:{deltaTimeInMs:C-g},additionalPayload:v},S),S}const C=w.generateCauseId();return B_.setCauseIdToNetworkInfo(C),this.tsCall.reject(C).then((()=>{const S=+new Date;this.sendCallStageEvent({eventName:uE.acs_calling_call_reject_success,correlationId:f,timestampInfo:{deltaTimeInMs:S-g}},void 0,void 0,B_.getRemoveCauseIdToNetworkInfo(C))})).catch((S=>{const _=+new Date,{callEndReason:T,callingCommunicationError:I}=getCallEndReason(this,S);throw v.additionalDetails.callEndReason=T,this.sendCallStageEvent({eventName:uE.acs_calling_call_reject_failed,correlationId:f,timestampInfo:{deltaTimeInMs:_-g},additionalPayload:v},I,void 0,B_.getRemoveCauseIdToNetworkInfo(C)),I}))}dispose(){this._disposed||(this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesChangedSub=void 0,this._extensibleApi.dispose(),this._eventEmitter.removeAllListeners(),this._onlineListener&&window.removeEventListener("online",this._onlineListener),this._offlineListener&&window.removeEventListener("offline",this._offlineListener),this._trouterStateChangedListener&&this._callAgent.offTrouterStateChanged(this._trouterStateChangedListener),this._mmrRdpConnectionManager.dispose(),this._selectedDeviceManager?.dispose(),this.explicitConsentStateImp.dispose(),this._disposed=!0)}async startAudioInternal(g,f=!1){const S=generateGuid(),v=+new Date,C=w.generateCauseId();B_.setCauseIdToNetworkInfo(C);try{if(this.isInternalApiCallWithoutRawMedia(g,f))return;this.sendRawMediaEvent({eventName:uE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:S,kindOfEvent:gE.attempt,isInternal:f,timestampInfo:"",additionalDetails:""}),this.validateRawMedia(g,D.CALL.START_AUDIO_LAS_NOT_RAW_MEDIA),this._userProvidedLocalAudioStreamCache=g;const _=await this.createMediaStream(g),T=await(this._callAgent.tsStack?.getDeviceManagerAsync?.());if(!getAcsEcsConfig()?.calling?.allowAccessRawMediaStream||!T?.setRawMediaStream)throw new CallingCommunicationError({defaultError:D.CALL.LOCAL_AUDIO_SET_MEDIA_STREAM});T?.setRawMediaStream(_,0),this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream(g);const I=+new Date;this.sendRawMediaEvent({eventName:uE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:S,kindOfEvent:gE.success,isInternal:f,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:I-v},additionalDetails:{networkInfo:B_.getRemoveCauseIdToNetworkInfo(C)}})}catch(g){const _=new CallingCommunicationError({defaultError:D.CALL.START_AUDIO_STREAM_FAILED,originalError:g});this.logger.error(`Failed to start raw media audio: ${_.message}`);const T=+new Date;throw this.sendRawMediaEvent({eventName:uE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:S,isInternal:f,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:T-v},additionalDetails:{failureReason:_.message||"",code:_.code,subCode:_.subCode,...extractCommunicationServicesErrorForTelemetry(_),networkInfo:B_.getRemoveCauseIdToNetworkInfo(C)}}),_}}isInternalApiCallWithoutRawMedia(g,f){return!("RawMedia"===g?.mediaStreamType||!f)&&(this.logger.info("startAudioInternal internal call: LocalAudioStream media type is raw media, skipping raw audio startAudioInternal"),!0)}validateRawMedia(g,f){if("RawMedia"!==g?.mediaStreamType)throw new CallingCommunicationError({defaultError:f})}async createMediaStream(g){let f;try{f=await g.getMediaStream()}catch(g){throw new CallingCommunicationError({defaultError:D.CALL.LOCAL_AUDIO_GET_MEDIA_STREAM,originalError:g})}return new MediaStream(f)}stopAudioInternal(g=!1){const f=generateGuid(),S=+new Date,v=w.generateCauseId();B_.setCauseIdToNetworkInfo(v);try{const C=this._localAudioStreams[0];if(this.isInternalApiCallWithoutRawMedia(C,g))return;this.sendRawMediaEvent({eventName:uE.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,kindOfEvent:gE.attempt,isInternal:g,timestampInfo:"",additionalDetails:""}),g||validateCallConnected(PS.StopAudio,this.state),this.validateRawMedia(C,D.CALL.STOP_AUDIO_LAS_NOT_RAW_MEDIA);const _=this._callAgent.tsStack?.getDeviceManager();if(!getAcsEcsConfig()?.calling?.allowAccessRawMediaStream||!_?.unsetRawMediaStream)throw new CallingCommunicationError({defaultError:D.CALL.LOCAL_AUDIO_UNSET_MEDIA_STREAM});_.unsetRawMediaStream(0),this._userProvidedLocalAudioStreamCache=void 0,this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream();const T=+new Date;this.sendRawMediaEvent({eventName:uE.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,kindOfEvent:gE.success,isInternal:g,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:T-S},additionalDetails:{networkInfo:B_.getRemoveCauseIdToNetworkInfo(v)}})}catch(C){const _=new CallingCommunicationError({defaultError:D.CALL.STOP_AUDIO_STREAM_FAILED,originalError:C});this.logger.error(`Failed to stop raw media audio: ${_.message}`);const T=+new Date;throw this.sendRawMediaEvent({eventName:uE.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,isInternal:g,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:T-S},additionalDetails:{failureReason:_.message||"",code:_.code,subCode:_.subCode,...extractCommunicationServicesErrorForTelemetry(_),networkInfo:B_.getRemoveCauseIdToNetworkInfo(v)}}),_}}bindTsCall(){void 0!==this.tsCall.callerMri&&(this._callerIdentity=constructIdentifierKindFromMri(this.tsCall.callerMri),this._callerDisplayName=this.tsCall.participants.find((g=>g.id===this.tsCall.callerMri))?.displayName),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._setCallRole(this.tsCall.advancedMeetingRole),this.tsCall.callQueueInfo?(this._callerIdentity=constructIdentifierKindFromMri(this.tsCall.callQueueInfo.onBehalfOf.id),this._callerDisplayName=this.tsCall.callQueueInfo.onBehalfOf.displayName?this.tsCall.callQueueInfo.onBehalfOf.displayName:this.tsCall.participants.find((g=>g.id===this.tsCall.callQueueInfo?.details.id))?.displayName,this._transferorIdentity=constructIdentifierKindFromMri(this.tsCall.callQueueInfo.details.id),this._transferorDisplayName=this.tsCall.callQueueInfo.details.displayName?this.tsCall.callQueueInfo.details.displayName:this.tsCall.participants.find((g=>g.id===this.tsCall.callQueueInfo?.details.id))?.displayName):this.tsCall.transferorMri&&(this._transferorIdentity=constructIdentifierKindFromMri(this.tsCall.transferorMri),this._transferorDisplayName=this.tsCall.transferorDisplayName),this.updateCallMode(),this.tsCall.changed((()=>{this.tsCall.callId!==this._id&&(this.logger.log(`tsCall callId changed from ${this._id} to ${this.tsCall.callId}`),sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),step:"id-changed",isAcsTeamsCall:this.isAcsTeamsCall,oldCallId:this._id,newCallId:this.tsCall.callId}),this._id=this.tsCall.callId,this._eventEmitter.emit("idChanged")),this.tsCall.state!==this._lastTsCallState&&(this.logger.log(`tsCall state changed=${this.tsCall.state}`),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._handleMuteChanges()),this._isScreenSharingOn!==this.tsCall.isScreenSharingOn&&(this.logger.log(`tsCall isScreenSharingOn changed=${this.tsCall.isScreenSharingOn}`),this._isScreenSharingOn=this.tsCall.isScreenSharingOn,this._isScreenSharingOn||this.removeScreenSharingStream(),this._eventEmitter.emit("isScreenSharingOnChanged")),this._isMicrophoneMuted!==this.tsCall.isMuted&&(this.logger.log(`tsCall isMuted changed=${this.tsCall.isMuted}`),this._isMicrophoneMuted=this.tsCall.isMuted,this._handleMuteChanges()),this._isSpeakerMuted!==this.tsCall.isSpeakerMuted&&(this.logger.log(`tsCall _isSpeakerMuted changed=${this.tsCall.isSpeakerMuted}`),this._isSpeakerMuted=this.tsCall.isSpeakerMuted,this._handleIncomingAudioMuteChanges()),this.tsCall.advancedMeetingRole!==this._lastTsCallAdvancedMeetingRole&&(this.logger.log(`tsCall advancedMeetingRole changed=${this.tsCall.advancedMeetingRole}`),this._setCallRole(this.tsCall.advancedMeetingRole)),(this.tsCall.meetingData?.meetingUrl||this.tsCall.meetingData?.passcode||"scheduledMeeting"==this.tsCall.conversationType)&&this.tsCall.meetingDetails&&hasMeetingDetailsChanged(this.tsCall.meetingDetails,this._lastTsCallMeetingDetails)&&this._setMeetingCapabilities(this.tsCall.meetingDetails),this.updateCallMode(),this.optimalVideoCountChanged()})),this.tsCall.on("serverMutedChanged",(()=>{this.logger.log(`tsCall isServerMuted changed=${this.tsCall.isServerMuted}`),this._handleMuteChanges()})),this._totalParticipantCount=getTotalNotBotParticipantCount(this.tsCall),this.tsCall.on("participantCountsUpdated",(()=>{const g=getTotalNotBotParticipantCount(this.tsCall);if(this._totalParticipantCount!==g){const f=this._totalParticipantCount;this._totalParticipantCount=g,this.logger.log(`tsCall totalParticipantCount changed from ${f} to ${this._totalParticipantCount}`),getAcsEcsConfig().rendering.remoteVideo.largeMeeting.handleVideoRendering&&this._enableOrDisable_largeMeeting_videoRendering(),this._eventEmitter.emit("totalParticipantCountChanged");try{this.stats.recordEvent({name:hE.number_of_participants,callId:this.id,localParticipantId:this.tsCall.participantId,data:{totalParticipantCount:this._totalParticipantCount,participantCounts:this.tsCall.participantCounts||{},previousParticipantCount:f}})}catch(g){this.logger.error("failed to send participant count change telemetry")}}}));const transportStateChanged=(g,f)=>{if(g!==f){this.logger.log(`transportState changed from ${this._transportState} to ${f}`);const S=void 0===this._transportStateTimestamp.get("Connected")?this._connectedTimestamp:void 0;this._transportStateTimestamp.delete(f);const v=M.omitBy({connectedTimetamp:S,transportConnectedTimestamp:this._transportStateTimestamp.get("Connected"),transportDisconnectedTimestamp:this._transportStateTimestamp.get("Disconnected"),transportFailedTimestamp:this._transportStateTimestamp.get("Failed")},M.isUndefined),C=M.merge(getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),{timestampInfo:v});sendCallProgressEvent(this._telemetryLogManager,this.logger,{...C,step:"transportState-changed",oldState:g,newState:f}),this._transportStateTimestamp.set(f,Date.now()),this._transportState=f}};this.tsCall.on("transportConnected",(()=>{transportStateChanged(this._transportState,"Connected")})),this.tsCall.on("transportDisconnected",(()=>{transportStateChanged(this._transportState,"Disconnected")})),this.tsCall.on("transportFailed",(()=>{transportStateChanged(this._transportState,"Failed")})),this.tsCall.on("callQualityChanged",(async g=>{try{let f,S;if(5===g.type||32===g.type||2===g.type||1===g.type||37===g.type?(f=hE.network_quality,this._trackNetworkQualityUfdEventDetails(g.type)):44===g.type||43===g.type||9===g.type||25===g.type||45===g.type||33===g.type||34===g.type||55===g.type||26===g.type||47===g.type?f=hE.video_device_issue:27===g.type?(S=!0,f=hE.video_device_issue):f=hE.other_diagnostic,3===g.value||2===g.value){if(S&&!this._speakingWhileMutedManager.shouldNotifyError(new Date))return;this.logger.warn(`Ufd error raised!, ufd=${g.type}, value=${g.value}, kind=${f}`),f===hE.network_quality&&window.dispatchEvent(new CustomEvent("online",{detail:!1}))}else{if(S&&!this._speakingWhileMutedManager.shouldNotifyRecovery(new Date))return;this.logger.warn(`Ufd error recovered!, ufd=${g.type}, value=${g.value}, kind=${f}`),f===hE.network_quality&&window.dispatchEvent(new CustomEvent("online",{detail:!0}))}let v="";const C=this._ufdsCorrelationIdCache[g.type][g.mediaType];3==g.value||2==g.value?C?v=C:(v=generateGuid(),this._ufdsCorrelationIdCache[g.type][g.mediaType]=v):(C&&(v=C),this._ufdsCorrelationIdCache[g.type][g.mediaType]=void 0);const _={type:g.type.toString(),level:g.value,mediaType:g.mediaType,correlationId:v};if(this.stats.recordEvent({name:f,callId:this.id,localParticipantId:this.tsCall.participantId,data:_}),this.shallStopVideo(g)){const f=+new Date,S=generateGuid();this.logger.warn(`Attempting to stop video gracefully due to video ufd being raised.UFD: ${g.type}, value: ${g.value}, call direction: ${this._direction}`),this.sendAudioEvent({eventName:uE.acs_calling_stop_video_on_ufd_attempt,timestampInfo:{attemptTimestamp:f},correlationId:S,step:"mid-call"});try{this.localVideoStream&&this.stopVideo(this.localVideoStream)}catch(f){const S=`Failed to stop video on video device start failed or capture mute event ${g.type} with value ${g.value}`;this.logger.error(S)}}if(this.shallRemoveLocalVideoStreamOnBadUfd(g)){const f=new CallingCommunicationError({defaultError:D.CALL.REMOVE_LOCAL_VIDEO_ON_BAD_UFD,defaultErrorMessageArgs:[g.type,g.value,this._direction]});this.localVideoStream&&(this.sendVideoEvent({eventName:uE.acs_calling_start_video_failure,correlationId:generateGuid(),timestampInfo:{attemptTimestamp:+new Date},step:"start",additionalDetails:{...extractCommunicationServicesErrorForTelemetry(f)},localVideoStream:this.localVideoStream,isScreenSharingOnFlag:this.isScreenSharingOn},f),this.removeLocalVideoStream(this.localVideoStream)),this.logger.error(f.message)}if(this.shallStopAudio(g)){const f=+new Date,S=generateGuid();if(getAcsEcsConfig()?.calling?.allowMuteOnBadUfd&&!this.tsCall.isMuted){this.sendAudioEvent({eventName:uE.acs_calling_mute_on_ufd_attempt,timestampInfo:{attemptTimestamp:f},correlationId:S,step:"mid-call"});try{await this.mute()}catch(f){const S=`Failed to mute on microphone device not functioning or capture mute event ${g.type} with value ${g.value}`;this.logger.error(S)}}const v=getAcsEcsConfig()?.calling?.preventStopAudio;if(v)return this.sendAudioEvent({eventName:uE.acs_calling_prevent_stop_audio,timestampInfo:{attemptTimestamp:f},correlationId:S,step:"mid-call"}),void(!getAcsEcsConfig()?.calling?.preventFakeMute&&this.markCallMuted());this.sendAudioEvent({eventName:uE.acs_calling_stop_audio_attempt,timestampInfo:{attemptTimestamp:f},correlationId:S,step:"mid-call"});try{await this.tsCall.stopAudio(),this.markCallMuted();const g=+new Date;this.sendAudioEvent({eventName:uE.acs_calling_stop_audio_success,timestampInfo:{deltaTimeInMs:g-f},correlationId:S,step:"mid-call"})}catch(v){const C=new CallingCommunicationError({defaultError:D.CALL.STOP_AUDIO_ON_BAD_UFD,defaultErrorMessageArgs:[g.type,g.value],originalError:v});this.logger.error(C.message);const _=+new Date;this.sendAudioEvent({eventName:uE.acs_calling_stop_audio_failure,timestampInfo:{deltaTimeInMs:_-f},correlationId:S,step:"mid-call"},C)}}this.muteUnmuteOnMicrophoneNotFunctioningUfd(g),this.audioDidAutoRecover(g)&&(this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges())}catch(g){this.logger.error("Failed to send ufd telemetry")}})),this.tsCall.on("participantAdded",(async g=>{this.logger.debug("tsCall participant added");const f=[];g.endpoints?.endpointDetails.forEach((g=>f.push(g.participantId))),0===f.length&&f.push("remoteParticipantId unavailable");const S=constructIdentifierKindFromMri(g.id);if(this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||"microsoftTeamsUser"===S.kind,this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:f,participantAddedOrRemoved:"added",kindOfEvent:gE.event}),isHiddenBot(g))this.logger.info("Add participant: Handle hidden calling application");else{this._handleLocalRingingCallState(g);try{const f=this.getOrCreateRemoteParticipant(S,g);this._eventEmitter.emit("remoteParticipantsUpdated",{added:[f],removed:[]})}catch(g){this.logger.log("unable to map call participant to ACS user")}}})),this.logger.debug(`tsCall current participant count=${this.tsCall?.participants?.length}`);const addParticipantOnCallInit=g=>{const f=constructIdentifierKindFromMri(g.id);this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||"microsoftTeamsUser"===f.kind;const S=this.getOrCreateRemoteParticipant(f,g);this._handleLocalRingingCallState(g),S.on("displayNameChanged",(()=>{this._callerIdentity&&getMriFromIdentifier(this._callerIdentity)===getMriFromIdentifier(S.identifier)&&(this._callerDisplayName=S.displayName,this._eventEmitter.emit("callerInfoChanged")),this._transferorIdentity&&getMriFromIdentifier(this._transferorIdentity)===getMriFromIdentifier(S.identifier)&&(this._transferorDisplayName=S.displayName,this._eventEmitter.emit("transferorInfoChanged"))}))},g=[];this.tsCall.participants.forEach((f=>{getAcsEcsConfig().calling.checkHiddenBotOnCallStart&&isHiddenBot(f)||addParticipantOnCallInit(f);try{f.endpoints?.endpointDetails.forEach((f=>g.push(f.participantId)))}catch(g){this.logger.error("Unable to get participantId from from remote participant")}}));try{this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:g,participantAddedOrRemoved:"added",kindOfEvent:gE.initialize})}catch(g){this.logger.error("Unable to send participant added telemtery")}this.tsCall.on("participantRemoved",(async g=>{this.logger.debug("tsCall participant removed");const f=[];if(g.endpoints?.endpointDetails.forEach((g=>f.push(g.participantId))),0===f.length&&f.push("remoteParticipantId unavailable"),isHiddenBot(g))return this.logger.info("Remove participant: Ignore calling application"),void this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:f,participantAddedOrRemoved:"removed",kindOfEvent:gE.event});const S=g.id;if(S){const v=this._remoteParticipants.find((g=>getMriFromIdentifier(g.identifier)===S));if(v){const{callEndReason:S}=getRemoteParticipantCallEndReason(this,g);v.setCallEndReason(S),this.deleteRemoteParticipant(v),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:[v]}),this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:f,participantAddedOrRemoved:"removed",kindOfEvent:gE.event,additionalDetails:{...extractCallEndReasonForTelemetry(S)}})}else this.logger.log("unable to find participant to remove")}}))}_trackNetworkQualityUfdEventDetails(g){const f=+new Date;let S="";switch(g){case 5:S=n_;break;case 32:S=a_;break;case 2:S=r_;break;case 1:S=s_;break;case 37:S=o_}this._networkQualityUfdEventDetails.push({eventName:S,timestampInfo:f})}async muteUnmuteOnMicrophoneNotFunctioningUfd(g){try{const f=getAcsEcsConfig().calling;if(!f.muteUnmuteOnMicrophoneNotFunctioning||this._isMuted||9!==g.type||3!==g.value)return;this.__attemptedToRecoverMicNotFunctioningBySDK=!0,await this.mute(),f.unmuteDelayForMicrophoneNotFunctioningInMs>=0&&await sleep(f.unmuteDelayForMicrophoneNotFunctioningInMs),await this.unmute()}catch(g){this.logger.info("Unable to perform mute and unmute to recover microphoneNotFunctioning",g)}finally{this.__attemptedToRecoverMicNotFunctioningBySDK=!1}}updateCallMode(){this.tsCall.callMode&&this._callMode!==this.tsCall.callMode&&(this.logger.log(`tsCall callMode changed from ${this._callMode} to ${this.tsCall.callMode}`),sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),step:"callMode-changed",oldState:WE[this._callMode],newState:WE[this.tsCall.callMode]}),this._callMode=this.tsCall.callMode)}async startCallInternal(g,f,S,v,C){const _=!!g?.audioOptions?.muted,T=this.getLocalVideoStreamFromCallOptions(g),I=this.getLocalAudioStreamFromCallOptions(g);let b;const A=C?.attemptTimestamp??+new Date,P=C?.correlationId??generateGuid(),R=generateGuid();this._joinContextDescription=getJoinContextDescription(S);const M=this._callAgent.getEcsConfigIds(),O=1===this.tsCall.participants.length&&!this.tsCall.threadId&&!f,N=!!O||this._allowIPAudio,k=!!O||this._allowIPVideo,L={joinContextDescription:this._joinContextDescription,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:v?.isEmergency||!1,trouterState:this._callAgent.getTrouterState(),muted:_,withVideo:k&&!!T,withAudio:N&&I?.mediaStreamType?I.mediaStreamType:"",...getMMRInfo(),AcsCallingSDKWeb_ecsConfigId:M.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:M.SkypeWebMedia,customContext:{userToUserPresent:!!g?.customContext?.userToUser,xHeadersPresent:!!g?.customContext?.xHeaders&&g.customContext.xHeaders.length>0},firstPartyOptions:{isDeviceTypeEnabled:getAcsEcsConfig().calling.setDeviceType,deviceType:this._callAgent.getDeviceType(),isImmersiveMode:g?.firstPartyOptions?.isImmersiveMode}},additionalDetails:{}};g?.videoOptions?.constraints&&(L.additionalProperties.constraints=this._mediaConstraintsManager.getTelemetryPayload({video:g?.videoOptions?.constraints})),v?.meetingInfo?.tenantId&&(this._teamsMeetingTenantId=v.meetingInfo.tenantId,L.additionalProperties.teamsMeetingTenantId=v.meetingInfo.tenantId),v?.threadId&&(this._teamsMeetingThreadId=v.threadId,L.additionalProperties.teamsMeetingThreadId=v.threadId),v?.onBehalfOf&&(L.additionalProperties.onBehalfOfProvided=!0,L.additionalProperties.onBehalfOfIdKind=constructIdentifierKindFromMri(v.onBehalfOf).kind);const F={...L},x={...L};this.sendCallStageEvent({eventName:uE.acs_calling_call_attempt,correlationId:P,timestampInfo:{attemptTimestamp:A},additionalPayload:L},void 0,void 0,void 0,"attempt");try{this._isMicrophoneMuted=_,g?.alternateCallerId&&(b=getMriFromIdentifier(g.alternateCallerId)),T&&await this.setLocalVideoStream(T),this.setLocalAudioStream(I)}catch(g){const f=+new Date,S=new CallingCommunicationError({defaultError:D.CALL.INSTANTIATE_CALL,originalError:g});throw F.additionalDetails.communicationServicesError=extractCommunicationServicesErrorForTelemetry(S).communicationServicesError,this.sendCallStageEvent({eventName:uE.acs_calling_call_failed,correlationId:P,timestampInfo:{deltaTimeInMs:f-A},additionalPayload:F},S,void 0,void 0,"failure"),this.logger.error(S.message),S}const U=w.generateCauseId();B_.setCauseIdToNetworkInfo(U);try{const S={...v};!getAcsEcsConfig().calling.setDeviceType||"mesh"!==this._callAgent.getDeviceType()&&"meshV2"!==this._callAgent.getDeviceType()||(S.endpointMetadata=JSON.stringify({meshapp:!0})),this.tsCall.init(S),T&&this.sendVideoEvent({correlationId:R,eventName:uE.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:A},localVideoStream:T,step:"start",isScreenSharingOnFlag:this._isScreenSharingOn});try{if(g?.videoOptions?.constraints){const f=await this._mediaConstraintsManager.setVideoConstraints(g?.videoOptions?.constraints,"start",R,A),S=this._mediaConstraintsManager.getTelemetryPayload({video:f});x.additionalProperties.constraints=S}}catch(g){const f=new CallingCommunicationError({defaultError:D.CALL.CALLSTART_VIDEO_CONSTRAINTS,originalError:g});this.logger.error(`${f.message}`)}const C=this.setClientEndpointCapabilities(g);if(getAcsEcsConfig()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(C.mediaConfiguration={connectionType:"NoDirectConnection"}),_&&(C.muteFlags=1),g?.firstPartyOptions?.disableAudioMixing&&(void 0===C.muteFlags?C.muteFlags=2:C.muteFlags|=2),void 0!==g?.firstPartyOptions?.enableSpatialAudio&&(C.mediaConfiguration=C.mediaConfiguration||{},C.mediaConfiguration.enableSpatialAudio=g.firstPartyOptions.enableSpatialAudio,this._callAgent.tsStack?await this._callAgent.tsStack.setMediaConfig({enableSpatialAudio:g.firstPartyOptions.enableSpatialAudio}):this.logger.error(`Could not set enableSpatialAudio to ${g.firstPartyOptions.enableSpatialAudio} since this._callAgent.tsStack is null`)),C.customHeaderContext=processCustomContext(g),I&&await this.startAudioInternal(I,!0).catch((g=>{this.logger.error(`Failed to start localAudioStream, message=${g?.message}`)})),"RawMedia"===T?.mediaStreamType)try{await this._setRawStream(T,1)}catch(g){const f=+new Date,S=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:g});this.sendVideoEvent({correlationId:R,eventName:uE.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:f-A},localVideoStream:T,step:"start",isScreenSharingOnFlag:this._isScreenSharingOn},S),this.removeLocalVideoStream(T)}f?await this.tsCall.startWithMeetingData(U,{withVideo:!!T&&this.isIPVideoEnabled,muted:_,ringOthers:!0,alternateId:b,shouldResurrect:"resurrect",...C}):await this.tsCall.start({withVideo:!!T&&this.isIPVideoEnabled,muted:_,ringOthers:!0,alternateId:b,...C},U);const M=+new Date;this.sendCallStageEvent({eventName:uE.acs_calling_call_connected,correlationId:P,timestampInfo:{deltaTimeInMs:M-A},additionalPayload:x},void 0,void 0,B_.getRemoveCauseIdToNetworkInfo(U),"success"),I&&this.shallRemoveLasAfterConnectedSuccessfully(I,"start",P,M,A),T&&this.shallRemoveLvsAfterConnectedSuccessfully(T,"start",P,M,A),this._handleAudioEffectsOperations()}catch(g){const f=+new Date,{callEndReason:S,callingCommunicationError:v}=getCallEndReason(this,g);if(T){const S=new CallingCommunicationError({defaultError:D.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND,originalError:g});this.sendVideoEvent({correlationId:R,eventName:uE.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:f-A},localVideoStream:T,step:"start",isScreenSharingOnFlag:this._isScreenSharingOn},S),this.removeLocalVideoStream(T)}throw I&&this.removeLocalAudioStream(I),F.additionalDetails.callEndReason=extractCallEndReasonForTelemetry(S).callEndReason,this.sendCallStageEvent({eventName:uE.acs_calling_call_failed,correlationId:P,timestampInfo:{deltaTimeInMs:f-A},additionalPayload:F},v,void 0,B_.getRemoveCauseIdToNetworkInfo(U),"failure"),this.logger.error(`Failed to start the call, message=${S?.message}, code=${S?.code}, subCode=${S?.subCode}, resultCategories=${S?.resultCategories}`),v}}getTopNDominantSpeakersWithVideoOn(){if(this._internalDominantSpeakersListener){const g=this._internalDominantSpeakersListener.dominantSpeakers.speakersList.map((g=>this._mriToRemoteParticipantMap.get(getMriFromIdentifier(g)))).filter((g=>!!g)).filter((g=>!!g.videoStreams.filter((g=>"Video"===g.mediaStreamType)).find((g=>g.tsStream.isAvailable))));if(this.logger.info(`There are currently ${g.length} top-n dominant speakers with video on in the large meeting where topCount is ${getAcsEcsConfig().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount}`),g.length<getAcsEcsConfig().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount){const f=this._remoteParticipants.filter((g=>!!g.videoStreams.filter((g=>"Video"===g.mediaStreamType)).find((g=>g.tsStream.isAvailable)))).filter((f=>!g.includes(f)));f.sort(((g,f)=>{const S=g.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((g=>"audio"===g.type)).map((g=>g.sourceId))??[],v=S.length>0?Math.min(...S):void 0,C=f.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((g=>"audio"===g.type)).map((g=>g.sourceId))??[],_=C.length>0?Math.min(...C):void 0;return void 0!==v&&null!=_?v-_:0}));for(const S of f){if(g.length===getAcsEcsConfig().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount)break;g.push(S)}}else g.splice(getAcsEcsConfig().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount);return g}return[]}getParticipantCapabilities(){const g=this._capabilityResolver.getCapabilities();return this.logger.log(`participant capabilities are ${g}`),g}getMeetingCapabilitiesInternal(){const g=this._capabilityResolver.getMeetingsCapabilitiesInternal();return this.logger.info(`meeting capabilities are ${g}`),g}feature(g){return this._extensibleApi.getApiObjectInstance(g.callApiCtor)}async hangUp(g){const f=+new Date,S=generateGuid(),v=w.generateCauseId();return B_.setCauseIdToNetworkInfo(v),this.sendCallStageEvent({eventName:uE.acs_calling_call_hangup_attempt,correlationId:S,timestampInfo:{attemptTimestamp:f}}),this.tsCall.stop(g?.forEveryone,v).then((()=>{const g=+new Date;this.sendCallStageEvent({eventName:uE.acs_calling_call_hangup_success,correlationId:S,timestampInfo:{deltaTimeInMs:g-f}},void 0,void 0,B_.getRemoveCauseIdToNetworkInfo(v))})).catch((g=>{const C=+new Date,{callEndReason:_,callingCommunicationError:T}=getCallEndReason(this,g),I=this._callAgent.getEcsConfigIds(),b={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:I.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:I.SkypeWebMedia},additionalDetails:{...extractCallEndReasonForTelemetry(_)}};throw this.sendCallStageEvent({eventName:uE.acs_calling_call_hangup_failure,correlationId:S,timestampInfo:{deltaTimeInMs:C-f},additionalPayload:b},T,void 0,B_.getRemoveCauseIdToNetworkInfo(v)),T}))}async mute(){const g=this.logger.createFnLogger(PS.Mute),f=+new Date,S=generateGuid(),v=w.generateCauseId();B_.setCauseIdToNetworkInfo(v),this.sendAudioEvent({eventName:uE.acs_calling_mute_attempt,eventType:mE.MuteMicrophone,timestampInfo:{attemptTimestamp:f},correlationId:S,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK});try{g.info("mute"),await this.tsCall.mute(v),g.info("mute success");const C=+new Date;this.sendAudioEvent({eventName:uE.acs_calling_mute_success,eventType:mE.MuteMicrophone,timestampInfo:{deltaTimeInMs:C-f},correlationId:S,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:B_.getRemoveCauseIdToNetworkInfo(v)})}catch(C){const _=new CallingCommunicationError({defaultError:D.CALL.MIC_MUTE,originalError:C});g.error("Failed to mute microphone");const T=+new Date;throw this.sendAudioEvent({eventName:uE.acs_calling_mute_failure,eventType:mE.MuteMicrophone,timestampInfo:{deltaTimeInMs:T-f},correlationId:S,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:B_.getRemoveCauseIdToNetworkInfo(v)},_),_}}async unmute(){const g=this.logger.createFnLogger(PS.Unmute),f=+new Date,S=generateGuid();let v=!1;const C=w.generateCauseId();if(B_.setCauseIdToNetworkInfo(C),this.sendAudioEvent({eventName:uE.acs_calling_unmute_attempt,eventType:mE.UnmuteMicrophone,timestampInfo:{attemptTimestamp:f},correlationId:S,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK}),!this.isAudioPermitted()){const f="cannot unmute as microphone is disabled";throw g.error(f),new CallingCommunicationError({defaultError:D.CALL.MIC_DISABLED,originalError:f})}if(!this.isIPAudioEnabled){const f="cannot unmute as IP audio in Teams Meeting Policy is disabled";throw g.error(f),new CallingCommunicationError({defaultError:D.CALL.IP_AUDIO_NOT_ALLOWED,originalError:f})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){const f="cannot unmute as consent is required to be recorded or transcribed";throw g.error(f),new CallingCommunicationError({defaultError:D.CALL.UNMUTE_CONSENT_RESTRICTED,originalError:f})}try{g.info("unmute"),await this.tsCall.unmute(C),g.info("unmute success");const _=+new Date;this.sendAudioEvent({eventName:uE.acs_calling_unmute_success,eventType:mE.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:_-f},correlationId:S,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:B_.getRemoveCauseIdToNetworkInfo(C)});const T=+new Date,I=getAcsEcsConfig()?.calling?.preventStopAudio;if(!I&&this._isDeviceNotFunctioningMuted){this.sendAudioEvent({eventName:uE.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:T},correlationId:S,step:"mid-call",networkInfo:B_.getRemoveCauseIdToNetworkInfo(C)}),v=!0,g.info("start audio"),await this.tsCall.startAudio(),g.info("start audio success");const f=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:uE.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:f-T},correlationId:S,step:"mid-call",networkInfo:B_.getRemoveCauseIdToNetworkInfo(C)})}this.setLocalAudioStream()}catch(_){const T=v?D.CALL.MIC_UNMUTE_AND_STARTAUDIO:D.CALL.MIC_UNMUTE,I=new CallingCommunicationError({defaultError:T,originalError:_});g.error(T.message);const b=+new Date;throw this.sendAudioEvent({eventName:v?uE.acs_calling_start_audio_failure:uE.acs_calling_unmute_failure,eventType:v?void 0:mE.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:b-f},correlationId:S,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK&&!v,networkInfo:B_.getRemoveCauseIdToNetworkInfo(C)},I),I}}async muteAllRemoteParticipants(){const g=getAcsEcsConfig();if(!g.calling.enableMuteOthers)throw new CallingCommunicationError({defaultError:D.CALL.MUTE_ALL_PARTICIPANTS_DISABLED});if(!this.tsCall.conversationType&&this._callInfo.context===jS.TwoParty)throw new CallingCommunicationError({defaultError:D.CALL.MUTE_ALL_PARTICIPANTS_1_TO_1_UNSUPPORTED});const f=this.logger.createFnLogger(PS.MuteAllRemoteParticipants),S=+new Date,v=generateGuid();this.sendAudioEvent({eventName:uE.acs_calling_mute_attempt,eventType:mE.MuteAllRemoteParticipants,timestampInfo:{attemptTimestamp:S},correlationId:v,step:"mid-call"});try{f.info("mute all others"),validateCallConnected(PS.MuteAllRemoteParticipants,this.state);const C=[];if(0!==this._remoteParticipants.length){let S=!1,v=!1,_="";if(this._remoteParticipants.map((T=>{const I=T.tsRemoteParticipant;g.calling.allowMutePstnRemoteParticipant||"phoneNumber"!==T.identifier.kind?[3,5].some((g=>g===I?.state))?void 0!==I&&(C.push(I),_+=getMriFromIdentifier(T.identifier)+", "):(f.warn("non-connected participants cannot be muted by others"),v=!0):(f.warn("PSTN participants cannot be muted by others"),S=!0)})),0!==C.length?(await this.tsCall.muteParticipants(1,C),f.info(`called mute function on the following participants: ${_}`)):f.error("all remote participants are not supported to be muted by others"),S){if(!this._isTeamsMultipersonaUser||!getAcsEcsConfig().calling.teamsMultipersonaSettings.enableServerMutePSTNParticipant)throw new CallingCommunicationError({defaultError:D.CALL.MUTE_ALL_PARTICIPANTS_PSTN_UNSUPPORTED});f.info("Enable server muting of PSTN participant for TeamsMultiPersona user")}if(v)throw new CallingCommunicationError({defaultError:D.CALL.MUTE_ALL_PARTICIPANTS_NONCONNECTED_UNSUPPORTED})}else f.info("no participants to mute in attempt to mute all remote participants");f.info("mute all others success");const _=+new Date;this.sendAudioEvent({eventName:uE.acs_calling_mute_success,eventType:mE.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:_-S},correlationId:v,step:"mid-call"})}catch(g){const C=new CallingCommunicationError({defaultError:D.CALL.MUTE_ALL_PARTICIPANTS,originalError:g});f.error(C.message);const _=+new Date;throw this.sendAudioEvent({eventName:uE.acs_calling_mute_failure,eventType:mE.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:_-S},correlationId:v,step:"mid-call"},C),C}}async muteIncomingAudio(){const g=this.logger.createFnLogger(PS.MuteIncomingAudio),f=+new Date,S=generateGuid();this.sendAudioEvent({eventName:uE.acs_calling_mute_attempt,eventType:mE.MuteIncomingAudio,timestampInfo:{attemptTimestamp:f},correlationId:S,step:"mid-call"});try{await this.tsCall.muteSpeaker();const g=+new Date;this.sendAudioEvent({eventName:uE.acs_calling_mute_success,eventType:mE.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:g-f},correlationId:S,step:"mid-call"})}catch(v){const C=new CallingCommunicationError({defaultError:D.CALL.MUTE_INCOMING_AUDIO,originalError:v});g.error(C.message);const _=+new Date;throw this.sendAudioEvent({eventName:uE.acs_calling_mute_failure,eventType:mE.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:_-f},correlationId:S,step:"mid-call"},C),C}}async unmuteIncomingAudio(){const g=this.logger.createFnLogger(PS.MuteIncomingAudio),f=+new Date,S=generateGuid();this.sendAudioEvent({eventName:uE.acs_calling_unmute_attempt,eventType:mE.UnmuteIncomingAudio,timestampInfo:{attemptTimestamp:f},correlationId:S,step:"mid-call"});try{await this.tsCall.unmuteSpeaker();const g=+new Date;this.sendAudioEvent({eventName:uE.acs_calling_unmute_success,eventType:mE.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:g-f},correlationId:S,step:"mid-call"})}catch(v){const C=new CallingCommunicationError({defaultError:D.CALL.UNMUTE_INCOMING_AUDIO,originalError:v});g.error(C.message);const _=+new Date;throw this.sendAudioEvent({eventName:uE.acs_calling_unmute_failure,eventType:mE.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:_-f},correlationId:S,step:"mid-call"},C),C}}async sendDtmf(g){const f=toDtmfTone(g);return this.tsCall.sendDtmfTone(f).catch((g=>{throw this.logger.error("Failed to send DTMF tone"),new CallingCommunicationError({defaultError:D.CALL.DTMF_TONE})}))}async startVideo(g){const f=this.logger.createFnLogger(PS.StartVideo),S=+new Date,v=generateGuid(),C=getAcsEcsConfig()?.calling?.preventStopAudio;if(this.sendVideoEvent({eventName:uE.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:S},localVideoStream:g,correlationId:v,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn}),!this.isVideoPermitted()){const g="cannot start video as camera is disabled by the Presenter or Organizer of the meeting";throw f.error(g),new CallingCommunicationError({defaultError:D.CALL.CAMERA_DISABLED,originalError:g})}if(!this.isIPVideoEnabled){const g="cannot start video as IP video is not allowed";throw f.error(g),new CallingCommunicationError({defaultError:D.CALL.IP_VIDEO_NOT_ALLOWED,originalError:g})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){const g="cannot start video as consent is restricted";throw f.error(g),new CallingCommunicationError({defaultError:D.CALL.VIDEOSTART_CONSENT_RESTRICTED,originalError:g})}if(this._isDeviceNotFunctioningMuted&&!C){this.sendAudioEvent({eventName:uE.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:S},correlationId:v,step:"mid-call"});try{f.info("start audio before starting video"),await this.tsCall.startAudio(),f.info("start audio success before starting video");const g=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:uE.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:g-S},correlationId:v,step:"mid-call"})}catch(g){const C="Failed to start audio before starting video",_=new CallingCommunicationError({defaultError:D.CALL.START_AUDIO_BEFORE_VIDEO,originalError:g});f.error(C);const T=+new Date;throw this.sendAudioEvent({eventName:uE.acs_calling_start_audio_failure,timestampInfo:{deltaTimeInMs:T-S},correlationId:v,step:"mid-call"},_),_}}try{if(!g)throw new CallingCommunicationError({defaultError:D.CALL.STREAM_NULL});if(!(g instanceof LocalVideoStream))throw new CallingCommunicationError({defaultError:D.CALL.STREAM_IS_NOT_LVS});if(this.tsCall.isVideoOn)throw new CallingCommunicationError({defaultError:D.CALL.VIDEO_ALREADY_ON});"RawMedia"===g?.mediaStreamType&&await this._setRawStream(g,1),await this.setLocalVideoStream(g)}catch(f){const C=new CallingCommunicationError({defaultError:D.CALL.START_VIDEO,originalError:f});throw this.sendVideoEvent({correlationId:v,eventName:uE.acs_calling_start_video_failure,timestampInfo:{attemptTimestamp:S},localVideoStream:g,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},C),C}const _=w.generateCauseId();B_.setCauseIdToNetworkInfo(_);try{f.info("start video"),await this.tsCall.startVideo(void 0,_);const C=+new Date;this.sendVideoEvent({correlationId:v,eventName:uE.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:C-S},localVideoStream:g,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:B_.getRemoveCauseIdToNetworkInfo(_)}),f.info("video started")}catch(C){const T=+new Date,I=handleVideoOperationFailure(f,C);throw this.sendVideoEvent({correlationId:v,eventName:uE.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:T-S},localVideoStream:g,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:B_.getRemoveCauseIdToNetworkInfo(_)},I),this.removeLocalVideoStream(g),I}}async stopVideo(g){const f=this.logger.createFnLogger(PS.StopVideo),S=+new Date,v=generateGuid();this.sendVideoEvent({correlationId:v,eventName:uE.acs_calling_stop_video_attempt,timestampInfo:{attemptTimestamp:S},localVideoStream:g,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn});const C=4===this.tsCall.state||5===this.tsCall.state;if(!C&&!this.tsCall.isVideoOn||C&&!this.localVideoStream){const f=new CallingCommunicationError({defaultError:D.CALL.VIDEO_ALREADY_OFF});throw this.sendVideoEvent({correlationId:v,eventName:uE.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:S},localVideoStream:g,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},f),f}if(void 0!==this.localVideoStream&&this.localVideoStream!==g){const f=new CallingCommunicationError({defaultError:D.CALL.STOP_WRONG_STREAM});throw this.sendVideoEvent({correlationId:v,eventName:uE.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:S},localVideoStream:g,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},f),f}const unsetRawVideoStream=()=>{try{if(getAcsEcsConfig().calling.allowAccessRawMediaStream&&"RawMedia"===g.mediaStreamType){const g=this._callAgent.tsStack?.getDeviceManager();g&&g.unsetRawMediaStream&&g.unsetRawMediaStream(1)}}catch(g){this.logger.info(`Unset raw video stream: ${g?.message??"Unkown error"}`)}},_=w.generateCauseId();B_.setCauseIdToNetworkInfo(_);try{f.info("stop video"),await this.tsCall.stopVideo(void 0,_),unsetRawVideoStream();const C=+new Date;this.sendVideoEvent({correlationId:v,eventName:uE.acs_calling_stop_video_success,timestampInfo:{deltaTimeInMs:C-S},localVideoStream:g,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:B_.getRemoveCauseIdToNetworkInfo(_)}),f.info("video stopped"),this.removeLocalVideoStream(g)}catch(C){unsetRawVideoStream();const T=+new Date,I=handleVideoOperationFailure(f,C,!0);throw this.sendVideoEvent({correlationId:v,eventName:uE.acs_calling_stop_video_failure,timestampInfo:{deltaTimeInMs:T-S},localVideoStream:g,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:B_.getRemoveCauseIdToNetworkInfo(_)},I),I}}startAudio(g){return this.startAudioInternal(g)}stopAudio(){return this.stopAudioInternal()}async hold(){const g=+new Date,f=generateGuid(),S=w.generateCauseId();B_.setCauseIdToNetworkInfo(S);try{this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Hold,kindOfEvent:gE.attempt,timestampInfo:{deltaTimeInMs:g},additionalDetails:{holdType:qS.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),getAcsEcsConfig().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log("Successfully turned off screen sharing before hold")})).catch((()=>{this.logger.error("Failed to turn off screensharing before hold")})),await this.tsCall.hold(void 0,S),this.removeLocalAudioStream(this._localAudioStreams[0]);const v=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Hold,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:v-g},additionalDetails:{holdType:qS.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn},networkInfo:B_.getRemoveCauseIdToNetworkInfo(S)})}catch(v){const C=+new Date,_=new CallingCommunicationError({defaultError:D.CALL.HOLD_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Hold,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:C-g},additionalDetails:{failureReason:_.message,code:_.code,subCode:_.subCode,holdType:qS.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...extractCommunicationServicesErrorForTelemetry(_)},networkInfo:B_.getRemoveCauseIdToNetworkInfo(S)}),_}}async resume(){const g=+new Date,f=generateGuid(),S=w.generateCauseId();B_.setCauseIdToNetworkInfo(S);try{this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Resume,kindOfEvent:gE.attempt,timestampInfo:{deltaTimeInMs:g},additionalDetails:{holdType:qS.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unhold(void 0,S),this.setLocalAudioStream();const v=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Resume,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:v-g},additionalDetails:{isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,holdType:qS.Standard},networkInfo:B_.getRemoveCauseIdToNetworkInfo(S)})}catch(v){const C=+new Date,_=new CallingCommunicationError({defaultError:D.CALL.RESUME_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Resume,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:C-g},additionalDetails:{failureReason:_.message,code:_.code,subCode:_.subCode,holdType:qS.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...extractCommunicationServicesErrorForTelemetry(_)},networkInfo:B_.getRemoveCauseIdToNetworkInfo(S)}),_}}async startScreenSharing(g){const f=this.logger.createFnLogger(PS.StartScreenShare),S=+new Date,v=generateGuid();try{if(this.sendScreenShareEvent({eventName:uE.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:v,kindOfEvent:gE.attempt,timestampInfo:"",additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:g}),3!==this.tsCall.state)throw new CallingCommunicationError({defaultError:D.CALL.START_SS_CALL_NOT_CONNECTED});if(this.tsCall.isScreenSharingOn)throw new CallingCommunicationError({defaultError:D.CALL.SS_ALREADY_ON});if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){const g="screen sharing cannot be started as consent is required to be recorded or transcribed";throw f.error(g),new CallingCommunicationError({defaultError:D.CALL.SCREENSHARE_CONSENT_RESTRICTED,originalError:g})}if(g){if(!(g instanceof LocalVideoStream))throw new CallingCommunicationError({defaultError:D.CALL.SS_RAW_STREAM_IS_NOT_LVS});if("RawMedia"!==g.mediaStreamType)throw new CallingCommunicationError({defaultError:D.CALL.SS_RAW_STREAM_LVS_IS_NOT_RAW_MEDIA});await this._setRawStream(g,2),this.localScreenSharingStream=g}else this.localScreenSharingStream=new LocalVideoStream(new VideoDeviceInfoImpl(CS.ScreenSharing,generateGuid(),CS.ScreenSharing,this._callAgent.deviceManager))}catch(g){const f=+new Date;this.removeScreenSharingStream();const C=new CallingCommunicationError({defaultError:D.CALL.START_SS,originalError:g});throw this.sendScreenShareEvent({eventName:uE.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:v,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:f-S},additionalDetails:{failureReason:C.message,code:C.code,subCode:C.subCode,...extractCommunicationServicesErrorForTelemetry(C)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),C}return this.tsCall.startScreenSharing().then((()=>{const g=+new Date;this.localScreenSharingStream&&-1===this._localVideoStreams.indexOf(this.localScreenSharingStream)&&(this.localScreenSharingStream.addCall(this),this._localVideoStreams.push(this.localScreenSharingStream),this._eventEmitter.emit("localVideoStreamsUpdated",{added:[this.localScreenSharingStream],removed:[]})),this.sendScreenShareEvent({eventName:uE.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:v,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:g-S},additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream})})).catch((g=>{const C=+new Date;this.removeScreenSharingStream();const _=handleVideoOperationFailure(f,g);throw this.sendScreenShareEvent({eventName:uE.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:v,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:C-S},additionalDetails:{failureReason:_.message,code:_.code,subCode:_.subCode,...extractCommunicationServicesErrorForTelemetry(_)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),_}))}async stopScreenSharing(){const g=this.logger.createFnLogger(PS.StopScreenShare),f=+new Date,S=generateGuid();if(this.sendScreenShareEvent({eventName:uE.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:S,kindOfEvent:gE.attempt,timestampInfo:"",additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),3!==this.tsCall.state)throw new CallingCommunicationError({defaultError:D.CALL.STOP_SS_CALL_NOT_CONNECTED});if(!this.tsCall.isScreenSharingOn){const g=+new Date,v=new CallingCommunicationError({defaultError:D.CALL.SS_ALREADY_OFF});throw this.sendScreenShareEvent({eventName:uE.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:S,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:g-f},additionalDetails:{failureReason:v.message,code:v.code,subCode:v.subCode,...extractCommunicationServicesErrorForTelemetry(v)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),v}return this.tsCall.stopScreenSharing().then((()=>{const g=+new Date,v=M.cloneDeep(this.localScreenSharingStream);this.removeScreenSharingStream(),this.sendScreenShareEvent({eventName:uE.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:S,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:g-f},additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:v})})).catch((v=>{const C=+new Date,_=handleVideoOperationFailure(g,v,!0),T="string"==typeof _?.message?_?.message:void 0;throw this.sendScreenShareEvent({eventName:uE.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:S,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:C-f},additionalDetails:{failureReason:T||"",code:_.code,subCode:_.subCode,...extractCommunicationServicesErrorForTelemetry(_)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),_}))}async setConstraints(g){const f=+new Date,S=generateGuid();try{const v=await this._mediaConstraintsManager.setVideoConstraints(g?.video,"mid-call",S,f);this.logger.info(`Video constraints set - ${JSON.stringify(v)}`)}catch(g){throw new CallingCommunicationError({defaultError:D.CALL.SET_VIDEO_CONSTRAINTS,originalError:g})}}on(g,f){if("stateChanged"!==g&&"idChanged"!==g&&"isMutedChanged"!==g&&"isIncomingAudioMutedChanged"!==g&&"isScreenSharingOnChanged"!==g&&"isLocalVideoStartedChanged"!==g&&"remoteParticipantsUpdated"!==g&&"localVideoStreamsUpdated"!==g&&"localAudioStreamsUpdated"!==g&&"remoteAudioStreamsUpdated"!==g&&"totalParticipantCountChanged"!==g&&"roleChanged"!=g&&"mutedByOthers"!==g&&"callerInfoChanged"!==g&&"transferorInfoChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("stateChanged"!==g&&"idChanged"!==g&&"isMutedChanged"!==g&&"isIncomingAudioMutedChanged"!=g&&"isScreenSharingOnChanged"!==g&&"isLocalVideoStartedChanged"!==g&&"remoteParticipantsUpdated"!==g&&"localVideoStreamsUpdated"!==g&&"localAudioStreamsUpdated"!==g&&"remoteAudioStreamsUpdated"!==g&&"totalParticipantCountChanged"!=g&&"roleChanged"!=g&&"mutedByOthers"!==g&&"callerInfoChanged"!==g&&"transferorInfoChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}onMeetingCapabilitiesChanged(g,f){if("meetingCapabilitiesChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}offMeetingCapabilitiesChanged(g,f){if("meetingCapabilitiesChanged"!=g)throw new CallingCommunicationError({defaultError:D.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}onParticipantCapabilitiesChanged(g,f){this.logger.log("participant capabilities change event listener registered"),this._eventEmitter.on(g,f)}offParticipantCapabilitiesChanged(g,f){this.logger.log("participant capabilities change event listener unregistered"),this._eventEmitter.off(g,f)}onWatermarkAudioOnlyFallbackTriggeredChanged(g,f){this.logger.log("watermark audio only fallback triggered listener registered"),this._eventEmitter.on(g,f)}offWatermarkAudioOnlyFallbackTriggeredChanged(g,f){this.logger.log("watermark audio only fallback triggered listener unregistered"),this._eventEmitter.off(g,f)}getOrCreateRemoteParticipant(g,f){let S=this._remoteParticipants.find((f=>getMriFromIdentifier(f.identifier)===getMriFromIdentifier(g)));return S||(S=new RemoteParticipantImpl(g,this.logger,this,this._callAgent,this._telemetryLogManager),this._remoteParticipants.push(S),this._mriToRemoteParticipantMap.set(getMriFromIdentifier(S.identifier),S)),f&&S.observeParticipant(f),S}deleteRemoteParticipant(g){let f=!0;return 1!==this._remoteParticipants.splice(this._remoteParticipants.indexOf(g),1).length&&(this.logger.warn("Deleted remote participant array is not 1"),f=!1),this._mriToRemoteParticipantMap.delete(getMriFromIdentifier(g.identifier))||(this.logger.warn("Deleted remote participant was not found in mri-to-remoteparticipant map"),f=!1),f}sendCallOnHoldAndResumedEvent(g){try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this.logger.debug("Unable to send call hold or resume telemetry")}}sendVideoEvent(g,f){try{let S,v;try{S=g.localVideoStream?.getStreamMetadata()}catch(g){this.logger.error("Unable to get stream meta data on send video event")}f&&(v="string"==typeof f?.message?f?.message:void 0,g.additionalDetails={...extractCommunicationServicesErrorForTelemetry(f)}),this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:{...S,callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:g.timestampInfo,correlationId:g.correlationId,step:g.step||"",failureReason:v||"",isScreenSharingOnFlag:g.isScreenSharingOnFlag,additionalDetails:g.additionalDetails||{},networkInfo:g.networkInfo||[]}})}catch(g){this.logger.debug("Unable to send video telemetry")}}sendScreenShareEvent(g){let f;try{f=g.localVideoStream?.getStreamMetadata()}catch(g){this.logger.error("Unable to get stream meta data on send video event")}try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:{...f,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:g.correlationId,kindOfEvent:g.kindOfEvent,timestampInfo:g.timestampInfo,additionalDetails:g.additionalDetails,isVideoOn:g.isVideoOn}})}catch(g){this.logger.debug("Unable to send screen share telemetry")}}sendRawMediaEvent(g){const f={...g};f.localAudioStream=g.localAudioStream?.source instanceof MediaStream?"MediaStream":"Device";try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:f})}catch(g){this.logger.debug("Unable to send raw media telemetry")}}sendAudioEvent(g,f){try{let S;f&&(S="string"==typeof f?.message?f?.message:void 0,g.additionalDetails={...extractCommunicationServicesErrorForTelemetry(f)});const v={callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:g.timestampInfo,correlationId:g.correlationId,step:g.step||"",failureReason:S||"",additionalDetails:g.additionalDetails||{},networkInfo:g.networkInfo||[]};void 0!==g.eventType&&(v.eventType=g.eventType),g.initiatedBySdk&&(v.initiatedBySdk=!0),this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:v})}catch(g){this.logger.debug("Unable to send audio telemetry")}}sendCallStageEvent(f,S,v,C,_){try{let T,I="";S&&(T=this?.tsCall?.callEndDiagnosticsInfo||v||{},I=S.message);const b=this._joinContextDescription===lS.RoomCall||this.kind===g.CallKind.Call&&"Incoming"===this._direction&&!this.tsCall.groupId&&!!this.tsCall.meetingData?.meetingCode&&!this.tsCall.threadId,A=!b&&this._joinContextDescription===lS.TeamsMeetingLink||this._joinContextDescription===lS.TeamsMeetingId||this._joinContextDescription===lS.TeamsCoordinates||"Incoming"==this._direction&&!this.tsCall.groupId&&!!this.tsCall.meetingData&&!!this.tsCall.threadId,P={localParticipantId:this?.tsCall?.participantId||"",callId:this?.tsCall?.callId||"",callType:this?.tsCall?.callType||"",callDirection:this._direction,failureReason:I,callEndDiagnosticsInfo:T,calleeIdentityType:this.getParticipantIdentityType(),groupJoin:!!this?.tsCall?.groupId,roomJoin:b,meetingJoin:A,hostRegion:this?.tsCall?.region||"",correlationId:f.correlationId,timestampInfo:f.timestampInfo,...f.additionalPayload,networkInfo:C||[]};this._telemetryLogManager.sendEvent({name:f.eventName,tenant:tf,properties:P},void 0,_)}catch(g){}}getParticipantIdentityType(){if(this.tsCall?.participants.length>1)return yS.group;if(0===this.tsCall?.participants.length)return yS.unknown;const g=this.tsCall?.participants[0];return constructIdentifierKindFromMri(g.id).kind}optimalVideoCountChanged(){const g=this._optimalVideoCount,f=this.tsCall.optimalVideoCount;if(f&&g!==f)try{sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),step:"optimalVideoCount-changed",previousOptimalVideoCount:g,newOptimalVideoCount:f,currentNumberOfVideosRendered:this.activeRemoteVideoStreamViews?.size||0})}catch(g){this.logger.error("Failed to send optimal video count change telemetry")}finally{this._optimalVideoCount=this.tsCall.optimalVideoCount||1}}_sendNetworkChangedTelemetry(){try{const recordNetworkChangedTelemetry=(g,f,S)=>{sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),step:"network-changed",trouterState:g,onLine:f,rdpState:S})};this._trouterStateChangedListener=g=>{recordNetworkChangedTelemetry(g,navigator.onLine,this._mmrRdpConnectionManager.state)},this._callAgent.onTrouterStateChanged(this._trouterStateChangedListener),this._onlineListener=g=>{recordNetworkChangedTelemetry(this._callAgent.getTrouterState(),!0,this._mmrRdpConnectionManager.state)},window.addEventListener("online",this._onlineListener),this._offlineListener=g=>{recordNetworkChangedTelemetry(this._callAgent.getTrouterState(),!1,this._mmrRdpConnectionManager.state)},window.addEventListener("offline",this._offlineListener),this._mmrRdpConnectionManager.on("stateChange",(g=>{recordNetworkChangedTelemetry(this._callAgent.getTrouterState(),!1,g)})),recordNetworkChangedTelemetry(this._callAgent.getTrouterState(),navigator.onLine,this._mmrRdpConnectionManager.state)}catch(g){this.logger.warn("Failed to subscribe to network changed")}}_setupSelectedDeviceChangedTelemetry(){try{const recordTelemetry=g=>{sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),step:"selectedDevice-changed",selectedDeviceType:g.selectedDeviceType,oldDevice:g.oldDevice,newDevice:g.newDevice})};if(this._selectedDeviceManager){this._selectedDeviceManager.on("selectedDeviceChanged",recordTelemetry);const g=this._selectedDeviceManager.selectedDevice("Speaker"),f=this._selectedDeviceManager.selectedDevice("Microphone");recordTelemetry({selectedDeviceType:"Speaker",oldDevice:void 0,newDevice:g}),recordTelemetry({selectedDeviceType:"Microphone",oldDevice:void 0,newDevice:f})}}catch(g){this.logger.warn("Failed to subscribe to selectedDevice changed")}}async setLocalVideoStream(g){if(!this._callAgent.tsStack)throw new CallingCommunicationError({defaultError:D.CALL.VIDEO_UNDEFINED_STACK});if(!this.localVideoStream&&g&&!this._localVideoStreams.find((f=>f===g))){if(this.localVideoStream=g,this._localVideoStreams.push(this.localVideoStream),"RawMedia"!==this.localVideoStream.mediaStreamType){const f=await(this._callAgent.tsStack.getDeviceManagerAsync?.());await(f?.selectDevicesAsync?.({camera:g.source.id}))}this.localVideoStream.addCall(this);try{this._eventEmitter.emit("localVideoStreamsUpdated",{added:[this.localVideoStream],removed:[]})}catch(g){this.logger.warn("Application threw on emit localVideoStreamsUpdated added")}this.logger.log("isLocalVideoStarted changed=true"),this._isLocalVideoStarted=!0,this._eventEmitter.emit("isLocalVideoStartedChanged")}}removeLocalVideoStream(g){if(this.localVideoStream&&g===this.localVideoStream&&this.localVideoStreams.find((g=>g===this.localVideoStream))){this.logger.log("Attempting to remove local video stream");if(0===this._localVideoStreams.splice(this._localVideoStreams.indexOf(this.localVideoStream),1).length)return void this.logger.warn("Stream not found, failed to remove stream from localVideoStreams collection");this.logger.log("Local video stream removed successfully"),this.localVideoStream.removeCall(this),this.localVideoStream.dispose();const g=this.localVideoStream;this.localVideoStream=void 0;try{this._eventEmitter.emit("localVideoStreamsUpdated",{added:[],removed:[g]})}catch(g){this.logger.warn("Application threw on emit localVideoStreamsUpdated removed")}this.logger.log("isLocalVideoStarted changed=false"),this._isLocalVideoStarted=!1,this._eventEmitter.emit("isLocalVideoStartedChanged")}}setLocalAudioStream(g){if(!this._callAgent.tsStack)throw new CallingCommunicationError({defaultError:D.CALL.LOCAL_AUDIO_UNDEFINED_STACK});if(g)g.on("audioSourceChanged",this.audioSourceChanged),this._localAudioStreams.push(g),g.addCall(this),this._eventEmitter.emit("localAudioStreamsUpdated",{added:[g],removed:[]});else if(0===this._localAudioStreams.length){if(this._userProvidedLocalAudioStreamCache)return(g=this._userProvidedLocalAudioStreamCache).on("audioSourceChanged",this.audioSourceChanged),this._localAudioStreams.push(g),g.addCall(this),void this._eventEmitter.emit("localAudioStreamsUpdated",{added:[g],removed:[]});const f=this.deviceManager?.selectedMicrophone;if(f){const g=new LocalAudioStream(f);g.on("audioSourceChanged",this.audioSourceChanged),this._localAudioStreams.push(g),g.addCall(this),this._eventEmitter.emit("localAudioStreamsUpdated",{added:[g],removed:[]})}else this.logger.warn("Could not get current selected microphone to update localAudioStreams collection")}else this.logger.warn("No localAudioStream provided and the collection is not empty, doing nothing")}removeLocalAudioStream(g){if(g){this.logger.log("Attempting to remove local audio stream"),g.off("audioSourceChanged",this.audioSourceChanged),g.dispose();if(0===this._localAudioStreams.splice(this._localAudioStreams.indexOf(g),1).length)return void this.logger.warn("Stream not found, failed to remove stream from localAudioStreams collection");g.removeCall(this),this.logger.log("Local audio stream removed successfully"),this._eventEmitter.emit("localAudioStreamsUpdated",{added:[],removed:[g]})}}_handleAudioEffectsOperations(){try{const g=this._localAudioStreams?.[0];if(!g)return void this.logger.debug("No LocalAudioStream found in the call, cannot handle call audio effects operations");this._audioEffectsStatsListener=g=>{this._audioEffectsProcessorStats=g};const f=g.feature(fb.AudioEffects);f?.on("effectsProcessorStatsUpdated",this._audioEffectsStatsListener)}catch(g){this.logger.warn(`Error handling audio effects operations during call start: ${g}`)}}isAudioPermitted(){return!!this.feature(fb.MediaAccess)?.getLocalParticipantMediaAccess().isAudioPermitted}isVideoPermitted(){return!!this.feature(fb.MediaAccess)?.getLocalParticipantMediaAccess().isVideoPermitted}removeScreenSharingStream(){if(this.localScreenSharingStream&&this.localVideoStreams.find((g=>g===this.localScreenSharingStream))){if(getAcsEcsConfig()?.calling?.allowAccessRawMediaStream&&"RawMedia"===this.localScreenSharingStream?.mediaStreamType){const g=this._callAgent.tsStack?.getDeviceManager();g?.unsetRawMediaStream&&g.unsetRawMediaStream(2)}this.localScreenSharingStream.dispose(),this.localScreenSharingStream.removeCall(this);const g=this._localVideoStreams.indexOf(this.localScreenSharingStream);this._localVideoStreams.splice(g,1);const f=this.localScreenSharingStream;this.localScreenSharingStream=void 0,this._eventEmitter.emit("localVideoStreamsUpdated",{added:[],removed:[f]})}}mapTsCallState(g){const f=qE[g];switch(f){case"Unknown":case void 0:this.logger.log(`Ignored tsCall state \`${g}\``);break;case"Disconnected":{this._callEndReason=getCallEndReason(this).callEndReason,this._remoteParticipants.forEach((g=>{g.setCallEndReason(getRemoteParticipantCallEndReason(this,g.tsRemoteParticipant).callEndReason),g.setParticipantState("Disconnected")}));const S=this._remoteParticipants.map((g=>g));this._remoteParticipants=[],this._mriToRemoteParticipantMap.clear(),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:S}),this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream),this.localAudioStreams[0]&&this.removeLocalAudioStream(this.localAudioStreams[0]),this._rawAudioStreamChangedSubscription?.dispose&&this._rawAudioStreamChangedSubscription.dispose(),getAcsEcsConfig().calling.allowAccessRawMediaStream&&this.remoteAudioStreams[0]&&this.removeRemoteAudioStream(this.remoteAudioStreams[0]),this._userProvidedLocalAudioStreamCache=void 0,this.logger.log(`Mapped tsCall state:${g} to ${f}`),this._setCallState(f),this._telemetryLogManager.flushAllEvents(this.id).then((()=>{this.logger.log("Telemetry flushed")})).catch((g=>{this.logger.warn("Failed to flush telemetry log manager events")}));break}case"Connected":this.logger.log(`Mapped tsCall state:${g} to ${f}`),this._remoteParticipantsChangedListeners.forEach((g=>{g.dispose()})),this._setCallState(f),this.setOrUpdateMediaMetricsDeviceEvents(),getAcsEcsConfig().calling.allowAccessRawMediaStream&&this.subscribeToGetRemoteAudioStream();break;case"Incoming Call":{this.logger.log(`state changed from ${this._state} to 'Incoming Call'`);const g=new CallInfoCommonImpl(this.tsCall,{config:this._config});sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),step:"state-changed",oldState:this._state,newState:"Incoming Call",callTypeInfo:{initiatorKind:g.initiatorKind,targetKind:g.targetKind,transferor:g.transferorKind,context:g.context,callScenario:g.callScenario,direction:g.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||"",teamsMeetingThreadId:this._teamsMeetingThreadId||"",callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1});break}default:this.logger.log(`Mapped tsCall state:${g} to ${f}`),this._setCallState(f)}}shallStopVideo(g){const f=getAcsEcsConfig()?.calling?.deviceNotFunctioningMuted,S=getAcsEcsConfig()?.calling?.deviceCaptureMutedVideo,v=getAcsEcsConfig()?.calling?.preventStopVideo,C=25===g.type&&3===g.value,_=C&&1===g.mediaType,T=33===g.type&&3===g.value,I=getBrowserInfo(),b="ios"===getOS()&&"Safari"===I.engine,A="android"===getOS(),P=3===this.tsCall.state;return v?P&&this.tsCall.isVideoOn&&T:f&&P&&this.tsCall.isVideoOn&&(T||b&&C||S&&A&&_)}shallRemoveLocalVideoStreamOnBadUfd(g){const f=this.tsCall.localMediaStreams.find((g=>1===g.mediaType)),S=1===g.mediaType&&3===g.value&&25===g.type,v=4==this.tsCall.state||5===this.tsCall.state;if("Mobile"===getBrowserInfo().formFactor&&(S||"hidden"==document.visibilityState)&&this.localVideoStream&&v&&!f)return!1;if(!getAcsEcsConfig()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return!1;const C=3===this.tsCall.state;return 1===g.mediaType&&3===g.value&&(33===g.type||25===g.type||34===g.type)&&!!this.localVideoStream&&!C&&!f}shallStopAudio(g){const f=getAcsEcsConfig()?.calling?.deviceNotFunctioningMuted,S=getAcsEcsConfig()?.calling?.osAutoRecoverAudio,v=25===g.type&&3===g.value&&0===g.mediaType,C=9===g.type&&3===g.value,_=getBrowserInfo(),T="ios"===getOS()&&"Safari"===_.engine,I=3===this.tsCall.state;return S?f&&I&&C:f&&!this._isDeviceNotFunctioningMuted&&I&&(C||T&&v)}markCallMuted(){this._isDeviceNotFunctioningMuted=!0,this._handleMuteChanges()}audioDidAutoRecover(g){const f=getAcsEcsConfig()?.calling?.deviceCaptureMuteRecover&&!getAcsEcsConfig()?.calling?.preventFakeMute,S=25===g.type&&1===g.value&&0===g.mediaType,v=3===this.tsCall.state,C=getBrowserInfo(),_="ios"===getOS()&&"Safari"===C.engine,T=9===g.type&&1===g.value;return f&&this._isDeviceNotFunctioningMuted&&v&&(T||_&&S)}sendParticipantAddedOrRemovedEvent(g){try{this._telemetryLogManager.sendEvent({name:uE.acs_calling_participant_added_or_removed,tenant:tf,properties:{callId:this.id,remotePerticipantId:Array.isArray(g?.remoteParticipantIds)?g?.remoteParticipantIds.slice(0,getAcsEcsConfig().telemetry.maxExistingReportedParticipants):[],participantAddedOrRemoved:g.participantAddedOrRemoved,localParticipantId:this.tsCall.participantId,kindOfEvent:g.kindOfEvent,correlationId:g.correlationId||"",timestampInfo:g.timestampInfo||"",additionalDetails:g.additionalDetails||{},networkInfo:g.networkInfo||[]}})}catch(g){this.logger.debug("Unable to send participant added or removed telemtery")}}_handleLocalRingingCallState(g){"Connected"===this._state||"Outgoing"!==this._direction||this._localRingingStateSet||this._remoteParticipantsChangedListeners.push(g.changed((()=>{2!==g.state||"Connected"===this._state||this._localRingingStateSet||(this._setCallState("Ringing"),this._localRingingStateSet=!0,this._remoteParticipantsChangedListeners.forEach((g=>{g.dispose()})))})))}_setCallState(g){if(g!==this._state){const f=this._state,S=g,v=new CallInfoCommonImpl(this.tsCall,{config:this._config});this.logger.log(`state changed from ${f} to ${S}`),this._state=S,"Connected"===S&&(this._connectedTimestamp=Date.now()),this._eventEmitter.emit("stateChanged"),sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),step:"state-changed",oldState:f,newState:S,callTypeInfo:{initiatorKind:v.initiatorKind,targetKind:v.targetKind,transferor:v.transferorKind,context:v.context,callScenario:v.callScenario,direction:v.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||"",teamsMeetingThreadId:this._teamsMeetingThreadId||"",callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1,additionalDetails:"Disconnected"===this._state&&this._callEndReason?{...extractCallEndReasonForTelemetry(this._callEndReason)}:void 0})}}_setCallRole(g){if(g!==this._lastTsCallAdvancedMeetingRole){const f=advancedMeetingRoleToParticipantRole(getAcsEcsConfig(),g);f===Gf?this.logger.log(`tsParticipant advancedMeetingRole=${this._role} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${g}=>${f}`),sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),step:"role-changed",oldAcsRole:this._role,newAcsRole:f,serviceRole:g||""}),this._role!=f&&(this.logger.log(`self-role changed ${this._role}=>${g}`),this._role=f,this._lastTsCallAdvancedMeetingRole=g,this._capabilityResolver.resolveCapabilitiesBasedOnRole(),this._eventEmitter.emit("roleChanged"))}}_setMeetingCapabilities(g){hasCoreMeetingCapabilitiesChanged(g,this._lastTsCallMeetingDetails)&&(sendCallProgressEvent(this._telemetryLogManager,this.logger,{...getCallProgressCommonPayload(this,this._callAgent,generateGuid(),this._joinContextDescription),step:"meetingCapabilities-changed",oldMeetingDetails:this._lastTsCallMeetingDetails,newMeetingDetails:g}),this.logger.log(`Core Meeting Capabilities has changed to: ${JSON.stringify(g)}`),this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities(),this._eventEmitter.emit("meetingCapabilitiesChanged")),Object.assign(this._lastTsCallMeetingDetails,g)}removeRemoteAudioStream(g){if(g){this.logger.log("Attempting to remove remote audio stream");if(0===this._remoteAudioStreams.splice(this._remoteAudioStreams.indexOf(g),1).length)return void this.logger.warn("Stream not found, failed to remove stream from remoteAudioStreams collection");this.logger.log("remote audio stream removed successfully"),this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:[],removed:[g]})}}async setOrUpdateMediaMetricsDeviceEvents(){if(getAcsEcsConfig().calling.mediaMetricsDeviceEventsEnabled)try{const g=await(this.tsCall.getMediaSessionStatsAsync?.());if(void 0!==g?.metrics?.DeviceEvents){const f=JSON.parse(g.metrics.DeviceEvents),S=getSafeObjectDiff(this._mediaMetricsDeviceEvents||{},f);S.length>0&&(this._mediaMetricsDeviceEvents=f,this.stats.recordEvent({name:hE.media_metrics_device_events,callId:this.id,localParticipantId:this.tsCall.participantId,data:{metricsDeviceEvents:S||{},metricsDevicesChangeCount:f?.metrics_DevicesChangeCount||0,metricsDevicesCount:f?.metrics_DevicesCount||{}}}))}else this.logger.info("Failed to set media metrics device events telemetry: no valid events data")}catch(g){this.logger.error("Failed to set media metrics device events telemetry")}}setClientEndpointCapabilities(g){const f={};let S=0;return g?.firstPartyOptions?.isImmersiveMode&&(S|=32768),getAcsEcsConfig()?.calling?.supportLiveStreaming&&(S|=32),getAcsEcsConfig()?.calling.sharedLineAppearance.enabled&&(S|=128),this._allowBreakoutRoomJoin&&(S|=4098),S>0&&(f.clientEndpointCapabilities=S),f}getLocalVideoStreamFromCallOptions(g){let f;if(Array.isArray(g?.videoOptions?.localVideoStreams)){if(1!==g?.videoOptions?.localVideoStreams.length)throw new CallingCommunicationError({defaultError:D.CALL.ONLY_SINGLE_VIDEO_STREAM});if(f=g?.videoOptions?.localVideoStreams[0],!(f instanceof LocalVideoStream))throw new CallingCommunicationError({defaultError:D.CALL.NOT_INSTANCE_OF_LVS})}return f}getLocalAudioStreamFromCallOptions(g){let f;if(Array.isArray(g?.audioOptions?.localAudioStreams)){if(1!==g?.audioOptions?.localAudioStreams.length)throw new CallingCommunicationError({defaultError:D.CALL.ONLY_SINGLE_AUDIO_STREAM});if(f=g?.audioOptions?.localAudioStreams[0],!(f instanceof LocalAudioStream))throw new CallingCommunicationError({defaultError:D.CALL.NOT_INSTANCE_OF_LAS})}return f&&(this._userProvidedLocalAudioStreamCache=f),f}async _setRawStream(g,f){if(!getAcsEcsConfig().calling.allowAccessRawMediaStream)throw new CallingCommunicationError({defaultError:D.CALL.ACCESS_RAW_MEDIA_STREAM_DISABLED});const S=await(this._callAgent.tsStack?.getDeviceManagerAsync?.());if(!S?.setRawMediaStream)throw new CallingCommunicationError({defaultError:D.CALL.ACCESS_RAW_MEDIA_STREAM_UNDEFINED_FUNC});try{const v=await g.getMediaStream();if(!v)throw new CallingCommunicationError({defaultError:D.CALL.SS_RAW_STREAM_UNDEFINED});S.setRawMediaStream(v,f)}catch(g){if(1===f)throw new CallingCommunicationError({defaultError:D.CALL.VIDEO_SET_MEDIA_STREAM,originalError:g});if(2===f)throw new CallingCommunicationError({defaultError:D.CALL.SS_RAW_STREAM_SET,originalError:g})}}shallRemoveLvsAfterConnectedSuccessfully(g,f,S,v,C){if(this.tsCall.localMediaStreams.find((g=>1===g.mediaType)))this.sendVideoEvent({correlationId:S,eventName:uE.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:v-C},localVideoStream:g,step:f,isScreenSharingOnFlag:this._isScreenSharingOn});else{if(!getAcsEcsConfig()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return;this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream);const v=+new Date,_=new CallingCommunicationError({defaultError:D.CALL.VIDEO_FAILED_TO_START,defaultErrorMessageArgs:[f]});this.logger.error(_.message),this.sendVideoEvent({correlationId:S,eventName:uE.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:v-C},localVideoStream:g,step:f,isScreenSharingOnFlag:this._isScreenSharingOn},_)}}shallRemoveLasAfterConnectedSuccessfully(g,f,S,v,C){if(this.tsCall.localMediaStreams.find((g=>0===g.mediaType)))this.sendRawMediaEvent({eventName:uE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:S,kindOfEvent:gE.success,localAudioStream:g,timestampInfo:{deltaTimeInMs:v-C},additionalDetails:""});else{if(!getAcsEcsConfig().calling.removeLocalAudioStreamCheckOnCallStartAndCallAccept)return;this.removeLocalAudioStream(this.localAudioStreams[0]);const v=+new Date;this.logger.error(`Removing local audio stream because audio failed to start during call-${f} process.`);const _=new CallingCommunicationError({defaultError:D.CALL.AUDIO_FAILED_TO_START,defaultErrorMessageArgs:[f]});this.sendRawMediaEvent({eventName:uE.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:S,localAudioStream:g,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:v-C},additionalDetails:{failureReason:_.message||"",code:_.code,subCode:_.subCode,...extractCommunicationServicesErrorForTelemetry(_)}})}}_enableOrDisable_largeMeeting_videoRendering(){try{!this._isHandlingLargeMeetingVideoRendering&&this._totalParticipantCount-1>=getAcsEcsConfig().rendering.remoteVideo.largeMeeting.participantCountThreshold?(this._isHandlingLargeMeetingVideoRendering=!0,this._internalDominantSpeakersListener=new DominantSpeakersCallImplOverTsCall(new CallingEventEmitter(this.logger.createChild((()=>`DominanSpeakersFeatureInternal:: Call(id=${this.tsCall.callId})`)))),this._internalDominantSpeakersListener.initialize(this.tsCall,this._callAgent,this._telemetryLogManager,this.logger,!0),this.logger.info("Initialized internal dominant speakers listener"),this._internalDominantSpeakersListener.on("dominantSpeakersChanged",(()=>{this.handleDominantSpeakersVideos()})),this.handleDominantSpeakersVideos(),this.logger.info("Initialized large meeting video rendering handler")):this._isHandlingLargeMeetingVideoRendering&&(this._totalParticipantCount-1>=getAcsEcsConfig().rendering.remoteVideo.largeMeeting.participantCountThreshold?this.handleDominantSpeakersVideos():(this._isHandlingLargeMeetingVideoRendering=!1,this._internalDominantSpeakersListener?.dispose(),this._internalDominantSpeakersListener=void 0,this.logger.info("Disposed of internal dominant speakers listener"),this.remoteParticipants.forEach((g=>{g.videoStreams.forEach((g=>{g.setIsAvailable(g.tsStream.isAvailable)}))})),this.logger.info("All remote streams isAvailable flags were reset"),this.logger.info("Disposed large meeting video rendering handler")))}catch(g){this.logger.error("Failed to handle large meeting video rendering",g)}}handleDominantSpeakersVideos(){this.logger.info("Dominant speakers changed during large meeting");const g=this.getTopNDominantSpeakersWithVideoOn();this.logger.info(`There are currently ${g.length} top-n speakers with video on in the large meeting`),g.forEach((g=>{g.videoStreams.filter((g=>"Video"===g.mediaStreamType)).forEach((g=>{g.setIsAvailable(g.tsStream.isAvailable)}))})),this._remoteParticipants.filter((f=>!g.includes(f))).forEach((g=>{g.videoStreams.filter((g=>"Video"===g.mediaStreamType)).forEach((g=>{try{g.setIsAvailable(!1)}catch(g){const f=new CallingCommunicationError({defaultError:D.CALL.LARGE_MEETING_FORCE_ISAVAILABLE,originalError:g});this.logger.warn(f.message)}const f=this.activeRemoteVideoStreamViews.get(g.id);f&&f.forEach((g=>{try{g.disposed||(g.dispose(wE.Internal_LargeMeetingVideoRendering),this.logger.info("Successfully disposed of view during large meeting"))}catch(g){const f=new CallingCommunicationError({defaultError:D.CALL.LARGE_MEETING_DISPOSE_VIEW,originalError:g});this.logger.warn(f.message)}}))}))}))}}__decorate$k([loggerProperty,__metadata$k("design:type",Object)],CallCommonImpl.prototype,"logger",void 0),__decorate$k([syncOperation(PS.BindToCall),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[]),__metadata$k("design:returntype",void 0)],CallCommonImpl.prototype,"bindTsCall",null),__decorate$k([syncOperation(PS.Feature),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[Object]),__metadata$k("design:returntype","function"==typeof(Zb="undefined"!=typeof TFeature&&TFeature)?Zb:Object)],CallCommonImpl.prototype,"feature",null),__decorate$k([asyncOperation(PS.HangUp),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[Object]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"hangUp",null),__decorate$k([asyncOperation(PS.Mute),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"mute",null),__decorate$k([asyncOperation(PS.Unmute),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"unmute",null),__decorate$k([asyncOperation(PS.MuteAllRemoteParticipants),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"muteAllRemoteParticipants",null),__decorate$k([asyncOperation(PS.MuteIncomingAudio),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"muteIncomingAudio",null),__decorate$k([asyncOperation(PS.UnmuteIncomingAudio),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"unmuteIncomingAudio",null),__decorate$k([asyncOperation(PS.SendDtmf),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[String]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"sendDtmf",null),__decorate$k([asyncOperation(PS.StartVideo),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[LocalVideoStream]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"startVideo",null),__decorate$k([asyncOperation(PS.StopVideo),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[LocalVideoStream]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"stopVideo",null),__decorate$k([asyncOperation(PS.StartAudio),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[LocalAudioStream]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"startAudio",null),__decorate$k([validateEmergencyCallOperation(PS.Hold),asyncOperation(PS.Hold),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"hold",null),__decorate$k([validateEmergencyCallOperation(PS.Resume),asyncOperation(PS.Resume),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"resume",null),__decorate$k([asyncOperation(PS.StartScreenShare),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[LocalVideoStream]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"startScreenSharing",null),__decorate$k([asyncOperation(PS.StopScreenShare),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"stopScreenSharing",null),__decorate$k([asyncOperation(PS.SetConstraints),__metadata$k("design:type",Function),__metadata$k("design:paramtypes",[Object]),__metadata$k("design:returntype",Promise)],CallCommonImpl.prototype,"setConstraints",null);var __decorate$l=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$l=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class CallImpl extends CallCommonImpl{get info(){return this._info}constructor(f,S,v,C,_){super(f,S,v,C,g.CallKind.Call,_),this._info=this.callInfo,this._allowBreakoutRoomJoin=getAcsEcsConfig().calling.breakoutRooms.enabled}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(g,f){let v,C;const _=f,T=f,I=f,b=+new Date,A=generateGuid();if(this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.attempt,participantAddedOrRemoved:"add",correlationId:A,timestampInfo:{attemptTimestamp:b},additionalDetails:{customContext:{userToUserPresent:!!_?.customContext?.userToUser,xHeadersPresent:!!_?.customContext?.xHeaders&&_?.customContext.xHeaders.length>0}}}),this._callAgent.isEnterpriseUser()){this.validateThreadId(g,f);switch(S.getIdentifierKind(g).kind){case"communicationUser":C=_.threadId;break;case"microsoftTeamsUser":C=I.threadId;break;case"phoneNumber":C=T.threadId;break;default:{const g=new CallingCommunicationError({defaultError:D.CALL.ADD_UNKNOWN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:A,timestampInfo:{deltaTimeInMs:+new Date-b},additionalDetails:{code:g.code,failureReason:g.message,...extractCommunicationServicesErrorForTelemetry(g)}}),g}}}let P;T?.alternateCallerId&&(validateIdentifier(T.alternateCallerId),v=getMriFromIdentifier(T.alternateCallerId));try{if(validateCallConnected(PS.AddParticipant,this.state),P=validateIdentifier(g),!isProxyAndCustomTurnAllowed(this.acsProxy,this.acsCustomRelayManager,!1,P))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}catch(g){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:A,timestampInfo:{deltaTimeInMs:+new Date-b},additionalDetails:{code:g.code,failureReason:g.message,...extractCommunicationServicesErrorForTelemetry(g)}}),g}if(this._remoteParticipants.find((f=>getMriFromIdentifier(f.identifier)===getMriFromIdentifier(g)))){const f=new CallingCommunicationError({defaultError:D.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[S.getIdentifierKind(g).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:A,timestampInfo:{deltaTimeInMs:+new Date-b},additionalDetails:{code:f.code,failureReason:f.message,...extractCommunicationServicesErrorForTelemetry(f)}}),f}const R=[...this.remoteParticipants.values()].map((g=>g.identifier));this._isAcsTeamsCall=isAcsTeamParticipantPresentInCall([...R,g],this._callAgent.kind),getAcsEcsConfig().calling.enableSmePassFakeConversation&&this._isAcsTeamsCall&&!C&&(C=this.tsCall.threadId||`${V}${generateGuid()}`);const M=w.generateCauseId();B_.setCauseIdToNetworkInfo(M);const O=this.getOrCreateRemoteParticipant(constructIdentifierKindFromMri(getMriFromIdentifier(g)));return this.tsCall.addParticipant(getMriFromIdentifier(g),{alternateId:v,threadId:C,customHeaderContext:processCustomContext(T)},M).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.success,participantAddedOrRemoved:"add",correlationId:A,timestampInfo:{deltaTimeInMs:+new Date-b},networkInfo:B_.getRemoveCauseIdToNetworkInfo(M)})})).catch((f=>{const{callEndReason:S}=getRemoteParticipantCallEndReason(this,O.tsRemoteParticipant,f);O.callEndReason||O.setCallEndReason(S);const v=extractCallEndReasonForTelemetry(S);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:A,timestampInfo:{deltaTimeInMs:+new Date-b},additionalDetails:{code:v?.callEndReason.code,subCode:v?.callEndReason.subCode,failureReason:v?.callEndReason.message,...v},networkInfo:B_.getRemoveCauseIdToNetworkInfo(M)}),this._remoteParticipants.find((f=>getMriFromIdentifier(f.identifier)===getMriFromIdentifier(g)))&&(this.deleteRemoteParticipant(O),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:[O]}))})),O}async removeParticipant(g,f){const v=+new Date,C=generateGuid();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.attempt,participantAddedOrRemoved:"remove",correlationId:C,timestampInfo:{attemptTimestamp:v}});try{validateCallConnected(PS.RemoveParticipant,this.state),validateIdentifier(g)}catch(g){const f=new CallingCommunicationError({defaultError:D.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:g});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"remove",correlationId:C,timestampInfo:{deltaTimeInMs:+new Date-v},additionalDetails:{code:g.code,failureReason:g.message,...extractCommunicationServicesErrorForTelemetry(f)}}),f}let _=this._remoteParticipants.find((f=>getMriFromIdentifier(f.identifier)===getMriFromIdentifier(g)));if(!_){const f=new CallingCommunicationError({defaultError:D.CALL.PARTICIPANT_NOT_IN_CALL,defaultErrorMessageArgs:[S.getIdentifierKind(g).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"remove",correlationId:C,timestampInfo:{deltaTimeInMs:v-+new Date},additionalDetails:{code:f.code,subCode:f.subCode,failureReason:f.message,...extractCommunicationServicesErrorForTelemetry(f)}}),f}const T=w.generateCauseId();B_.setCauseIdToNetworkInfo(T);try{await this.tsCall.removeParticipant(getMriFromIdentifier(g)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.success,participantAddedOrRemoved:"remove",correlationId:C,timestampInfo:{deltaTimeInMs:v-+new Date},networkInfo:B_.getRemoveCauseIdToNetworkInfo(T)})}catch(g){const f=getRemoteParticipantCallEndReason(this,_.tsRemoteParticipant,g).callEndReason;_.callEndReason||_.setCallEndReason(f);const S=extractCallEndReasonForTelemetry(f);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"remove",correlationId:C,timestampInfo:{deltaTimeInMs:v-+new Date},additionalDetails:{code:S?.callEndReason.code,subCode:S?.callEndReason.subCode,failureReason:S?.callEndReason.message,...S},networkInfo:B_.getRemoveCauseIdToNetworkInfo(T)}),new CallingCommunicationError({defaultError:{message:f.message,code:f.code,subCode:f.subCode||0,resultCategories:f.resultCategories},originalError:g})}}validateThreadId(g,f){if(!f?.threadId)throw new CallingCommunicationError({defaultError:D.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID})}}__decorate$l([syncOperation(PS.AddParticipant),__metadata$l("design:type",Function),__metadata$l("design:paramtypes",[Object,Object]),__metadata$l("design:returntype",Object)],CallImpl.prototype,"addParticipant",null),__decorate$l([asyncOperation(PS.RemoveParticipant),__metadata$l("design:type",Function),__metadata$l("design:paramtypes",[Object,Object]),__metadata$l("design:returntype",Promise)],CallImpl.prototype,"removeParticipant",null);var __decorate$m=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$m=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class IncomingCallCommonImpl{get kind(){return this._kind}get id(){return this._callCommon.id}get callerInfo(){return this._callCommon.callerInfo}get transferorInfo(){return this._callCommon.transferorInfo}get callEndReason(){return this._callCommon.callEndReason}get customContext(){return this._customContext}constructor(g,f){this._callCommon=g,this._eventEmitter=new LE.EventEmitter,this._kind=f,this._callConnected="Connected"===this._callCommon.state,this._customContext=parseCustomContext(this._callCommon.tsCall),this._callCommon.on("stateChanged",(()=>{"Connected"===this._callCommon.state?this._callConnected=!0:"Disconnected"!==this._callCommon.state||this._callConnected||this._eventEmitter.emit("callEnded",{callEndReason:this._callCommon.callEndReason})})),this._callCommon.on("callerInfoChanged",(()=>{this._eventEmitter.emit("callerInfoChanged")})),this._callCommon.on("transferorInfoChanged",(()=>{this._eventEmitter.emit("transferorInfoChanged")}))}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}reject(){return this._callCommon.reject()}}__decorate$m([asyncOperation(),__metadata$m("design:type",Function),__metadata$m("design:paramtypes",[]),__metadata$m("design:returntype",Promise)],IncomingCallCommonImpl.prototype,"reject",null);var __decorate$n=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$n=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class IncomingCallImpl extends IncomingCallCommonImpl{get info(){return this._call.info}constructor(f){super(f,g.IncomingCallKind.IncomingCall),this._call=f}async accept(g){if("microsoftTeamsUser"===this.info?.initiatorKind&&!isProxyAndCustomTurnAllowed(this._call.acsProxy,this._call.acsCustomRelayManager,!0))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._call.accept(g),this._call}}__decorate$n([asyncOperation(PS.Accept),__metadata$n("design:type",Function),__metadata$n("design:paramtypes",[Object]),__metadata$n("design:returntype",Promise)],IncomingCallImpl.prototype,"accept",null);class HttpRequestHelper{constructor(g,f){this.logger=g,this.proxy=f}async sendRequestWithRetry(g,f,S,v,C,_=1,T){if(_>C)throw new Error("Max retry reached");v.timeout||(v.timeout=2e4),v.maxRedirects=0,this.proxy&&(f=this.proxy.proxyfyUrl(f));try{switch(g){case"post":default:return await TI.post(f,S,v);case"get":return await TI.get(f,v);case"put":return await TI.put(f,S,v);case"delete":return await TI.delete(f,v)}}catch(I){let b=I?.response?.status;this.logger.error(`Found error for request ${g} ${f} ${b||""}`);const A=_+1;if(A<=C){let _=f;if(I&&I.response)if(301===I.response.status||302===I.response.status||303===I.response.status||307===I.response.status||404===I.response.status)_=I.response.headers&&I.response.headers.location?I.response.headers.location:_;else if(I.response.status<500)throw I;return this.logger.error(`Retrying, attempt #${A} url=${_}`),await new Promise((g=>setTimeout(g,T))),this.sendRequestWithRetry(g,_,S,v,C,A,T)}throw I}}}const eA={callNotification:"callNotification",conversationInvitation:"conversationInvitation",debugContent:"debugContent",groupContext:"groupContext"};class IncomingCallPushNotificationHandler{get callId(){return this._callId}get localParticipantId(){return this._localParticipantId}constructor(g,f,S){if(this._callId="",this._localParticipantId="",this._logger=S.createChild("IncomingCallPushNotificationHandler"),!g.incomingCallContext)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD_NO_CONTEXT_PROVIDED});if(Object.keys(g).length>1)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_PAYLOAD_TOO_MANY_KEYS});if(this._payload=g,this._incomingCallContext=this._payload.incomingCallContext,this._tsCallRegistry=f,this._gp=JSON.parse(lE.inflate(atob(this._incomingCallContext),{to:"string"})),!(this._gp.hasOwnProperty(eA.callNotification)&&this._gp.hasOwnProperty(eA.conversationInvitation)&&this._gp.hasOwnProperty(eA.debugContent)&&this._gp.hasOwnProperty(eA.groupContext)))throw this._logger.error(`Missing incoming call context data. Found: ${Object.keys(this._gp)}`),new CallingCommunicationError({defaultError:D.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD});this._callId=this._gp.debugContent.callId,this._localParticipantId=this._gp.debugContent.participantId}async process(){try{if(this._tsCallRegistry.calls.some((g=>g.callId==this._callId)))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_ALREADY_PROCESSED});const g=defer$1(),callAddedListener=f=>{const checkNotified=()=>{f.callId===this._callId&&f.participantId===this._localParticipantId&&1===f.state&&g.resolve()};this._tsCallStateSub=f.on("callStateChanged",checkNotified),checkNotified()};this._tsCallRegistrySub=this._tsCallRegistry.on("callAdded",callAddedListener);const f={eventId:Ff,body:{gp:this._gp}};if(!this._tsCallRegistry.incomingCallMessageHandler.handleMessage(f))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_FAILED_TO_PROCESS});setTimeout((()=>{g.isPending()&&g.reject(new CallingCommunicationError({defaultError:D.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_CALL_MISSED}))}),5e3),await g.promise}catch(g){throw g}finally{this._tsCallRegistrySub?.dispose(),this._tsCallStateSub?.dispose()}}}const tA=0,iA=220004,nA=220005,rA=220006,sA=220007;class AcsMiddleTierPolicyService{constructor(g){this._httpRequestHelper=g,this._isPolicyFetchApplicable=!1,this._policySettingData={},this._threadIdData={};const S=f.createClientLogger("ACS");this._logger=new DefaultLogger(S)}initialize(g){this._localParticipant=g.localParticipant,this._jwtTokenProvider=g.jwtTokenProvider,this._telemetryLogManager=g.telemetryLogManager}userDialedNumber(g){this._userDialedPstnNumber=g,this._emergencyNumber=this._userDialedPstnNumber}async CreateChatThreadId(g,f){this._callId=g;const S=+new Date,v=f?.createThreadIdSuffix??getAcsEcsConfig().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix;this.sendMiddleTierApiEvent({eventName:uE.acs_calling_middletier_gateway_api,suffix:v,kindOfEvent:gE.attempt});const C=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),_=new URL(v,getAcsEcsConfig().MiddleTier.baseServiceUrl);f?.participants.push({id:this._localParticipant});const T={Participants:f?.participants};try{const g=await this._httpRequestHelper.sendRequestWithRetry("post",_.toString(),T,{headers:C},getAcsEcsConfig().MiddleTier.maxRetry);return this._logger.info("Successfully created chat thread using ACS MiddleTier Service."),this._threadIdData=g?.data,this.sendMiddleTierApiEvent({eventName:uE.acs_calling_middletier_gateway_api,suffix:v,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-S},additionalDetails:{phrase:"Thread Id was successfully created from ACS MiddleTier Service",code:tA,subCode:rA}}),Promise.resolve(this._threadIdData.threadId)}catch(g){this._logger.error("Error creating thread Id from ACS MiddleTier Service");const f=new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:uE.acs_calling_middletier_gateway_api,suffix:v,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-S},additionalDetails:{failureReason:f.message,code:f.code,subCode:f.subCode,...extractCommunicationServicesErrorForTelemetry(f)}}),f}}async AddParticipantsToThread(g,f){this._callId=g;const S=+new Date,v=f?.addParticipantsSuffix??getAcsEcsConfig().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix;this.sendMiddleTierApiEvent({eventName:uE.acs_calling_middletier_gateway_api,suffix:v,kindOfEvent:gE.attempt});const C=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),_=new URL(v,getAcsEcsConfig().MiddleTier.baseServiceUrl),T={threadId:f?.threadId,Participants:f?.participants};try{const g=await this._httpRequestHelper.sendRequestWithRetry("post",_.toString(),T,{headers:C},getAcsEcsConfig().MiddleTier.maxRetry);this._logger.info("Call to add participants to chat thread using ACS MiddleTier Service");const f=g?.data;if(null!==f){if(!f.isSuccess)throw new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});f.multipleStatus.length>0&&735==f.multipleStatus[0].statusCode&&this._logger.info("Trying to add the same participant to the thread id")}return this.sendMiddleTierApiEvent({eventName:uE.acs_calling_middletier_gateway_api,suffix:v,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-S},additionalDetails:{phrase:"Successfully add participants from ACS MiddleTier Service",code:tA,subCode:sA}}),Promise.resolve(f.isSuccess)}catch(g){this._logger.error("Fail to add participant error from ACS MiddleTier Service");const f=new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:uE.acs_calling_middletier_gateway_api,suffix:v,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-S},additionalDetails:{failureReason:f.message,code:f.code,subCode:f.subCode,...extractCommunicationServicesErrorForTelemetry(f)}}),f}}async fetchUserPoliciesFromAcsMiddleTier(g,f,S){this._policySettingData=await this.requestUserPoliciesFromAcsMiddleTier(g,f,S)}async requestUserPoliciesFromAcsMiddleTier(g,f,S,v){this._callId=g;const C=+new Date;if(this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:gE.attempt},f),!f){const g=new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.TEAMS_USER_ID_NOT_PROVIDED});throw this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-C},additionalDetails:{failureReason:g.message,code:g.code,subCode:g.subCode,...extractCommunicationServicesErrorForTelemetry(g)}}),g}let _,T={},I=getAcsEcsConfig().MiddleTier.baseServiceUrl;S?(_=new URL(S.policyUrlSuffix,I),T={id:f,userPolicies:S.userPolicies,userProperties:S.userProperties}):(_=new URL(getAcsEcsConfig().MiddleTier.policyUrlSuffix,I),T={id:f});const b=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(v);try{const g=await this._httpRequestHelper.sendRequestWithRetry("post",_.toString(),T,{headers:b},getAcsEcsConfig().MiddleTier.maxRetry);return this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-C},additionalDetails:{phrase:"Teams user policy was fetched successfully from ACS MiddleTier Service",code:tA,subCode:iA}},f),g?.data}catch(g){const S=handleFetchPoliciesFromAcsMiddleTierFailure(g,D.CTE_MID_TIER_POLICY_SERVICE.FETCH_POLICY);throw this._logger.error(S.message),this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-C},additionalDetails:{failureReason:S.message,code:S.code,subCode:S.subCode,...extractCommunicationServicesErrorForTelemetry(S)}},f),S}}isEvEnabled(){const g=this._policySettingData?.userAggregatedPolicySettingData?.userProperties;return g?.evEnabled||!1}isMoHEnabled(){const g=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsCallingPolicy,f=g?.musicOnHoldEnabledType;return this._logger.info("Checking Music on Hold Policy, Enabled Type is: "+f),f===(GS.Enabled||GS.UserOverride)}isBreakoutRoomsAllowed(){const g=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy;let f=g?.allowBreakoutRooms;return this._logger.info("Allow Breakout rooms from Teams meeting policy is "+f),null==f&&(f=!0),f}isIPAudioAllowed(){if(!getAcsEcsConfig().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info("Allow IP audio is true as feature flag ipAudioVideoPolicyEnabled is false"),!0;const g=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy,f=g?.ipAudioMode!==WS.Disabled;return this._logger.info("Allow IP audio from Teams meeting policy is "+f),f}isIPVideoAllowed(){if(!getAcsEcsConfig().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info("Allow IP video is true as feature flag ipAudioVideoPolicyEnabled is false"),!0;const g=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy,f=g?.ipVideoMode!==WS.Disabled;return this._logger.info("Allow IP video from Teams meeting policy is "+f),f}getTeamsUserCaptionsPoliciesData(){const g=+new Date;let f="";this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:gE.attempt});const S=this._policySettingData.userAggregatedPolicySettingData,v=S?.userPolicies,C=S?.userProperties;if(!v?.teamsCallingPolicy){const f=new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_CALLINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-g},additionalDetails:{failureReason:f.message,code:f.code,subCode:f.subCode,...extractCommunicationServicesErrorForTelemetry(f)}})}if(!v?.teamsMeetingPolicy){const f=new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_MEETINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-g},additionalDetails:{failureReason:f.message,code:f.code,subCode:f.subCode,...extractCommunicationServicesErrorForTelemetry(f)}})}if(!C?.featureTypes){const f=new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_FEATURETYPE_TEAMSPROMGMT_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-g},additionalDetails:{failureReason:f.message,code:f.code,subCode:f.subCode,...extractCommunicationServicesErrorForTelemetry(f)}})}return(v?.teamsCallingPolicy||v?.teamsMeetingPolicy||C?.featureTypes?.includes(SS.TeamsProMgmt))&&(f=JSON.stringify({isLiveCaptionsEnabledForCalling:v?.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling===vS.DisabledUserOverride,isLiveCaptionsEnabledForMeeting:v?.teamsMeetingPolicy?.liveCaptionsEnabledType===vS.DisabledUserOverride,isTeamsProMgmtSkuAvailable:C?.featureTypes?.includes(SS.TeamsProMgmt)??!1}),this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-g},additionalDetails:{phrase:"Fetching Captions policy from ACS MiddleTier Service response was successful",code:tA}}),this._logger.info(`Fetching user's captions policy content = ${f}`)),f}getEmergencyContent(){const g=+new Date;this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_emergency_content,kindOfEvent:gE.attempt});let f="";try{const S=this._policySettingData.userAggregatedPolicySettingData,v=S?.userPolicies;let C=!1,_="";if(v?.locationPolicy?.emergencyNumbers){const g=v.locationPolicy.emergencyNumbers||[];this.isPhoneNumberInLocationPolicy(g)&&(C=!0,f=JSON.stringify({enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:S?.userProperties.region,locationPolicyTag:v?.locationPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:v?.teamsEmergencyCallingPolicy?.policyDocument}),_="LocationPolicy")}if(!C&&v?.teamsEmergencyCallRoutingPolicy){const g=v?.teamsEmergencyCallRoutingPolicy?.emergencyNumbers||[];this.isPhoneNumberInTeamsEmergenencyRoutingPolicy(g)&&(C=!0,f=JSON.stringify({enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:S?.userProperties.region,teamsEmergencyCallRoutingPolicyTag:v?.teamsEmergencyCallRoutingPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:v?.teamsEmergencyCallingPolicy?.policyDocument}),_="TeamsEmergencyCallingRoutingPolicy")}const T=C?`Created Emergency policy using ${_}`:"This is NOT an emergency call";return this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_emergency_content,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:(new Date).getTime()-g},additionalDetails:{phrase:"Deriving Emergency policy from ACS MiddleTier Service response was successful",code:tA,subCode:nA}}),this._logger.info(`Deriving emergency policy message = ${T}. Emergency Content = ${f}`),f}catch(f){const S=new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.DERIVE_EMERGENCY_POLICY,originalError:f});throw this.sendMiddleTierPolicyEvent({eventName:uE.acs_calling_middletier_gateway_emergency_content,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:(new Date).getTime()-g},additionalDetails:{failureReason:S.message,code:S.code,subCode:S.subCode,...extractCommunicationServicesErrorForTelemetry(S)}}),S}}isFetchUserPoliciesAndSettingsApplicable(g,f){return isNullOrUndefined$1(g)||isNullOrUndefined$1(f)||(this._isPolicyFetchApplicable=this.verifyFetchUserPoliciesSettings(g,f)),this._isPolicyFetchApplicable}getEmergencyNumber(){return this._emergencyNumber}getUserDialedPstnNumber(){return this._userDialedPstnNumber}getUserPolicy(){return this._policySettingData.userAggregatedPolicySettingData?.userPolicies}getUserProperties(){return this._policySettingData.userAggregatedPolicySettingData?.userProperties}isPhoneNumberInLocationPolicy(g){if(!isNullOrUndefined$1(g))for(const f of g)if(f.dialString===this._userDialedPstnNumber||!isNullOrUndefined$1(f.dialMask?.split(";").find((g=>g===this._userDialedPstnNumber))))return this._emergencyNumber=f.dialString,!0;return!1}isPhoneNumberInTeamsEmergenencyRoutingPolicy(g){if(!isNullOrUndefined$1(g))for(const f of g)if(f.emergencyDialString===this._userDialedPstnNumber||!isNullOrUndefined$1(f.emergencyDialMask?.split(";").find((g=>g===this._userDialedPstnNumber))))return this._emergencyNumber=f.emergencyDialString,!0;return!1}verifyFetchUserPoliciesSettings(g,f){const v=getAcsEcsConfig().MiddleTier;return v.enabled?v.userPolicySettingsApi?g?Array.isArray(f)&&(f.length>1||!S.isPhoneNumberIdentifier(f[0]))?(this._logger.info("Target particpant (Callee) is not a PSTN Number"),!1):Array.isArray(f)||S.isPhoneNumberIdentifier(f)?(this._logger.info("Teams user is eligible to fetch policies and settings from MiddleTier Service "),!0):(this._logger.info("Target particpant (Callee) is not a PSTN Number"),!1):(this._logger.info("Originator (Caller) is not a Teams User"),!1):(this._logger.info("ACS MiddleTier Policy API is disabled"),v.userPolicySettingsApi):(this._logger.info("ACS MiddleTier service is disabled"),v.enabled)}isSecurityDeskEnabled(){const g=this._policySettingData.userAggregatedPolicySettingData?.userPolicies?.teamsEmergencyCallingPolicy;return!(isNullOrUndefined$1(g?.notificationGroup)&&isNullOrUndefined$1(g?.notificationDialOutNumber)||0==g?.notificationGroup?.trim().length&&0==g?.notificationDialOutNumber?.trim().length)}async getAcsMiddletierServiceRequestHeader(){return{"Content-Type":"application/json","X-Skypetoken":this._jwtTokenProvider?await this._jwtTokenProvider():"","Access-Control-Allow-Origin":"*","X-Microsoft-Skype-Chain-ID":this._callId}}async getAcsMiddletierServiceRequestHeaderForThreadApi(g){let f={};return f=await this.getAcsMiddletierServiceRequestHeader(),f.onbehalfOfUser=g??this._localParticipant,f}sendMiddleTierPolicyEvent(g,f){try{this.setDefaultEventData(g,f),this._telemetryLogManager?.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this._logger.debug("Unable to send AcsMiddleTierPolicyService telemetry")}}sendMiddleTierApiEvent(g){try{this.setDefaultEventData(g),this._telemetryLogManager?.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this._logger.debug("Unable to send MiddleTier Api telemetry")}}setDefaultEventData(g,f){g.callId=this._callId,g.localParticipantId=this._localParticipant,g.requestedParticipantMRI=f??this._localParticipant,g.timestampInfo=g.timestampInfo??"",g.additionalDetails=g.additionalDetails??""}}class HardwareInfo{constructor(g){this._logger=g}get gpu(){const g={};try{const f=document.createElement("canvas"),S=f.getContext("webgl")||f.getContext("experimental-webgl");if(S){const f=S.getExtension("WEBGL_debug_renderer_info");f?(g.vendor=S.getParameter(f.UNMASKED_VENDOR_WEBGL),g.renderer=S.getParameter(f.UNMASKED_RENDERER_WEBGL)):this._logger?.info("Unable to get GPU info: debug renderer info is not supported")}else this._logger?.info("Unable to get GPU info: WebGL is not supported")}catch(g){this._logger?.info(`Unable to get GPU info: ${g}`)}return g}get hardwareConcurrency(){return navigator.hardwareConcurrency}}var aA;!function(g){g.deviceSelection="deviceSelection",g.handleIncomingCall="handleIncomingCall"}(aA||(aA={}));var oA,__decorate$o=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$o=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};let lA=1;class CallAgentCommonImpl{get kind(){return this._kind}get connectionState(){return this._connectionState}constructor(g,f,S,v,C,_,T){this._callClient=g,this._pushHandlingDeltaTimeInMs=new Map,this._disposed=!1,this.tokenProvider=async g=>{const f=+new Date;let S;try{if(this.sendTokenChangedEvent({kindOfEvent:"attempt",timestampInfo:{attemptTimestamp:f},oldTokenExpiration:this._oldTokenExpiration}),!this._communicationTokenCredential)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.GET_TOKEN_BEFORE_INIT});S=await parseTokenCredential(this._communicationTokenCredential,getAcsEcsConfig().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),S.acsResourceId===this._parsedTokenCredential?.acsResourceId&&S.identityMri===this._parsedTokenCredential?.identityMri||logErrorAndThrow(D.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this.logger),g?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNmberOfRetries&&(this.updateConnectionState("invalidToken"),this._disposed||await this.dispose(),logErrorAndThrow(D.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this.logger));const v=+new Date;return this.sendTokenChangedEvent({kindOfEvent:"success",timestampInfo:{deltaTimeInMs:v-f},oldTokenExpiration:this._oldTokenExpiration,newTokenExpiration:S.exp,isTokenChanged:this._oldToken!==S.jwtToken}),this._oldToken=S.jwtToken,this._oldTokenExpiration=S.exp,S.jwtToken}catch(g){const v={kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-f},oldTokenExpiration:this._oldTokenExpiration};throw S&&(v.newTokenExpiration=S.exp,v.isTokenChanged=this._oldToken!==S.jwtToken,this._oldToken=S.jwtToken,this._oldTokenExpiration=S.exp),this.sendTokenChangedEvent(v,g),g}},this.sendTokenChangedEvent=(g,f)=>{try{let S={kindOfEvent:g.kindOfEvent,timestampInfo:g.timestampInfo,oldTokenExpiration:g.oldTokenExpiration};void 0!==g.newTokenExpiration&&(S.newTokenExpiration=g.newTokenExpiration),void 0!==g.isTokenChanged&&(S.isTokenChanged=g.isTokenChanged),f&&(S={...S,...extractCommunicationServicesErrorForTelemetry(f)}),this._telemetryLogManager.sendEvent({name:uE.acs_calling_token_expiration_changed,tenant:tf,properties:S})}catch(g){this.logger.debug("Unable to send token change telemetry")}},this.pushHandlingStarted=g=>{const f=generateGuid();this._pushHandlingDeltaTimeInMs.set(g,{correlationId:f,timestamp:+new Date}),this.logger.log("Incoming call state started",g),B_.setCauseIdToNetworkInfo(g),this.sendIncomingNotificationEvent({eventName:uE.acs_calling_client_operations,operation:aA.handleIncomingCall,networkInfo:[],kindOfEvent:"attempt",timestampInfo:{deltaTimeInMs:void 0},correlationId:f,additionalDetails:{},callId:"",participantId:""})},this.pushHandlingEnded=(g,f)=>{const S=void 0!==f?.code&&[0,200].includes(f?.code),convertIncomingCallHandlingErrorToCallingCommunicationError=g=>{if(S)return new CallingCommunicationError({defaultError:{code:g?.code??0,subCode:g?.subCode??0,message:"Success",resultCategories:["Success"]}});const f=[D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_INVALID_NOTIFICATION_PAYLOAD,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_EXTRACT_PAYLOAD,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_HANDLED,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_IGNORING_DUPLICATE_NOTIFICATION,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_HANDLE_NOTIFICATION_FOR_GROUPID_CALL,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_PAYLOAD,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_SUCCEEDED,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_FAILED,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_EVENT_TYPE,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_EXISTS,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CANNOT_CONNECT,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_NO_SIGNALING,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CONFLICT,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_PUSH_IGNORED,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_ANSWERED_ELSEWHERE,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CALL_ALREADY_ENDED,D.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_IN_PROGRESS],v=M.find(f,(f=>f.subCode===g?.subCode))??D.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA;return new CallingCommunicationError({defaultError:v})};this.logger.log("Incoming call state ended",g,f);const v=B_.getRemoveCauseIdToNetworkInfo(g),C=this._pushHandlingDeltaTimeInMs.get(g)?.correlationId||"unknown",_=convertIncomingCallHandlingErrorToCallingCommunicationError(f);this.sendIncomingNotificationEvent({eventName:uE.acs_calling_client_operations,operation:aA.handleIncomingCall,networkInfo:v||[],kindOfEvent:S?"success":"failure",timestampInfo:{deltaTimeInMs:this._pushHandlingDeltaTimeInMs.has(g)?+new Date-this._pushHandlingDeltaTimeInMs.get(g)?.timestamp:void 0},correlationId:C,additionalDetails:{...extractCommunicationServicesErrorForTelemetry(_)},callId:f.callId||"",participantId:f.participantId||""}),this._pushHandlingDeltaTimeInMs.delete(g),this._eventEmitter.emit("handleIncomingCall",{callId:f.callId||"",participantId:f.participantId||"",...extractCallEndReasonForTelemetry({code:_.code,subCode:_.subCode,message:_.message,resultCategories:_.resultCategories})})},this.logger=f.createChild("CallAgent"+lA++),this._telemetryLogManager=v,this._kind=_,this._connectionState="Disconnected",this._eventEmitter=new CallingEventEmitter(this.logger),this._internalEventEmitter=new LE.EventEmitter,this.clientId=S,this._abortController=new AbortController,this._maxDisplayNameLength=getAcsEcsConfig()?.calling?.maxDisplayNameLength||Of,this._oldToken="",this._oldTokenExpiration=0,this._tokenFetchTries=0,this._maxNmberOfRetries=getAcsEcsConfig()?.calling?.maxNumberOfTokenFetchRetries||Cf,this._callStack=C,this.acsProxy=this._callClient.acsProxy,this.acsCustomRelayManager=this._callClient.acsCustomRelayManager,this._httpRequestHelper=new HttpRequestHelper(this.logger,this.acsProxy),this.mtPolicyService=new AcsMiddleTierPolicyService(this._httpRequestHelper),this._parsedTokenCredential={jwtToken:"",acsResourceId:void 0,identityMri:"",cloudType:tm.Public,isEnterpriseUser:!1,mriType:void 0,region:"",rgnClaimExists:!1,exp:0},this._caConfigBag={clientId:"",acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?lm.Enterprise:lm.Consumer,region:this._parsedTokenCredential.region,emergencyCountryCode:void 0,IsUserEmergencyCountryCode:!1,mriType:this._parsedTokenCredential.mriType},this.deviceManager=T,this._extensibleApi=new ExtensibleFeatureImpl(this.logger,{callClient:this._callClient,callAgent:this},{tsStack:this.tsStack,callAgent:this,telemetryLogManager:this._telemetryLogManager});const I=getRegisteredFeatures(UE.CallAgentFeature);for(const g of I)"OnExtendedObjectConstructor"===g.activationOptions.activationEvent&&this.feature(g);this._trouterStateChangeCallback=g=>{this.logger.log(`Callback Trouter state changed to ${g}`),this.updateConnectionState("trouterChanged")},this._registrarStateChangeCallback=g=>{this.logger.log(`Callback Registrar state changed to ${g}`),this.updateConnectionState("registrarChanged")}}getHttpRequestHelper(){return this._httpRequestHelper}getTrouterState(){return this._callStack?this._callStack.getTrouterState():"Unknown"}onTrouterStateChanged(g){return this._callStack.onTrouterStateChanged(g)}offTrouterStateChanged(g){return this._callStack.offTrouterStateChanged(g)}onDisposed(g){this._internalEventEmitter.on("disposed",g)}getAcsResourceId(){return this._parsedTokenCredential?.acsResourceId||""}getUserMri(){return`8:${this._parsedTokenCredential?.identityMri}`||""}getUserPolicy(){return this._userPolicies}getUserProperties(){return this._userProperties}async initialize(f,S){const v=+new Date,C=new HardwareInfo(this.logger),_={gpu:C.gpu,hardwareConcurrency:C.hardwareConcurrency};try{if(this.sendCallAgentInitializiedEvent(uE.acs_calling_call_agent_init_attempt,{attemptTimestamp:v},_),this._communicationTokenCredential=f,this._parsedTokenCredential=await parseTokenCredential(f,getAcsEcsConfig().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._kind!==g.CallAgentKind.TeamsCallAgent||this._parsedTokenCredential.isEnterpriseUser?this._kind===g.CallAgentKind.CallAgent&&this._parsedTokenCredential.isEnterpriseUser&&logErrorAndThrow(D.CALL_AGENT.ACS_CALLAGENT_TOKEN_ONLY,this.logger):logErrorAndThrow(D.CALL_AGENT.TEAMS_CALLAGENT_TOKEN_ONLY,this.logger),S?.displayName){if(this._parsedTokenCredential.isEnterpriseUser)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.ENTERPRISE_DISPLAY_NAME});if(S?.displayName.length>this._maxDisplayNameLength)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.DISPLAY_NAME_TOO_LONG})}if(this._parsedTokenCredential.cloudType===tm.Public&&(!this._parsedTokenCredential.region||""===this._parsedTokenCredential.region)){try{const g=+new Date-v;this._telemetryLogManager.sendEvent({name:uE.acs_calling_token_has_no_data_location,tenant:tf,properties:{deltaTimeInMs:g}})}catch(g){this.logger.debug("Unable to send token has no data location assigned")}this._parsedTokenCredential.region=this._parsedTokenCredential.rgnClaimExists?hm[0]:dm[0],this.logger.info("Used default data location because token has no data location assigned")}this._caConfigBag={clientId:this.clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?lm.Enterprise:lm.Consumer,emergencyCountryCode:S?.emergencyCallOptions?.countryCode,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!!S?.emergencyCallOptions?.countryCode,mriType:this._parsedTokenCredential.mriType},this.addToCallAgentsMap(this._parsedTokenCredential),this._disposed=!1;try{this.runningEnvironmentInfo=await this._callClient.getEnvironmentInfoInternal()}catch(g){this.logger.debug("Unable to get the running environment info")}if(this.tsStack=await this._callStack.initializeStackForUser(this.tokenProvider,this._caConfigBag),this._parsedTokenCredential.rgnClaimExists)try{await this.updateParsedTokenCredentials(f)}catch(g){this.logger.debug(`Failed to update parsed token credentials. Error message = ${g?.message||""}`)}await this.setUserPoliciesOnAgentInitialization(),this.isEnterpriseUser()&&(S={...S,displayName:this._userProperties?.displayName??void 0}),this._telemetryLogManager.initialize(this._caConfigBag),this._tsCallRegistry=await this.initializeCallRegistry(this.tsStack,S),this.registerConnectionStateEventHandlers();const C=+new Date;this.sendCallAgentInitializiedEvent(uE.acs_calling_call_agent_init_success,{deltaTimeInMs:C-v},_)}catch(g){this._caConfigBag&&!this._telemetryLogManager.isInitialized()&&this._telemetryLogManager.initialize(this._caConfigBag);const f=new CallingCommunicationError({defaultError:D.CALL_AGENT.INIT_FAIL,originalError:g});this.removeFromCallAgentsMap(this._parsedTokenCredential);const S=+new Date;throw this.sendCallAgentInitializiedEvent(uE.acs_calling_call_agent_init_failure,{deltaTimeInMs:S-v},_,f),this._telemetryLogManager.clearTelemetryLoggers(),f}}async setUserPoliciesOnAgentInitialization(){this.mtPolicyService.initialize({localParticipant:this.getUserMri(),jwtTokenProvider:this.tokenProvider,telemetryLogManager:this._telemetryLogManager})}isEnterpriseUser(){return void 0!==this._parsedTokenCredential?.isEnterpriseUser&&this._parsedTokenCredential?.isEnterpriseUser}isTeamsMultipersonaUser(){return void 0!==this._parsedTokenCredential?.mriType&&this._parsedTokenCredential?.mriType==cm.TeamsMultiPersona}getClientId(){return this.clientId}getCallByCallId(g,f){return f?this._tsCallRegistry.getCall(g,f):this._tsCallRegistry.calls.filter((f=>f.callId===g))?.[0]}async createTransferTargetCall(g){const f=w.generateCauseId(),S=generateGuid(),v=generateGuid(),C=await this._tsCallRegistry.createCallAsync({callId:S,localParticipantId:v,causeId:f,type:"ThreadId",threadId:""}),_=this.createNewCall(S,C);return this.addToCallArray(_),this.handleCallState(_),C.addParticipant(g.targetMri).catch((()=>{this.logger.error("Failed to add participant for transer call")})),_.bindTsCall(),this._eventEmitter.emit("callsUpdated",{added:[_],removed:[]}),_}async subscribeCallWithoutModality(g){const f=w.generateCauseId(),S=await this._tsCallRegistry.createCallAsync({callId:g.callId,localParticipantId:g.participantId,causeId:f,type:"ThreadId",threadId:g.threadId,messageId:g.messageId}),v=this.createNewCall(g.callId,S),C={conversationUrl:g.meetingUrl,conversationId:g.callId},_={};return this.addToCallArray(v),this.handleCallState(v),S.joinCallWithoutCallModality(C,_,f).then((()=>{this.logger.info("Successfully joined call without modalities")})).catch((g=>{throw this.logger.error("Error while joining call without modalities",g),new CallingCommunicationError({defaultError:D.CALL_AGENT.INVALID_JOIN_LOCATOR,originalError:g})})),v.bindTsCall(),v}getEcsConfigIds(){return this._callStack.getEcsConfigIds()}feature(g){return this._extensibleApi.getApiObjectInstance(g.callAgentApiCtor)}async handlePushNotification(g){const f=generateGuid(),S=+new Date;let v;try{if(this.sendHandlePushNotificationEvent({eventName:uE.acs_calling_handle_push_notification,correlationId:f,featureName:"handlePushNotification",operationName:"handleIncomingCallPushNotification",callId:"",localParticipantId:"",kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),!g.incomingCallContext)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA});v=new IncomingCallPushNotificationHandler(g,this._tsCallRegistry,this.logger),await v.process(),this.sendHandlePushNotificationEvent({eventName:uE.acs_calling_handle_push_notification,correlationId:f,featureName:"handlePushNotification",operationName:"handleIncomingCallPushNotification",callId:v.callId,localParticipantId:v.localParticipantId,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:+new Date-S},additionalDetails:""})}catch(g){const C=new CallingCommunicationError({defaultError:D.CALL_AGENT.PUSH_NOTIFICATION_FAIL,originalError:g});throw this.sendHandlePushNotificationEvent({eventName:uE.acs_calling_handle_push_notification,correlationId:f,featureName:"handlePushNotification",operationName:"handleIncomingCallPushNotification",callId:v?.callId||"",localParticipantId:v?.localParticipantId||"",kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-S},additionalDetails:{failureReason:C.message,code:C.code,...extractCommunicationServicesErrorForTelemetry(C)}}),C}}getDeviceType(){const g=this._callClient?.firstPartyOptions?.acsDeviceType;return g?dS[g]:"default"}isWatermarkSupported(){return this.isEnterpriseUser()?getAcsEcsConfig().calling.watermark.watermarkEnabledForCteUsers:getAcsEcsConfig().calling.watermark.watermarkEnabledForAcsUsers}trackCallEndTimeToStopTelemetry(g){0===g.length?TelemetryLogManager.callEndTimestamp=Date.now():TelemetryLogManager.callEndTimestamp=Number.MAX_SAFE_INTEGER}updateConnectionState(g){const f=this.getCallAgentConnectionState(),S=this.getTrouterState(),v=this._callStack?.isRegistered()?"Connected":"Disconnected",C="Connected"===f?void 0:"invalidToken"==g?"invalidToken":"connectionIssue";if(this.sendCallAgentInfoEvent({eventName:uE.acs_calling_call_agent,additionalDetails:{step:"connectionState-changed",oldState:this._connectionState,newState:f,trouterState:S,registrarState:v,reason:C,connectionStateSource:g}}),f!==this._connectionState||C!==this._connectionStateReason){const g={oldValue:this._connectionState,newValue:f,reason:C};this._connectionState=f,this._connectionStateReason=C,this._eventEmitter.emit("connectionStateChanged",g)}}sendCallAgentInfoEvent(g){try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:{...g.additionalDetails}})}catch(g){this.logger.debug("Failed to send connection state changed event",g)}}sendCallAgentInitializiedEvent(g,f,S,v){try{let C="string"==typeof v?.message?v?.message:void 0;g!==uE.acs_calling_call_agent_init_failure&&(C=void 0);const _=v?extractCommunicationServicesErrorForTelemetry(v):void 0,T=this.getEcsConfigIds();this._telemetryLogManager.sendEvent({name:g,tenant:tf,properties:{...f,isSupportedEnvironment:this.runningEnvironmentInfo?.isSupportedEnvironment,failureReason:C,additionalProperties:{AcsCallingSDKWeb_ecsConfigIds:T.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigIds:T.SkypeWebMedia},additionalInformation:{trouterState:this.getTrouterState(),hardwareInfo:S},additionalDetails:{..._,firstPartyOptions:{isDeviceTypeEnabled:getAcsEcsConfig().calling.setDeviceType,deviceTypeRawStrlen:this._callClient?.firstPartyOptions?.acsDeviceType?.length,deviceType:this.getDeviceType()},aadPftClaimExists:this._parsedTokenCredential.aadpftClaimExists}}})}catch(g){this.logger.debug("Unable to send telemtery")}}sendHandlePushNotificationEvent(g){try{this._telemetryLogManager?.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this.logger.debug("Unable to send handle push notification telemetry")}}async initializeCallRegistry(g,f){const S=f?.displayName,v=await this.getCallRegistry(g,this._parsedTokenCredential,this.tokenProvider,S);return this.logger.info(`registry created for version number=${getSdkVersion()}`),v}async getCallRegistry(g,f,S,v){const C={id:f.identityMri,displayName:v||"",tokenProvider:S},_=await g.createCallRegistry(C);await _.login(C);const T=getAcsEcsConfig()?.tsCalling?.accountConfiguration?.ring||void 0,I=f.isEnterpriseUser?lm.Enterprise:lm.Consumer,b=f.acsResourceId,A=f.region;let P={acsResourceId:b,clientType:I,ring:T};if(getAcsEcsConfig().calling.setDeviceType)P.deviceType=this.getDeviceType();else if(this._callClient.firstPartyOptions?.acsDeviceType)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.SET_DEVICE_TYPE_NOT_ALLOWED});const R=getAcsEcsConfig().calling.eudb;return R.isEnabled&&R.sendRegionToNgc&&(R.isRgnClaimEnabledForACS||f.isEnterpriseUser)&&(P={...P,region:A}),getAcsEcsConfig()?.calling.supportLiveStreaming&&(P.clientSupportsUms=!0),P.clientSupportsWatermark=this.isWatermarkSupported(),await _.setConfiguration(P),_.on("callAdded",this.handleCallAdded),_.on("callRemoved",this.handleCallRemoved),_.on("pushHandlingStarted",this.pushHandlingStarted),_.on("pushHandlingEnded",this.pushHandlingEnded),v&&await _.updateDisplayName(v),_}async updateParsedTokenCredentials(g){this._parsedTokenCredential=await parseTokenCredential(g,getAcsEcsConfig().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._caConfigBag.region=this._parsedTokenCredential.region}registerConnectionStateEventHandlers(){this._callStack.onRegisteredChanged(this._registrarStateChangeCallback),this.onTrouterStateChanged(this._trouterStateChangeCallback)}getCallAgentConnectionState(){return this._callStack?.isRegistered()&&"Connected"===this.getTrouterState()?"Connected":"Disconnected"}sendIncomingNotificationEvent(g){try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this.logger.debug("Unable to send incoming call notification telemetry")}}}__decorate$o([loggerProperty,__metadata$o("design:type",Object)],CallAgentCommonImpl.prototype,"logger",void 0),__decorate$o([asyncOperation(AS.Initialize),__metadata$o("design:type",Function),__metadata$o("design:paramtypes",[Object,Object]),__metadata$o("design:returntype",Promise)],CallAgentCommonImpl.prototype,"initialize",null),__decorate$o([syncOperation(AS.Feature),__metadata$o("design:type",Function),__metadata$o("design:paramtypes",[Object]),__metadata$o("design:returntype","function"==typeof(oA="undefined"!=typeof TFeature&&TFeature)?oA:Object)],CallAgentCommonImpl.prototype,"feature",null),__decorate$o([asyncOperation(AS.HandlePushNotification),__metadata$o("design:type",Function),__metadata$o("design:paramtypes",[Object]),__metadata$o("design:returntype",Promise)],CallAgentCommonImpl.prototype,"handlePushNotification",null);var __decorate$p=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$p=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class CallAgentImpl extends CallAgentCommonImpl{get calls(){return this._calls}constructor(f,S,v,C,_,T,I){super(f,S,C,_,v,g.CallAgentKind.CallAgent,T),this._calls=[],this.handleCallRemoved=g=>{this.logger.info(`removing callId=${g.callId}`);const f=this._calls.find((f=>f.id===g.callId));if(f){if(f.isBreakoutRoomCall){const g=getAcsEcsConfig().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(f)}),g)}else this.disposeCall(f);this._eventEmitter.emit("callsUpdated",{added:[],removed:[f]}),this.logger.info("call removed")}},this.handleCallAdded=g=>{if(!this._calls.find((f=>f.id===g.callId))){const f=g.on("callStateChanged",(()=>{if(1===g.state){const S=g.callId;f.dispose();const v=new CallImpl({callId:S,isIncoming:!0},this,g,this._telemetryLogManager),C=new IncomingCallImpl(v);this.handleCallState(v),v.bindTsCall(),this._eventEmitter.emit("incomingCall",{incomingCall:C})}}))}},this.handleCallState=g=>{g.on("stateChanged",(async()=>{try{if("Disconnected"===g.state){this.tsStack?(await(this._tsCallRegistry.deleteCallAsync?.(g.tsCall))||this.logger.error(`Failed to remove call from registry, call id: ${g.id}`),g.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(g.id).catch((()=>{this.logger.error("Failed to flush telemetry log manager events")}))):this.logger.info("Unable to remove call from registry")}else"Connecting"===g.state&&"Incoming"==g.direction&&(this.addToCallArray(g),this._eventEmitter.emit("callsUpdated",{added:[g],removed:[]}))}catch(g){this.logger.error("Failed to handle call state changed event")}}))},this.displayName=I?.displayName}addToCallAgentsMap(g){CallAgentImpl.callAgents.get(g?.identityMri)&&logErrorAndThrow(D.CALL_AGENT.ACS_CALLAGENT_ALREADY_EXSISTS,this.logger),CallAgentImpl.callAgents.set(g?.identityMri,this)}removeFromCallAgentsMap(g){g?.identityMri&&CallAgentImpl.callAgents.get(g?.identityMri)===this&&CallAgentImpl.callAgents.delete(g?.identityMri)}disposeCall(g){const f=this._calls.indexOf(g);-1!==f&&this._calls.splice(f,1),g.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}async getExistingCallAgentWithToken(g){try{const f=await parseTokenCredential(g,getAcsEcsConfig().calling.eudb.isRgnClaimEnabledForACS);return CallAgentImpl.callAgents.get(f.identityMri)}catch(g){throw new CallingCommunicationError({defaultError:D.CALL_AGENT.PARSE_ACCESSTOKEN,originalError:g})}}createNewCall(g,f){return new CallImpl({callId:g},this,f,this._telemetryLogManager)}addToCallArray(g){this._calls.push(g),this.trackCallEndTimeToStopTelemetry(this._calls)}startCall(g,f){const S=generateGuid(),v=+new Date,C={correlationId:S,timestampInfo:{attemptTimestamp:v}};this._telemetryLogManager.sendEvent({name:uE.acs_calling_call_attempt,tenant:tf,properties:C},void 0,"attempt");try{if(this.assertCallUserIds(g),f?.alternateCallerId&&validateIdentifier(f.alternateCallerId),g.find((g=>getMriFromIdentifier(g)===this.getUserMri())))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.CANT_CALL_YOURSELF});let C=f?.audioOptions?.muted;return void 0===C&&(C=!1),this.logger.info(`startCall with video=${!!f?.videoOptions},muted=${C}`),this.createCall({participants:g,startCallOptions:f},{correlationId:S,attemptTimestamp:v})}catch(g){let f,C;throw g instanceof CallingCommunicationError&&(f="string"==typeof g?.message?g?.message:void 0,C={...extractCommunicationServicesErrorForTelemetry(g)}),this._telemetryLogManager.sendEvent({name:uE.acs_calling_call_failed,tenant:tf,properties:{correlationId:S,timestampInfo:{deltaTimeInMs:+new Date-v},failureReason:f||"",additionalDetails:C||{}}},void 0,"failure"),g}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(S)}}join(g,f){if(!isProxyAndCustomTurnAllowed(this.acsProxy,this.acsCustomRelayManager,!1,void 0,g))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});this.assertCallContext(g);let S=f?.audioOptions?.muted;return void 0===S&&(S=!1),this.logger.info(`join with video=${!!f?.videoOptions},muted=${S}`),this.createCall({callContext:g,startCallOptions:f})}async dispose(){if(this._disposed)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.ACS_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&CallAgentImpl.callAgents.delete(this._parsedTokenCredential?.identityMri);try{const g=this._tokenFetchTries>this._maxNmberOfRetries;await(this._callStack?.dispose(g))}catch(g){this.logger.error("Call Agent failed to dispose to Call Stack")}this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),delete this._callStack,this._telemetryLogManager.clearTelemetryLoggers(),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit("disposed"),this._internalEventEmitter.removeAllListeners()}on(g,f){if("handleIncomingCall"!==g&&"incomingCall"!==g&&"callsUpdated"!==g&&"connectionStateChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("handleIncomingCall"!==g&&"incomingCall"!==g&&"callsUpdated"!==g&&"connectionStateChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}createCall(g,f){if(g?.startCallOptions?.firstPartyOptions?.isImmersiveMode&&"meshV2"!==this.getDeviceType())throw new CallingCommunicationError({defaultError:D.CALL_AGENT.MESH_DEVICETYPE_V2});let S,v,C,_=g?.callContext?.threadId||g?.startCallOptions?.threadId,T=!1,I=g?.callContext?.groupId;const b=g?.callContext?.roomId,A=g?.callContext?.meetingLink,P=g?.callContext?.meetingId,R=g?.callContext?.passcode||"";if(I&&I.startsWith("19:")&&(_=I,I=""),A)if(isLongMeetingUrl(A))v=parseLongMeetingLink(A);else{if(!isShortMeetingUrl(A,this.logger))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INVALID_MEETING_LINK});if(isTflMeetingLink(A.trim().toLocaleLowerCase(),getAcsEcsConfig().calling.tfl.hosts)&&!getAcsEcsConfig().calling.tfl.isEnabled)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});T=!0}if(g?.callContext?.threadId&&g?.callContext?.organizerId&&g?.callContext?.tenantId&&(v={threadId:g?.callContext?.threadId,messageId:g?.callContext?.messageId?g?.callContext?.messageId.toString():"0",organizerId:g?.callContext?.organizerId,tenantId:g?.callContext?.tenantId}),v&&(C={meetingType:"0"===v.messageId?1:2,tenantId:v.tenantId,organizerId:v.organizerId,replyChainMessageId:v.messageId}||void 0,_=v.threadId,S=v.messageId),this.tsStack){const v=w.generateCauseId(),M=generateGuid(),O=generateGuid();let D,N=!1;I?D=this._tsCallRegistry.createCallWithGroupId(I,M,O,v):P?D=this._tsCallRegistry.createCallWithMeetingData({meetingCode:P,passcode:R,threadId:_},M,O,v):b?D=this._tsCallRegistry.createCallWithMeetingData({meetingCode:b},M,O,v):T?D=this._tsCallRegistry.createCallWithMeetingData({meetingUrl:A},M,O,v):(N=!!g?.participants&&g.participants.length>=2&&isAcsTeamParticipantPresentInCall(g.participants,this.kind),getAcsEcsConfig().calling.enableSmePassFakeConversation&&!_&&N&&(_=`${V}${generateGuid()}`),D=this._tsCallRegistry.createCall(_||"",M,O,S,v));const k=new CallImpl({callId:M,roomId:b},this,D,this._telemetryLogManager,N);this.addToCallArray(k),this.handleCallState(k);const L={threadId:_||"",messageId:S||"",meetingInfo:C,mediaPeerType:2};return g?.participants&&g?.participants.forEach((g=>{D.addParticipant(getMriFromIdentifier(g)).catch((()=>{this.logger.error("Failed to add participant during call start")}))})),k.startCallInternal(g?.startCallOptions,!!P||!!b,g?.callContext,L,f).catch(noop),k.bindTsCall(),this._eventEmitter.emit("callsUpdated",{added:[k],removed:[]}),k}throw new CallingCommunicationError({defaultError:D.CALL_AGENT.STACK_NOT_INIT})}assertCallContext(g){if(!g||this.checkForAtLeastOneValidCallConfig(g)||this.checkIfMultiplesConfigsWereSpecified(g)||this.checkForInvalidTeamsMeetingCoordinates(g))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(g){return!(g.threadId||g.meetingLink||g.groupId||g.meetingId||g.roomId)}checkIfMultiplesConfigsWereSpecified(g){return g.threadId&&g.groupId||g.groupId&&g.meetingLink}checkForInvalidTeamsMeetingCoordinates(g){return!g.threadId&&g.tenantId&&g.organizerId||g.threadId&&(g.organizerId&&!g.tenantId||!g.organizerId&&g.tenantId)}assertCallUserIds(g){assertIsObject(g,D.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),assertNotNull(g,D.CALL_AGENT.USERIDS_CANNOT_BE_NULL),assertIsArrayOfIdentifiers(g),g.forEach((g=>{const f=validateIdentifier(g);if(!isProxyAndCustomTurnAllowed(this.acsProxy,this.acsCustomRelayManager,!1,f))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}))}}CallAgentImpl.callAgents=new Map,__decorate$p([syncOperation(AS.StartCall),__metadata$p("design:type",Function),__metadata$p("design:paramtypes",[Array,Object]),__metadata$p("design:returntype",Object)],CallAgentImpl.prototype,"startCall",null),__decorate$p([syncOperation(AS.Join),__metadata$p("design:type",Function),__metadata$p("design:paramtypes",[Object,Object]),__metadata$p("design:returntype",Object)],CallAgentImpl.prototype,"join",null),__decorate$p([asyncOperation(AS.Dispose),__metadata$p("design:type",Function),__metadata$p("design:paramtypes",[]),__metadata$p("design:returntype",Promise)],CallAgentImpl.prototype,"dispose",null);var cA=createCommonjsModule((function(g,f){var S=window;!function(f,S){g.exports=S(R,M)}(0,((g,f)=>{var v={},C={exports:v},_=Object.create,T=Object.defineProperty,I=Object.getOwnPropertyDescriptor,b=Object.getOwnPropertyNames,A=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty,__commonJS=(g,f)=>function __require(){return f||(0,g[b(g)[0]])((f={exports:{}}).exports,f),f.exports},__export=(g,f)=>{for(var S in f)T(g,S,{get:f[S],enumerable:!0})},__copyProps=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let C of b(f))P.call(g,C)||C===S||T(g,C,{get:()=>f[C],enumerable:!(v=I(f,C))||v.enumerable});return g},__toESM=(g,f,S)=>(S=null!=g?_(A(g)):{},__copyProps(!f&&g&&g.__esModule?S:T(S,"default",{value:g,enumerable:!0}),g)),__toCommonJS=g=>__copyProps(T({},"__esModule",{value:!0}),g),w=__commonJS({"../node_modules/lodash.clonedeep/index.js"(g,f){var v=200,C="__lodash_hash_undefined__",_=9007199254740991,T="[object Arguments]",I="[object Array]",b="[object Boolean]",A="[object Date]",P="[object Error]",R="[object Function]",M="[object GeneratorFunction]",w="[object Map]",O="[object Number]",D="[object Object]",N="[object Promise]",k="[object RegExp]",L="[object Set]",F="[object String]",x="[object Symbol]",U="[object WeakMap]",V="[object ArrayBuffer]",B="[object DataView]",H="[object Float32Array]",$="[object Float64Array]",j="[object Int8Array]",G="[object Int16Array]",q="[object Int32Array]",W="[object Uint8Array]",z="[object Uint8ClampedArray]",K="[object Uint16Array]",J="[object Uint32Array]",Y=/[\\^$.*+?()[\]{}|]/g,Q=/\w*$/,X=/^\[object .+?Constructor\]$/,Z=/^(?:0|[1-9]\d*)$/,ee={};ee[T]=ee[I]=ee[V]=ee[B]=ee[b]=ee[A]=ee[H]=ee[$]=ee[j]=ee[G]=ee[q]=ee[w]=ee[O]=ee[D]=ee[k]=ee[L]=ee[F]=ee[x]=ee[W]=ee[z]=ee[K]=ee[J]=!0,ee[P]=ee[R]=ee[U]=!1;var te="object"==typeof S&&S&&S.Object===Object&&S,ie="object"==typeof self&&self&&self.Object===Object&&self,ne=te||ie||Function("return this")(),re="object"==typeof g&&g&&!g.nodeType&&g,se=re&&"object"==typeof f&&f&&!f.nodeType&&f,ae=se&&se.exports===re;function addMapEntry(g,f){return g.set(f[0],f[1]),g}function addSetEntry(g,f){return g.add(f),g}function arrayEach(g,f){for(var S=-1,v=g?g.length:0;++S<v&&!1!==f(g[S],S,g););return g}function arrayPush(g,f){for(var S=-1,v=f.length,C=g.length;++S<v;)g[C+S]=f[S];return g}function arrayReduce(g,f,S,v){var C=-1,_=g?g.length:0;for(v&&_&&(S=g[++C]);++C<_;)S=f(S,g[C],C,g);return S}function baseTimes(g,f){for(var S=-1,v=Array(g);++S<g;)v[S]=f(S);return v}function getValue(g,f){return null==g?void 0:g[f]}function isHostObject(g){var f=!1;if(null!=g&&"function"!=typeof g.toString)try{f=!!(g+"")}catch(g){}return f}function mapToArray(g){var f=-1,S=Array(g.size);return g.forEach((function(g,v){S[++f]=[v,g]})),S}function overArg(g,f){return function(S){return g(f(S))}}function setToArray(g){var f=-1,S=Array(g.size);return g.forEach((function(g){S[++f]=g})),S}var oe,le=Array.prototype,ce=Function.prototype,de=Object.prototype,he=ne["__core-js_shared__"],ue=(oe=/[^.]+$/.exec(he&&he.keys&&he.keys.IE_PROTO||""))?"Symbol(src)_1."+oe:"",ge=ce.toString,pe=de.hasOwnProperty,me=de.toString,fe=RegExp("^"+ge.call(pe).replace(Y,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Se=ae?ne.Buffer:void 0,ve=ne.Symbol,Ce=ne.Uint8Array,ye=overArg(Object.getPrototypeOf,Object),Ee=Object.create,_e=de.propertyIsEnumerable,Te=le.splice,Ie=Object.getOwnPropertySymbols,be=Se?Se.isBuffer:void 0,Ae=overArg(Object.keys,Object),Pe=getNative(ne,"DataView"),Re=getNative(ne,"Map"),Me=getNative(ne,"Promise"),we=getNative(ne,"Set"),Oe=getNative(ne,"WeakMap"),De=getNative(Object,"create"),Ne=toSource(Pe),ke=toSource(Re),Le=toSource(Me),Fe=toSource(we),xe=toSource(Oe),Ue=ve?ve.prototype:void 0,Ve=Ue?Ue.valueOf:void 0;function Hash(g){var f=-1,S=g?g.length:0;for(this.clear();++f<S;){var v=g[f];this.set(v[0],v[1])}}function hashClear(){this.__data__=De?De(null):{}}function hashDelete(g){return this.has(g)&&delete this.__data__[g]}function hashGet(g){var f=this.__data__;if(De){var S=f[g];return S===C?void 0:S}return pe.call(f,g)?f[g]:void 0}function hashHas(g){var f=this.__data__;return De?void 0!==f[g]:pe.call(f,g)}function hashSet(g,f){return this.__data__[g]=De&&void 0===f?C:f,this}function ListCache(g){var f=-1,S=g?g.length:0;for(this.clear();++f<S;){var v=g[f];this.set(v[0],v[1])}}function listCacheClear(){this.__data__=[]}function listCacheDelete(g){var f=this.__data__,S=assocIndexOf(f,g);return!(S<0)&&(S==f.length-1?f.pop():Te.call(f,S,1),!0)}function listCacheGet(g){var f=this.__data__,S=assocIndexOf(f,g);return S<0?void 0:f[S][1]}function listCacheHas(g){return assocIndexOf(this.__data__,g)>-1}function listCacheSet(g,f){var S=this.__data__,v=assocIndexOf(S,g);return v<0?S.push([g,f]):S[v][1]=f,this}function MapCache(g){var f=-1,S=g?g.length:0;for(this.clear();++f<S;){var v=g[f];this.set(v[0],v[1])}}function mapCacheClear(){this.__data__={hash:new Hash,map:new(Re||ListCache),string:new Hash}}function mapCacheDelete(g){return getMapData(this,g).delete(g)}function mapCacheGet(g){return getMapData(this,g).get(g)}function mapCacheHas(g){return getMapData(this,g).has(g)}function mapCacheSet(g,f){return getMapData(this,g).set(g,f),this}function Stack(g){this.__data__=new ListCache(g)}function stackClear(){this.__data__=new ListCache}function stackDelete(g){return this.__data__.delete(g)}function stackGet(g){return this.__data__.get(g)}function stackHas(g){return this.__data__.has(g)}function stackSet(g,f){var S=this.__data__;if(S instanceof ListCache){var C=S.__data__;if(!Re||C.length<v-1)return C.push([g,f]),this;S=this.__data__=new MapCache(C)}return S.set(g,f),this}function arrayLikeKeys(g,f){var S=$e(g)||isArguments(g)?baseTimes(g.length,String):[],v=S.length,C=!!v;for(var _ in g)!f&&!pe.call(g,_)||C&&("length"==_||isIndex(_,v))||S.push(_);return S}function assignValue(g,f,S){var v=g[f];pe.call(g,f)&&eq(v,S)&&(void 0!==S||f in g)||(g[f]=S)}function assocIndexOf(g,f){for(var S=g.length;S--;)if(eq(g[S][0],f))return S;return-1}function baseAssign(g,f){return g&&copyObject(f,keys(f),g)}function baseClone(g,f,S,v,C,_,I){var b;if(v&&(b=_?v(g,C,_,I):v(g)),void 0!==b)return b;if(!isObject3(g))return g;var A=$e(g);if(A){if(b=initCloneArray(g),!f)return copyArray(g,b)}else{var P=He(g),w=P==R||P==M;if(je(g))return cloneBuffer(g,f);if(P==D||P==T||w&&!_){if(isHostObject(g))return _?g:{};if(b=initCloneObject(w?{}:g),!f)return copySymbols(g,baseAssign(b,g))}else{if(!ee[P])return _?g:{};b=initCloneByTag(g,P,baseClone,f)}}I||(I=new Stack);var O=I.get(g);if(O)return O;if(I.set(g,b),!A)var N=S?getAllKeys(g):keys(g);return arrayEach(N||g,(function(C,_){N&&(C=g[_=C]),assignValue(b,_,baseClone(C,f,S,v,_,g,I))})),b}function baseCreate(g){return isObject3(g)?Ee(g):{}}function baseGetAllKeys(g,f,S){var v=f(g);return $e(g)?v:arrayPush(v,S(g))}function baseGetTag(g){return me.call(g)}function baseIsNative(g){return!(!isObject3(g)||isMasked(g))&&(isFunction3(g)||isHostObject(g)?fe:X).test(toSource(g))}function baseKeys(g){if(!isPrototype(g))return Ae(g);var f=[];for(var S in Object(g))pe.call(g,S)&&"constructor"!=S&&f.push(S);return f}function cloneBuffer(g,f){if(f)return g.slice();var S=new g.constructor(g.length);return g.copy(S),S}function cloneArrayBuffer(g){var f=new g.constructor(g.byteLength);return new Ce(f).set(new Ce(g)),f}function cloneDataView(g,f){var S=f?cloneArrayBuffer(g.buffer):g.buffer;return new g.constructor(S,g.byteOffset,g.byteLength)}function cloneMap(g,f,S){return arrayReduce(f?S(mapToArray(g),!0):mapToArray(g),addMapEntry,new g.constructor)}function cloneRegExp(g){var f=new g.constructor(g.source,Q.exec(g));return f.lastIndex=g.lastIndex,f}function cloneSet(g,f,S){return arrayReduce(f?S(setToArray(g),!0):setToArray(g),addSetEntry,new g.constructor)}function cloneSymbol(g){return Ve?Object(Ve.call(g)):{}}function cloneTypedArray(g,f){var S=f?cloneArrayBuffer(g.buffer):g.buffer;return new g.constructor(S,g.byteOffset,g.length)}function copyArray(g,f){var S=-1,v=g.length;for(f||(f=Array(v));++S<v;)f[S]=g[S];return f}function copyObject(g,f,S,v){S||(S={});for(var C=-1,_=f.length;++C<_;){var T=f[C],I=v?v(S[T],g[T],T,S,g):void 0;assignValue(S,T,void 0===I?g[T]:I)}return S}function copySymbols(g,f){return copyObject(g,Be(g),f)}function getAllKeys(g){return baseGetAllKeys(g,keys,Be)}function getMapData(g,f){var S=g.__data__;return isKeyable(f)?S["string"==typeof f?"string":"hash"]:S.map}function getNative(g,f){var S=getValue(g,f);return baseIsNative(S)?S:void 0}Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var Be=Ie?overArg(Ie,Object):stubArray,He=baseGetTag;function initCloneArray(g){var f=g.length,S=g.constructor(f);return f&&"string"==typeof g[0]&&pe.call(g,"index")&&(S.index=g.index,S.input=g.input),S}function initCloneObject(g){return"function"!=typeof g.constructor||isPrototype(g)?{}:baseCreate(ye(g))}function initCloneByTag(g,f,S,v){var C=g.constructor;switch(f){case V:return cloneArrayBuffer(g);case b:case A:return new C(+g);case B:return cloneDataView(g,v);case H:case $:case j:case G:case q:case W:case z:case K:case J:return cloneTypedArray(g,v);case w:return cloneMap(g,v,S);case O:case F:return new C(g);case k:return cloneRegExp(g);case L:return cloneSet(g,v,S);case x:return cloneSymbol(g)}}function isIndex(g,f){return!!(f=null==f?_:f)&&("number"==typeof g||Z.test(g))&&g>-1&&g%1==0&&g<f}function isKeyable(g){var f=typeof g;return"string"==f||"number"==f||"symbol"==f||"boolean"==f?"__proto__"!==g:null===g}function isMasked(g){return!!ue&&ue in g}function isPrototype(g){var f=g&&g.constructor;return g===("function"==typeof f&&f.prototype||de)}function toSource(g){if(null!=g){try{return ge.call(g)}catch(g){}try{return g+""}catch(g){}}return""}function cloneDeep2(g){return baseClone(g,!0,!0)}function eq(g,f){return g===f||g!=g&&f!=f}function isArguments(g){return isArrayLikeObject(g)&&pe.call(g,"callee")&&(!_e.call(g,"callee")||me.call(g)==T)}(Pe&&He(new Pe(new ArrayBuffer(1)))!=B||Re&&He(new Re)!=w||Me&&He(Me.resolve())!=N||we&&He(new we)!=L||Oe&&He(new Oe)!=U)&&(He=function(g){var f=me.call(g),S=f==D?g.constructor:void 0,v=S?toSource(S):void 0;if(v)switch(v){case Ne:return B;case ke:return w;case Le:return N;case Fe:return L;case xe:return U}return f});var $e=Array.isArray;function isArrayLike(g){return null!=g&&isLength(g.length)&&!isFunction3(g)}function isArrayLikeObject(g){return isObjectLike(g)&&isArrayLike(g)}var je=be||stubFalse;function isFunction3(g){var f=isObject3(g)?me.call(g):"";return f==R||f==M}function isLength(g){return"number"==typeof g&&g>-1&&g%1==0&&g<=_}function isObject3(g){var f=typeof g;return!!g&&("object"==f||"function"==f)}function isObjectLike(g){return!!g&&"object"==typeof g}function keys(g){return isArrayLike(g)?arrayLikeKeys(g):baseKeys(g)}function stubArray(){return[]}function stubFalse(){return!1}f.exports=cloneDeep2}}),O=__commonJS({"../skype-calling-pluginless/dist/skype-calling-pluginless.bundle.js"(g,f){var S,v,C=window;S=g,v=(g,f)=>{var S={},v={exports:S},_=Object.create,T=Object.defineProperty,I=Object.getOwnPropertyDescriptor,b=Object.getOwnPropertyNames,A=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty,__commonJS2=(g,f)=>function __require(){return f||(0,g[b(g)[0]])((f={exports:{}}).exports,f),f.exports},__export2=(g,f)=>{for(var S in f)T(g,S,{get:f[S],enumerable:!0})},__copyProps2=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let C of b(f))P.call(g,C)||C===S||T(g,C,{get:()=>f[C],enumerable:!(v=I(f,C))||v.enumerable});return g},__toESM2=(g,f,S)=>(S=null!=g?_(A(g)):{},__copyProps2(!f&&g&&g.__esModule?S:T(S,"default",{value:g,enumerable:!0}),g)),__toCommonJS2=g=>__copyProps2(T({},"__esModule",{value:!0}),g),__decorateClass=(g,f,S,v)=>{for(var C,_=v>1?void 0:v?I(f,S):f,b=g.length-1;b>=0;b--)(C=g[b])&&(_=(v?C(f,S,_):C(_))||_);return v&&_&&T(f,S,_),_},__decorateParam=(g,f)=>(S,v)=>f(S,v,g),w=__commonJS2({"../node_modules/axios/lib/helpers/bind.js"(g,f){f.exports=function bind(g,f){return function wrap(){for(var S=new Array(arguments.length),v=0;v<S.length;v++)S[v]=arguments[v];return g.apply(f,S)}}}}),O=__commonJS2({"../node_modules/axios/lib/utils.js"(g,f){var S=w(),v=Object.prototype.toString;function isArray4(g){return"[object Array]"===v.call(g)}function isUndefined7(g){return void 0===g}function isBuffer(g){return null!==g&&!isUndefined7(g)&&null!==g.constructor&&!isUndefined7(g.constructor)&&"function"==typeof g.constructor.isBuffer&&g.constructor.isBuffer(g)}function isArrayBuffer(g){return"[object ArrayBuffer]"===v.call(g)}function isFormData(g){return"undefined"!=typeof FormData&&g instanceof FormData}function isArrayBufferView(g){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(g):g&&g.buffer&&g.buffer instanceof ArrayBuffer}function isString3(g){return"string"==typeof g}function isNumber5(g){return"number"==typeof g}function isObject4(g){return null!==g&&"object"==typeof g}function isDate22(g){return"[object Date]"===v.call(g)}function isFile(g){return"[object File]"===v.call(g)}function isBlob(g){return"[object Blob]"===v.call(g)}function isFunction3(g){return"[object Function]"===v.call(g)}function isStream(g){return isObject4(g)&&isFunction3(g.pipe)}function isURLSearchParams(g){return"undefined"!=typeof URLSearchParams&&g instanceof URLSearchParams}function trim2(g){return g.replace(/^\s*/,"").replace(/\s*$/,"")}function isStandardBrowserEnv(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document}function forEach3(g,f){if(null!=g)if("object"!=typeof g&&(g=[g]),isArray4(g))for(var S=0,v=g.length;S<v;S++)f.call(null,g[S],S,g);else for(var C in g)Object.prototype.hasOwnProperty.call(g,C)&&f.call(null,g[C],C,g)}function merge4(){var g={};function assignValue(f,S){"object"==typeof g[S]&&"object"==typeof f?g[S]=merge4(g[S],f):g[S]=f}for(var f=0,S=arguments.length;f<S;f++)forEach3(arguments[f],assignValue);return g}function deepMerge(){var g={};function assignValue(f,S){"object"==typeof g[S]&&"object"==typeof f?g[S]=deepMerge(g[S],f):g[S]="object"==typeof f?deepMerge({},f):f}for(var f=0,S=arguments.length;f<S;f++)forEach3(arguments[f],assignValue);return g}function extend3(g,f,v){return forEach3(f,(function assignValue(f,C){g[C]=v&&"function"==typeof f?S(f,v):f})),g}f.exports={isArray:isArray4,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString3,isNumber:isNumber5,isObject:isObject4,isUndefined:isUndefined7,isDate:isDate22,isFile:isFile,isBlob:isBlob,isFunction:isFunction3,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach3,merge:merge4,deepMerge:deepMerge,extend:extend3,trim:trim2}}}),D=__commonJS2({"../node_modules/axios/lib/helpers/buildURL.js"(g,f){var S=O();function encode(g){return encodeURIComponent(g).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}f.exports=function buildURL(g,f,v){if(!f)return g;var C;if(v)C=v(f);else if(S.isURLSearchParams(f))C=f.toString();else{var _=[];S.forEach(f,(function serialize(g,f){null!=g&&(S.isArray(g)?f+="[]":g=[g],S.forEach(g,(function parseValue(g){S.isDate(g)?g=g.toISOString():S.isObject(g)&&(g=JSON.stringify(g)),_.push(encode(f)+"="+encode(g))})))})),C=_.join("&")}if(C){var T=g.indexOf("#");-1!==T&&(g=g.slice(0,T)),g+=(-1===g.indexOf("?")?"?":"&")+C}return g}}}),N=__commonJS2({"../node_modules/axios/lib/core/InterceptorManager.js"(g,f){var S=O();function InterceptorManager(){this.handlers=[]}InterceptorManager.prototype.use=function use(g,f){return this.handlers.push({fulfilled:g,rejected:f}),this.handlers.length-1},InterceptorManager.prototype.eject=function eject(g){this.handlers[g]&&(this.handlers[g]=null)},InterceptorManager.prototype.forEach=function forEach3(g){S.forEach(this.handlers,(function forEachHandler(f){null!==f&&g(f)}))},f.exports=InterceptorManager}}),k=__commonJS2({"../node_modules/axios/lib/core/transformData.js"(g,f){var S=O();f.exports=function transformData(g,f,v){return S.forEach(v,(function transform(S){g=S(g,f)})),g}}}),L=__commonJS2({"../node_modules/axios/lib/cancel/isCancel.js"(g,f){f.exports=function isCancel(g){return!(!g||!g.__CANCEL__)}}}),F=__commonJS2({"../node_modules/axios/lib/helpers/normalizeHeaderName.js"(g,f){var S=O();f.exports=function normalizeHeaderName(g,f){S.forEach(g,(function processHeader(S,v){v!==f&&v.toUpperCase()===f.toUpperCase()&&(g[f]=S,delete g[v])}))}}}),x=__commonJS2({"../node_modules/axios/lib/core/enhanceError.js"(g,f){f.exports=function enhanceError(g,f,S,v,C){return g.config=f,S&&(g.code=S),g.request=v,g.response=C,g.isAxiosError=!0,g.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:this.config,code:this.code}},g}}}),U=__commonJS2({"../node_modules/axios/lib/core/createError.js"(g,f){var S=x();f.exports=function createError(g,f,v,C,_){var T=new Error(g);return S(T,f,v,C,_)}}}),V=__commonJS2({"../node_modules/axios/lib/core/settle.js"(g,f){var S=U();f.exports=function settle(g,f,v){var C=v.config.validateStatus;!C||C(v.status)?g(v):f(S("Request failed with status code "+v.status,v.config,null,v.request,v))}}}),B=__commonJS2({"../node_modules/axios/lib/helpers/isAbsoluteURL.js"(g,f){f.exports=function isAbsoluteURL(g){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(g)}}}),H=__commonJS2({"../node_modules/axios/lib/helpers/combineURLs.js"(g,f){f.exports=function combineURLs(g,f){return f?g.replace(/\/+$/,"")+"/"+f.replace(/^\/+/,""):g}}}),$=__commonJS2({"../node_modules/axios/lib/core/buildFullPath.js"(g,f){var S=B(),v=H();f.exports=function buildFullPath(g,f){return g&&!S(f)?v(g,f):f}}}),j=__commonJS2({"../node_modules/axios/lib/helpers/parseHeaders.js"(g,f){var S=O(),v=["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"];f.exports=function parseHeaders(g){var f,C,_,T={};return g?(S.forEach(g.split("\n"),(function parser(g){if(_=g.indexOf(":"),f=S.trim(g.substr(0,_)).toLowerCase(),C=S.trim(g.substr(_+1)),f){if(T[f]&&v.indexOf(f)>=0)return;T[f]="set-cookie"===f?(T[f]?T[f]:[]).concat([C]):T[f]?T[f]+", "+C:C}})),T):T}}}),G=__commonJS2({"../node_modules/axios/lib/helpers/isValidXss.js"(g,f){f.exports=function isValidXss(g){return/(\b)(on\w+)=|javascript|(<\s*)(\/*)script/gi.test(g)}}}),q=__commonJS2({"../node_modules/axios/lib/helpers/isURLSameOrigin.js"(g,f){var S=O(),v=G();f.exports=S.isStandardBrowserEnv()?function standardBrowserEnv(){var g,f=/(msie|trident)/i.test(navigator.userAgent),C=document.createElement("a");function resolveURL(g){var S=g;if(v(g))throw new Error("URL contains XSS injection attempt");return f&&(C.setAttribute("href",S),S=C.href),C.setAttribute("href",S),{href:C.href,protocol:C.protocol?C.protocol.replace(/:$/,""):"",host:C.host,search:C.search?C.search.replace(/^\?/,""):"",hash:C.hash?C.hash.replace(/^#/,""):"",hostname:C.hostname,port:C.port,pathname:"/"===C.pathname.charAt(0)?C.pathname:"/"+C.pathname}}return g=resolveURL(window.location.href),function isURLSameOrigin(f){var v=S.isString(f)?resolveURL(f):f;return v.protocol===g.protocol&&v.host===g.host}}():function nonStandardBrowserEnv(){return function isURLSameOrigin(){return!0}}()}}),W=__commonJS2({"../node_modules/axios/lib/helpers/cookies.js"(g,f){var S=O();f.exports=S.isStandardBrowserEnv()?function standardBrowserEnv(){return{write:function write5(g,f,v,C,_,T){var I=[];I.push(g+"="+encodeURIComponent(f)),S.isNumber(v)&&I.push("expires="+new Date(v).toGMTString()),S.isString(C)&&I.push("path="+C),S.isString(_)&&I.push("domain="+_),!0===T&&I.push("secure"),document.cookie=I.join("; ")},read:function read(g){var f=document.cookie.match(new RegExp("(^|;\\s*)("+g+")=([^;]*)"));return f?decodeURIComponent(f[3]):null},remove:function remove6(g){this.write(g,"",Date.now()-864e5)}}}():function nonStandardBrowserEnv(){return{write:function write5(){},read:function read(){return null},remove:function remove6(){}}}()}}),z=__commonJS2({"../node_modules/axios/lib/adapters/xhr.js"(g,f){var S=O(),v=V(),C=D(),_=$(),T=j(),I=q(),b=U();f.exports=function xhrAdapter(g){return new Promise((function dispatchXhrRequest(f,A){var P=g.data,R=g.headers;S.isFormData(P)&&delete R["Content-Type"];var M=new XMLHttpRequest;if(g.auth){var w=g.auth.username||"",O=g.auth.password||"";R.Authorization="Basic "+btoa(w+":"+O)}var D=_(g.baseURL,g.url);if(M.open(g.method.toUpperCase(),C(D,g.params,g.paramsSerializer),!0),M.timeout=g.timeout,M.onreadystatechange=function handleLoad(){if(M&&4===M.readyState&&(0!==M.status||M.responseURL&&0===M.responseURL.indexOf("file:"))){var S="getAllResponseHeaders"in M?T(M.getAllResponseHeaders()):null,C={data:g.responseType&&"text"!==g.responseType?M.response:M.responseText,status:M.status,statusText:M.statusText,headers:S,config:g,request:M};v(f,A,C),M=null}},M.onabort=function handleAbort(){M&&(A(b("Request aborted",g,"ECONNABORTED",M)),M=null)},M.onerror=function handleError(){A(b("Network Error",g,null,M)),M=null},M.ontimeout=function handleTimeout(){var f="timeout of "+g.timeout+"ms exceeded";g.timeoutErrorMessage&&(f=g.timeoutErrorMessage),A(b(f,g,"ECONNABORTED",M)),M=null},S.isStandardBrowserEnv()){var N=W(),k=(g.withCredentials||I(D))&&g.xsrfCookieName?N.read(g.xsrfCookieName):void 0;k&&(R[g.xsrfHeaderName]=k)}if("setRequestHeader"in M&&S.forEach(R,(function setRequestHeader(g,f){void 0===P&&"content-type"===f.toLowerCase()?delete R[f]:M.setRequestHeader(f,g)})),S.isUndefined(g.withCredentials)||(M.withCredentials=!!g.withCredentials),g.responseType)try{M.responseType=g.responseType}catch(f){if("json"!==g.responseType)throw f}"function"==typeof g.onDownloadProgress&&M.addEventListener("progress",g.onDownloadProgress),"function"==typeof g.onUploadProgress&&M.upload&&M.upload.addEventListener("progress",g.onUploadProgress),g.cancelToken&&g.cancelToken.promise.then((function onCanceled(g){M&&(M.abort(),A(g),M=null)})),void 0===P&&(P=null),M.send(P)}))}}}),K=__commonJS2({"../node_modules/axios/lib/defaults.js"(g,f){var S=O(),v=F(),C={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(g,f){!S.isUndefined(g)&&S.isUndefined(g["Content-Type"])&&(g["Content-Type"]=f)}function getDefaultAdapter(){var g;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(g=z()),g}var _={adapter:getDefaultAdapter(),transformRequest:[function transformRequest(g,f){return v(f,"Accept"),v(f,"Content-Type"),S.isFormData(g)||S.isArrayBuffer(g)||S.isBuffer(g)||S.isStream(g)||S.isFile(g)||S.isBlob(g)?g:S.isArrayBufferView(g)?g.buffer:S.isURLSearchParams(g)?(setContentTypeIfUnset(f,"application/x-www-form-urlencoded;charset=utf-8"),g.toString()):S.isObject(g)?(setContentTypeIfUnset(f,"application/json;charset=utf-8"),JSON.stringify(g)):g}],transformResponse:[function transformResponse(g){if("string"==typeof g)try{g=JSON.parse(g)}catch(g){}return g}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function validateStatus(g){return g>=200&&g<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};S.forEach(["delete","get","head"],(function forEachMethodNoData(g){_.headers[g]={}})),S.forEach(["post","put","patch"],(function forEachMethodWithData(g){_.headers[g]=S.merge(C)})),f.exports=_}}),J=__commonJS2({"../node_modules/axios/lib/core/dispatchRequest.js"(g,f){var S=O(),v=k(),C=L(),_=K();function throwIfCancellationRequested(g){g.cancelToken&&g.cancelToken.throwIfRequested()}f.exports=function dispatchRequest(g){return throwIfCancellationRequested(g),g.headers=g.headers||{},g.data=v(g.data,g.headers,g.transformRequest),g.headers=S.merge(g.headers.common||{},g.headers[g.method]||{},g.headers),S.forEach(["delete","get","head","post","put","patch","common"],(function cleanHeaderConfig(f){delete g.headers[f]})),(g.adapter||_.adapter)(g).then((function onAdapterResolution(f){return throwIfCancellationRequested(g),f.data=v(f.data,f.headers,g.transformResponse),f}),(function onAdapterRejection(f){return C(f)||(throwIfCancellationRequested(g),f&&f.response&&(f.response.data=v(f.response.data,f.response.headers,g.transformResponse))),Promise.reject(f)}))}}}),Y=__commonJS2({"../node_modules/axios/lib/core/mergeConfig.js"(g,f){var S=O();f.exports=function mergeConfig(g,f){f=f||{};var v={},C=["url","method","params","data"],_=["headers","auth","proxy"],T=["baseURL","url","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"];S.forEach(C,(function valueFromConfig2(g){void 0!==f[g]&&(v[g]=f[g])})),S.forEach(_,(function mergeDeepProperties(C){S.isObject(f[C])?v[C]=S.deepMerge(g[C],f[C]):void 0!==f[C]?v[C]=f[C]:S.isObject(g[C])?v[C]=S.deepMerge(g[C]):void 0!==g[C]&&(v[C]=g[C])})),S.forEach(T,(function defaultToConfig2(S){void 0!==f[S]?v[S]=f[S]:void 0!==g[S]&&(v[S]=g[S])}));var I=C.concat(_).concat(T),b=Object.keys(f).filter((function filterAxiosKeys(g){return-1===I.indexOf(g)}));return S.forEach(b,(function otherKeysDefaultToConfig2(S){void 0!==f[S]?v[S]=f[S]:void 0!==g[S]&&(v[S]=g[S])})),v}}}),Q=__commonJS2({"../node_modules/axios/lib/core/Axios.js"(g,f){var S=O(),v=D(),C=N(),_=J(),T=Y();function Axios(g){this.defaults=g,this.interceptors={request:new C,response:new C}}Axios.prototype.request=function request(g){"string"==typeof g?(g=arguments[1]||{}).url=arguments[0]:g=g||{},(g=T(this.defaults,g)).method?g.method=g.method.toLowerCase():this.defaults.method?g.method=this.defaults.method.toLowerCase():g.method="get";var f=[_,void 0],S=Promise.resolve(g);for(this.interceptors.request.forEach((function unshiftRequestInterceptors(g){f.unshift(g.fulfilled,g.rejected)})),this.interceptors.response.forEach((function pushResponseInterceptors(g){f.push(g.fulfilled,g.rejected)}));f.length;)S=S.then(f.shift(),f.shift());return S},Axios.prototype.getUri=function getUri(g){return g=T(this.defaults,g),v(g.url,g.params,g.paramsSerializer).replace(/^\?/,"")},S.forEach(["delete","get","head","options"],(function forEachMethodNoData(g){Axios.prototype[g]=function(f,v){return this.request(S.merge(v||{},{method:g,url:f}))}})),S.forEach(["post","put","patch"],(function forEachMethodWithData(g){Axios.prototype[g]=function(f,v,C){return this.request(S.merge(C||{},{method:g,url:f,data:v}))}})),f.exports=Axios}}),X=__commonJS2({"../node_modules/axios/lib/cancel/Cancel.js"(g,f){function Cancel(g){this.message=g}Cancel.prototype.toString=function toString(){return"Cancel"+(this.message?": "+this.message:"")},Cancel.prototype.__CANCEL__=!0,f.exports=Cancel}}),Z=__commonJS2({"../node_modules/axios/lib/cancel/CancelToken.js"(g,f){var S=X();function CancelToken(g){if("function"!=typeof g)throw new TypeError("executor must be a function.");var f;this.promise=new Promise((function promiseExecutor(g){f=g}));var v=this;g((function cancel(g){v.reason||(v.reason=new S(g),f(v.reason))}))}CancelToken.prototype.throwIfRequested=function throwIfRequested(){if(this.reason)throw this.reason},CancelToken.source=function source(){var g;return{token:new CancelToken((function executor(f){g=f})),cancel:g}},f.exports=CancelToken}}),ee=__commonJS2({"../node_modules/axios/lib/helpers/spread.js"(g,f){f.exports=function spread(g){return function wrap(f){return g.apply(null,f)}}}}),te=__commonJS2({"../node_modules/axios/lib/axios.js"(g,f){var S=O(),v=w(),C=Q(),_=Y();function createInstance(g){var f=new C(g),_=v(C.prototype.request,f);return S.extend(_,C.prototype,f),S.extend(_,f),_}var T=createInstance(K());T.Axios=C,T.create=function create(g){return createInstance(_(T.defaults,g))},T.Cancel=X(),T.CancelToken=Z(),T.isCancel=L(),T.all=function all(g){return Promise.all(g)},T.spread=ee(),f.exports=T,f.exports.default=T}}),ie=__commonJS2({"../node_modules/axios/index.js"(g,f){f.exports=te()}}),ne=__commonJS2({"../node_modules/ua-parser-js/src/ua-parser.js"(g,f){!function(S,v){var C="1.0.38",_="",T="?",I="function",b="undefined",A="object",P="string",R="major",M="model",w="name",O="type",D="vendor",N="version",k="architecture",L="console",F="mobile",x="tablet",U="smarttv",V="wearable",B="embedded",H=500,$="Amazon",j="Apple",G="ASUS",q="BlackBerry",W="Browser",z="Chrome",K="Firefox",J="Google",Y="Huawei",Q="LG",X="Microsoft",Z="Motorola",ee="Opera",te="Samsung",ie="Sharp",ne="Sony",re="Xiaomi",se="Zebra",ae="Facebook",oe="Chromium OS",le="Mac OS",extend3=function(g,f){var S={};for(var v in g)f[v]&&f[v].length%2==0?S[v]=f[v].concat(g[v]):S[v]=g[v];return S},enumerize=function(g){for(var f={},S=0;S<g.length;S++)f[g[S].toUpperCase()]=g[S];return f},has2=function(g,f){return typeof g===P&&-1!==lowerize(f).indexOf(lowerize(g))},lowerize=function(g){return g.toLowerCase()},majorize=function(g){return typeof g===P?g.replace(/[^\d\.]/g,_).split(".")[0]:v},trim2=function(g,f){if(typeof g===P)return g=g.replace(/^\s\s*/,_),typeof f===b?g:g.substring(0,H)},rgxMapper=function(g,f){for(var S,C,_,T,b,P,R=0;R<f.length&&!b;){var M=f[R],w=f[R+1];for(S=C=0;S<M.length&&!b&&M[S];)if(b=M[S++].exec(g))for(_=0;_<w.length;_++)P=b[++C],typeof(T=w[_])===A&&T.length>0?2===T.length?typeof T[1]==I?this[T[0]]=T[1].call(this,P):this[T[0]]=T[1]:3===T.length?typeof T[1]!==I||T[1].exec&&T[1].test?this[T[0]]=P?P.replace(T[1],T[2]):v:this[T[0]]=P?T[1].call(this,P,T[2]):v:4===T.length&&(this[T[0]]=P?T[3].call(this,P.replace(T[1],T[2])):v):this[T]=P||v;R+=2}},strMapper=function(g,f){for(var S in f)if(typeof f[S]===A&&f[S].length>0){for(var C=0;C<f[S].length;C++)if(has2(f[S][C],g))return S===T?v:S}else if(has2(f[S],g))return S===T?v:S;return g},ce={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},de={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[N,[w,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[N,[w,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[w,N],[/opios[\/ ]+([\w\.]+)/i],[N,[w,ee+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[N,[w,ee+" GX"]],[/\bopr\/([\w\.]+)/i],[N,[w,ee]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[N,[w,"Baidu"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim)\s?(?:browser)?[\/ ]?([\w\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[w,N],[/\bddg\/([\w\.]+)/i],[N,[w,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[N,[w,"UC"+W]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[N,[w,"WeChat"]],[/konqueror\/([\w\.]+)/i],[N,[w,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[N,[w,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[N,[w,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[N,[w,"Smart Lenovo "+W]],[/(avast|avg)\/([\w\.]+)/i],[[w,/(.+)/,"$1 Secure "+W],N],[/\bfocus\/([\w\.]+)/i],[N,[w,K+" Focus"]],[/\bopt\/([\w\.]+)/i],[N,[w,ee+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[N,[w,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[N,[w,"Dolphin"]],[/coast\/([\w\.]+)/i],[N,[w,ee+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[N,[w,"MIUI "+W]],[/fxios\/([-\w\.]+)/i],[N,[w,K]],[/\bqihu|(qi?ho?o?|360)browser/i],[[w,"360 "+W]],[/(oculus|sailfish|huawei|vivo)browser\/([\w\.]+)/i],[[w,/(.+)/,"$1 "+W],N],[/samsungbrowser\/([\w\.]+)/i],[N,[w,te+" Internet"]],[/(comodo_dragon)\/([\w\.]+)/i],[[w,/_/g," "],N],[/metasr[\/ ]?([\d\.]+)/i],[N,[w,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[w,"Sogou Mobile"],N],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345Explorer)[\/ ]?([\w\.]+)/i],[w,N],[/(lbbrowser)/i,/\[(linkedin)app\]/i],[w],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[w,ae],N],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[w,N],[/\bgsa\/([\w\.]+) .*safari\//i],[N,[w,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[N,[w,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[N,[w,z+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[w,z+" WebView"],N],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[N,[w,"Android "+W]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[w,N],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[N,[w,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[N,w],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[w,[N,strMapper,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[w,N],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[w,"Netscape"],N],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[N,[w,K+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[w,N],[/(cobalt)\/([\w\.]+)/i],[w,[N,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[k,"amd64"]],[/(ia32(?=;))/i],[[k,lowerize]],[/((?:i[346]|x)86)[;\)]/i],[[k,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[k,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[k,"armhf"]],[/windows (ce|mobile); ppc;/i],[[k,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[k,/ower/,_,lowerize]],[/(sun4\w)[;\)]/i],[[k,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[k,lowerize]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[M,[D,te],[O,x]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[M,[D,te],[O,F]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[M,[D,j],[O,F]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[M,[D,j],[O,x]],[/(macintosh);/i],[M,[D,j]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[M,[D,ie],[O,F]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[M,[D,Y],[O,x]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[M,[D,Y],[O,F]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[M,/_/g," "],[D,re],[O,F]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[M,/_/g," "],[D,re],[O,x]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[M,[D,"OPPO"],[O,F]],[/\b(opd2\d{3}a?) bui/i],[M,[D,"OPPO"],[O,x]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[M,[D,"Vivo"],[O,F]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[M,[D,"Realme"],[O,F]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[M,[D,Z],[O,F]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[M,[D,Z],[O,x]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[M,[D,Q],[O,x]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[M,[D,Q],[O,F]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[M,[D,"Lenovo"],[O,x]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[M,/_/g," "],[D,"Nokia"],[O,F]],[/(pixel c)\b/i],[M,[D,J],[O,x]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[M,[D,J],[O,F]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[M,[D,ne],[O,F]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[M,"Xperia Tablet"],[D,ne],[O,x]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[M,[D,"OnePlus"],[O,F]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[M,[D,$],[O,x]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[M,/(.+)/g,"Fire Phone $1"],[D,$],[O,F]],[/(playbook);[-\w\),; ]+(rim)/i],[M,D,[O,x]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[M,[D,q],[O,F]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[M,[D,G],[O,x]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[M,[D,G],[O,F]],[/(nexus 9)/i],[M,[D,"HTC"],[O,x]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[D,[M,/_/g," "],[O,F]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[M,[D,"Acer"],[O,x]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[M,[D,"Meizu"],[O,F]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[M,[D,"Ulefone"],[O,F]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[D,M,[O,F]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[D,M,[O,x]],[/(surface duo)/i],[M,[D,X],[O,x]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[M,[D,"Fairphone"],[O,F]],[/(u304aa)/i],[M,[D,"AT&T"],[O,F]],[/\bsie-(\w*)/i],[M,[D,"Siemens"],[O,F]],[/\b(rct\w+) b/i],[M,[D,"RCA"],[O,x]],[/\b(venue[\d ]{2,7}) b/i],[M,[D,"Dell"],[O,x]],[/\b(q(?:mv|ta)\w+) b/i],[M,[D,"Verizon"],[O,x]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[M,[D,"Barnes & Noble"],[O,x]],[/\b(tm\d{3}\w+) b/i],[M,[D,"NuVision"],[O,x]],[/\b(k88) b/i],[M,[D,"ZTE"],[O,x]],[/\b(nx\d{3}j) b/i],[M,[D,"ZTE"],[O,F]],[/\b(gen\d{3}) b.+49h/i],[M,[D,"Swiss"],[O,F]],[/\b(zur\d{3}) b/i],[M,[D,"Swiss"],[O,x]],[/\b((zeki)?tb.*\b) b/i],[M,[D,"Zeki"],[O,x]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[D,"Dragon Touch"],M,[O,x]],[/\b(ns-?\w{0,9}) b/i],[M,[D,"Insignia"],[O,x]],[/\b((nxa|next)-?\w{0,9}) b/i],[M,[D,"NextBook"],[O,x]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[D,"Voice"],M,[O,F]],[/\b(lvtel\-)?(v1[12]) b/i],[[D,"LvTel"],M,[O,F]],[/\b(ph-1) /i],[M,[D,"Essential"],[O,F]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[M,[D,"Envizen"],[O,x]],[/\b(trio[-\w\. ]+) b/i],[M,[D,"MachSpeed"],[O,x]],[/\btu_(1491) b/i],[M,[D,"Rotor"],[O,x]],[/(shield[\w ]+) b/i],[M,[D,"Nvidia"],[O,x]],[/(sprint) (\w+)/i],[D,M,[O,F]],[/(kin\.[onetw]{3})/i],[[M,/\./g," "],[D,X],[O,F]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[M,[D,se],[O,x]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[M,[D,se],[O,F]],[/smart-tv.+(samsung)/i],[D,[O,U]],[/hbbtv.+maple;(\d+)/i],[[M,/^/,"SmartTV"],[D,te],[O,U]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[D,Q],[O,U]],[/(apple) ?tv/i],[D,[M,j+" TV"],[O,U]],[/crkey/i],[[M,z+"cast"],[D,J],[O,U]],[/droid.+aft(\w+)( bui|\))/i],[M,[D,$],[O,U]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[M,[D,ie],[O,U]],[/(bravia[\w ]+)( bui|\))/i],[M,[D,ne],[O,U]],[/(mitv-\w{5}) bui/i],[M,[D,re],[O,U]],[/Hbbtv.*(technisat) (.*);/i],[D,M,[O,U]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[D,trim2],[M,trim2],[O,U]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[O,U]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[D,M,[O,L]],[/droid.+; (shield) bui/i],[M,[D,"Nvidia"],[O,L]],[/(playstation [345portablevi]+)/i],[M,[D,ne],[O,L]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[M,[D,X],[O,L]],[/((pebble))app/i],[D,M,[O,V]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[M,[D,j],[O,V]],[/droid.+; (glass) \d/i],[M,[D,J],[O,V]],[/droid.+; (wt63?0{2,3})\)/i],[M,[D,se],[O,V]],[/(quest( \d| pro)?)/i],[M,[D,ae],[O,V]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[D,[O,B]],[/(aeobc)\b/i],[M,[D,$],[O,B]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[M,[O,F]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[M,[O,x]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[O,x]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[O,F]],[/(android[-\w\. ]{0,9});.+buil/i],[M,[D,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[N,[w,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[N,[w,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[w,N],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[N,w]],os:[[/microsoft (windows) (vista|xp)/i],[w,N],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[w,[N,strMapper,ce]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[N,strMapper,ce],[w,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[N,/_/g,"."],[w,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[w,le],[N,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[N,w],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[w,N],[/\(bb(10);/i],[N,[w,q]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[N,[w,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[N,[w,K+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[N,[w,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[N,[w,"watchOS"]],[/crkey\/([\d\.]+)/i],[N,[w,z+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[w,oe],N],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[w,N],[/(sunos) ?([\w\.\d]*)/i],[[w,"Solaris"],N],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[w,N]]},UAParser2=function(g,f){if(typeof g===A&&(f=g,g=v),!(this instanceof UAParser2))return new UAParser2(g,f).getResult();var C=typeof S!==b&&S.navigator?S.navigator:v,T=g||(C&&C.userAgent?C.userAgent:_),L=C&&C.userAgentData?C.userAgentData:v,U=f?extend3(de,f):de,V=C&&C.userAgent==T;return this.getBrowser=function(){var g={};return g[w]=v,g[N]=v,rgxMapper.call(g,T,U.browser),g[R]=majorize(g[N]),V&&C&&C.brave&&typeof C.brave.isBrave==I&&(g[w]="Brave"),g},this.getCPU=function(){var g={};return g[k]=v,rgxMapper.call(g,T,U.cpu),g},this.getDevice=function(){var g={};return g[D]=v,g[M]=v,g[O]=v,rgxMapper.call(g,T,U.device),V&&!g[O]&&L&&L.mobile&&(g[O]=F),V&&"Macintosh"==g[M]&&C&&typeof C.standalone!==b&&C.maxTouchPoints&&C.maxTouchPoints>2&&(g[M]="iPad",g[O]=x),g},this.getEngine=function(){var g={};return g[w]=v,g[N]=v,rgxMapper.call(g,T,U.engine),g},this.getOS=function(){var g={};return g[w]=v,g[N]=v,rgxMapper.call(g,T,U.os),V&&!g[w]&&L&&L.platform&&"Unknown"!=L.platform&&(g[w]=L.platform.replace(/chrome os/i,oe).replace(/macos/i,le)),g},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 T},this.setUA=function(g){return T=typeof g===P&&g.length>H?trim2(g,H):g,this},this.setUA(T),this};UAParser2.VERSION=C,UAParser2.BROWSER=enumerize([w,N,R]),UAParser2.CPU=enumerize([k]),UAParser2.DEVICE=enumerize([M,D,O,L,F,U,x,V,B]),UAParser2.ENGINE=UAParser2.OS=enumerize([w,N]),typeof g!==b?(typeof f!==b&&f.exports&&(g=f.exports=UAParser2),g.UAParser=UAParser2):typeof S!==b&&(S.UAParser=UAParser2);var he=typeof S!==b&&(S.jQuery||S.Zepto);if(he&&!he.ua){var ue=new UAParser2;he.ua=ue.getResult(),he.ua.get=function(){return ue.getUA()},he.ua.set=function(g){ue.setUA(g);var f=ue.getResult();for(var S in f)he.ua[S]=f[S]}}}("object"==typeof window?window:g)}}),re=__commonJS2({"../node_modules/@skype/hydra_player_sdk/hydra_player_sdk_bundle.js"(g,f){var S,v;S=g,v=function(){return g={103:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.defer=void 0,f.defer=function(){var g,f;return{promise:new Promise((function(S,v){g=S,f=v})),resolve:g,reject:f}}},457:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.iframeConfigDefault=void 0,f.iframeConfigDefault={scriptSrcDownload:!1,allowSameOrigin:!1}},1:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.liveStreamStatisticConfigDefault=void 0,f.liveStreamStatisticConfigDefault={maxUserInitiatedEventCount:100}},318:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.logSupportedCodecsConfigDefault=void 0,f.logSupportedCodecsConfigDefault={logSupportedCodecs:!1}},508:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.webRtcIceCandidateCollectorConfigDefault=void 0,f.webRtcIceCandidateCollectorConfigDefault={WebRtcIceCandidateCollectorDelayAfterCompleteMs:2500,WebRtcIceCandidateCollectorDelayAfterErrorMs:1e3,WebRtcIceCandidateCollectorMaxRetriesMs:5,WebRtcIceCandidateCollectorRetryDelayMs:100,WebRtcIceCandidateCollectorMaxCollectionTimeMs:6e4,WebRtcIceCandidateCollectorDisableCollection:!1}},10:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.default=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(g){var f=16*Math.random()|0;return("x"===g?f:3&f|8).toString(16)}))}},171:function(g,f,S){var v=this&&this.__assign||function(){return v=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},v.apply(this,arguments)},C=this&&this.__awaiter||function(g,f,S,v){return new(S||(S=Promise))((function(C,_){function o2(g){try{l2(v.next(g))}catch(g){_(g)}}function s2(g){try{l2(v.throw(g))}catch(g){_(g)}}function l2(g){var f;g.done?C(g.value):(f=g.value,f instanceof S?f:new S((function(g){g(f)}))).then(o2,s2)}l2((v=v.apply(g,f||[])).next())}))},_=this&&this.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:s2(0),throw:s2(1),return:s2(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function s2(I){return function(b){return function(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!((C=(C=T.trys).length>0&&C[C.length-1])||6!==I[0]&&2!==I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}([I,b])}}},T=this&&this.__spreadArray||function(g,f,S){if(S||2===arguments.length)for(var v,C=0,_=f.length;C<_;C++)!v&&C in f||(v||(v=Array.prototype.slice.call(f,0,C)),v[C]=f[C]);return g.concat(v||Array.prototype.slice.call(f))};Object.defineProperty(f,"__esModule",{value:!0}),f.LiveStreamStatistic=f.PlayerScenario=void 0;var I=S(346),b=S(963),A=S(1),P=S(534),R=S(318),M=function(){function e3(g,f,S){this.name=g,this.details=f,this.failReason=S,this.timeStamp=Date.now()}return e3.prototype.getName=function(){return this.name},e3.prototype.getFailReason=function(){return this.failReason},e3.prototype.getDetails=function(){return this.details},e3.prototype.getTimeStamp=function(){return this.timeStamp},e3}();f.PlayerScenario=M;var w=function(){function e3(g,f,S,v){this.config=g,this.logFn=f,this.playerDiagnosticsLog=S,this.playerMetadata=v,this.playerEvents=[],this.playbackEvents=[],this.ecdnPluginEvents=[],this.experimentalEvents=[],this.userInitiatedSeekEvents=[],this.userInitiatedPlayEvents=[],this.userInitiatedPauseEvents=[],this.hydraInitResult=null,this.callSetupSucceeded=!1,this.callDropped=!1,this.latestErrorReason=void 0,this.clientNetworkType=void 0,this.supportedCodecs=void 0,this.maxPlayerPlaybackEventCount=g.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=g.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=g.maxPlayerMemoryTraceLogCount||100,this.maxPlayerExperimentalEvents=g.maxPlayerExperimentalEvents||100,this.maxUserInitiatedEventCount=P.getECSSetting(this.config,"maxUserInitiatedEventCount",A.liveStreamStatisticConfigDefault.maxUserInitiatedEventCount),this.config.debugLogging&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener(),P.getECSSetting(this.config,"logSupportedCodecs",R.logSupportedCodecsConfigDefault.logSupportedCodecs)&&this.populateSupportedCodecs()}return e3.prototype.getPlayerDiagnosticSnapshot=function(){return this.currentPlayerDiagnosticSnapshot},e3.prototype.setHydraInitResult=function(g){this.hydraInitResult=g},e3.prototype.registerStatsUpdated=function(g){var f=this;this.currentPlayerDiagnosticSnapshot=g,Object.keys(this.playerDiagnosticsLog).forEach((function(S){var v,C=S,_=null!==(v=f.playerDiagnosticsLog[S])&&void 0!==v?v:[];if(Array.isArray(_)){_.push(g[C]);var T="memoryLog"===C&&_.length>f.maxPlayerMemoryTraceLogCount,I="memoryLog"!==C&&_.length>f.maxPlayerDiagnosticsCount;(T||I)&&_.splice(0,1)}else f.playerDiagnosticsLog[S]=g[C]}))},e3.prototype.registerEventLoadAttempt=function(g,f){this.registerScenario(g,f)},e3.prototype.registerEventLoadFailed=function(g,f){this.completeScenario(g,f)},e3.prototype.registerEventLoadSucceeded=function(g,f){this.completeScenario(g,void 0,f),g===b.PlayerScenarioType.LoadPlayer&&(this.callSetupSucceeded=!0)},e3.prototype.registerSdnPluginLoadAttempt=function(g){this.registerScenario(b.PlayerScenarioType.SdnPluginLoad,g)},e3.prototype.registerSdnPluginLoadFailed=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginLoad,g)},e3.prototype.registerSdnPluginLoadSucceeded=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginLoad,void 0,g)},e3.prototype.registerSdnPluginInitializeAttempt=function(g){this.registerScenario(b.PlayerScenarioType.SdnPluginInitialize,g)},e3.prototype.registerSdnPluginInitializeFailed=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginInitialize,g)},e3.prototype.registerSdnPluginInitializeSucceeded=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginInitialize,void 0,g)},e3.prototype.registerSdnPluginSetSourceAttempt=function(g){this.registerScenario(b.PlayerScenarioType.SdnPluginSetSource,g)},e3.prototype.registerSdnPluginSetSourceFailed=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginSetSource,g)},e3.prototype.registerSdnPluginSetSourceSucceeded=function(g){this.completeScenario(b.PlayerScenarioType.SdnPluginSetSource,void 0,g)},e3.prototype.registerStreamConnectionAttempt=function(g){this.registerScenario(b.PlayerScenarioType.StreamConnection,{streamUrl:g})},e3.prototype.registerStreamConnectionSucceeded=function(g){this.completeScenario(b.PlayerScenarioType.StreamConnection,void 0,{result:P.stringifyObject(g)})},e3.prototype.registerStreamConnectionFailed=function(g,f){this.completeScenario(b.PlayerScenarioType.StreamConnection,g,{result:P.stringifyObject(f)})},e3.prototype.registerSetSourceAttempt=function(g,f,S){var v=g||"";S&&(v={src:g||"",isPrimary:P.stringifyObject(f),reason:S}),this.registerScenario(b.PlayerScenarioType.SetSource,v)},e3.prototype.registerSetSourceSucceeded=function(g,f,S,v,C){this.completeScenario(b.PlayerScenarioType.SetSource,void 0,{src:g,isPrimary:P.stringifyObject(f),switchingDiagnostics:P.stringifyObject(S),stepDuration:P.stringifyObject(v),initialSeekToLiveEdge:P.stringifyObject(C)})},e3.prototype.registerSetSourceFailed=function(g,f,S,v,C){this.completeScenario(b.PlayerScenarioType.SetSource,g,{src:P.stringifyObject(f),isPrimary:P.stringifyObject(S),switchingDiagnostics:P.stringifyObject(v),stepDuration:P.stringifyObject(C)})},e3.prototype.registerPlayerDestroyed=function(g){this.registerScenario(b.PlayerScenarioType.Destroyed,g),this.completeScenario(b.PlayerScenarioType.Destroyed)},e3.prototype.registerPlaybackStateChanged=function(g,f){var S,v,C,_,T,A;if(g!==I.HydraPlayerPlaybackState.CanPlayThrough||this.firstReadyStateTimestamp){if(g===I.HydraPlayerPlaybackState.Playing){if(this.firstPlayingState||(this.firstPlayingState={timestamp:Date.now()},f&&(f.edgeLatency&&(this.firstPlayingState.edgeLatency=f.edgeLatency),f.bufferLength&&(this.firstPlayingState.bufferLength=f.bufferLength))),this.userInitiatedSeekEvents.length>0){var P=this.userInitiatedSeekEvents[this.userInitiatedSeekEvents.length-1];this.modifyTelemetryEventPayload(P,{playingStatePosition:null!==(v=null===(S=this.currentPlayerDiagnosticSnapshot)||void 0===S?void 0:S.currentPlayPosition)&&void 0!==v?v:-1,playingStateTimestamp:Date.now()},!1)}if(this.userInitiatedPlayEvents.length>0){var R=this.userInitiatedPlayEvents[this.userInitiatedPlayEvents.length-1];this.modifyTelemetryEventPayload(R,{playingStatePosition:null!==(_=null===(C=this.currentPlayerDiagnosticSnapshot)||void 0===C?void 0:C.currentPlayPosition)&&void 0!==_?_:-1,playingStateTimestamp:Date.now()},!1)}}else if(g===I.HydraPlayerPlaybackState.Pause&&this.userInitiatedPauseEvents.length>0){var M=this.userInitiatedPauseEvents[this.userInitiatedPauseEvents.length-1];this.modifyTelemetryEventPayload(M,{pauseStatePosition:null!==(A=null===(T=this.currentPlayerDiagnosticSnapshot)||void 0===T?void 0:T.currentPlayPosition)&&void 0!==A?A:-1,pauseStateTimestamp:Date.now()},!1)}}else this.firstReadyStateTimestamp=Date.now();this.registerPlaybackEvent(b.TelemetryEventType.StateChanged,g)},e3.prototype.registerCapabilitiesUpdated=function(g){this.registerPlaybackEvent(b.TelemetryEventType.CapabilitiesUpdated,g)},e3.prototype.registerHydraInputStateChanged=function(g,f){this.registerPlaybackEvent(b.TelemetryEventType.HydraInputStateChanged,g,f)},e3.prototype.registerHydraOutputStateChanged=function(g,f){this.registerPlaybackEvent(b.TelemetryEventType.HydraOutputStateChanged,g,f)},e3.prototype.registerPlaybackBuffering=function(g){this.registerPlaybackEvent(b.TelemetryEventType.Buffering,g)},e3.prototype.registerSdnPluginEvent=function(g){var f=this.createTelemetryEvent(b.TelemetryEventType.EcdnPluginEvents,g);this.ecdnPluginEvents.push(f),this.ecdnPluginEvents.length>this.maxPlayerPlaybackEventCount&&this.ecdnPluginEvents.splice(0,1),this.logTelemetryEvent(f)},e3.prototype.registerPlaybackError=function(g,f,S,v){this.registerPlaybackEvent(b.TelemetryEventType.Error,{errorType:g,details:f,errorSource:S,errorReason:v}),this.latestErrorReason=v},e3.prototype.registerIgnoredPlaybackError=function(g){this.registerPlaybackEvent(b.TelemetryEventType.IgnoredError,g)},e3.prototype.registerDownloadBitrateChanged=function(g){this.registerPlaybackEvent(b.TelemetryEventType.BitrateChangedDownload,g)},e3.prototype.registerStreamOptionsConfigured=function(g,f){this.registerPlaybackEvent(b.TelemetryEventType.StreamOptionsConfigured,g,f)},e3.prototype.registerPlaybackBitrateChanged=function(g){this.registerPlaybackEvent(b.TelemetryEventType.BitrateChangedPlayback,g)},e3.prototype.registerVolumeChange=function(g){this.registerPlaybackEvent(b.TelemetryEventType.Volume,g)},e3.prototype.getSnapshotReport=function(){var g,f,S=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.buildCompleteTelemetryEvent()),C=this.playbackEvents,_={};this.currentPlayerDiagnosticSnapshot&&(_=this.filterAndPrepareTelemetry());var T=P.getECSSetting(this.config,"logSupportedCodecs",R.logSupportedCodecsConfigDefault.logSupportedCodecs);return v(v(v(v(v(v(v(v(v(v(v(v(v(v(v(v({isFullReport:!1,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(f=null===(g=this.currentPlayerDiagnosticSnapshot)||void 0===g?void 0:g.statsInterval)&&void 0!==f?f:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(S)),this.getHydraInternalReport(C)),this.getPlaybackReport(C)),this.getBitrateReport(C)),this.getStreamConnectionReport(S)),this.getSdnReport(S)),this.getSetSourceReport(S)),this.getExperimentalEvents()),this.getUserInitiatedSeekEvents()),{networkType:this.getClientNetworkType()}),T?{supportedCodecs:P.stringifyObject(this.supportedCodecs)}:{}),{callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),_)},e3.prototype.getReport=function(){var g,f,S,C,_=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.buildCompleteTelemetryEvent()),T=this.playbackEvents,I=P.getECSSetting(this.config,"logSupportedCodecs",R.logSupportedCodecsConfigDefault.logSupportedCodecs);return v(v(v(v(v(v(v(v(v(v(v(v(v(v(v(v(v({isFullReport:!0,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(f=null===(g=this.currentPlayerDiagnosticSnapshot)||void 0===g?void 0:g.statsInterval)&&void 0!==f?f:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(_)),this.getHydraInternalReport(T)),this.getPlaybackReport(T)),this.getBitrateReport(T)),this.getStreamConnectionReport(_)),this.getSdnReport(_)),this.getSetSourceReport(_)),this.getExperimentalEvents()),this.getUserInitiatedSeekEvents()),{networkType:this.getClientNetworkType()}),I?{supportedCodecs:P.stringifyObject(this.supportedCodecs)}:{}),{callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),this.getPlayerDiagnosticLog()),{eventId:(null===(S=this.currentPlayerDiagnosticSnapshot)||void 0===S?void 0:S.eventId)||"",templateId:(null===(C=this.currentPlayerDiagnosticSnapshot)||void 0===C?void 0:C.templateId)||""})},e3.prototype.buildCompleteTelemetryEvent=function(){this.playerEvents.sort((function(g,f){return g.getName()!==f.getName()?Object.keys(b.PlayerScenarioType).indexOf(g.getName())-Object.keys(b.PlayerScenarioType).indexOf(f.getName()):g.getTimeStamp()-f.getTimeStamp()}));for(var g,f,S,C,_,T=[],I=0,A=this.playerEvents;I<A.length;I++){var P=A[I],R=T[T.length-1];T.length&&P.getName()===R.name&&0===R.duration?T[T.length-1]=(g=R,S=(f=P).getFailReason()?{failReason:f.getFailReason()}:{},C=f.getDetails()?{details:f.getDetails()}:{},_={name:g.name,startTime:g.startTime,duration:f.getTimeStamp()>g.startTime?f.getTimeStamp()-g.startTime:g.duration},v(v(v({},_),S),C)):T.push({name:b.PlayerScenarioType[P.getName()],startTime:P.getTimeStamp(),duration:0})}return T},e3.prototype.getHydraLoadEvent=function(){var g,f,S,v={name:b.PlayerScenarioType.LoadHydra,startTime:(null===(g=this.hydraInitResult)||void 0===g?void 0:g.initStartTime)||-1,duration:(null===(f=this.hydraInitResult)||void 0===f?void 0:f.initDuration)||0};(null===(S=this.hydraInitResult)||void 0===S?void 0:S.errorMsg)&&(v.failReason=this.hydraInitResult.errorMsg);var C=this.getHydraRuntimeDownloadDetails();return C&&(v.details=C),v},e3.prototype.getHydraRuntimeDownloadDetails=function(){if(this.hydraInitResult){for(var g=[],f=0,S=this.hydraInitResult.runtimeDownloadResults;f<S.length;f++){var v=S[f],C={success:v.success,url:v.url,startTime:v.startTime,duration:v.duration,trackingReference:v.trackingReference,timeTakenToDownloadScript:v.timeTakenToDownloadScript};v.errorMsg&&(C.errorMsg=v.errorMsg),g.push(C)}return P.stringifyObject(g)}return null},e3.prototype.getTotalLoadEvent=function(){var g,f,S,v=this.getScenario(b.PlayerScenarioType.LoadPlayer),C=(null===(g=this.hydraInitResult)||void 0===g?void 0:g.initDuration)||0,_=v.length>0?v[v.length-1].getTimeStamp()-v[0].getTimeStamp():0,T=v.length>0?v[v.length-1].getFailReason():void 0,I={name:b.PlayerScenarioType.Load,startTime:(null===(f=this.hydraInitResult)||void 0===f?void 0:f.initStartTime)||-1,duration:C+_};return(null===(S=this.hydraInitResult)||void 0===S?void 0:S.errorMsg)?I.failReason=this.hydraInitResult.errorMsg:T&&(I.failReason=T),I},e3.prototype.getPlayerMetadataReport=function(){return{playerId:this.playerMetadata.playerId||"",traceId:this.playerMetadata.playerId?this.playerMetadata.playerId.replace(/-/g,""):"",hydraPlayerRuntimeVersion:this.playerMetadata.hydraPlayerRuntimeVersion||"",hydraPlayerSdkVersion:this.playerMetadata.hydraPlayerSdkVersion,player_playerType:this.playerMetadata.hydraPlayerType}},e3.prototype.registerPlaybackEvent=function(g,f,S){var v=this.createTelemetryEvent(g,f,S);g===b.TelemetryEventType.Error&&(null==f?void 0:f.errorType)!==I.HydraPlayerPlaybackErrorType.PlaybackRetried&&(v.fatal=!0,this.callDropped=!0),this.playbackEvents.push(v),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(v)},e3.prototype.getPlayerDiagnosticLog=function(){var g=this;if(!this.currentPlayerDiagnosticSnapshot)return{};var f=this.currentPlayerDiagnosticSnapshot,S=this.playerDiagnosticsLog,C=v(v({},f),S),_={};return Object.keys(C).forEach((function(f){_["player_".concat(f)]=g.prepareForTelemetry(C[f])})),_},e3.prototype.getHydraInitializationReport=function(){var g,f,S,v;return{hydraInit_succeeded:(null===(g=this.hydraInitResult)||void 0===g?void 0:g.initSucceeded)||!1,hydraInit_startTime:(null===(f=this.hydraInitResult)||void 0===f?void 0:f.initStartTime)||-1,hydraInit_errorMessage:(null===(S=this.hydraInitResult)||void 0===S?void 0:S.errorMsg)||"",hydraInit_duration:(null===(v=this.hydraInitResult)||void 0===v?void 0:v.initDuration)||0}},e3.prototype.getPlayerInitializationReport=function(g){var f,S=g.find((function(g){return g.name===b.PlayerScenarioType.Load})),v=this.playerEvents.find((function(g){return g.getName()===b.PlayerScenarioType.StreamConnection})),C={init_timeLoadToStreamConnectionEstablished:(S&&v?v.getTimeStamp()-S.startTime:-1)||-1,init_timeLoadToReady:(S&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-S.startTime:-1)||-1,init_timeLoadToPlaying:(S&&(null===(f=this.firstPlayingState)||void 0===f?void 0:f.timestamp)?this.firstPlayingState.timestamp-S.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(g)};return this.firstPlayingState&&(C.init_firstPlayingStateStatistics=this.prepareForTelemetry(this.firstPlayingState)),C},e3.prototype.getHydraInternalReport=function(g){var f=g.filter((function(g){return g.eventType===b.TelemetryEventType.HydraInputStateChanged})),S=g.filter((function(g){return g.eventType===b.TelemetryEventType.HydraOutputStateChanged}));return{hydra_inputStateChangeEvents:this.prepareForTelemetry(f),hydra_outputStateChangeEvents:this.prepareForTelemetry(S)}},e3.prototype.getPlaybackReport=function(g){var f=g.filter((function(g){return g.eventType===b.TelemetryEventType.StateChanged})),S=f.find((function(g){return g.payload===I.HydraPlayerPlaybackState.CanPlayThrough})),v=f.find((function(g){return g.payload===I.HydraPlayerPlaybackState.Play})),C=f.find((function(g){return g.payload===I.HydraPlayerPlaybackState.Start})),_=f.find((function(g){return g.payload===I.HydraPlayerPlaybackState.Playing})),T=null!=S&&null!=v?v.timestamp-S.timestamp:-1,A=null!=v&&null!=C?C.timestamp-v.timestamp:-1,P=null!=C&&null!=_?_.timestamp-C.timestamp:-1,R=f.filter((function(g){return g.payload===I.HydraPlayerPlaybackState.Seeked})),M=f.filter((function(g){return g.payload===I.HydraPlayerPlaybackState.Seeking})),w=f.filter((function(g){return g.payload===I.HydraPlayerPlaybackState.Pause})),O=f.filter((function(g){return g.payload===I.HydraPlayerPlaybackState.Waiting})),D=[b.TelemetryEventType.BitrateChangedDownload,b.TelemetryEventType.BitrateChangedPlayback,b.TelemetryEventType.Error,b.TelemetryEventType.Mute,b.TelemetryEventType.StateChanged,b.TelemetryEventType.Volume,b.TelemetryEventType.StreamOptionsConfigured,b.TelemetryEventType.IgnoredError],N=g.filter((function(g){return g.eventType===b.TelemetryEventType.Error})),k=g.filter((function(g){return g.eventType===b.TelemetryEventType.IgnoredError})),L=g.filter((function(g){return g.eventType===b.TelemetryEventType.Volume||g.eventType===b.TelemetryEventType.Mute})),F=g.filter((function(g){return g.eventType===b.TelemetryEventType.StreamOptionsConfigured})),x=g.filter((function(g){return!D.includes(g.eventType)}));return{playback_timeReadyToPlay:T,playback_timePlayToStart:A,playback_timeStartToPlaying:P,playback_bufferingEvents:this.prepareForTelemetry(O),playback_errorEvents:this.prepareForTelemetry(N),playback_ignoredErrorEvents:this.prepareForTelemetry(k),playback_pauseEvents:this.prepareForTelemetry(w),playback_otherEvents:this.prepareForTelemetry(x),playback_seekedEvents:this.prepareForTelemetry(R),playback_seekingEvents:this.prepareForTelemetry(M),playback_stateChangeEvents:this.prepareForTelemetry(f),playback_volumeEvents:this.prepareForTelemetry(L),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(F),playback_latestErrorReason:this.latestErrorReason||""}},e3.prototype.getBitrateReport=function(g){var f,S,C,_,T=g.filter((function(g){return g.eventType===b.TelemetryEventType.BitrateChangedDownload})),I=T.sort((function(g){return Number(g.payload)})),A=T.length>0?{bitrate_downloadChanges:this.prepareForTelemetry(T),bitrate_downloadChangeCount:T.length>0||-1,bitrate_downloadMin:(null===(f=I[0])||void 0===f?void 0:f.payload)||-1,bitrate_downloadMax:(null===(S=I[I.length-1])||void 0===S?void 0:S.payload)||-1}:{},P=g.filter((function(g){return g.eventType===b.TelemetryEventType.BitrateChangedPlayback})),R=P.sort((function(g){return Number(g.payload)})),M=P.length>0?{bitrate_playbackChanges:this.prepareForTelemetry(P),bitrate_playbackChangeCount:P.length>0||-1,bitrate_playbackMin:(null===(C=R[0])||void 0===C?void 0:C.payload)||-1,bitrate_playbackMax:(null===(_=R[R.length-1])||void 0===_?void 0:_.payload)||-1}:{};return v(v({},A),M)},e3.prototype.addNetworkTypeEventListener=function(){var g,f,S,v,C=this;(null===(f=null===(g=window.navigator)||void 0===g?void 0:g.connection)||void 0===f?void 0:f.type)&&(null===(v=null===(S=window.navigator)||void 0===S?void 0:S.connection)||void 0===v||v.addEventListener("change",(function(){C.updateClientNetworkType()})))},e3.prototype.updateClientNetworkType=function(){this.clientNetworkType=void 0,this.getClientNetworkType()},e3.prototype.getClientNetworkType=function(){var g,f,S,v;if(void 0===this.clientNetworkType){var C="Unknown";if(null===(f=null===(g=window.navigator)||void 0===g?void 0:g.connection)||void 0===f?void 0:f.type)switch(null===(v=null===(S=window.navigator)||void 0===S?void 0:S.connection)||void 0===v?void 0:v.type){case"cellular":C="WWAN";break;case"ethernet":C="Wired";break;case"wifi":C="Wireless";break;default:C="Unknown"}this.clientNetworkType=C}return this.clientNetworkType},e3.prototype.getCodecList=function(){return[{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L93",width:1920,height:1080,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L90",width:1920,height:1080,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L63",width:1280,height:720,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L60",width:1280,height:720,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=hev1.1.6.L30",width:640,height:480,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.64002A",width:1920,height:1080,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.640028",width:1920,height:1080,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.640020",width:1280,height:720,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.64001E",width:1280,height:720,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=avc1.640015",width:640,height:480,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/webm; codecs=vp09.00.10.08",width:1920,height:1080,bitrate:5e6,framerate:30}},{type:"file",video:{contentType:"video/webm; codecs=vp8",width:1920,height:1080,bitrate:5e6,framerate:30}},{type:"file",video:{contentType:"video/ogg; codecs=theora, vorbis",width:640,height:480,bitrate:5e5,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.05M.08",width:1920,height:1080,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.04M.08",width:1920,height:1080,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.03M.08",width:1280,height:720,bitrate:1e4,framerate:60}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.03M.08",width:1280,height:720,bitrate:1e4,framerate:30}},{type:"file",video:{contentType:"video/mp4; codecs=av01.0.02M.08",width:640,height:480,bitrate:1e4,framerate:30}},{type:"file",audio:{contentType:"audio/webm; codecs=opus",channels:"2",bitrate:64e3,samplerate:48e3}},{type:"file",audio:{contentType:"audio/ogg; codecs=vorbis",channels:"2",bitrate:128e3,samplerate:44100}},{type:"file",audio:{contentType:"audio/mp4; codecs=mp4a.40.2",channels:"2",bitrate:128e3,samplerate:44100}},{type:"file",audio:{contentType:"audio/mp4; codecs=mp4a.40.5",channels:"2",bitrate:64e3,samplerate:48e3}},{type:"file",audio:{contentType:"audio/mpeg",channels:"2",bitrate:128e3,samplerate:44100}},{type:"file",audio:{contentType:"audio/flac",channels:"2",bitrate:32e4,samplerate:96e3}},{type:"file",audio:{contentType:"audio/mp4 codecs=ac-3",channels:"6",bitrate:64e4,samplerate:48e3}},{type:"file",audio:{contentType:"audio/mp4 codecs=ec-3",channels:"6",bitrate:64e4,samplerate:48e3}},{type:"file",audio:{contentType:"audio/wav; codecs=1",channels:"2",bitrate:1411200,samplerate:44100}}]},e3.prototype.getAudioVideoCodecsSupported=function(g){return C(this,void 0,void 0,(function(){var f,S,v=this;return _(this,(function(T){switch(T.label){case 0:return f=[],"mediaCapabilities"in navigator?(S=g.map((function(g){return C(v,void 0,void 0,(function(){var S,v;return _(this,(function(C){switch(C.label){case 0:S=g,C.label=1;case 1:return C.trys.push([1,3,,4]),[4,navigator.mediaCapabilities.decodingInfo(S)];case 2:return(v=C.sent()).supported&&(g.video?f.push({codec:g.video.contentType,supported:v.supported,smooth:v.smooth,powerEfficient:v.powerEfficient,resolution:g.video.height,framerate:g.video.framerate}):g.audio&&f.push({codec:g.audio.contentType,supported:v.supported,smooth:v.smooth,powerEfficient:v.powerEfficient})),[3,4];case 3:return C.sent(),[3,4];case 4:return[2]}}))}))})),[4,Promise.allSettled(S)]):[3,2];case 1:T.sent(),T.label=2;case 2:return[2,f]}}))}))},e3.prototype.populateSupportedCodecs=function(){var g=this;void 0===this.supportedCodecs&&this.getAudioVideoCodecsSupported(this.getCodecList()).then((function(f){g.supportedCodecs=f}))},e3.prototype.getSdnReport=function(g){var f,S=g.filter((function(g){return[b.PlayerScenarioType.SdnPluginLoad,b.PlayerScenarioType.SdnPluginInitialize,b.PlayerScenarioType.SdnPluginSetSource].includes(g.name)})),v=T(T([],S,!0),this.ecdnPluginEvents,!0),C=S.filter((function(g){return void 0!==g.failReason})),_=S.filter((function(g){return g.name===b.PlayerScenarioType.SdnPluginLoad})).sort((function(g,f){return f.startTime-g.startTime}))[0];return{sdn_loaded:!(null==_||void 0!==_.failReason),sdn_details:null!==(f=null==_?void 0:_.details)&&void 0!==f?f:"",sdn_error:C.length>0&&C[C.length-1].failReason||"",sdn_events:this.prepareForTelemetry(v)}},e3.prototype.getStreamConnectionReport=function(g){var f=g.filter((function(g){return g.name===b.PlayerScenarioType.StreamConnection}));return{stream_connection_events:this.prepareForTelemetry(f)}},e3.prototype.getSetSourceReport=function(g){var f=g.filter((function(g){return g.name===b.PlayerScenarioType.SetSource}));return{set_source_events:this.prepareForTelemetry(f)}},e3.prototype.registerScenario=function(g,f){this.playerEvents.push(new M(g,f))},e3.prototype.completeScenario=function(g,f,S){this.playerEvents.push(new M(g,S,f))},e3.prototype.logTelemetryEvent=function(g){this.config.debugLogging&&(this.logFn("debug","PlayerTelemetryEvent: ".concat(JSON.stringify(g))),this.logFn("debug","PlayerDiagnosticData: ".concat(JSON.stringify(this.currentPlayerDiagnosticSnapshot))))},e3.prototype.filterAndPrepareTelemetry=function(){var g=this,f=new Set;f.add("serviceLatencyCdg"),f.add("endToEndLatencyCdg"),f.add("videoEdgeLatencyCdg"),f.add("eventId"),f.add("templateId");var S={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((function(v){f.has(v)||(S["player_".concat(v)]=g.prepareForTelemetry(g.currentPlayerDiagnosticSnapshot[v]))})),S},e3.prototype.prepareForTelemetry=function(g){return"boolean"==typeof g?g:"string"==typeof g||void 0===g?g||"":"number"==typeof g?null!=g?g:-1:JSON.stringify(g)},e3.prototype.getScenario=function(g){return this.playerEvents.filter((function(f){return f.getName()===g}))},e3.prototype.createTelemetryEvent=function(g,f,S){var v,C,_={eventType:g,timestamp:Date.now(),currentPlayPosition:null!==(C=null===(v=this.currentPlayerDiagnosticSnapshot)||void 0===v?void 0:v.currentPlayPosition)&&void 0!==C?C:-1};return void 0!==f&&(_.payload=this.prepareForTelemetry(f)),_.message=S,_},e3.prototype.modifyTelemetryEventPayload=function(g,f,S){try{if(g.payload){var C=JSON.parse(g.payload);C=S?v(v({},C),f):v(v({},f),C),g.payload=this.prepareForTelemetry(C)}else g.payload=this.prepareForTelemetry(f)}catch(f){this.logFn("error","Failed to modify payload for event: ".concat(P.stringifyObject(g),", error: ").concat(f))}},e3.prototype.registerExperimentalEvent=function(g,f,S){var v=this.createTelemetryEvent(g,f,S);this.experimentalEvents.push(v),this.experimentalEvents.length>this.maxPlayerExperimentalEvents&&this.experimentalEvents.splice(0,1),this.logTelemetryEvent(v)},e3.prototype.getExperimentalEvents=function(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}},e3.prototype.registerUserInitiatedSeek=function(g){var f,S,v={newCurrentPlayPosition:g,seekForward:(null!==(S=null===(f=this.currentPlayerDiagnosticSnapshot)||void 0===f?void 0:f.currentPlayPosition)&&void 0!==S?S:-1)<g},C=this.createTelemetryEvent(b.TelemetryEventType.UserInitiatedSeek,v);this.userInitiatedSeekEvents.push(C),this.userInitiatedSeekEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedSeekEvents.splice(0,1)},e3.prototype.registerUserInitiatedPlay=function(){var g=this.createTelemetryEvent(b.TelemetryEventType.UserInitiatedPlay);this.userInitiatedPlayEvents.push(g),this.userInitiatedPlayEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedPlayEvents.splice(0,1)},e3.prototype.registerUserInitiatedPause=function(){var g=this.createTelemetryEvent(b.TelemetryEventType.UserInitiatedPause);this.userInitiatedPauseEvents.push(g),this.userInitiatedPauseEvents.length>this.maxUserInitiatedEventCount&&this.userInitiatedPauseEvents.splice(0,1)},e3.prototype.getUserInitiatedSeekEvents=function(){return{playback_userInitiatedSeekEvents:this.prepareForTelemetry(this.userInitiatedSeekEvents),playback_userInitiatedPlayEvents:this.prepareForTelemetry(this.userInitiatedPlayEvents),playback_userInitiatedPauseEvents:this.prepareForTelemetry(this.userInitiatedPauseEvents)}},e3.prototype.registerPlayBlocked=function(g){this.registerScenario(b.PlayerScenarioType.PlayAttemptBlocked,"Called video element play() but it failed with error: ".concat(g)),this.completeScenario(b.PlayerScenarioType.PlayAttemptBlocked)},e3}();f.LiveStreamStatistic=w},42:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.Spinner=void 0;var S=function(){function e3(g){this.container=g,this.spinnerId="hydra-player-spinner",this.firstSpinnerShowTimestamp=null,this.firstSpinnerHideTimestamp=null,this.spinnerInfoHistory=[],this.maxTimestampHistorySize=100;var f=this.container.ownerDocument.getElementById(this.spinnerId);if(f)return this.spinner=f,void this.show();var S=this.container.ownerDocument.createElement("style");S.textContent="\n            .ml-player-spinner-container {\n                width: 100%;\n                height: 100%;\n                display: flex;\n                justify-content: center;\n                align-items: center;\n                position: absolute;\n                pointer-events: none;\n            }\n            .ml-player-spinner {\n                width: 3.6rem;\n                height: 3.6rem;\n                display: block;\n                overflow-clip-margin: content-box;\n                overflow: hidden;\n                animation: ml-player-spinner-outer-rotate 3s linear infinite;\n            }\n            .ml-player-spinner-dark-wheel {\n                fill: none;\n                r: 45%;\n                cx: 50%;\n                cy: 50%;\n                stroke: rgb(68, 71, 145);\n                stroke-width: 8px;\n            }\n            .ml-player-spinner-light-wheel {\n                fill: none;\n                r: 45%;\n                cx: 50%;\n                cy: 50%;\n                stroke: rgb(127, 133, 245);\n                stroke-width: 8px;\n                stroke-dasharray: 283;\n                stroke-dashoffset: 280;\n                stroke-linecap: round;\n                transform-origin: 50% 50%;\n                animation: ml-player-spinner-inner-rotate 1.5s cubic-bezier(0.33, 0, 0.67, 1) infinite;\n            }\n            @keyframes ml-player-spinner-outer-rotate {\n                0% {\n                    transform: rotate(0deg);\n                }\n                100% {\n                    transform: rotate(360deg);\n                }\n            }\n            @keyframes ml-player-spinner-inner-rotate {\n                0% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(0deg);\n                }\n                25% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(0deg);\n                }\n                50% {\n                    stroke-dashoffset: 75;\n                    transform: rotate(45deg);\n                }\n                75% {\n                    stroke-dashoffset: 75;\n                    transform: rotate(45deg);\n                }\n                100% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(360deg);\n                }\n            }\n        ",this.container.ownerDocument.head.appendChild(S),this.container.style.position="relative";var v=this.container.ownerDocument.createElement("div");v.classList.add("ml-player-spinner-container"),this.container.appendChild(v),this.spinner=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","svg"),this.spinner.style.position="absolute",this.spinner.setAttribute("viewBox","0 0 100 100"),this.spinner.classList.add("ml-player-spinner"),this.spinner.id=this.spinnerId,v.appendChild(this.spinner);var C=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");C.classList.add("ml-player-spinner-dark-wheel"),this.spinner.appendChild(C);var _=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");_.classList.add("ml-player-spinner-light-wheel"),this.spinner.appendChild(_),this.show()}return Object.defineProperty(e3.prototype,"firstShowTimestamp",{get:function(){return this.firstSpinnerShowTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e3.prototype,"firstHideTimestamp",{get:function(){return this.firstSpinnerHideTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e3.prototype,"firstSpinnerDuration",{get:function(){return this.firstSpinnerShowTimestamp?this.firstSpinnerHideTimestamp?this.firstSpinnerHideTimestamp-this.firstSpinnerShowTimestamp:Date.now()-this.firstSpinnerShowTimestamp:null},enumerable:!1,configurable:!0}),Object.defineProperty(e3.prototype,"visibilityHistory",{get:function(){if(this.spinnerInfoHistory.length>0){var g=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];g.hideTimestamp||(g.displayDuration=Date.now()-g.showTimestamp)}return this.spinnerInfoHistory},enumerable:!1,configurable:!0}),e3.prototype.show=function(){var g=Date.now();this.firstSpinnerShowTimestamp||(this.firstSpinnerShowTimestamp=g),(0===this.spinnerInfoHistory.length||this.spinnerInfoHistory[this.spinnerInfoHistory.length-1].hideTimestamp)&&(this.spinnerInfoHistory.push({showTimestamp:g,displayDuration:0}),this.spinnerInfoHistory.length>this.maxTimestampHistorySize&&this.spinnerInfoHistory.splice(0,1)),this.spinner.style.display="block"},e3.prototype.hide=function(){var g=Date.now();if(this.firstSpinnerHideTimestamp||(this.firstSpinnerHideTimestamp=g),this.spinnerInfoHistory.length>0){var f=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];f.hideTimestamp||(f.hideTimestamp=g,f.displayDuration=g-f.showTimestamp)}this.spinner.style.display="none"},e3.prototype.isVisible=function(){return"none"!==this.spinner.style.display},e3}();f.Spinner=S},378:function(g,f){var S,v;Object.defineProperty(f,"__esModule",{value:!0}),f.MessageType=void 0,(v=S||(f.MessageType=S={})).Command="Command",v.CommandSuccessResult="CommandSuccessResult",v.CommandFailureResult="CommandFailureResult",v.PlayerEvent="PlayerEvent",v.InternalPlayerEvent="InternalPlayerEvent"},963:function(g,f){var S,v,C;Object.defineProperty(f,"__esModule",{value:!0}),f.PlayerScenarioType=f.TelemetryEventType=void 0,(C=S||(f.TelemetryEventType=S={})).BitrateChangedDownload="BitrateChangedDownload",C.StreamOptionsConfigured="StreamOptionsConfigured",C.BitrateChangedPlayback="BitrateChangedPlayback",C.CaptionsToggled="CaptionsToggled",C.Error="Error",C.IgnoredError="IgnoredError",C.FullscreenChanged="FullscreenChanged",C.Mute="Mute",C.PotentialMediaFreeze="PotentialMediaFreeze",C.StateChanged="StateChanged",C.HydraInputStateChanged="HydraInputStateChanged",C.HydraOutputStateChanged="HydraOutputStateChanged",C.Volume="Volume",C.Buffering="Buffering",C.Online="Online",C.Offline="Offline",C.NetworkChange="NetworkChange",C.HlsEvents="HlsEvents",C.EcdnPluginEvents="EcdnPluginEvents",C.UserInitiatedSeek="UserInitiatedSeek",C.UserInitiatedPlay="UserInitiatedPlay",C.UserInitiatedPause="UserInitiatedPause",C.CapabilitiesUpdated="CapabilitiesUpdated",function(g){g.LoadHydra="LoadHydra",g.LoadHlsScript="LoadHlsScript",g.LoadPlayer="LoadPlayer",g.Load="Load",g.LoadHlsAuthCookie="LoadHlsAuthCookie",g.HlsManifestLoad="HlsManifestLoad",g.HlsKeyLoad="HlsKeyLoad",g.LoadHlsFirstFragment="LoadHlsFirstFragment",g.SetSource="SetSource",g.SdnPluginLoad="SdnPluginLoad",g.ThaPluginLoad="ThaPluginLoad",g.HydraPipelineInitialization="HydraPipelineInitialization",g.Destroyed="Destroyed",g.Setup="Setup",g.StreamConnection="StreamConnection",g.SdnPluginInitialize="SdnPluginInitialize",g.SdnPluginSetSource="SdnPluginSetSource",g.PlayAttemptBlocked="PlayAttemptBlocked"}(v||(f.PlayerScenarioType=v={}))},176:function(g,f){var S,v,C,_,T,I,b,A;Object.defineProperty(f,"__esModule",{value:!0}),f.MobileInteractionType=f.HydraSupportedSDN=f.HydraPlayerDestroyedReason=f.HydraOutputState=f.HydraInputState=f.HydraPlayerPlaybackErrorSource=f.PlaybackMode=void 0,(A=S||(f.PlaybackMode=S={})).Live="Live",A.DVR="DVR",function(g){g.Stream="Stream",g.HydraPipeline="HydraPipeline",g.VideoPlayer="VideoPlayer"}(v||(f.HydraPlayerPlaybackErrorSource=v={})),function(g){g.Idle="Idle",g.Started="Started",g.BufferReceived="BufferReceived",g.Ended="Ended",g.Stopped="Stopped",g.Destroyed="Destroyed"}(C||(f.HydraInputState=C={})),function(g){g.Idle="Idle",g.Attached="Attached",g.Starting="Starting",g.Started="Started",g.BufferReceived="BufferReceived",g.BufferAppended="BufferAppended",g.Stopped="Stopped",g.Destroyed="Destroyed"}(_||(f.HydraOutputState=_={})),function(g){g.PlayerStopped="PlayerStopped",g.PlaybackError="PlaybackError"}(T||(f.HydraPlayerDestroyedReason=T={})),function(g){g.Hive="hive",g.Kollective="kollective",g.Ramp="ramp",g.Peer5="peer5",g.Microsoft="microsoft"}(I||(f.HydraSupportedSDN=I={})),function(g){g[g.DoublePress3Fingers=0]="DoublePress3Fingers"}(b||(f.MobileInteractionType=b={}))},346:function(g,f){var S,v,C,_,T,I,b,A,P;Object.defineProperty(f,"__esModule",{value:!0}),f.HttpFetchErrorReason=f.IframeMessages=f.HydraPlayerType=f.HydraPlayerPlaybackErrorType=f.HydraPlayerPlaybackState=f.HydraPlayerSetupErrorType=f.HydraStreamDeliveryPipeline=f.HydraStreamingEventType=void 0,(P=S||(f.HydraStreamingEventType=S={})).TLE="TLE",P.Overflow="Overflow",P.TownHallBasic="TownHall_Basic",P.TownHallPremium="TownHall_Premium",P.TownHall="TownHall",function(g){g.AMS="AMS",g.HLS="MiddleLaneHttpLiveStreaming",g.Ums="MiddleLaneUltraLowLatency"}(v||(f.HydraStreamDeliveryPipeline=v={})),function(g){g.MultiplePlayerLoad="MultiplePlayerLoad",g.PlayerInitializationFailed="PlayerInitializationFailed",g.InvalidStream="InvalidStream",g.SetSourceFailed="SetSourceFailed"}(C||(f.HydraPlayerSetupErrorType=C={})),function(g){g.LoadStart="loadstart",g.LoadedData="loadeddata",g.LoadedMetadata="loadedmetadata",g.Start="start",g.CanPlayThrough="canplaythrough",g.Play="play",g.Playing="playing",g.Pause="pause",g.Waiting="waiting",g.Seeking="seeking",g.Seeked="seeked",g.Ended="ended",g.Error="error",g.Destroyed="destroyed",g.Initialized="initialized",g.Stalled="stalled",g.VolumeChange="volumechange",g.PlaybackBitrateChanged="playbackbitratechanged",g.DownloadBitrateChanged="downloadbitratechanged",g.TimeUpdate="timeupdate",g.DurationChange="durationchange",g.HlsKeyLoading="hlsKeyLoading",g.HlsKeyLoaded="hlsKeyLoaded",g.HlsKeyLoadedFailed="hlsKeyLoadedFailed",g.HlsManifestLoading="hlsManifestLoading",g.HlsManifestLoaded="hlsManifestLoaded",g.HlsManifestLoadedFailed="hlsManifestLoadedFailed",g.HlsFirstFragmentLoading="hlsFragLoading",g.HlsFirstFragmentBuffered="hlsFragBuffered",g.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",g.HlsFragmentChanged="hlsFragmentChanged",g.Online="online",g.Offline="offline",g.NetworkChange="networkChange"}(_||(f.HydraPlayerPlaybackState=_={})),function(g){g.UnsupportedPlatform="UnsupportedPlatform",g.NetworkError="NetworkError",g.PlaybackRetried="PlaybackRetried",g.PlaybackError="PlaybackError",g.Unknown="Unknown",g.MediaTimeout="MediaTimeout",g.NoMediaFlow="NoMediaFlow"}(T||(f.HydraPlayerPlaybackErrorType=T={})),function(g){g[g.Hls=1]="Hls",g[g.Ums=2]="Ums"}(I||(f.HydraPlayerType=I={})),function(g){g.RequestIceCandidates="RequestIceCandidates"}(b||(f.IframeMessages=b={})),function(g){g.Unknown="Unknown",g.ClientNetwork="ClientNetwork",g.ClientNetworkOrUnreachableServer="ClientNetworkOrUnreachableServer",g.ServerNetwork="ServerNetwork",g.ClientAuthIssue="ClientAuthIssue",g.ServerResourceNotFound="ServerResourceNotFound"}(A||(f.HttpFetchErrorReason=A={}))},534:function(g,f,S){var v=this&&this.__awaiter||function(g,f,S,v){return new(S||(S=Promise))((function(C,_){function o2(g){try{l2(v.next(g))}catch(g){_(g)}}function s2(g){try{l2(v.throw(g))}catch(g){_(g)}}function l2(g){var f;g.done?C(g.value):(f=g.value,f instanceof S?f:new S((function(g){g(f)}))).then(o2,s2)}l2((v=v.apply(g,f||[])).next())}))},C=this&&this.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:s2(0),throw:s2(1),return:s2(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function s2(I){return function(b){return function(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!((C=(C=T.trys).length>0&&C[C.length-1])||6!==I[0]&&2!==I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}([I,b])}}};Object.defineProperty(f,"__esModule",{value:!0}),f.isPlaybackStoppingState=f.tryCallVideoElementPlay=f.sanitizeForFormatSpecifiers=f.addEvent=f.TimeRanges=f.NO_OP_BUFFERED=f.getHttpFetchErrorReason=f.createVideoPlayButton=f.createVideoElement=f.createVideoElementDiv=f.showPlayerControls=f.repeatUntilCancel=f.wait=f.stringifyError=f.stringifyObject=f.getRandomHexString=f.getPlayerSetting=f.getECSSetting=f.retry=f.createIFrame=f.getMajorFromVersion=void 0;var _=S(346),T=S(457);function s(g,f,S,_,T,I,b){return v(this,void 0,void 0,(function(){var A,P,R,M,w,O=this;return C(this,(function(D){switch(D.label){case 0:return A=100,P=Date.now(),[4,c(S,R={trackingRef:"",timeTakenToDownloadScript:-1},T,I,b).catch((function(g){return v(O,void 0,void 0,(function(){var f;return C(this,(function(v){switch(v.label){case 0:return f="Failed to get IFrame source: ".concat(p(g)),_.push({success:!1,url:S,startTime:P,duration:Date.now()-P,trackingReference:R.trackingRef,timeTakenToDownloadScript:R.timeTakenToDownloadScript,errorMsg:f}),_.length>A&&_.shift(),[4,Promise.reject(new Error(f))];case 1:return[2,v.sent()]}}))}))}))];case 1:return M=D.sent(),f.srcdoc=M,w=new Promise((function(g,v){f.onload=function(){_.push({success:!0,url:S,startTime:P,duration:Date.now()-P,trackingReference:R.trackingRef,timeTakenToDownloadScript:R.timeTakenToDownloadScript}),_.length>A&&_.shift(),g()},f.onerror=function(g){var f="Failed to load HydraPlayer IFrame: ".concat(p(g));_.push({success:!1,url:S,startTime:P,duration:Date.now()-P,trackingReference:R.trackingRef,timeTakenToDownloadScript:R.timeTakenToDownloadScript,errorMsg:f}),_.length>A&&_.shift(),v(new Error(f))}})),g.appendChild(f),[4,w];case 2:return D.sent(),[2]}}))}))}function l(g){return v(this,arguments,void 0,(function(g,f,S){var _=this;return void 0===f&&(f=5),void 0===S&&(S=200),C(this,(function(T){switch(T.label){case 0:return[4,g(f).catch((function(T){return v(_,void 0,void 0,(function(){var _=this;return C(this,(function(I){switch(I.label){case 0:return 0!=--f?[3,2]:[4,Promise.reject(new Error("[retry] retries exhausted: ".concat(y(T))))];case 1:case 3:return[2,I.sent()];case 2:return[4,new Promise((function(I){return setTimeout((function(){I(l(g,f,S).catch((function(g){return v(_,void 0,void 0,(function(){return C(this,(function(f){switch(f.label){case 0:return[4,Promise.reject(new Error("".concat(y(T)).concat(", ",y(g))))];case 1:return[2,f.sent()]}}))}))})))}),S)}))]}}))}))}))];case 1:return[2,T.sent()]}}))}))}function c(g,f,S,_,T){return v(this,void 0,void 0,(function(){var I,b,A,P=this;return C(this,(function(R){switch(R.label){case 0:return I=Date.now(),S?(b='<script src="'.concat(g,'"></script')+">",[3,3]):[3,1];case 1:return[4,d(g,f,_).catch((function(g){return v(P,void 0,void 0,(function(){return C(this,(function(f){switch(f.label){case 0:return[4,Promise.reject(g)];case 1:return[2,f.sent()]}}))}))}))];case 2:A=R.sent(),b=T?'<script nonce="'.concat(T,'">').concat(A,"</script")+">":"<script>".concat(A,"</script")+">",R.label=3;case 3:return f.timeTakenToDownloadScript=Date.now()-I,[2,"\n        <html class style='height: 100%; width: 100%; overflow: hidden'>\n        <head></head>\n        <body class style='height: 100%; width: 100%; margin: 0px'>\n            ".concat(b,"\n        </body>\n        </html>\n    ")]}}))}))}function d(g,f,S){return v(this,void 0,void 0,(function(){var _,T,I,b=this;return C(this,(function(A){switch(A.label){case 0:return _=function(g,f){var S,v;return f.includes("vz")?null!==(v=g.headers.get("uuid"))&&void 0!==v?v:"":null!==(S=g.headers.get("X-Azure-Ref"))&&void 0!==S?S:""},S?(T=new AbortController,I=setTimeout((function(){T.abort()}),S),[4,fetch(g,{signal:T.signal,cache:"no-cache"}).then((function(S){return v(b,void 0,void 0,(function(){return C(this,(function(v){switch(v.label){case 0:return clearTimeout(I),S.ok?[3,2]:[4,Promise.reject(new Error("".concat(S.status)))];case 1:return[2,v.sent()];case 2:return f.trackingRef=_(S,g),[2,S]}}))}))})).then((function(f){return v(b,void 0,void 0,(function(){var S=this;return C(this,(function(_){switch(_.label){case 0:return[4,f.text().then((function(_){return v(S,void 0,void 0,(function(){return C(this,(function(S){switch(S.label){case 0:return _?[2,_]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(f.status,", script ").concat(g," contents are null")))];case 2:return[2,S.sent()]}}))}))}))];case 1:return[2,_.sent()]}}))}))})).catch((function(g){return v(b,void 0,void 0,(function(){return C(this,(function(f){throw clearTimeout(I),g}))}))}))]):[3,2];case 1:case 3:return[2,A.sent()];case 2:return[4,fetch(g,{cache:"no-cache"}).then((function(S){return v(b,void 0,void 0,(function(){return C(this,(function(v){switch(v.label){case 0:return S.ok?[3,2]:[4,Promise.reject(new Error("".concat(S.status)))];case 1:return[2,v.sent()];case 2:return f.trackingRef=_(S,g),[2,S]}}))}))})).then((function(f){return v(b,void 0,void 0,(function(){var S=this;return C(this,(function(_){switch(_.label){case 0:return[4,f.text().then((function(_){return v(S,void 0,void 0,(function(){return C(this,(function(S){switch(S.label){case 0:return _?[2,_]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(f.status,", script ").concat(g," contents are null")))];case 2:return[2,S.sent()]}}))}))}))];case 1:return[2,_.sent()]}}))}))}))]}}))}))}function u(g,f,S){var v,C=S,_=null===(v=g.ecsSettings)||void 0===v?void 0:v[f];return typeof _==typeof C&&(C=_),C}function p(g){try{if(!g)return"".concat(g);if(g instanceof Map)return S={},g.forEach((function(g,f){S[f.toString()]=g})),JSON.stringify(S);var f=g.toString();return f.endsWith("[object Object]")?JSON.stringify(g):f}catch(g){return""}var S}function y(g){return g instanceof Error?g.message:p(g)}function h(g){return v(this,void 0,void 0,(function(){return C(this,(function(f){switch(f.label){case 0:return[4,new Promise((function(f){return setTimeout(f,g)}))];case 1:return f.sent(),[2]}}))}))}function f22(g){return g?g.replace(/%[a-zA-Z]/g,""):g}f.getMajorFromVersion=function(g){var f=g.match(/^(\d+)\.\d+\.\d+(-.*)?$/);return f?f[1]:null},f.createIFrame=function(g,f,S){return v(this,void 0,void 0,(function(){var _,I,b,A,P,R,M,w,O,D,N=this;return C(this,(function(k){switch(k.label){case 0:return _=u(S,"scriptSrcDownload",T.iframeConfigDefault.scriptSrcDownload),I=u(S,"allowSameOrigin",T.iframeConfigDefault.allowSameOrigin),b=S.maxRetryCountForLoadingResources,A=S.disableSandbox,P=S.hydraRuntimeFetchTimeout,R=[],(M=g.ownerDocument.createElement("iframe")).id="player-iframe",A||(I?null===(O=M.sandbox)||void 0===O||O.add("allow-scripts","allow-same-origin"):null===(D=M.sandbox)||void 0===D||D.add("allow-scripts")),M.allowFullscreen=!0,M.allow="camera; microphone; autoplay",M.style.height="100%",M.style.width="100%",M.style.border="none",w=function(g){return f[g%f.length]},[4,l((function(f){return v(N,void 0,void 0,(function(){var v,T,I;return C(this,(function(C){switch(C.label){case 0:return v=w(f),T=null!==(I=S.nonce)&&void 0!==I?I:"",[4,s(g,M,v,R,_,P,T)];case 1:return C.sent(),[2]}}))}))}),b).then((function(){return{iframe:M,initResult:{isSuccess:!0,runtimeDownloadResults:R}}})).catch((function(g){return v(N,void 0,void 0,(function(){var S;return C(this,(function(v){return S="Failed to load Hydra player runtime scripts, src: ",f.forEach((function(g){return S=S.concat(g,", ")})),S+="errors: ".concat(p(g)),[2,{initResult:{isSuccess:!1,runtimeDownloadResults:R,errorMsg:S}}]}))}))}))];case 1:return[2,k.sent()]}}))}))},f.retry=l,f.getECSSetting=u,f.getPlayerSetting=function(g,f){var S;return void 0!==(null===(S=g.ecsSettings)||void 0===S?void 0:S[f])?g.ecsSettings[f]:g[f]},f.getRandomHexString=function(g){return Array.from(Array(g)).map((function(){return Math.floor(16*Math.random()).toString(16)})).join("")},f.stringifyObject=p,f.stringifyError=y,f.wait=h,f.repeatUntilCancel=function(g,f,S,_){var T=!1,I=_||console.log,b=f22(g);return I("RepeatUntilCancel starting task: ".concat(b)),v(this,void 0,void 0,(function(){var g,v,_;return C(this,(function(C){switch(C.label){case 0:return T?[3,2]:(g=new Date,f(),v=(new Date).getTime()-g.getTime(),(_=S-v)<0&&(_=S+_%S,I("Skipping execution for ".concat(b,", last execution took: ").concat(v," ms, delayMs: ").concat(S),"warn")),[4,h(_)]);case 1:return C.sent(),[3,0];case 2:return[2]}}))})),function(){I("RepeatUntilCancel stopping task: ".concat(b)),T=!0}},f.showPlayerControls=function(g){return void 0!==g.allowPlayerControls?g.allowPlayerControls:g.streamingEventType===_.HydraStreamingEventType.TLE},f.createVideoElementDiv=function(g,f,S){S("createVideoElementDiv started");var v=f.ownerDocument.createElement("div");return v.id=g,v.style.position="relative",v.style.width="100%",v.style.height="100%",f.appendChild(v),S("createVideoElementDiv done"),v},f.createVideoElement=function(g,f,S,v,C){C("createVideoElement started");var _=f.ownerDocument.createElement("video");_.controls=v,_.id=g,_.setAttribute("playsinline","");var T=S.videoLang;T&&(_.setAttribute("lang",T),C("createVideoElement: language set to ".concat(T)));var I=S.videoElementStyles;if(I)for(var b=0;b<I.length;b++)_.classList.add(I[b]);return _.style.width="100%",_.style.height="100%",_.style.position="absolute",_.muted=S.muteVideo,_.addEventListener("contextmenu",(function(g){g.preventDefault()})),["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"].forEach((function(g){try{navigator.mediaSession.setActionHandler(g,(function(){}))}catch(g){}})),f.appendChild(_),C("createVideoElement done"),_},f.createVideoPlayButton=function(g,f,S,v){v("createVideoPlayButton started");var C=f.ownerDocument.createElement("style");C.innerHTML="\n    .hydra-play-button {\n        width: 70px;\n        height: 70px;\n        background-color: #373538;\n        border: none;\n        border-radius: 50%;\n        position: absolute;\n        top: 50%;\n        left: 50%;\n        transform: translate(-50%, -50%);\n        cursor: pointer;\n        display: flex;\n        align-items: center;\n        justify-content: center;\n    }\n\n    .triangle {\n        position: relative;\n        background-color: white;\n        text-align: left;\n    }\n    .triangle:before,\n    .triangle:after {\n        content: '';\n        position: absolute;\n        background-color: inherit;\n    }\n    .triangle,\n    .triangle:before,\n    .triangle:after {\n        width: 1em;\n        height: 1em;\n        border-top-right-radius: 30%;\n    }\n\n    .triangle {\n        transform: rotate(270deg) skewX(-30deg) scale(1, .866) translate(10%, -15%);\n    }\n    .triangle:before {\n        transform: rotate(-135deg) skewX(-45deg) scale(1.414, .707) translate(0, -50%);\n    }\n    .triangle:after {\n        transform: rotate(135deg) skewY(-45deg) scale(.707, 1.414) translate(50%);\n    }\n    ",f.ownerDocument.head.appendChild(C);var _=f.ownerDocument.createElement("div");_.id=g,_.className="hydra-play-button";var T=document.createElement("div");return T.className="triangle",_.appendChild(T),S||(_.style.display="none"),f.appendChild(_),v("createVideoPlayButton done"),_},f.getHttpFetchErrorReason=function(g){return void 0===g?_.HttpFetchErrorReason.Unknown:0===g?_.HttpFetchErrorReason.ClientNetworkOrUnreachableServer:401===g?_.HttpFetchErrorReason.ClientAuthIssue:404===g?_.HttpFetchErrorReason.ServerResourceNotFound:g>=400&&g<=499?_.HttpFetchErrorReason.ClientNetwork:g>=500&&g<=599?_.HttpFetchErrorReason.ServerNetwork:_.HttpFetchErrorReason.Unknown},f.NO_OP_BUFFERED={length:0,start:function(){return 0},end:function(){return 0}},f.TimeRanges={toString:function(g){for(var f="",S=g.length,v=0;v<S;v++)f+="[".concat(g.start(v).toFixed(3),"-").concat(g.end(v).toFixed(3),"]");return f},range:function(g){return g&&0!==g.length?[g.start(g.length-1),g.end(g.length-1)]:[0,0]},prevRange:function(g){if(g&&2===g.length)return[g.start(g.length-2),g.end(g.length-2)]}},f.addEvent=function(g,f){var S={};return(null==f?void 0:f.detail)&&(S={detail:f.detail}),new CustomEvent(g,S)},f.sanitizeForFormatSpecifiers=f22,f.tryCallVideoElementPlay=function(g){var f=g.play();return void 0!==f?f:new Promise((function(g){return g()}))},f.isPlaybackStoppingState=function(g){return g===_.HydraPlayerPlaybackState.Pause||g===_.HydraPlayerPlaybackState.Ended||g===_.HydraPlayerPlaybackState.Seeking||g===_.HydraPlayerPlaybackState.Waiting||g===_.HydraPlayerPlaybackState.Stalled||g===_.HydraPlayerPlaybackState.Destroyed}},564:function(g,f){var S,v,C,_,T,I,b,A,P,R;Object.defineProperty(f,"__esModule",{value:!0}),f.UmsModality=f.HttpFetchErrorReason=f.IframeMessages=f.HydraPlayerType=f.HydraPlayerPlaybackErrorType=f.HydraPlayerPlaybackState=f.HydraPlayerSetupErrorType=f.HydraStreamDeliveryPipeline=f.HydraStreamingEventType=void 0,(R=S||(f.HydraStreamingEventType=S={})).TLE="TLE",R.Overflow="Overflow",R.TownHallBasic="TownHall_Basic",R.TownHallPremium="TownHall_Premium",R.TownHall="TownHall",function(g){g.AMS="AMS",g.HLS="MiddleLaneHttpLiveStreaming",g.Ums="MiddleLaneUltraLowLatency"}(v||(f.HydraStreamDeliveryPipeline=v={})),function(g){g.MultiplePlayerLoad="MultiplePlayerLoad",g.PlayerInitializationFailed="PlayerInitializationFailed",g.InvalidStream="InvalidStream",g.SetSourceFailed="SetSourceFailed"}(C||(f.HydraPlayerSetupErrorType=C={})),function(g){g.LoadStart="loadstart",g.LoadedData="loadeddata",g.LoadedMetadata="loadedmetadata",g.Start="start",g.CanPlayThrough="canplaythrough",g.Play="play",g.Playing="playing",g.Pause="pause",g.Waiting="waiting",g.Seeking="seeking",g.Seeked="seeked",g.Ended="ended",g.Error="error",g.Destroyed="destroyed",g.Initialized="initialized",g.Stalled="stalled",g.VolumeChange="volumechange",g.PlaybackBitrateChanged="playbackbitratechanged",g.DownloadBitrateChanged="downloadbitratechanged",g.TimeUpdate="timeupdate",g.DurationChange="durationchange",g.HlsKeyLoading="hlsKeyLoading",g.HlsKeyLoaded="hlsKeyLoaded",g.HlsKeyLoadedFailed="hlsKeyLoadedFailed",g.HlsManifestLoading="hlsManifestLoading",g.HlsManifestLoaded="hlsManifestLoaded",g.HlsManifestLoadedFailed="hlsManifestLoadedFailed",g.HlsFirstFragmentLoading="hlsFragLoading",g.HlsFirstFragmentBuffered="hlsFragBuffered",g.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",g.HlsFragmentChanged="hlsFragmentChanged",g.Online="online",g.Offline="offline",g.NetworkChange="networkChange"}(_||(f.HydraPlayerPlaybackState=_={})),function(g){g.UnsupportedPlatform="UnsupportedPlatform",g.NetworkError="NetworkError",g.PlaybackRetried="PlaybackRetried",g.PlaybackError="PlaybackError",g.Unknown="Unknown",g.MediaTimeout="MediaTimeout",g.NoMediaFlow="NoMediaFlow"}(T||(f.HydraPlayerPlaybackErrorType=T={})),function(g){g[g.Hls=1]="Hls",g[g.Ums=2]="Ums"}(I||(f.HydraPlayerType=I={})),function(g){g.RequestIceCandidates="RequestIceCandidates"}(b||(f.IframeMessages=b={})),function(g){g.Unknown="Unknown",g.ClientNetwork="ClientNetwork",g.ClientNetworkOrUnreachableServer="ClientNetworkOrUnreachableServer",g.ServerNetwork="ServerNetwork",g.ClientAuthIssue="ClientAuthIssue",g.ServerResourceNotFound="ServerResourceNotFound"}(A||(f.HttpFetchErrorReason=A={})),function(g){g.audio="Audio",g.video="Video",g.text="Text"}(P||(f.UmsModality=P={}))},521:function(g,f,S){var v=this&&this.__awaiter||function(g,f,S,v){return new(S||(S=Promise))((function(C,_){function o2(g){try{l2(v.next(g))}catch(g){_(g)}}function s2(g){try{l2(v.throw(g))}catch(g){_(g)}}function l2(g){var f;g.done?C(g.value):(f=g.value,f instanceof S?f:new S((function(g){g(f)}))).then(o2,s2)}l2((v=v.apply(g,f||[])).next())}))},C=this&&this.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:s2(0),throw:s2(1),return:s2(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function s2(I){return function(b){return function(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!((C=(C=T.trys).length>0&&C[C.length-1])||6!==I[0]&&2!==I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}([I,b])}}};Object.defineProperty(f,"__esModule",{value:!0}),f.HydraPlayer=f.getSdkVersion=void 0;var _=S(346),T=S(378),I=S(715),b=S(357),A=S(534),P=S(42),R=S(103),M=S(282),w=S(10);f.getSdkVersion=function(){return"4.2521.1"};var O=function(){function e3(g,f){this.playerSettings=g,this.eventHandler=f,this.spinner=null,this.telemetryReportHandler=null,this.playerRuntimeUrls=[],this.commandResultsMap=new Map,this.iframeCommunicationHandler=null,this.MAX_COMMAND_RESULTS_MAP_SIZE=1e4,this.playerInternalEventHandler=new I.HydraPlayerInternalEventHandler}return e3.prototype.dispose=function(){var g;null===(g=this.telemetryReportHandler)||void 0===g||g.addDisposeTelemetry(),this.isIFrameCommunicationActive()&&this.callPlayerApi("disposeHydraPlayer")},e3.prototype.release=function(){var g;null===(g=this.spinner)||void 0===g||g.hide(),this.contextWindow&&this.contextWindow.removeEventListener("message",this.onMessage.bind(this)),this.iframeCommunicationHandler&&this.iframeCommunicationHandler.dispose(),this.iframe&&this.container&&this.container.hasChildNodes()&&this.container.removeChild(this.iframe)},e3.prototype.setup=function(g){return v(this,void 0,void 0,(function(){var f,S,v,T,I,b,R,M;return C(this,(function(C){switch(C.label){case 0:f=Date.now(),this.container=g,S=null,C.label=1;case 1:return C.trys.push([1,14,,15]),this.spinner=new P.Spinner(this.container),this.playerInternalEventHandler.setSpinner(this.spinner),[4,this.initializeIFrame()];case 2:if(!(S=C.sent()).isSuccess)return[3,12];v={initSucceeded:!0,initStartTime:f,initDuration:Date.now()-f,runtimeDownloadResults:S.runtimeDownloadResults||[]},C.label=3;case 3:return C.trys.push([3,5,,11]),[4,this.callPlayerApi("createHydraPlayer",this.playerSettings,v)];case 4:return C.sent(),[3,11];case 5:return T=C.sent(),this.eventHandler.log("warn","Failed to create HydraPlayer: ".concat(T)),this.playerSettings.playerType!==_.HydraPlayerType.Hls?[3,7]:[4,this.callPlayerApi("createHlsHydraPlayer",this.playerSettings,v)];case 6:return C.sent(),[3,10];case 7:return this.playerSettings.playerType!==_.HydraPlayerType.Ums?[3,9]:[4,this.callPlayerApi("createUmsHydraPlayer",this.playerSettings,v)];case 8:return C.sent(),[3,10];case 9:throw new Error("Cannot create Hydra player - Unknown player type");case 10:return[3,11];case 11:return this.onSetupCompleted(v),[2,!0];case 12:throw new Error(S.errorMsg);case 13:return[3,15];case 14:I=C.sent(),b=(0,A.stringifyObject)(I),this.eventHandler.log("error","Failed to setup HydraPlayer: ".concat(b)),R={initSucceeded:!1,initStartTime:f,initDuration:Date.now()-f,runtimeDownloadResults:(null==S?void 0:S.runtimeDownloadResults)||[],errorMsg:b};try{null===(M=this.spinner)||void 0===M||M.hide()}catch(g){this.eventHandler.log("error","Failed to hide spinner: ".concat((0,A.stringifyObject)(g)))}return this.onSetupCompleted(R),[2,!1];case 15:return[2]}}))}))},e3.prototype.onSetupCompleted=function(g){this.telemetryReportHandler=new b.TelemetryReportHandler(this.playerSettings,this.eventHandler.log.bind(this.eventHandler),g,this.spinner),this.playerInternalEventHandler.setTelemetryReportHandler(this.telemetryReportHandler)},e3.prototype.getFullTelemetryReport=function(){var g;return(null===(g=this.telemetryReportHandler)||void 0===g?void 0:g.getFullTelemetryReport())||{}},e3.prototype.getSnapshotTelemetryReport=function(){var g;return(null===(g=this.telemetryReportHandler)||void 0===g?void 0:g.getSnapshotTelemetryReport())||{}},e3.prototype.callPlayerApi=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];return v(this,void 0,void 0,(function(){var S,v,_,I,b;return C(this,(function(C){switch(C.label){case 0:return this.iframe?[3,2]:[4,Promise.reject(new Error("Hydra IFrame not initialized yet"))];case 1:case 3:return[2,C.sent()];case 2:if(S=(0,w.default)(),v={msgType:T.MessageType.Command,id:S,name:g,args:f},!this.isIFrameCommunicationActive())throw new Error("IFrame MessageAPI communication not active");if(this.commandResultsMap.size>=this.MAX_COMMAND_RESULTS_MAP_SIZE)throw new Error("Too many Hydra player API commands in progress - skipping this player API call");return _=R.defer(),I={name:g,id:S},this.commandResultsMap.set(I,_),null===(b=this.iframe.contentWindow)||void 0===b||b.postMessage(v,"*"),[4,_.promise]}}))}))},Object.defineProperty(e3.prototype,"contextWindow",{get:function(){var g;return null===(g=this.container)||void 0===g?void 0:g.ownerDocument.defaultView},enumerable:!1,configurable:!0}),e3.prototype.isIFrameCommunicationActive=function(){var g;return!!(null===(g=this.iframe)||void 0===g?void 0:g.contentWindow)&&!!this.contextWindow},e3.prototype.getRuntimeUrls=function(g){if(!Array.isArray(this.playerSettings.playerRuntimeJsUrls)){var f=(0,A.getMajorFromVersion)(g);return f&&this.playerSettings.playerRuntimeJsUrls[f]||[]}return this.playerSettings.playerRuntimeJsUrls},e3.prototype.initializeIFrame=function(){return v(this,void 0,void 0,(function(){var g;return C(this,(function(f){switch(f.label){case 0:return this.playerSettings.hydraPlayerSdkVersion="4.2521.1",this.playerRuntimeUrls=this.getRuntimeUrls(this.playerSettings.hydraPlayerSdkVersion),0!==this.playerRuntimeUrls.length&&this.container?[4,(0,A.createIFrame)(this.container,this.playerRuntimeUrls,this.playerSettings)]:[2,{isSuccess:!1,runtimeDownloadResults:[],errorMsg:"No compatible runtime URLs provided for HydraPlayer SDK version:\n                    ".concat(this.playerSettings.hydraPlayerSdkVersion,", URLs:\n                    ").concat((0,A.stringifyObject)(this.playerSettings.playerRuntimeJsUrls))}];case 1:return(g=f.sent()).initResult.isSuccess&&g.iframe&&(this.iframe=g.iframe,this.iframeCommunicationHandler=new M.IframeCommunicationHandler(this.iframe,this.playerSettings,this.eventHandler.log),this.contextWindow.addEventListener("message",this.onMessage.bind(this))),[2,g.initResult]}}))}))},e3.prototype.onMessage=function(g){switch(g.data.msgType){case T.MessageType.PlayerEvent:this.processPlayerEvent(g.data);break;case T.MessageType.InternalPlayerEvent:this.processInternalPlayerEvent(g.data);break;case T.MessageType.CommandSuccessResult:this.processCommandSuccessResult(g.data);break;case T.MessageType.CommandFailureResult:this.processCommandFailureResult(g.data)}},e3.prototype.processCommandSuccessResult=function(g){var f=this;this.eventHandler.log("debug","HydraPlayer command succeeded for ".concat(g.name," - result: ").concat((0,A.stringifyObject)(g.result))),this.getMapCommandResults(g).forEach((function(S){S[1].resolve(g.result),f.commandResultsMap.delete(S[0])}))},e3.prototype.processCommandFailureResult=function(g){var f=this;this.eventHandler.log("debug","HydraPlayer command failed for ".concat(g.name," - error: ").concat(g.error.message)),this.getMapCommandResults(g).forEach((function(S){S[1].reject(g.error),f.commandResultsMap.delete(S[0])}))},e3.prototype.getMapCommandResults=function(g){var f=Array.from(this.commandResultsMap.entries()),S=[];return g.id?S=f.filter((function(f){return f[0].id===g.id})):g.name&&(S=f.filter((function(f){return f[0].name===g.name}))),S},e3.prototype.processPlayerEvent=function(g){var f;null===(f=this.eventHandler[g.name])||void 0===f||f.apply(this.eventHandler,g.args)},e3.prototype.processInternalPlayerEvent=function(g){this.playerInternalEventHandler&&this.playerInternalEventHandler[g.name].apply(this,g.args)},e3}();f.HydraPlayer=O},282:function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.IframeCommunicationHandler=void 0;var v=S(346),C=S(735),_=function(){function e3(g,f,S){var v=this;this.iframe=g,this.playerSettings=f,this.logger=S,this.setupMessageListener(),this.candidatesCollector=new C.WebRtcIceCandidateCollector(this.playerSettings),this.candidatesCollector.startCandidatesCollection().catch((function(g){v.logger("warn","Failed to start collecting ICE candidates ".concat(g))}))}return e3.prototype.setupMessageListener=function(){var g;null===(g=this.iframe.ownerDocument.defaultView)||void 0===g||g.addEventListener("message",this.processMessage.bind(this))},e3.prototype.postMessageToIframe=function(g){var f;null===(f=this.iframe.contentWindow)||void 0===f||f.postMessage(g,"*")},e3.prototype.dispose=function(){var g;null===(g=this.iframe.ownerDocument.defaultView)||void 0===g||g.removeEventListener("message",this.processMessage.bind(this)),this.candidatesCollector&&this.candidatesCollector.destroy()},e3.prototype.processMessage=function(g){var f=this;g.data===v.IframeMessages.RequestIceCandidates&&void 0===g.data.candidates&&this.candidatesCollector.getCandidates().then((function(g){var S=JSON.stringify(g.map((function(g){return JSON.stringify(g)})));f.postMessageToIframe({topic:v.IframeMessages.RequestIceCandidates,candidates:S})})).catch((function(){f.postMessageToIframe({topic:v.IframeMessages.RequestIceCandidates,candidates:[]})}))},e3}();f.IframeCommunicationHandler=_},260:function(g,f,S){var v=this&&this.__createBinding||(Object.create?function(g,f,S,v){void 0===v&&(v=S);var C=Object.getOwnPropertyDescriptor(f,S);C&&!("get"in C?!f.__esModule:C.writable||C.configurable)||(C={enumerable:!0,get:function(){return f[S]}}),Object.defineProperty(g,v,C)}:function(g,f,S,v){void 0===v&&(v=S),g[v]=f[S]}),C=this&&this.__exportStar||function(g,f){for(var S in g)"default"===S||Object.prototype.hasOwnProperty.call(f,S)||v(f,g,S)};Object.defineProperty(f,"__esModule",{value:!0}),C(S(521),f),C(S(564),f)},715:function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.HydraPlayerInternalEventHandler=void 0;var S=function(){function e3(){this.spinner=null,this.telemetryReportHandler=null}return e3.prototype.setSpinner=function(g){this.spinner=g},e3.prototype.setTelemetryReportHandler=function(g){this.telemetryReportHandler=g},e3.prototype.firstPlayerLoadAttemptDone=function(){var g;null===(g=this.spinner)||void 0===g||g.hide()},e3.prototype.fullTelemetryReportUpdated=function(g){var f;null===(f=this.telemetryReportHandler)||void 0===f||f.setFullTelemetryReport(g)},e3.prototype.snapshotTelemetryReportUpdated=function(g){var f;null===(f=this.telemetryReportHandler)||void 0===f||f.setSnapshotTelemetryReport(g)},e3}();f.HydraPlayerInternalEventHandler=S},357:function(g,f,S){var v=this&&this.__assign||function(){return v=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},v.apply(this,arguments)};Object.defineProperty(f,"__esModule",{value:!0}),f.TelemetryReportHandler=void 0;var C=S(346),_=S(176),T=S(963),I=S(171),b=S(534),A=function(){function e3(g,f,S,v){var _=this;this.logFn=f,this.spinner=v,this.initialLiveStreamStatistic=new I.LiveStreamStatistic(g,(function(g,f){_.logFn(g,f)}),{videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],statsInterval:[]},{hydraPlayerSdkVersion:g.hydraPlayerSdkVersion||"Unknown",hydraPlayerType:C.HydraPlayerType.Hls}),this.initialLiveStreamStatistic.setHydraInitResult(S),this.fullTelemetryReport=this.initialLiveStreamStatistic.getReport(),this.snapshotTelemetryReport=this.initialLiveStreamStatistic.getSnapshotReport()}return e3.prototype.getFullTelemetryReport=function(){return this.fullTelemetryReport},e3.prototype.getSnapshotTelemetryReport=function(){return this.snapshotTelemetryReport},e3.prototype.setFullTelemetryReport=function(g){var f,S,C,_,T,I,b;this.fullTelemetryReport=v(v({},g),{init_spinnerShowTimestamp:null!==(S=null===(f=this.spinner)||void 0===f?void 0:f.firstShowTimestamp)&&void 0!==S?S:-1,init_spinnerHideTimestamp:null!==(_=null===(C=this.spinner)||void 0===C?void 0:C.firstHideTimestamp)&&void 0!==_?_:-1,init_spinnerDuration:null!==(I=null===(T=this.spinner)||void 0===T?void 0:T.firstSpinnerDuration)&&void 0!==I?I:-1,init_spinnerVisible:(null===(b=this.spinner)||void 0===b?void 0:b.isVisible())||!1})},e3.prototype.setSnapshotTelemetryReport=function(g){var f,S,C,_,T,I,b;this.snapshotTelemetryReport=v(v({},g),{init_spinnerShowTimestamp:null!==(S=null===(f=this.spinner)||void 0===f?void 0:f.firstShowTimestamp)&&void 0!==S?S:-1,init_spinnerHideTimestamp:null!==(_=null===(C=this.spinner)||void 0===C?void 0:C.firstHideTimestamp)&&void 0!==_?_:-1,init_spinnerDuration:null!==(I=null===(T=this.spinner)||void 0===T?void 0:T.firstSpinnerDuration)&&void 0!==I?I:-1,init_spinnerVisible:(null===(b=this.spinner)||void 0===b?void 0:b.isVisible())||!1})},e3.prototype.addDisposeTelemetry=function(){var g=Date.now();this.updateInitEventsWithDisposeEvent(this.fullTelemetryReport,g,"full"),this.updateInitEventsWithDisposeEvent(this.snapshotTelemetryReport,g,"snapshot"),this.updateStateChangeEventsWithDisposeEvent(this.fullTelemetryReport,g,"full"),this.updateStateChangeEventsWithDisposeEvent(this.snapshotTelemetryReport,g,"snapshot")},e3.prototype.updateInitEventsWithDisposeEvent=function(g,f,S){try{var v=g.init_allEvents,C=JSON.parse(v);C[C.length-1].name!==T.PlayerScenarioType.Destroyed&&C.push({name:T.PlayerScenarioType.Destroyed,startTime:f,duration:0,details:_.HydraPlayerDestroyedReason.PlayerStopped}),g.init_allEvents=(0,b.stringifyObject)(C)}catch(g){this.logFn("warn","Failed to add player destroyed information to init_allEvents telemetry field in ".concat(S," telemetry report."))}},e3.prototype.updateStateChangeEventsWithDisposeEvent=function(g,f,S){try{var v=g.playback_stateChangeEvents,_=JSON.parse(v);_[_.length-1].name!==C.HydraPlayerPlaybackState.Destroyed&&_.push({eventType:T.TelemetryEventType.StateChanged,timestamp:f,currentPlayPosition:-1,payload:C.HydraPlayerPlaybackState.Destroyed}),g.playback_stateChangeEvents=(0,b.stringifyObject)(_)}catch(g){this.logFn("warn","Failed to add player destroyed information to playback_stateChangeEvents telemetry field in ".concat(S," telemetry report."))}},e3}();f.TelemetryReportHandler=A},735:function(g,f,S){var v=this&&this.__awaiter||function(g,f,S,v){return new(S||(S=Promise))((function(C,_){function o2(g){try{l2(v.next(g))}catch(g){_(g)}}function s2(g){try{l2(v.throw(g))}catch(g){_(g)}}function l2(g){var f;g.done?C(g.value):(f=g.value,f instanceof S?f:new S((function(g){g(f)}))).then(o2,s2)}l2((v=v.apply(g,f||[])).next())}))},C=this&&this.__generator||function(g,f){var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:s2(0),throw:s2(1),return:s2(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_;function s2(I){return function(b){return function(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!((C=(C=T.trys).length>0&&C[C.length-1])||6!==I[0]&&2!==I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}([I,b])}}},_=this&&this.__spreadArray||function(g,f,S){if(S||2===arguments.length)for(var v,C=0,_=f.length;C<_;C++)!v&&C in f||(v||(v=Array.prototype.slice.call(f,0,C)),v[C]=f[C]);return g.concat(v||Array.prototype.slice.call(f))};Object.defineProperty(f,"__esModule",{value:!0}),f.WebRtcIceCandidateCollector=void 0;var T=S(103),I=S(534),b=S(508),A=function(){function e3(g){this.playerSettings=g,this.latestCandidates=[],this.newCandidates=[],this.peerConnection=null,this.timeoutId=void 0,this.candidatesCollectionDefer=null,this.delayAfterComplete=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDelayAfterCompleteMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDelayAfterCompleteMs),this.delayAfterError=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDelayAfterErrorMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDelayAfterErrorMs),this.maxRetries=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorMaxRetriesMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorMaxRetriesMs),this.retryDelay=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorRetryDelayMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorRetryDelayMs),this.maxCollectionTime=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorMaxCollectionTimeMs",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorMaxCollectionTimeMs),this.disabledCollection=(0,I.getECSSetting)(this.playerSettings,"WebRtcIceCandidateCollectorDisableCollection",b.webRtcIceCandidateCollectorConfigDefault.WebRtcIceCandidateCollectorDisableCollection)}return e3.prototype.handleIceCandidate=function(g){g.candidate&&this.newCandidates.push(g.candidate)},e3.prototype.handleIceGatheringStateChange=function(){var g,f;"complete"===(null===(g=this.peerConnection)||void 0===g?void 0:g.iceGatheringState)&&(this.latestCandidates=_([],this.newCandidates,!0),this.newCandidates=[],null===(f=this.candidatesCollectionDefer)||void 0===f||f.resolve(),this.candidatesCollectionDefer=null,this.destroyConnection(),this.clearCollectionTimeout(),this.startCandidatesCollection(this.delayAfterComplete))},e3.prototype.setUpPeerConnection=function(){return v(this,void 0,void 0,(function(){var g,f,S,v;return C(this,(function(C){switch(C.label){case 0:return C.trys.push([0,3,,4]),this.peerConnection=new RTCPeerConnection,this.peerConnection.createDataChannel("local-ip-hydra-player-ice-candidates"),this.peerConnection.addEventListener("icecandidate",this.handleIceCandidate.bind(this)),this.peerConnection.addEventListener("icegatheringstatechange",this.handleIceGatheringStateChange.bind(this)),[4,null===(S=this.peerConnection)||void 0===S?void 0:S.createOffer()];case 1:return g=C.sent(),[4,null===(v=this.peerConnection)||void 0===v?void 0:v.setLocalDescription(g)];case 2:return C.sent(),[3,4];case 3:throw f=C.sent(),this.destroyConnection(),new Error("Failure starting collection: ".concat((0,I.stringifyError)(f)));case 4:return[2]}}))}))},e3.prototype.destroyConnection=function(){this.peerConnection&&(this.peerConnection.removeEventListener("icecandidate",this.handleIceCandidate.bind(this)),this.peerConnection.removeEventListener("icegatheringstatechange",this.handleIceGatheringStateChange.bind(this)),this.peerConnection.close(),this.peerConnection=null)},e3.prototype.clearCollectionTimeout=function(){void 0!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0)},e3.prototype.destroy=function(){this.disabledCollection=!0,this.destroyConnection(),this.clearCollectionTimeout(),this.candidatesCollectionDefer&&(this.candidatesCollectionDefer.reject(new Error("Collection aborted due to destroy")),this.candidatesCollectionDefer=null)},e3.prototype.startCandidatesCollection=function(){return v(this,arguments,void 0,(function(g){var f,S=this;return void 0===g&&(g=0),C(this,(function(_){switch(_.label){case 0:return this.candidatesCollectionDefer||this.disabledCollection?[2]:g>0?[4,new Promise((function(f){return setTimeout(f,g)}))]:[3,2];case 1:_.sent(),_.label=2;case 2:return this.candidatesCollectionDefer=(0,T.defer)(),this.candidatesCollectionDefer.promise.catch((function(){})),f=this.setUpPeerConnection.bind(this),[4,(0,I.retry)(f,this.maxRetries,this.retryDelay).then((function(){S.timeoutId=setTimeout((function(){var g;null===(g=S.candidatesCollectionDefer)||void 0===g||g.reject(new Error("Collection timed out")),S.candidatesCollectionDefer=null,S.destroyConnection(),S.startCandidatesCollection(S.delayAfterError)}),S.maxCollectionTime)})).catch((function(g){return v(S,void 0,void 0,(function(){var f,S;return C(this,(function(v){switch(v.label){case 0:return f="Failed to start collection ".concat((0,I.stringifyError)(g)),null===(S=this.candidatesCollectionDefer)||void 0===S||S.reject(new Error(f)),this.candidatesCollectionDefer=null,[4,Promise.reject(new Error(f))];case 1:return v.sent(),this.startCandidatesCollection(this.delayAfterError),[2]}}))}))}))];case 3:return _.sent(),[2]}}))}))},e3.prototype.getCandidates=function(){return v(this,void 0,void 0,(function(){return C(this,(function(g){switch(g.label){case 0:return 0===this.latestCandidates.length&&this.candidatesCollectionDefer?[4,this.candidatesCollectionDefer.promise]:[3,2];case 1:g.sent(),g.label=2;case 2:return[2,this.latestCandidates]}}))}))},e3}();f.WebRtcIceCandidateCollector=A}},f={},function n(S){var v=f[S];if(void 0!==v)return v.exports;var C=f[S]={exports:{}};return g[S].call(C.exports,C,C.exports,n),C.exports}(260);var g,f},"object"==typeof g&&"object"==typeof f?f.exports=v():"object"==typeof g?g.hydra_player_sdk=v():S.hydra_player_sdk=v()}}),se=__commonJS2({"../node_modules/pako/lib/utils/common.js"(g){var f="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function _has(g,f){return Object.prototype.hasOwnProperty.call(g,f)}g.assign=function(g){for(var f=Array.prototype.slice.call(arguments,1);f.length;){var S=f.shift();if(S){if("object"!=typeof S)throw new TypeError(S+"must be non-object");for(var v in S)_has(S,v)&&(g[v]=S[v])}}return g},g.shrinkBuf=function(g,f){return g.length===f?g:g.subarray?g.subarray(0,f):(g.length=f,g)};var S={arraySet:function(g,f,S,v,C){if(f.subarray&&g.subarray)g.set(f.subarray(S,S+v),C);else for(var _=0;_<v;_++)g[C+_]=f[S+_]},flattenChunks:function(g){var f,S,v,C,_,T;for(v=0,f=0,S=g.length;f<S;f++)v+=g[f].length;for(T=new Uint8Array(v),C=0,f=0,S=g.length;f<S;f++)_=g[f],T.set(_,C),C+=_.length;return T}},v={arraySet:function(g,f,S,v,C){for(var _=0;_<v;_++)g[C+_]=f[S+_]},flattenChunks:function(g){return[].concat.apply([],g)}};g.setTyped=function(f){f?(g.Buf8=Uint8Array,g.Buf16=Uint16Array,g.Buf32=Int32Array,g.assign(g,S)):(g.Buf8=Array,g.Buf16=Array,g.Buf32=Array,g.assign(g,v))},g.setTyped(f)}}),ae=__commonJS2({"../node_modules/pako/lib/zlib/trees.js"(g){var f=se(),S=4,v=0,C=1,_=2;function zero(g){for(var f=g.length;--f>=0;)g[f]=0}var T=0,I=1,b=2,A=3,P=258,R=29,M=256,w=M+1+R,O=30,D=19,N=2*w+1,k=15,L=16,F=7,x=256,U=16,V=17,B=18,H=[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],$=[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],j=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],G=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],q=512,W=new Array(2*(w+2));zero(W);var z=new Array(2*O);zero(z);var K=new Array(q);zero(K);var J=new Array(P-A+1);zero(J);var Y=new Array(R);zero(Y);var Q,X,Z,ee=new Array(O);function StaticTreeDesc(g,f,S,v,C){this.static_tree=g,this.extra_bits=f,this.extra_base=S,this.elems=v,this.max_length=C,this.has_stree=g&&g.length}function TreeDesc(g,f){this.dyn_tree=g,this.max_code=0,this.stat_desc=f}function d_code(g){return g<256?K[g]:K[256+(g>>>7)]}function put_short(g,f){g.pending_buf[g.pending++]=255&f,g.pending_buf[g.pending++]=f>>>8&255}function send_bits(g,f,S){g.bi_valid>L-S?(g.bi_buf|=f<<g.bi_valid&65535,put_short(g,g.bi_buf),g.bi_buf=f>>L-g.bi_valid,g.bi_valid+=S-L):(g.bi_buf|=f<<g.bi_valid&65535,g.bi_valid+=S)}function send_code(g,f,S){send_bits(g,S[2*f],S[2*f+1])}function bi_reverse(g,f){var S=0;do{S|=1&g,g>>>=1,S<<=1}while(--f>0);return S>>>1}function bi_flush(g){16===g.bi_valid?(put_short(g,g.bi_buf),g.bi_buf=0,g.bi_valid=0):g.bi_valid>=8&&(g.pending_buf[g.pending++]=255&g.bi_buf,g.bi_buf>>=8,g.bi_valid-=8)}function gen_bitlen(g,f){var S,v,C,_,T,I,b=f.dyn_tree,A=f.max_code,P=f.stat_desc.static_tree,R=f.stat_desc.has_stree,M=f.stat_desc.extra_bits,w=f.stat_desc.extra_base,O=f.stat_desc.max_length,D=0;for(_=0;_<=k;_++)g.bl_count[_]=0;for(b[2*g.heap[g.heap_max]+1]=0,S=g.heap_max+1;S<N;S++)(_=b[2*b[2*(v=g.heap[S])+1]+1]+1)>O&&(_=O,D++),b[2*v+1]=_,v>A||(g.bl_count[_]++,T=0,v>=w&&(T=M[v-w]),I=b[2*v],g.opt_len+=I*(_+T),R&&(g.static_len+=I*(P[2*v+1]+T)));if(0!==D){do{for(_=O-1;0===g.bl_count[_];)_--;g.bl_count[_]--,g.bl_count[_+1]+=2,g.bl_count[O]--,D-=2}while(D>0);for(_=O;0!==_;_--)for(v=g.bl_count[_];0!==v;)(C=g.heap[--S])>A||(b[2*C+1]!==_&&(g.opt_len+=(_-b[2*C+1])*b[2*C],b[2*C+1]=_),v--)}}function gen_codes(g,f,S){var v,C,_=new Array(k+1),T=0;for(v=1;v<=k;v++)_[v]=T=T+S[v-1]<<1;for(C=0;C<=f;C++){var I=g[2*C+1];0!==I&&(g[2*C]=bi_reverse(_[I]++,I))}}function tr_static_init(){var g,f,S,v,C,_=new Array(k+1);for(S=0,v=0;v<R-1;v++)for(Y[v]=S,g=0;g<1<<H[v];g++)J[S++]=v;for(J[S-1]=v,C=0,v=0;v<16;v++)for(ee[v]=C,g=0;g<1<<$[v];g++)K[C++]=v;for(C>>=7;v<O;v++)for(ee[v]=C<<7,g=0;g<1<<$[v]-7;g++)K[256+C++]=v;for(f=0;f<=k;f++)_[f]=0;for(g=0;g<=143;)W[2*g+1]=8,g++,_[8]++;for(;g<=255;)W[2*g+1]=9,g++,_[9]++;for(;g<=279;)W[2*g+1]=7,g++,_[7]++;for(;g<=287;)W[2*g+1]=8,g++,_[8]++;for(gen_codes(W,w+1,_),g=0;g<O;g++)z[2*g+1]=5,z[2*g]=bi_reverse(g,5);Q=new StaticTreeDesc(W,H,M+1,w,k),X=new StaticTreeDesc(z,$,0,O,k),Z=new StaticTreeDesc(new Array(0),j,0,D,F)}function init_block(g){var f;for(f=0;f<w;f++)g.dyn_ltree[2*f]=0;for(f=0;f<O;f++)g.dyn_dtree[2*f]=0;for(f=0;f<D;f++)g.bl_tree[2*f]=0;g.dyn_ltree[2*x]=1,g.opt_len=g.static_len=0,g.last_lit=g.matches=0}function bi_windup(g){g.bi_valid>8?put_short(g,g.bi_buf):g.bi_valid>0&&(g.pending_buf[g.pending++]=g.bi_buf),g.bi_buf=0,g.bi_valid=0}function copy_block(g,S,v,C){bi_windup(g),C&&(put_short(g,v),put_short(g,~v)),f.arraySet(g.pending_buf,g.window,S,v,g.pending),g.pending+=v}function smaller(g,f,S,v){var C=2*f,_=2*S;return g[C]<g[_]||g[C]===g[_]&&v[f]<=v[S]}function pqdownheap(g,f,S){for(var v=g.heap[S],C=S<<1;C<=g.heap_len&&(C<g.heap_len&&smaller(f,g.heap[C+1],g.heap[C],g.depth)&&C++,!smaller(f,v,g.heap[C],g.depth));)g.heap[S]=g.heap[C],S=C,C<<=1;g.heap[S]=v}function compress_block(g,f,S){var v,C,_,T,I=0;if(0!==g.last_lit)do{v=g.pending_buf[g.d_buf+2*I]<<8|g.pending_buf[g.d_buf+2*I+1],C=g.pending_buf[g.l_buf+I],I++,0===v?send_code(g,C,f):(send_code(g,(_=J[C])+M+1,f),0!==(T=H[_])&&send_bits(g,C-=Y[_],T),send_code(g,_=d_code(--v),S),0!==(T=$[_])&&send_bits(g,v-=ee[_],T))}while(I<g.last_lit);send_code(g,x,f)}function build_tree(g,f){var S,v,C,_=f.dyn_tree,T=f.stat_desc.static_tree,I=f.stat_desc.has_stree,b=f.stat_desc.elems,A=-1;for(g.heap_len=0,g.heap_max=N,S=0;S<b;S++)0!==_[2*S]?(g.heap[++g.heap_len]=A=S,g.depth[S]=0):_[2*S+1]=0;for(;g.heap_len<2;)_[2*(C=g.heap[++g.heap_len]=A<2?++A:0)]=1,g.depth[C]=0,g.opt_len--,I&&(g.static_len-=T[2*C+1]);for(f.max_code=A,S=g.heap_len>>1;S>=1;S--)pqdownheap(g,_,S);C=b;do{S=g.heap[1],g.heap[1]=g.heap[g.heap_len--],pqdownheap(g,_,1),v=g.heap[1],g.heap[--g.heap_max]=S,g.heap[--g.heap_max]=v,_[2*C]=_[2*S]+_[2*v],g.depth[C]=(g.depth[S]>=g.depth[v]?g.depth[S]:g.depth[v])+1,_[2*S+1]=_[2*v+1]=C,g.heap[1]=C++,pqdownheap(g,_,1)}while(g.heap_len>=2);g.heap[--g.heap_max]=g.heap[1],gen_bitlen(g,f),gen_codes(_,A,g.bl_count)}function scan_tree(g,f,S){var v,C,_=-1,T=f[1],I=0,b=7,A=4;for(0===T&&(b=138,A=3),f[2*(S+1)+1]=65535,v=0;v<=S;v++)C=T,T=f[2*(v+1)+1],++I<b&&C===T||(I<A?g.bl_tree[2*C]+=I:0!==C?(C!==_&&g.bl_tree[2*C]++,g.bl_tree[2*U]++):I<=10?g.bl_tree[2*V]++:g.bl_tree[2*B]++,I=0,_=C,0===T?(b=138,A=3):C===T?(b=6,A=3):(b=7,A=4))}function send_tree(g,f,S){var v,C,_=-1,T=f[1],I=0,b=7,A=4;for(0===T&&(b=138,A=3),v=0;v<=S;v++)if(C=T,T=f[2*(v+1)+1],!(++I<b&&C===T)){if(I<A)do{send_code(g,C,g.bl_tree)}while(0!=--I);else 0!==C?(C!==_&&(send_code(g,C,g.bl_tree),I--),send_code(g,U,g.bl_tree),send_bits(g,I-3,2)):I<=10?(send_code(g,V,g.bl_tree),send_bits(g,I-3,3)):(send_code(g,B,g.bl_tree),send_bits(g,I-11,7));I=0,_=C,0===T?(b=138,A=3):C===T?(b=6,A=3):(b=7,A=4)}}function build_bl_tree(g){var f;for(scan_tree(g,g.dyn_ltree,g.l_desc.max_code),scan_tree(g,g.dyn_dtree,g.d_desc.max_code),build_tree(g,g.bl_desc),f=D-1;f>=3&&0===g.bl_tree[2*G[f]+1];f--);return g.opt_len+=3*(f+1)+5+5+4,f}function send_all_trees(g,f,S,v){var C;for(send_bits(g,f-257,5),send_bits(g,S-1,5),send_bits(g,v-4,4),C=0;C<v;C++)send_bits(g,g.bl_tree[2*G[C]+1],3);send_tree(g,g.dyn_ltree,f-1),send_tree(g,g.dyn_dtree,S-1)}function detect_data_type(g){var f,S=4093624447;for(f=0;f<=31;f++,S>>>=1)if(1&S&&0!==g.dyn_ltree[2*f])return v;if(0!==g.dyn_ltree[18]||0!==g.dyn_ltree[20]||0!==g.dyn_ltree[26])return C;for(f=32;f<M;f++)if(0!==g.dyn_ltree[2*f])return C;return v}zero(ee);var te=!1;function _tr_init(g){te||(tr_static_init(),te=!0),g.l_desc=new TreeDesc(g.dyn_ltree,Q),g.d_desc=new TreeDesc(g.dyn_dtree,X),g.bl_desc=new TreeDesc(g.bl_tree,Z),g.bi_buf=0,g.bi_valid=0,init_block(g)}function _tr_stored_block(g,f,S,v){send_bits(g,(T<<1)+(v?1:0),3),copy_block(g,f,S,!0)}function _tr_align(g){send_bits(g,I<<1,3),send_code(g,x,W),bi_flush(g)}function _tr_flush_block(g,f,v,C){var T,A,P=0;g.level>0?(g.strm.data_type===_&&(g.strm.data_type=detect_data_type(g)),build_tree(g,g.l_desc),build_tree(g,g.d_desc),P=build_bl_tree(g),T=g.opt_len+3+7>>>3,(A=g.static_len+3+7>>>3)<=T&&(T=A)):T=A=v+5,v+4<=T&&-1!==f?_tr_stored_block(g,f,v,C):g.strategy===S||A===T?(send_bits(g,(I<<1)+(C?1:0),3),compress_block(g,W,z)):(send_bits(g,(b<<1)+(C?1:0),3),send_all_trees(g,g.l_desc.max_code+1,g.d_desc.max_code+1,P+1),compress_block(g,g.dyn_ltree,g.dyn_dtree)),init_block(g),C&&bi_windup(g)}function _tr_tally(g,f,S){return g.pending_buf[g.d_buf+2*g.last_lit]=f>>>8&255,g.pending_buf[g.d_buf+2*g.last_lit+1]=255&f,g.pending_buf[g.l_buf+g.last_lit]=255&S,g.last_lit++,0===f?g.dyn_ltree[2*S]++:(g.matches++,f--,g.dyn_ltree[2*(J[S]+M+1)]++,g.dyn_dtree[2*d_code(f)]++),g.last_lit===g.lit_bufsize-1}g._tr_init=_tr_init,g._tr_stored_block=_tr_stored_block,g._tr_flush_block=_tr_flush_block,g._tr_tally=_tr_tally,g._tr_align=_tr_align}}),oe=__commonJS2({"../node_modules/pako/lib/zlib/adler32.js"(g,f){function adler32(g,f,S,v){for(var C=65535&g|0,_=g>>>16&65535|0,T=0;0!==S;){S-=T=S>2e3?2e3:S;do{_=_+(C=C+f[v++]|0)|0}while(--T);C%=65521,_%=65521}return C|_<<16|0}f.exports=adler32}}),le=__commonJS2({"../node_modules/pako/lib/zlib/crc32.js"(g,f){function makeTable(){for(var g,f=[],S=0;S<256;S++){g=S;for(var v=0;v<8;v++)g=1&g?3988292384^g>>>1:g>>>1;f[S]=g}return f}var S=makeTable();function crc32(g,f,v,C){var _=S,T=C+v;g^=-1;for(var I=C;I<T;I++)g=g>>>8^_[255&(g^f[I])];return-1^g}f.exports=crc32}}),ce=__commonJS2({"../node_modules/pako/lib/zlib/messages.js"(g,f){f.exports={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"}}}),de=__commonJS2({"../node_modules/pako/lib/zlib/deflate.js"(g){var f,S=se(),v=ae(),C=oe(),_=le(),T=ce(),I=0,b=1,A=3,P=4,R=5,M=0,w=1,O=-2,D=-3,N=-5,k=-1,L=1,F=2,x=3,U=4,V=0,B=2,H=8,$=9,j=15,G=8,q=286,W=30,z=19,K=2*q+1,J=15,Y=3,Q=258,X=Q+Y+1,Z=32,ee=42,te=69,ie=73,ne=91,re=103,de=113,he=666,ue=1,ge=2,pe=3,me=4,fe=3;function err(g,f){return g.msg=T[f],f}function rank(g){return(g<<1)-(g>4?9:0)}function zero(g){for(var f=g.length;--f>=0;)g[f]=0}function flush_pending(g){var f=g.state,v=f.pending;v>g.avail_out&&(v=g.avail_out),0!==v&&(S.arraySet(g.output,f.pending_buf,f.pending_out,v,g.next_out),g.next_out+=v,f.pending_out+=v,g.total_out+=v,g.avail_out-=v,f.pending-=v,0===f.pending&&(f.pending_out=0))}function flush_block_only(g,f){v._tr_flush_block(g,g.block_start>=0?g.block_start:-1,g.strstart-g.block_start,f),g.block_start=g.strstart,flush_pending(g.strm)}function put_byte(g,f){g.pending_buf[g.pending++]=f}function putShortMSB(g,f){g.pending_buf[g.pending++]=f>>>8&255,g.pending_buf[g.pending++]=255&f}function read_buf(g,f,v,T){var I=g.avail_in;return I>T&&(I=T),0===I?0:(g.avail_in-=I,S.arraySet(f,g.input,g.next_in,I,v),1===g.state.wrap?g.adler=C(g.adler,f,I,v):2===g.state.wrap&&(g.adler=_(g.adler,f,I,v)),g.next_in+=I,g.total_in+=I,I)}function longest_match(g,f){var S,v,C=g.max_chain_length,_=g.strstart,T=g.prev_length,I=g.nice_match,b=g.strstart>g.w_size-X?g.strstart-(g.w_size-X):0,A=g.window,P=g.w_mask,R=g.prev,M=g.strstart+Q,w=A[_+T-1],O=A[_+T];g.prev_length>=g.good_match&&(C>>=2),I>g.lookahead&&(I=g.lookahead);do{if(A[(S=f)+T]===O&&A[S+T-1]===w&&A[S]===A[_]&&A[++S]===A[_+1]){_+=2,S++;do{}while(A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&A[++_]===A[++S]&&_<M);if(v=Q-(M-_),_=M-Q,v>T){if(g.match_start=f,T=v,v>=I)break;w=A[_+T-1],O=A[_+T]}}}while((f=R[f&P])>b&&0!=--C);return T<=g.lookahead?T:g.lookahead}function fill_window(g){var f,v,C,_,T,I=g.w_size;do{if(_=g.window_size-g.lookahead-g.strstart,g.strstart>=I+(I-X)){S.arraySet(g.window,g.window,I,I,0),g.match_start-=I,g.strstart-=I,g.block_start-=I,f=v=g.hash_size;do{C=g.head[--f],g.head[f]=C>=I?C-I:0}while(--v);f=v=I;do{C=g.prev[--f],g.prev[f]=C>=I?C-I:0}while(--v);_+=I}if(0===g.strm.avail_in)break;if(v=read_buf(g.strm,g.window,g.strstart+g.lookahead,_),g.lookahead+=v,g.lookahead+g.insert>=Y)for(T=g.strstart-g.insert,g.ins_h=g.window[T],g.ins_h=(g.ins_h<<g.hash_shift^g.window[T+1])&g.hash_mask;g.insert&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[T+Y-1])&g.hash_mask,g.prev[T&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=T,T++,g.insert--,!(g.lookahead+g.insert<Y)););}while(g.lookahead<X&&0!==g.strm.avail_in)}function deflate_stored(g,f){var S=65535;for(S>g.pending_buf_size-5&&(S=g.pending_buf_size-5);;){if(g.lookahead<=1){if(fill_window(g),0===g.lookahead&&f===I)return ue;if(0===g.lookahead)break}g.strstart+=g.lookahead,g.lookahead=0;var v=g.block_start+S;if((0===g.strstart||g.strstart>=v)&&(g.lookahead=g.strstart-v,g.strstart=v,flush_block_only(g,!1),0===g.strm.avail_out))return ue;if(g.strstart-g.block_start>=g.w_size-X&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}return g.insert=0,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):(g.strstart>g.block_start&&(flush_block_only(g,!1),g.strm.avail_out),ue)}function deflate_fast(g,f){for(var S,C;;){if(g.lookahead<X){if(fill_window(g),g.lookahead<X&&f===I)return ue;if(0===g.lookahead)break}if(S=0,g.lookahead>=Y&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+Y-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart),0!==S&&g.strstart-S<=g.w_size-X&&(g.match_length=longest_match(g,S)),g.match_length>=Y)if(C=v._tr_tally(g,g.strstart-g.match_start,g.match_length-Y),g.lookahead-=g.match_length,g.match_length<=g.max_lazy_match&&g.lookahead>=Y){g.match_length--;do{g.strstart++,g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+Y-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart}while(0!=--g.match_length);g.strstart++}else g.strstart+=g.match_length,g.match_length=0,g.ins_h=g.window[g.strstart],g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+1])&g.hash_mask;else C=v._tr_tally(g,0,g.window[g.strstart]),g.lookahead--,g.strstart++;if(C&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}return g.insert=g.strstart<Y-1?g.strstart:Y-1,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?ue:ge}function deflate_slow(g,f){for(var S,C,_;;){if(g.lookahead<X){if(fill_window(g),g.lookahead<X&&f===I)return ue;if(0===g.lookahead)break}if(S=0,g.lookahead>=Y&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+Y-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart),g.prev_length=g.match_length,g.prev_match=g.match_start,g.match_length=Y-1,0!==S&&g.prev_length<g.max_lazy_match&&g.strstart-S<=g.w_size-X&&(g.match_length=longest_match(g,S),g.match_length<=5&&(g.strategy===L||g.match_length===Y&&g.strstart-g.match_start>4096)&&(g.match_length=Y-1)),g.prev_length>=Y&&g.match_length<=g.prev_length){_=g.strstart+g.lookahead-Y,C=v._tr_tally(g,g.strstart-1-g.prev_match,g.prev_length-Y),g.lookahead-=g.prev_length-1,g.prev_length-=2;do{++g.strstart<=_&&(g.ins_h=(g.ins_h<<g.hash_shift^g.window[g.strstart+Y-1])&g.hash_mask,S=g.prev[g.strstart&g.w_mask]=g.head[g.ins_h],g.head[g.ins_h]=g.strstart)}while(0!=--g.prev_length);if(g.match_available=0,g.match_length=Y-1,g.strstart++,C&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}else if(g.match_available){if((C=v._tr_tally(g,0,g.window[g.strstart-1]))&&flush_block_only(g,!1),g.strstart++,g.lookahead--,0===g.strm.avail_out)return ue}else g.match_available=1,g.strstart++,g.lookahead--}return g.match_available&&(C=v._tr_tally(g,0,g.window[g.strstart-1]),g.match_available=0),g.insert=g.strstart<Y-1?g.strstart:Y-1,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?ue:ge}function deflate_rle(g,f){for(var S,C,_,T,b=g.window;;){if(g.lookahead<=Q){if(fill_window(g),g.lookahead<=Q&&f===I)return ue;if(0===g.lookahead)break}if(g.match_length=0,g.lookahead>=Y&&g.strstart>0&&(C=b[_=g.strstart-1])===b[++_]&&C===b[++_]&&C===b[++_]){T=g.strstart+Q;do{}while(C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&C===b[++_]&&_<T);g.match_length=Q-(T-_),g.match_length>g.lookahead&&(g.match_length=g.lookahead)}if(g.match_length>=Y?(S=v._tr_tally(g,1,g.match_length-Y),g.lookahead-=g.match_length,g.strstart+=g.match_length,g.match_length=0):(S=v._tr_tally(g,0,g.window[g.strstart]),g.lookahead--,g.strstart++),S&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}return g.insert=0,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?ue:ge}function deflate_huff(g,f){for(var S;;){if(0===g.lookahead&&(fill_window(g),0===g.lookahead)){if(f===I)return ue;break}if(g.match_length=0,S=v._tr_tally(g,0,g.window[g.strstart]),g.lookahead--,g.strstart++,S&&(flush_block_only(g,!1),0===g.strm.avail_out))return ue}return g.insert=0,f===P?(flush_block_only(g,!0),0===g.strm.avail_out?pe:me):g.last_lit&&(flush_block_only(g,!1),0===g.strm.avail_out)?ue:ge}function Config(g,f,S,v,C){this.good_length=g,this.max_lazy=f,this.nice_length=S,this.max_chain=v,this.func=C}function lm_init(g){g.window_size=2*g.w_size,zero(g.head),g.max_lazy_match=f[g.level].max_lazy,g.good_match=f[g.level].good_length,g.nice_match=f[g.level].nice_length,g.max_chain_length=f[g.level].max_chain,g.strstart=0,g.block_start=0,g.lookahead=0,g.insert=0,g.match_length=g.prev_length=Y-1,g.match_available=0,g.ins_h=0}function DeflateState(){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=H,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 S.Buf16(2*K),this.dyn_dtree=new S.Buf16(2*(2*W+1)),this.bl_tree=new S.Buf16(2*(2*z+1)),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new S.Buf16(J+1),this.heap=new S.Buf16(2*q+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new S.Buf16(2*q+1),zero(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(g){var f;return g&&g.state?(g.total_in=g.total_out=0,g.data_type=B,(f=g.state).pending=0,f.pending_out=0,f.wrap<0&&(f.wrap=-f.wrap),f.status=f.wrap?ee:de,g.adler=2===f.wrap?0:1,f.last_flush=I,v._tr_init(f),M):err(g,O)}function deflateReset(g){var f=deflateResetKeep(g);return f===M&&lm_init(g.state),f}function deflateSetHeader(g,f){return g&&g.state?2!==g.state.wrap?O:(g.state.gzhead=f,M):O}function deflateInit2(g,f,v,C,_,T){if(!g)return O;var I=1;if(f===k&&(f=6),C<0?(I=0,C=-C):C>15&&(I=2,C-=16),_<1||_>$||v!==H||C<8||C>15||f<0||f>9||T<0||T>U)return err(g,O);8===C&&(C=9);var b=new DeflateState;return g.state=b,b.strm=g,b.wrap=I,b.gzhead=null,b.w_bits=C,b.w_size=1<<b.w_bits,b.w_mask=b.w_size-1,b.hash_bits=_+7,b.hash_size=1<<b.hash_bits,b.hash_mask=b.hash_size-1,b.hash_shift=~~((b.hash_bits+Y-1)/Y),b.window=new S.Buf8(2*b.w_size),b.head=new S.Buf16(b.hash_size),b.prev=new S.Buf16(b.w_size),b.lit_bufsize=1<<_+6,b.pending_buf_size=4*b.lit_bufsize,b.pending_buf=new S.Buf8(b.pending_buf_size),b.d_buf=1*b.lit_bufsize,b.l_buf=3*b.lit_bufsize,b.level=f,b.strategy=T,b.method=v,deflateReset(g)}function deflateInit(g,f){return deflateInit2(g,f,H,j,G,V)}function deflate(g,S){var C,T,D,k;if(!g||!g.state||S>R||S<0)return g?err(g,O):O;if(T=g.state,!g.output||!g.input&&0!==g.avail_in||T.status===he&&S!==P)return err(g,0===g.avail_out?N:O);if(T.strm=g,C=T.last_flush,T.last_flush=S,T.status===ee)if(2===T.wrap)g.adler=0,put_byte(T,31),put_byte(T,139),put_byte(T,8),T.gzhead?(put_byte(T,(T.gzhead.text?1:0)+(T.gzhead.hcrc?2:0)+(T.gzhead.extra?4:0)+(T.gzhead.name?8:0)+(T.gzhead.comment?16:0)),put_byte(T,255&T.gzhead.time),put_byte(T,T.gzhead.time>>8&255),put_byte(T,T.gzhead.time>>16&255),put_byte(T,T.gzhead.time>>24&255),put_byte(T,9===T.level?2:T.strategy>=F||T.level<2?4:0),put_byte(T,255&T.gzhead.os),T.gzhead.extra&&T.gzhead.extra.length&&(put_byte(T,255&T.gzhead.extra.length),put_byte(T,T.gzhead.extra.length>>8&255)),T.gzhead.hcrc&&(g.adler=_(g.adler,T.pending_buf,T.pending,0)),T.gzindex=0,T.status=te):(put_byte(T,0),put_byte(T,0),put_byte(T,0),put_byte(T,0),put_byte(T,0),put_byte(T,9===T.level?2:T.strategy>=F||T.level<2?4:0),put_byte(T,fe),T.status=de);else{var L=H+(T.w_bits-8<<4)<<8;L|=(T.strategy>=F||T.level<2?0:T.level<6?1:6===T.level?2:3)<<6,0!==T.strstart&&(L|=Z),L+=31-L%31,T.status=de,putShortMSB(T,L),0!==T.strstart&&(putShortMSB(T,g.adler>>>16),putShortMSB(T,65535&g.adler)),g.adler=1}if(T.status===te)if(T.gzhead.extra){for(D=T.pending;T.gzindex<(65535&T.gzhead.extra.length)&&(T.pending!==T.pending_buf_size||(T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),flush_pending(g),D=T.pending,T.pending!==T.pending_buf_size));)put_byte(T,255&T.gzhead.extra[T.gzindex]),T.gzindex++;T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),T.gzindex===T.gzhead.extra.length&&(T.gzindex=0,T.status=ie)}else T.status=ie;if(T.status===ie)if(T.gzhead.name){D=T.pending;do{if(T.pending===T.pending_buf_size&&(T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),flush_pending(g),D=T.pending,T.pending===T.pending_buf_size)){k=1;break}k=T.gzindex<T.gzhead.name.length?255&T.gzhead.name.charCodeAt(T.gzindex++):0,put_byte(T,k)}while(0!==k);T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),0===k&&(T.gzindex=0,T.status=ne)}else T.status=ne;if(T.status===ne)if(T.gzhead.comment){D=T.pending;do{if(T.pending===T.pending_buf_size&&(T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),flush_pending(g),D=T.pending,T.pending===T.pending_buf_size)){k=1;break}k=T.gzindex<T.gzhead.comment.length?255&T.gzhead.comment.charCodeAt(T.gzindex++):0,put_byte(T,k)}while(0!==k);T.gzhead.hcrc&&T.pending>D&&(g.adler=_(g.adler,T.pending_buf,T.pending-D,D)),0===k&&(T.status=re)}else T.status=re;if(T.status===re&&(T.gzhead.hcrc?(T.pending+2>T.pending_buf_size&&flush_pending(g),T.pending+2<=T.pending_buf_size&&(put_byte(T,255&g.adler),put_byte(T,g.adler>>8&255),g.adler=0,T.status=de)):T.status=de),0!==T.pending){if(flush_pending(g),0===g.avail_out)return T.last_flush=-1,M}else if(0===g.avail_in&&rank(S)<=rank(C)&&S!==P)return err(g,N);if(T.status===he&&0!==g.avail_in)return err(g,N);if(0!==g.avail_in||0!==T.lookahead||S!==I&&T.status!==he){var U=T.strategy===F?deflate_huff(T,S):T.strategy===x?deflate_rle(T,S):f[T.level].func(T,S);if(U!==pe&&U!==me||(T.status=he),U===ue||U===pe)return 0===g.avail_out&&(T.last_flush=-1),M;if(U===ge&&(S===b?v._tr_align(T):S!==R&&(v._tr_stored_block(T,0,0,!1),S===A&&(zero(T.head),0===T.lookahead&&(T.strstart=0,T.block_start=0,T.insert=0))),flush_pending(g),0===g.avail_out))return T.last_flush=-1,M}return S!==P?M:T.wrap<=0?w:(2===T.wrap?(put_byte(T,255&g.adler),put_byte(T,g.adler>>8&255),put_byte(T,g.adler>>16&255),put_byte(T,g.adler>>24&255),put_byte(T,255&g.total_in),put_byte(T,g.total_in>>8&255),put_byte(T,g.total_in>>16&255),put_byte(T,g.total_in>>24&255)):(putShortMSB(T,g.adler>>>16),putShortMSB(T,65535&g.adler)),flush_pending(g),T.wrap>0&&(T.wrap=-T.wrap),0!==T.pending?M:w)}function deflateEnd(g){var f;return g&&g.state?(f=g.state.status)!==ee&&f!==te&&f!==ie&&f!==ne&&f!==re&&f!==de&&f!==he?err(g,O):(g.state=null,f===de?err(g,D):M):O}function deflateSetDictionary(g,f){var v,_,T,I,b,A,P,R,w=f.length;if(!g||!g.state)return O;if(2===(I=(v=g.state).wrap)||1===I&&v.status!==ee||v.lookahead)return O;for(1===I&&(g.adler=C(g.adler,f,w,0)),v.wrap=0,w>=v.w_size&&(0===I&&(zero(v.head),v.strstart=0,v.block_start=0,v.insert=0),R=new S.Buf8(v.w_size),S.arraySet(R,f,w-v.w_size,v.w_size,0),f=R,w=v.w_size),b=g.avail_in,A=g.next_in,P=g.input,g.avail_in=w,g.next_in=0,g.input=f,fill_window(v);v.lookahead>=Y;){_=v.strstart,T=v.lookahead-(Y-1);do{v.ins_h=(v.ins_h<<v.hash_shift^v.window[_+Y-1])&v.hash_mask,v.prev[_&v.w_mask]=v.head[v.ins_h],v.head[v.ins_h]=_,_++}while(--T);v.strstart=_,v.lookahead=Y-1,fill_window(v)}return v.strstart+=v.lookahead,v.block_start=v.strstart,v.insert=v.lookahead,v.lookahead=0,v.match_length=v.prev_length=Y-1,v.match_available=0,g.next_in=A,g.input=P,g.avail_in=b,v.wrap=I,M}f=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],g.deflateInit=deflateInit,g.deflateInit2=deflateInit2,g.deflateReset=deflateReset,g.deflateResetKeep=deflateResetKeep,g.deflateSetHeader=deflateSetHeader,g.deflate=deflate,g.deflateEnd=deflateEnd,g.deflateSetDictionary=deflateSetDictionary,g.deflateInfo="pako deflate (from Nodeca project)"}}),he=__commonJS2({"../node_modules/pako/lib/utils/strings.js"(g){var f=se(),S=!0,v=!0;try{String.fromCharCode.apply(null,[0])}catch(g){S=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(g){v=!1}var C,_=new f.Buf8(256);for(C=0;C<256;C++)_[C]=C>=252?6:C>=248?5:C>=240?4:C>=224?3:C>=192?2:1;function buf2binstring(g,C){if(C<65534&&(g.subarray&&v||!g.subarray&&S))return String.fromCharCode.apply(null,f.shrinkBuf(g,C));for(var _="",T=0;T<C;T++)_+=String.fromCharCode(g[T]);return _}_[254]=_[254]=1,g.string2buf=function(g){var S,v,C,_,T,I=g.length,b=0;for(_=0;_<I;_++)55296==(64512&(v=g.charCodeAt(_)))&&_+1<I&&56320==(64512&(C=g.charCodeAt(_+1)))&&(v=65536+(v-55296<<10)+(C-56320),_++),b+=v<128?1:v<2048?2:v<65536?3:4;for(S=new f.Buf8(b),T=0,_=0;T<b;_++)55296==(64512&(v=g.charCodeAt(_)))&&_+1<I&&56320==(64512&(C=g.charCodeAt(_+1)))&&(v=65536+(v-55296<<10)+(C-56320),_++),v<128?S[T++]=v:v<2048?(S[T++]=192|v>>>6,S[T++]=128|63&v):v<65536?(S[T++]=224|v>>>12,S[T++]=128|v>>>6&63,S[T++]=128|63&v):(S[T++]=240|v>>>18,S[T++]=128|v>>>12&63,S[T++]=128|v>>>6&63,S[T++]=128|63&v);return S},g.buf2binstring=function(g){return buf2binstring(g,g.length)},g.binstring2buf=function(g){for(var S=new f.Buf8(g.length),v=0,C=S.length;v<C;v++)S[v]=g.charCodeAt(v);return S},g.buf2string=function(g,f){var S,v,C,T,I=f||g.length,b=new Array(2*I);for(v=0,S=0;S<I;)if((C=g[S++])<128)b[v++]=C;else if((T=_[C])>4)b[v++]=65533,S+=T-1;else{for(C&=2===T?31:3===T?15:7;T>1&&S<I;)C=C<<6|63&g[S++],T--;T>1?b[v++]=65533:C<65536?b[v++]=C:(C-=65536,b[v++]=55296|C>>10&1023,b[v++]=56320|1023&C)}return buf2binstring(b,v)},g.utf8border=function(g,f){var S;for((f=f||g.length)>g.length&&(f=g.length),S=f-1;S>=0&&128==(192&g[S]);)S--;return S<0||0===S?f:S+_[g[S]]>f?S:f}}}),ue=__commonJS2({"../node_modules/pako/lib/zlib/zstream.js"(g,f){function ZStream(){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}f.exports=ZStream}}),ge=__commonJS2({"../node_modules/pako/lib/deflate.js"(g){var f=de(),S=se(),v=he(),C=ce(),_=ue(),T=Object.prototype.toString,I=0,b=4,A=0,P=1,R=2,M=-1,w=0,O=8;function Deflate(g){if(!(this instanceof Deflate))return new Deflate(g);this.options=S.assign({level:M,method:O,chunkSize:16384,windowBits:15,memLevel:8,strategy:w,to:""},g||{});var I=this.options;I.raw&&I.windowBits>0?I.windowBits=-I.windowBits:I.gzip&&I.windowBits>0&&I.windowBits<16&&(I.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _,this.strm.avail_out=0;var b=f.deflateInit2(this.strm,I.level,I.method,I.windowBits,I.memLevel,I.strategy);if(b!==A)throw new Error(C[b]);if(I.header&&f.deflateSetHeader(this.strm,I.header),I.dictionary){var P;if(P="string"==typeof I.dictionary?v.string2buf(I.dictionary):"[object ArrayBuffer]"===T.call(I.dictionary)?new Uint8Array(I.dictionary):I.dictionary,(b=f.deflateSetDictionary(this.strm,P))!==A)throw new Error(C[b]);this._dict_set=!0}}function deflate(g,f){var S=new Deflate(f);if(S.push(g,!0),S.err)throw S.msg||C[S.err];return S.result}function deflateRaw(g,f){return(f=f||{}).raw=!0,deflate(g,f)}function gzip(g,f){return(f=f||{}).gzip=!0,deflate(g,f)}Deflate.prototype.push=function(g,C){var _,M,w=this.strm,O=this.options.chunkSize;if(this.ended)return!1;M=C===~~C?C:!0===C?b:I,"string"==typeof g?w.input=v.string2buf(g):"[object ArrayBuffer]"===T.call(g)?w.input=new Uint8Array(g):w.input=g,w.next_in=0,w.avail_in=w.input.length;do{if(0===w.avail_out&&(w.output=new S.Buf8(O),w.next_out=0,w.avail_out=O),(_=f.deflate(w,M))!==P&&_!==A)return this.onEnd(_),this.ended=!0,!1;0!==w.avail_out&&(0!==w.avail_in||M!==b&&M!==R)||("string"===this.options.to?this.onData(v.buf2binstring(S.shrinkBuf(w.output,w.next_out))):this.onData(S.shrinkBuf(w.output,w.next_out)))}while((w.avail_in>0||0===w.avail_out)&&_!==P);return M===b?(_=f.deflateEnd(this.strm),this.onEnd(_),this.ended=!0,_===A):M!==R||(this.onEnd(A),w.avail_out=0,!0)},Deflate.prototype.onData=function(g){this.chunks.push(g)},Deflate.prototype.onEnd=function(g){g===A&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=S.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg},g.Deflate=Deflate,g.deflate=deflate,g.deflateRaw=deflateRaw,g.gzip=gzip}}),pe=__commonJS2({"../node_modules/pako/lib/zlib/inffast.js"(g,f){var S=30,v=12;f.exports=function inflate_fast(g,f){var C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q;C=g.state,_=g.next_in,G=g.input,T=_+(g.avail_in-5),I=g.next_out,q=g.output,b=I-(f-g.avail_out),A=I+(g.avail_out-257),P=C.dmax,R=C.wsize,M=C.whave,w=C.wnext,O=C.window,D=C.hold,N=C.bits,k=C.lencode,L=C.distcode,F=(1<<C.lenbits)-1,x=(1<<C.distbits)-1;e:do{N<15&&(D+=G[_++]<<N,N+=8,D+=G[_++]<<N,N+=8),U=k[D&F];t:for(;;){if(D>>>=V=U>>>24,N-=V,0==(V=U>>>16&255))q[I++]=65535&U;else{if(!(16&V)){if(0==(64&V)){U=k[(65535&U)+(D&(1<<V)-1)];continue t}if(32&V){C.mode=v;break e}g.msg="invalid literal/length code",C.mode=S;break e}B=65535&U,(V&=15)&&(N<V&&(D+=G[_++]<<N,N+=8),B+=D&(1<<V)-1,D>>>=V,N-=V),N<15&&(D+=G[_++]<<N,N+=8,D+=G[_++]<<N,N+=8),U=L[D&x];i:for(;;){if(D>>>=V=U>>>24,N-=V,!(16&(V=U>>>16&255))){if(0==(64&V)){U=L[(65535&U)+(D&(1<<V)-1)];continue i}g.msg="invalid distance code",C.mode=S;break e}if(H=65535&U,N<(V&=15)&&(D+=G[_++]<<N,(N+=8)<V&&(D+=G[_++]<<N,N+=8)),(H+=D&(1<<V)-1)>P){g.msg="invalid distance too far back",C.mode=S;break e}if(D>>>=V,N-=V,H>(V=I-b)){if((V=H-V)>M&&C.sane){g.msg="invalid distance too far back",C.mode=S;break e}if($=0,j=O,0===w){if($+=R-V,V<B){B-=V;do{q[I++]=O[$++]}while(--V);$=I-H,j=q}}else if(w<V){if($+=R+w-V,(V-=w)<B){B-=V;do{q[I++]=O[$++]}while(--V);if($=0,w<B){B-=V=w;do{q[I++]=O[$++]}while(--V);$=I-H,j=q}}}else if($+=w-V,V<B){B-=V;do{q[I++]=O[$++]}while(--V);$=I-H,j=q}for(;B>2;)q[I++]=j[$++],q[I++]=j[$++],q[I++]=j[$++],B-=3;B&&(q[I++]=j[$++],B>1&&(q[I++]=j[$++]))}else{$=I-H;do{q[I++]=q[$++],q[I++]=q[$++],q[I++]=q[$++],B-=3}while(B>2);B&&(q[I++]=q[$++],B>1&&(q[I++]=q[$++]))}break}}break}}while(_<T&&I<A);_-=B=N>>3,D&=(1<<(N-=B<<3))-1,g.next_in=_,g.next_out=I,g.avail_in=_<T?T-_+5:5-(_-T),g.avail_out=I<A?A-I+257:257-(I-A),C.hold=D,C.bits=N}}}),me=__commonJS2({"../node_modules/pako/lib/zlib/inftrees.js"(g,f){var S=se(),v=15,C=852,_=592,T=0,I=1,b=2,A=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],P=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],R=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],M=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];f.exports=function inflate_table(g,f,w,O,D,N,k,L){var F,x,U,V,B,H,$,j,G,q=L.bits,W=0,z=0,K=0,J=0,Y=0,Q=0,X=0,Z=0,ee=0,te=0,ie=null,ne=0,re=new S.Buf16(v+1),se=new S.Buf16(v+1),ae=null,oe=0;for(W=0;W<=v;W++)re[W]=0;for(z=0;z<O;z++)re[f[w+z]]++;for(Y=q,J=v;J>=1&&0===re[J];J--);if(Y>J&&(Y=J),0===J)return D[N++]=20971520,D[N++]=20971520,L.bits=1,0;for(K=1;K<J&&0===re[K];K++);for(Y<K&&(Y=K),Z=1,W=1;W<=v;W++)if(Z<<=1,(Z-=re[W])<0)return-1;if(Z>0&&(g===T||1!==J))return-1;for(se[1]=0,W=1;W<v;W++)se[W+1]=se[W]+re[W];for(z=0;z<O;z++)0!==f[w+z]&&(k[se[f[w+z]]++]=z);if(g===T?(ie=ae=k,H=19):g===I?(ie=A,ne-=257,ae=P,oe-=257,H=256):(ie=R,ae=M,H=-1),te=0,z=0,W=K,B=N,Q=Y,X=0,U=-1,V=(ee=1<<Y)-1,g===I&&ee>C||g===b&&ee>_)return 1;for(;;){$=W-X,k[z]<H?(j=0,G=k[z]):k[z]>H?(j=ae[oe+k[z]],G=ie[ne+k[z]]):(j=96,G=0),F=1<<W-X,K=x=1<<Q;do{D[B+(te>>X)+(x-=F)]=$<<24|j<<16|G|0}while(0!==x);for(F=1<<W-1;te&F;)F>>=1;if(0!==F?(te&=F-1,te+=F):te=0,z++,0==--re[W]){if(W===J)break;W=f[w+k[z]]}if(W>Y&&(te&V)!==U){for(0===X&&(X=Y),B+=K,Z=1<<(Q=W-X);Q+X<J&&!((Z-=re[Q+X])<=0);)Q++,Z<<=1;if(ee+=1<<Q,g===I&&ee>C||g===b&&ee>_)return 1;D[U=te&V]=Y<<24|Q<<16|B-N|0}}return 0!==te&&(D[B+te]=W-X<<24|64<<16|0),L.bits=Y,0}}}),fe=__commonJS2({"../node_modules/pako/lib/zlib/inflate.js"(g){var f=se(),S=oe(),v=le(),C=pe(),_=me(),T=0,I=1,b=2,A=4,P=5,R=6,M=0,w=1,O=2,D=-2,N=-3,k=-4,L=-5,F=8,x=1,U=2,V=3,B=4,H=5,$=6,j=7,G=8,q=9,W=10,z=11,K=12,J=13,Y=14,Q=15,X=16,Z=17,ee=18,te=19,ie=20,ne=21,re=22,ae=23,ce=24,de=25,he=26,ue=27,ge=28,fe=29,Se=30,ve=31,Ce=852,ye=592,Ee=15;function zswap32(g){return(g>>>24&255)+(g>>>8&65280)+((65280&g)<<8)+((255&g)<<24)}function InflateState(){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 f.Buf16(320),this.work=new f.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(g){var S;return g&&g.state?(S=g.state,g.total_in=g.total_out=S.total=0,g.msg="",S.wrap&&(g.adler=1&S.wrap),S.mode=x,S.last=0,S.havedict=0,S.dmax=32768,S.head=null,S.hold=0,S.bits=0,S.lencode=S.lendyn=new f.Buf32(Ce),S.distcode=S.distdyn=new f.Buf32(ye),S.sane=1,S.back=-1,M):D}function inflateReset(g){var f;return g&&g.state?((f=g.state).wsize=0,f.whave=0,f.wnext=0,inflateResetKeep(g)):D}function inflateReset2(g,f){var S,v;return g&&g.state?(v=g.state,f<0?(S=0,f=-f):(S=1+(f>>4),f<48&&(f&=15)),f&&(f<8||f>15)?D:(null!==v.window&&v.wbits!==f&&(v.window=null),v.wrap=S,v.wbits=f,inflateReset(g))):D}function inflateInit2(g,f){var S,v;return g?(v=new InflateState,g.state=v,v.window=null,(S=inflateReset2(g,f))!==M&&(g.state=null),S):D}function inflateInit(g){return inflateInit2(g,Ee)}var _e,Te,Ie=!0;function fixedtables(g){if(Ie){var S;for(_e=new f.Buf32(512),Te=new f.Buf32(32),S=0;S<144;)g.lens[S++]=8;for(;S<256;)g.lens[S++]=9;for(;S<280;)g.lens[S++]=7;for(;S<288;)g.lens[S++]=8;for(_(I,g.lens,0,288,_e,0,g.work,{bits:9}),S=0;S<32;)g.lens[S++]=5;_(b,g.lens,0,32,Te,0,g.work,{bits:5}),Ie=!1}g.lencode=_e,g.lenbits=9,g.distcode=Te,g.distbits=5}function updatewindow(g,S,v,C){var _,T=g.state;return null===T.window&&(T.wsize=1<<T.wbits,T.wnext=0,T.whave=0,T.window=new f.Buf8(T.wsize)),C>=T.wsize?(f.arraySet(T.window,S,v-T.wsize,T.wsize,0),T.wnext=0,T.whave=T.wsize):((_=T.wsize-T.wnext)>C&&(_=C),f.arraySet(T.window,S,v-C,_,T.wnext),(C-=_)?(f.arraySet(T.window,S,v-C,C,0),T.wnext=C,T.whave=T.wsize):(T.wnext+=_,T.wnext===T.wsize&&(T.wnext=0),T.whave<T.wsize&&(T.whave+=_))),0}function inflate3(g,se){var oe,le,pe,me,Ce,ye,Ee,_e,Te,Ie,be,Ae,Pe,Re,Me,we,Oe,De,Ne,ke,Le,Fe,xe,Ue,Ve=0,Be=new f.Buf8(4),He=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!g||!g.state||!g.output||!g.input&&0!==g.avail_in)return D;(oe=g.state).mode===K&&(oe.mode=J),Ce=g.next_out,pe=g.output,Ee=g.avail_out,me=g.next_in,le=g.input,ye=g.avail_in,_e=oe.hold,Te=oe.bits,Ie=ye,be=Ee,Fe=M;e:for(;;)switch(oe.mode){case x:if(0===oe.wrap){oe.mode=J;break}for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(2&oe.wrap&&35615===_e){oe.check=0,Be[0]=255&_e,Be[1]=_e>>>8&255,oe.check=v(oe.check,Be,2,0),_e=0,Te=0,oe.mode=U;break}if(oe.flags=0,oe.head&&(oe.head.done=!1),!(1&oe.wrap)||(((255&_e)<<8)+(_e>>8))%31){g.msg="incorrect header check",oe.mode=Se;break}if((15&_e)!==F){g.msg="unknown compression method",oe.mode=Se;break}if(Te-=4,Le=8+(15&(_e>>>=4)),0===oe.wbits)oe.wbits=Le;else if(Le>oe.wbits){g.msg="invalid window size",oe.mode=Se;break}oe.dmax=1<<Le,g.adler=oe.check=1,oe.mode=512&_e?W:K,_e=0,Te=0;break;case U:for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(oe.flags=_e,(255&oe.flags)!==F){g.msg="unknown compression method",oe.mode=Se;break}if(57344&oe.flags){g.msg="unknown header flags set",oe.mode=Se;break}oe.head&&(oe.head.text=_e>>8&1),512&oe.flags&&(Be[0]=255&_e,Be[1]=_e>>>8&255,oe.check=v(oe.check,Be,2,0)),_e=0,Te=0,oe.mode=V;case V:for(;Te<32;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.head&&(oe.head.time=_e),512&oe.flags&&(Be[0]=255&_e,Be[1]=_e>>>8&255,Be[2]=_e>>>16&255,Be[3]=_e>>>24&255,oe.check=v(oe.check,Be,4,0)),_e=0,Te=0,oe.mode=B;case B:for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.head&&(oe.head.xflags=255&_e,oe.head.os=_e>>8),512&oe.flags&&(Be[0]=255&_e,Be[1]=_e>>>8&255,oe.check=v(oe.check,Be,2,0)),_e=0,Te=0,oe.mode=H;case H:if(1024&oe.flags){for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.length=_e,oe.head&&(oe.head.extra_len=_e),512&oe.flags&&(Be[0]=255&_e,Be[1]=_e>>>8&255,oe.check=v(oe.check,Be,2,0)),_e=0,Te=0}else oe.head&&(oe.head.extra=null);oe.mode=$;case $:if(1024&oe.flags&&((Ae=oe.length)>ye&&(Ae=ye),Ae&&(oe.head&&(Le=oe.head.extra_len-oe.length,oe.head.extra||(oe.head.extra=new Array(oe.head.extra_len)),f.arraySet(oe.head.extra,le,me,Ae,Le)),512&oe.flags&&(oe.check=v(oe.check,le,Ae,me)),ye-=Ae,me+=Ae,oe.length-=Ae),oe.length))break e;oe.length=0,oe.mode=j;case j:if(2048&oe.flags){if(0===ye)break e;Ae=0;do{Le=le[me+Ae++],oe.head&&Le&&oe.length<65536&&(oe.head.name+=String.fromCharCode(Le))}while(Le&&Ae<ye);if(512&oe.flags&&(oe.check=v(oe.check,le,Ae,me)),ye-=Ae,me+=Ae,Le)break e}else oe.head&&(oe.head.name=null);oe.length=0,oe.mode=G;case G:if(4096&oe.flags){if(0===ye)break e;Ae=0;do{Le=le[me+Ae++],oe.head&&Le&&oe.length<65536&&(oe.head.comment+=String.fromCharCode(Le))}while(Le&&Ae<ye);if(512&oe.flags&&(oe.check=v(oe.check,le,Ae,me)),ye-=Ae,me+=Ae,Le)break e}else oe.head&&(oe.head.comment=null);oe.mode=q;case q:if(512&oe.flags){for(;Te<16;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(_e!==(65535&oe.check)){g.msg="header crc mismatch",oe.mode=Se;break}_e=0,Te=0}oe.head&&(oe.head.hcrc=oe.flags>>9&1,oe.head.done=!0),g.adler=oe.check=0,oe.mode=K;break;case W:for(;Te<32;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}g.adler=oe.check=zswap32(_e),_e=0,Te=0,oe.mode=z;case z:if(0===oe.havedict)return g.next_out=Ce,g.avail_out=Ee,g.next_in=me,g.avail_in=ye,oe.hold=_e,oe.bits=Te,O;g.adler=oe.check=1,oe.mode=K;case K:if(se===P||se===R)break e;case J:if(oe.last){_e>>>=7&Te,Te-=7&Te,oe.mode=ue;break}for(;Te<3;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}switch(oe.last=1&_e,Te-=1,3&(_e>>>=1)){case 0:oe.mode=Y;break;case 1:if(fixedtables(oe),oe.mode=ie,se===R){_e>>>=2,Te-=2;break e}break;case 2:oe.mode=Z;break;case 3:g.msg="invalid block type",oe.mode=Se}_e>>>=2,Te-=2;break;case Y:for(_e>>>=7&Te,Te-=7&Te;Te<32;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if((65535&_e)!=(_e>>>16^65535)){g.msg="invalid stored block lengths",oe.mode=Se;break}if(oe.length=65535&_e,_e=0,Te=0,oe.mode=Q,se===R)break e;case Q:oe.mode=X;case X:if(Ae=oe.length){if(Ae>ye&&(Ae=ye),Ae>Ee&&(Ae=Ee),0===Ae)break e;f.arraySet(pe,le,me,Ae,Ce),ye-=Ae,me+=Ae,Ee-=Ae,Ce+=Ae,oe.length-=Ae;break}oe.mode=K;break;case Z:for(;Te<14;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(oe.nlen=257+(31&_e),_e>>>=5,Te-=5,oe.ndist=1+(31&_e),_e>>>=5,Te-=5,oe.ncode=4+(15&_e),_e>>>=4,Te-=4,oe.nlen>286||oe.ndist>30){g.msg="too many length or distance symbols",oe.mode=Se;break}oe.have=0,oe.mode=ee;case ee:for(;oe.have<oe.ncode;){for(;Te<3;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.lens[He[oe.have++]]=7&_e,_e>>>=3,Te-=3}for(;oe.have<19;)oe.lens[He[oe.have++]]=0;if(oe.lencode=oe.lendyn,oe.lenbits=7,xe={bits:oe.lenbits},Fe=_(T,oe.lens,0,19,oe.lencode,0,oe.work,xe),oe.lenbits=xe.bits,Fe){g.msg="invalid code lengths set",oe.mode=Se;break}oe.have=0,oe.mode=te;case te:for(;oe.have<oe.nlen+oe.ndist;){for(;we=(Ve=oe.lencode[_e&(1<<oe.lenbits)-1])>>>16&255,Oe=65535&Ve,!((Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(Oe<16)_e>>>=Me,Te-=Me,oe.lens[oe.have++]=Oe;else{if(16===Oe){for(Ue=Me+2;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(_e>>>=Me,Te-=Me,0===oe.have){g.msg="invalid bit length repeat",oe.mode=Se;break}Le=oe.lens[oe.have-1],Ae=3+(3&_e),_e>>>=2,Te-=2}else if(17===Oe){for(Ue=Me+3;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}Te-=Me,Le=0,Ae=3+(7&(_e>>>=Me)),_e>>>=3,Te-=3}else{for(Ue=Me+7;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}Te-=Me,Le=0,Ae=11+(127&(_e>>>=Me)),_e>>>=7,Te-=7}if(oe.have+Ae>oe.nlen+oe.ndist){g.msg="invalid bit length repeat",oe.mode=Se;break}for(;Ae--;)oe.lens[oe.have++]=Le}}if(oe.mode===Se)break;if(0===oe.lens[256]){g.msg="invalid code -- missing end-of-block",oe.mode=Se;break}if(oe.lenbits=9,xe={bits:oe.lenbits},Fe=_(I,oe.lens,0,oe.nlen,oe.lencode,0,oe.work,xe),oe.lenbits=xe.bits,Fe){g.msg="invalid literal/lengths set",oe.mode=Se;break}if(oe.distbits=6,oe.distcode=oe.distdyn,xe={bits:oe.distbits},Fe=_(b,oe.lens,oe.nlen,oe.ndist,oe.distcode,0,oe.work,xe),oe.distbits=xe.bits,Fe){g.msg="invalid distances set",oe.mode=Se;break}if(oe.mode=ie,se===R)break e;case ie:oe.mode=ne;case ne:if(ye>=6&&Ee>=258){g.next_out=Ce,g.avail_out=Ee,g.next_in=me,g.avail_in=ye,oe.hold=_e,oe.bits=Te,C(g,be),Ce=g.next_out,pe=g.output,Ee=g.avail_out,me=g.next_in,le=g.input,ye=g.avail_in,_e=oe.hold,Te=oe.bits,oe.mode===K&&(oe.back=-1);break}for(oe.back=0;we=(Ve=oe.lencode[_e&(1<<oe.lenbits)-1])>>>16&255,Oe=65535&Ve,!((Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(we&&0==(240&we)){for(De=Me,Ne=we,ke=Oe;we=(Ve=oe.lencode[ke+((_e&(1<<De+Ne)-1)>>De)])>>>16&255,Oe=65535&Ve,!(De+(Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}_e>>>=De,Te-=De,oe.back+=De}if(_e>>>=Me,Te-=Me,oe.back+=Me,oe.length=Oe,0===we){oe.mode=he;break}if(32&we){oe.back=-1,oe.mode=K;break}if(64&we){g.msg="invalid literal/length code",oe.mode=Se;break}oe.extra=15&we,oe.mode=re;case re:if(oe.extra){for(Ue=oe.extra;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.length+=_e&(1<<oe.extra)-1,_e>>>=oe.extra,Te-=oe.extra,oe.back+=oe.extra}oe.was=oe.length,oe.mode=ae;case ae:for(;we=(Ve=oe.distcode[_e&(1<<oe.distbits)-1])>>>16&255,Oe=65535&Ve,!((Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(0==(240&we)){for(De=Me,Ne=we,ke=Oe;we=(Ve=oe.distcode[ke+((_e&(1<<De+Ne)-1)>>De)])>>>16&255,Oe=65535&Ve,!(De+(Me=Ve>>>24)<=Te);){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}_e>>>=De,Te-=De,oe.back+=De}if(_e>>>=Me,Te-=Me,oe.back+=Me,64&we){g.msg="invalid distance code",oe.mode=Se;break}oe.offset=Oe,oe.extra=15&we,oe.mode=ce;case ce:if(oe.extra){for(Ue=oe.extra;Te<Ue;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}oe.offset+=_e&(1<<oe.extra)-1,_e>>>=oe.extra,Te-=oe.extra,oe.back+=oe.extra}if(oe.offset>oe.dmax){g.msg="invalid distance too far back",oe.mode=Se;break}oe.mode=de;case de:if(0===Ee)break e;if(Ae=be-Ee,oe.offset>Ae){if((Ae=oe.offset-Ae)>oe.whave&&oe.sane){g.msg="invalid distance too far back",oe.mode=Se;break}Ae>oe.wnext?(Ae-=oe.wnext,Pe=oe.wsize-Ae):Pe=oe.wnext-Ae,Ae>oe.length&&(Ae=oe.length),Re=oe.window}else Re=pe,Pe=Ce-oe.offset,Ae=oe.length;Ae>Ee&&(Ae=Ee),Ee-=Ae,oe.length-=Ae;do{pe[Ce++]=Re[Pe++]}while(--Ae);0===oe.length&&(oe.mode=ne);break;case he:if(0===Ee)break e;pe[Ce++]=oe.length,Ee--,oe.mode=ne;break;case ue:if(oe.wrap){for(;Te<32;){if(0===ye)break e;ye--,_e|=le[me++]<<Te,Te+=8}if(be-=Ee,g.total_out+=be,oe.total+=be,be&&(g.adler=oe.check=oe.flags?v(oe.check,pe,be,Ce-be):S(oe.check,pe,be,Ce-be)),be=Ee,(oe.flags?_e:zswap32(_e))!==oe.check){g.msg="incorrect data check",oe.mode=Se;break}_e=0,Te=0}oe.mode=ge;case ge:if(oe.wrap&&oe.flags){for(;Te<32;){if(0===ye)break e;ye--,_e+=le[me++]<<Te,Te+=8}if(_e!==(4294967295&oe.total)){g.msg="incorrect length check",oe.mode=Se;break}_e=0,Te=0}oe.mode=fe;case fe:Fe=w;break e;case Se:Fe=N;break e;case ve:return k;default:return D}return g.next_out=Ce,g.avail_out=Ee,g.next_in=me,g.avail_in=ye,oe.hold=_e,oe.bits=Te,(oe.wsize||be!==g.avail_out&&oe.mode<Se&&(oe.mode<ue||se!==A))&&updatewindow(g,g.output,g.next_out,be-g.avail_out),Ie-=g.avail_in,be-=g.avail_out,g.total_in+=Ie,g.total_out+=be,oe.total+=be,oe.wrap&&be&&(g.adler=oe.check=oe.flags?v(oe.check,pe,be,g.next_out-be):S(oe.check,pe,be,g.next_out-be)),g.data_type=oe.bits+(oe.last?64:0)+(oe.mode===K?128:0)+(oe.mode===ie||oe.mode===Q?256:0),(0===Ie&&0===be||se===A)&&Fe===M&&(Fe=L),Fe}function inflateEnd(g){if(!g||!g.state)return D;var f=g.state;return f.window&&(f.window=null),g.state=null,M}function inflateGetHeader(g,f){var S;return g&&g.state?0==(2&(S=g.state).wrap)?D:(S.head=f,f.done=!1,M):D}function inflateSetDictionary(g,f){var v,C=f.length;return g&&g.state?0!==(v=g.state).wrap&&v.mode!==z?D:v.mode===z&&S(1,f,C,0)!==v.check?N:updatewindow(g,f,C,C)?(v.mode=ve,k):(v.havedict=1,M):D}g.inflateReset=inflateReset,g.inflateReset2=inflateReset2,g.inflateResetKeep=inflateResetKeep,g.inflateInit=inflateInit,g.inflateInit2=inflateInit2,g.inflate=inflate3,g.inflateEnd=inflateEnd,g.inflateGetHeader=inflateGetHeader,g.inflateSetDictionary=inflateSetDictionary,g.inflateInfo="pako inflate (from Nodeca project)"}}),Se=__commonJS2({"../node_modules/pako/lib/zlib/constants.js"(g,f){f.exports={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_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}}}),ve=__commonJS2({"../node_modules/pako/lib/zlib/gzheader.js"(g,f){function GZheader(){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}f.exports=GZheader}}),Ce=__commonJS2({"../node_modules/pako/lib/inflate.js"(g){var f=fe(),S=se(),v=he(),C=Se(),_=ce(),T=ue(),I=ve(),b=Object.prototype.toString;function Inflate(g){if(!(this instanceof Inflate))return new Inflate(g);this.options=S.assign({chunkSize:16384,windowBits:0,to:""},g||{});var A=this.options;A.raw&&A.windowBits>=0&&A.windowBits<16&&(A.windowBits=-A.windowBits,0===A.windowBits&&(A.windowBits=-15)),!(A.windowBits>=0&&A.windowBits<16)||g&&g.windowBits||(A.windowBits+=32),A.windowBits>15&&A.windowBits<48&&0==(15&A.windowBits)&&(A.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new T,this.strm.avail_out=0;var P=f.inflateInit2(this.strm,A.windowBits);if(P!==C.Z_OK)throw new Error(_[P]);if(this.header=new I,f.inflateGetHeader(this.strm,this.header),A.dictionary&&("string"==typeof A.dictionary?A.dictionary=v.string2buf(A.dictionary):"[object ArrayBuffer]"===b.call(A.dictionary)&&(A.dictionary=new Uint8Array(A.dictionary)),A.raw&&(P=f.inflateSetDictionary(this.strm,A.dictionary))!==C.Z_OK))throw new Error(_[P])}function inflate3(g,f){var S=new Inflate(f);if(S.push(g,!0),S.err)throw S.msg||_[S.err];return S.result}function inflateRaw(g,f){return(f=f||{}).raw=!0,inflate3(g,f)}Inflate.prototype.push=function(g,_){var T,I,A,P,R,M=this.strm,w=this.options.chunkSize,O=this.options.dictionary,D=!1;if(this.ended)return!1;I=_===~~_?_:!0===_?C.Z_FINISH:C.Z_NO_FLUSH,"string"==typeof g?M.input=v.binstring2buf(g):"[object ArrayBuffer]"===b.call(g)?M.input=new Uint8Array(g):M.input=g,M.next_in=0,M.avail_in=M.input.length;do{if(0===M.avail_out&&(M.output=new S.Buf8(w),M.next_out=0,M.avail_out=w),(T=f.inflate(M,C.Z_NO_FLUSH))===C.Z_NEED_DICT&&O&&(T=f.inflateSetDictionary(this.strm,O)),T===C.Z_BUF_ERROR&&!0===D&&(T=C.Z_OK,D=!1),T!==C.Z_STREAM_END&&T!==C.Z_OK)return this.onEnd(T),this.ended=!0,!1;M.next_out&&(0!==M.avail_out&&T!==C.Z_STREAM_END&&(0!==M.avail_in||I!==C.Z_FINISH&&I!==C.Z_SYNC_FLUSH)||("string"===this.options.to?(A=v.utf8border(M.output,M.next_out),P=M.next_out-A,R=v.buf2string(M.output,A),M.next_out=P,M.avail_out=w-P,P&&S.arraySet(M.output,M.output,A,P,0),this.onData(R)):this.onData(S.shrinkBuf(M.output,M.next_out)))),0===M.avail_in&&0===M.avail_out&&(D=!0)}while((M.avail_in>0||0===M.avail_out)&&T!==C.Z_STREAM_END);return T===C.Z_STREAM_END&&(I=C.Z_FINISH),I===C.Z_FINISH?(T=f.inflateEnd(this.strm),this.onEnd(T),this.ended=!0,T===C.Z_OK):I!==C.Z_SYNC_FLUSH||(this.onEnd(C.Z_OK),M.avail_out=0,!0)},Inflate.prototype.onData=function(g){this.chunks.push(g)},Inflate.prototype.onEnd=function(g){g===C.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=S.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg},g.Inflate=Inflate,g.inflate=inflate3,g.inflateRaw=inflateRaw,g.ungzip=inflate3}}),ye=__commonJS2({"../node_modules/pako/index.js"(g,f){var S={};(0,se().assign)(S,ge(),Ce(),Se()),f.exports=S}}),Ee=__commonJS2({"../signaling-agent/node_modules/sdp-transform/lib/grammar.js"(g,f){var S=f.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\S*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(g){return g.encoding?"rtpmap:%d %s/%s/%s":g.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(g){return null!=g.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(g){return"rtcp-fb:"+("*"===g.payload?"%s":"%d")+" x-message %s"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%d trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(g){return null!=g.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(g){return"extmap:%d"+(g.direction?"/%s":"%v")+(g["encrypt-uri"]?" %s":"%v")+" %s"+(g.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"cryptoscale",reg:/^cryptoscale:(\d*) (client|server) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","flavor","suite","config","sessionConfig"],format:function(g){return null!=g.sessionConfig?"cryptoscale:%d %s %s %s %s":"cryptoscale:%d %s %s %s"}},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(g){return null!=g.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(g){var f="candidate:%s %d %s %d %s %d typ %s";return f+=null!=g.raddr?" raddr %s rport %d":"%v%v",f+=null!=g.tcptype?" tcptype %s":"%v",null!=g.generation&&(f+=" generation %d"),f+=null!=g["network-id"]?" network-id %d":"%v",f+=null!=g["network-cost"]?" network-cost %d":"%v"}},{push:"xCandidatesIpv6",reg:/^x-candidate-ipv6:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation"],format:function(g){var f="candidate:%s %d %s %d %s %d typ %s";return f+=null!=g.raddr?" raddr %s rport %d":"%v%v",f+=null!=g.tcptype?" tcptype %s":"%v",null!=g.generation&&(f+=" generation %d"),f}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(g){var f="ssrc:%d";return null!=g.attribute&&(f+=" %s",null!=g.value&&(f+=":%s")),f}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(g){return null!=g.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(g){return g.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(g){return"imageattr:%s %s %s"+(g.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(g){return"simulcast:%s %s"+(g.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(g){return"ts-refclk:%s"+(null!=g.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(g){var f="mediaclk:";return f+=null!=g.id?"id=%s %s":"%v%s",f+=null!=g.mediaClockValue?"=%s":"",f+=null!=g.rateNumerator?" rate=%s":"",f+=null!=g.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{name:"xMediaBw",reg:/^x-mediabw:(\S*) send=(\d*);recv=(\d*)/,names:["label","sendBw","receiveBw"],format:"x-mediabw:%s send=%d;recv=%d"},{name:"xSsrcRange",reg:/^x-ssrc-range:(\d*)-(\d*)/,names:["ssrcMin","ssrcMax"],format:"x-ssrc-range:%d-%d"},{name:"xSource",reg:/^x-source:(\S*)/,format:"x-source:%s"},{name:"xSourceStreamId",reg:/^x-source-streamid:(\S*)/,format:"x-source-streamid:%s"},{name:"xCaps",reg:/^x-caps:(\d*) (\S*)/,names:["payloadType","value"],format:"x-caps:%d %s"},{name:"signalingFbXMessage",reg:/^x-signaling-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(g){return"x-signaling-fb:"+("*"===g.payload?"%s":"%d")+" x-message %s"}},{push:"xMediaSettings",reg:/^x-mediasettings:([\S| ]*)/,names:["settings"],format:"x-mediasettings:%s"},{name:"xDataProtocol",reg:/^x-data-protocol:\s?(.*)/,format:"x-data-protocol:%s"},{push:"invalid",names:["value"]}]};Object.keys(S).forEach((function(g){S[g].forEach((function(g){g.reg||(g.reg=/(.*)/),g.format||(g.format="%s")}))}))}}),_e=__commonJS2({"../signaling-agent/node_modules/sdp-transform/lib/parser.js"(g){var toIntIfInt=function(g){return String(Number(g))===g?Number(g):g},attachProperties=function(g,f,S,v){if(v&&!S)f[v]=toIntIfInt(g[1]);else for(var C=0;C<S.length;C+=1)null!=g[C+1]&&(f[S[C]]=toIntIfInt(g[C+1]))},parseReg=function(g,f,S){var v=g.name&&g.names;g.push&&!f[g.push]?f[g.push]=[]:v&&!f[g.name]&&(f[g.name]={});var C=g.push?{}:v?f[g.name]:f;attachProperties(S.match(g.reg),C,g.names,g.name),g.push&&f[g.push].push(C)},f=Ee(),S=RegExp.prototype.test.bind(/^([a-z])=(.*)/);g.parse=function(g){var v={},C=[],_=v;return g.split(/(\r\n|\r|\n)/).filter(S).forEach((function(g){var S=g[0],v=g.slice(2);"m"===S&&(C.push({rtp:[],fmtp:[]}),_=C[C.length-1]);for(var T=0;T<(f[S]||[]).length;T+=1){var I=f[S][T];if(I.reg.test(v))return parseReg(I,_,v)}})),v.media=C,v};var paramReducer=function(g,f){var S=f.split(/=(.+)/,2);return 2===S.length?g[S[0]]=toIntIfInt(S[1]):1===S.length&&f.length>1&&(g[S[0]]=void 0),g};g.parseParams=function(g){return g.split(/;\s?/).reduce(paramReducer,{})},g.parseFmtpConfig=g.parseParams,g.parsePayloads=function(g){return g.toString().split(" ").map(Number)},g.parseRemoteCandidates=function(g){for(var f=[],S=g.split(" ").map(toIntIfInt),v=0;v<S.length;v+=3)f.push({component:S[v],ip:S[v+1],port:S[v+2]});return f},g.parseImageAttributes=function(g){return g.split(" ").map((function(g){return g.substring(1,g.length-1).split(",").reduce(paramReducer,{})}))},g.parseSimulcastStreamList=function(g){return g.split(";").map((function(g){return g.split(",").map((function(g){var f,S=!1;return"~"!==g[0]?f=toIntIfInt(g):(f=toIntIfInt(g.substring(1,g.length)),S=!0),{scid:f,paused:S}}))}))}}}),Te=__commonJS2({"../signaling-agent/node_modules/sdp-transform/lib/writer.js"(g,f){var S=Ee(),v=/%[sdv%]/g,format=function(g){var f=1,S=arguments,C=S.length;return g.replace(v,(function(g){if(f>=C)return g;var v=S[f];switch(f+=1,g){case"%%":return"%";case"%s":return String(v);case"%d":return Number(v);case"%v":return""}}))},makeLine=function(g,f,S){var v=[g+"="+(f.format instanceof Function?f.format(f.push?S:S[f.name]):f.format)];if(f.names)for(var C=0;C<f.names.length;C+=1){var _=f.names[C];f.name?v.push(S[f.name][_]):v.push(S[f.names[C]])}else v.push(S[f.name]);return format.apply(null,v)},C=["v","o","s","i","u","e","p","c","b","t","r","z","a"],_=["i","c","b","a"];f.exports=function(g,f){f=f||{},null==g.version&&(g.version=0),null==g.name&&(g.name=" "),g.media.forEach((function(g){null==g.payloads&&(g.payloads="")}));var v=f.outerOrder||C,T=f.innerOrder||_,I=[];return v.forEach((function(f){S[f].forEach((function(S){S.name in g&&null!=g[S.name]?I.push(makeLine(f,S,g)):S.push in g&&null!=g[S.push]&&g[S.push].forEach((function(g){I.push(makeLine(f,S,g))}))}))})),g.media.forEach((function(g){I.push(makeLine("m",S.m[0],g)),T.forEach((function(f){S[f].forEach((function(S){S.name in g&&null!=g[S.name]?I.push(makeLine(f,S,g)):S.push in g&&null!=g[S.push]&&g[S.push].forEach((function(g){I.push(makeLine(f,S,g))}))}))}))})),I.join("\r\n")+"\r\n"}}}),Ie=__commonJS2({"../signaling-agent/node_modules/sdp-transform/lib/index.js"(g){var f=_e(),S=Te();g.write=S,g.parse=f.parse,g.parseParams=f.parseParams,g.parseFmtpConfig=f.parseFmtpConfig,g.parsePayloads=f.parsePayloads,g.parseRemoteCandidates=f.parseRemoteCandidates,g.parseImageAttributes=f.parseImageAttributes,g.parseSimulcastStreamList=f.parseSimulcastStreamList}}),be=__commonJS2({"../skype-calling-utilities/dist/skype-calling-utilities.bundle.js"(g,f){var S,v;S=g,v=(g,f)=>{var S={},v={exports:S},C=Object.defineProperty,_=Object.getOwnPropertyDescriptor,T=Object.getOwnPropertyNames,I=Object.prototype.hasOwnProperty,__copyProps22=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let b of T(f))I.call(g,b)||b===S||C(g,b,{get:()=>f[b],enumerable:!(v=_(f,b))||v.enumerable});return g},__toCommonJS22=g=>__copyProps22(C({},"__esModule",{value:!0}),g),b={};((g,f)=>{for(var S in f)C(g,S,{get:f[S],enumerable:!0})})(b,{SlimCoreElectronControlCapturer:()=>H}),v.exports=__toCommonJS22(b);var A=M;function stringifyObject22(g){if(!g)return`${g}`;if(g instanceof Map)return mapToString22(g);const f=g.toString();return f.endsWith("[object Object]")?JSON.stringify(g):f}function mapToString22(g){const f={};return g.forEach(((g,S)=>{f[S.toString()]=g})),JSON.stringify(f)}var P,R=class{constructor(g){this.eventLogger=g,this.subscriptions=[]}subscribe(g){return new w(this.subscriptions,g)}dispose(g){this.subscriptions=[]}raiseEvents(g){this.subscriptions.slice().forEach((f=>{try{void 0!==f.eventHandler&&g(f.eventHandler)}catch(g){this.eventLogger?.warn?.("Event handler exception caught!",stringifyObject22(g))}}))}},w=class{constructor(g,f){this.subscriptions=g,this.eventHandler=f,this.subscriptions.push(this)}dispose(){(0,A.remove)(this.subscriptions,(g=>g===this)),this.eventHandler=void 0}},O=class extends R{constructor(g){super(g)}changed(g,f){return this.subscribe({changed:{skipEventConfig:f,handler:g},on:void 0})}on(g,f){return this.subscribe({changed:void 0,on:{name:String(g),handler:this._toEventCallback(f)}})}once(g,f,S){let v;const onceSubscription=(...g)=>{v.dispose(S),this._toEventCallback(f)(...g)};return v=this.on(g,this._fromEventCallback(onceSubscription)),v}raiseChanged(g){this.raiseEvents((f=>{if(!f.changed)return;const{skipEventConfig:S,handler:v}=f.changed;!this.getShouldSkipChangedEvent(g,S)&&v()}))}event(g){return{raise:this._fromEventCallback(((...f)=>this._raiseEventImpl(String(g),...f)))}}_raiseEventImpl(g,...f){this.raiseEvents((S=>S.on&&S.on.name===g&&S.on.handler(...f)))}_toEventCallback(g){return g}_fromEventCallback(g){return g}getShouldSkipChangedEvent(g,f){return g?.skipDominantSpeakerUpdatesOnCall?!!f?.skipDominantSpeakerUpdatesOnCall:!!g?.skipParticipantsUpdatesOnCall&&!!f?.skipParticipantsUpdatesOnCall}async onAsync(g,f){return this.on(g,f)}async onceAsync(g,f,S){return this.once(g,f,S)}async changedAsync(g,f){return this.changed(g,f)}async disposeAsync(g){this.dispose(g)}};(g=>{const f=7,S=3;function encodeMouseEvent(g){if(!g)return new Uint8Array(0);g.buttonType||(g.buttonType=0),g.xPos||(g.xPos=0),g.yPos||(g.yPos=0),g.wheelRotation||(g.wheelRotation=0);const S=new ArrayBuffer(f),v=new DataView(S),C=(3&g.type)<<0,_=(7&g.buttonType)<<2,T=(g.buttonDown?1:0)<<5,I=(g.wheelButtonDown?1:0)<<6,b=0;return v.setUint8(0,1),v.setUint8(1,C|_|T|I|b),v.setUint16(2,g.xPos,!0),v.setUint16(4,g.yPos,!0),v.setUint8(6,g.wheelRotation),new Uint8Array(S)}function encodeKeyboardEvent(g){const f=new ArrayBuffer(S),v=new DataView(f),C=(3&g.codeType)<<0,_=0,T=(g.keyUp?1:0)<<4,I=(g.repeat?1:0)<<5,b=0,A=0;return v.setUint8(0,0),v.setUint8(1,C|_|T|I|b|A),v.setUint8(2,g.code),new Uint8Array(f)}function decodeEventType(g){return g[0]}function decodeMouseEvent(g){if(1!==g[0]||g.length!==f)return null;const S=new DataView(g.buffer),v=S.getUint8(1);return{type:3&v,buttonType:v>>2&7,buttonDown:!!(v>>5&1),wheelButtonDown:!!(v>>6&1),xPos:S.getUint16(2,!0),yPos:S.getUint16(4,!0),wheelRotation:S.getUint8(6)}}function decodeKeyboardEvent(g){if(0!==g[0]||g.length!==S)return null;const f=new DataView(g.buffer),v=f.getUint8(1);return{codeType:3&v,code:f.getUint8(2),repeat:!!(v>>5&1),keyUp:!!(v>>4&1)}}g.encodeMouseEvent=encodeMouseEvent,g.encodeKeyboardEvent=encodeKeyboardEvent,g.decodeEventType=decodeEventType,g.decodeMouseEvent=decodeMouseEvent,g.decodeKeyboardEvent=decodeKeyboardEvent})(P||(P={}));var D=65535,N=3e3,k=250,L=18,F=17,x=16,U=91,V=50,B=30,H=class extends O{constructor(g,f,S=!0,v=1){super(),this._logger=g,this._element=f,this._captureRegionPreserveAspectRatio=S,this._mouseMoveCount=0,this._mouseMoveStartTime=0,this._isMouseDown=!1,this._isMouseOnRenderer=!1,this._captureMode=0,this._pollTimerID=0,this._resizeTimerID=0,this._mouseMoveThrottlingEnabled=!1,this._handleResizeEvents=()=>{clearTimeout(this._resizeTimerID),this._resizeTimerID=window.setTimeout((()=>{this.updateCaptureRegion()}),k)},this._handleMouseLeave=g=>{!this._isOnScreenContent(g)&&this._isMouseOnRenderer&&(this._raiseCaptureEvent(2),this._logger.info("Mouse leaving render region")),this._isMouseOnRenderer=!1},this._handleMouseEnter=g=>{this._isOnScreenContent(g)&&(this._isMouseOnRenderer=!0,this._raiseCaptureEvent(1),this._logger.info("Mouse entering render region"))},this._handleLosingFocus=()=>{this._syncKeyStates(!0)},this._handleClick=g=>{this._isOnScreenContent(g)&&(this._raiseCaptureEvent(0),this._logger.info("Mouse clicked"))},this._handleMouseMove=g=>{if(!this._isOnScreenContent(g)&&this._isMouseOnRenderer)return this._raiseCaptureEvent(2),this._isMouseOnRenderer=!1,void this._logger.info("Mouse leaving render region");if(this._isOnScreenContent(g)&&!this._isMouseOnRenderer&&(this._raiseCaptureEvent(1),this._isMouseOnRenderer=!0,this._logger.info("Mouse entering render region")),2!==this._captureMode&&3!==this._captureMode)return;if(this._mouseMoveCount++,this._mouseMoveThrottlingEnabled){if(!this._isOnScreenContent(g)||!this._shouldMoveMouse())return}else if(!this._isOnScreenContent(g)||this._mouseMoveCount%2==0)return;const f={type:0};this._normalizeMousePosition(g,f),this._raiseMouseEvent(f)},this._handleMouseDown=g=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(g))return;const f={type:2,buttonType:convertButton(g.button),buttonDown:!0};this._isMouseDown=!0,this._normalizeMousePosition(g,f),this._raiseMouseEvent(f)},this._handleMouseUp=g=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(g))return;const f={type:2,buttonType:convertButton(g.button),buttonDown:!1};this._isMouseDown=!1,this._normalizeMousePosition(g,f),this._raiseMouseEvent(f)},this._handleKeyDown=g=>{this._raiseKeyboardEvent({codeType:1,code:g.keyCode,repeat:g.repeat,keyUp:!1}),g.stopPropagation(),g.preventDefault()},this._handleKeyUp=g=>{this._raiseKeyboardEvent({codeType:1,code:g.keyCode,repeat:g.repeat,keyUp:!0}),g.stopPropagation(),g.preventDefault()},this._handleWheel=g=>{this._raiseMouseEvent({type:1,wheelRotation:g.deltaY>0?-120:120})},this._handleContextMenu=g=>{g.preventDefault()},this._ensureCanReceiveKeyboardInput(),this._element.ownerDocument?.defaultView?.addEventListener("resize",this._handleResizeEvents,!1),this._captureRegion={left:0,top:0,width:this._element.clientWidth,height:this._element.clientHeight},this._videoSize={width:Math.floor(f.clientHeight*v),height:f.clientHeight},this._origElementSize={width:0,height:0},this._checkElementSize(),this._mouseMoveStartTime=new Date(0).getTime()}get captureMode(){return this._captureMode}get captureRegion(){return this._captureRegion}setMouseMoveThrottlingFeatureFlag(g){this._mouseMoveThrottlingEnabled=g}dispose(g){this._logger.info(`dispose causeId: ${g}`),window.clearTimeout(this._pollTimerID),this._element.ownerDocument?.defaultView?.removeEventListener("resize",this._handleResizeEvents,!1),super.dispose(g)}updateVideoSize(g,f){this._videoSize.width=g,this._videoSize.height=f,this.updateCaptureRegion()}updateCaptureRegion(){this._captureRegionPreserveAspectRatio?(this._captureRegion.width=this._element.clientWidth,this._captureRegion.height=this._element.clientWidth*this._videoSize.height/this._videoSize.width,this._captureRegion.height>this._element.clientHeight?(this._captureRegion.width=this._element.clientHeight*this._videoSize.width/this._videoSize.height,this._captureRegion.height=this._element.clientHeight,this._captureRegion.left=(this._element.clientWidth-this._captureRegion.width)/2,this._captureRegion.top=0):(this._captureRegion.left=0,this._captureRegion.top=(this._element.clientHeight-this._captureRegion.height)/2)):(this._captureRegion.width=this._element.clientWidth,this._captureRegion.height=this._element.clientHeight,this._captureRegion.top=0,this._captureRegion.left=0)}setCaptureMode(g){3===this._captureMode&&3!==g&&this._syncKeyStates(!0),this._captureMode=g,0!==g?("none"===this._element.style.pointerEvents&&this._logger.warn("Element pointer-events is 'none', event handlers will not work"),this._element.addEventListener("click",this._handleClick),this._element.addEventListener("pointermove",this._handleMouseMove),this._element.addEventListener("pointerdown",this._handleMouseDown),this._element.addEventListener("pointerup",this._handleMouseUp),this._element.addEventListener("pointerenter",this._handleMouseEnter),this._element.addEventListener("pointerleave",this._handleMouseLeave),3===g?(this._element.addEventListener("wheel",this._handleWheel),this._element.addEventListener("keydown",this._handleKeyDown),this._element.addEventListener("keyup",this._handleKeyUp),this._element.addEventListener("contextmenu",this._handleContextMenu),this._element.addEventListener("blur",this._handleLosingFocus)):(this._element.removeEventListener("wheel",this._handleWheel),this._element.removeEventListener("keydown",this._handleKeyDown),this._element.removeEventListener("keyup",this._handleKeyUp),this._element.removeEventListener("contextmenu",this._handleContextMenu),this._element.removeEventListener("blur",this._handleLosingFocus))):(this._element.removeEventListener("pointermove",this._handleMouseMove),this._element.removeEventListener("pointerdown",this._handleMouseDown),this._element.removeEventListener("pointerup",this._handleMouseUp),this._element.removeEventListener("pointerenter",this._handleMouseEnter),this._element.removeEventListener("pointerleave",this._handleMouseLeave),this._element.removeEventListener("click",this._handleClick),this._element.removeEventListener("wheel",this._handleWheel),this._element.removeEventListener("keydown",this._handleKeyDown),this._element.removeEventListener("keyup",this._handleKeyUp),this._element.removeEventListener("contextmenu",this._handleContextMenu),this._element.removeEventListener("blur",this._handleLosingFocus))}_ensureCanReceiveKeyboardInput(){this._element.tabIndex=this._element.tabIndex}_checkElementSize(){this._origElementSize.width===this._element.clientWidth&&this._origElementSize.height===this._element.clientHeight||(this.updateCaptureRegion(),this._origElementSize.width=this._element.clientWidth,this._origElementSize.height=this._element.clientHeight),this._pollTimerID=window.setTimeout((()=>{this._checkElementSize()}),N)}_raiseMouseEvent(g){this.event("mouseControlEvent").raise(g)}_raiseKeyboardEvent(g){this.event("keyboardControlEvent").raise(g)}_raiseCaptureEvent(g){this.event("ctrlCaptureEvent").raise(g)}_normalizeMousePosition(g,f){f.xPos=(g.offsetX-this._captureRegion.left)/this._captureRegion.width*D,f.yPos=(g.offsetY-this._captureRegion.top)/this._captureRegion.height*D}_isOnScreenContent(g){const f=this._captureRegion.left,S=this._captureRegion.left+this._captureRegion.width,v=this._captureRegion.top,C=this._captureRegion.top+this._captureRegion.height;return f<=g.offsetX&&g.offsetX<S&&v<=g.offsetY&&g.offsetY<C}_shouldMoveMouse(){if(this._mouseMoveStartTime){const g=(new Date).getTime(),f=g-this._mouseMoveStartTime;if(this._isMouseDown&&f>=B||!this._isMouseDown&&f>=V)return this._mouseMoveStartTime=g,!0}else this._mouseMoveStartTime=(new Date).getTime();return!1}_syncKeyStates(g){this._raiseKeyboardEvent({codeType:1,code:F,repeat:!1,keyUp:g}),this._raiseKeyboardEvent({codeType:1,code:x,repeat:!1,keyUp:g}),this._raiseKeyboardEvent({codeType:1,code:L,repeat:!1,keyUp:g}),this._raiseKeyboardEvent({codeType:1,code:U,repeat:!1,keyUp:g}),this._logger.info("Synced Key states.")}static formatMouseEvent(g){return P.encodeMouseEvent(g)}static formatKeyboardEvent(g){return P.encodeKeyboardEvent(g)}};function convertButton(g){switch(g){case 0:return 0;case 2:return 1;case 1:return 2;default:return}}if("object"==typeof v.exports&&"object"==typeof S){var __cp2=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let C of Object.getOwnPropertyNames(f))Object.prototype.hasOwnProperty.call(g,C)||C===S||Object.defineProperty(g,C,{get:()=>f[C],enumerable:!(v=Object.getOwnPropertyDescriptor(f,C))||v.enumerable});return g};v.exports=__cp2(v.exports,S)}return v.exports},"object"==typeof g&&"object"==typeof f?f.exports=v(R,M):"object"==typeof g?g["skype-calling-utilities"]=v(R,M):S["skype-calling-utilities"]=v(S["@skype/rt-js-bindings"],S.lodash)}}),Ae=__commonJS2({"../node_modules/synctasks/dist/SyncTasks.js"(g){function fromThenable(g){var f=Defer();return g.then((function(g){f.resolve(g)}),(function(g){f.reject(g)})),f.promise().thenAsync((function(g){return g}))}function isThenable(g){return null!=g&&"function"==typeof g.then}function isCancelable(g){return null!=g&&"function"==typeof g.cancel}function run(f,S){if(!g.config.catchExceptions)return f();try{return f()}catch(g){return S(g)}}Object.defineProperty(g,"__esModule",{value:!0}),g.config={exceptionsToConsole:!0,catchExceptions:!0,traceEnabled:!1,exceptionHandler:void 0,unhandledErrorHandler:function(g){throw g}},g.fromThenable=fromThenable;var f,S,v,C=[],_="undefined"!=typeof setImmediate;function asyncCallback(g){C.push(g),1===C.length&&(_?setImmediate(resolveAsyncCallbacks):setTimeout(resolveAsyncCallbacks,0))}function resolveAsyncCallbacks(){var g=C;C=[];for(var f=0;f<g.length;f++)g[f]()}function all(g){if(0===g.length)return Resolved2([]);var S,v=Defer(),C=g.length,_=Array(g.length);v.onCancel((function(S){g.forEach((function(g){isCancelable(g)&&f.SyncTask.cancelOtherInternal(g,S)}))}));var checkFinish=function(){0==--C&&(void 0!==S?v.reject(S):v.resolve(_))};return g.forEach((function(g,f){isThenable(g)?g.then((function(g){_[f]=g,checkFinish()}),(function(g){void 0===S&&(S=void 0===g||g),checkFinish()})):(_[f]=g,checkFinish())})),v.promise()}function Defer(){return new f.SyncTask}function Resolved2(g){return(new f.SyncTask).resolve(g).promise()}function Rejected(g){return(new f.SyncTask).reject(g).promise()}function race(g){var S=Defer(),v=!1;return S.onCancel((function(S){g.forEach((function(g){isCancelable(g)&&f.SyncTask.cancelOtherInternal(g,S)}))})),g.forEach((function(g){isThenable(g)?g.then((function(g){v||(v=!0,S.resolve(g))}),(function(g){v||(v=!0,S.reject(g))})):v||(v=!0,S.resolve(g))})),S.promise()}function raceTimer(g,f){var S=Defer(),v=setTimeout((function(){S.resolve({timedOut:!0})}),f);return race([g.then((function(g){return clearTimeout(v),{timedOut:!1,result:g}})),S.promise()])}g.asyncCallback=asyncCallback,S=f||(f={}),v=function(){function SyncTask2(){this._completedSuccess=!1,this._completedFail=!1,this._traceEnabled=!1,this._cancelCallbacks=[],this._wasCanceled=!1,this._wasExplicitlyCanceled=!1,this._resolving=!1,this._storedCallbackSets=[],this._mustHandleError=!0}return SyncTask2.prototype._addCallbackSet=function(g,f){var S=this,v=new SyncTask2;return v.onCancel((function(f){g.wasCanceled=!0,g.cancelContext=f,S._cancelInternal(f)})),g.task=v,this._storedCallbackSets.push(g),f?this._mustHandleError=!1:v._mustHandleError=!1,this._resolving||(this._completedSuccess?this._resolveSuccesses():this._completedFail&&this._resolveFailures()),v.promise()},SyncTask2.prototype.onCancel=function(g){return this._completedSuccess||this._completedFail||(this._wasCanceled?g(this._cancelContext):this._cancelCallbacks.push(g)),this},SyncTask2.prototype.then=function(g,f){return this._addCallbackSet({successFunc:g,failFunc:f},!0)},SyncTask2.prototype.thenAsync=function(g,f){return this._addCallbackSet({successFunc:g,failFunc:f,asyncCallback:!0},!0)},SyncTask2.prototype.catch=function(g){return this._addCallbackSet({failFunc:g},!0)},SyncTask2.prototype.always=function(g){return this._addCallbackSet({successFunc:g,failFunc:g},!0)},SyncTask2.prototype.setTracingEnabled=function(g){return this._traceEnabled=g,this},SyncTask2.prototype.finally=function(g){return this._addCallbackSet({successFunc:g,failFunc:g},!1),this},SyncTask2.prototype.done=function(g){return this._addCallbackSet({successFunc:g},!1),this},SyncTask2.prototype.fail=function(g){return this._addCallbackSet({failFunc:g},!1),this},SyncTask2.prototype.resolve=function(g){return this._checkState(!0),this._completedSuccess=!0,this._storedResolution=g,this._cancelCallbacks=[],this._resolveSuccesses(),this},SyncTask2.prototype.reject=function(g){return this._checkState(!1),this._completedFail=!0,this._storedErrResolution=g,this._cancelCallbacks=[],this._resolveFailures(),SyncTask2._enforceErrorHandled(this),this},SyncTask2.prototype._checkState=function(f){if(this._completedSuccess||this._completedFail){this._completeStack&&console.error(this._completeStack.message,this._completeStack.stack);var S="Failed to "+(f?"resolve":"reject")+": the task is already "+(this._completedSuccess?"resolved":"rejected");throw new Error(S)}(g.config.traceEnabled||this._traceEnabled)&&(this._completeStack=new Error("resolve"))},SyncTask2._enforceErrorHandled=function(f){f._mustHandleError&&(SyncTask2._rejectedTasks.push(f),SyncTask2._enforceErrorHandledTimer||(SyncTask2._enforceErrorHandledTimer=setTimeout((function(){SyncTask2._enforceErrorHandledTimer=void 0;var f=SyncTask2._rejectedTasks;SyncTask2._rejectedTasks=[],f.forEach((function(f,S){f._mustHandleError&&g.config.unhandledErrorHandler(f._storedErrResolution)}))}),0)))},SyncTask2.prototype.cancel=function(g){if(this._wasExplicitlyCanceled)throw new Error("Already Canceled");this._wasExplicitlyCanceled=!0,this._cancelInternal(g)},SyncTask2.prototype._cancelInternal=function(g){var f=this;if(!this._wasCanceled){this._wasCanceled=!0,this._cancelContext=g;var S=this._cancelCallbacks;this._cancelCallbacks=[],S.length>0&&S.forEach((function(g){f._completedSuccess||f._completedFail||g(f._cancelContext)}))}},SyncTask2.cancelOtherInternal=function(g,f){var S=g;S._storedCallbackSets&&S._cancelInternal?S._cancelInternal(f):g.cancel(f)},SyncTask2.prototype.promise=function(){return this},SyncTask2.prototype._resolveSuccesses=function(){var g=this;for(this._resolving=!0;this._storedCallbackSets.length;){var f=this._storedCallbackSets;this._storedCallbackSets=[],f.forEach((function(f){f.asyncCallback?asyncCallback((function(){return g._resolveSuccessCallback(f)})):g._resolveSuccessCallback(f)}))}this._resolving=!1},SyncTask2.prototype._resolveSuccessCallback=function(g){var f=this;g.successFunc?run((function(){var S=g.successFunc(f._storedResolution);isCancelable(S)&&(g.wasCanceled?SyncTask2.cancelOtherInternal(S,g.cancelContext):g.task.onCancel((function(g){return SyncTask2.cancelOtherInternal(S,g)}))),isThenable(S)?S.then((function(f){g.task.resolve(f)}),(function(f){g.task.reject(f)})):g.task.resolve(S)}),(function(S){f._handleException(S,"SyncTask caught exception in success block: "+S.toString()),g.task.reject(S)})):g.task.resolve(this._storedResolution)},SyncTask2.prototype._resolveFailures=function(){var g=this;for(this._resolving=!0;this._storedCallbackSets.length;){var f=this._storedCallbackSets;this._storedCallbackSets=[],f.forEach((function(f){f.asyncCallback?asyncCallback((function(){return g._resolveFailureCallback(f)})):g._resolveFailureCallback(f)}))}this._resolving=!1},SyncTask2.prototype._resolveFailureCallback=function(g){var f=this;g.failFunc?run((function(){var S=g.failFunc(f._storedErrResolution);isCancelable(S)&&(g.wasCanceled?SyncTask2.cancelOtherInternal(S,g.cancelContext):g.task.onCancel((function(g){return SyncTask2.cancelOtherInternal(S,g)}))),isThenable(S)?S.then((function(f){g.task.resolve(f)}),(function(f){g.task.reject(f)})):g.task.resolve(S)}),(function(S){f._handleException(S,"SyncTask caught exception in failure block: "+S.toString()),g.task.reject(S)})):g.task.reject(this._storedErrResolution)},SyncTask2.prototype._handleException=function(f,S){g.config.exceptionsToConsole&&console.error(S),g.config.exceptionHandler&&g.config.exceptionHandler(f)},SyncTask2.prototype.toEs6Promise=function(){var g=this;return new Promise((function(f,S){return g.then(f,S)}))},SyncTask2._rejectedTasks=[],SyncTask2}(),S.SyncTask=v,g.all=all,g.Defer=Defer,g.Resolved=Resolved2,g.Rejected=Rejected,g.race=race,g.raceTimer=raceTimer}}),Pe=__commonJS2({"../node_modules/sdp-transform/lib/grammar.js"(g,f){var S=f.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\S*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(g){return g.encoding?"rtpmap:%d %s/%s/%s":g.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(g){return null!=g.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(g){return"rtcp-fb:"+("*"===g.payload?"%s":"%d")+" x-message %s"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%d trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(g){return null!=g.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(g){return"extmap:%d"+(g.direction?"/%s":"%v")+(g["encrypt-uri"]?" %s":"%v")+" %s"+(g.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"cryptoscale",reg:/^cryptoscale:(\d*) (client|server) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","flavor","suite","config","sessionConfig"],format:function(g){return null!=g.sessionConfig?"cryptoscale:%d %s %s %s %s":"cryptoscale:%d %s %s %s"}},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(g){return null!=g.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(g){var f="candidate:%s %d %s %d %s %d typ %s";return f+=null!=g.raddr?" raddr %s rport %d":"%v%v",f+=null!=g.tcptype?" tcptype %s":"%v",null!=g.generation&&(f+=" generation %d"),f+=null!=g["network-id"]?" network-id %d":"%v",f+=null!=g["network-cost"]?" network-cost %d":"%v"}},{push:"xCandidatesIpv6",reg:/^x-candidate-ipv6:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation"],format:function(g){var f="candidate:%s %d %s %d %s %d typ %s";return f+=null!=g.raddr?" raddr %s rport %d":"%v%v",f+=null!=g.tcptype?" tcptype %s":"%v",null!=g.generation&&(f+=" generation %d"),f}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(g){var f="ssrc:%d";return null!=g.attribute&&(f+=" %s",null!=g.value&&(f+=":%s")),f}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(g){return null!=g.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(g){return g.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(g){return"imageattr:%s %s %s"+(g.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(g){return"simulcast:%s %s"+(g.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(g){return"ts-refclk:%s"+(null!=g.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(g){var f="mediaclk:";return f+=null!=g.id?"id=%s %s":"%v%s",f+=null!=g.mediaClockValue?"=%s":"",f+=null!=g.rateNumerator?" rate=%s":"",f+=null!=g.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{name:"xMediaBw",reg:/^x-mediabw:(\S*) send=(\d*);recv=(\d*)/,names:["label","sendBw","receiveBw"],format:"x-mediabw:%s send=%d;recv=%d"},{name:"xSsrcRange",reg:/^x-ssrc-range:(\d*)-(\d*)/,names:["ssrcMin","ssrcMax"],format:"x-ssrc-range:%d-%d"},{name:"xSource",reg:/^x-source:(\S*)/,format:"x-source:%s"},{name:"xSourceStreamId",reg:/^x-source-streamid:(\S*)/,format:"x-source-streamid:%s"},{name:"xCaps",reg:/^x-caps:(\d*) (\S*)/,names:["payloadType","value"],format:"x-caps:%d %s"},{name:"signalingFbXMessage",reg:/^x-signaling-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(g){return"x-signaling-fb:"+("*"===g.payload?"%s":"%d")+" x-message %s"}},{push:"xMediaSettings",reg:/^x-mediasettings:([\S| ]*)/,names:["settings"],format:"x-mediasettings:%s"},{name:"xDataProtocol",reg:/^x-data-protocol:\s?(.*)/,format:"x-data-protocol:%s"},{name:"xMultiStream",reg:/^x-multi-stream:(\d*) (\d*) (\d*) (\d*)/,names:["numberOfStreams","startSsrc","ssrcRange","ssrcGroupRange"],format:"x-multi-stream:%d %d %d %d"},{push:"invalid",names:["value"]}]};Object.keys(S).forEach((function(g){S[g].forEach((function(g){g.reg||(g.reg=/(.*)/),g.format||(g.format="%s")}))}))}}),Re=__commonJS2({"../node_modules/sdp-transform/lib/parser.js"(g){var toIntIfInt=function(g){return String(Number(g))===g?Number(g):g},attachProperties=function(g,f,S,v){if(v&&!S)f[v]=toIntIfInt(g[1]);else for(var C=0;C<S.length;C+=1)null!=g[C+1]&&(f[S[C]]=toIntIfInt(g[C+1]))},parseReg=function(g,f,S){var v=g.name&&g.names;g.push&&!f[g.push]?f[g.push]=[]:v&&!f[g.name]&&(f[g.name]={});var C=g.push?{}:v?f[g.name]:f;attachProperties(S.match(g.reg),C,g.names,g.name),g.push&&f[g.push].push(C)},f=Pe(),S=RegExp.prototype.test.bind(/^([a-z])=(.*)/);g.parse=function(g){var v={},C=[],_=v;return g.split(/(\r\n|\r|\n)/).filter(S).forEach((function(g){var S=g[0],v=g.slice(2);"m"===S&&(C.push({rtp:[],fmtp:[]}),_=C[C.length-1]);for(var T=0;T<(f[S]||[]).length;T+=1){var I=f[S][T];if(I.reg.test(v))return parseReg(I,_,v)}})),v.media=C,v};var paramReducer=function(g,f){var S=f.split(/=(.+)/,2);return 2===S.length?g[S[0]]=toIntIfInt(S[1]):1===S.length&&f.length>1&&(g[S[0]]=void 0),g};g.parseParams=function(g){return g.split(/;\s?/).reduce(paramReducer,{})},g.parseFmtpConfig=g.parseParams,g.parsePayloads=function(g){return g.toString().split(" ").map(Number)},g.parseRemoteCandidates=function(g){for(var f=[],S=g.split(" ").map(toIntIfInt),v=0;v<S.length;v+=3)f.push({component:S[v],ip:S[v+1],port:S[v+2]});return f},g.parseImageAttributes=function(g){return g.split(" ").map((function(g){return g.substring(1,g.length-1).split(",").reduce(paramReducer,{})}))},g.parseSimulcastStreamList=function(g){return g.split(";").map((function(g){return g.split(",").map((function(g){var f,S=!1;return"~"!==g[0]?f=toIntIfInt(g):(f=toIntIfInt(g.substring(1,g.length)),S=!0),{scid:f,paused:S}}))}))}}}),Me=__commonJS2({"../node_modules/sdp-transform/lib/writer.js"(g,f){var S=Pe(),v=/%[sdv%]/g,format=function(g){var f=1,S=arguments,C=S.length;return g.replace(v,(function(g){if(f>=C)return g;var v=S[f];switch(f+=1,g){case"%%":return"%";case"%s":return String(v);case"%d":return Number(v);case"%v":return""}}))},makeLine=function(g,f,S){var v=[g+"="+(f.format instanceof Function?f.format(f.push?S:S[f.name]):f.format)];if(f.names)for(var C=0;C<f.names.length;C+=1){var _=f.names[C];f.name?v.push(S[f.name][_]):v.push(S[f.names[C]])}else v.push(S[f.name]);return format.apply(null,v)},C=["v","o","s","i","u","e","p","c","b","t","r","z","a"],_=["i","c","b","a"];f.exports=function(g,f){f=f||{},null==g.version&&(g.version=0),null==g.name&&(g.name=" "),g.media.forEach((function(g){null==g.payloads&&(g.payloads="")}));var v=f.outerOrder||C,T=f.innerOrder||_,I=[];return v.forEach((function(f){S[f].forEach((function(S){S.name in g&&null!=g[S.name]?I.push(makeLine(f,S,g)):S.push in g&&null!=g[S.push]&&g[S.push].forEach((function(g){I.push(makeLine(f,S,g))}))}))})),g.media.forEach((function(g){I.push(makeLine("m",S.m[0],g)),T.forEach((function(f){S[f].forEach((function(S){S.name in g&&null!=g[S.name]?I.push(makeLine(f,S,g)):S.push in g&&null!=g[S.push]&&g[S.push].forEach((function(g){I.push(makeLine(f,S,g))}))}))}))})),I.join("\r\n")+"\r\n"}}}),we=__commonJS2({"../node_modules/sdp-transform/lib/index.js"(g){var f=Re(),S=Me();g.write=S,g.parse=f.parse,g.parseParams=f.parseParams,g.parseFmtpConfig=f.parseFmtpConfig,g.parsePayloads=f.parsePayloads,g.parseRemoteCandidates=f.parseRemoteCandidates,g.parseImageAttributes=f.parseImageAttributes,g.parseSimulcastStreamList=f.parseSimulcastStreamList}}),Oe={};__export2(Oe,{HttpRequestDispatcherImplementation:()=>$e,generateCauseId:()=>generateCauseId,getOvb:()=>getOvb2,getVersion:()=>getTsCallingVersion2,pluginlessStackFactory:()=>gw,whiteList:()=>pw}),v.exports=__toCommonJS2(Oe);var De=__toESM2(ie()),Ne=8;function generateCauseId(){const g="abcdef0123456789",f=g.length;let S="";for(let v=0;v<Ne;v++)S+=g.charAt(Math.floor(Math.random()*f));return S}function validateCauseId(g){return new RegExp("^[a-f0-9]{8}$").test(g)&&g.length===Ne}var ke=R,Le=M,Fe=class _TsCallingLogger{constructor(g,f,S=""){this.ulLogComponent=g,this.ulSafeComponent=f,this._getPrefix=(0,Le.isFunction)(S)?S:()=>S,this.logComponent=ke.LogFactory.instance().component(this.ulLogComponent),ke.LogFactory.instance().declareComponentSafe(this.ulLogComponent,f)}createChild(g){const f=(0,Le.isFunction)(g)?g:()=>g;return new _TsCallingLogger(this.ulLogComponent,this.ulSafeComponent,(()=>this._getPrefix()?`${this._getPrefix()}/${f()}`:f()))}log(...g){this._apply((g=>this.logComponent.debug2(null,g)),g)}debug(...g){this._apply((g=>this.logComponent.debug4(null,g)),g)}info(...g){this._apply((g=>this.logComponent.debug1(null,g)),g)}warn(...g){this._apply((g=>this.logComponent.warn(null,g)),g)}error(...g){this._apply((g=>this.logComponent.error(null,g)),g)}_apply(g,f=[]){this._addPrefix(f),g(f.map((g=>g instanceof DOMException?g.toString():g)).map((g=>(0,Le.isObject)(g)?JSON.stringify(g):g)).join(", "))}_addPrefix(g){if(g&&g[0]){const f=`${this._getPrefix()} ${g[0]}`;g[0]=f}}},xe=R,Ue=class{constructor(g,f){this.value=g,this.piiKind=f}},Ve=["id"," orgid","username","phonenumber"];function scrubMriOrOmit(g){return"string"==typeof g?xe.pii.Mri(g):xe.pii.Omit(g)}function scrubMriOrOmitList(g){try{return g.map(scrubMriOrOmit)}catch(g){return[]}}function scrubObjectFields(g,f=["id"],S={threadId:8}){if(!g||"object"!=typeof g)return g;try{let v=createDeepCopy(g);return v=scrubObjectData(v,f,S),v}catch(g){return{error:"failed to scrub object fields"}}}function scrubMriKeys(g){try{const f={};return Object.keys(g).forEach((S=>{const v=scrubMriOrOmit(S);f[v]=g[S]})),f}catch(g){return{error:"failed to scrub mri keys"}}}function getLoggableMriKeys(g){return JSON.stringify(scrubMriKeys(g))}function mriOrId(g){return g&&xe.pii.Mri(g)}function getLoggableThreadId(g){const f=_scrubThreadId(g);return f&&f.substr(0,8)}function _scrubThreadId(g){const f="99:";return g&&g.substr(0,3)===f?xe.pii.Omit(g):g}function createDeepCopy(g){if(!g||"object"!=typeof g)return g;const f=new Set,S=JSON.stringify(g,((g,S)=>{if("object"==typeof S&&null!==S){if(f.has(S))return;f.add(S)}return S}));return JSON.parse(S)}function scrubObjectData(g,f,S){if(!g||"object"!=typeof g)return g;const v={...g};for(const[C,_]of Object.entries(g))Array.isArray(_)?v[C]=_.map((g=>scrubObjectData(g,f,S))):"object"==typeof _?v[C]=scrubObjectData(_,f,S):"displayname"===C.toLowerCase()?v[C]="(redacted)":_&&(f.includes(C)||Ve.includes(C.toLowerCase())?v[C]=scrubMriOrOmit(_):S[C]&&"string"==typeof _&&(v[C]=_.toString().substring(0,S[C])));return v}function getMaskingRegex(g){const f=String.raw`[\\]*['|\"]?\s*[\:|=]\s*[\\]*['|\"]?`,S=String.raw`[a-zA-Z\d#.~?!@$%^&*-_()+]+?`;return new RegExp(String.raw`(${g}${f})(${S})(\\?['\"])`,"g")}function replacement(g,f,S,v,C){const _=scrubMriOrOmit(v);return String.raw`${f}${_}${C}`}function maskUserIdentity(g){if(!g)return null;const f=getMaskingRegex("([U|u]ser[N|n]ame|[O|o]rg[I|i]d)");return g.replace(f,replacement)}function maskSensitiveData(g,f="(redacted)"){if(!g)return null;const S=getMaskingRegex("([P|p]assword|[T|t]oken|[S|s]ecret|[A|a]uthorization|[D|d]isplay[N|n]ame|[P|p]honeNumber|[A|a]ddress|IP)");return maskUserIdentity(g.replace(S,`$1${f}$4`))}var Be=__toESM2(M),He=["response","responseText","responseURL","status","state","statusText","timeout","withCredentials","stack","message","name","error","piiSafe","phase","code","participantId","phrase","subCode","reason","conversationType","terminatedReason","terminatedReasonCode","terminatedReasonSubCode","errorMessage"];function getPIISafeObject(g){try{return JSON.parse(JSON.stringify(g,He,4))}catch(g){return{error:"failed to parse object"}}}var processStackTrace=g=>{try{return g.split("\n")[0]}catch(g){return"invalid stack"}};function getPrintableObject(g,f=!1){if(null==g)return"void";if(g instanceof Error)return g.toString();if(g instanceof String||g instanceof Number||g instanceof Boolean)return g.toString();try{return g.stack&&(g.stack=processStackTrace(g.stack)),(f?JSON.stringify(g):JSON.stringify(g,He,4)).replace(/(\r\n\t|\n|\r\t|\s)/gm,"")}catch(f){return`failed to get error information:${g&&"function"==typeof g.toString&&g.toString()} ${g?.response&&JSON.stringify(g.response)}`}}function safeJsonStringify(g){try{return JSON.stringify(g,null,2)}catch(f){return`failed to stringify obj ${g}`}}function truncate(g,f){try{return g.substring(0,f)}catch(f){return g}}function hasValue(g){return g||!1===g||""===g||0===g}function getPIISafeCallInitOptions(g){const f={mediaPeerType:g.mediaPeerType,threadId:getLoggableThreadId(g.threadId)};return hasValue(g.messageId)&&(f.messageId=g.messageId),hasValue(g.enableGroupCallMeetupGeneration)&&(f.enableGroupCallMeetupGeneration=g.enableGroupCallMeetupGeneration),hasValue(g.endpointMetadata)&&(f.endpointMetadata=g.endpointMetadata),hasValue(g.onBehalfOf)&&(f.onBehalfOf=scrubMriOrOmit(g.onBehalfOf)),hasValue(g.onBehalfOfUserDisplayName)&&(f.onBehalfOfUserDisplayName=g.onBehalfOfUserDisplayName),hasValue(g.emergencyContent)&&(f.emergencyContent=g.emergencyContent),hasValue(g.isEmergency)&&(f.isEmergency=g.isEmergency),hasValue(g.broadcastContext)&&(f.broadcastContext=g.broadcastContext),g.meetingInfo&&(f.meetingInfo={tenantId:g.meetingInfo.tenantId,organizerId:scrubMriOrOmit(g.meetingInfo.organizerId)},hasValue(g.meetingInfo.meetingType)&&(f.meetingInfo.meetingType=g.meetingInfo.meetingType),hasValue(g.meetingInfo.replyChainMessageId)&&(f.meetingInfo.replyChainMessageId=g.meetingInfo.replyChainMessageId)),g.transferContext&&(f.transferContext={transferorMri:scrubMriOrOmit(g.transferContext.transferorMri),targetMri:scrubMriOrOmit(g.transferContext.targetMri),context:scrubObjectFields(g.transferContext.context)},hasValue(g.transferContext.transferType)&&(f.transferContext.transferType=g.transferContext.transferType)),safeJsonStringify(f)}function getPIISafePayload(g,f){try{const S=scrubObjectFields(g);return Object.keys(g).forEach((v=>{f.includes(v)?S[v]=scrubMriOrOmit(g[v]):"conversationId"===v&&(S[v]=getLoggableThreadId(g[v]))})),safeJsonStringify(Be.omit(S,["body.gp"]))}catch(g){return{error:"failed to get safe payload"}}}function getPIISafeRequestResponse(g){try{let f=scrubObjectFields(g,["id","groupCallInitiator","organizerId"]);return scrubProperty(f,"response.roster.participants"),scrubProperty(f,"response.additionalActionResponses.0.output.roster.participants"),scrubProperty(f,"response.muteUnmuteResponse"),f=Be.omit(f,["meetingChatProperties"]),f=scrubRequestData(f),f}catch(g){return"failed to return safe response"}}function getPIISafeRequest(g){try{return scrubRequestData(scrubObjectFields(g))}catch(g){return"failed to return safe request"}}function scrubRequestData(g){if(g?.config?.data){let f=g.config.data;f=JSON.parse(f),f=scrubObjectFields(f),g.config.data=safeJsonStringify(f)}return safeJsonStringify(g)}function getPIISafeMessage(g){try{const f=scrubObjectFields(g,["id","groupCallInitiator"]);return scrubProperty(f,"body.participants"),safeJsonStringify(f)}catch(g){return"failed to return safe response"}}function getPIISafeEndpointDetails(g){try{return safeJsonStringify(scrubObjectFields(g,["originalId"]))}catch(g){return"failed to return safe endpoint details"}}function scrubProperty(g,f){g&&Be.get(g,f)&&Be.set(g,f,scrubMriKeys(Be.get(g,f)))}function getRandomizedTimeout(g){const f=Math.floor(11*Math.random())+10;return Math.floor(g*(1-f/100))}function isStringBase64(g){if(!g)return!1;try{return atob(g),!0}catch(g){return!1}}function isPromiseLike2(g){return!!g&&"function"==typeof g.then}function stringifyObject2(g){if(!g)return`${g}`;if(g instanceof Map)return mapToString2(g);const f=g.toString();return f.endsWith("[object Object]")?JSON.stringify(g):f}function stringifyRequestResponse(g){try{if(g.status)return`status: ${g.status}, URL: ${g.responseURL}, statusText: ${g.responseText}`}catch(g){}return stringifyObject2(g)}function mapToString2(g){const f={};return g.forEach(((g,S)=>{f[S.toString()]=g})),JSON.stringify(f)}function stringToBuffer(g){const f=new ArrayBuffer(g.length),S=new Uint8Array(f);for(let f=0;f<g.length;f++)S[f]=g.charCodeAt(f);return S}function limitArraySize2(g,f,S=0){return g&&void 0!==f&&f>-1&&g.length>f&&g.splice(S,g.length-f),g}function arrayLimitedPush2(g,f,S,v=0){limitArraySize2(g,0===S?0:S-1,v),0!==S&&g.push(f)}var $e=class{constructor(g){g&&"function"==typeof g.createChild?this.logger=g.createChild("RequestDispatcher"):this.logger=new Fe("JS.TsCalling.RequestDispatcher",!1)}getRequestOptions(g,f,S,v,C){return{headers:f||{},timeout:v,payload:S||null,responseType:C}}getAsync(g,f){return this.sendRequest(g,f,"GET")}postAsync(g,f){return this.sendRequest(g,f,"POST")}putAsync(g,f){return this.sendRequest(g,f,"PUT")}removeAsync(g,f){return this.sendRequest(g,f,"DELETE")}async sendRequest(g,f={headers:{}},S){return f.useFetch?this.sendFetchRequest(g,f,S):this.sendAxiosRequest(g,f,S)}async sendAxiosRequest(g,f={headers:{}},S){const v=this.logger.createChild(`[${f.causeId||generateCauseId()}][AxiosRequest]`);v.info(`sending, ${S}-${g}`);const C=Date.now();let _;handleHeaders(f);try{const T=De.default.request({url:g,method:S,headers:f.headers,timeout:"number"==typeof f.timeout?f.timeout:45e3,data:f.payload||"",responseType:f.responseType||f.dataType||"json",withCredentials:valueOrDefault(f.withCredentials,!1),cancelToken:new De.default.CancelToken((g=>{_=g}))});isPromiseLike2(f.timeout)&&f.timeout.then((()=>{v.info("Aborting pending request"),_()}),(()=>{v.info("Timeout promise rejected, ignoring")}));const I=await T;return v.info(`success, status=${I.status}`),{response:I.data,request:{status:I.status,statusText:I.statusText,headers:I.headers,responseURL:I.request.responseURL,readyState:I.request.readyState,response:I.request.response,responseText:""===I.request.responseType||"text"===I.request.responseType?I.request.responseText:"",withCredentials:I.request.withCredentials},duration:Date.now()-C}}catch(g){if(v.info("failed"),De.default.isCancel(g))throw v.info(`response=${getPIISafeRequestResponse(g.message)}`),{aborted:!0};throw g.response?v.info(`response=${getPIISafeRequestResponse(g.response)}`):g.request?v.info(`no response, request=${getPIISafeRequest(g.request)}`):v.info(`request not made, error=${getPrintableObject(g)}`),g||new Error("Request failed")}}async sendFetchRequest(g,f={headers:{}},S){const v=this.logger.createChild(`[${f.causeId||generateCauseId()}][FetchRequest]`);v.info(`sending, ${S}-${g}`);const C=Date.now(),_=new AbortController;let T,I=null,b=null;const abortPendingRequest=()=>{v.info("Aborting pending request"),_.abort()};handleHeaders(f);try{if(f.fetchUseKeepAlive&&f.payload?.toString().length>65e3&&v.warn("Using fetch with keep alive with more than 64kib data"),v.info(`${JSON.stringify(f.headers)}`),I=fetch(g,{method:S,headers:f.headers,body:f.payload,credentials:f.withCredentials?"include":"same-origin",signal:_.signal,keepalive:f.fetchUseKeepAlive}),isPromiseLike2(f.timeout))f.timeout.then((()=>{abortPendingRequest()}),(()=>{v.info("Timeout promise rejected, ignoring")}));else if(f.timeout){const g=setTimeout((()=>abortPendingRequest()),f.timeout);I=I.finally((()=>clearTimeout(g)))}b=await I;try{T=await b.json()}catch(g){v.info(`unable to parse response as json with error ${g}`)}const A={response:T,request:{status:b.status,statusText:b.statusText,headers:Object.fromEntries(b.headers.entries()),responseURL:b.url,response:T,withCredentials:f.withCredentials},duration:Date.now()-C};if(!b.ok)throw v.info(`failed response, status=${b.status}`),A;return v.info(`success, status=${b.status}`),A}catch(g){if(v.info(`failed error=${getPrintableObject(g)}`),"AbortError"===g.name)throw{aborted:!0};throw g||new Error("Request failed")}}};function valueOrDefault(g,f){return void 0!==g?g:f}function handleHeaders(g){g.headers=g.headers||{},g.headers["content-type"]||(g.headers["content-type"]=g.contentType||"application/json")}var je=M,Ge=class _InternalLogger{constructor(g){this._callingLogger=g,this._maybeLog=(g,...f)=>{try{this._callingLogger[g](...f)}catch(g){this._callingLogger.info("[failed to log]",getPrintableObject(g))}}}getPrefix(g,f){let S="";return f&&(S+=`[${f}]`),g&&(S+=`[${g}]`),S}createChild(g,f){return new _InternalLogger(this._callingLogger.createChild(g,f))}createFnLogger(g,f,...S){return new _InternalLogger(this._callingLogger.createChild(this.getPrefix(g,f)+S.join(""),!1))}logSuccess(g){this._maybeLog("info",`success=${g}}`)}logFailure(g){const f=getPrintableObject(g);this._maybeLog("info",`failed=${f}}`)}log(...g){this._maybeLog("log",...g)}debug(...g){this._maybeLog("debug",...g)}info(...g){this._maybeLog("info",...g)}warn(...g){this._maybeLog("warn",...g)}error(...g){this._maybeLog("error",...g)}},qe=M,We=class{constructor(g){this.eventLogger=g,this.subscriptions=[]}subscribe(g){return new ze(this.subscriptions,g)}dispose(g){this.subscriptions=[]}raiseEvents(g){this.subscriptions.slice().forEach((f=>{try{void 0!==f.eventHandler&&g(f.eventHandler)}catch(g){this.eventLogger?.warn?.("Event handler exception caught!",stringifyObject2(g))}}))}},ze=class{constructor(g,f){this.subscriptions=g,this.eventHandler=f,this.subscriptions.push(this)}dispose(){(0,qe.remove)(this.subscriptions,(g=>g===this)),this.eventHandler=void 0}},Ke=class extends We{constructor(g){super(g)}changed(g,f){return this.subscribe({changed:{skipEventConfig:f,handler:g},on:void 0})}on(g,f){return this.subscribe({changed:void 0,on:{name:String(g),handler:this._toEventCallback(f)}})}once(g,f,S){let v;const onceSubscription=(...g)=>{v.dispose(S),this._toEventCallback(f)(...g)};return v=this.on(g,this._fromEventCallback(onceSubscription)),v}raiseChanged(g){this.raiseEvents((f=>{if(!f.changed)return;const{skipEventConfig:S,handler:v}=f.changed;!this.getShouldSkipChangedEvent(g,S)&&v()}))}event(g){return{raise:this._fromEventCallback(((...f)=>this._raiseEventImpl(String(g),...f)))}}_raiseEventImpl(g,...f){this.raiseEvents((S=>S.on&&S.on.name===g&&S.on.handler(...f)))}_toEventCallback(g){return g}_fromEventCallback(g){return g}getShouldSkipChangedEvent(g,f){return g?.skipDominantSpeakerUpdatesOnCall?!!f?.skipDominantSpeakerUpdatesOnCall:!!g?.skipParticipantsUpdatesOnCall&&!!f?.skipParticipantsUpdatesOnCall}async onAsync(g,f){return this.on(g,f)}async onceAsync(g,f,S){return this.once(g,f,S)}async changedAsync(g,f){return this.changed(g,f)}async disposeAsync(g){this.dispose(g)}};function getTsCallingVersion2(){return"2025.03.01.41"}function getOvb2(){return"cba3e05218cf5c9f3c5c1009bd560650dc7383a5"}var Je=M,Ye=__toESM2(ne()),Qe={OS:{Android:"Android",iOS:"iOS",MacOS:"Mac OS"},Browsers:{Opera:"Opera",Edge:"Edge",Yandex:"Yandex",Firefox:"Firefox",Safari:"Safari",MobileSafari:"Mobile Safari",WebKit:"WebKit"},Engines:{Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",WebKit:"WebKit"}},Xe="Unknown",Ze="0.0",et=class _BrowserInfoProvider{constructor(){const g=navigator.userAgent,f=new Ye.UAParser(g).getResult();this.browserInfo={name:f.browser.name||"Unknown",engine:f.engine.name||"Unknown",version:f.browser.version||Ze,formFactor:getFormFactor(f)||"Unknown",osName:f.os.name||Xe,osVersion:f.os.version||Xe},this.modifyParserResult(f)}static get instance(){return _BrowserInfoProvider._instance||(_BrowserInfoProvider._instance=new _BrowserInfoProvider),_BrowserInfoProvider._instance}static isFormFactor(...g){return g.map((g=>g.toString())).includes(this.getBrowserInfo().formFactor)}static isEngine(...g){return g.map((g=>g.toString())).includes(this.getBrowserInfo().engine)}static isBrowser(...g){return g.map((g=>g.toString())).includes(this.getBrowserInfo().name)}static isVersionGreaterOrEqual(g){const f=this.getBrowserInfo().version,S=g.split(".").map((g=>parseInt(g,10))),v=f.split(".").map((g=>parseInt(g,10)));return v[0]>S[0]||v[0]===S[0]&&v[1]>=S[1]}static getBrowserInfo(){return this.instance.browserInfo}static isRemote(){return window.navigator.mediaDevices?.isRemote}static toString(){const g=this.getBrowserInfo();return`${g.name}/${g.version} ${g.engine} ${g.formFactor}`}modifyParserResult(g){switch(g.engine.name){case Qe.Engines.EdgeHTML:this.browserInfo.engine="Edge";break;case Qe.Engines.Blink:this.browserInfo.engine="Chromium";break;case Qe.Engines.WebKit:g.browser.name?.includes("Safari")||(this.browserInfo.engine="Chromium");break;case Qe.Engines.Gecko:this.browserInfo.engine="Firefox"}g.engine.name===Qe.Engines.Blink&&g.browser.name===Qe.Browsers.Edge&&(this.browserInfo.name="EdgeAnaheim"),g.engine.name===Qe.Engines.Blink&&g.os.name===Qe.OS.Android&&(this.browserInfo.version=g.engine.version||Ze),g.browser.name!==Qe.Browsers.Opera&&g.browser.name!==Qe.Browsers.Yandex||(this.browserInfo.version=g.engine.version||Ze,g.browser.name===Qe.Browsers.Yandex&&(this.browserInfo.name="YandexBrowser")),(g.os.name===Qe.OS.iOS||g.browser.name?.includes(Qe.Browsers.Safari))&&(this.browserInfo.engine="Safari"),g.os.name!==Qe.OS.MacOS&&g.os.name!==Qe.OS.iOS||g.browser.name!==Qe.Browsers.WebKit||(this.browserInfo.engine="Safari",this.browserInfo.name="AppleWebView"),g.os.name===Qe.OS.iOS&&(this.browserInfo.version=g.os.version||Ze),g.browser.name===Qe.Browsers.MobileSafari&&(this.browserInfo.name="Safari"),g.ua.includes("maglev")&&(this.browserInfo.name="Maglev",this.browserInfo.version=g.engine.version||Ze),_BrowserInfoProvider.isRemote()&&(this.browserInfo.engine="ChromiumAVD"),g.ua.includes("Cisco")&&(this.browserInfo.name="CiscoOS"),g.ua.includes("ZoomRoom")&&(this.browserInfo.name="ZoomRoom"),g.ua.includes("TeamsSamsungTVBrowser")&&(this.browserInfo.name="SamsungTV")}};function getFormFactor(g){const f="136";if(getOsSkuInfo()===f)return"Hololens";if(/hostAudio-Processing/i.test(g.ua))return"RoomAudioProcessing";const S=g.device.type;return"mobile"===S||"tablet"===S?"Mobile":void 0===g.browser.name?"Unknown":"Desktop"}function getOsSkuInfo(){const g="os-sku",f=window.external;return f?.getHostEnvironmentValue?JSON.parse(f.getHostEnvironmentValue(g))[g]:"-1"}var tt={src:["https://statics.teams.cdn.office.net/hashed/azuremediaplayer.min-d46c9f4.js","https://statics.teams.cdn.office.net/evergreen-assets/broadcast/player-skin.min.js"],css:["https://statics.teams.cdn.office.net/evergreen-assets/broadcast/player-skin.min.css?v=2","https://statics.teams.cdn.office.net/evergreen-assets/broadcast/video-player.css?v=3"],styles:["azuremediaplayer","amp-stream-skin","amp-big-play-centered"],lang:"en-us",disableFullscreenButton:!1,playerType:0},it={src:["https://res.cdn.office.net/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js"],css:[],styles:[],lang:"en-us",disableFullscreenButton:!1,muteVideo:!1,playerType:1,hydraPlayerWebSdkUrls:["https://res-4.public.onecdn.static.microsoft/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js","https://res.cdn.office.net/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js"]},nt={src:[],css:[],styles:[],playerType:2,hydraPlayerWebSdkUrls:["https://res.cdn.office.net/s01-ml-player/4.24352.3/hydra_player_ums_bundle.js"]},rt=class{constructor(g,f,S,v){this.configIds=S,this.logger=v,this.defaultSettings=getSettings(),this.logger.info(`client settings: ${JSON.stringify(f)}`),this.defaultSettings.debug=f?.debug||!1,this.defaultSettings.playerType=f?.playerConfig?.playerType||this.defaultSettings.playerType,f?.playerConfig&&(0===this.defaultSettings.playerType?this.defaultSettings.ampSettings.liveStreamPlayerConfiguration=f.playerConfig:1===this.defaultSettings.playerType?this.defaultSettings.hlsSettings.liveStreamPlayerConfiguration=f.playerConfig:2===this.defaultSettings.playerType&&(this.defaultSettings.umsSettings.liveStreamPlayerConfiguration=f.playerConfig)),(0,Je.mergeWith)(this.defaultSettings,g,arrayMergeCustomizer),this.logger.info(`applied settings: ${JSON.stringify(this.defaultSettings)}`)}get playerConfig(){return 0===this.defaultSettings.playerType?this.defaultSettings.ampSettings.liveStreamPlayerConfiguration:1===this.defaultSettings.playerType?this.defaultSettings.hlsSettings.liveStreamPlayerConfiguration:2===this.defaultSettings.playerType?this.defaultSettings.umsSettings.liveStreamPlayerConfiguration:null}get config(){return this.defaultSettings}},st=class{constructor(){this.defaultSettings={allowSdnPlugins:!0,capturePlayerLogs:!0,playerType:0,loadType:1,maxPlayerDiagnosticsCount:50,maxPlayerMemoryTraceLogCount:1e3,maxPlayerPlaybackEventCount:50,maxRetryCount:10,playerTelemetryTickMs:1e3,removeEmptyDefaultTextTrack:!0,sendSnapshotTelemetry:!1,sendSnapshotTelemetryEveryMs:1e4,sendInitialTelemetryAfterMs:6e4,sendTelemetry:!0,textTrackKind:"subtitles",maxRetryCountForLoadingResources:5,maxVideoTrackHistoryLogCount:100,hydraRuntimeFetchTimeout:6e3,ampSettings:{errorCodesEligibleForStreamingUrlSwitch:[4194309,2097564,2097556,2097752,2097753,5242884],liveStreamPlayerConfiguration:tt,sourceResetTimeoutInMs:1e3,streamingUrlSwitchMaxCount:2,resetStreamingUrlSwitchCount:!1,useBrowserWindowSizeForBitRate:!0,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,collectUserInitiatedSeekEventsTelemetry:!0,maxUserInitiatedSeekEventCount:100,noMediaTimeoutMs:-1},hlsSettings:{liveStreamPlayerConfiguration:it,timeoutForSwitchingUrl:9e3,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,playlistInitialSequenceNumber:1,skipNonce:!1,maxStreamConnectionResultsLogCount:100,logHlsJsEvents:!1,logHlsJsEventsEveryMs:5e3,maxPlayerExperimentalEvents:100},umsSettings:{liveStreamPlayerConfiguration:nt,timeoutForSwitchingUrl:9e3,maxStreamConnectionResultsLogCount:100,minTargetEdgeLatency:.2,latencyCompensationThreshold:.5,maxPlayerExperimentalEvents:100}}}getSettings(){return this.defaultSettings}},at=class extends st{constructor(){super(),this.settings=super.getSettings(),this.settings.loadType=0,this.settings.allowSdnPlugins=!1,this.settings.umsSettings.minTargetEdgeLatency=.6,this.settings.umsSettings.latencyCompensationThreshold=.9}getSettings(){return this.settings}};function getSettings(){return(et.isEngine("Safari")?new at:new st).getSettings()}function arrayMergeCustomizer(g,f){if((0,Je.isArray)(g))return f.slice()}function isStreamValid(g){return!!g&&!!g.url&&!!g.decryptionToken}function assert(g,f,S){if(!g&&!S)throw new Error("Assert failed"+(void 0!==f?`: ${f}`:""))}var ot=class{constructor(g,f,S){this.name=g,this.stopCrash=f,this.start(S)}complete(){assert(this.startTime,"not started",this.stopCrash),assert(void 0===this.duration,"already completed",this.stopCrash),this.duration=Date.now()-this.startTime}updateDetails(g,f){if(this.details&&"object"==typeof this.details)for(let S=0;S<g.length;S++)this.details[g[S]]=f[S]}fail(g){this.failReason=g,this.complete()}set detail(g){this.details=g}getTelemetryEvent(){assert(this.startTime,"not started",this.stopCrash);try{assert(void 0!==this.duration,"not completed",this.stopCrash)}catch(g){if("SetSource"!==this.name&&"Load"!==this.name)throw g}const g={name:this.name,startTime:this.startTime,duration:this.duration};return this.failReason&&(g.failReason=this.failReason),this.details&&(g.details=this.details),g}start(g){assert(!this.startTime,"already started",this.stopCrash),this.startTime=Date.now(),this.details=g}},lt=class{constructor(g,f,S){this.config=g,this.logger=f,this.playerDiagnosticsLog=S,this.currentScenarioMap=new Map,this.playerEvents=[],this.playbackEvents=[],this.userInitiatedSeekEvents=[],this.experimentalEvents=[],this.clientNetworkType=void 0,this.maxPlayerPlaybackEventCount=g.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=g.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=g.maxPlayerMemoryTraceLogCount||100,this.maxUserInitiatedSeekEventCount=g.ampSettings?.maxUserInitiatedSeekEventCount||100,this.stopCrash=g.stopCrash||!1,this.config.debug&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener()}getPlayerDiagnosticSnapshot(){return this.currentPlayerDiagnosticSnapshot}registerStatsUpdated(g){this.currentPlayerDiagnosticSnapshot=g,Object.keys(this.playerDiagnosticsLog).forEach((f=>{const S=f,v=this.playerDiagnosticsLog[f];if(Array.isArray(v)){v.push(g[S]);const f="memoryLog"===S&&v.length>this.maxPlayerMemoryTraceLogCount,C="memoryLog"!==S&&v.length>this.maxPlayerDiagnosticsCount;(f||C)&&v.splice(0,1)}else this.playerDiagnosticsLog[f]=g[S]}))}registerEventLoadAttempt(g,f){this.registerScenario(g,f)}registerEventLoadFailed(g,f){this.completeScenario(g,f)}registerEventLoadSucceeded(g,f){this.completeScenario(g,void 0,f)}registerPlayerLoadAttempt(){this.registerScenario("Load")}registerPlayerLoadSucceeded(g){this.completeScenario("Load",void 0,g)}registerPlayerLoadFailed(g){this.completeScenario("Load",g)}registerPlayerSetupAttempt(){this.registerScenario("Setup")}registerPlayerSetupSucceeded(){this.completeScenario("Setup")}registerPlayerSetupFailed(g){this.completeScenario("Setup",g)}registerStreamConnectionAttempt(g){this.registerScenario("StreamConnection")}registerStreamConnectionSucceeded(){this.completeScenario("StreamConnection")}registerStreamConnectionFailed(g){this.completeScenario("StreamConnection",g)}registerSetSourceAttempt(g,f){let S=g;f&&(S={src:g,reason:f}),this.registerScenario("SetSource",S)}registerSetSourceSucceeded(g){this.getScenario("SetSource").updateDetails(["src"],[g]),this.completeScenario("SetSource")}registerSetSourcedFailed(g,f){this.getScenario("SetSource").updateDetails(["src"],[f]),this.completeScenario("SetSource",g)}registerSdnPluginLoad(g,f,S){this.registerScenario("SdnPluginLoad",g);const v=f?void 0:S;this.completeScenario("SdnPluginLoad",v)}registerPlayerDestroyed(g){this.registerScenario("Destroyed",g),this.completeScenario("Destroyed")}registerPlaybackStateChanged(g,f){let S;"Ready"!==g||this.firstReadyStateTimestamp?"Playing"!==g||this.firstPlayingStateTimestamp||(this.firstPlayingStateTimestamp=Date.now()):this.firstReadyStateTimestamp=Date.now(),f&&"Buffering"===g&&(f?S=f.message:this.logger.debug(`Unexpected buffering payload: ${JSON.stringify(f)}`)),this.registerPlaybackEvent("StateChanged",g,S)}registerPlaybackError(g,f){this.registerPlaybackEvent("Error",{errorType:g,details:f})}registerDownloadBitratechanged(g){this.registerPlaybackEvent("BitrateChangedDownload",g)}registerStreamOptionsConfigured(g,f){this.registerPlaybackEvent("StreamOptionsConfigured",this.generateCleanedStreamOption(g),f)}registerPlaybackBitratechanged(g){this.registerPlaybackEvent("BitrateChangedPlayback",g)}registerPotentialMediaFreeze(g){this.registerPlaybackEvent("PotentialMediaFreeze",g)}registerCaptionToggle(g,f,S){const v={isEnabled:g,culture:f,playerTime:S};this.registerPlaybackEvent("CaptionsToggled",v)}registerFullScreenChange(g){this.registerPlaybackEvent("FullscreenChanged",g)}registerMute(g){this.registerPlaybackEvent("Mute",g)}registerVolumeChange(g){this.registerPlaybackEvent("Volume",g)}getExperimentalEvents(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}}getUserInitiatedSeekEvents(){return{playback_userInitiatedSeekEvents:this.prepareForTelemetry(this.userInitiatedSeekEvents)}}getSnapshotReport(g={}){const f=this.playerEvents.map((g=>g.getTelemetryEvent())),S=this.playbackEvents;let v={};return this.currentPlayerDiagnosticSnapshot&&(v=this.filterAndPrepareTelemetry()),{isFullReport:!1,configIds:g.configIds||"",playerId:g.playerId||"",correlationId:g.correlationId||"",traceId:g.correlationId?g.correlationId.replace(/-/g,""):"",eTag:g.eTag||"",isFinal:g.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:g.disableFullscreenButton??!1,threadId:g.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:getTsCallingVersion2(),...this.getInitializationReport(f,S),...this.getPlaybackReport(S),...this.getBitrateReport(S),...this.getSdnReport(f),...this.getSetSourceReport(f),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(f),callDropped:this.getCallDropped(S),...v}}getReport(g={}){const f=this.playerEvents.map((g=>g.getTelemetryEvent())),S=this.playbackEvents;return{callendReason:g.callendReason,isFullReport:!0,configIds:g.configIds||"",playerId:g.playerId||"",correlationId:g.correlationId||"",traceId:g.correlationId?g.correlationId.replace(/-/g,""):"",eTag:g.eTag||"",isFinal:g.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:g.disableFullscreenButton??!1,threadId:g.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:getTsCallingVersion2(),...this.getInitializationReport(f,S),...this.getPlaybackReport(S),...this.getBitrateReport(S),...this.getSdnReport(f),...this.getSetSourceReport(f),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(f),callDropped:this.getCallDropped(S),...this.getPlayerDiagnosticLog()}}registerExperimentalEvent(g,f,S){const v=this.createTelemetryEvent(g,f,S);this.experimentalEvents.push(v),this.logTelemetryEvent(v)}registerUserInitiatedSeek(g){const f=(this.currentPlayerDiagnosticSnapshot?.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1)<g.newCurrentPlayPosition,S={...g,seekForward:f},v=this.createTelemetryEvent("UserInitiatedSeek",S);this.userInitiatedSeekEvents.push(v),this.userInitiatedSeekEvents.length>this.maxUserInitiatedSeekEventCount&&this.userInitiatedSeekEvents.splice(0,1)}createTelemetryEvent(g,f,S){const v={eventType:g,timestamp:Date.now(),currentPlayPosition:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1};return void 0!==f&&(v.payload=this.prepareForTelemetry(f)),v.message=S,v}registerPlaybackEvent(g,f,S){const v=this.createTelemetryEvent(g,f,S);"Error"===g&&"PlaybackRetried"!==f?.errorType&&(v.fatal=!0),this.playbackEvents.push(v),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(v)}getPlayerDiagnosticLog(){if(!this.currentPlayerDiagnosticSnapshot)return{};const g={...this.currentPlayerDiagnosticSnapshot,...this.playerDiagnosticsLog},f={};return Object.keys(g).forEach((S=>{f[`player_${S}`]=this.prepareForTelemetry(g[S])})),f}getCallSetupSucceeded(g){const f=g.find((g=>"Load"===g.name));return!!f&&!f.failReason}getCallDropped(g){return!!g.filter((g=>"Error"===g.eventType)).find((g=>g.fatal))}getInitializationReport(g,f){const S=g.find((g=>"Load"===g.name));return{init_timeLoadToStreamConnectionEstablished:(S&&this.initialStreamConnectionEstablishedTimestamp?this.initialStreamConnectionEstablishedTimestamp-S.startTime:-1)||-1,init_timeLoadToReady:(S&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-S.startTime:-1)||-1,init_timeLoadToPlaying:(S&&this.firstPlayingStateTimestamp?this.firstPlayingStateTimestamp-S.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(g)}}getPlaybackReport(g){const f=g.filter((g=>"StateChanged"===g.eventType)),S=f.find((g=>"Ready"===g.payload)),v=f.find((g=>"Play"===g.payload)),C=f.find((g=>"Start"===g.payload)),_=f.find((g=>"Playing"===g.payload)),T=S&&v?v.timestamp-S.timestamp:-1,I=v&&C?C.timestamp-v.timestamp:-1,b=C&&_?_.timestamp-C.timestamp:-1,A=f.filter((g=>"Seeked"===g.payload)),P=f.filter((g=>"Seeking"===g.payload)),R=f.filter((g=>"Paused"===g.payload)),M=f.filter((g=>"Resume"===g.payload)),w=f.filter((g=>"Buffering"===g.payload)),O=["BitrateChangedDownload","BitrateChangedPlayback","Error","Mute","StateChanged","Volume","StreamOptionsConfigured"],D=g.filter((g=>"Error"===g.eventType)),N=g.filter((g=>"Volume"===g.eventType||"Mute"===g.eventType)),k=g.filter((g=>"StreamOptionsConfigured"===g.eventType)),L=g.filter((g=>!O.includes(g.eventType)));return{playback_timeReadyToPlay:T,playback_timePlayToStart:I,playback_timeStartToPlaying:b,playback_bufferingEvents:this.prepareForTelemetry(w),playback_errorEvents:this.prepareForTelemetry(D),playback_pauseEvents:this.prepareForTelemetry(R),playback_resumeEvents:this.prepareForTelemetry(M),playback_otherEvents:this.prepareForTelemetry(L),playback_seekedEvents:this.prepareForTelemetry(A),playback_seekingEvents:this.prepareForTelemetry(P),playback_stateChangeEvents:this.prepareForTelemetry(f),playback_volumeEvents:this.prepareForTelemetry(N),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(k)}}generateCleanedStreamOption(g){return{...g,stream:{...g?.stream,decryptionToken:g?.stream?.decryptionToken?"valid":"empty",sdnContext:g?.stream?.sdnContext?"valid":"empty",keyAuthorizationToken:g?.stream?.keyAuthorizationToken?"valid":"empty"},altStream:g?.altStream?{...g?.altStream,decryptionToken:g?.altStream?.decryptionToken?"valid":"empty",sdnContext:g?.altStream?.sdnContext?"valid":"empty",keyAuthorizationToken:g?.stream?.keyAuthorizationToken?"valid":"empty"}:void 0}}getBitrateReport(g){const f=g.filter((g=>"BitrateChangedDownload"===g.eventType)),S=f.sort((g=>Number(g.payload))),v=f.length?{bitrate_downloadChanges:this.prepareForTelemetry(f),bitrate_downloadChangeCount:f.length||-1,bitrate_downloadMin:S[0].payload||-1,bitrate_downloadMax:S[S.length-1].payload||-1}:{},C=g.filter((g=>"BitrateChangedPlayback"===g.eventType)),_=C.sort((g=>Number(g.payload)));return{...v,...C.length?{bitrate_playbackChanges:this.prepareForTelemetry(C),bitrate_playbackChangeCount:C.length||-1,bitrate_playbackMin:_[0].payload||-1,bitrate_playbackMax:_[_.length-1].payload||-1}:{}}}addNetworkTypeEventListener(){window.navigator?.connection?.type&&window.navigator?.connection?.addEventListener("change",(()=>this.updateClientNetworkType()))}updateClientNetworkType(){this.clientNetworkType=void 0,this.getClientNetworkType()}getClientNetworkType(){if(void 0===this.clientNetworkType){let g="Unknown";if(window.navigator?.connection?.type){const f=window.navigator?.connection?.type;switch(f){case"cellular":g="WWAN";break;case"ethernet":g="Wired";break;case"wifi":g="Wireless";break;default:g="Unknown"}}this.clientNetworkType=g}return this.clientNetworkType}getSdnReport(g){const f=g.filter((g=>"SdnPluginLoad"===g.name)),S=f.length?f[f.length-1]:void 0;return{sdn_loaded:!(!S||void 0!==S.failReason),sdn_details:S&&S.details||"",sdn_error:S&&S.failReason||"",sdn_events:this.prepareForTelemetry(f)}}getSetSourceReport(g){const f=g.filter((g=>"SetSource"===g.name));return{set_source_events:this.prepareForTelemetry(f)}}registerScenario(g,f){const S=this.currentScenarioMap.get(g),v=new ot(g,this.stopCrash,f);assert(!S,`previous scenario:${stringifyObject2(S)} is not completed, new scenario:${stringifyObject2(v)}`,this.stopCrash),this.currentScenarioMap.set(g,v),this.playerEvents.push(v)}getScenario(g){return this.currentScenarioMap.get(g)}completeScenario(g,f,S){const v=this.currentScenarioMap.get(g);assert(v,"no scenario to complete",this.stopCrash),f?v.fail(f):("StreamConnection"!==g||this.initialStreamConnectionEstablishedTimestamp||(this.initialStreamConnectionEstablishedTimestamp=Date.now()),S&&(v.detail=S),v.complete()),this.currentScenarioMap.delete(g)}logTelemetryEvent(g){this.config.debug&&(this.logger.debug(`PlayerTelemetryEvent: ${JSON.stringify(g)}`),this.logger.debug(`PlayerDiagnosticData: ${JSON.stringify(this.currentPlayerDiagnosticSnapshot)}`))}filterAndPrepareTelemetry(){const g=new Set;g.add("serviceLatencyCdg"),g.add("endToEndLatencyCdg"),g.add("videoEdgeLatencyCdg");const f={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((S=>{g.has(S)||(f[`player_${S}`]=this.prepareForTelemetry(this.currentPlayerDiagnosticSnapshot[S]))})),f}prepareForTelemetry(g){return"boolean"==typeof g?g:"string"==typeof g||void 0===g?g||"":"number"==typeof g?g??-1:JSON.stringify(g)}},ct=M;function asap(g){return new Promise((f=>{f(g())}))}var dt=class{constructor(){this.isPendingInt=!0,this.promiseInt=new Promise(((g,f)=>{this.resolveInt=g,this.rejectInt=f}))}get resolve(){return g=>{this.isPendingInt=!1,this.resolveInt(g),this.clearTimeout()}}get reject(){return g=>{this.isPendingInt=!1,this.rejectInt(g),this.clearTimeout()}}get promise(){return this.promiseInt}get isPending(){return this.isPendingInt}setTimeout(g,f=`deferred timed out after ${g}ms`){this.isPendingInt&&(this.timeoutId=setTimeout((()=>{this.reject(f)}),g))}clearTimeout(){this.timeoutId&&clearTimeout(this.timeoutId)}};function deferWithTimeout2(g,f=`deferred timed out after ${g}ms`){const S=new dt;return S.setTimeout(g,f),S}function delay(g){return new Promise((f=>setTimeout(f,g)))}var ht=class{static build(g,f){return new ut(g,f)}},ut=class{constructor(g,f){this.ontimeout=g,this.name=f}start(g){if(void 0!==this.timeoutId)throw new Error(`Timer ${this.name} already started`);return this.timeoutId=window.setTimeout((()=>this.ontimeout()),g),this}stop(){if(void 0===this.timeoutId)throw new Error(`Timer ${this.name} is not defined`);clearTimeout(this.timeoutId),this.timeoutId=void 0}};function AmpPlayerF(){const g=AmpDiagnosticProviderF(),f=CaptionsControlToggleProviderF();let S;return(S||(S={})).CaptionFunctionalityNotSupported="CaptionFunctionalityNotSupported",class{constructor(g,f){this.container=g,this.eventsHandler=f,this.videoElementEvents=[],this.playerEvents=[],this.maxMemoryTraceLogCount=1e4,this.videoSourceType="application/dash+xml",this.sdnPluginLoaded=!1,this.statsTimer=-1,this.statsInterval=1e3,this.videoSourceSetAttemptCount=0,this.totalBufferingTime=0,this.isBuffering=!1,this.totalPlayingTime=0,this.isPlaying=!1,this.videoTrackTotalDurations=[]}get contextWindow(){return this.container.ownerDocument.defaultView}configure(g,f,S){this.liveStreamOptions=g,this.playerId=S,f&&(this.configProvider=f,this.statsInterval=f.config.playerTelemetryTickMs||this.statsInterval,this.maxMemoryTraceLogCount=f.config.maxPlayerMemoryTraceLogCount||this.maxMemoryTraceLogCount)}getIceCandidates(){let g=[];try{const f=this.liveStreamOptions.stream.sdnContext||this.liveStreamOptions.altStream?.sdnContext||"",S=JSON.parse(f),v=JSON.parse(S.sdnConfig);if(!v.RTCIceCandidates)throw new Error("RTCIceCandidates not present in SDN Context");g=v.RTCIceCandidates}catch(g){this.log(`getIceCandidates failed: ${JSON.stringify(g.message)}`,"error")}return this.log(`getIceCandidates: ${JSON.stringify(g)}`,"debug"),g}loadPlayerScript(){let g=Promise.resolve("");const f=this.configProvider.playerConfig.nonce,S=this.configProvider.playerConfig.css;for(let v=0;v<S.length;v++)g=g.then((()=>this.retry((()=>this.loadCss(this.container.ownerDocument,S[v],f)))));return g=g.then((()=>this.loadAmpScript())),g}loadAmpScript(){this.log("loadPlayerScript started");let g=Promise.resolve("");const f=this.configProvider.playerConfig?.nonce,S=this.configProvider.playerConfig?.src||[],v=Math.max(2,this.configProvider.config.maxRetryCountForLoadingResources);if(0===S.length)return Promise.reject("AMP Player Src is empty");for(let C=0;C<S.length;++C)g=g.then((()=>this.loadScriptPromise(S,C,f,v)));return g}loadScriptPromise(g,f,S,v,C=""){return this.retry((()=>this.setScriptByLoad(this.container.ownerDocument,g[f],S)),v).then((S=>`${g[f]}: ${S} `.concat(C))).catch((_=>this.retry((()=>this.setScriptByBlob(this.container.ownerDocument,g[f],S)),v).then((S=>`${g[f]}: ${S}`.concat(` ${_} `,` ${C} `))).catch((T=>this.retry((()=>this.setScriptByInnerHtml(this.container.ownerDocument,g[f],S)),1).then((S=>`${g[f]}: ${S}`.concat(` ${_} `,`${T} `,` ${C} `))).catch((_=>{let I=C;return f<g.length&&(I=I.concat(`Failed to load script, nonce: ${S}, src: ${g[f]} index: ${f} `),I=I.concat(`${v} attempts LoadFailure `,`${v} attempts BlobFetchFailure: `,T,", 1 attempt InnerHtmlFailure: ",`${_} `)),Promise.reject(I)}))))))}retry(g,f=this.configProvider.config.maxRetryCountForLoadingResources,S=1,v=200){return g(f).then((g=>`${g}, succeeded on load number: ${S} `)).catch((C=>(this.log(`Error loading resource: ${C} -- ${f} retriesLeft`),0==--f?Promise.reject(`${C}`):new Promise((_=>setTimeout((()=>_(this.retry(g,f,S+1).then((g=>"string"==typeof g?`${g}, succeeded on load number: ${S}`:g)).catch((g=>Promise.reject(`${C}`.concat(", ",g)))))),v))))))}setScriptByLoad(g,f,S){const v=g.createElement("script"),C=this.getElementLoadPromise(v,f);return v.src=f,S&&(v.nonce=S),g.head.appendChild(v),C.then((()=>Promise.resolve("Success: setScriptByLoad")))}setScriptByBlob(g,f,S){return this.safeResponse(f).then((f=>f.blob().then((v=>{if(v){const f=URL.createObjectURL(v);return this.setScriptByLoad(g,f,S).then((()=>Promise.resolve("Success: setScriptByBlob")))}return Promise.reject(`${f.status}, blob is null`)}))))}setScriptByInnerHtml(g,f,S){return this.safeResponse(f).then((f=>f.text().then((v=>{if(v){const f=document.createElement("script");return f.innerHTML=v,S&&!this.configProvider.config.hlsSettings.skipNonce&&(f.nonce=S),g.head.appendChild(f),Promise.resolve("Success: setScriptByInnerHtml")}return Promise.reject(`status code:${f.status}, text is null`)}))))}safeResponse(g){return fetch(g).then((g=>g.ok?g:Promise.reject(`${g.status}`)))}tryLoadSdnPlugin(){return this.sdnPluginLoaded||!this.liveStreamOptions.sdn?Promise.resolve():this.configProvider.config.allowSdnPlugins?(this.log("tryLoadSdnPlugin started"),this.retry((()=>this.setScriptByLoad(this.container.ownerDocument,this.liveStreamOptions.sdn.url,this.configProvider.playerConfig.nonce))).then((()=>{this.log("SDN script loaded"),this.sdnPluginLoaded=!0,this.log("tryLoadSdnPlugin done")}))):(this.log("Loading SDN plugins is not allowed"),Promise.reject("Loading SDN plugins is not allowed"))}createAmp(){this.log("createAmp started"),this.createVideoElement();const S=this.getAmpOptions();if(this.playerInstance=this.contextWindow.amp(this.video.id,S),!this.playerInstance)throw this.log("createAmp failed","error"),new Error("playerInstance is null");"html5"===this.playerInstance.currentTechName()?.toLowerCase()&&this.configProvider.config.ampSettings.estimateAbsoluteTime&&this.isControlsDisabled()?(this.absoluteTimeOffsetEstimator=new pt(this.log.bind(this)),this.diagnosticProvider=new g(this.playerInstance,this.contextWindow,new Date,this.configProvider,this.absoluteTimeOffsetEstimator),this.absoluteTimeOffsetEstimator.setEstimationResultCallback(this.onAbsoluteTimeOffsetEstimation.bind(this))):this.diagnosticProvider=new g(this.playerInstance,this.contextWindow,new Date,this.configProvider);const v={controlsEnabled:!this.isControlsDisabled(),logFn:this.log.bind(this),removeEmptyDefaultTextTrack:this.configProvider.config.removeEmptyDefaultTextTrack};this.diagnosticProvider.setValue("streamingEventType",this.liveStreamOptions.streamingEventType),this.diagnosticProvider.setValue("eventId",this.liveStreamOptions?.eventId||""),this.diagnosticProvider.setValue("templateId",this.liveStreamOptions?.templateId||""),this.diagnosticProvider.setValue("playerControlsEnabled",!this.isControlsDisabled()),this.captionsControl=new f(this.playerInstance,this,v,this.diagnosticProvider),this.registerPlayerEvents(),this.log("createAmp done")}isControlsDisabled(){return void 0!==this.liveStreamOptions.allowPlayerControls?!this.liveStreamOptions.allowPlayerControls:"Overflow"===this.liveStreamOptions.streamingEventType||"TownHall_Basic"===this.liveStreamOptions.streamingEventType||"TownHall_Premium"===this.liveStreamOptions.streamingEventType||"TownHall"===this.liveStreamOptions.streamingEventType}onAbsoluteTimeOffsetEstimation(g){if(this.diagnosticProvider.appendAbsoluteTimeOffsetEstimation(g),!g.isSuccess){const g=this.addEvent("CaptionFunctionalityNotSupported",{detail:{data:{fatal:!0,details:"absolute time offset estimation failed - captions will fail"}}});this.video.dispatchEvent(g)}}addEvent(g,f){let S={};return f?.detail&&(S={detail:f.detail}),new CustomEvent(g,S)}setSource(g){if(this.log("setSource started"),!this.playerInstance)throw this.log("setSource failed: playerInstance is null","error"),new Error("playerInstance is null");this.videoSourceSetAttemptCount++,this.videoSourceSetAttemptCount>0&&this.diagnosticProvider.setValue("retryCount",this.videoSourceSetAttemptCount-1);const f={src:g.url,type:this.videoSourceType,protectionInfo:g.decryptionToken?[{type:"AES",authenticationToken:g.decryptionToken}]:null};this.configureSdnSource(f,g),this.diagnosticProvider.setValue("streamUrl",g.url),this.diagnosticProvider.setValue("streamId",this.getStreamIdFromStreamUrl(g.url)),this.diagnosticProvider.setValue("streamDeliveryPipeline",g.streamDeliveryPipeline||""),this.playerInstance.src([f],this.getTextTracks()),this.absoluteTimeOffsetEstimator&&this.absoluteTimeOffsetEstimator.setManifestFileURL(g.url+"(format=m3u8-aapl-v4)"),this.log("setSource done")}getStreamIdFromStreamUrl(g){try{const f=new URL(g).pathname;if(f){const g=f.split("/");if(g?.length>1)return g[1]}return this.log(`unable to parse stream ID from stream URL: ${g}`,"warn"),""}catch{return this.log(`cannot parse stream ID from invalid stream URL: ${g}`,"warn"),""}}setPlayTime(g){g&&(this.log(`setPlayerTime: ${g}`),this.playerInstance.currentTime(g))}dispose(){this.log("dispose started"),this.diagnosticProvider&&(this.stopStatsCollection(),this.diagnosticProvider.dispose(),this.diagnosticProvider=null),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null),this.playerInstance&&(this.removePlayerEventListeners(),this.playerInstance.getMemoryLog(!0),this.playerInstance.dispose(),this.playerInstance=null),this.eventsHandler.ampDisposed(),this.video&&(this.removeVideoEventListeners(),this.video.parentNode&&this.video.parentNode.removeChild(this.video),this.video=null),this.absoluteTimeOffsetEstimator&&(this.absoluteTimeOffsetEstimator.stopStreamAbsoluteTimeOffsetRetrieval(),this.absoluteTimeOffsetEstimator=null),this.log("dispose done"),this.eventsHandler=null}updatePlaybackDiagnostics(){this.updateTotalPlayingTimeStatistic(),this.updateBufferingRateStatistic(),this.updateVideoTrackHistoryStatistic()}handlePlaybackStopped(){this.isBuffering=!1,this.isPlaying=!1,this.currentVideoPlaybackBitrate=null}showCaptions(g){this.log(`showCaptions: ${g}`),this.captionsControl.showCaptions(g)}addCues(g){g=g.filter((g=>g.text&&0!==g.text.trim().length)),this.captionsControl.addCues(g)}clearCues(){this.captionsControl.clearCues()}captionsToggled(g,f,S){this.log(`captionsToggled: ${g} for culture ${f} at ${S}`),this.eventsHandler.message("captionsToggled").send(g,f,S)}createVideoElement(){this.log("createVideoElement started"),this.video=this.container.ownerDocument.createElement("video"),this.video.id="amp-player",this.video.setAttribute("playsinline","");const g=this.configProvider.playerConfig.lang;g&&(this.video.setAttribute("lang",g),this.log(`createVideoElement: language set to ${g}`));const f=this.configProvider.playerConfig.styles;for(let g=0;g<f.length;g++)this.video.classList.add(f[g]);this.container.appendChild(this.video),this.log("createVideoElement done")}getAmpOptions(){const g=[];this.configProvider.config.debug?g.push({target:"memory",maxMemoryTraceCount:this.maxMemoryTraceLogCount}):g.push({target:"console"});const f={TraceTargets:g,maxLogLevel:this.configProvider.config.debug?3:2},S={techOrder:["azureHtml5JS","html5"],nativeControlsForTouch:!1,autoplay:!0,preload:"auto",controls:!this.isControlsDisabled(),logo:{enabled:!1},height:"100%",width:"100%",traceConfig:f,disableFullscreenButton:this.configProvider.playerConfig?.disableFullscreenButton,staleDataTimeLimitInSec:30,heuristicProfile:this.contextWindow.amp.Player.HeuristicProfile.HighQuality,customPlayerSettings:{customHeuristicSettings:{bandwidthTestWithTimeThresholdDuringLive:!1,windowSizeHeuristics:this.configProvider.config.ampSettings.useBrowserWindowSizeForBitRate,useBrowserWindowForWindowSizeRule:this.configProvider.config.ampSettings.useBrowserWindowSizeForBitRate,useVariableFragmentSizeMode:!0}},plugins:{}};return this.initializePluginOptions(S),S}isStreamValid(g){return g&&!!g.url&&!!g.decryptionToken}initializePluginOptions(g){if(!this.sdnPluginLoaded||!this.liveStreamOptions.sdn)return;const f=this.isStreamValid(this.liveStreamOptions.stream)?this.liveStreamOptions.stream:this.liveStreamOptions.altStream;this.log(`initializePluginOptions, receivedSDNContext: ${JSON.stringify(f?.sdnContext)}`,"info");try{const S=this.liveStreamOptions.correlationId||this.playerId;switch(this.liveStreamOptions.sdn.name){case"hive":if(g.plugins={hive:{debugLevel:this.configProvider.config.debug?"debug":"notice",telemetryId:S}},f&&f.sdnContext)try{const S=JSON.parse(f.sdnContext);if(S.sdnConfig){const f=JSON.parse(S.sdnConfig);f.candidateTopicName="RequestIceCandidates",delete f.RTCIceCandidates,Object.assign(g.plugins.hive,f)}}catch(g){this.log(`initializePluginOptions, failed to parse Hive sdnConfig Json from sdnContext Json, error: ${g}`,"warn")}break;case"kollective":if(f&&f.sdnContext){let v=null,C=null,_=null;try{v=this.parseJson(f.sdnContext,"kollective sdn context")}catch(g){this.log(`initializePluginOptions, failed to parse Kollective sdnContext Json, error: ${g}`,"error")}if(v){try{C=this.parseJson(v.playbackinfo,"kollective sdn playback info")}catch(g){this.log(`initializePluginOptions, failed to parse Kollective sdnContext playbackinfo Json, error: ${g}`,"error")}try{_=this.parseJson(v.sdnConfig,"kollective sdn config")}catch(g){this.log(`initializePluginOptions, failed to parse Kollective sdnContext sdnConfig Json, error: ${g}`,"error")}}g.plugins={kollectiveSDN:{playbackInfo:C,sdnConfig:_,reportSessionId:S}}}break;case"ramp":f&&f.sdnContext&&(g.plugins={RampMOPlugin:this.parseJson(f.sdnContext,"ramp sdn context")},this.configProvider.config.debug&&(g.plugins.RampMOPlugin.verbose=!0));break;case"peer5":f.sdnContext&&(g.plugins={peer5:this.parseJson(f.sdnContext,"peer5 sdn context")})}}catch(g){this.log(`initializePluginOptions failed, error: ${g.message}`,"error")}this.log(`initializePluginOptions, configured plugin options: ${JSON.stringify(g.plugins)}`,"info")}getTextTracks(){const g=[];if(this.isControlsDisabled())g.push({id:"amp-player_default",kind:"captions",label:"default-text-track",src:"",srclang:"en"});else if(this.liveStreamOptions.supportedSubtitleLanguages){const f=this.liveStreamOptions.supportedSubtitleLanguages;for(let S=0;S<f.length;S++)g.push({id:`amp-player_${f[S].culture}`,kind:this.configProvider.config.textTrackKind,label:f[S].name||f[S].culture,src:"",srclang:f[S].culture.substr(0,2)})}return g}configureSdnSource(g,f){if(this.sdnPluginLoaded&&this.liveStreamOptions.sdn){switch(this.liveStreamOptions.sdn.name){case"hive":if(!f.sdnContext){g.sdnList=[];break}try{const S=JSON.parse(f.sdnContext);S.playbackinfo&&(g.sdnList=[{sdnName:"hive",sdnUrl:S.playbackinfo}])}catch(S){g.sdnList=[{sdnName:"hive",sdnUrl:f.sdnContext}]}break;case"kollective":if(!f.sdnContext){g.sdnList=[];break}try{const S=this.parseJson(f.sdnContext,"kollective sdn list context"),v=this.parseJson(S.playbackinfo,"kollective sdn list playback info"),C=this.parseJson(S.sdnConfig,"kollective sdn list sdn config");g.sdnList=[{sdnName:"kollectiveSDN",playbackInfo:v,sdnConfig:C}]}catch(f){return g.sdnList=[],void this.log(`configureSdnSource failed, error: ${f}`,"error")}break;case"ramp":case"peer5":g.sdnList=[];break;default:return}this.log(`configureSdnSource, configured source context: ${JSON.stringify(g)}`,"info")}}registerPlayerEvents(){this.registerPlayerEvent(this.contextWindow.amp.eventName.error,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.error)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.canplaythrough,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.canplaythrough)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.play,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.play)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.playing,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.playing)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.pause,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.pause)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.resume,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.resume)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.start,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.start)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.ended,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.ended)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.seeking,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.seeking)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.seeked,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.seeked)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.loadedmetadata,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.loadedmetadata)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.waiting,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.waiting)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.playbackbitratechanged,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.playbackbitratechanged)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.downloadbitratechanged,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.downloadbitratechanged)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.fullscreenchange,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.fullscreenchange)})),this.registerPlayerEvent("potentialMediaFreeze",(()=>{this.onAmpEvent("potentialMediaFreeze")})),this.registerPlayerEvent(this.contextWindow.amp.eventName.mute,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.mute)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.unmute,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.unmute)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.volumechange,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.volumechange)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.loadeddata,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.loadeddata)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.loadstart,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.loadstart)})),Object.values(S).forEach((g=>{this.registerVideoEvent(g,(f=>{this.handleUserExperienceErrorEvent(g,f.detail.data.details,f.detail.data.fatal)}))})),this.configProvider.config.ampSettings.collectUserInitiatedSeekEventsTelemetry&&(this.playerEvents.push("currentTimeChanging"),this.playerInstance.addEventListener("currentTimeChanging",((g,f)=>this.onAmpCurrentTimeChangingEvent(g,f))))}onAmpCurrentTimeChangingEvent(g,f){if("currentTimeChanging"!==g.type||!f.time)return;const S={newCurrentPlayPosition:f.time};this.eventsHandler.message("stateChanged").send("UserInitiatedSeek",S)}registerPlayerEvent(g,f){this.playerEvents.push(g),this.playerInstance.addEventListener(g,f)}registerVideoEvent(g,f){this.videoElementEvents.push({name:g,callback:f}),this.video.addEventListener(g,f)}removePlayerEventListeners(){this.playerEvents.forEach((g=>{this.playerInstance.removeEventListener(g)}))}removeVideoEventListeners(){this.videoElementEvents.forEach((g=>{this.video.removeEventListener(g.name,g.callback)}))}onAmpEvent(g){let f,S;switch(g){case this.contextWindow.amp.eventName.error:S=this.playerInstance.error(),f={currentTime:this.playerInstance.currentTime(),errorCode:S?S.code:0,message:S?S.message:""};break;case this.contextWindow.amp.eventName.canplaythrough:this.initializeStatsColletion();break;case this.contextWindow.amp.eventName.loadedmetadata:this.captionsControl.initialize(),this.absoluteTimeOffsetEstimator&&this.absoluteTimeOffsetEstimator.restartStreamAbsoluteTimeOffsetRetrieval();break;case this.contextWindow.amp.eventName.fullscreenchange:f={isFullscreen:this.playerInstance.isFullscreen()};break;case this.contextWindow.amp.eventName.playbackbitratechanged:f={bitrate:this.playerInstance.currentPlaybackBitrate()};break;case this.contextWindow.amp.eventName.downloadbitratechanged:f={bitrate:this.playerInstance.currentDownloadBitrate()};break;case this.contextWindow.amp.eventName.seeked:f={captionsTimestamp:this.isControlsDisabled()?this.playerInstance.currentMediaTime():this.playerInstance.currentTime()};break;case this.contextWindow.amp.eventName.volumechange:f={value:this.playerInstance.volume()}}this.updatePlaybackDiagnostics(),this.updatePlayerState(g),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(g,f)}updatePlayerState(g){this.updatePlayingState(g),this.updateBufferingState(g),this.updateCurrentVideoTrackBitrate(g),g!==this.contextWindow.amp.eventName.ended&&g!==this.contextWindow.amp.eventName.error||this.handlePlaybackStopped()}handleUserExperienceErrorEvent(g,f,S){const v={currentTime:this.video?this.video.currentTime:0,message:f,type:g,errorCode:0,fatal:S};this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(this.contextWindow.amp.eventName.error,v)}updatePlayingState(g){this.isPlaying?g!==this.contextWindow.amp.eventName.pause&&g!==this.contextWindow.amp.eventName.seeking&&g!==this.contextWindow.amp.eventName.ended&&g!==this.contextWindow.amp.eventName.error&&g!==this.contextWindow.amp.eventName.waiting||(this.isPlaying=!1):g===this.contextWindow.amp.eventName.playing&&(this.isPlaying=!0)}updateBufferingState(g){this.isBuffering?(g===this.contextWindow.amp.eventName.pause&&"html5"===this.playerInstance.currentTechName()?.toLowerCase()||g===this.contextWindow.amp.eventName.seeking||g===this.contextWindow.amp.eventName.ended||g===this.contextWindow.amp.eventName.error||g===this.contextWindow.amp.eventName.playing)&&(this.isBuffering=!1):g===this.contextWindow.amp.eventName.waiting&&(this.isBuffering=!0)}updateCurrentVideoTrackBitrate(g){g===this.contextWindow.amp.eventName.playbackbitratechanged&&this.playerInstance.currentPlaybackBitrate()!==this.currentVideoPlaybackBitrate&&(this.currentVideoPlaybackBitrate=this.playerInstance.currentPlaybackBitrate(),this.updateVideoTrackHistoryStatistic())}initializeStatsColletion(){this.diagnosticProvider.initialize(),this.statsTimer=window.setInterval((()=>{this.eventsHandler&&(this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()))}),this.statsInterval)}stopStatsCollection(){this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),-1!==this.statsTimer&&window.clearInterval(this.statsTimer),this.statsTimer=-1}updateVideoTrackHistoryStatistic(){const g=new Date;if(this.currentVideoPlaybackBitrate){const f=this.diagnosticProvider.getValue("videoTrackHistory"),S=this.diagnosticProvider.getValue("videoTrackTotalDurations");if(f.length>0&&this.currentVideoPlaybackBitrate===f[f.length-1].trackPlaybackBitrate){if(this.videoTrackHistoryUpdatedTimestamp){this.latestVideoTrackDuration+=(g.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,f[f.length-1].durationInSeconds=Number(this.latestVideoTrackDuration.toFixed(0));const v=this.videoTrackTotalDurations.find((g=>g.trackPlaybackBitrate===this.currentVideoPlaybackBitrate)),C=S.find((g=>g.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));v&&C&&(v.totalDurationInSeconds+=(g.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,C.totalDurationInSeconds=Number(v.totalDurationInSeconds.toFixed(0)))}}else{const v=this.playerInstance.videoBufferData();let C=null;v&&v.perceivedBandwidth&&(C=v.perceivedBandwidth),f.push({trackPlaybackBitrate:this.currentVideoPlaybackBitrate,trackSwitchTimestamp:g.getTime(),trackSwitchMeasuredBandwidth:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredBandwidth():null,trackSwitchMeasuredByteSize:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredVideoDownloadSize():null,trackSwitchPerceivedBandwidth:C,durationInSeconds:0}),this.latestVideoTrackDuration=0,f.length>this.configProvider.config.maxVideoTrackHistoryLogCount&&f.splice(0,1);const _=this.videoTrackTotalDurations.find((g=>g.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));if(!_){const g={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0},f={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0};this.videoTrackTotalDurations.push(g),S.push(f)}}}this.videoTrackHistoryUpdatedTimestamp=g}updateTotalPlayingTimeStatistic(){const g=new Date;this.isPlaying&&this.totalPlayingTimeUpdatedTimestamp&&(this.totalPlayingTime+=g.getTime()-this.totalPlayingTimeUpdatedTimestamp.getTime()),this.totalPlayingTimeUpdatedTimestamp=g,this.diagnosticProvider.setValue("totalPlayingTimeInSeconds",Number((this.totalPlayingTime/1e3).toFixed(0)))}updateBufferingRateStatistic(){const g=new Date;this.isBuffering&&this.bufferingRateStatUpdatedTimestamp&&(this.totalBufferingTime+=g.getTime()-this.bufferingRateStatUpdatedTimestamp.getTime()),this.bufferingRateStatUpdatedTimestamp=g;const f=this.totalPlayingTime>0||this.totalBufferingTime>0?this.totalBufferingTime/(this.totalPlayingTime+this.totalBufferingTime):0;this.diagnosticProvider.setValue("bufferingRate",Number(f.toFixed(3)))}getPlayerDiagnostics(){const g=this.diagnosticProvider.getPlayerDiagnosticSnapshot();return g.statsInterval=this.statsInterval,this.configProvider.config.debug&&(g.memoryLog=this.playerInstance.getMemoryLog(!0)),g}log(g,f="info"){const S=`[AmpPlayer${1===this.configProvider.config.loadType?"IFrame":""}]: ${g}`;this.configProvider.config.debug&&console.log(S),this.eventsHandler.message("log").send(f,S)}getElementLoadPromise(g,f){return new Promise(((S,v)=>{g.onload=()=>{S("Element Load success")},g.onerror=()=>{v(`Failed to load script: ${f}`)}}))}loadCss(g,f,S){const v=g.createElement("link"),C=this.getElementLoadPromise(v,f);return v.href=f,v.rel="stylesheet",S&&(v.nonce=S),g.head.appendChild(v),C}parseJson(g,f){try{return JSON.parse(g)}catch(g){throw this.log(`Error parsing JSON for ${f}, error: ${JSON.stringify(g)}`),g}}}}function AmpCommunicationHandlerF(){const g=AmpPlayerF();return class{constructor(f,S){this.pipe=f,this.amp=new g(S,this)}processMessage(g){"Command"===g.msgType&&Promise.resolve().then((()=>this.amp[g.cmd].apply(this.amp,g.args))).then((f=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:g.cmd,result:JSON.stringify(f)})})).catch((f=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:g.cmd,error:f})}))}message(g){return{send:this.fromMessage(((...f)=>{this.sendMessageImpl(g,f)}))}}ampDisposed(){this.pipe.dispose(),this.pipe=null,this.amp=null}fromMessage(g){return g}sendMessageImpl(g,f){this.pipe.sendMsg({msgType:"PlayerNotification",name:g,args:f})}}}AmpPlayerF();var gt=AmpCommunicationHandlerF();function IFrameMessageHandlerF(){function isCmdResult(g){return"CommandResult"===g.msgType}function getErrorString(g){let f="unknown";try{f="string"==typeof g?g:"toString"in g&&0!==g.toString().indexOf("[object")?g.toString():JSON.stringify(g)}catch(f){console.error("Failed to stringify error",g)}return f}return class{constructor(){this.processMsg=this.processMsg.bind(this),window.addEventListener("message",this.processMsg)}sendMsg(g){try{let f=g;isCmdResult(g)&&g.error instanceof Event&&(console.debug("Stringifying error Event before trying to postMessage:",g),f={msgType:g.msgType,cmd:g.cmd,error:`Event: ${getErrorString(g.error)}`}),this.postMessage(f)}catch(f){console.error("Unexpected exception caught from postMessage.\n","message:",g,"\n","exception:",f);const S={msgType:"PlayerNotification",name:"log",args:["error",`Unexpected error with postMessage: ${getErrorString(f)}`]};throw this.postMessage(S),f}}registerObserver(g){this.observer=g}dispose(){window.removeEventListener("message",this.processMsg),this.observer=null}processMsg(g){this.observer.processMessage(g.data)}postMessage(g){window.parent.postMessage(g,"*")}}}function HlsAbsoluteTimeOffsetEstimatorF(){const g=HlsFileParserF();return class{constructor(f){this.playlistFileDownloadPromise=Promise.resolve(),this.playlistFileDownloadRetryWaitTime=250,this.playlistFileDownloadMaxRetryCount=20,this.playlistFileDownloadCancellationFlag=!1,this.logFn=(g,S)=>f(`[HlsAbsoluteTimeOffsetEstimator]: ${g}`,S),this.hlsFileParser=new g(f)}get absoluteTimeOffset(){return this.estimatedAbsoluteTimeOffset}setEstimationResultCallback(g){this.onAbsoluteTimeOffsetEstimation=g}restartStreamAbsoluteTimeOffsetRetrieval(){this.stopStreamAbsoluteTimeOffsetRetrieval().then((()=>this.startStreamAbsoluteTimeOffsetRetrieval()))}setManifestFileURL(g){this.cachedManifestUrl=g}startStreamAbsoluteTimeOffsetRetrieval(){this.playlistFileDownloadPromise=this.retryPlaylistFileDownload((()=>this.estimateStreamTimeFromPlaylist(this.currentManifestUrl))).then((()=>{this.logFn(`Succeeded in downloading playlist files to estimate\n                    absolute stream time offset as: ${this.estimatedAbsoluteTimeOffset}`)})).catch((g=>{this.logFn(`Failed to download playlist files to estimate absolute stream time offset: ${g.message}`,"error")}))}stopStreamAbsoluteTimeOffsetRetrieval(){return this.playlistFileDownloadCancellationFlag=!0,this.playlistFileDownloadPromise.then((()=>{this.playlistFileDownloadCancellationFlag=!1,this.currentManifestUrl=this.cachedManifestUrl,this.cachedManifestUrl=null}))}retryPlaylistFileDownload(g,f=0){let S=Promise.resolve();return S=g().then((()=>(this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:f,isSuccess:!0,absoluteTimeOffsetEstimation:this.absoluteTimeOffset}),Promise.resolve()))).catch((S=>(f++,this.logFn(`Error loading playlist file: ${S} -- attempt ${f}`),this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:f,isSuccess:!1,error:S.message}),f===this.playlistFileDownloadMaxRetryCount?Promise.reject(new Error(`${S} after ${f} attempts`)):this.playlistFileDownloadCancellationFlag?Promise.reject(new Error("cancelling playlist file download")):new Promise((S=>setTimeout((()=>S(this.retryPlaylistFileDownload(g,f))),this.playlistFileDownloadRetryWaitTime)))))),S}estimateStreamTimeFromPlaylist(g){return this.hlsFileParser.getStreamRenditionsUrlsFromManifest(g).then((f=>{if(0===f.audioRenditions.length&&0===f.videoRenditions.length)throw new Error(`Unable to retrieve renditions URLs from manifest: ${g}`);return Promise.all([f.videoRenditions.length>0?this.hlsFileParser.getTextFileContent(f.videoRenditions[0]):Promise.resolve(null),f.audioRenditions.length>0?this.hlsFileParser.getTextFileContent(f.audioRenditions[0]):Promise.resolve(null)])})).then((g=>{let f;for(let S=0;S<g.length;S++){const v=g[S];if(v){this.logFn("Using segment duration and sequence number to calculate absolute time offset","debug");const g=this.hlsFileParser.getHlsFieldByName("SequenceNumber",v);if(0==g.length)throw new Error("Unable to retrieve sequence number from playlist file");const S=this.hlsFileParser.getHlsFieldByName("SegmentDuration",v,10);if(0==S.length)throw new Error("Unable to retrieve segment durations from playlist file");const C=S.map(Number);C.sort(((g,f)=>g-f));const _=C[Math.floor(C.length/2)],T=Number(g[0])*Number(_);f=f?Math.max(f,T):T}}this.estimatedAbsoluteTimeOffset=f}))}}}var pt=HlsAbsoluteTimeOffsetEstimatorF();function HlsFileParserF(){return class{constructor(g){this.fieldNameRegexMap={BaseUrl:/(.*)\/.*/,AudioManifestFile:/#EXT-X-MEDIA:TYPE=AUDIO.*URI=\"(.*)\"/,SequenceNumber:/#EXT-X-MEDIA-SEQUENCE:(\d+)/,SegmentDuration:/#EXTINF:(\d+(\.\d+)?)/},this.logFn=(f,S)=>g(`[HlsFileParser]: ${f}`,S)}getHlsFieldByName(g,f,S=1){const v=[];for(let C=1;C<=S;C++){const S=this.fieldNameRegexMap[g].exec(f);if(!(S&&S.length>0))break;v.push(S[1]),f=f.substring(S.index+S[0].length)}return v}getStreamRenditionsUrlsFromManifest(g){return g?this.getTextFileContent(g).then((f=>{const S={audioRenditions:[],videoRenditions:[]},v=f.split("\n"),C=this.getHlsFieldByName("BaseUrl",g);for(let g=0;g<v.length;g++)if(v[g].includes("#EXT-X-STREAM-INF")){const f=v[g+1];f.includes("http")?S.videoRenditions.push(f):C.length>0&&S.videoRenditions.push(`${C[0]}/${f}`)}else if(v[g].includes("EXT-X-MEDIA:TYPE")){const f=this.getHlsFieldByName("AudioManifestFile",v[g]);if(f.length>0){const g=f[0];g.includes("http")?S.audioRenditions.push(g):C.length>0&&S.audioRenditions.push(`${C[0]}/${g}`)}}return S})).catch((g=>(this.logFn(`Failed to extract stream renditions from manifest, error: ${g.message}`,"error"),{audioRenditions:[],videoRenditions:[]}))):(this.logFn("No manifest URL provided to parse"),Promise.resolve({audioRenditions:[],videoRenditions:[]}))}getTextFileContent(g){const f=fetch(g).then((f=>{if(!f.ok)throw new Error(`http-error ${f.status} when downloading: ${g}`);return f.text()})).catch((g=>(this.logFn(`Error downloading resource: ${g}`,"error"),Promise.reject(g))));return f}}}function AmpDiagnosticProviderF(){return class{constructor(g,f,S,v,C){this.playerInstance=g,this.contextWindow=f,this.streamingStartedTimestamp=S,this.configProvider=v,this.absoluteTimeOffsetEstimator=C,this.currentDiagnosticSnapshot={playerType:0,currentPlayPosition:null,tech:null,perceivedBandwidth:null,playerHeight:null,playerWidth:null,mediaHeight:null,mediaWidth:null,windowHeight:null,windowWidth:null,videoStream:null,audioStream:null,totalDurationInSeconds:null,avgVideoDownloadLatency:null,avgAudioDownloadLatency:null,avgVideoDownloadBytes:null,avgAudioDownloadBytes:null,avgAudioDownloadBandwidth:null,avgVideoDownloadBandwidth:null,maxVideoDownloadBytes:null,minVideoDownloadBytes:null,videoDownloadSuccessCount:null,audioDownloadSuccessCount:null,videoDownloadFailureCount:null,audioDownloadFailureCount:null,videoBufferLength:null,videoCachedLength:null,audioBufferLength:null,audioCachedLength:null,videoEdgeLatency:null,audioEdgeLatency:null,playbackRate:null,playbackBitrate:null,downloadBitrate:null,audioDownloadBitrate:null,audioPlaybackBitrate:null,isFullscreen:null,streamType:null,playerVersion:null,isP2PSdnUsed:null,sdnName:null,livePosition:null,muted:null,volume:null,errorCode:null,currentMediaTime:null,currentAbsoluteTime:null,absoluteTimeOffsetEstimationResults:null,estimatedAbsoluteTimeOffset:null,videoDownloadFailures:null,audioDownloadFailures:null,heuristicProfile:null,encryption:null,retryFrequency:null,averageDownloadBitrate:null,totalDownloadedBytes:0,streamId:null,streamUrl:null,streamingEventType:null,playerControlsEnabled:null,streamDeliveryPipeline:null,retryCount:0,totalPlayingTimeInSeconds:0,bufferingRate:0,videoTrackHistory:[],videoTrackTotalDurations:[],memoryLog:null,statsInterval:null},this.videoDownloadLatencies=[],this.audioDownloadLatencies=[],this.audioDownloadBytes=[],this.videoDownloadBytes=[],this.audioDownloadBandwidths=[],this.videoDownloadBandwidths=[],this.videoDownloadSuccessCount=0,this.audioDownloadSuccessCount=0,this.videoDownloadFailureCount=0,this.audioDownloadFailureCount=0,this.audioDownloadFailures=[],this.videoDownloadFailures=[],this.totalDownloadedBytes=0,this.slidingWindowLengthForLatency=5,this.slidingWindowLengthForDownloadBytes=30,this.slidingWindowLengthForDownloadBandwidth=10,this.absoluteTimeOffsetEstimationResults=[],this.downloadFailuresLimit=10,this.onAudioDownloadCompleted=this.onAudioDownloadCompleted.bind(this),this.onAudioDownloadError=this.onAudioDownloadError.bind(this),this.onVideoDownloadCompleted=this.onVideoDownloadCompleted.bind(this),this.onVideoDownloadError=this.onVideoDownloadError.bind(this)}initialize(){this.playerVideoBuffer=this.playerInstance.videoBufferData(),this.playerAudioBuffer=this.playerInstance.audioBufferData(),this.registerForPlayerBufferEvents()}setValue(g,f){this.currentDiagnosticSnapshot[g]=f}getValue(g){return this.currentDiagnosticSnapshot[g]}appendAbsoluteTimeOffsetEstimation(g){this.absoluteTimeOffsetEstimationResults.push(g),this.absoluteTimeOffsetEstimationResults.length>this.configProvider.config.ampSettings.maxAbsoluteTimeOffsetEstimationResultsLogCount&&this.absoluteTimeOffsetEstimationResults.splice(0,1)}getPlayerDiagnosticSnapshot(){if(!this.playerInstance)return null;const g=window.screen,f=this.playerInstance.error(),mean5=g=>{const f=g.slice().sort();return f[Math.floor(f.length/2)]};this.currentDiagnosticSnapshot.errorCode=f&&f.code||0,this.currentDiagnosticSnapshot.currentPlayPosition=this.playerInstance.currentTime(),this.currentDiagnosticSnapshot.currentMediaTime=this.playerInstance.currentMediaTime()??this.playerInstance.currentTime(),this.currentDiagnosticSnapshot.currentAbsoluteTime=this.getCurrentAbsoluteTime(),this.currentDiagnosticSnapshot.absoluteTimeOffsetEstimationResults=this.absoluteTimeOffsetEstimationResults,this.currentDiagnosticSnapshot.estimatedAbsoluteTimeOffset=this.getCurrentAbsoluteTimeOffset(),this.currentDiagnosticSnapshot.playbackBitrate=this.playerInstance.currentPlaybackBitrate(),this.currentDiagnosticSnapshot.downloadBitrate=this.playerInstance.currentDownloadBitrate(),this.currentDiagnosticSnapshot.audioDownloadBitrate=this.lastAudioDownloadBitrate,this.currentDiagnosticSnapshot.perceivedBandwidth=this.playerVideoBuffer?this.playerVideoBuffer.perceivedBandwidth:0,this.currentDiagnosticSnapshot.tech=this.playerInstance.currentTechName(),this.currentDiagnosticSnapshot.playerVersion=this.playerInstance.getAmpVersion(),this.currentDiagnosticSnapshot.isP2PSdnUsed=this.isP2PSdnUsed(),this.currentDiagnosticSnapshot.sdnName=this.sdnName(),this.currentDiagnosticSnapshot.heuristicProfile=this.playerInstance.currentHeuristicProfile(),this.currentDiagnosticSnapshot.encryption=this.playerInstance.currentProtectionInfo()?this.playerInstance.currentProtectionInfo().type:"",this.currentDiagnosticSnapshot.streamType=this.getStreamType(this.currentDiagnosticSnapshot.streamType),this.currentDiagnosticSnapshot.totalDurationInSeconds=this.getTotalDurationInSeconds(),this.currentDiagnosticSnapshot.audioStream=this.getAudioStreamData(),this.currentDiagnosticSnapshot.videoStream=this.getVideoStreamData(),this.currentDiagnosticSnapshot.muted=this.playerInstance.muted(),this.currentDiagnosticSnapshot.volume=this.playerInstance.volume(),this.currentDiagnosticSnapshot.playbackRate=this.playerInstance.playbackRate();const S=this.getPlayerCachedLength(),v=this.getPlayerEdgeLatency();this.currentDiagnosticSnapshot.audioBufferLength=this.playerAudioBuffer?this.playerAudioBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.audioCachedLength=S,this.currentDiagnosticSnapshot.audioEdgeLatency=v,this.currentDiagnosticSnapshot.videoBufferLength=this.playerVideoBuffer?this.playerVideoBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.videoCachedLength=S,this.currentDiagnosticSnapshot.videoEdgeLatency=v,this.currentDiagnosticSnapshot.livePosition=this.getLivePosition(),this.currentDiagnosticSnapshot.mediaHeight=this.playerInstance.videoHeight(),this.currentDiagnosticSnapshot.mediaWidth=this.playerInstance.videoWidth(),this.currentDiagnosticSnapshot.playerHeight=this.playerInstance.height(),this.currentDiagnosticSnapshot.playerWidth=this.playerInstance.width(),this.currentDiagnosticSnapshot.windowHeight=g?g.height:0,this.currentDiagnosticSnapshot.windowWidth=g?g.width:0,this.currentDiagnosticSnapshot.isFullscreen=this.playerInstance.isFullscreen(),this.currentDiagnosticSnapshot.avgAudioDownloadLatency=mean5(this.audioDownloadLatencies),this.currentDiagnosticSnapshot.avgVideoDownloadLatency=mean5(this.videoDownloadLatencies),this.currentDiagnosticSnapshot.avgAudioDownloadBytes=mean5(this.audioDownloadBytes),this.currentDiagnosticSnapshot.avgVideoDownloadBytes=mean5(this.videoDownloadBytes),this.currentDiagnosticSnapshot.maxVideoDownloadBytes=Math.max.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.minVideoDownloadBytes=Math.min.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.avgAudioDownloadBandwidth=mean5(this.audioDownloadBandwidths),this.currentDiagnosticSnapshot.avgVideoDownloadBandwidth=mean5(this.videoDownloadBandwidths),this.currentDiagnosticSnapshot.audioDownloadFailureCount=this.audioDownloadFailureCount,this.currentDiagnosticSnapshot.audioDownloadSuccessCount=this.audioDownloadSuccessCount,this.currentDiagnosticSnapshot.videoDownloadFailureCount=this.videoDownloadFailureCount,this.currentDiagnosticSnapshot.videoDownloadSuccessCount=this.videoDownloadSuccessCount,this.currentDiagnosticSnapshot.audioDownloadFailures=this.audioDownloadFailures,this.currentDiagnosticSnapshot.videoDownloadFailures=this.videoDownloadFailures,this.currentDiagnosticSnapshot.totalDownloadedBytes=this.totalDownloadedBytes,this.currentDiagnosticSnapshot.retryFrequency=this.getRetryFrequency(),this.currentDiagnosticSnapshot.averageDownloadBitrate=this.getAverageDownloadBitrate();const C=this.getDiagnosticWritableField();return Object.keys(C).forEach((g=>{this.currentDiagnosticSnapshot[g]=C[g]})),this.currentDiagnosticSnapshot}getDiagnosticWritableField(){return{streamUrl:this.currentDiagnosticSnapshot.streamUrl,streamId:this.currentDiagnosticSnapshot.streamId,streamingEventType:this.currentDiagnosticSnapshot.streamingEventType,playerControlsEnabled:this.currentDiagnosticSnapshot.playerControlsEnabled,streamDeliveryPipeline:this.currentDiagnosticSnapshot.streamDeliveryPipeline,retryCount:this.currentDiagnosticSnapshot.retryCount,totalPlayingTimeInSeconds:this.currentDiagnosticSnapshot.totalPlayingTimeInSeconds,bufferingRate:this.currentDiagnosticSnapshot.bufferingRate,videoTrackHistory:this.currentDiagnosticSnapshot.videoTrackHistory,videoTrackTotalDurations:this.currentDiagnosticSnapshot.videoTrackTotalDurations,eventId:this.currentDiagnosticSnapshot.eventId||"",templateId:this.currentDiagnosticSnapshot.templateId||""}}dispose(){this.unsubscribeFromPlayerBufferEvents()}registerForPlayerBufferEvents(){this.playerVideoBuffer&&(this.playerVideoBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onVideoDownloadCompleted),this.playerVideoBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onVideoDownloadError)),this.playerAudioBuffer&&(this.playerAudioBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onAudioDownloadCompleted),this.playerAudioBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onAudioDownloadError))}unsubscribeFromPlayerBufferEvents(){this.playerVideoBuffer&&(this.playerVideoBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onVideoDownloadCompleted),this.playerVideoBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onVideoDownloadError)),this.playerAudioBuffer&&(this.playerAudioBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onAudioDownloadCompleted),this.playerAudioBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onAudioDownloadError))}isP2PSdnUsed(){return!!this.sdnName()}sdnName(){const g="options_";return this.playerInstance[g]&&this.playerInstance[g].sdn&&this.playerInstance[g].sdn.name}getStreamType(g){let f="";return this.playerInstance&&(f=this.playerInstance.isLive()?"LIVE":"DVR"),""===f||"LIVE"===g&&f!==g?g||"":f}getCurrentAbsoluteTime(){return this.absoluteTimeOffsetEstimator?this.absoluteTimeOffsetEstimator.absoluteTimeOffset?this.absoluteTimeOffsetEstimator.absoluteTimeOffset+this.playerInstance.currentTime():this.playerInstance.currentTime():this.playerInstance.currentAbsoluteTime()??this.playerInstance.currentTime()}getCurrentAbsoluteTimeOffset(){return this.getCurrentAbsoluteTime()-this.playerInstance.currentTime()}getTotalDurationInSeconds(){const g=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;return Number(g.toFixed(0))}onVideoDownloadCompleted(){this.videoDownloadSuccessCount++,this.addToList(this.videoDownloadLatencies,this.playerVideoBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForLatency),this.addToList(this.videoDownloadBytes,this.playerVideoBuffer.downloadCompleted.totalBytes,this.slidingWindowLengthForDownloadBytes),this.addToList(this.videoDownloadBandwidths,8*this.playerVideoBuffer.downloadCompleted.totalBytes*1e3/this.playerVideoBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForDownloadBandwidth),this.totalDownloadedBytes+=this.playerVideoBuffer.downloadCompleted.totalBytes}onAudioDownloadCompleted(){this.audioDownloadSuccessCount++,this.addToList(this.audioDownloadLatencies,this.playerAudioBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForLatency),this.addToList(this.audioDownloadBytes,this.playerAudioBuffer.downloadCompleted.totalBytes,this.slidingWindowLengthForDownloadBytes),this.addToList(this.audioDownloadBandwidths,8*this.playerAudioBuffer.downloadCompleted.totalBytes*1e3/this.playerAudioBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForDownloadBandwidth),this.totalDownloadedBytes+=this.playerAudioBuffer.downloadCompleted.totalBytes;const g=this.playerAudioBuffer.downloadCompleted.mediaDownload.bitrate;g!==this.lastAudioDownloadBitrate&&(this.lastAudioDownloadBitrate=g)}addToList(g,f,S){g.push(f),g.length>S&&g.shift()}onVideoDownloadError(){this.videoDownloadFailureCount++,this.addDownloadFailureInfo(this.playerVideoBuffer.downloadFailed,this.videoDownloadFailures)}onAudioDownloadError(){this.audioDownloadFailureCount++,this.addDownloadFailureInfo(this.playerAudioBuffer.downloadFailed,this.audioDownloadFailures)}addDownloadFailureInfo(g,f){const S={bitrate:g.mediaDownload.bitrate,errorCode:g.code,mediaTime:g.mediaDownload.mediaTime,message:g.message,timestamp:Date.now()};this.addToList(f,S,this.downloadFailuresLimit)}getAudioStreamData(){const g=this.playerInstance.currentAudioStreamList();if(g)try{const f=g.streams[g.enabledIndices[0]];return{bitrate:f.bitrate,codec:f.codec,enabled:f.enabled,name:f.name,language:f.language}}catch(g){return}}getVideoStreamData(){const g=this.playerInstance.currentVideoStreamList();if(g)try{const f=g.streams[g.selectedIndex],S=this.playerInstance.currentPlaybackBitrate(),mapTrackData=g=>({bitrate:g.bitrate,height:g.height,id:g.id,selectable:g.selectable,width:g.width}),v=f.tracks?f.tracks.map(mapTrackData).find((g=>g.bitrate===S)):null;return{codec:f.codec,name:f.name,currentTrack:v}}catch(g){return}}getLivePosition(){const g=this.playerInstance.buffered();if(0===g.length)return 0;let f=g.end(0);for(let S=1;S<g.length;S++)f=Math.max(f,g.end(S));return f}getAverageDownloadBitrate(){if(this.streamingStartedTimestamp&&this.totalDownloadedBytes){const g=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;if(g>0)return 8*this.totalDownloadedBytes/g}return 0}getRetryFrequency(){const g=this.currentDiagnosticSnapshot.retryCount;if(this.streamingStartedTimestamp&&g){const f=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/6e4;if(f>0)return g/f}return 0}getAverageMeasuredBandwidth(){if(0===this.videoDownloadBandwidths.length)return null;let g=0;for(let f=0;f<this.videoDownloadBandwidths.length;f++)g+=this.videoDownloadBandwidths[f];return g/this.videoDownloadBandwidths.length}getAverageMeasuredVideoDownloadSize(){if(0===this.videoDownloadBytes.length)return null;let g=0;for(let f=0;f<this.videoDownloadBytes.length;f++)g+=this.videoDownloadBytes[f];return g/this.videoDownloadBytes.length}getPlayerCachedLength(){const g=this.playerInstance.buffered();let f=0;for(let S=0;S<g.length;S++)f+=g.end(S)-g.start(S);return f}getPlayerEdgeLatency(){const g=this.playerInstance.buffered();if(0===g.length)return 0;let f=g.end(0);for(let S=1;S<g.length;S++)f=Math.max(f,g.end(S));return f-this.playerInstance.currentTime()}}}function CaptionsControlToggleProviderF(){return class{constructor(g,f,S,v){this.player=g,this.toggleListener=f,this.config=S,this.diagnosticProvider=v,this.onTextTrackChanged=this.onTextTrackChanged.bind(this),this.isHtml5Tech="html5"===this.player.currentTechName()?.toLowerCase()}dispose(){this.unsubscribeFromTrackEvents(),this.player=null,this.toggleListener=null}initialize(){const g=this.getPlayerTextTracksAsArray();if(!this.config.controlsEnabled&&g.length>0)g[0].mode="showing";else for(let f=0;f<g.length;f++)g[f].mode="disabled";this.subscribeOnTrackEvents()}addCues(g){const f=this.player.getCurrentTextTrack();if(!f)return;const S=this.getCurrentAbsoluteTime()||1,v=this.getCurrentTime(),C=this.config.controlsEnabled?S-v:Math.max(S-v,0),_=this.isHtml5Tech?window.VTTCue:window.vttjs&&window.vttjs.VTTCue||window.VTTCue;for(let S=0;S<g.length;S++){const{start:v,end:T,text:I}=g[S],b=2,A=new _(Number((v-C).toFixed(b)),Number((T-C).toFixed(b)),I);A.size=100,!this.containsCue(f,A)&&f.addCue(A)}}clearCues(){const g=this.player.getCurrentTextTrack();if(g)try{if(g.activeCues&&g.removeCue)for(;g.activeCues.length>0;)g.removeCue(g.activeCues[0]);const f="setCues_";if(g.cues[f]){g.cues_&&(g.cues_.length=0),g.cues[f]([]);const S=Object.getOwnPropertyNames(g.cues);for(let f=0;f<S.length;f++)"length"!==S[f]&&"length_"!==S[f]&&"cues_"!==S[f]&&delete g.cues[S[f]]}}catch(g){this.config.logFn(`[clearCues]: ${g}`,"warn")}}showCaptions(g){this.config.logFn(`[CaptionsControl]: showCaptions(${g})`),g?this.show():this.hide()}hide(){this.previouslyVisibleTextTrack=this.player.getCurrentTextTrack(),this.previouslyVisibleTextTrack&&(this.previouslyVisibleTextTrack.mode="disabled"),this.player.captionToggle&&this.player.captionToggle.hide&&this.player.captionToggle.hide(),this.player.MoreOptionscaptionSubtitleButton&&this.player.MoreOptionscaptionSubtitleButton.hide&&this.player.MoreOptionscaptionSubtitleButton.hide(),this.player.MoreOptionscaptionSettingsButton&&this.player.MoreOptionscaptionSettingsButton.hide&&this.player.MoreOptionscaptionSettingsButton.hide()}show(){this.previouslyVisibleTextTrack&&(this.previouslyVisibleTextTrack.mode="showing"),this.player.captionToggle&&this.player.captionToggle.show&&this.player.captionToggle.show(),this.player.MoreOptionscaptionSubtitleButton&&this.player.MoreOptionscaptionSubtitleButton.show&&this.player.MoreOptionscaptionSubtitleButton.show(),this.player.MoreOptionscaptionSettingsButton&&this.player.MoreOptionscaptionSettingsButton.show&&this.player.MoreOptionscaptionSettingsButton.show()}subscribeOnTrackEvents(){const g=this.player.textTracks(),f="addEventListener";g&&g[f]&&(this.config.controlsEnabled&&g[f]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&g[f]("addtrack",this.onAddTrack.bind(this)))}unsubscribeFromTrackEvents(){const g=this.player.textTracks(),f="removeEventListener";g&&g[f]&&(this.config.controlsEnabled&&g[f]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&g[f]("addtrack",this.onAddTrack.bind(this)))}onTextTrackChanged(){const g=this.player.getCurrentTextTrack();if(!g||!this.currentTextTrack||this.currentTextTrack.label!==g.label||this.currentTextTrack.mode!==g.mode){if(g||this.currentTextTrack){const f=!!g&&"showing"===g.mode,S=this.getCulture(g||this.currentTextTrack),v=this.getCurrentTime();this.toggleListener.captionsToggled(f,S,v),this.config.logFn(`[CaptionsControl]: track changed: culture '${S}', timestamp '${v}'`)}this.currentTextTrack=g}}onAddTrack(g){const f=g?.track;"captions"===f?.kind&&!f.label&&!f.id&&(this.player?.textTracks_?.removeTrack_(f),this.config.logFn("[CaptionsControl]: removing default empty text track"))}getCurrentTime(){return this.isHtml5Tech?this.player.currentTime():(this.config.controlsEnabled?this.player.currentTime():this.player.currentMediaTime())||1}getCurrentAbsoluteTime(){return this.diagnosticProvider.getCurrentAbsoluteTime()}getCulture(g){if(!g)return"";if(g.id){const f=g.id.split("_")[1];if(f)return f}return""}getPlayerTextTracksAsArray(){const g=this.player.textTracks();return g&&g.tracks_||[]}containsCue(g,f){return Array.from(g?.cues||[]).some((g=>this.areCueEquals(g,f)))}areCueEquals(g,f){function getCueField(g){return{start:g.start?g.start:g.startTime,end:g.end?g.end:g.endTime,text:g.text}}const S=getCueField(g),v=getCueField(f);return S.start===v.start&&S.end===v.end&&S.text===v.text}}}function initIFrame(){const g=IFrameMessageHandlerF(),f=AmpCommunicationHandlerF(),S=new g,v=new f(S,document.body);S.registerObserver(v)}function buildAmpEmbeddedSrc(){let g=`(${initIFrame.toString()})();`;return g+=AmpPlayerF.toString()+";",g+=IFrameMessageHandlerF.toString()+";",g+=AmpCommunicationHandlerF.toString()+";",g+=CaptionsControlToggleProviderF.toString()+";",g+=AmpDiagnosticProviderF.toString()+";",g+=HlsAbsoluteTimeOffsetEstimatorF.toString()+";",g+=HlsFileParserF.toString()+";",g+="//# sourceURL=TsCallingAmpPlayer.js",g}var mt=class{sendMsg(g){this.peer.onMsg(g)}registerObserver(g){this.observer=g}onMsg(g){this.observer&&this.observer.processMessage(g)}connect(g){this.peer=g}dispose(){this.peer=null,this.observer=null}},ft=class{constructor(g){this.container=g}get contextWindow(){return this.container.ownerDocument.defaultView}sendMsg(g){this.iframe?.contentWindow?.postMessage(g,"*")}registerObserver(g){this.observer=g}dispose(){this.contextWindow&&this.contextWindow.removeEventListener("message",this.processMsg),this.iframe&&this.container.hasChildNodes()&&this.container.removeChild(this.iframe),this.iframe=null}initializeAmpIframe(g){const f=this.initializeIframe();return this.setAmpIframeContent(g),this.finalizeIframe(f)}initializeIframe(){const g=new dt;return this.iframe=this.container.ownerDocument.createElement("iframe"),this.iframe.id="player-iframe",this.iframe.sandbox.add("allow-scripts"),this.iframe.allowFullscreen=!0,this.iframe.allow="camera; microphone; autoplay",this.iframe.style.height="100%",this.iframe.style.width="100%",this.iframe.style.border="none",this.iframe.onload=()=>{g.resolve()},this.iframe.onerror=()=>{g.reject("iframe load failed")},g}finalizeIframe(g){return this.container.appendChild(this.iframe),this.processMsg=this.processMsg.bind(this),this.contextWindow.addEventListener("message",this.processMsg),g.promise}processMsg(g){"null"===g.origin&&g.source===this.iframe.contentWindow&&this.observer&&("RequestIceCandidates"===g.data?this.observer.processMessage({msgType:"Command",cmd:"getIceCandidates",args:[]}):this.observer.processMessage(g.data))}setAmpIframeContent(g){const f=buildAmpEmbeddedSrc(),S=`\n            <html class style='height: 100%; width: 100%; overflow: hidden'>\n            <head></head>\n            <body class style='height: 100%; width: 100%; margin: 0px'>\n                ${g?`<script nonce='${g}'> ${f}<\/script>`:`<script> ${f}<\/script>`}\n            </body>\n            </html>\n        `;this.iframe.srcdoc=S}};async function setupAmpAndBuildPipe(g,f,S){if(0===f){const f=new mt,S=new mt;return f.connect(S),S.connect(f),S.registerObserver(new gt(S,g)),f}if(1===f){const f=new ft(g);return await f.initializeAmpIframe(S),f}throw new Error(`Unsupported communication type ${f}`)}var St=class extends Ke{constructor(g){super(g),this.logger=g,this.resultsMap=new Map,this.on("log",((g,f)=>{this.logger[g](f)}))}async initialize(g,f,S,v){const C={config:S.config,playerConfig:S.playerConfig},_=S.playerConfig?.nonce||"";this.pipe=await setupAmpAndBuildPipe(g,S.config.loadType,_),this.pipe.registerObserver(this),await this.message("configure").send(f,C,v)}message(g){return{send:this.fromMessage(((...f)=>this.sendMessageImpl(g,...f)))}}dispose(){super.dispose(),this.pipe.sendMsg(this.buildMsg("dispose")),this.pipe.dispose()}processMessage(g){let f;switch(g.msgType){case"CommandResult":f=this.getDeferred(g.cmd.toString()),f&&(g.error?(f.reject(g.error),this.logger.warn(`remote command failed: ${String(g.cmd)}, ${g.error}`)):g.result?f.resolve(g.result):f.resolve(),this.processCommandResult(g),this.resultsMap.delete(g.cmd.toString()));break;case"PlayerNotification":{const f=this.event(g.name);f.raise.apply(f,g.args);break}case"Command":this.processCommand(g).catch((f=>this.logger.warn(`error while processing command: ${JSON.stringify(g)}: ${f}`)));break;default:this.logger.warn(`unexpected message received: ${JSON.stringify(g)}`)}}async processCommand(g){"getIceCandidates"===g.cmd.toString()?await this.message("getIceCandidates").send():this.logger.warn(`unsupported command received: ${JSON.stringify(g)}`)}processCommandResult(g){"getIceCandidates"===g.cmd.toString()?this.pipe.sendMsg({topic:"RequestIceCandidates",candidates:g.result}):this.logger.debug(`ignoring command result for: ${JSON.stringify(g)}`)}fromMessage(g){return g}sendMessageImpl(g,...f){return this.pipe.sendMsg(this.buildMsg(g,f)),this.waitForCompletion(g.toString())}buildMsg(g,f){return{msgType:"Command",cmd:g,args:f}}getDeferred(g){return this.resultsMap.get(g)}waitForCompletion(g){const f=this.getDeferred(g);f&&f.reject(new Error(`function ${g} is invoked again, before previous call is completed`));const S=new dt;return this.resultsMap.set(g,S),S.promise}},vt=class extends Ke{constructor(g,f){super(),this.player=g,this.logger=f,this.playerSubs=[],this.subscribeForPlayerEvents()}get isRendering(){return!!this.player&&this.player.isRendering()}get streamSize(){return this.player?this.player.getStreamSize():{width:0,height:0}}get rendererType(){return 0}get frameType(){return-1}seek(g){this.player.seek(g)}seekToLiveEdge(){this.player.seekToLiveEdge()}play(){this.player.play()}pause(){this.player.pause()}setVolume(g){this.player.setVolume(g)}selectVideoTrack(g){this.player.selectVideoTrack(g)}dispose(){this.stopPlayer(),super.dispose()}captions(){return this.player.getCaptionsControl()}getStats(){throw new Error("Method not implemented.")}setScalingMode(g,f){throw new Error("Method not implemented.")}captureFrame(g,f){throw new Error("Method not implemented.")}stopPlayer(){const g=this.player;this.player=null,g&&(this.logger.info("stopPlayer"),this.unsubscribeFromPlayerEvents(),g.stop())}subscribeForPlayerEvents(){this.playerSubs.push(this.player.on("fullscreenToggled",(g=>this.onFullScreenToggled(g)))),this.playerSubs.push(this.player.on("captionsToggled",((g,f,S)=>this.onCaptionsToggled(g,f,S)))),this.playerSubs.push(this.player.on("playbackTimeUpdated",(g=>this.onPlaybackTimeUpdated(g)))),this.playerSubs.push(this.player.on("videoTracksChanged",(g=>this.onVideoTracksChanged(g))))}unsubscribeFromPlayerEvents(){for(const g of this.playerSubs)g.dispose();this.playerSubs=[]}onFullScreenToggled(g){this.event("fullScreenToggled").raise(g)}onCaptionsToggled(g,f,S){this.logger.info(`Turned captions ${g?"ON":"OFF"} for culture [${f}] at player time [${S}]`),this.event("captionsToggled").raise(g,f,S)}onPlaybackTimeUpdated(g){this.event("playbackTimeUpdated").raise(g)}onVideoTracksChanged(g){this.event("videoTracksUpdated").raise(g)}},Ct=class{constructor(g,f){this.player=g,this.availableCultures=f,this.selectedCulture="",this.disposable=this.player.on("captionsToggled",((g,f,S)=>{this.selectedCulture=g?f:""}))}async addCues(g){await this.player.message("addCues").send(g)}async clearCues(){await this.player.message("clearCues").send()}async showCaptions(g){await this.player.message("showCaptions").send(g)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.disposable.dispose(),this.player=null}};function generateGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(g=>{const f=16*Math.random()|0;return("x"===g?f:3&f|8).toString(16)}))}function validateGuid(g){return new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(g)&&36===g.length}var yt=[2097152,2097552,2097556,2097557,2097564,2097652,2097654,2097655,2097656,2097752,3145728,4194305,4194306,4194307,4194308,4194309,5242880,5242881,5242882,5242884,5242885,5242886],Et=2097753,_t=class extends Ke{constructor(g,f,S){super(),this.logger=g,this.liveStreamStatistic=f,this.configProvider=S,this.playerState="Destroyed",this.retryCount=0,this.captionsTimestamp=0,this.isSwitchStreamingUrlOngoing=!1,this.streamingUrlSwitchCount=0,this.isPlaybackUnsupported=!1,this.noMediaTimeoutId=-1,this.lastPlaybackError=void 0,this.id=generateGuid(),this.logger.info(`AmpLiveStreamPlayer created: ID: ${this.id}`)}get playerId(){return this.id}async configure(g){if(!isStreamValid(g.stream)&&!isStreamValid(g.altStream))return void this.logger.error("Invalid Live Stream configuration provided: no valid primary or alternative stream");this.logger.info("Live Stream configuration provided"),this.liveStreamOptions=g;const f=isStreamValid(g.stream)?g.stream:g.altStream;if(this.playerInstance&&!this.isPlaybackUnsupported){try{await this.playerInstance.message("configure").send(g)}catch(g){const f=stringifyObject2(g);this.logger.error(`configure failed: ${f}`)}await this.handleStreamInfoUpdate(f)}else this.selectedStreamDetails=f}async loadPlayer(g){if(this.playerInstance)return this.logger.error("playerLoadFailed: cannot load a player while current one is still active"),{setupSucceeded:!1,playerSetupError:{errorType:"MultiplePlayerLoad",errorMessage:"cannot load a player while current one is still active"}};if(!this.liveStreamOptions||!this.selectedStreamDetails||!isStreamValid(this.selectedStreamDetails))return this.logger.error("playerLoadFailed: empty/invalid primary and alternate stream info configured"),{setupSucceeded:!1,playerSetupError:{errorType:"InvalidStream",errorMessage:"empty/invalid primary and alternate stream info configured"}};this.playerInstance=new St(this.logger.createChild("AmpPlayerWrapper")),this.playerInstance.on("stateChanged",((g,f)=>this.ampStateChanged(g,f))),this.playerInstance.on("captionsToggled",((g,f,S)=>this.captionsToggled(g,f,S))),this.playerInstance.on("statsUpdated",(g=>this.liveStreamStatistic.registerStatsUpdated(g)));const f=this.configProvider.config.ampSettings.noMediaTimeoutMs;let S;-1!==f&&-1===this.noMediaTimeoutId&&(this.noMediaTimeoutId=self.setTimeout((()=>this.callDropDueToMediaTimeout()),f)),await this.playerInstance.initialize(g,this.liveStreamOptions,this.configProvider,this.id),this.liveStreamStatistic.registerPlayerLoadAttempt(),this.loadSucceeded=!1,this.liveStreamStatistic.registerEventLoadAttempt("LoadScript"),this.srcLoadPromise||(this.srcLoadPromise=this.playerInstance.message("loadPlayerScript").send());try{S=await this.srcLoadPromise}catch(g){const f=stringifyObject2(g);return this.logger.error(`playerLoadFailed: player scripts load failed: ${f}`),this.liveStreamStatistic.registerEventLoadFailed("LoadScript",`Load Script failed: ${g}`),this.liveStreamStatistic.registerPlayerLoadFailed(`script load failed: ${S}`),this.srcLoadPromise=null,{setupSucceeded:!1,playerSetupError:{errorType:"PlayerScriptLoadFailed",errorMessage:f}}}this.liveStreamStatistic.registerEventLoadSucceeded("LoadScript"),await this.tryLoadSdnPlugin(),this.liveStreamStatistic.registerEventLoadAttempt("CreateAmp");try{await this.playerInstance.message("createAmp").send()}catch(g){const f=stringifyObject2(g);return this.logger.error(`playerLoadFailed: createAmp failed: ${f}`),this.liveStreamStatistic.registerEventLoadFailed("CreateAmp",`createAmp failed: ${g}`),this.liveStreamStatistic.registerPlayerLoadFailed(`create amp failed ${f}, script load: ${S}`),{setupSucceeded:!1,playerSetupError:{errorType:"PlayerInitializationFailed",errorMessage:f}}}this.liveStreamStatistic.registerEventLoadSucceeded("CreateAmp");try{return await this.setPlayerSource(this.selectedStreamDetails),this.loadSucceeded=!0,this.logger.info(`loadPlayer succeeded: ${this.loadSucceeded}`),this.liveStreamStatistic.registerPlayerLoadSucceeded(S),this.playerState="Initialized",{setupSucceeded:this.loadSucceeded}}catch(g){const f=stringifyObject2(g);return this.loadSucceeded=!1,this.logger.error(`loadPlayer succeeded: ${this.loadSucceeded}: setSource failed: ${f}`),this.liveStreamStatistic.registerPlayerLoadFailed(`setPlayerSource failed; script load: ${S}`),{setupSucceeded:this.loadSucceeded,playerSetupError:{errorType:"SetSourceFailed",errorMessage:f}}}}getRenderer(){return!this.renderer&&this.playerInstance&&(this.renderer=new vt(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}seek(g){throw new Error(`Method not implemented - cannot perform video seek operation with args: [timestamp: ${g}]`)}seekToLiveEdge(){throw new Error("Method not implemented - cannot perform video seek to live edge operation")}play(){throw new Error("Method not implemented - cannot perform video play operation")}pause(){throw new Error("Method not implemented - cannot perform video pause operation")}setVolume(g){throw new Error(`Method not implemented - cannot set video volume with args: [volume: ${g}]`)}selectVideoTrack(g){throw new Error(`Method not implemented - cannot select video track with args: [track: ${g}]`)}stop(){this.destroy("PlayerStopped")}getPlaybackState(){return this.playerState}getCaptionsTimestamp(){return this.captionsTimestamp}getCaptionsControl(){if(!this.captionsControl&&this.playerInstance){const g=this.liveStreamOptions.supportedSubtitleLanguages?this.liveStreamOptions.supportedSubtitleLanguages.map((g=>g.culture)):[];this.captionsControl=new Ct(this.playerInstance,g)}return this.captionsControl}getStreamSize(){const g=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return g?{width:g.mediaWidth,height:g.mediaHeight}:{width:0,height:0}}isRendering(){const g=this.getStreamSize();return g.width>0&&g.height>0}ampStateChanged(g,f){switch(g){case"error":return this.handlePlaybackError(f);case"canplaythrough":return this.onCanplaythrough();case"play":return this.onPlay();case"playing":return this.onPlaying();case"pause":return this.onPause();case"resume":return this.onResume();case"start":return this.onStart();case"ended":return this.onEnded();case"seeking":return this.onSeeking();case"seeked":return this.onSeeked(f);case"loadedmetadata":return this.onMetadataLoaded();case"waiting":return this.onWaiting();case"playbackbitratechanged":return this.onPlaybackBitrateChanged(f);case"downloadbitratechanged":return this.onDownloadBitrateChanged(f);case"fullscreenchange":return this.onFullscreenChange(f);case"potentialMediaFreeze":return this.onPotentialMediaFreeze();case"mute":return this.onMute();case"unmute":return this.onUnmute();case"volumechange":return this.onVolumeChange(f);case"loadstart":return this.onLoadStart();case"loadeddata":return this.onLoadedData();case"UserInitiatedSeek":return this.onUserInitiatedSeek(f);default:this.logger.warn(`Unknown amp event ${g}`)}}onUserInitiatedSeek(g){this.liveStreamStatistic.registerUserInitiatedSeek(g)}captionsToggled(g,f,S){this.event("captionsToggled").raise(g,f,S),this.liveStreamStatistic.registerCaptionToggle(g,f,S)}async tryLoadSdnPlugin(){if(this.sdnPluginLoadPromise)return void this.raiseSdnPluginSkippedEvent("SDN plugin already loaded");if(!this.liveStreamOptions.sdn)return void this.raiseSdnPluginSkippedEvent("No SDNs configured in liveStreamOptions");if(!this.configProvider.config.allowSdnPlugins)return void this.raiseSdnPluginSkippedEvent("Client configured to not allow SDN plugins");switch(this.liveStreamOptions.sdn.name){case"hive":case"kollective":case"ramp":case"peer5":break;default:return this.logger.warn(`unsupported SDN provider: ${this.liveStreamOptions.sdn.name}`),void this.liveStreamStatistic.registerSdnPluginLoad(this.liveStreamOptions.sdn.name,!1,`Unsupported SDN provider: ${this.liveStreamOptions.sdn.name}`)}let g;this.liveStreamStatistic.registerEventLoadAttempt("SdnPluginLoad");try{this.sdnPluginLoadPromise=this.playerInstance.message("tryLoadSdnPlugin").send(),await this.sdnPluginLoadPromise,this.liveStreamStatistic.registerEventLoadSucceeded("SdnPluginLoad",this.liveStreamOptions.sdn.name)}catch(f){g=stringifyObject2(f),this.sdnPluginLoadPromise=void 0,this.logger.error(`loadSdnPlugin failed: ${g}`),this.liveStreamStatistic.registerEventLoadFailed("SdnPluginLoad",g),this.event("sdnPluginLoadFailed").raise(g)}}raiseSdnPluginSkippedEvent(g){this.logger.warn(`skipping SDN plugin load: ${g}`),this.event("sdnPluginLoadSkipped").raise(g)}async setPlayerSource(g){if(!g)throw this.logger.error("setPlayerSource: streamDetails is undefined"),new Error("setPlayerSource: streamDetails is undefined");if(!this.playerInstance)throw this.logger.error("setPlayerSource: playerInstance is null"),new Error("playerInstance is null");this.logger.info(`setPlayerSource: AMP source set to: [${g.url}]`),this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;try{this.logger.info("setPlayerSource: src changed"),this.selectedStreamDetails=g,this.liveStreamStatistic.registerSetSourceAttempt(g.url),await this.playerInstance.message("setSource").send(g),this.liveStreamStatistic.registerSetSourceSucceeded()}catch(g){const f=stringifyObject2(g);throw this.logger.error(`setPlayerSource: failed with error [${f}]`),this.liveStreamStatistic.registerSetSourcedFailed(f),g}}async handleStreamInfoUpdate(g){this.loadSucceeded&&g.url!==this.selectedStreamDetails.url?await this.setPlayerSource(g):this.loadSucceeded&&this.playerInstance&&this.getCurrentTime()>0&&this.setPlaybackState("Start")}async switchStreamingUrl(g,f){if(this.streamingUrlSwitchCount>=this.configProvider.config.ampSettings.streamingUrlSwitchMaxCount||!(0,ct.includes)(this.configProvider.config.ampSettings.errorCodesEligibleForStreamingUrlSwitch,g)&&!f)return!1;const S=this.selectedStreamDetails.url===this.liveStreamOptions.stream?.url,v=S?this.liveStreamOptions.altStream:this.liveStreamOptions.stream;return isStreamValid(v)?(this.isSwitchStreamingUrlOngoing=!0,this.streamingUrlSwitchCount++,this.setPlayerSource(v).then((()=>!0)).catch((()=>!1))):(this.logger.error(`Stream to switch (${S?"alternative":"primary"}) is not valid`),!1)}destroy(g){this.srcLoadPromise=null,this.sdnPluginLoadPromise=null,this.renderer&&(this.renderer.dispose(),this.renderer=null),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null),this.playerInstance&&(this.liveStreamStatistic.registerPlayerDestroyed(g),this.playerInstance.dispose(),this.playerInstance=null,this.setPlaybackState("Destroyed"))}getCurrentTime(){const g=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return g&&g.currentPlayPosition||0}onCanplaythrough(){this.setPlaybackState("Ready")}onPlay(){(this.retryCount>0||this.lastKnownPlayTime)&&(this.logger.info(`Playing after retry count ${this.retryCount}, Setting current time to ${this.lastKnownPlayTime}`),this.playerInstance.message("setPlayTime").send(this.lastKnownPlayTime),this.retryCount=0,this.lastKnownPlayTime=void 0),this.setPlaybackState("Play")}onPlaying(){this.setPlaybackState("Playing")}onPause(){this.setPlaybackState("Paused")}onResume(){this.setPlaybackState("Resume")}onStart(){this.logger.info(`Playback started, retry count: ${this.retryCount}`),this.setPlaybackState("Start"),this.event("playbackStarted").raise(),self.clearTimeout(this.noMediaTimeoutId),this.isSwitchStreamingUrlOngoing&&(this.logger.info(`Playback started, switch count: ${this.streamingUrlSwitchCount}`),this.event("urlSwitched").raise(this.selectedStreamDetails===this.liveStreamOptions.altStream),this.isSwitchStreamingUrlOngoing=!1)}onEnded(){this.setPlaybackState("Ended")}onSeeking(){this.setPlaybackState("Seeking")}onSeeked(g){this.captionsTimestamp=g.captionsTimestamp,this.setPlaybackState("Seeked")}onMetadataLoaded(){this.setPlaybackState("LoadedMetadata")}onWaiting(){this.setPlaybackState("Buffering")}onLoadedData(){this.setPlaybackState("LoadedData")}onLoadStart(){this.setPlaybackState("LoadStart")}setPlaybackState(g){this.playerState=g,this.logger.debug(`playback state changed: ${g}`),this.liveStreamStatistic.registerPlaybackStateChanged(g),this.event("playbackStateChanged").raise()}onPlaybackBitrateChanged(g){this.liveStreamStatistic.registerPlaybackBitratechanged(g.bitrate)}onDownloadBitrateChanged(g){this.liveStreamStatistic.registerDownloadBitratechanged(g.bitrate)}onFullscreenChange(g){this.logger.debug(`fullscreenchange, isFullscreen=${g.isFullscreen}`),this.event("fullscreenToggled").raise(g.isFullscreen),this.liveStreamStatistic.registerFullScreenChange(g.isFullscreen)}onPotentialMediaFreeze(){this.logger.warn("Player detected a potential media freeze"),this.liveStreamStatistic.registerPotentialMediaFreeze()}onMute(){this.liveStreamStatistic.registerMute(!0)}onUnmute(){this.liveStreamStatistic.registerMute(!1)}onVolumeChange(g){this.liveStreamStatistic.registerVolumeChange(g.value)}stringifyPlayerError(g){return JSON.stringify(g,(function(g,f){return"errorCode"===g?f.toString(16):f}))}async handlePlaybackError(g){const f=4194307;this.playerState="Error",this.lastPlaybackError=g;const S=this.stringifyPlayerError(g);if(this.logger.info(`Playback error ${S}`),!g.errorCode&&null==g.fatal)return void this.logger.error("onError: error details are not available");if((g.errorCode&f)===f)return this.isPlaybackUnsupported=!0,this.raisePlaybackError("UnsupportedPlatform",S),void this.destroy("PlaybackError");this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;const v=g.errorCode,C=268435455&v;this.logger.error(`onError: errorCode: 0x${v.toString(16)}, errorCodeExcludingTech: 0x${C.toString(16)}, message: ${g.message}`),this.retryCount<this.configProvider.config.maxRetryCount&&(!1===g.fatal||-1!==(0,ct.indexOf)(yt,C))?setTimeout((async()=>{this.logger.info(`Retry loading stream because of error code: 0x${v.toString(16)}`),this.retryCount++,this.raisePlaybackError("PlaybackRetried",S),this.setPlayerSource(this.selectedStreamDetails)}),this.configProvider.config.ampSettings.sourceResetTimeoutInMs):await this.switchStreamingUrl(C,g.fatal)?this.configProvider.config.ampSettings.resetStreamingUrlSwitchCount&&(this.streamingUrlSwitchCount=0):(C===Et||g.message?.includes(Et.toString(16))?this.raisePlaybackError("NetworkError",S):this.raisePlaybackError("PlaybackError",S),this.destroy("PlaybackError"))}raisePlaybackError(g,f){this.liveStreamStatistic.registerPlaybackError(g,f),this.event("playbackError").raise(g,f)}callDropDueToMediaTimeout(){const g={currentTime:-1,errorCode:0,message:JSON.stringify({state:this.playerState,error:this.stringifyPlayerError(this.lastPlaybackError)}),fatal:!0},f=this.stringifyPlayerError(g);this.raisePlaybackError("MediaTimeout",f),this.destroy("MediaTimeout")}},Tt=__toESM2(re()),It=class extends Ke{constructor(g,f,S){super(),this.logger=g,this.telemetryLogger=S,this.playerLoaded=!1,this.playbackState="Destroyed",this.playerSubs=[],this.isFinalTelemetrySent=!1,this.captionsTimestamp=0,this.configProvider=f;const v=this.createHydraPlayerSettings();this.eventHandler=this.createEventHandler(),this.addPlayerEventSubscribers(),this.hydraPlayer=new Tt.HydraPlayer(v,this.eventHandler)}async configure(g){if(this.streamOptions=g,this.threadId=g.threadId,this.playerLoaded){const g=this.createHydraStreamOptions();await this.hydraPlayer.callPlayerApi("configureHydraPlayer",g)}}async loadPlayer(g){if(!await this.hydraPlayer.setup(g))return{setupSucceeded:!1,playerSetupError:{errorType:"HydraRuntimeLoadFailed",errorMessage:"Failed to create IFrame with Hydra runtime script"}};if(this.streamOptions){const g=this.createHydraStreamOptions();await this.hydraPlayer.callPlayerApi("configureHydraPlayer",g)}else this.logger.warn("No stream options configured before Hydra player loaded");const f=await this.hydraPlayer.callPlayerApi("loadHydraPlayer");return f.setupSucceeded&&(this.playerLoaded=!0,this.startTelemetryGathering()),this.getHydraPlayerSetupResult(f)}convertStreamDeliveryPipeline(g){switch(g){case"AMS":return Tt.HydraStreamDeliveryPipeline.AMS;case"MiddleLaneHttpLiveStreaming":return Tt.HydraStreamDeliveryPipeline.HLS;case"MiddleLaneUltraLowLatency":return Tt.HydraStreamDeliveryPipeline.Ums;default:throw new Error(`Unable to convert StreamDeliveryPipeline ${g} to HydraStreamDeliveryPipeline`)}}convertStreamingEventType(g){switch(g){case"TLE":return Tt.HydraStreamingEventType.TLE;case"Overflow":return Tt.HydraStreamingEventType.Overflow;case"TownHall_Basic":return Tt.HydraStreamingEventType.TownHallBasic;case"TownHall_Premium":return Tt.HydraStreamingEventType.TownHallPremium;case"TownHall":return Tt.HydraStreamingEventType.TownHall;default:throw new Error(`Unable to convert StreamingEventType ${g} to HydraStreamingEventType`)}}addPlayerEventSubscribers(){this.playerSubs.push(this.eventHandler.on("playbackStateChanged",(g=>{this.onPlaybackStateChanged(g)}))),this.playerSubs.push(this.eventHandler.on("playbackError",((g,f)=>{this.onPlaybackError(g,f)}))),this.playerSubs.push(this.eventHandler.on("playbackSeeked",(g=>{this.onPlaybackSeeked(g)}))),this.playerSubs.push(this.eventHandler.on("urlSwitched",(g=>{this.onUrlSwitched(g)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadSkipped",(g=>{this.onSdnPluginLoadSkipped(g)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadFailed",(g=>{this.onSdnPluginLoadFailed(g)}))),this.playerSubs.push(this.eventHandler.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.eventHandler.on("playbackTimeUpdated",(g=>{this.onPlaybackTimeUpdated(g)}))),this.playerSubs.push(this.eventHandler.on("videoTracksUpdated",(g=>{this.onVideoTracksUpdated(g)}))),this.playerSubs.push(this.eventHandler.on("statsUpdated",(g=>{this.onStatsUpdated(g)}))),this.playerSubs.push(this.eventHandler.on("log",((g,f)=>{this.onLog(g,f)}))),this.playerSubs.push(this.eventHandler.on("capabilitiesUpdated",(g=>{this.onCapabilitiesUpdated(g)})))}getTelemetryReport(){return this.hydraPlayer?.getFullTelemetryReport()}getSnapshotTelemetryReport(){return this.hydraPlayer?.getSnapshotTelemetryReport()}startTelemetryGathering(){let g,f;this.statsSub=window.setTimeout((async()=>{clearTimeout(this.statsSub),this.logger.debug(`initial telemetry report after ${this.configProvider.config.sendInitialTelemetryAfterMs} ms`),this.sendTelemetry(!1)}),this.configProvider.config.sendInitialTelemetryAfterMs),1===this.configProvider.playerConfig.playerType?(g=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,f=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs):(g=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,f=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs),g&&(this.diagSub=window.setInterval((async()=>{this.sendSnapshotTelemetry()}),f))}getHydraPlayerSetupResult(g){return{setupSucceeded:g.setupSucceeded,playerSetupError:g.playerSetupError?{errorType:this.convertHydraPlayerSetupError(g.playerSetupError.errorType),errorMessage:g.playerSetupError.errorMessage}:void 0}}convertHydraPlayerSetupError(g){switch(g){case Tt.HydraPlayerSetupErrorType.InvalidStream:return"InvalidStream";case Tt.HydraPlayerSetupErrorType.MultiplePlayerLoad:return"MultiplePlayerLoad";case Tt.HydraPlayerSetupErrorType.PlayerInitializationFailed:return"PlayerInitializationFailed";case Tt.HydraPlayerSetupErrorType.SetSourceFailed:return"SetSourceFailed";default:return}}getRenderer(){return!this.renderer&&this.hydraPlayer&&(this.renderer=new vt(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}onStatsUpdated(g){this.playerStats=g}getStats(){return this.playerStats}onLog(g,f){this.logger[g](f)}onPlaybackStateChanged(g){try{this.playbackState=this.convertHydraPlaybackState(g),this.event("playbackStateChanged").raise()}catch(g){this.logger.warn(`Not handling playback state changed event: ${stringifyObject2(g)}`)}}convertHydraPlaybackState(g){switch(g){case Tt.HydraPlayerPlaybackState.LoadStart:return"LoadStart";case Tt.HydraPlayerPlaybackState.LoadedData:return"LoadedData";case Tt.HydraPlayerPlaybackState.LoadedMetadata:return"LoadedMetadata";case Tt.HydraPlayerPlaybackState.Start:return"Start";case Tt.HydraPlayerPlaybackState.CanPlayThrough:return"Ready";case Tt.HydraPlayerPlaybackState.Play:return"Play";case Tt.HydraPlayerPlaybackState.Playing:return"Playing";case Tt.HydraPlayerPlaybackState.Pause:return"Paused";case Tt.HydraPlayerPlaybackState.Waiting:return"Buffering";case Tt.HydraPlayerPlaybackState.Seeking:return"Seeking";case Tt.HydraPlayerPlaybackState.Seeked:return"Seeked";case Tt.HydraPlayerPlaybackState.Ended:return"Ended";case Tt.HydraPlayerPlaybackState.Error:return"Error";case Tt.HydraPlayerPlaybackState.Destroyed:return"Destroyed";case Tt.HydraPlayerPlaybackState.Initialized:return"Initialized";case Tt.HydraPlayerPlaybackState.Stalled:return"Stalled";default:throw new Error(`Unable to convert HydraPlayerPlaybackState ${g} to PlaybackState`)}}onPlaybackError(g,f){try{const S=this.convertHydraPlaybackErrorType(g);this.event("playbackError").raise(S,f)}catch(g){this.logger.warn(`Not handling playback error event: ${stringifyObject2(g)}`)}}convertHydraPlaybackErrorType(g){switch(g){case Tt.HydraPlayerPlaybackErrorType.UnsupportedPlatform:return"UnsupportedPlatform";case Tt.HydraPlayerPlaybackErrorType.NetworkError:return"NetworkError";case Tt.HydraPlayerPlaybackErrorType.PlaybackRetried:return"PlaybackRetried";case Tt.HydraPlayerPlaybackErrorType.PlaybackError:return"PlaybackError";case Tt.HydraPlayerPlaybackErrorType.MediaTimeout:return"MediaTimeout";case Tt.HydraPlayerPlaybackErrorType.Unknown:return"Unknown";default:throw new Error(`Unable to convert HydraPlayerPlaybackErrorType ${g} to PlaybackErrorType`)}}seek(g){this.hydraPlayer.callPlayerApi("seekHydraPlayer",g)}seekToLiveEdge(){this.hydraPlayer.callPlayerApi("seekHydraPlayerToLiveEdge")}play(){this.hydraPlayer.callPlayerApi("playHydraPlayer")}pause(){this.hydraPlayer.callPlayerApi("pauseHydraPlayer")}setVolume(g){this.hydraPlayer.callPlayerApi("setHydraPlayerVolume",g)}selectVideoTrack(g){this.hydraPlayer.callPlayerApi("selectHydraPlayerVideoTrack",g)}getStreamSize(){return this.playerStats?{width:this.playerStats.mediaWidth,height:this.playerStats.mediaHeight}:{width:0,height:0}}isRendering(){const g=this.getStreamSize();return g.width>0&&g.height>0}disposePlayer(){this.hydraPlayer?.dispose()}releasePlayer(){this.hydraPlayer&&(this.hydraPlayer.release(),this.hydraPlayer=null)}stop(){this.clearPlayerEventSubscribers(),this.destroyPlayer()}destroyPlayer(){this.renderer&&(this.renderer.dispose(),this.renderer=null),this.statsSub&&(clearTimeout(this.statsSub),this.statsSub=null),this.diagSub&&(clearInterval(this.diagSub),this.diagSub=null),this.disposePlayer(),this.sendFinalTelemetry(),this.releasePlayer()}getPlaybackState(){return this.playbackState}getCaptionsTimestamp(){return this.captionsTimestamp}sendFinalTelemetry(){this.isFinalTelemetrySent||(this.isFinalTelemetrySent=!0,this.sendTelemetry(!0))}sendTelemetry(g){if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const f={...this.getTelemetryReport(),isFinal:g,threadId:this.threadId,tsCallingVersion:getTsCallingVersion2(),correlationId:this.streamOptions.correlationId};this.logger.debug("generated live stream report: ",f),this.telemetryLogger.sendEvent({eventName:"live_events",props:f})}else this.logger.info("telemetry not sent")}sendSnapshotTelemetry(){if(this.telemetryLogger){const g={...this.getSnapshotTelemetryReport(),isFinal:!1,threadId:this.threadId,tsCallingVersion:getTsCallingVersion2(),correlationId:this.streamOptions.correlationId};this.logger.debug("sending snapshot telemetry: ",g),this.telemetryLogger.sendEvent({eventName:"live_events",props:g})}else this.logger.error("snapshot telemetry not sent, telemetryLogger is not set")}clearPlayerEventSubscribers(){for(const g of this.playerSubs)g.dispose();this.playerSubs=[]}onPlaybackSeeked(g){this.captionsTimestamp=g}onUrlSwitched(g){this.event("urlSwitched").raise(g)}onSdnPluginLoadSkipped(g){this.event("sdnPluginLoadSkipped").raise(g)}onSdnPluginLoadFailed(g){this.event("sdnPluginLoadFailed").raise(g)}onPlaybackStarted(){this.event("playbackStarted").raise()}onPlaybackTimeUpdated(g){this.event("playbackTimeUpdated").raise(g)}onVideoTracksUpdated(g){this.event("videoTracksChanged").raise(g)}onCapabilitiesUpdated(g){this.event("capabilitiesUpdated").raise(g)}},bt=class extends Ke{constructor(){super()}playbackStateChanged(g){this.event("playbackStateChanged").raise(g)}playbackSeeked(g){this.event("playbackSeeked").raise(g)}log(g,f){this.event("log").raise(g,f)}playbackError(g,f){this.event("playbackError").raise(g,f)}urlSwitched(g){this.event("urlSwitched").raise(g)}sdnPluginLoadSkipped(g){this.event("sdnPluginLoadSkipped").raise(g)}sdnPluginLoadFailed(g){this.event("sdnPluginLoadFailed").raise(g)}statsUpdated(g){this.event("statsUpdated").raise(g)}playbackStarted(){this.event("playbackStarted").raise()}playbackTimeUpdated(g){this.event("playbackTimeUpdated").raise(g)}videoTracksUpdated(g){this.event("videoTracksUpdated").raise(g)}capabilitiesUpdated(g){this.event("capabilitiesUpdated").raise(g)}},At=__toESM2(re());function GetHlsStreamPlaybackCoordinatesFromStream(g){if(g.playbackCoordinates)return g.playbackCoordinates;if(!g.url&&!g.hlsUrls)return[];const f=[];return(g.hlsUrls?g.hlsUrls:[g.url]).forEach((S=>{f.push({url:S,sdnContext:g.sdnContext})})),f}function GetUmsStreamPlaybackCoordinatesFromStream(g){return g.url?[{url:g.url,sdnContext:g.sdnContext}]:[]}var Pt=["https://res-4.public.onecdn.static.microsoft/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js","https://res.cdn.office.net/s01-ml-player/legacy/hls/hydra_player_hls_bundle_4.24351.2.js"],Rt=class extends It{createEventHandler(){return new wt}createHydraPlayerSettings(){return{playerType:At.HydraPlayerType.Hls,hydraRuntimeFetchTimeout:this.configProvider.config.hydraRuntimeFetchTimeout,capturePlayerLogs:this.configProvider.config.capturePlayerLogs,allowSdnPlugins:this.configProvider.config.allowSdnPlugins,debugLogging:this.configProvider.config.debug??!1,muteVideo:this.configProvider.playerConfig?.muteVideo??!1,videoLang:this.configProvider.playerConfig?.lang,videoElementStyles:this.configProvider.playerConfig?.styles,maxPlayerDiagnosticsCount:this.configProvider.config.maxPlayerDiagnosticsCount,maxPlayerMemoryTraceLogCount:this.configProvider.config.maxPlayerMemoryTraceLogCount,maxPlayerPlaybackEventCount:this.configProvider.config.maxPlayerPlaybackEventCount,maxPlayerExperimentalEvents:this.configProvider.config.hlsSettings.maxPlayerExperimentalEvents,maxRetryCount:this.configProvider.config.maxRetryCount,playerTelemetryTickMs:this.configProvider.config.playerTelemetryTickMs,removeEmptyDefaultTextTrack:this.configProvider.config.removeEmptyDefaultTextTrack,maxRetryCountForLoadingResources:this.configProvider.config.maxRetryCountForLoadingResources,maxVideoTrackHistoryLogCount:this.configProvider.config.maxVideoTrackHistoryLogCount,maxStreamConnectionResultsLogCount:this.configProvider.config.hlsSettings.maxStreamConnectionResultsLogCount,maxAbsoluteTimeOffsetEstimationResultsLogCount:this.configProvider.config.hlsSettings.maxAbsoluteTimeOffsetEstimationResultsLogCount,skipNonce:this.configProvider.config.hlsSettings.skipNonce,configIds:this.configProvider.configIds,estimateAbsoluteTime:this.configProvider.config.hlsSettings.estimateAbsoluteTime,playlistInitialSequenceNumber:this.configProvider.config.hlsSettings.playlistInitialSequenceNumber,timeoutForSwitchingUrl:this.configProvider.config.hlsSettings.timeoutForSwitchingUrl,hlsConfig:this.configProvider.config.hlsSettings.hlsConfig,logHlsJsEvents:this.configProvider.config.hlsSettings.logHlsJsEvents,logHlsJsEventsEveryMs:this.configProvider.config.hlsSettings.logHlsJsEventsEveryMs,switchingPolicy:this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.switchingPolicy,enableUuidTrace:this.configProvider.config.hlsSettings.enableUuidTrace,thaScript:this.configProvider.config.hlsSettings.thaScript,enableOffsetComputeBasedOfStreamTime:this.configProvider.config.hlsSettings.enableOffsetComputeBasedOfStreamTime,stopCrash:this.configProvider.config.stopCrash,stopTerminating:this.configProvider.config.hlsSettings.stopTerminating,stallDetectionPolicy:this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.stallDetectionPolicy,playerRuntimeJsUrls:this.configProvider.config.hydraPlayerHlsSettings?.runtimeUrls??this.configProvider.playerConfig?.hydraPlayerWebSdkUrls??Pt,disableSandbox:this.configProvider.config.hlsSettings.disableSandbox,ecsSettings:this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings,nonce:this.configProvider.playerConfig?.nonce??""}}createHydraStreamOptions(){let g=At.HydraStreamingEventType.TLE;g=this.streamOptions.streamingEventType?this.convertStreamingEventType(this.streamOptions.streamingEventType):this.streamOptions.overflow?At.HydraStreamingEventType.Overflow:At.HydraStreamingEventType.TLE;const f={stream:{playbackCoordinates:GetHlsStreamPlaybackCoordinatesFromStream(this.streamOptions.stream),urls:this.streamOptions.stream.hlsUrls?this.streamOptions.stream.hlsUrls:[this.streamOptions.stream.url],keyAuthorizationToken:this.streamOptions.stream.keyAuthorizationToken,keyDeliveryUrl:this.streamOptions.stream.keyDeliveryUrl,sdnContext:this.streamOptions.stream.sdnContext,streamDeliveryPipeline:this.streamOptions.stream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(this.streamOptions.stream.streamDeliveryPipeline):void 0},altStream:this.streamOptions.altStream?{playbackCoordinates:GetHlsStreamPlaybackCoordinatesFromStream(this.streamOptions.altStream),urls:this.streamOptions.altStream.hlsUrls?this.streamOptions.altStream.hlsUrls:[this.streamOptions.altStream.url],keyAuthorizationToken:this.streamOptions.altStream.keyAuthorizationToken,keyDeliveryUrl:this.streamOptions.altStream.keyDeliveryUrl,sdnContext:this.streamOptions.altStream.sdnContext,streamDeliveryPipeline:this.streamOptions.altStream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(this.streamOptions.altStream.streamDeliveryPipeline):void 0}:void 0,supportedSubtitleLanguages:this.streamOptions.supportedSubtitleLanguages,streamingEventType:g,allowPlayerControls:this.streamOptions.allowPlayerControls,sdn:this.streamOptions.sdn?{name:this.streamOptions.sdn.name,url:this.streamOptions.sdn.url,plugin:this.streamOptions.sdn.plugin}:void 0,thaContext:this.streamOptions.thaContext?{eventId:this.streamOptions.thaContext.eventId,organizer:{userId:this.streamOptions.thaContext.organizer?.userId,tenantId:this.streamOptions.thaContext.organizer?.tenantId},attendee:{userId:this.streamOptions.thaContext.attendee?.userId,tenantId:this.streamOptions.thaContext.attendee?.tenantId},coOrganizers:this.streamOptions.thaContext.coOrganizers}:void 0};return this.streamOptions.eventId&&(f.eventId=this.streamOptions.eventId),this.streamOptions.templateId&&(f.templateId=this.streamOptions.templateId),this.streamOptions.meetingMetadata&&(f.meetingMetadata=this.streamOptions.meetingMetadata),f}onCaptionsToggled(g,f,S){this.captionsControl&&this.captionsControl.toggleCaptions(g,f),this.event("captionsToggled").raise(g,f,S)}getCaptionsControl(){if(!this.captionsControl&&this.hydraPlayer){const g=this.streamOptions?.supportedSubtitleLanguages?this.streamOptions.supportedSubtitleLanguages.map((g=>g.culture)):["en","es"];this.captionsControl=new Mt(this.hydraPlayer,g)}return this.captionsControl}addPlayerEventSubscribers(){super.addPlayerEventSubscribers(),this.playerSubs.push(this.eventHandler.on("captionsToggled",((g,f,S)=>{this.onCaptionsToggled(g,f,S)})))}releasePlayer(){super.releasePlayer(),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null)}},Mt=class{constructor(g,f){this.hydraPlayer=g,this.availableCultures=f,this.selectedCulture=""}async addCues(g){const f=this.convertCues(g);await this.hydraPlayer.callPlayerApi("addHydraPlayerCues",f)}convertCues(g){const f=[];return g.forEach((g=>{f.push({start:g.start,end:g.end,text:g.text})})),f}async clearCues(){await this.hydraPlayer.callPlayerApi("clearHydraPlayerCues")}async showCaptions(g){await this.hydraPlayer.callPlayerApi("showHydraPlayerCaptions",g)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.hydraPlayer=null}toggleCaptions(g,f){this.selectedCulture=g?f:""}},wt=class extends bt{constructor(){super()}captionsToggled(g,f,S){this.event("captionsToggled").raise(g,f,S)}},Ot=__toESM2(re()),Dt=class extends It{get tracks(){return this.trackInfo}createEventHandler(){return new kt}createHydraPlayerSettings(){return{playerType:Ot.HydraPlayerType.Ums,hydraRuntimeFetchTimeout:this.configProvider.config.hydraRuntimeFetchTimeout,allowSdnPlugins:this.configProvider.config.allowSdnPlugins,debugLogging:this.configProvider.config.debug??!1,muteVideo:this.configProvider.playerConfig?.muteVideo??!1,videoLang:this.configProvider.playerConfig?.lang,videoElementStyles:this.configProvider.playerConfig?.styles,maxPlayerDiagnosticsCount:this.configProvider.config.maxPlayerDiagnosticsCount,maxPlayerMemoryTraceLogCount:this.configProvider.config.maxPlayerMemoryTraceLogCount,maxPlayerPlaybackEventCount:this.configProvider.config.maxPlayerPlaybackEventCount,maxPlayerExperimentalEvents:this.configProvider.config.umsSettings.maxPlayerExperimentalEvents,maxRetryCount:this.configProvider.config.maxRetryCount,playerTelemetryTickMs:this.configProvider.config.playerTelemetryTickMs,maxRetryCountForLoadingResources:this.configProvider.config.maxRetryCountForLoadingResources,maxVideoTrackHistoryLogCount:this.configProvider.config.maxVideoTrackHistoryLogCount,maxStreamConnectionResultsLogCount:this.configProvider.config.umsSettings.maxStreamConnectionResultsLogCount,configIds:this.configProvider.configIds,timeoutForSwitchingUrl:this.configProvider.config.umsSettings.timeoutForSwitchingUrl,latencyCompensationThreshold:this.configProvider.config.umsSettings.latencyCompensationThreshold,switchingPolicy:this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.switchingPolicy,enableUuidTrace:this.configProvider.config.umsSettings.enableUuidTrace,thaScript:this.configProvider.config.umsSettings.thaScript,stopCrash:this.configProvider.config.stopCrash,stopTerminating:this.configProvider.config.umsSettings.stopTerminating,stallDetectionPolicy:this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.stallDetectionPolicy,playerRuntimeJsUrls:this.configProvider.config.hydraPlayerUmsSettings?.runtimeUrls??this.configProvider.playerConfig?.hydraPlayerWebSdkUrls,disableSandbox:this.configProvider.config.umsSettings.disableSandbox,ecsSettings:this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings,nonce:this.configProvider.playerConfig?.nonce??"",useLiveUmsCaptions:this.configProvider.config.umsSettings?.useLiveUmsCaptions??!1}}createHydraStreamOptions(){let g=Ot.HydraStreamingEventType.TLE;g=this.streamOptions.streamingEventType?this.convertStreamingEventType(this.streamOptions.streamingEventType):this.streamOptions.overflow?Ot.HydraStreamingEventType.Overflow:Ot.HydraStreamingEventType.TLE;const f={stream:{playbackCoordinates:GetUmsStreamPlaybackCoordinatesFromStream(this.streamOptions.stream),urls:[this.streamOptions.stream.url],decryptionKey:this.streamOptions.stream.decryptionKey,sdnContext:this.streamOptions.stream.sdnContext,streamDeliveryPipeline:this.streamOptions.stream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(this.streamOptions.stream.streamDeliveryPipeline):void 0},altStream:this.streamOptions.altStream?{playbackCoordinates:GetUmsStreamPlaybackCoordinatesFromStream(this.streamOptions.altStream),urls:[this.streamOptions.altStream.url],decryptionKey:this.streamOptions.altStream.decryptionKey,sdnContext:this.streamOptions.altStream.sdnContext,streamDeliveryPipeline:this.streamOptions.altStream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(this.streamOptions.altStream.streamDeliveryPipeline):void 0}:void 0,streamingEventType:g,allowPlayerControls:this.streamOptions.allowPlayerControls,sdn:this.streamOptions.sdn?{name:this.streamOptions.sdn.name,url:this.streamOptions.sdn.url,plugin:this.streamOptions.sdn.plugin}:void 0,thaContext:this.streamOptions.thaContext?{eventId:this.streamOptions.thaContext.eventId,organizer:{userId:this.streamOptions.thaContext.organizer?.userId,tenantId:this.streamOptions.thaContext.organizer?.tenantId},attendee:{userId:this.streamOptions.thaContext.attendee?.userId,tenantId:this.streamOptions.thaContext.attendee?.tenantId},coOrganizers:this.streamOptions.thaContext.coOrganizers}:void 0};return this.streamOptions.eventId&&(f.eventId=this.streamOptions.eventId),this.streamOptions.templateId&&(f.templateId=this.streamOptions.templateId),this.streamOptions.meetingMetadata&&(f.meetingMetadata=this.streamOptions.meetingMetadata),f}addPlayerEventSubscribers(){super.addPlayerEventSubscribers(),this.playerSubs.push(this.eventHandler.on("trackListUpdated",(g=>{this.onTrackListUpdated(g)}))),this.playerSubs.push(this.eventHandler.on("trackSelected",(g=>{this.onTrackSelected(g)})))}onTrackListUpdated(g){this.trackInfo=g;const f=stringifyObject2(g);this.logger.info(`[onTrackListUpdated]: Track list updated to: ${f}`)}onTrackSelected(g){const f=stringifyObject2(g);this.logger.info(`[onTrackSelected]: Track selected: ${f}`)}getCaptionsControl(){return!this.captionsControl&&this.hydraPlayer&&(this.captionsControl=new Nt(this.hydraPlayer,this.logger.createChild("CaptionsControl"))),this.captionsControl}releasePlayer(){super.releasePlayer(),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null)}},Nt=class{constructor(g,f){this.hydraPlayer=g,this.logger=f}async addCues(g){this.logger.warn("[addCues]: not implemented for UMS player")}async clearCues(){this.logger.warn("[clearCues]: not implemented for UMS player")}async showCaptions(g){await this.hydraPlayer.callPlayerApi("showHydraPlayerCaptions",g)}getSelectedCulture(){return this.logger.warn("[getSelectedCulture]: not implemented for UMS player"),""}getAvailableCultures(){return this.logger.warn("[getAvailableCultures]: not implemented for UMS player"),[]}dispose(){this.hydraPlayer=null}async selectTextTrack(g){await this.hydraPlayer.callPlayerApi("selectHydraPlayerTextTrack",g)}},kt=class extends bt{constructor(){super()}trackListUpdated(g){this.event("trackListUpdated").raise(g)}trackSelected(g){this.event("trackSelected").raise(g)}},Lt=class extends Ke{constructor(g,f,S){super(),this.configProvider=g,this.logger=f,this.getTelemetryLogger=S,this.isAvailable=!0,this._isStreaming=!1,this.playerSubs=[],this.isFinalTelemetrySent=!1,this.telemetryLogger=this.getTelemetryLogger(),1===this.configProvider.playerConfig.playerType?this.player=new Rt(this.logger.createChild("HlsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):2===this.configProvider.playerConfig.playerType?this.player=new Dt(this.logger.createChild("UmsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):(this.initializeAmpTelemetry(),this.player=new _t(this.logger.createChild("AmpLiveStreamPlayer"),this.liveStreamStatistic,this.configProvider)),this.subscribeForPlayerEvents()}get isStreaming(){return this._isStreaming}isActive(){return this.isAvailable&&this.isStreaming}async start(g,f){await this.setOptions(f),this.isFinalTelemetrySent=!1;const S=await this.player.loadPlayer(g);if(!S.setupSucceeded){this.player.stop(),this.logger.error("playerLoadFailed");const g=JSON.stringify(S.playerSetupError);throw this.sendFinalTelemetry(g),new Error(g)}return this._isStreaming=!0,this.liveStreamStatistic&&(this.statsSub=window.setTimeout((()=>{clearTimeout(this.statsSub),this.logger.debug(`initial telemetry report after ${this.configProvider.config.sendInitialTelemetryAfterMs} ms`),this.sendTelemetry(!1)}),this.configProvider.config.sendInitialTelemetryAfterMs),this.configProvider.config.sendSnapshotTelemetry&&(this.diagSub=window.setInterval((()=>{this.sendSnapshotTelemetry()}),this.configProvider.config.sendSnapshotTelemetryEveryMs))),this.player.getRenderer()}initializeAmpTelemetry(){const g={perceivedBandwidth:[],videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],currentMediaTime:[],statsInterval:[]};this.liveStreamStatistic=new lt(this.configProvider.config,this.logger.createChild("LiveStreamStatistic"),g)}async stop(){}async setOptions(g){return void 0!==g.overflow&&(g.streamingEventType||(g.streamingEventType=g.overflow?"Overflow":"TLE"),delete g.overflow),this.options=g,this.player.configure(g)}getStats(){return this.liveStreamStatistic?this.liveStreamStatistic.getPlayerDiagnosticSnapshot():this.player?.getStats?.()}dispose(){this.unsubscribeFromPlayerEvents(),this.player.stop(),this.statsSub&&(clearTimeout(this.statsSub),this.statsSub=null),this.diagSub&&(clearInterval(this.diagSub),this.diagSub=null),this.logger.debug("stopping live event"),this.sendFinalTelemetry("graceful disposed"),super.dispose()}sendFinalTelemetry(g){this.isFinalTelemetrySent||(this.isFinalTelemetrySent=!0,this.sendTelemetry(!0,g))}sendTelemetry(g,f){if(this.liveStreamStatistic)if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const S={configIds:this.configProvider.configIds,playerId:this.player.playerId,correlationId:this.options?.correlationId,eTag:this.configProvider.etag,isFinal:g,threadId:this.options?.threadId,disableFullscreenButton:this.configProvider.playerConfig.disableFullscreenButton,callendReason:f},v=this.liveStreamStatistic?.getReport(S);this.logger.debug("generated live stream report",v),this.telemetryLogger.sendEvent({eventName:"live_events",props:v})}else this.logger.info("telemetry not sent");else this.logger.info("telemetry not tracked in ILiveStream object")}sendSnapshotTelemetry(){if(this.liveStreamStatistic)if(this.telemetryLogger){const g=this.liveStreamStatistic.getSnapshotReport({configIds:this.configProvider.configIds,playerId:this.player.playerId,correlationId:this.options?.correlationId,eTag:this.configProvider.etag,isFinal:!1,threadId:this.options?.threadId,disableFullscreenButton:this.configProvider.playerConfig.disableFullscreenButton});this.logger.debug("sending snapshot telemetry: ",g),this.telemetryLogger.sendEvent({eventName:"live_events",props:g})}else this.logger.error("snapshot telemetry not sent, telemetryLogger is not set");else this.logger.info("telemetry not tracked in ILiveStream object")}subscribeForPlayerEvents(){this.playerSubs.push(this.player.on("playbackStateChanged",(()=>{this.onPlaybackStateChanged()}))),this.playerSubs.push(this.player.on("playbackError",((g,f)=>{this.onPlaybackError(g,f)}))),this.playerSubs.push(this.player.on("urlSwitched",(g=>{this.onUrlSwitched(g)}))),this.playerSubs.push(this.player.on("sdnPluginLoadSkipped",(g=>{this.onSdnPluginLoadSkipped(g)}))),this.playerSubs.push(this.player.on("sdnPluginLoadFailed",(g=>{this.onSdnPluginLoadFailed(g)}))),this.playerSubs.push(this.player.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.player.on("capabilitiesUpdated",(g=>this.onCapabilitiesUpdated(g))))}unsubscribeFromPlayerEvents(){for(const g of this.playerSubs)g.dispose();this.playerSubs=[]}onPlaybackStarted(){this.event("playbackStarted").raise()}onPlaybackStateChanged(){const g=this.player.getPlaybackState();switch(g){case"Start":this.event("playbackStarted").raise();break;case"Ended":this.event("playbackNotLive").raise(),this.sendFinalTelemetry("playback ended");break;case"Seeked":this.event("playbackSeeked").raise(this.player.getCaptionsTimestamp());break;default:this.logger.debug(`playbackStateChanged: ${g}`)}this.event("playbackStateChanged").raise(this.player.getPlaybackState())}onPlaybackError(g,f){this.event("error").raise(g,f)}onUrlSwitched(g){this.event("urlSwitched").raise(g)}onSdnPluginLoadSkipped(g){this.event("sdnPluginLoadSkipped").raise(g)}onSdnPluginLoadFailed(g){this.event("sdnPluginLoadFailed").raise(g)}onCapabilitiesUpdated(g){this.event("capabilitiesUpdated").raise(g)}},Ft=class{constructor(g,f,S){this.ecsConfig=g,this.logger=f,this.getTelemetryLogger=S}configure(g){this.configuration=g}async initialize(){const g="MDN_MIDDLELANE_TEAMS",f="liveStream",S=this.ecsConfig.getString(g,f);let v={};try{v=JSON.parse(S)}catch(S){this.logger.warn(`failed to parse ECS configuration for ${g}/${f}`)}const C=this.ecsConfig.getString("ConfigIDs",g);this._configProvider=new rt(v,this.configuration,C,this.logger.createChild("LiveStreamConfigProvider"))}createLiveStream(){return new Lt(this._configProvider,this.logger.createChild("LiveStream"),this.getTelemetryLogger)}dispose(){}},xt=class extends Ke{constructor(){super(...arguments),this.isAudioOutputSelectionSupported=!1}createAudioPlayer(){return null}createAudioRenderer(){return null}getRawDeviceMediaStream(g){return null}askDevicePermission(){return Promise.resolve({audio:!1,video:!1})}getPermissionState(g){return"granted"}enumerateDevicesAsync(){return Promise.resolve([])}getPreferredCamera(){return null}selectDevices(){}getSelectedDevices(){return{}}createPreview(){return Promise.resolve(new Ut)}createPreviewRenderer(){return Promise.resolve(new Ut)}createScreenSharingPreviewRenderer(){return Promise.resolve(new Ut)}getDeviceNameAsync(){return Promise.resolve("")}setDeviceEffectsAsync(){return Promise.resolve()}getDeviceEffectsCapabilityAsync(){return Promise.resolve(0)}setBackgroundImageAsync(){return Promise.resolve()}getImagePropertyAsync(){return Promise.resolve({width:0,height:0,uri:" "})}getMicrophoneGeometryArrayInfoAsync(g){return Promise.resolve({})}transformImageAsync(){return Promise.resolve(!1)}sendMessageDeviceVideoEffectsAsync(){return Promise.resolve({code:0})}sendMessageDeviceVideoExtensibilityAsync(){return Promise.resolve({code:0,type:"Error",response:{details:"The API has not been implemented."}})}setVideoCaptureConfigAsync(){return Promise.resolve()}captureVideoFrameWithoutEffectsAsync(){return Promise.resolve(new ImageData(0,0))}enableSignLanguageDetectionAsync(g,f){return Promise.resolve()}downloadAiModel(g,f){return Promise.resolve("")}setAudioProcessingFlags(g){}getSpeakerVolume(){return Promise.resolve(0)}getSpeakerSystemVolume(){return Promise.resolve(0)}setSpeakerVolume(g){return Promise.resolve()}setSpeakerSystemVolume(g){return Promise.resolve()}unmuteMicrophone(){return Promise.resolve()}unmuteSpeaker(){return Promise.resolve()}getNrgLevelsForDeviceTuner(g){return Promise.resolve(0)}getNrgLevelPollerForDeviceTuner(g){return Promise.resolve(new Bt)}setAudioEffectsAsync(){return Promise.resolve()}getAudioFeatureCapability(g){return Promise.resolve(0)}getMicrophoneVolume(){return Promise.resolve(0)}setMicrophoneVolume(g){return Promise.resolve()}setDeviceTelemetryData(g,f,S,v=0){return Promise.resolve()}getSpeakerDeviceDomIdAsync(g,f){return Promise.reject()}mapBrowserDevices(g,f){return Promise.reject()}getSourceFormats(g){return Promise.resolve([])}enableShellSharing(){return Promise.resolve()}disableShellSharing(){return Promise.resolve()}enableParticipantCameras(){return Promise.resolve()}registerDerivedSource(g,f){return Promise.resolve()}unregisterDerivedSource(g){return Promise.resolve()}startAudioLoopbackDevice(g){return Promise.resolve()}async dispose(g){return Promise.resolve()}},Ut=class extends Ke{constructor(){super(...arguments),this.isRendering=!1,this.streamSize={width:0,height:0},this.rendererType=-1,this.frameType=-1}captureFrame(){return Promise.resolve(new Vt)}getStats(){return Promise.resolve({framesDropped:0,framesTotal:0})}setScalingMode(){return Promise.resolve()}cameraAutoControl(g){return Promise.resolve(!1)}getCameraManualControlStates(g){return Promise.resolve([])}setCameraManualControlStates(g){return Promise.resolve([])}enumerateCameraManualControls(){return Promise.resolve([])}isCameraAdvancedControlCapable(){return Promise.resolve(!1)}dispose(){}},Vt=class extends Ke{getSize(){return{width:0,height:0}}isMirrored(){return!1}},Bt=class{getInputLevel(){return 0}getInputLevelNormalized(g,f){return 0}dispose(){}},Ht=Ke,$t="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",jt="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",Gt="http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00",qt={MEDIA_STATE:{send:"sendonly",receive:"recvonly",sendReceive:"sendrecv",inactive:"inactive"},MEDIA_DIRECTION:{SEND:"send",RECV:"recv"},MEDIA_DEVICE_KIND:{audioInput:"audioinput",audioOutput:"audiooutput",videoInput:"videoinput",compositeAudio:"compositeAudio",virtualDevice:"virtualDevice"},MEDIA_DEVICE:{camera:"camera",microphone:"microphone",speaker:"speaker",compositeAudio:"compositeAudio",defaultId:"default",communicationsId:"communications",defaultDeviceLabel:"Default",audioIngestDevice:"audioIngestDevice",virtualDevice:"virtualDevice"},MEDIA_ERROR:{constraintNotSatisfiedError:"ConstraintNotSatisfiedError",iceConnectionError:"iceConnectionError",srtpError:"srtpError",permissionDeniedError:"permissionDeniedError",internalError:"internalError",sourceUnavailableError:"SourceUnavailableError",devicesNotFoundError:"DevicesNotFoundError",noDeviceSelected:"noDeviceSelected",noNetworkError:"noNetworkError",incompatibleOffer:"IncompatibleOffer",mediaStreamRequestError:"MediaStreamRequestError",extensionNotFoundError:"ExtensionNotFoundError",sharingCancelledError:"SharingCancelledError",permissionDeniedBySystemError:"PermissionsDeniedBySystem",chromeRuntimeNotDefinedError:"ChromeRuntimeNotDefinedError",mediaStreamRequestTimedOut:"MediaStreamRequestTimedout",unsupportedStream:"UnsupportedStream",webGlRendererError:"WebGlRendererError",audioPlaybackError:"audioPlaybackError",unexpectedClose:"unexpectedClose",incompatibleOriginator:"incompatibleOriginator"},HISTOGRAM_BATCH:{seconds1to3:2,seconds3to5:4,seconds5to8:7,seconds8to15:14,seconds15to60:59,seconds60toMax:1e6},RENEGOTIATION_ERROR:{local:"local",glare:"glare",signaling:"signaling",media:"media",escalation:"escalation"},MSI:{unsubscribe:-1,subscribeAny:-2},MEDIA_LABEL:{audio:"main-audio",video:"main-video",sharing:"applicationsharing-video",data:"data"},MEDIA_TYPE:{audio:"audio",video:"video",sharing:"sharing",data:"x-data",dataChannel:"application"},MODALITY:{audio:"audio",video:"video",sharing:"sharing",data:"data"},TRACK_KIND:{audio:"audio",video:"video"},ICE_TRANSPORT_POLICY:{all:"all",relay:"relay"},RENDERER_TYPE:{video:"video",sharing:"sharing"},CONTENT_TYPE:{SDP:"application/sdp",SDP_NGC:"application/sdp-ngc-1.0"},ALLOWED_CONTENT_TYPES:{SDP_ONLY:["application/sdp"],SDP_NGC:["application/sdp","application/sdp-ngc-0.5","application/sdp-ngc-1.0"]},STREAMING_STATE:{created:"created",started:"started",active:"active",inactive:"inactive",stopped:"stopped",removed:"removed",failed:"failed"},TIME_INTERVAL:{SEC_1:1},DISPLAY_SOURCE_ID:"display",EMPTY_DEVICE_ID:"0",SYSTEM_AUDIO_SOURCE_ID:"system",MULTIPLE_RECV_STREAMS:"multipleVideoStreams",PROFILES:{udpTlsRtpSavpf:"UDP/TLS/RTP/SAVPF",rtpSavpf:"RTP/SAVPF",rtpSavp:"RTP/SAVP",udpDtlsSctp:"UDP/DTLS/SCTP"},REPORTING_PROFILE:{RT_PROFILE:"REAL_TIME",BE_PROFILE:"BEST_EFFORT",NRT_PROFILE:"NEAR_REAL_TIME"},PAYLOAD_TYPE:{DATA_CHANNEL:"webrtc-datachannel",X_DATA:"127 126",MSRTC_RED:97,MSRTC_CNFB:120},VIDEO_CAPABILITIES:{MAX_FS_PATH:"max-fs",MAX_MBPS_PATH:"max-mbps",MAX_FPS_PATH:"max-fps",MAX_BR_PATH:"max-br",SSRC_PATH:"ssrc",RID_PATH:"rid",KEYFRAME_PATH:"KeyFrame",MAX_WIDTH:"max-width",MAX_HEIGHT:"max-height",MAX_STREAMS:"max-streams",MAX_LAYERS:"max-layers",PRIORITY_LAYOUT_MIN_MBPR:"priority-layout-min-mbpr",PRIORITY_LAYOUT_MIN_BITRATE:"priority-layout-min-bitrate",VLA_DEBUG:"vla-debug",LADDER_TYPE:"ladder-type"},TRANSPORT_CC:{EXT_URI:$t,MSSDP_ENCODED_URI:$t.replace(/\//g,"\\"),ATTRIBUTE:"transport-cc"},ABS_SEND_TIME:{EXT_URI:jt,MSSDP_ENCODED_URI:jt.replace(/\//g,"\\")},VLA:{EXT_URI:Gt,EXT_URI_NON_ADV:Gt+"-non-advertised",DEFAULT_VALUE:10},MACROBLOCK_SIZE:16,MAX_FS_1080P:8160,MEDIA_EVENT_FIELDS:{Extensions:["IceConnectionState","IceConnectionStatePrevious","SignalingState","SignalingStatePrevious"],metrics:["ReconnectInProgress","IceConnectedStateTime","ErrorType","ErrorDetail","InitialNegotiationType","InitialNegotiationCompleted","TerminationReason_subCode","TerminationReason_code"]},RES_TABLE:{SEND:[{w:320,h:180,fps:15,minBr:2e4,maxBr:175e3},{w:416,h:234,fps:15,minBr:125e3,maxBr:5e5},{w:640,h:360,fps:30,minBr:4e5,maxBr:575e3},{w:960,h:540,fps:30,minBr:5e5,maxBr:1125e3},{w:1280,h:720,fps:30,minBr:1e6,maxBr:25e5},{w:1920,h:1080,fps:30,minBr:175e4,maxBr:1e8}],RECV:[{w:320,h:180,fps:15,minBr:2e4,maxBr:175e3},{w:426,h:240,fps:15,minBr:125e3,maxBr:5e5},{w:640,h:360,fps:30,minBr:4e5,maxBr:575e3},{w:960,h:540,fps:30,minBr:5e5,maxBr:1125e3},{w:1280,h:720,fps:30,minBr:1e6,maxBr:25e5},{w:1920,h:1080,fps:30,minBr:175e4,maxBr:1e8}]}};function forOwn(g,f){for(const S in g)g.hasOwnProperty(S)&&f(g[S],S)}function forOwnRec(g,f){for(const S in g)g.hasOwnProperty(S)&&("object"==typeof g[S]?forOwnRec(g[S],f):f(g[S],S,g))}function isDefined2(g){return null!=g&&!Number.isNaN(g)}function getMinDefined(g,f){return isDefined2(f)?isDefined2(g)?Math.min(g,f):f:g}function getMaxDefined(g,f){return isDefined2(f)?isDefined2(g)?Math.max(g,f):f:g}function average(g){let f=0;return g.forEach((g=>f+=g)),f/=g.length,f}function remove2(g,f){let S=!1;for(let v=g.length;v-- >0;)f(g[v],v,g)&&(g.splice(v,1),S=!0);return S}function compareArraysBy(g,f,S){const v=[];return g.forEach((g=>{f.some((f=>S(g,f)))||v.push(g)})),0===v.length&&g.length===f.length}function values(g){const f=[];for(const S in g)g.hasOwnProperty(S)&&f.push(g[S]);return f}function assign(g,f){for(const S in f)f.hasOwnProperty(S)&&(g[S]=f[S])}function isEmpty(g){return!Object.keys(g).length}function keys(g){return Object.keys(g)}function shallowClone(g){const f={};return forOwn(g,((g,S)=>{f[S]=g})),f}function deepClone(g){let f;if(!g||"object"!=typeof g)return g;if(g instanceof Date)return f=new Date,f.setTime(g.getTime()),f;if(g instanceof Array){f=[];for(let S=0,v=g.length;S<v;S++)f[S]=deepClone(g[S]);return f}if(g instanceof Object)return f={},forOwn(g,(function(g,S){f[S]=deepClone(g)})),f;throw new Error("Unable to copy: "+stringifyObject2(g))}function removeUndefinedFields(g){return Object.keys(g).forEach((f=>{void 0===g[f]&&delete g[f]})),g}function uniqueId(){const segment=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return segment()+segment()+segment()+"4"+segment().substring(1)+"b"+segment().substring(1)+segment()+segment()+segment()}function deepEqual(g,f){let S;const v=typeof g;if(g===f)return!0;if(v!==typeof f||"object"!==v&&"function"!==v)return!1;if(null===g||null===f)return g===f;if(g instanceof Date&&f instanceof Date)return+g==+f;if(g instanceof Map&&f instanceof Map)return compareMaps(g,f);for(S in g)if(!(S in f)||!deepEqual(g[S],f[S]))return!1;for(S in f)if(!(S in g)||!deepEqual(g[S],f[S]))return!1;return!0}function compareMaps(g,f){let S;if(g.size!==f.size)return!1;let v=!0;return g.forEach(((g,C)=>{S=f.get(C),(S!==g||void 0===S&&!f.has(C))&&(v=!1)})),v}function getMaxSubstring(g,f){return f.reduce(((f,S)=>{const v=g.includes(S)?S.length:0;return f.length<v?S:f}),"")}function assertContentTypeSupported(g,f){if(-1===f.indexOf(g))throw{detail:`${g} mediaContent.contentType is not supported`,type:qt.MEDIA_ERROR.incompatibleOffer}}function throwIfFeatureNotSupported(g,f){g.forEach((g=>{if(""!==g&&-1!==f.findIndex((f=>f===g)))throw{detail:`Required feature '${g}' is not acceptable.`,type:qt.MEDIA_ERROR.incompatibleOffer}}))}function getClosestValue(g,f,S,v=0){for(let C=1;C<g.length;C++)if(g[C-1]+v<f&&f<=g[C]+v)return S?g[C]:g[C-1];return g[0]}function isInRange(g,f,S){return f<=g&&g<=S}function getFrom(g,...f){for(const S of f)if(S.hasOwnProperty(g))return S[g]}function subtractFrom(g,f){return g.filter((g=>!f.some((f=>f===g))))}function getLongestCommonContiguousSubstring(g,f){if(g===f)return g;let S=0,v=0,C="";for(let _=0;_<g.length&&!(C.length>g.length-_);_++){let T=_;v-S>C.length&&(C=g.substring(S,v),_=v-1),S=_,v=_;for(let I=0;I<f.length;I++)T<g.length&&f[I]===g[T++]?v=T:(T=_,v-S>C.length&&(C=g.substring(S,v),_=v-1),S=_,v=_)}return C}function levenshteinDistance(g,f){const S=new Array(g.length+1);for(let v=0;v<g.length+1;v++){S[v]=new Array(f.length+1);for(let g=0;g<f.length+1;g++)S[v][g]=0}for(let f=1;f<g.length+1;f++)S[f][0]=f;for(let g=1;g<f.length+1;g++)S[0][g]=g;for(let v=1;v<g.length+1;v++)for(let C=1;C<f.length+1;C++){let _=1;g[v-1]===f[C-1]&&(_=0),S[v][C]=Math.min(S[v-1][C]+1,S[v][C-1]+1,S[v-1][C-1]+_)}return S[g.length][f.length]}function getAverage(g){return g.reduce(((g,f)=>g+f),0)/(g.length?g.length:1)}function round(g,f=3){return g&&parseFloat(g.toFixed(f))}function scrubDeviceLabelPii(g,f){if(!g)return"";if(g.length<3)return g;const S=[],v=g.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);v&&S.push(v[1]);try{if(f?.length){const v=new RegExp(`(${f.join("|")})`,"gi");let C=v.exec(g);for(;C;)S.push(C[1]),C=v.exec(g)}else S.push("no_keywords")}catch(g){S.push(`Error: ${stringifyObject2(g)}`)}return 0===S.length?"unknown":S.join(" ")}function limitArraySize22(g,f,S=0){return g&&void 0!==f&&f>-1&&g.length>f&&g.splice(S,g.length-f),g}function arrayLimitedPush22(g,f,S,v=0){limitArraySize22(g,0===S?0:S-1,v),0!==S&&g.push(f)}function addGetterFields(g,f){const S={};for(const g in f)S[g]={get:f[g],configurable:!1,enumerable:!0};Object.defineProperties(g,S)}function getLast(g){return g?.length>0?g[g.length-1]:void 0}var Wt=window?.performance?.now&&window?.performance?.timeOrigin,zt=Wt?()=>window.performance.now():()=>Date.now(),Kt=Wt?window.performance.timeOrigin:0,Jt=zt,Yt=Kt;function rebaseTime(g,f,S){if(g?.length>0){const v=[];for(const C of g){const g=deepClone(C);g[f]=g[f]&&g[f]-S,v.push(g)}return v}return g}function rebaseAndLimitHistogramTimestamps(g,f,S){if(!g)return;const v={seconds1to3:[],seconds3to5:[],seconds5to8:[],seconds8to15:[],seconds15to60:[],seconds60toMax:[]};for(const[C,_]of Object.entries(g))for(const g of _)arrayLimitedPush22(v[C],g-f,S);return v}function sampleseries(g,f,S=!1){const v=g?.map(f).filter((g=>void 0!==g&&!isNaN(g)&&null!==g&&(!1===S||0!==g)));return v?.length?v.join(","):void 0}function sampleseriesArr(g,f,S){const v=g?.map(f).filter((g=>void 0!==g&&!isNaN(g)&&null!==g)).splice(-S);return v?.length?v:void 0}function clearObj(g,f){const S=[];for(const v of Object.keys(g))f.has(v)||S.push(v);for(const f of S)delete g[f]}function clearMap(g,f){const S=[];for(const v of g.keys())f.has(v)||S.push(v);for(const f of S)g.delete(f)}function convertContextProperty(g){return"object"==typeof g?stringifyObject2(g):g}function getPercentilesProviderFromSampleFreqs(g){const f=Object.keys(g).map(Number).sort(((g,f)=>g-f)),S=f.reduce(((f,S)=>f+(g[S]??0)),0);return{getPercentile:v=>{const C=S*v;let _=0;for(const S of f)if(_+=g[S],_>=C)return S}}}function getHeaderValue(g,f){return g.hasOwnProperty(f)?g[f]:g.hasOwnProperty(f.toLowerCase())?g[f.toLowerCase()]:void 0}function parseServiceTokenTypes(g){const f=g.toLowerCase(),S='token_types="',v=f.indexOf(S);if(-1===v)return[];const C=f.indexOf('"',v+S.length);if(-1===C)return[];const _=f.substring(v+S.length,C).trim();return""===_?[]:_.split(" ")}function ceilToMacroblock(g){const f=16;return Math.ceil(g/f)*f}function limitRebaseAndStringifyEvents(g,f,S,v){return JSON.stringify(rebaseTime(limitArraySize22(g,f),S,v))}var Qt=M;function createResolutionTable(g){return g.map((g=>new Xt(g.w,g.h,g.fps,g.minBr,g.maxBr)))}var Xt=class{constructor(g,f,S=0,v=0,C=0){this.width=g,this.height=f,this.fps=S,this.minBitrate=v,this.maxBitrate=C,this.fs=Math.ceil(g/qt.MACROBLOCK_SIZE)*Math.ceil(f/qt.MACROBLOCK_SIZE)}toString(){return this.height?`${this.height}p`:`${this.fs}fs`}},Zt=class _ResolutionTable2{constructor(g){g||(this.resolutions=createResolutionTable(qt.RES_TABLE.SEND)),this.resolutions=createResolutionTable(g)}static initialize(g){_ResolutionTable2.Send=new _ResolutionTable2(g.config.sendResolutionTableOverride),_ResolutionTable2.Recv=new _ResolutionTable2(g.config.recvResolutionTableOverride),g.on("configUpdated",(()=>{_ResolutionTable2.Send=new _ResolutionTable2(g.config.sendResolutionTableOverride),_ResolutionTable2.Recv=new _ResolutionTable2(g.config.recvResolutionTableOverride)}))}get initialResolution(){return this.resolutions[this.resolutions.length-1]}getResolutionByFs(g){return this.getResolutionRecord(void 0,g)}getMaxFsForHeight(g){return this.getResolutionRecord(g).fs}getResolutionForBitrate(g){let f=this.resolutions.filter((f=>f.maxBitrate&&f.maxBitrate>=g)).shift(),S=this.resolutions.filter((f=>f.minBitrate&&f.minBitrate<=g)).pop();return f=f??S,S=S??f,{lowRes:f,highRes:S}}getBitrateForResolution(g,f){const S=this.getResolutionRecord(Math.min(g,f));return{minBitrate:S.minBitrate,maxBitrate:S.maxBitrate}}getResolutionRecord(g,f){if(this===_ResolutionTable2.Send){for(let S=this.resolutions.length-1;S>=0;S--){if(g&&this.resolutions[S].height<=g)return this.resolutions[S];if(f&&this.resolutions[S].fs<=f)return this.resolutions[S]}return this.resolutions[0]}for(const S of this.resolutions){if(g&&S.height>=g)return S;if(f&&S.fs>=f)return S}return this.resolutions[this.resolutions.length-1]}getNextLowerResolution(g,f){const S=Math.min(g,f),v=this.getResolutionRecord(S),C=this.resolutions.indexOf(v);return S===Math.min(v.width,v.height)||this===_ResolutionTable2.Recv?this.resolutions[C-1]:this.resolutions[C]}getNextHigherResolution(g,f){const S=Math.min(g,f),v=this.getResolutionRecord(S),C=this.resolutions.indexOf(v);return S===Math.min(v.width,v.height)?this.resolutions[C+1]:this===_ResolutionTable2.Recv?this.resolutions[C]:this.resolutions[C+1]}getResolutions(){return this.resolutions}};Zt.Recv=new Zt(qt.RES_TABLE.RECV),Zt.Send=new Zt(qt.RES_TABLE.SEND);var ei=Zt,convertFramesizeToResolution=g=>ei.Send.getResolutionByFs(g).height,convertResolutionToFramesize=g=>ei.Send.getMaxFsForHeight(g),ti={numVideoChannelsGvc:({current:g,constraints:f})=>getMaxIncomingStreams(g,f),specCompliantSimulcast:({current:g,constraints:f})=>getMaxSimulcastLayers(g,f),multiviewResolutionLimits:({current:g,constraints:f,logger:S})=>getMaxParticipantResolutions(g,f,S),enableVla:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getVlaEnabledStatus(g,f,S,v),allowRemoteVla:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getVlaEnabledStatus(g,f,S,v),enableNonAdvVla:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getVlaEnabledStatus(g,f,S,v),outgoingVideoLimit:({current:g,settings:f,constraints:S})=>getOutgoingVideoLimit(g,f,S),webrtcCameraOpenFs:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getMaxFsAccordingToLimit(g,f,S,v),webrtcVideoCapabilityMaxFS:({current:g,settings:f,constraints:S,settingsSuffix:v})=>getMaxFsAccordingToLimit(g,f,S,v)},convertCallConstraintsToSettings=(g,f,S)=>({...buildSettings(g,f,S),...buildSettings(g,f,S,"1on1"),...buildSettings(g,f,S,"Multiparty")}),buildSettings=(g,f,S,v)=>{const C={};for(const _ of Object.keys(ti)){const T=`${_}${v??""}`;v&&!isDefined2(f[T])||(C[T]=ti[_]({current:f[T],settings:f,constraints:S,settingsSuffix:v,logger:g}))}return C},getMaxIncomingStreams=(g,f)=>getMinDefined(g,f.maxIncomingStreams),getMaxParticipantResolutions=(g,f,S)=>{const v=f.maxParticipantResolutions;if(!v)return g;const C={more:g.more};if(Number.isInteger(v))Object.keys(g).forEach((f=>{C[f]=getMinDefined(v,g[f])}));else{const f=Object.keys(v);if(!f.length)return S.warn(`ignoring invalid value provided for maxParticipantResolutions: ${v}}`),g;f.forEach((f=>{C[f]=getMinDefined(v[f],g[f]||g.more)}))}return C},getMaxSimulcastLayers=(g,f)=>void 0!==f.maxSimulcastLayers||g.allowOverride?{...g,video:getConstrainedSimulcastConfig(g.video,f),sharing:getConstrainedSimulcastConfig(g.sharing,f)}:g,getConstrainedSimulcastConfig=(g,f)=>{const S=g?.layerScaleFactors?.filter((g=>g<=f.maxSimulcastLayers));return S?.length>1?{...g,layerScaleFactors:S}:{...g,enableLocally:!1,allowEnableRemotely:!1}},getMaxResolutionFromConstraints=g=>getMinDefined((0,Qt.isNumber)(g?.outgoingVideoLimit)?g?.outgoingVideoLimit:g?.outgoingVideoLimit?.maxResolution,g?.maxOutgoingResolution),getOutgoingVideoLimit=(g,f,S)=>{const{outgoingVideoLimit:v}=S,C=(0,Qt.isNumber)(v),_=getMaxResolutionFromConstraints(S);if(f.sendVideoCapabilityManager?.isEnabled){const fsToResolution=g=>g?convertFramesizeToResolution(g):g,resolve=(g,f,S,v)=>f?getMaxDefined(getMinDefined(f,v),S):g,_=C?void 0:v?.maxFramerate,T=C?void 0:v?.maxBitrate,I=getMaxResolutionFromConstraints(S);return{...g,maxResolution:resolve(g?.maxResolution,I,fsToResolution(f.sendVideoCapabilityManager?.minFS),fsToResolution(f.sendVideoCapabilityManager?.maxFS)),maxFramerate:resolve(g?.maxFramerate,_,f.sendVideoCapabilityManager?.minFPS,f.sendVideoCapabilityManager?.maxFPS),maxBitrate:resolve(g?.maxBitrate,T)}}let T=getMinDefined(g?.maxResolution,_);if(_>0&&f.maxCameraFsViaCallConstraints>0){const g=convertFramesizeToResolution(f.maxCameraFsViaCallConstraints);T=getMaxDefined(getMinDefined(T,g),getMinDefined(_,g))}const I=getMinDefined(g?.maxBitrate,C?void 0:v?.maxBitrate),b=getMinDefined(g?.maxFramerate,C?void 0:v?.maxFramerate);return{...g,maxResolution:T,maxBitrate:I,maxFramerate:b}},getMaxFsAccordingToLimit=(g,f,S,v)=>{if(getMaxResolutionFromConstraints(S)>0&&f.maxCameraFsViaCallConstraints>0){const C=`outgoingVideoLimit${v??""}`,{maxResolution:_}=getOutgoingVideoLimit(f[C],f,S);return getMaxDefined(g,_?convertResolutionToFramesize(_):g)}return g},getVlaEnabledStatus=(g,f,S,v)=>!((f.specCompliantSimulcast.constraintsDisableVla||f[`specCompliantSimulcast${v}`]?.constraintsDisableVla)&&S.maxSimulcastLayers<2)&&g,ii=class extends Ht{constructor(g){super(g),this.logger=g,this._constraints={},this._callConstraintsTelemetry=[]}get constraints(){return this._constraints}get callConstraintsTelemetry(){return this._callConstraintsTelemetry}addCallConstraintsTelemetryEvent(g,f){const S={timestamp:(new Date).getTime(),type:f,value:g};this._callConstraintsTelemetry.push(S)}setConstraints(g){this.logger.debug("Setting new platform call constraints",JSON.stringify(g)),this._constraints=g,this.addCallConstraintsTelemetryEvent(g,"requested"),this.raiseChanged()}getSettings(g){return convertCallConstraintsToSettings(this.logger,g,this._constraints)}},ni=M,ri='"rtcmedia"';function getRelayCredentials(g){return{expires:g.expires,username:g.username,password:g.password,realm:g.realm}}var si=class{constructor(g){this.version=g,this.reports={},this.version||(this.version=1)}watch(g){const f={time:Date.now(),duration:-1,version:this.version};return this.reports[g]&&(g=`${g}_last`),this.reports[g]=f,{end:g=>{g&&(f.error=g),f.duration=Date.now()-f.time}}}getReports(){return this.reports}};function clientToRelayConfig(g){return{Service:g.Service,Relay:g.Relay,Token:g.Token}}var ai="configFetch",oi="skypeTokenFetch",li="trapTokenFetch",ci=class{constructor(g){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new si,this.context=g,this.logger=g.logger.createChild("RM"),this.request=g.request,this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setRelayOverride(g){this.relaysOverride=g}setDefaultRelayConfig(g){this.config??(this.config=g)}async queryRelaysAsync(g={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const f=await this.updateRelaysPromise;return f?"turn"===g.relayType?f.Turn:g.isRemoteClientLync?f.Lync:f.Skype:[]}getAuthTokenStats(){}getStats(){return{config:clientToRelayConfig(this.config),stats:this.timers.getReports()}}updateRelaysFromConfigAsync(g=!1){const f=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((g=>(this.updateRelaysPromise=f,g))).catch((f=>(this.updateRelaysPromise=null,g?this.logger.warn("failed to retrieve relays",stringifyRequestResponse(f)):this.logger.error("failed to retrieve relays",stringifyRequestResponse(f)),null)));return f}refreshRelaysFromConfig(){this.request.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}updateRelaysAsync(){const g=this.config.Service.tokenUrl;let f;const fetchTrapTokenThroughProvider=async()=>(f=this.timers.watch(li),this.context.trapTokenCredentialsProvider()),fetchTrapTokenDirectly=async()=>{const S=this.timers.watch(oi);let v="";try{v=await this.context.tokenProvider(),this.logger.info("fetching skypeToken")}catch(g){throw S.end(stringifyRequestResponse(g)),g}return S.end(),f=this.timers.watch(li),(await this.request.get(g,{headers:{"X-Skypetoken":v,"api-version":2}})).response},S=this.context.trapTokenCredentialsProvider?fetchTrapTokenThroughProvider:fetchTrapTokenDirectly;return this.logger.info("Fetch TRAP token "+(this.context.trapTokenCredentialsProvider?"with provider":"directly")),S().then((g=>{f.end();let S=0;const v=this.config.Token.earlyRefreshMinutes,C=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(g),S=Math.max(g.expires-60*v,g.expires*C/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*S);const _=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:ri,T=getRelayCredentials(this.getTrapToken(_)),I={addresses:this.config.Relay.Skype.addresses,fqdns:this.config.Relay.Skype.fqdns,tcpPort:this.config.Relay.Skype.tcpPort,udpPort:this.config.Relay.Skype.udpPort,type:"msturn"},b={addresses:this.config.Relay.Lync.addresses,fqdns:this.config.Relay.Lync.fqdns,tcpPort:this.config.Relay.Lync.tcpPort,udpPort:this.config.Relay.Lync.udpPort,type:"msturn"},A={addresses:this.config.Relay.Turn.addresses,fqdns:this.config.Relay.Turn.fqdns,tcpPort:this.config.Relay.Turn.tcpPort,udpPort:this.config.Relay.Turn.udpPort,tlsPort:this.config.Relay.Turn.tlsPort,type:"turn"},P={Skype:[{...I,...T}],Lync:[{...b,...T}],Turn:[{...A,...T}]};return this.logger.info("relays from trap",[I,b,A]),P})).catch((g=>{throw f&&f.end(stringifyRequestResponse(g)),g}))}storeTrapTokens(g){if(!g?.tokens)return void this.logger.error("failed to get tokens from trap response");const f={};g.tokens.forEach((S=>{f[S.realm]={expires:g.expires,username:S.username,password:S.password,realm:S.realm}})),this.trapTokens=f}getTrapToken(g){if("string"==typeof g){const f=g.replace(/^"|"$/g,""),S=`"${f}"`,v=this.trapTokens[S]||this.trapTokens[f];if(v)return v}throw new Error(`token for relay not found, realm: ${g}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const g=this.timers.watch(ai);try{const f=await this.context.configProvider();g.end(),this.logger.info("retrieved configuration:",f),(0,ni.isEmpty)(f)||(this.config=f),this.logger.info("applied configuration:",this.config)}catch(f){this.logger.warn("failed to retrieve configuration",stringifyObject2(f)),g.end(stringifyRequestResponse(f))}}};function build(g){return new ci(g)}var di=M,hi="aadTokenFetch",ui=class{constructor(g){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new si(2),this.context=g,this.authTokenFetcher=this.context.authTokenFetcher,this.logger=g.logger.createChild("RM2")}setRelayOverride(g){this.relaysOverride=g}setDefaultRelayConfig(g){this.config??(this.config=g),this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setClientSupportsGenericTokenApi(g){this.authTokenFetcher.supportsGenericTokenApi=g}async queryRelaysAsync(g={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const f=await this.updateRelaysPromise;return f?"turn"===g.relayType?f.Turn:g.isRemoteClientLync?f.Lync:f.Skype:[]}getStats(){return{config:clientToRelayConfig(this.config),stats:this.timers.getReports()}}getAuthTokenStats(){return this.context.authTokenFetcher.getStats()}updateRelaysFromConfigAsync(g=!1){const f=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((g=>(this.updateRelaysPromise=f,g))).catch((f=>(this.updateRelaysPromise=null,g?this.logger.warn("failed to retrieve relays",stringifyRequestResponse(f)):this.logger.error("failed to retrieve relays",stringifyRequestResponse(f)),null)));return f}refreshRelaysFromConfig(){this.context.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}async updateRelaysAsync(){const g=this.context.configProvider?.config.useNewTokenApi?hi:oi,f=this.timers.watch(g),S=generateCauseId();this.logger.info(`${S}[RM2] Fetch TRAP token`);try{const g=await this.context.authTokenFetcher.fetchTrapToken(S,this.config);f.end();let v=0;const C=this.config.Token.earlyRefreshMinutes,_=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(g),v=Math.max(g.expires-60*C,g.expires*_/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*v);const T=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:ri,I=getRelayCredentials(this.getTrapToken(T)),b={addresses:this.config.Relay.Skype.addresses,fqdns:this.config.Relay.Skype.fqdns,tcpPort:this.config.Relay.Skype.tcpPort,udpPort:this.config.Relay.Skype.udpPort,type:"msturn"},A={addresses:this.config.Relay.Lync.addresses,fqdns:this.config.Relay.Lync.fqdns,tcpPort:this.config.Relay.Lync.tcpPort,udpPort:this.config.Relay.Lync.udpPort,type:"msturn"},P={addresses:this.config.Relay.Turn.addresses,fqdns:this.config.Relay.Turn.fqdns,tcpPort:this.config.Relay.Turn.tcpPort,udpPort:this.config.Relay.Turn.udpPort,tlsPort:this.config.Relay.Turn.tlsPort,type:"turn"},R={Skype:[{...b,...I}],Lync:[{...A,...I}],Turn:[{...P,...I}]};return this.logger.info("relays from trap",[b,A,P]),R}catch(g){throw this.logger.info(`Fetch TRAP token failed with error ${g}`),f&&f.end(stringifyRequestResponse(g)),g}}storeTrapTokens(g){const f={};if(g?.tokens)g.tokens.forEach((S=>{f[S.realm]={expires:g.expires,username:S.username,password:S.password,realm:S.realm}}));else{if(!g.realm)return void this.logger.error("failed to get tokens from trap response");f[g.realm]=g}this.trapTokens=f}getTrapToken(g){if("string"==typeof g){const f=g.replace(/^"|"$/g,""),S=`"${f}"`,v=this.trapTokens[S]||this.trapTokens[f];if(v)return v}throw new Error(`token for relay not found, realm: ${g}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const g=this.timers.watch(ai);try{const f=await this.context.relayConfigProvider();g.end(),this.logger.info("retrieved configuration:",f),(0,di.isEmpty)(f)||(this.config=f),this.logger.info("applied configuration:",this.config)}catch(f){this.logger.warn("failed to retrieve configuration",stringifyRequestResponse(f)),g.end(stringifyRequestResponse(f))}}},gi=class{constructor(g,f,S,v,C){this.signalingAgentProvider=f,this.request=S,this.tokenProviders=v,this.configProvider=C,this.errors=[],this.clientSupportsGenericTokenAPI=!1,this.logger=g.createChild("AuthTokenFetcher")}set supportsGenericTokenApi(g){this.clientSupportsGenericTokenAPI=g}buildHeaders(g,f){const S={"api-version":2};switch(this.configProvider?.config.useTokenMigrationHeader&&(S["X-MS-Migration"]="True"),g){case 4:case 8:return S.Authorization=`Bearer ${f}`,S;case 1:return S["X-Skypetoken"]=f,S;default:throw new Error(`TokenType ${g} is not supported`)}}serviceSupportedTokenTypes(g){let f=null;if(void 0===g)f=this.clientSupportedTokenTypes();else{const S=g?.toLowerCase();f=this.constructTokenType(S)}return null===f&&this.configProvider?.config.useSkypeTokenWhenNoAuthenticateHeader&&(f|=1),f}extractWwwauthenticateHeaders(g){let f={};if(g){const S=getHeaderValue(g,"www-authenticate");S&&(f={authenticationHeaders:[S]})}return f}convertStringToTokenType(g){switch(g){case"cae":return 8;case"aad":return 4;case"skype":return 1;default:return this.logger.info("[authTokenFetcher][convertStringToTokenType]unexpected: unrecognized token type ${tokenType}"),null}}getTokenTypeFromHeaders(g,f){if(!this.clientSupportsGenericTokenAPI)return 1;let S=null;const v=f?.authenticationHeaders;if(!v&&g)this.configProvider?.config.useSkypeTokenWhenNoAuthenticateHeader?(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),S=1):(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),S=this.clientSupportedTokenTypes());else if(v||g){if(v&&g)for(const g of v){const f=parseServiceTokenTypes(g);if(this.configProvider?.config.supportMissingTokenTypesInResponse&&0===f.length)this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),S=this.clientSupportedTokenTypes();else for(const g of f){const f=this.convertStringToTokenType(g.toLowerCase());this.configProvider?.config.clientSupportsCaeToken&&8===f&&(S|=8),this.configProvider?.config.clientSupportsAadToken&&4===f&&(S|=4),this.configProvider?.config.clientSupportsSkypeToken&&1===f&&(S|=1)}}}else this.logger.info("[authTokenFetcher][getTokenTypeFromHeaders] retrying to fetch token woth client supported tokens"),S=this.clientSupportedTokenTypes();return S}constructTokenType(g){let f=null;return g.includes("aad")&&this.configProvider?.config.clientSupportsAadToken&&(f|=4),g.includes("cae")&&this.configProvider?.config.clientSupportsCaeToken&&(f|=8),g.includes("skype")&&this.configProvider?.config.clientSupportsSkypeToken&&(f|=1),f}getTokenMetadataForTrapService(g,f,S){const v={verb:"POST",path:g},C=JSON.stringify(v);let _=null;const T=this.extractWwwauthenticateHeaders(S),I=!!T?.authenticationHeaders;return _=S?this.getTokenTypeFromHeaders(I,T):this.serviceSupportedTokenTypes(f),this.logger.info(`[authTokenFetcher][getTokenMetadata] return token type=${_}, factoJson=${C}`),{tokenType:_,factorsJson:C,requestMetadataJson:T,isUnauthorized:I}}clientSupportedTokenTypes(){let g=null;return this.configProvider?.config.clientSupportsAadToken&&(g|=4),this.configProvider?.config.clientSupportsCaeToken&&(g|=8),this.configProvider?.config.clientSupportsSkypeToken&&(g|=1),g}async handleAuthTokenFailure(g,f,S,v){this.logger.info("[authTokenFetcher][handleAuthTokenFailure] failed to fetch token, retrying");try{const C=this.getTokenMetadataForTrapService(f,void 0,S);return this.logger.info(`[authTokenFetcher][handleAuthTokenFailure] token request options=${C}`),C.invalidToken=v,await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(g,!1,C)}catch(g){const f={status:g?.response?.status||g?.status,error:g,fatal:!0};this.errors.push(stringifyObject2(f)),this.logger.error(`[authTokenFetcher] failed to fetch token trough new api with error: ${stringifyObject2(f)}, quiting`)}}getRequestToken(g){const f=getHeaderValue(g,"X-Skypetoken");if(f)return f;const S=getHeaderValue(g,"Authorization");if(S){const g=S.split(" ");if(2===g.length)return g[1]}}async fetchTrapCredentials(g,f,S){const v=this.buildHeaders(f,g),C=await this.request.get(S,{headers:v});return C?.response}async fetchTrapTokenWithNewTokenApi(g,f,S){let v;this.logger.info(`${S}[authTokenFetcher] fetching token through fetchTrapTokenWithNewTokenApi`);const C=this.getTokenMetadataForTrapService(g,f);try{return v=await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(S,!1,C),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(S),await this.fetchTrapCredentials(v,this.tokenTypeFetched,g)}catch(f){const C={status:f?.response?.status||f?.status,error:f,fatal:!1};this.errors.push(stringifyObject2(C)),this.logger.error(`${S}[authTokenFetcher] fetchTrapTokenWithNewTokenApi failed with ${stringifyObject2(C)}, retrying...`);const _=f?.response?.headers;if(_){const f=this.getRequestToken(_);return v=await this.handleAuthTokenFailure(S,g,_,f),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(S),await this.fetchTrapCredentials(v,this.tokenTypeFetched,g)}throw f}}async fetchTrapTokenThroughProvider(){return this.logger.info("[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokenThroughProvider"),this.tokenProviders.trapTokenCredentialsProvider()}async fetchTrapTokensWithLegacyTokenFetcher(g,f){this.logger.info(`${f}[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokensWithLegacyTokenFetcher`);try{this.tokenTypeFetched=1;const f=await this.tokenProviders.skypeTokenProvider();return(await this.request.get(g,{headers:{"X-Skypetoken":f,"api-version":2}})).response}catch(g){throw this.errors.push(stringifyObject2(g)),this.logger.error(`${f}[authTokenFetcher] fetchTrapTokensWithLegacyTokenFetcher failed with ${stringifyObject2(g)}`),g}}getStats(){return{tokenType:this.tokenTypeFetched,errors:limitArraySize2(this.errors,this.configProvider?.config.diagnostics.telemetryLimits.numAuthTokenErrors??100)}}async fetchTrapToken(g,f){let S;this.logger.info(`${g}[AuthTokenFetcher] Start fetching token`);const v=f.Service.tokenUrl,C=f.Service.supportedTokenTypes;return S=this.configProvider?.config.useNewTokenApi?this.fetchTrapTokenWithNewTokenApi(v,C,g):this.tokenProviders.trapTokenCredentialsProvider?this.fetchTrapTokenThroughProvider():this.fetchTrapTokensWithLegacyTokenFetcher(v,g),S}},pi=class{constructor(g,f,S,v){this.config=g,this.signalingAgentProvider=f,this.ecsProvider=S,this.logger=v}getOrCreateRelayManager(){return this.config.relayManager?this.config.relayManager:this.relayManager||this.createRelayManager()}setConfigProvider(g){this.configProvider=g}createRelayManager(){return this.relayManager??(this.relayManager=this.buildRelayManager(this.config.httpRequestDispatcher,this.config.tokenProvider,this.config.configProvider,this.config.appStateProvider,this.config.trapTokenCredentialsProvider,this.configProvider))}buildRelayManager(g,f,S,v,C,_){const T=g||new $e(this.logger),I=this.ecsProvider.getEcsConfig("SkypeCalling","enableFetchApi"),b={get:(g,f)=>T.getAsync(g,{...T.getRequestOptions("GET",f?.headers,null,f?.timeout),useFetch:I}),isOnline:v.isOnline};if(this.configProvider?.config.useNewTokenApi){const g=new gi(this.logger,this.signalingAgentProvider,b,{skypeTokenProvider:f,trapTokenCredentialsProvider:C},_);return new ui({logger:this.logger,relayConfigProvider:()=>S.getRelayConfig(),isOnline:v.isOnline,authTokenFetcher:g,configProvider:_})}return build({logger:this.logger,tokenProvider:f,trapTokenCredentialsProvider:C,configProvider:()=>S.getRelayConfig(),request:{get:(g,f)=>T.getAsync(g,{...T.getRequestOptions("GET",f?.headers,null,f?.timeout),useFetch:I}),isOnline:v.isOnline}})}},mi={CALL_SETUP_NATIVE:"skypecosi_concore_native_ts_calling_call_setup_session",CALL_IN_CALL_NATIVE:"skypecosi_concore_native_ts_calling_in_call_session",REGISTRY_WEB:"skypecosi_concore_web_ts_calling_registry",REGISTRY_NATIVE:"skypecosi_concore_native_ts_calling_registry"},fi={PARK:"*11",SHARED_LINE:"*12",SERVER_HOLD:"*13",CALL_PARK:"*14"},Si={totalParticipants:0,preheatedParticipants:0,lobbyParticipants:0,totalPresenters:0,requestingAttentionPresenters:0,totalAttendees:0,requestingAttentionAttendees:0,overflowAttendees:0},vi=R,Ci=150,yi=30,Ei=class{constructor(g,f,S,v,C){this.eventName=g,this.eventStartTime=f,this.type=S,this.causeId=v,this.status="Pending",this.eventStartTimestamp=(new Date).getTime(),this.data=[],this.causeId=v?.substring(0,8),"Event"===this.type&&delete this.status,C&&this.data.push(C)}set variant(g){this.eventVariant=g}recordSuccess(g,f){this.recordResult("Success",g,f)}recordFailure(g,f){this.recordResult("Failure",g,f)}recordTimeout(g,f){this.recordResult("Timeout",g,f)}addData(g){this.data.push(g)}isPending(){return"Pending"===this.status}getEvent(){const g={start:this.eventStartTime,duration:this.duration,status:this.status,result:this.result,causeId:this.causeId,resultCauseId:this.resultCauseId,variant:this.eventVariant,data:this.data.map((g=>this.prepareData(g,!0))).filter((g=>!!g))};return"Event"===this.type&&delete g.status,g.data.length||delete g.data,g.causeId||delete g.causeId,g.resultCauseId||delete g.resultCauseId,g.result||delete g.result,g.variant||delete g.variant,{[this.eventName]:g}}recordResult(g,f,S){this.status=g,this.result=this.prepareData(f),this.causeId!==S&&(this.resultCauseId=S),this.duration=(new Date).getTime()-this.eventStartTimestamp}prepareData(g,f=!1){if(null==g)return"";if("string"==typeof g)return scrubMriOrOmit(g);if("number"==typeof g||"boolean"==typeof g)return String(g);if("function"==typeof g)return"";if(g instanceof Error)return g.toString();try{return Object.keys(g).length?f?g:getPIISafeObject(g):""}catch(g){return"invalid"}}},_i=class{constructor(g,f,S,v){this.logger=g,this.startTime=f,this.maxEventsExceeded=S,this.perfModule=v,this.recordedEvents=[],this.ipcStats=[],this.ongoingOperations={}}recordEvent(g,f,S=generateCauseId()){this.logger.debug("Event:",g,vi.pii.Omit(f));const v=new Ei(g,this.getEventStartTime(),"Event",S,f);return this.pushToRecordedEvents(v),v}recordOperationSuccess(g,f=null,S,v,C){this.logger.info("Event success:",v,g,vi.pii.Omit(S),vi.pii.Omit(f)),this.recordOperationResult(g,f,"Success",S,v,C)}recordOperationFailure(g,f,S,v,C){this.logger.info("Event failure:",g,vi.pii.Omit(S),f),this.recordOperationResult(g,f,"Failure",S,v,C)}recordOperationTimeout(g,f,S,v,C){this.logger.info("Event timeout:",g,vi.pii.Omit(S),f),this.recordOperationResult(g,f,"Timeout",S,v,C)}maybeRecordOperationSuccess(g,f=null,S,v,C){this.hasOngoingEvent(g,S)&&this.recordOperationSuccess(g,f,S,v,C)}maybeRecordOperationFailure(g,f,S,v,C){this.hasOngoingEvent(g,S)&&this.recordOperationFailure(g,f,S,v,C)}maybeRecordOperationTimeout(g,f,S,v,C){this.hasOngoingEvent(g,S)&&this.recordOperationTimeout(g,f,S,v,C)}recordOperationResult(g,f,S,v,C,_){this.hasOngoingEvent(g,v)||this.recordOperation(g,C,v);let T=this.ongoingOperations[g];switch(v&&(T=T[v]),_&&T.addData(_),S){case"Success":T.recordSuccess(f,C);break;case"Failure":T.recordFailure(f,C);break;case"Timeout":T.recordTimeout(f,C);break;default:this.logger.error("Unknown operation record state in record operation result.")}v?delete this.ongoingOperations[g][v]:delete this.ongoingOperations[g]}recordOperation(g,f,S,v){this.logger.debug("Event create:",f,g,vi.pii.Omit(S),v);const C=new Ei(g,this.getEventStartTime(),"Operation",f,v);return this.ongoingOperations[g]||(this.ongoingOperations[g]={}),S?this.ongoingOperations[g][S]=C:this.ongoingOperations[g]=C,this.pushToRecordedEvents(C),C}setOperationVariant(g,f,S){let v;v=S?this.ongoingOperations[g][S]:this.ongoingOperations[g],v?v.variant=f:this.logger.error(`Could not find operation ${g} to set variant ${f}`)}updateOperationData(g,f,S,v){try{if(!this.ongoingOperations[g])return void this.recordEvent(g,f,S);v?this.ongoingOperations[g][v]&&this.ongoingOperations[g][v].addData(f):this.ongoingOperations[g].addData(f)}catch(f){return void this.logger.info(`Unable to update operation: ${g} data`)}}pushToRecordedEvents(g){if(this.maxEventsExceeded&&this.maxEventsExceeded()&&this.recordedEvents.shift(),this.recordedEvents.push(g),this.perfModule&&this.ipcStats.length<=yi){const g=this.perfModule.getIpcStats();g&&this.ipcStats.push({ingestionTime:this.getEventStartTime(),stats:g})}}hasOngoingEvent(g,f){return this.ongoingOperations[g]?!(f&&!this.ongoingOperations[g][f]&&(this.logger.warn(`Unable to find event for name\\id ${g}\\${vi.pii.Omit(f)}`),1)):(this.logger.warn(`Unable to find event for name ${g}`),!1)}getEventStartTime(){return(new Date).getTime()-this.startTime}getEventTimestampBag(g,f){const S=f?[f.getEvent()]:this.recordedEvents.filter((f=>!g||!f.isPending())).map((g=>g.getEvent())),v=JSON.stringify({eventStart:this.startTime,events:S});return this.logger.info(`Call eventTimestampBag ${vi.pii.Omit(v)}`),v}getIPCStats(){return 0!==this.ipcStats.length?JSON.stringify(this.ipcStats):""}removeRecordedEvent(g){const f=this.recordedEvents.indexOf(g);f>-1&&this.recordedEvents.splice(f,1)}},Ti=class extends _i{constructor(g,f){super(g,f,(()=>this.recordedEvents.length>Ci)),this.getHostName=()=>{try{return"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>"}catch(g){return"unknown"}},this.tsCallingVersion=getTsCallingVersion2(),this.logger=g.createChild("CallRegistryTelemetry")}setClientType(g){this.clientType=g}setEndpointId(g){this.endpointId=g}setSkypeId(g){this.skypeId=scrubMriOrOmit(g)}setApplicationType(g){this.applicationType=g}setRing(g){this.ring=g}setTenantId(g){this.tenantId=g}setUserHexCID(g){this.userHexCID=g}setAcsResourceId(g){this.acsResourceId=g}setRegion(g){this.region=g}setPartition(g){this.partition=g}getEvent(g,f){const getValue2=g=>void 0===g?"":g;return{EndpointId:getValue2(this.endpointId),SkypeId:getValue2(this.skypeId),ApplicationType:getValue2(this.applicationType),Ring:getValue2(this.ring),TenantId:getValue2(this.tenantId),userHexCID:getValue2(this.userHexCID),AcsResourceId:getValue2(this.acsResourceId),Region:getValue2(this.region),Partition:getValue2(this.partition),TsCallingVersion:getValue2(this.tsCallingVersion),HostName:this.getHostName(),EventTimestampBag:this.getEventTimestampBag(g,f),DiagnosticInfo:this.callEndDiagnosticInfo,ClientType:getValue2(this.clientType)}}removeNonPendingOperations(){this.recordedEvents=this.recordedEvents.filter((g=>g.isPending()))}},Ii=class extends _i{constructor(g,f,S){super(g,f,(()=>this.inCallMode&&this.recordedEvents.length>Ci),S),this.inCallMode=!1,this.tsCallingVersion=getTsCallingVersion2(),this.logger=g.createChild("CallTelemetry")}setClientType(g){this.clientType=g}setCallId(g){this.currentCallId&&(this.previousCallId=this.currentCallId),this.currentCallId=g}setConsultativeCallId(g){this.consultativeCallId=g}setEndpointId(g){this.endpointId=g}setParticipantId(g){this.participantId=g}setDisplayName(g){this.displayName=g}setPreheatFlags(g){this.preheatFlags=g}setCallOrigin(g){this.origin=g}setGroupId(g){this.groupId=g}setThreadId(g){this.threadId=g}setBackroomThreadId(g){this.backroomThreadId=g}setStreamThreadId(g){this.streamThreadId=g}setLobbyThreadId(g){this.lobbyThreadId=g}setComplianceRecordingContentLength(g){this.complianceRecordingContentLength=g}setConversationStartTime(g){this.conversationStartTime=g}setMessageId(g){this.messageId=g}setSkypeId(g){this.skypeId=scrubMriOrOmit(g)}setApplicationType(g){this.applicationType=g}setRing(g){this.ring=g}setTenantId(g){this.tenantId=g}setUserHexCID(g){this.userHexCID=g}setAcsResourceId(g){this.acsResourceId=g}setRegion(g){this.region=g}setPartition(g){this.partition=g}setFailureType(g){this.failureType=g}setIsCast(g){this.isCast=g?"True":"False"}setIsHuddleGroupCall(g){this.isHuddleGroupCall=g?"True":"False"}setIsEmergency(g){this.isEmergency=g?"True":"False"}setRole(g){this.isAnonymous="admin"===g?"False":"True"}setCallType(g){this.callType=g}setConversationType(g){this.conversationType=g}setDirection(g){this.direction=g}setSelfParticipantRole(g){this.selfParticipantRole=g}setTerminationState(g){this.terminationState=g}setTerminationReason(g){this.terminationReason=g}setCallEndDiagnosticInfo(g){this.callEndDiagnosticInfo=g}setStackConfig(g){this.stackConfig=g}setJoinedFrom(g){this.joinedFrom=g}setMeetingCode(g){this.meetingCode=g}setMeetingUrl(g){this.meetingUrl=g}setHasMeetingRegistrationId(g){this.hasMeetingRegistrationId=g?"True":"False"}setHasParticipantPin(g){this.hasParticipantPin=g?"True":"False"}getEvent(g,f){const getValue2=g=>void 0===g?"":g;return{CorrelationId:getValue2(this.currentCallId),PreviousCorrelationId:getValue2(this.previousCallId),ConsultativeCallId:getValue2(this.consultativeCallId),EndpointId:getValue2(this.endpointId),SkypeId:getValue2(this.skypeId),ParticipantId:getValue2(this.participantId),DisplayName:new Ue(this.displayName??"",1),PreheatFlags:getValue2(this.preheatFlags),CallType:getValue2(this.callType),ConversationType:getValue2(this.conversationType),Direction:getValue2(this.direction),Origin:getValue2(this.origin),SelfParticipantRole:getValue2(this.selfParticipantRole),IsAnonymous:getValue2(this.isAnonymous),GroupId:scrubMriOrOmit(getValue2(this.groupId)),ThreadId:getLoggableThreadId(getValue2(this.threadId)),MessageId:getValue2(this.messageId),ApplicationType:getValue2(this.applicationType),Ring:getValue2(this.ring),TenantId:getValue2(this.tenantId),UserHexCID:getValue2(this.userHexCID),AcsResourceId:getValue2(this.acsResourceId),Region:getValue2(this.region),Partition:getValue2(this.partition),FailureType:getValue2(this.failureType),IsCast:getValue2(this.isCast),IsHuddleGroupCall:getValue2(this.isHuddleGroupCall),IsEmergency:getValue2(this.isEmergency),TsCallingVersion:getValue2(this.tsCallingVersion),TerminationState:getValue2(this.terminationState),TerminationReason:getValue2(this.terminationReason),StackConfig:getValue2(this.stackConfig),EventTimestampBag:this.getEventTimestampBag(g,f),HostName:this.getHostName(),DiagnosticInfo:this.callEndDiagnosticInfo,JoinedFrom:this.joinedFrom,MeetingCode:this.meetingCode,MeetingUrl:this.meetingUrl,HasMeetingRegistrationId:this.hasMeetingRegistrationId,HasParticipantPin:this.hasParticipantPin,IPCStats:this.getIPCStats(),ComplianceRecordingContentLength:getValue2(this.complianceRecordingContentLength),ConversationStartTime:getValue2(this.conversationStartTime),BackroomThreadId:getLoggableThreadId(getValue2(this.backroomThreadId)),StreamThreadId:getLoggableThreadId(getValue2(this.streamThreadId)),LobbyThreadId:getLoggableThreadId(getValue2(this.lobbyThreadId)),ClientType:getValue2(this.clientType)}}getShortEvent(){const getValue2=g=>void 0===g?"":g;return{CorrelationId:getValue2(this.currentCallId),EndpointId:getValue2(this.endpointId),ParticipantId:getValue2(this.participantId),DisplayName:new Ue(this.displayName??"",1),CallType:getValue2(this.callType),ConversationType:getValue2(this.conversationType),Direction:getValue2(this.direction),Origin:getValue2(this.origin),SelfParticipantRole:getValue2(this.selfParticipantRole),IsAnonymous:getValue2(this.isAnonymous),ThreadId:getLoggableThreadId(getValue2(this.threadId)),ApplicationType:getValue2(this.applicationType),Ring:getValue2(this.ring),TenantId:getValue2(this.tenantId),UserHexCID:getValue2(this.userHexCID),AcsResourceId:getValue2(this.acsResourceId),Region:getValue2(this.region),TsCallingVersion:getValue2(this.tsCallingVersion),DiagnosticInfo:this.callEndDiagnosticInfo,JoinedFrom:this.joinedFrom,ClientType:getValue2(this.clientType)}}switchToInCallTelemetry(){this.recordedEvents=this.recordedEvents.filter((g=>g.isPending())),this.inCallMode=!0}getHostName(){try{return location.host}catch(g){return"unknown"}}},getEndpointInformationForTelemetry=g=>Array.isArray(g)?g.map((g=>({endpointId:g.endpointId,participantId:g.participantId}))):null,calculateJoinedFromForTelemetry=(g,f,S,v,C)=>{if(g){if(g.meetingUrl)return"MeetingUrl";if(g.meetingCode)return"MeetingCode"}return f||S?"ThreadContext":v?"GroupId":C?"Awareness":""};function sanitizeMeetingCode(g,f,S){if(!g)return S.info(`sanitizeMeetingCode[${f}] empty / undefined meeting code parameter`),g;let v=g.replace(/\s/g,"");return v=v.replace(/-/g,""),S.info(`sanitizeMeetingCode[${f}] meetingCode: ${g}, sanitizedMeetingCode: ${v}`),v}function getMeetingCodeFromMeetingUrl(g,f,S){if(!g)return S.info(`getMeetingCodeFromMeetingUrl[${f}] empty / undefined meeting Url parameter`),g;const v=new URL(g);let C="";if(v&&v.pathname&&v.pathname.split("/").length>=2){const g=v.pathname.split("/");"meet"===g[g.length-2]&&(C=g[g.length-1])}return S.info(`getMeetingCodeFromMeetingUrl[${f}] meetingUrl: ${g}, meetingUrlObject: ${safeJsonStringify(v)}, meetingCode: ${C}`),C}function compareMeetingData(g,f,S,v){const C=sanitizeMeetingCode(g&&g.meetingCode||"",S,v),_=sanitizeMeetingCode(f&&f.meetingCode||"",S,v),definedAndEqual=(g,f)=>!!g&&!!f&&g===f;if(definedAndEqual(C,_))return!0;let T=getMeetingCodeFromMeetingUrl(g&&g.meetingUrl||"",S,v);T=sanitizeMeetingCode(T,S,v);let I=getMeetingCodeFromMeetingUrl(f&&f.meetingUrl||"",S,v);if(I=sanitizeMeetingCode(I,S,v),definedAndEqual(T,I))return!0;if(definedAndEqual(T,_)||definedAndEqual(I,C))return!0;if(g&&g.meetingUrl&&f&&f.meetingUrl){const S=new URL(g.meetingUrl),v=new URL(f.meetingUrl);if(S.hostname===v.hostname&&S.pathname===v.pathname)return!0}return!1}function noop(){}var bi={CODE:{SUCCESS:0,MEDIA_ERROR:410,CLIENT_ERROR_CODE:499,UNKNOWN_ERROR:497},SUB_CODE:{VDI_DISCONNECTED:3e3,ACTION_NOT_ALLOWED:3548,INVALID_DATA_TYPE:3757,ABANDONED:4990,ENDED_BY_REMOTE_ENDPOINT:5028,BEACON:4521,UNKNOWN_FAILURE:3545,SLIMCORE_CALL_SETUP_FAILURE:3546}},Ai=4294967294,Pi="_operationIdValue_",Ri="_causeIdValue_",Mi="_callStartOptionsValue_",wi="_clientReasonValue_";function callOperation(g,f,S=!1){return operationDecorator(0,g,f,S)}function participantOperation(g,f){return operationDecorator(1,g,f)}var operationId=(g,f,S)=>{if(g[f][Pi])throw new Error("can not specify more than one operation id");g[f][Pi]=S},causeId=(g,f,S)=>{if(g[f][Ri])throw new Error("can not specify more than one cause id");g[f][Ri]=S},callStartOptions=(g,f,S)=>{if(g[f][Mi])throw new Error("can not specify options more than once");g[f][Mi]=S},reason=(g,f,S)=>{if(g[f][wi])throw new Error("can not specify reason more than once");g[f][wi]=S},operationDecorator=(g,f,S,v=!1)=>(C,_,T)=>{const I=T.value,b=C[_]?.[Pi],A=C[_]?.[Ri],P=C[_]?.[Mi],R=C[_]?.[wi],M=S?.type||"Async";return T.value=function(...C){const _=this;let T=v?generateGuid():generateCauseId();void 0!==A&&(C[A]&&(validateCauseId(C[A])||validateGuid(C[A]))?T=C[A]:C[A]=T);let w,O=void 0!==b?C[b]:void 0;if(void 0!==O)if(Array.isArray(O))try{const g=O.map((g=>g.toString())).sort().concat().toString();O=getStringHash(g).toString()}catch{const g=`[${O}]${f} failed in array parsing in operationDecorator`,S={terminatedReason:32,terminatedReasonCode:bi.CODE.UNKNOWN_ERROR,terminatedReasonSubCode:bi.SUB_CODE.UNKNOWN_FAILURE,errorMessage:g};return Promise.reject(S)}else if(O&&"object"==typeof O)try{let g=JSON.stringify(O);S&&S.operationIdKey&&O.hasOwnProperty(S.operationIdKey)&&(g=O[S.operationIdKey]),O=g}catch{const g=`[${O}]${f} failed in object parsing in operationDecorator`,S={terminatedReason:32,terminatedReasonCode:bi.CODE.UNKNOWN_ERROR,terminatedReasonSubCode:bi.SUB_CODE.UNKNOWN_FAILURE,errorMessage:g};return Promise.reject(S)}void 0!==R&&C[R]&&(w=C[R]);const D=getOperationHandler(_,g);if(D.logOperation(T,f),S&&S.singular&&D.hasPendingOperation(f))return D.logOperation(T,f,"Not allowed, pending operation exists"),Promise.reject(60);if(S&&S.idempotencyLevel&&D.getRecord(f)>0)switch(D.logOperation(T,f,`Called multiple times, handling operation according to specified policy: idempotency=${S.idempotencyLevel}`),S.idempotencyLevel){case"NoOp":return Promise.resolve();case"Error":return Promise.reject(60)}try{void 0!==P&&C[P]&&_.processCallStartOptions(C[P],T)}catch{const g=`${f} failed in processCallStartOptions`,S={terminatedReason:32,terminatedReasonCode:bi.CODE.UNKNOWN_ERROR,terminatedReasonSubCode:bi.SUB_CODE.UNKNOWN_FAILURE,errorMessage:g};return Promise.reject(S)}const N=!(!S||!S.convertError),execute=()=>"Chained"===M?D.executeChained(I.bind(this,...C),f,O,T,N,w,S):"Sync"===M?D.executeSync(I.bind(this,...C),f,O,T,N,w):D.execute(I.bind(this,...C),f,O,T,N,w,S);if("StartCall"!==f&&"JoinCall"!==f||D.hasPendingOperation("_CallStartOrJoinInitiated")||D.createPendingOperation("_CallStartOrJoinInitiated").catch(noop),S&&S.triggerAttach&&(D.hasPendingOperation("_ElectronSlimcoreReady")||D.createPendingOperation("_ElectronSlimcoreReady").catch(noop)),S&&"Sync"!==S.type){const g=S&&S.waitFor;if(Array.isArray(g))return Promise.all(g.map((g=>g&&D.hasPendingOperation(g)&&D.waitForOperation(g,void 0,T)))).then(execute,execute);if(g&&D.hasPendingOperation(g))return D.waitForOperation(g,void 0,T).then(execute,execute)}return execute()},T},getOperationHandler=(g,f)=>{if(0===f)return g._callOperationHandler;if(1===f)return g._participantOperationHandler;throw new Error("Unsupported operation handler type!")};function getStringHash(g){let f=0;for(let S=0;S<g.length;S++)f=(f<<5)-f+g.charCodeAt(S),f|=0;return f}var Oi=class{constructor(g){this._disposed=!1,this._logger=g.createChild("[ASYNC]"),this._endOperationDeferred=new dt,this._endOperationDeferred.promise.catch((g=>{this._logger.info("Rejected all operations")})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._deferredOperationsWithCauseId={},this._logger=g}registerPromise(g,f){let S=!1;const always=()=>{S=!0};f.then(always,always);const v=this._endOperationDeferred.promise.catch((f=>{if(!S)throw new Error(`Operation ${g} did not complete, reason:${f}`)}));return Promise.race([v,f])}updateOperationId(g,f){this._logger.info(`updateOperationId ${g} ${f}`),Object.keys(this._deferredOperationsWithOperationId).forEach((S=>{S&&this._deferredOperationsWithOperationId[S]&&(this._logger.info(`_deferredOperationsWithOperationId ${S}`),Object.keys(this._deferredOperationsWithOperationId[S]).forEach((v=>{v&&this._deferredOperationsWithOperationId[S][v]&&(this._logger.info(`_deferredOperationsWithOperationId ${v} ${f}`),v===g&&(this._deferredOperationsWithOperationId[S][f]=this._deferredOperationsWithOperationId[S][v],delete this._deferredOperationsWithOperationId[S][v]))})))})),Object.keys(this._deferredOperationsWithCauseId).forEach((S=>{S&&this._deferredOperationsWithCauseId[S]&&(this._logger.info(`_deferredOperationsWithCauseId ${S}`),Object.keys(this._deferredOperationsWithCauseId[S]).forEach((v=>{v&&this._deferredOperationsWithCauseId[S][v]&&(this._logger.info(`_deferredOperationsWithCauseId ${v} ${f}`),v===g&&(this._deferredOperationsWithOperationId[S][f]=this._deferredOperationsWithOperationId[S][v],delete this._deferredOperationsWithOperationId[S][v]))})))}))}createPendingOperation(g,f,S=generateCauseId(),v={}){const C=new dt;C.promise.catch(noop);const _=this.getOperationInfoForLogging(S,g,f);let T;if(this._logger.info(`${_}[creating...]`),this._disposed)return this._logger.info(`${_}[create failed, call is disposed]`),Promise.reject(60);if(f){if(this._deferredOperationsWithOperationId[g]||(this._deferredOperationsWithOperationId[g]={}),this._deferredOperationsWithOperationId[g][f])return this._logger.warn(`${_} Deferred operation with given name and operation id is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${g}/${scrubMriOrOmit(f)}`));this._deferredOperationsWithOperationId[g][f]={deferred:C,causeId:S},this._deferredOperationsWithCauseId[S]||(this._deferredOperationsWithCauseId[S]={}),this._deferredOperationsWithCauseId[S][f]={deferred:C,options:v,operationName:g},T=this._endOperationDeferred.promise.catch((S=>{if(this.hasPendingOperationWithOperationId(g,f))throw new Error(`Operation ${g} ${f} did not complete, reason:${S}`)}))}else{if(this._deferredOperations[g])return this._logger.warn(`${_} Deferred operation with given name is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${g}`));this._deferredOperationsWithCauseId[S]||(this._deferredOperationsWithCauseId[S]={}),this._deferredOperationsWithCauseId[S][""]={deferred:C,options:v,operationName:g},this._deferredOperations[g]={deferred:C,causeId:S},T=this._endOperationDeferred.promise.catch((f=>{if(this.hasPendingOperation(g))throw new Error(`Operation ${g} did not complete, reason:${f}`)}))}return Promise.race([T,C.promise])}hasPendingOperation(g){return!!this._deferredOperations[g]}hasAtleastOneOfPendingOperation(g){for(const f of g)if(this.hasPendingOperation(f))return!0;return!1}hasPendingOperationWithOperationId(g,f){return!(!f||!this._deferredOperationsWithOperationId[g]||!this._deferredOperationsWithOperationId[g][f])}hasPendingOperationWithCauseId(g,f){const S=f||"";return this._deferredOperationsWithCauseId[g]&&!!this._deferredOperationsWithCauseId[g][S]}getPendingOperationWithCauseId(g,f){return this.hasPendingOperationWithCauseId(g,f)?this._deferredOperationsWithCauseId[g][f].deferred.promise:Promise.reject(`[${g}][${f}]: getPendingOperationWithCauseId for given causeId, operationId`)}resolveOperationWithCauseId(g,f,S){const v=f||"";if(this.hasPendingOperationWithCauseId(g,v)){const f=this._deferredOperationsWithCauseId[g][v],C=f.deferred.promise;return f.deferred.resolve(S),this._logger.info(`[${g}][${v}] resolved, result=${getPrintableObject(S)||"void"}`),delete this._deferredOperationsWithCauseId[g][v],C}return Promise.reject(`[${g}][${v}] resolveOperationWithCauseId failed, operation not found`)}rejectOperationWithCauseId(g,f,S){const v=f||"";if(this.hasPendingOperationWithCauseId(g,v)){const f=this._deferredOperationsWithCauseId[g][v],C=f.deferred.promise;return C.catch(noop),f.deferred.reject(S),this._logger.info(`[${g}][${v}] rejected, result=${getPrintableObject(S)||"void"}`),delete this._deferredOperationsWithCauseId[g][v],C}return Promise.reject(`[${g}][${v}] rejectOperationWithCauseId failed, operation not found`)}maybeResolveOperationWithCauseId(g,f,S){this.hasPendingOperationWithCauseId(g,f)?this.resolveOperationWithCauseId(g,f,S).catch((f=>{this._logger.info(`${g}maybeResolveOperationWithCauseId failed, reason=${getPrintableObject(f)}`)})):this._logger.info(`${g}maybeResolveOperationWithCauseId ignored, operation does not exist`)}maybeRejectOperationWithCauseId(g,f,S){this.hasPendingOperationWithCauseId(g,f)?this.rejectOperationWithCauseId(g,f,S).catch(noop):this._logger.info(`${g}maybeRejectOperationWithCauseId ignored, operation does not exist`)}getPendingOperation(g,f,S=generateCauseId()){return!f&&this._deferredOperations[g]?this._deferredOperations[g].deferred.promise:f&&this._deferredOperationsWithOperationId[g]&&this._deferredOperationsWithOperationId[g][f]?this._deferredOperationsWithOperationId[g][f].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(S,g,f)}: Deferred operation with given name and operation does not exist`)}waitForOperation(g,f,S=generateCauseId()){return f&&this.hasPendingOperationWithOperationId(g,f)?this._deferredOperationsWithOperationId[g][f].deferred.promise:this.hasPendingOperation(g)?this._deferredOperations[g].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(S,g,f)}failed=wait failed, operation not found`)}resolveOperation(g,f,S,v=generateCauseId(),C=!1){if(!g)return Promise.reject("Unable to resolve deferred operation with empty name");if(S&&this.hasPendingOperationWithOperationId(g,S)){const v=this._deferredOperationsWithOperationId[g][S],_=v.deferred.promise;return v.deferred.resolve(f),this._logger.info(`${this.getOperationInfoForLogging(v.causeId,g,S)}resolved, result=${getPrintableObject(f)||"void"}`),C||delete this._deferredOperationsWithOperationId[g][S],_}if(this.hasPendingOperation(g)){const v=this._deferredOperations[g],_=this._deferredOperations[g].deferred.promise;return this._deferredOperations[g].deferred.resolve(f),this._logger.info(`${this.getOperationInfoForLogging(v.causeId,g,S)}resolved, result=${getPrintableObject(f)||"void"}`),C||delete this._deferredOperations[g],_}return Promise.reject(`${this.getOperationInfoForLogging(v,g,S)}failed=resolve failed, operation not found`)}rejectOperation(g,f,S,v=generateCauseId()){if(!g)return Promise.reject("Unable to reject deferred operation with empty name");if(S&&this.hasPendingOperationWithOperationId(g,S)){const v=this._deferredOperationsWithOperationId[g][S],C=v.deferred.promise;return C.catch(noop),v.deferred.reject(f),this._logger.info(`${this.getOperationInfoForLogging(v.causeId,g,S)}rejected, reason=${getPrintableObject(f)||"void"}`),delete this._deferredOperationsWithOperationId[g][S],C}if(this.hasPendingOperation(g)){const v=this._deferredOperations[g],C=v.deferred.promise;return C.catch(noop),v.deferred.reject(f),this._logger.info(`${this.getOperationInfoForLogging(v.causeId,g,S)}rejected, reason=${getPrintableObject(f)||"void"}`),delete this._deferredOperations[g],C}return Promise.reject(`${this.getOperationInfoForLogging(v,g,S)}failed=reject failed, operation not found`)}maybeResolveOperation(g,f,S,v=generateCauseId()){const C=this.getOperationInfoForLogging(v,g,S);S&&this.hasPendingOperationWithOperationId(g,S)||this.hasPendingOperation(g)?this.resolveOperation(g,f,S,v).catch((g=>{this._logger.info(`${C}maybeResolveOperation failed, reason=${getPrintableObject(g)}`)})):this._logger.info(`${C}maybeResolveOperation ignored, operation does not exist`)}maybeResolveOperations(g,f,S,v=generateCauseId()){for(const C of g)this.maybeResolveOperation(C,f,S,v)}maybeRejectOperation(g,f,S,v=generateCauseId()){const C=this.getOperationInfoForLogging(v,g,S);S&&this.hasPendingOperationWithOperationId(g,S)||this.hasPendingOperation(g)?this.rejectOperation(g,f,S,v).catch(noop):this._logger.info(`${C}maybeRejectOperation ignored, operation does not exist`)}maybeRejectOperations(g,f,S,v=generateCauseId()){for(const C of g)this.maybeRejectOperation(C,f,S,v)}rejectPendingOperations(g,f=generateCauseId()){this._disposed=!0,this._logger.info(`[${f}]rejectPendingOperations=${JSON.stringify(g)}`),Object.keys(this._deferredOperations).forEach((S=>{this.maybeRejectOperation(S,g,void 0,f),this._deferredOperationsWithOperationId[f]&&delete this._deferredOperationsWithOperationId[f][""]})),Object.keys(this._deferredOperationsWithOperationId).forEach((S=>{Object.keys(this._deferredOperationsWithOperationId[S]).forEach((v=>{this.maybeRejectOperation(S,g,v,f),this._deferredOperationsWithOperationId[f]&&delete this._deferredOperationsWithOperationId[f][v]}))})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._endOperationDeferred.reject(g)}maybeRejectPendingOperationsWithPredicate(g,f=generateCauseId(),S){this._logger.info(`[${f}]rejectPendingOperationsWithPredicate`),Object.keys(this._deferredOperationsWithCauseId).forEach((f=>{Object.keys(this._deferredOperationsWithCauseId[f]).forEach((v=>{const C=this._deferredOperationsWithCauseId[f][v];C&&S(C.operationName,C.options)&&(this.maybeRejectOperation(C.operationName,g,v),this.maybeRejectOperationWithCauseId(f,v,g))}))}))}getOperationInfoForLogging(g,f,S=""){const v=S?`[${scrubMriOrOmit(S)}]`:"";return`[${g.substring(0,8)}][${f}]${v}`}},Di=M,Ni=class{constructor(g){this._logger=g,this._promise=Promise.resolve(void 0),this._actionQueue=[]}chainPromise(g,f,S=generateCauseId(),v=!1){const C=Date.now(),_=(("function"==typeof f?f():f)||"").toString();this._actionQueue.push(_),this._logger.info(`[${S}][${_}]enqueueing, queue=[${this._actionQueue}], reset=${v}`);const removeFromQueue=()=>{this._actionQueue=this._actionQueue.filter((g=>g!==_))};return v&&this.reset(S),this._promise=this._promise.catch(Di.noop).then((()=>{const f=Date.now()-C;return this._logger.info(`[${S}][${_}]begin, delayMs=${f}`),g()})),this._promise.then((()=>{removeFromQueue();const g=Date.now()-C;this._logger.info(`[${S}][${_}]success, durationMs=${g}`)}),(g=>{removeFromQueue();const f=Date.now()-C;this._logger.warn(`[${S}][${_}]failed=${safeJsonStringify(g)}, durationMs=${f}`)})),this._promise}reset(g){this._logger.info(`[${g}] resetting`),this._promise=Promise.resolve(void 0)}};function isSessionTerminatedReason(g){return!!g?.terminatedReasonCode}function convertFromTerminatedReasonFormat(g){return isSessionTerminatedReason(g)?{code:g.terminatedReasonCode,subCode:g.terminatedReasonSubCode,phrase:g.errorMessage}:g}function isTransactionEnd(g){return!!g?.code}function getRejectTransactionEnd(g,f){let S;return S=isTransactionEnd(g)?g:{code:499,subCode:void 0!==f?f:0,phrase:"string"==typeof g?g:getPrintableObject(g)},S}function getSuccessTransactionEnd(){return{code:0}}var ki=class{constructor(){this.msElapsed=0,this.isPaused=!1,this._startTime=(new Date).getTime(),this.pause=()=>{this.isPaused||(this.msElapsed+=(new Date).getTime()-this._startTime,this.isPaused=!0)},this.resume=()=>{this.isPaused&&(this.isPaused=!1,this._startTime=(new Date).getTime())},this.duration=()=>this.isPaused?this.msElapsed:this.msElapsed+(new Date).getTime()-this._startTime,this.durationInMinutes=()=>{const g=this.duration()/6e4;return Math.ceil(g)},this.durationInSeconds=()=>{const g=this.duration()/1e3;return Math.ceil(g)}}get startTime(){return this._startTime}};function build2(){return new ki}var Li=class extends Oi{constructor(g,f,S,v,C){super(g),this.callTelemetry=f,this._ecsConfig=S,this._publishCallback=v,this._preconditionFunction=C,this._record={},this.logSuccess=(g,f,S)=>{this._logger.info(`${g} execution succeeded, result=${f?getPrintableObject(f):"void"}, time=${S.duration()}`)},this.logFailure=(g,f,S)=>{this._logger.info(`${g} execution failed, reason=${this.stringifyForLogging(f)}, time=${S.duration()}`)},this.logTimeout=(g,f,S)=>{this._logger.info(`${g} execution timed out, reason=${this.stringifyForLogging(f)}, time=${S.duration()}`)},this.stringifyForLogging=g=>{let f;if(g instanceof Error)f=g.toString()||"Unknown Error";else try{f=JSON.stringify(g)}catch(g){f="Unable to stringify data"}return f},this.convertToTransactionEndIfErrorOrString=(g,f,S)=>{if(this._logger.info(`ecsEnableErrorConversion in operationHandler is: ${this._ecsConfig&&this._ecsConfig.enableErrorConversion}`),f&&this._ecsConfig&&this._ecsConfig.enableErrorConversion&&("string"==typeof g||g instanceof Error)){const f=getRejectTransactionEnd(g);return this._logger.info(`${S} Error converted from ${g} to ${getPrintableObject(f)}`),f}return g},this._logger=g.createChild("[Operation]"),this._chainedPromise=new Ni(this._logger.createChild("[Chained]"))}resetOperationChain(g){this._chainedPromise.reset(g)}executeSync(g,f,S,v=generateCauseId(),C,_){const T=this.getOperationInfoForLogging(v,f,S),I=build2();this._logger.info(`${T}API calledSync`);const b=this.callTelemetry.recordOperation(f,v,S,_);let A;try{this._setRecord(f),A=g(),b.recordSuccess(A,v),this.logSuccess(T,A,I)}catch(g){const f=this.convertToTransactionEndIfErrorOrString(g,C,T);b.recordFailure(f,v),this.logFailure(T,f,I)}return A}async executeChained(g,f,S,v=generateCauseId(),C,_,T){return this.checkPendingOperationAndExecute(g,!0,f,S,v,C,_,T)}async execute(g,f,S,v=generateCauseId(),C,_,T){return this.checkPendingOperationAndExecute(g,!1,f,S,v,C,_,T)}logOperation(g,f,...S){const v=S.length&&S.map((g=>this.stringifyForLogging(scrubMriOrOmit(g))));this._logger.info(`[${g.substring(0,8)}][${f}]API called, ${v?`with args=${v}`:""}`)}rejectPendingOperations(g,f=generateCauseId(),S){if(S){for(const g of Object.keys(this._deferredOperations))this.callTelemetry.maybeRecordOperationFailure(g,S,void 0,f);for(const g of Object.keys(this._deferredOperationsWithOperationId))for(const v of Object.keys(this._deferredOperationsWithOperationId[g]))this.callTelemetry.maybeRecordOperationFailure(g,S,v,f)}super.rejectPendingOperations(g,f)}maybeRejectOperations(g,f,S,v=generateCauseId(),C){if(C)for(const f of g)this.callTelemetry.maybeRecordOperationFailure(f,C,void 0,v);super.maybeRejectOperations(g,f,S,v)}checkPendingOperationAndExecute(g,f,S,v,C=generateCauseId(),_,T,I){const b=this.getOperationInfoForLogging(C,S,v);let A=null,P=null;return this.hasPendingOperationWithOperationId(S,v)||this.hasPendingOperation(S)?(this._logger.info(`${b}already pending, returning existing operation`),A=this.waitForOperation(S,v,C)):P=this.createPendingOperation(S,v,C,I),f?(this._logger.info(`${b}chained`),this._chainedPromise.chainPromise((()=>A||this.executeInternal(P,C,g,S,v,_,T,I)),S,C)):A||this.executeInternal(P,C,g,S,v,_,T,I)}_setRecord(g){this._record.hasOwnProperty(g)||(this._record[g]=0),this._record[g]+=1}getRecord(g){return this._record[g]}_recordTelemetryTimeoutAndPublish(g,f,S,v,C,_,T){const I=g||60;return window.setTimeout((()=>{if(!this._publishCallback)return void this._logger.warn(`${C} is marked to publish telemetry but no publish callback is defined.`);if(!this.hasPendingOperationWithOperationId(v,T)&&!this.hasPendingOperation(v))return;const g=new Error(`${C} execution did not complete before telemetry timeout of ${I}s.`);this.logTimeout(C,g,_),this.callTelemetry.maybeRecordOperationTimeout(v,g,T,S),this._publishCallback(f),this.callTelemetry.removeRecordedEvent(f)}),1e3*I)}_instantTelemetryPublish(g,f){this._publishCallback?(this._publishCallback(f),this.callTelemetry.removeRecordedEvent(f)):this._logger.warn(`${g} is marked to publish telemetry but no publish callback is defined.`)}parseInstantTelemetryParameters(g){let f,S=!1;return g&&(S=g.enableInstantTelemetry,f=g.telemetryTimeout),[S,f]}async executeInternal(g,f,S,v,C,_,T,I){const b=this.getOperationInfoForLogging(f,v,C);this._logger.info(`${b} executing operation...`);const A=build2(),P=this.callTelemetry.recordOperation(v,f,C,T),[R,M]=this.parseInstantTelemetryParameters(I);try{let g;this._setRecord(v),R&&(g=this._recordTelemetryTimeoutAndPublish(M,P,f,v,b,A,C)),I?.preconditionTags?.length&&this._preconditionFunction&&this._preconditionFunction(v,I.preconditionTags);const _=await S();g&&clearTimeout(g),this.callTelemetry.maybeRecordOperationSuccess(v,_,C),this.logSuccess(b,_,A),this.maybeResolveOperation(v,_,C,f)}catch(g){const S=this.convertToTransactionEndIfErrorOrString(g,_,b);this.callTelemetry.maybeRecordOperationFailure(v,convertFromTerminatedReasonFormat(S),C),this.logFailure(b,S,A),this.maybeRejectOperation(v,S,C,f)}return R&&this._instantTelemetryPublish(b,P),g}getEcsConfig(){return this._ecsConfig}},Fi={Cancel:487,Reject:603,NoNgcEndpoint:480,Forbidden:403,PreconditionFailed:412,Success:0,CallRedirected:302,BadRequest:400,NotFound:404,NotAcceptable:406,Timeout:408,Conflict:409,MediaError:410,ConfParticipantCountLimitReached:413,CallAccepted:450,CallForwarded:451,CallForwardedToVoicemail:452,P2pRejectCall:453,P2pFallbackForScreensharing:460,P2pFallbackDueToGroupCall:461,CallLegEndedOnService:470,CallDoesNotExist:481,NotAcceptableHere:488,NetworkError:490,GlareError:491,SkypeTokenError:495,LocalHttpStackError:496,UnknownError:497,LocalError:498,InternalServerError:500,CallModalityFailure:580,ServiceUnavailable:503},xi={Success:0,CallRedirectedSuccess:3020,InsufficientCapabilities:5204,PolicyRestriction:5448,UserBlocked:10005,MaxLobbyParticipantLimitReached:5807,MaxParticipantLimitReached:5808,MaxParticipantLimitReached2:5817,SharingStolenError:10029,DowngradeToStreamingClient:3099,MediaDropDuringConnect:3100,MediaDropAfterConnect:3101,MediaAnswerProcessingError:3102,MediaFinalAnswerProcessingError:3103,MediaOfferTimeout:3104,MediaFinalAnswerTimeout:3105,MediaOfferNull:3106,MediaAudioDeviceError:3107,MediaRenegotiationError:3108,MediaPermissionError:3109,MediaUnknownError:3110,MediaOfferProcessingError:3111,MediaWhiteListingIssue:3112,MediaMuteMicrophoneError:3113,MediaMuteSpeakerError:3114,MediaUnmuteMicrophoneError:3115,MediaUnmuteSpeakerError:3115,AttachActionFailed:4103,AttachFailed:4105,PreheatedCallTimedout:4113,RemovedFromConversation:5e3,DeniedInLobby:5854,RemovedFromCall:5300,TimedOutInLobby:5855,AnonymousJoinDisabledByPolicy:5723,B2bJoinDisabledByPolicy:5724,NoLobbyForBroadcastJoin:5354,NotAllowedDueToInformationBarrier:5810,TeamParkPolicyDisabled:10193,BroadcastLimitReached:800100,Suspended:58e4},Ui={[Fi.Success]:1,[Fi.Cancel]:12,[Fi.Reject]:10,[Fi.NoNgcEndpoint]:2,[Fi.Timeout]:6,[Fi.CallAccepted]:30,[Fi.CallRedirected]:75,[Fi.NotFound]:24,[Fi.CallDoesNotExist]:46,[Fi.NotAcceptable]:5,[Fi.BadRequest]:5,[Fi.MediaError]:4,[Fi.ConfParticipantCountLimitReached]:59,[Fi.CallModalityFailure]:4,[Fi.NetworkError]:3,[Fi.LocalHttpStackError]:31,[Fi.LocalError]:25,[Fi.CallForwarded]:27,[Fi.CallForwardedToVoicemail]:28,[Fi.SkypeTokenError]:29,[Fi.InternalServerError]:7,[Fi.Conflict]:7,[Fi.GlareError]:7,[Fi.CallLegEndedOnService]:7,[Fi.NotAcceptableHere]:26,[Fi.UnknownError]:32,[Fi.Forbidden]:8,[Fi.PreconditionFailed]:65},Vi={9401:33,9422:33,6102:1,6423:14,9402:14,9432:14,6519:3,9403:15,9410:36,9411:37,1e3:2,9407:17,13430:18,6009:19,10484:19,10604:19,10404:19,10420:19,10403:20,17401:20,10408:9,10486:11,10600:11,10686:11,10487:21,10500:3,10501:3,10502:3,10503:3,10504:3,10480:22,10482:22,10603:10,13406:23,13416:23},Bi={500:39,403:41,404:42,480:40},Hi={INCOMING_SKYPE_NGC_CALL:107,INCOMING_SKYPE_NGC_GVC_CALL:109,INCOMING_PSTN_NGC_CALL:111,INCOMING_SCREENSHARE_WITH_CHAT:119,INCOMING_CALLQUEUE_SUPERVISOR_CONTENT:125,INCOMING_TFL_TFW_CALL:126},$i={SHARED_LINE_CALL_RECORD:121,SHARED_LINE_V2_CALL_RECORD:123,MEETING_STARTED_NOTIFICATION:128},ji={LOG_UPLOAD_EVENT:120},Gi={Unknown:"CallEndReasonUnknown",MediaError:"CallEndReasonMediaError",MediaOfferTimeout:"CallEndReasonMediaOfferTimeout",MediaFinalAnswerTimeout:"CallEndReasonMediaFinalAnswerTimeout",MediaAnswerError:"CallEndReasonMediaAnswerError",MediaFinalAnswerError:"CallEndReasonFinalAnswerError",MediaPermissionError:"CallEndReasonMediaPermissionError",MediaRenegotiationError:"CallEndReasonRenegotiationError",MediaDropDuringConnect:"CallEndReasonMediaDropDuringConnectError",MediaDropAfterConnect:"CallEndReasonMediaDropAfterConnectError",MediaOfferProcessingError:"CallEndReasonMediaOfferProcessingError",DowngradeToStreamingClient:"DowngradeToStreamingClient",IncompatibleOffer:"CallEndReasonIncompatibleOffer",MediaWhiteListingIssue:"MediaWhitelistingIssue",AudioDeviceError:"CallEndReasonAudioDeviceError",AttachFailed:"CallEndReasonAttachFailed",BadNotificationPayload:"CallEndReasonBadNotificationPayload",RetargetNotSupported:"RetargetNotSupported",CallEndReasonLocalUserInitiated:"CallEndReasonLocalUserInitiated",EndedByRemoteEndpoint:"EndedByRemoteEndpoint",CallEndReasonRedirected:"CallEndReasonRedirected",CallEndReasonVDIdisconnect:"CallEndReasonVDIdisconnect",CallEndReasonSuspended:"CallEndReasonSuspended"},qi=(g=>(g.GetSignalingMediaTypes="GetSignalingMediaTypes",g.CallStart="CallStart",g.WaitForAnswer="WaitForAnswer",g.WaitForConnect="WaitForConnect",g.Accept="Accept",g))(qi||{}),Wi=(g=>(g.InitializeMediaSession="InitializeMediaSession",g.UpdateMediaModalities="UpdateMediaModalities",g.CreateOffer="CreateOffer",g.CreateAnswer="CreateAnswer",g.ProcessAnswer="ProcessAnswer",g.GetSignalingMediaTypes="GetSignalingMediaTypes",g.MuteUnmute="MuteUnmute",g.MuteUnmuteSpeakers="MuteUnmuteSpeakers",g.StartVideoSafe="StartVideoSafe",g.CompleteNegotiation="CompleteNegotiation",g.MuteInput="MuteInput",g.MuteOutput="MuteOutput",g.UnmuteInput="UnmuteInput",g.UnmuteOutput="UnmuteOutput",g.evaluateEndpointStatesForAccept="evaluateEndpointStatesForAccept",g.handleEndpointStatesForAccept="handleEndpointStatesForAccept",g))(Wi||{}),zi=(g=>(g.InitializeMediaSession="InitializeMediaSession",g.ProcessOffer="ProcessOffer",g.ProcessOfferedModalities="ProcessOfferedModalities",g.TrySendingProvisionalAnswer="TrySendingProvisionalAnswer",g))(zi||{}),Ki=M,Ji=__toESM2(M),Yi=__toESM2(M),Qi=__toESM2(ye()),Xi={Success:"Success",ExpectedError:"ExpectedError",UnexpectedClientError:"UnexpectedClientError",UnexpectedServerError:"UnexpectedServerError"},Zi={INCOMING_MESSAGE_ORIGIN:{TROUTER:"Trouter",BROKER:"Broker"},INVITATION_TYPE:{NUDGE:"nudge"},KNOWN_PAYLOAD_ENCODINGS:{GZIP:!0},WEBRTC_NOTIFICATION_TYPE:{CONTROL_VIDEO_STREAMING:"ControlVideoStreaming",DOMINANT_SPEAKER_INFO:"DominantSpeakerInfo",CSRC_INFO:"CsrcInfo"},PARTICIPANT_AUDIO_STATE:{CONNECTING:"Connecting",RINGING:"Ringing",CONNECTED:"Connected",OTHER:"Other"},HEADERS:{MESSAGE_ID:"X-Microsoft-Skype-Message-ID",ORIGINAL_MESSAGE_ID:"X-Microsoft-Skype-Original-Message-ID",CONTENT_ENCODING:"X-Microsoft-Skype-Content-Encoding",CORRELATION_ID:"X-Microsoft-Skype-Chain-ID",CONTENT_SHARING_CORRELATION_ID:"X-Microsoft-Skype-ContentSharing-Chain-ID",CLIENT_USER_AGENT:"X-Microsoft-Skype-Client",SKYPE_TOKEN:"X-Skypetoken",AUTHORIZATION:"Authorization",BEARER_KEYWORD:"Bearer",AAD_KEYWORD:"Aad",CAE_KEYWORD:"Cae",SKYPE_KEYWORD:"Skype",CACHE_SKYPE_TOKEN:"X-CacheSkypeToken",AUTHENTICATE:"www-authenticate",TOKEN_MIGRATION:"X-MS-Migration",BROKER_USE_BATCHING_HEADER_NAME:"X-UseBatching",PARTICIPANT_ID:"X-Microsoft-Skype-Participant-ID",CONTENT_TYPE:"Content-Type",RING:"MS-Teams-Ring",REGION:"MS-Teams-Region",PARTITION:"MS-Teams-Partition"},KNOWN_BOTS:{VOICEMAIL_BOT_ID:"28:14524421-25b4-403a-a0f7-e62d4379cabc"},HTTP_STACK_ERROR:{NONE:0,CANNOT_CONNECT:7,REQUEST_TIMEOUT:10,ATTEMPT_TIMEOUT:30,REQUEST_ABORTED:16,ATTEMPT_ABORTED:31,ABORTED_OTHER_ATTEMPT_SUCCESSFUL:32},HTTP_STATUS_CODES:{UNKNOWN:0,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,FORBIDDEN:403,PRECONDITION_FAILED:412,UNPROCESSABLE_ENTITY:422,NETWORK_ERROR:490,SKYPE_TOKEN_ERROR:495,OFFLINE:496,TIMEOUT:498,ABORTED:498,OTHER:499,INTERNAL_SERVER_ERROR:500,CONFLICT:409,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504},CALL_END_SKYPE_TOKEN_ERROR:{code:495,subCode:4507,phrase:"CallEndReasonSkypeTokenFetchError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_TOKEN_TIMEOUT_ERROR:{code:499,subCode:3119,phrase:"CallEndReasonTokenFetchTimeout",resultCategories:[Xi.UnexpectedClientError]},CALL_END_UNSUPPORTED_TOKEN_ERROR:{code:499,subCode:3126,phrase:"CallEndReasonUnsupportedTokenError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_TOKEN_ERROR:{code:499,subCode:3127,phrase:"CallEndReasonTokenFetchError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED:{code:499,subCode:3128,phrase:"CallEndReasonTokenTimeoutInterActvityRequired",resultCategories:[Xi.UnexpectedClientError]},CALL_END_LOCAL_HTTP_STACK_ERROR:{code:496,subCode:4520,phrase:"LocalHTTPStackError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_UNKNOWN_ERROR:{code:497,subCode:3121,phrase:"CallEndReasonUnknownError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_NETWORK_ERROR:{code:490,subCode:4502,phrase:"CallEndReasonNetworkError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_DNS_HOST_NAME_RESOLVE_ERROR:{code:490,subCode:4522,phrase:"CallEndReasonDnsHostNameResolveError",resultCategories:[Xi.UnexpectedClientError]},CALL_END_LOCAL_DECLINE:{code:486,subCode:4508,phrase:"LocalDecline",resultCategories:[Xi.Success]},RESOURCE_NOT_FOUND_ERROR:{code:404,subCode:404,phrase:"ResourceNotFound",resultCategories:[Xi.ExpectedError]},CALL_STATUS:{IDLE:"Idle",RINGING:"Ringing",CONNECTING:"Connecting",CONNECTED:"Connected",CONNECTED_FOR_ROSTER_ONLY:"ConnectedForRosterOnly",LOCAL_TERMINATED:"LocalTerminated",REMOTE_TERMINATED:"RemoteTerminated"},MEDIA_TYPES:{AUDIO:"Audio",VIDEO:"Video",SCREEN_SHARER:"ScreenSharer",SCREEN_VIEWER:"ScreenViewer"},MUTE_SCOPE:{MYSELF:"Myself",EVERYONE_ELSE:"EveryoneElse",SPECIFIED_PARTICIPANTS:"SpecifiedParticipants"},URL_BASE:{CALLAGENT:"callAgent"},LINKS:{HANGUP:"hangup",MEDIA_REJECTION:"mediaRejection",MEDIA_ANSWER:"mediaAnswer",MEDIA_RENEGOTIATION:"mediaRenegotiation",ACCEPT:"accept",ATTACH:"attach",REJECT:"reject",REDIRECT:"redirect",REPLACE:"replace",TRANSFER:"transfer",NEW_OFFER:"newOffer",TRANSFER_ACCEPTANCE:"transferAcceptance",TRANSFER_COMPLETION:"transferCompletion",CONVERSATION_CONTROLLER:"conversationController",ADD_PARTICIPANT:"addParticipant",ADD_PARTICIPANTS_AND_MODALITY:"addParticipantsAndModality",LEAVE:"leave",NOTIFICATION_LINKS:"notificationLinks",REMOVE_PARTICIPANT:"removeParticipant",KEEPALIVE:"keepAlive",ADD_MODALITY:"AddModality",REMOVE_MODALITY:"RemoveModality",CONTENT_SHARING_CONTROLLER:"contentSharingController",CONTENT_SHARING_TAKE_CONTROL:"contentSharingTakeControl",CONTENT_SHARING_UPDATE_SESSION_STATE:"contentSharingUpdateSessionState",CONTENT_SHARING_UPDATE_PARTICIPANT_STATE:"contentSharingUpdateParticipantState",CONTENT_SHARING_NOTIFICATION_LINKS:"contentSharingNotificationLinks",CONTENT_SHARING_LEAVE:"contentSharingLeave",MUTE:"mute",UNMUTE:"unmute",ADMIT:"admit",ADMIT_ALL:"admitAll",CONTROL_VIDEO_STREAMING:"controlVideoStreaming",APPLY_CHANNEL_PARAMETERS:"applyChannelParameters",UPDATE_ENDPOINT_STATE:"updateEndpointState",UPDATE_ENDPOINT_METADATA:"updateEndpointMetadata",LMC_NOTIFICATION_LINKS:"lmcNotificationLinks",UPDATE_PARTICIPANT_ROLE:"updateParticipantRole",PUBLISH_STATE:"publishState",REMOVE_STATE:"removeState",UPDATE_MEETING_SETTINGS:"updateMeetingSettings",SEARCH_PARTICIPANTS:"searchParticipants",GET_ALL_PARTICIPANTS:"getAllParticipants",PARK:"park",UNPARK:"unpark",UPDATE_MEETING_LIVE_STATE:"updateMeetingLiveState",UPDATE_MEETING_GROUPS:"updateMeetingGroups",SET_MEETING_LAYOUT:"setMeetingLayout",UPDATE_PARTICIPANT_INTERPRETATION_STATE:"updateParticipantInterpretationState",JOIN_MEETING_GROUP:"joinMeetingGroup",LEAVE_MEETING_GROUP:"leaveMeetingGroup",SEND_MESSAGE:"sendMessage",UPDATE_PARTICIPANTS_PROPERTIES:"updateParticipantsProperties",UPDATE_MEDIA_DESCRIPTIONS:"updateMediaDescriptions",UPDATE_MEETING_STATES:"updateMeetingStates",UPDATE_MONITOR_SESSION:"monitor"},CONTENT_TYPE:{JSON:"application/json",SDP:"application/sdp"},TROUTER_EVENT_TYPE:{SKYPE_SKYPE_CALL:107,LYNC_SKYPE_CALL:105},MISC:{CONVERSATION:"conversation",LOBBY_CALL_CONTROLLER:"lobby",LOBBY_PARTICIPANT_STATE:"lobby"},SIGNALING_FSM_STATE:{IDLE:"Idle",INCOMING:"Incoming",WAITING_CALL_ACCEPTANCE_ACK:"WaitingCallAcceptanceAck",OUTGOING:"Outgoing",CONNECTED:"Connected",OUTGOING_FOR_ROSTER_ONLY:"OutgoingForRosterOnly",CONNECTED_FOR_ROSTER_ONLY:"ConnectedForRosterOnly"},MEDIA_RENEGOTIATION_FSM_STATE:{IDLE:"Idle",CALL_CONNECTED:"Connected",INCOMING_RENEGOTIATION:"IncomingRenegotiation",OUTGOING_RENEGOTIATION:"OutgoingRenegotiation",RENEGOTIATION_GLARE:"RenegotiationGlare"},CONTENT_SHARING_FSM_STATE:{IDLE:"Idle",CONTENT_SHARING_START_INITIATED:"ContentSharingStartInitiated",CONTENT_SHARING_JOIN_INITIATED:"ContentSharingJoinInitiated",CONTENT_SHARING_LEAVE_INITIATED:"ContentSharingLeaveInitiated",CONTENT_SHARING_DELETE_INITIATED:"ContentSharingDeleteInitiated",CONTENT_SHARING_CONNECTED:"ContentSharingConnected"},TIMEOUT_OPERATIONS:{ADD_PARTICIPANT:"AddParticipant",NUDGE_PARTICIPANT:"NudgeParticipant",REMOVE_PARTICIPANT:"RemoveParticipant",ADMIT_PARTICIPANT:"AdmitParticipant",ADMIT:"Admit",CALL_REDIRECT:"CallRedirect",CALL_ME_BACK:"CallMeBack",INCOMING_CALL_ESTABLISHMENT:"IncomingCallEstablishment",OUTGOING_CALL_ESTABLISHMENT:"OutgoingCallEstablishment",MEDIA_ANSWER:"MediaAnswer",MEDIA_ANSWER_ACKNOWLEDGEMENT:"MediaAnswerAcknowledgement",ADD_MODALITY:"AddModality",UNMUTE:"Unmute",UPDATE_MEETING_ROLE:"UpdateMeetingRole",MAX_PREAHEATED_TIMEOUT:"MaxPreheateadTimeout",PARK_COMPLETION:"ParkCompletion",UNPARK_COMPLETION:"UnparkCompletion",UPDATE_MEETING_LIVE_STATE_COMPLETION:"UpdateMeetingLiveStateCompletion",UPDATE_MEETING_GROUPS_COMPLETION:"UpgradeMeetingGroupsCompletion",UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION:"UpdateParticipantInterpretationStateCompletion",UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION:"UpdateParticipantsPropertiesCompletion",JOIN_MEETING_GROUP_COMPLETION:"JoinMeetingGroupCompletion",LEAVE_MEETING_GROUP_COMPLETION:"LeaveMeetingGroupCompletion",SET_MEETING_LAYOUT_COMPLETION:"SetMeetingLayoutCompletion",SEND_MESSAGE_COMPLETION:"SendMessageCompletion",DISABLE_PREHEAT_ASYNC_TIMEOUT:"DisablePreheatAsyncTimeout",UPDATE_MEETING_STATES_COMPLETION:"UpdateMeetingStatesCompletion",UPDATE_MONITOR_SESSION_COMPLETION:"UpdateMonitorSessionCompletion"},TIMEOUT_VALUES_IN_SECONDS:{ADD_PARTICIPANT_TIMEOUT:130,REMOVE_PARTICIPANT_TIMEOUT:60,INCOMING_CALL_ESTABLISHMENT_TIMEOUT:75,OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:90,LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:185,MEDIA_ANSWER_TIMEOUT:35,MEDIA_ANSWER_ACKNOWLEDGEMENT_TIMEOUT:15,ADD_MODALITY_TIMEOUT:65,UNMUTE_TIMEOUT:35,ADMIT_PARTICIPANT_TIMEOUT:210,ADMIT_TIMEOUT:60,UPDATE_MEETING_ROLE_TIMEOUT:15,NUDGE_PARTICIPANT_TIMEOUT:60,CALL_ME_BACK_TIMEOUT:120,MAX_PREAHEATED_TIMEOUT:90,PARK_COMPLETION_TIMEOUT:45,UNPARK_COMPLETION_TIMEOUT:45,UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT:45,UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT:45,SET_MEETING_LAYOUT_COMPLETION_TIMEOUT:45,UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION_TIMEOUT:45,UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION_TIMEOUT:45,JOIN_MEETING_GROUP_COMPLETION_TIMEOUT:45,LEAVE_MEETING_GROUP_COMPLETION_TIMEOUT:45,CONVERSATION_KEEP_ALIVE_TIMEOUT:2700,TOKEN_REQUIRED_TIMEOUT:20,SEND_MESSAGE_COMPLETION_TIMEOUT:15,DISABLE_PREHEAT_TIMEOUT:45,UPDATE_MEETING_STATES_COMPLETION_TIMEOUT:45,UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT:45},CALL_END_CODE:{REJECT:603,SUCCESS:0,CALL_REDIRECTED:302,CANCEL:487,TIMEOUT:408,SERVICE_UNAVAILABLE:500,BAD_REQUEST:406,NO_NGC_ENDPOINT:480,P2P_FALLBACK_FOR_SCREENSHARING:460,CONFLICT:409,MEDIA_ERROR:410,CONF_PARTICIPANT_COUNT_LIMIT_REACHED:413,CALL_DOES_NOT_EXIST:481,CALL_ACCEPTED:450,CALL_FORWARDED:451,CALL_FORWARDED_TO_VOICEMAIL:452,P2P_REJECT_CALL:453,P2P_FALLBACK_DUE_TO_GROUPCALL:461,CALL_LEG_ENDED_ON_SERVICE:470,NOT_ACCEPTABLE_HERE:488,NETWORK_ERROR:490,UNKNOWN_ERROR:497,LOCAL_ERROR:498,CALL_MODALITY_FAILURE:580,ATC_CONTROLLER_FAILURE:581,CVA_CONTROLLER_FAILURE:586,GLARE_ERROR:491,NOT_FOUND:404,SKYPE_TOKEN_ERROR:495,LOCAL_HTTP_STACK_ERROR:496,HTTP_OTHER_ERROR:499,DECODING_FAILED:407,NOT_AUTHORIZED:403,BAD_SERVICE_RESPONSE:400},CALL_END_SUB_CODE:{SUCCESS:0,CALL_REDIRECTED_SUCCESS:3020,DOWNGRADE_TO_STREAMING_CLIENT:3099,MEDIA_DROP_DURING_CONNECT:3100,MEDIA_DROP_AFTER_CONNECT:3101,MEDIA_ANSWER_PROCESSING_ERROR:3102,MEDIA_FINAL_ANSWER_PROCESSING_ERROR:3103,MEDIA_OFFER_TIMEOUT:3104,MEDIA_FINAL_ANSWER_TIMEOUT:3105,MEDIA_OFFER_NULL:3106,MEDIA_AUDIO_DEVICE_ERROR:3107,MEDIA_RENEGOTIATION_ERROR:3108,MEDIA_PERMISSION_ERROR:3109,MEDIA_UNKNOWN_ERROR:3110,MEDIA_OFFER_PROCESSING_ERROR:3111,MEDIA_WHITELISTING_ISSUE:3112,MEDIA_MUTE_MICROPHONE_ERROR:3114,MEDIA_MUTE_SPEAKER_ERROR:3115,MEDIA_UNMUTE_MICROPHONE_ERROR:3116,MEDIA_UNMUTE_SPEAKER_ERROR:3117,MEDIA_GLARE_ERROR:3118,CONVERSATION_TERMINATION_UNKNOWN_ERROR:3121,CONVERSATION_NOTIFICATION_TIMEOUT:3125,CALL_NOT_ATTEMPTED:4500,CONV_URL_NOT_SET:4501,FAILED_TO_REACH_SERVICE:4502,PLACE_CALL_FAILED:4503,ATTACH_CALL_FAILED:4504,BAD_NOTIFICATION_PAYLOAD:4505,CALL_ESTABLISHMENT_TIMEOUT:4506,SKYPE_TOKEN_ERROR:4507,CONVERSATION_RESOLUTION_CONFLICT:5704,CALL_PARTICIPANT_REMOVAL_TIMEOUT:4507,UNMUTE_REQUEST_TIMEOUT:4509,UNMUTE_REQUEST_REJECTED:4510,CONFLICT_IN_NG:4090,CONFLICT_WITH_P2P:4091,CONVERSATION_END_RECEIVED_FROM_SERVICE:4100,TRANSFER_COMPLETE_TIMEOUT:4101,ATTACH_TO_NON_EXISTENT_CALL:4102,ATTACH_ACTION_FAILED:4103,ATTACH_FAILED:4105,CONVERSATION_ESTABLISHMENT_FAILED:4106,BEFORE_CONNECT:4107,AFTER_CONNECT:4108,AFTER_ACCEPT:4109,TROUTER_CONNECTION_DROPPED:4111,DUE_TO_CALL_ASSIMILATION:4112,PREHEATED_CALL_TIMEDOUT:4113,UNPARK_COMPLETION_TIMEOUT:4114,PARK_COMPLETION_TIMEOUT:4115,UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT:4116,UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT:4117,SET_MEETING_LAYOUT_COMPLETION_TIMEOUT:4118,UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT:4119,JOIN_MEETING_GROUP_TIMEOUT:4120,LEAVE_MEETING_GROUP_TIMEOUT:4121,UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT:4122,UPDATE_MEETING_STATES_COMPLETION_TIMEOUT:4123,UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT:4124,MISSING_REQUEST_URI:4511,MISC_ERROR:4512,LOCAL_HTTP_STACK_ERROR:4520,BEACON:4521,DNS_HOST_NAME_RESOLVE_ERROR:4522,CONVERSATION_ENDED_NO_NEW_OWNER_FOUND:5014,UNABLE_TO_GENERATE_MEETUP_ID:5015,UPDATE_MEETING_ROLE_REJECTED:5651,UPDATE_MEETING_ROLE_TIMEOUT:5652,PUBLISH_STATE_LINK_MISSING:5653,PUBLISH_STATE_INVALID_CONTENT:5654,PUBLISH_STATE_INVALID_SERVICE_RESPONSE:5655,REMOVE_STATE_LINK_MISSING:5656,REMOVE_STATE_MISSING_ARGUMENTS:5657,UPDATE_MEETING_SETTINGS_LINK_MISSING:5658,UPDATE_MEETING_SETTINGS_MISSING_ARGUMENTS:5659,ADMIT_ALL_LINK_MISSING:5660,ADMIT_TIMEOUT:5661,CALL_ACCEPTANCE_INVALID_SERVICE_RESPONSE:5670,ROSTER_HANDLING_INVALID_SERVICE_RESPONSE:5671,SEARCH_PARTICIPANTS_LINK_MISSING:5672,SEARCH_PARTICIPANTS_INVALID_SERVICE_RESPONSE:5673,GET_ALL_PARTICIPANTS_LINK_MISSING:5674,GET_ALL_PARTICIPANTS_INVALID_SCOPE:5675,GET_ALL_PARTICIPANTS_INVALID_SERVICE_RESPONSE:5676,PARK_UNPARK_TYPE_MISSING:5680,PARK_UNPARK_V2_DISABLED:5682,UPDATE_PARTICIPANTS_PROPERTIES_LINK_MISSING:5683,DISABLE_PREHEAT_TIMEOUT:5684,CALL_ENDED_BY_PLATFORM_AGENT:7e3,CONVERSATION_TERMINATION_INTERACTION_REQUIRED:71014},CALL_END_PHRASE:{UNKNOWN:"CallEndReasonUnknown",MEDIA_ERROR:"CallEndReasonMediaError",MEDIA_OFFER_TIMEOUT:"CallEndReasonMediaOfferTimeout",MEDIA_FINAL_ANSWER_TIMEOUT:"CallEndReasonMediaFinalAnswerTimeout",MEDIA_ANSWER_ERROR:"CallEndReasonMediaAnswerError",MEDIA_FINAL_ANSWER_ERROR:"CallEndReasonFinalAnswerError",MEDIA_PERMISSION_ERROR:"CallEndReasonMediaPermissionError",MEDIA_RENEGOTIATION_ERROR:"CallEndReasonRenegotiationError",MEDIA_DROP_DURING_CONNECT:"CallEndReasonMediaDropDuringConnectError",MEDIA_DROP_AFTER_CONNECT:"CallEndReasonMediaDropAfterConnectError",MEDIA_OFFER_PROCESSING_ERROR:"CallEndReasonMediaOfferProcessingError",MEDIA_WHITELISTING_ISSUE:"MediaWhitelistingIssue",AUDIO_ERROR:"CallEndReasonAudioDeviceError",CONVERSATION_NOTIFICATION_TIMEOUT:"ConversationNotificationTimeout",BAD_NOTIFICATION_PAYLOAD:"BadCallNotificationPayload",NETWORK_ERROR:"CallEndReasonNetworkError",LOCAL_USER_INITIATED:"CallEndReasonLocalUserInitiated",REMOTE_USER_INITIATED:"CallEndReasonRemoteUserInitiated",ESTABLISHMENT_TIMEOUT:"CallEndReasonEstablishmentTimeout",PARTICIPANT_REMOVAL_TIMEOUT:"CallParticipantRemovalTimeout",LOCAL_ERROR:"CallEndReasonLocalError",CALL_UPDATE_ERROR:"CallEndReasonCallUpdateError",CALL_REDIRECT_IS_NOT_ALLOWED:"CallRedirectisNotAllowed",P2P_FORK_CONNECTED:"CallEndReasonP2pForkConnected",P2P_FORK_FORWARDED:"CallEndReasonP2pForkForwarded",P2P_FORK_FORWARDED_TO_VOICEMAIL:"CallEndReasonP2pForkForwardedToVoiceMail",P2P_FALLBACK_FOR_SCREENSHARING:"CallEndReasonP2pFallbackForScreensharing",P2P_FALLBACK_FOR_GROUPCALL:"CallEndReasonP2pFallbackForGroupCall",P2P_FALLBACK_FOR_CALL_ASSIMILATION:"CallEndReasonP2pFallbackForCallAssimilation",P2P_FALLBACK_FOR_TRANSLATION:"CallEndReasonP2pFallbackForCallTranslation",P2P_FORK_REJECTED:"CallEndReasonP2pForkRejected",TROUTER_CONNECTION_DROPPED:"CallEndReasonTrouterConnectionDropped",REMOVED_FROM_CALL:"CallEndReasonRemovedFromCall",TRANSFER_COMPLETION_TIMEOUT:"CallEndReasonTransferCompletionTimeout",CALL_DOES_NOT_EXIST:"CallEndReasonCallDoesNotExist",ATTACH_ACTION_FAILED:"CallEndReasonAttachActionFailed",ATTACH_FAILED:"CallEndReasonAttachFailed",CONVERSATION_ESTABLISHMENT_FAILED:"CallEndReasonConversationEstablishmentFailed",CONV_END_FROM_SERVICE:"CallEndReasonConversationEndReceivedFromService",CONV_END_FROM_SERVICE_WITH_ERROR:"CallEndReasonConversationEndReceivedFromServiceWithError",SERVICE_ERROR:"CallEndReasonServiceError",CONFLICT:"CallEndReasonConflict",CALL_ALREADY_IN_P2P:"CallEndReasonCallAlreadyExistsInP2p",CONV_END_NO_MODALITY:"ConversationEndNoModalityConnected",CONV_END_FOR_ALL_INITIATED:"ConversationEndForAllInitiated",RENEGOTIATION_IN_PROGRESS:"NegotiationIsInProgress",ADD_PARTICIPANT_URL_MISSING:"AddParticipantUrlMissing",ADMIT_PARTICIPANT_URL_MISSING:"AdmitParticipantUrlMissing",ADMIT_ALL_URL_MISSING:"AdmitAllUrlMissing",UPDATE_PARTICIPANT_INTERPRETATION_STATE_URL_MISSING:"UpdateParticipantInterpretationStateUrlMissing",UPDATE_PARTICIPANTS_PROPERTIES_URL_MISSING:"UpdateParticipantsPropertiesUrlMissing",ADMIT_TIMEOUT:"AdmitTimeout",UNABLE_TO_GENERATE_MEETUP_ID:"Unable to generate GroupChat meetup id.",ENDED_BY_PMA:"Call ended by media agent.",OWNERSHIP_RESOLUTION_CONFLICT:"Conversation cannot be created due to a failure to resolve ownership.",CONVERSATION_ENDED_NO_NEW_OWNER_FOUND:"This conversation has ended since we were unable to determine a potential host for the group call.",UNMUTE_REQUEST_TIMEOUT:"UnmuteRequestTimeout",UNMUTE_REQUEST_REJECTED:"UnmuteRequestRejected",UPDATE_MEETING_ROLE_TIMEOUT:"UpdateMeetingRoleTimeout",UPDATE_MEETING_ROLE_REJECTED:"Update meeting role operation failed due to insufficient privileges.",PARK_REQUEST_FAILED:"Park Request Failed",PARK_COMPLETION_TIMEOUT:"ParkCompletionTimeout",PARK_COMPLETION_FAILED:"ParkCompletionFailed",UNPARK_REQUEST_FAILED:"UnparkFailed",UNPARK_COMPLETION_TIMEOUT:"UnparkCompletionTimeout",UNPARK_COMPLETION_FAILED:"UnparkCompletionFailed",BAD_SERVICE_RESPONSE:"BadServiceResponse",UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT:"UpdateMeetingLiveStateCompletionTimeout",UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT:"UpdateMeetingGroupsCompletionTimeout",SET_MEETING_LAYOUT_COMPLETION_TIMEOUT:"SetMeetingLayoutCompletionTimeout",UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT:"UpdateParticipantInterpretationTimeout",JOIN_MEETING_GROUP_TIMEOUT:"JoinMeetingGroupTimeout",LEAVE_MEETING_GROUP_TIMEOUT:"LeaveMeetingGroupTimeout",DOWNGRADE_TO_STREAMING_CLIENT:"DowngradeToStreamingClient",MESSAGE_STATUS_WITH_FAILURE_COUNT:"NotZeroFailureCount",UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT:"UpdateParticipantsPropertiesTimeout",DISABLE_PREHEAT_TIMEOUT:"DisablePreheatTimeout",UPDATE_MEETING_STATES_COMPLETION_TIMEOUT:"UpdateMeetingStatesCompletionTimeout",UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT:"UpdateMonitorSessionCompletionTimeout"},TRANSACTION_END_CODE:{SUCCESS:0},URL_DEFAULTS:{UPLOAD_LOG_URL:"https://api.cc.skype.com/cc/v1/uploadlog/"},SUCCESS_TRANSACTION_END:{code:0,resultCategories:[Xi.Success]},VALIDATION:{VALIDATION_FAILED:6e3,NULL_OR_EMPTY:6001}},en={REQUEST_TIMEOUT:{status:Zi.HTTP_STATUS_CODES.TIMEOUT,statusText:"Request timed out",readyState:0,response:Zi.HTTP_STACK_ERROR.REQUEST_TIMEOUT},ATTEMPT_TIMEOUT:{status:Zi.HTTP_STATUS_CODES.TIMEOUT,statusText:"Attempt timed out",readyState:0,response:Zi.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT},REQUEST_ABORTED:{status:Zi.HTTP_STATUS_CODES.ABORTED,statusText:"Request Aborted",readyState:0,response:Zi.HTTP_STACK_ERROR.REQUEST_ABORTED},ATTEMPT_ABORTED:{status:Zi.HTTP_STATUS_CODES.ABORTED,statusText:"Attempt Aborted",readyState:0,response:Zi.HTTP_STACK_ERROR.ATTEMPT_ABORTED}},tn={MEDIA_ACKNOWLEDGEMENT:"/call/mediaAcknowledgement/",MEDIA_REJECTION:"/call/rejection/",ACKNOWLEDGEMENT:"/call/acknowledgement/",MEDIA_RENEGOTIATION:"/call/mediaRenegotiation/",REPLACE:"/call/replacement/",PROGRESS:"/call/progress/",MEDIA_ANSWER:"/call/mediaAnswer/",NEW_MEDIA_OFFER:"/call/newMediaOffer/",REDIRECTION:"/call/redirection/",BALANCE_UPDATE:"/call/balanceUpdate/",ACCEPT:"/call/acceptance/",CONTROL_VIDEO_STREAMING:"/call/controlVideoStreaming/",DOMINANT_SPEAKER_INFO:"/call/dominantSpeakerInfo/",CSRC_INFO:"/call/csrcInfo/",END:"/call/end/",RETARGET_COMPLETION:"/call/retargetCompletion/",TRANSFER:"/call/transfer/",TRANSFER_ACCEPTANCE:"/call/transferAcceptance/",TRANSFER_COMPLETION:"/call/transferCompletion/",PARK_COMPLETION:"/call/holdCompletion/",UNPARK_COMPLETION:"/call/resumeCompletion/",UPDATE_MEDIA_DESCRIPTIONS:"/call/updateMediaDescriptions",MONITOR_COMPLETION:"/call/monitorCompletion/"},nn={CONV_END:"/conversation/conversationEnd/",CONV_END_SUBSCRIBE:"/subscribe/conversation/conversationEnd/",CONV_END_JOIN:"/join/conversation/conversationEnd/",CONV_UPDATE:"/conversation/conversationUpdate/",CONV_LOCAL_PARTICIPANT_UPDATE:"/conversation/localParticipantUpdate/",CONV_ROSTER_UPDATE:"/conversation/rosterUpdate/",CONV_ADD_PARTICIPANT_SUCCESS:"/conversation/addParticipantSuccess/",CONV_ADD_PARTICIPANT_FAILURE:"/conversation/addParticipantFailure/",CONV_NUDGE_PARTICIPANT_SUCCESS:"/conversation/nudgeParticipantSuccess/",CONV_NUDGE_PARTICIPANT_FAILURE:"/conversation/nudgeParticipantFailure/",CONV_ADMIT_PARTICIPANT_SUCCESS:"/conversation/admitParticipantSuccess/",CONV_ADMIT_PARTICIPANT_FAILURE:"/conversation/admitParticipantFailure/",CONV_ADMIT_ALL_STATUS:"/conversation/admitAllStatus/",CONV_REMOVE_PARTICIPANT_SUCCESS:"/conversation/removeParticipantSuccess/",CONV_REMOVE_PARTICIPANT_FAILURE:"/conversation/removeParticipantFailure/",CONV_ADD_MODALITY_SUCCESS:"/conversation/addModalitySuccess/",CONV_ADD_MODALITY_FAILURE:"/conversation/addModalityFailure/",CONV_CONTENT_SHARING_UPDATE:"/conversation/contentSharingUpdate/",CONV_CONTENT_SHARING_END:"/conversation/contentSharingEnd/",CONV_BROADCAST_UPDATE:"/conversation/broadcastUpdate/",CONV_CONFIRM_UNMUTE:"/conversation/confirmUnmute/",CONV_UNMUTE_SUCCESS:"/conversation/unmuteSuccess/",CONV_UNMUTE_FAILURE:"/conversation/unmuteFailure/",UPDATE_MEETING_LIVE_STATE_STATUS:"/conversation/updateMeetingLiveStateStatus/",UPDATE_MEETING_GROUPS_STATUS:"/conversation/updateMeetingGroupsStatus/",SET_MEETING_LAYOUT_STATUS:"/conversation/setMeetingLayoutStatus/",UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS:"/conversation/updateParticipantInterpretationStateStatus/",UPDATE_PARTICIPANT_PROPERTIES_STATUS:"/conversation/updateParticipantPropertiesStatus/",JOIN_MEETING_GROUP_STATUS:"/conversation/joinMeetingGroupStatus/",LEAVE_MEETING_GROUP_STATUS:"/conversation/leaveMeetingGroupStatus/",RECEIVE_MESSAGE:"/conversation/receiveMessage/",SEND_MESSAGE_STATUS:"/conversation/sendMessageStatus/",DISABLE_PREHEAT_ASYNC_STATUS:"/conversation/disablePreheatAsyncStatus/",UPDATE_MEETING_STATES_STATUS:"/conversation/updateMeetingStatesStatus/",MUTE_UNMUTE_ASYNC:"/conversation/muteUnmuteAsync/"},rn={...tn,...nn},sn={CALL_NOTIFICATION:"callNotification",MEDIA_ANSWER:"mediaAnswer",MEDIA_ACKNOWLEDGEMENT:"mediaAcknowledgement",CALL_ACCEPTANCE:"callAcceptance",CALL_END:"callEnd",CALL_PROGRESS:"callProgress",CALL_ACCEPTANCE_ACKNOWLEDGEMENT:"callAcceptanceAcknowledgement",MEDIA_NEGOTIATION:"mediaNegotiation",MEDIA_NEGOTIATION_FAILURE:"mediaNegotiationFailure",BALANCE_UPDATE:"balanceUpdate",RETARGET_COMPLETED:"retargetCompleted",CALL_TRANSFER:"callTransfer",TRANSFER_COMPLETION:"transferCompletion",TRANSFER_ACCEPTANCE:"transferAcceptance",PARK_COMPLETION:"holdCompletion",UNPARK_COMPLETION:"resumeCompletion",UPDATE_MEETING_LIVE_STATE_RESPONSE:"updateMeetingLiveStateResponse",UPDATE_MEETING_GROUPS_RESPONSE:"updateMeetingGroupsResponse",SET_MEETING_LAYOUT_RESPONSE:"setMeetingLayoutResponse",UPDATE_MEETING_STATES_RESPONSE:"updateMeetingStatesResponse",MONITOR_COMPLETION:"monitorCompletion"},an=Zi,on=__toESM2(M),ln=class _HttpHeaderImpl{constructor(g){this.headers={},g&&Object.keys(g).forEach((f=>{this.headers[this.getLowerCaseName(f)]=g[f]}))}isEmpty(){return on.isEmpty(this.headers)}set(g,f){this.headers[this.getLowerCaseName(g)]=f}get(g,f){return f?_HttpHeaderImpl.getHeaderValue(this.headers,g)||f:_HttpHeaderImpl.getHeaderValue(this.headers,g)}delete(g){delete this.headers[g],delete this.headers[g.toLowerCase()]}hasOwnPropertyCaseInsensitive(g){return Object.keys(this.headers).filter((function(f){return f.toUpperCase()===g.toUpperCase()})).length>0}getAll(){return this.headers}getLowerCaseName(g){return _HttpHeaderImpl.useLowerCaseHeaders?g.toLowerCase():g}static getHeaderValue(g,f){return g.hasOwnProperty(f)?g[f]:g.hasOwnProperty(f.toLowerCase())?g[f.toLowerCase()]:void 0}};function get2(g,f,S=causeId2()){return assertNotNullOrEmpty(f,"trailingPath cannot be null"),assertNotNull(g,"signalingSession cannot be null"),assertNotNull(g.baseMessagingChannelUrl,"messaging channel url is not set"),`${g.baseMessagingChannelUrl}${an.URL_BASE.CALLAGENT}/${g.sessionId}/${S}${f}`}function getIdFromUrl(g){const f=g.match(new RegExp(`/${escapeRegExp(an.URL_BASE.CALLAGENT)}/+([^/]+)`,"i"));return f?f[1]:null}function clientSupportedTokenTypes(g){let f=1;return g.callingServiceSupportsAADTokens&&(f|=4),g.callingServiceSupportsCAETokens&&(f|=8),f}function parseServiceTokenTypes2(g){const f=g.toLowerCase(),S='token_types="',v=f.indexOf(S);if(-1===v)return[];const C=f.indexOf('"',v+S.length);if(-1===C)return[];const _=f.substring(v+S.length,C).trim();return""===_?[]:_.split(" ")}function is1to1Mri(g){return!!g.match(/^8:/)}function stripMri(g){return g.replace(/^\d+:/,"")}function causeId2(){return newGuid2().substr(0,8)}function newMessageId(g){return g&&/^[a-z0-9]{8}$/.test(g)?g+newGuid2().substr(8):newGuid2()}function newGuid2(){const g="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",f="0123456789abcdef";let S="",v=0,C=0;for(;C<36;){const _=g[C];switch(v=C%8==0?4294967295*Math.random()|0:v>>4,_){case"x":S+=f[15&v];break;case"y":S+=f[3&v|8];break;case"4":case"-":S+=_}C++}return S}function assert2(g,f){g||throwAssertTransactionEnd("Assert failed"+(void 0!==f?`:${f}`:""))}function assertNotNullOrEmpty(g,f){(!g||g instanceof String&&""===g||g instanceof Array&&0===g.length)&&throwAssertTransactionEnd("AssertNotNullOrEmpty failed. "+(void 0!==f?`: ${f}`:""))}function assertNotNull(g,f){g||throwAssertTransactionEnd("AssertNotNull failed. "+(void 0!==f?`: ${f}`:""))}function assertCallEndReason(g){assertNotNullOrEmpty(g,"callEndReason cannot be null or empty"),(void 0===g.code||void 0===g.subCode||void 0===g.phrase||g.code<0||g.subCode<0||" "===g.phrase)&&throwAssertTransactionEnd(`callEndReason must specify code, subCode and phrase. Invalid reason : ${getPrintableObject(g)}`)}function throwAssertTransactionEnd(g){throw{code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.MISC_ERROR,phrase:g,resultCategories:[Xi.ExpectedError]}}function getMediaTypes(g){assertNotNull(g,"MediaTypes passed cannot be null");const f=[],S=an.MEDIA_TYPES;for(const v of Object.keys(S))arrayContains(g,S[v])&&f.push(S[v]);return f}function getLinksPayload(g,f){const S={};for(const v of Object.values(f)){const f=v.split("/");S[f[f.length-2]]=get2(g,v)}return S}function stringEndsWith(g,f){return g.length>=f.length&&g.indexOf(f,g.length-f.length)>-1}function arrayContains(g,f){const S=f.toString().toLowerCase();return g.map((g=>g.toString().toLowerCase())).indexOf(S)>-1}function tryAddNewKeyToHashTable(g,f,S){return!g.hasOwnProperty(f)&&(g[f]=S,!0)}function tryRemoveKeyFromHashTable(g,f){return!!g.hasOwnProperty(f)&&(delete g[f],!0)}function escapeRegExp(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tryParse(g){let f=null;try{return f=JSON.parse(g),"object"==typeof f?f:null}catch(g){return null}}function getErrorForXHRFailure(g,f){if(!g)return{telemetryEndSubCode:an.CALL_END_CODE.UNKNOWN_ERROR,error:an.CALL_END_UNKNOWN_ERROR};let S;if("object"==typeof g.response)S=g.response;else try{S=JSON.parse(g.response)}catch(g){}if(g.skypeTokenError)return{telemetryEndSubCode:an.CALL_END_CODE.SKYPE_TOKEN_ERROR,error:an.CALL_END_SKYPE_TOKEN_ERROR};if(g.tokenTimeoutError&&!g.tokenInteractivityRequiredTimeout)return{telemetryEndSubCode:an.CALL_END_CODE.HTTP_OTHER_ERROR,error:an.CALL_END_TOKEN_TIMEOUT_ERROR};if(g.tokenError){const f=g.tokenErrorSubCode?{code:an.CALL_END_TOKEN_ERROR.code,subCode:g.tokenErrorSubCode,phrase:an.CALL_END_TOKEN_ERROR.phrase,resultCategories:an.CALL_END_TOKEN_ERROR.resultCategories}:an.CALL_END_TOKEN_ERROR;return{telemetryEndSubCode:an.CALL_END_CODE.HTTP_OTHER_ERROR,error:f}}if(g.tokenInteractivityRequiredTimeout)return{telemetryEndSubCode:an.CALL_END_CODE.HTTP_OTHER_ERROR,error:an.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED};if(S&&(S.operationFailure||S.broadcastOperationFailure)){const g=S.operationFailure||S.broadcastOperationFailure;return{telemetryEndSubCode:g.code,error:g}}return S&&"net::err_name_not_resolved"===S._error?.toLowerCase()?{telemetryEndSubCode:an.CALL_END_CODE.NETWORK_ERROR,error:an.CALL_END_DNS_HOST_NAME_RESOLVE_ERROR}:S?.code?{telemetryEndSubCode:S.code,error:S}:isNaN(g.status)||g.status!==an.CALL_END_CODE.NOT_FOUND?!isNaN(g.status)&&g.status?{telemetryEndSubCode:g.status,error:{code:g.status,subCode:isNaN(g.response)?0:g.response,phrase:g.statusText,resultCategories:[Xi.UnexpectedClientError]}}:!isNaN(g.response)&&g.response?{telemetryEndSubCode:0,error:{code:0,subCode:g.response,phrase:g.statusText,resultCategories:[Xi.UnexpectedClientError]}}:{telemetryEndSubCode:an.CALL_END_CODE.NETWORK_ERROR,error:an.CALL_END_NETWORK_ERROR}:{telemetryEndSubCode:an.CALL_END_CODE.NOT_FOUND,error:an.RESOURCE_NOT_FOUND_ERROR}}function isDuplicateMessage(g,f){if(g&&!g.isEmpty()&&f){const S=g.get(an.HEADERS.ORIGINAL_MESSAGE_ID),v=g.get(an.HEADERS.MESSAGE_ID);if(v&&arrayContains(f,v)||S&&arrayContains(f,S))return!0;f.length>9&&f.shift(),f.push(S||v)}return!1}function extractMessageIdFromMessage(g){const f="unknown";return g.headers?g.headers.get(an.HEADERS.ORIGINAL_MESSAGE_ID,f):f}function extractCauseIdFromMessage(g){try{return g.headers.get(an.HEADERS.ORIGINAL_MESSAGE_ID).replace("-","").substr(0,8)}catch(g){return causeId2()}}function cacheMessageResult(g,f,S){if(g&&f){const v=g.get(an.HEADERS.ORIGINAL_MESSAGE_ID)||g.get(an.HEADERS.MESSAGE_ID)||null;v&&(f[v]=S)}}function getMessageResultFromCache(g,f){return g&&f[g.get(an.HEADERS.ORIGINAL_MESSAGE_ID)||g.get(an.HEADERS.MESSAGE_ID)||null]||null}function isEncodedMessage(g){return g&&g.hasOwnPropertyCaseInsensitive(an.HEADERS.CONTENT_ENCODING)}function isMessageEncodingSupported(g){return g&&an.KNOWN_PAYLOAD_ENCODINGS.hasOwnProperty(g.get(an.HEADERS.CONTENT_ENCODING).toUpperCase())}function parseRawHttpMessage(g){const f=g.split(/\r?\n\r?\n/),S=f[0].split(/\r?\n/),v=f[1].split(/\r?\n/),C=S.shift().split(" "),_=C[0],T=C[1]||"",I=new ln;for(const g of S)try{const[f,S]=g.split(":").map((g=>Yi.trim(g)));I.set(f,S)}catch(f){throw new Error(`Malformed header: ${g+f}`)}return{url:T,headers:I,method:_,body:v.join("")}}function decodeMessage(g){const f=atob(g);return Qi.inflate(f,{to:"string"})}function defer(){let g,f,S=!0;return{isPending:()=>S,promise:new Promise(((S,v)=>{g=S,f=v})),resolve:f=>{S&&(g(f),S=!1)},reject:g=>{S&&(f(g),S=!1)}}}function isTrouterAndNavigatorConnected(g){let f=!1;try{if(f=g&&2===g.state(),navigator.onLine&&f)return 3;if(!navigator.onLine&&f)return 2;if(navigator.onLine&&!f)return 1}catch{}return 0}function isRetryable(g){return[an.HTTP_STATUS_CODES.UNKNOWN,an.HTTP_STATUS_CODES.UNAUTHORIZED,an.HTTP_STATUS_CODES.NETWORK_ERROR,an.HTTP_STATUS_CODES.OFFLINE,an.HTTP_STATUS_CODES.TIMEOUT,an.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,an.HTTP_STATUS_CODES.BAD_GATEWAY,an.HTTP_STATUS_CODES.SERVICE_UNAVAILABLE,an.HTTP_STATUS_CODES.GATEWAY_TIMEOUT].indexOf(g)>=0}function convertStringToTokenType(g,f){switch(g){case an.HEADERS.CAE_KEYWORD.toLowerCase():return 8;case an.HEADERS.AAD_KEYWORD.toLowerCase():return 4;case an.HEADERS.SKYPE_KEYWORD.toLowerCase():return 1;default:return f?.info("unexpected: unrecognized token type ${tokenType}"),null}}function getAuthHeadersTokenTypes(g,f,S,v,C){if(!f)return 1;const{callingServiceSupportsAADTokens:_,callingServiceSupportsCAETokens:T,supportMissingTokenTypesInResponse:I,useSkypeTokenWhenNoAuthenticateHeader:b}=g,A=C?.authenticationHeaders;v?.info(`[getAuthHeadersTokenTypes] UnauthorizedResponse=${S} and authHeaders=${A}`);let P=null;if(!A&&S)b?(v?.info("[getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),P=1):(v?.info("[getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),P=clientSupportedTokenTypes(g));else if(A||S){if(A&&S)for(const f of A){const S=parseServiceTokenTypes2(f);if(I&&0===S.length)v?.info("[getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),P=clientSupportedTokenTypes(g);else for(const g of S){const f=convertStringToTokenType(g.toLowerCase(),v);T&&8===f&&(P|=8),_&&4===f&&(P|=4),1===f&&(P|=1)}}}else v?.info("[getAuthHeadersTokenTypes] first time requesting token, request client supported token types"),P=clientSupportedTokenTypes(g);return P}function getRequestTypeAsString(g){switch(g){case 0:return"GET";case 1:return"POST";case 2:return"PUT";case 3:return"DELETE"}}function extractWwwauthenticateHeaders(g){let f={};if(g){const S=ln.getHeaderValue(g,an.HEADERS.AUTHENTICATE);S&&(f={authenticationHeaders:[S]})}return f}function getTokenMetadata(g,f,S,v,C=!1,_,T){T?.createChild("[utils.ts]");const I={verb:getRequestTypeAsString(S),path:v.url},b=JSON.stringify(I),A=extractWwwauthenticateHeaders(_),P=getAuthHeadersTokenTypes(g,f,C,T,A);return T?.info(`[getTokenMetadata] return token type=${P}, factoJson=${b}, headers=${A?.authenticationHeaders}`),{tokenType:P,factorsJson:b,requestMetadataJson:A,isUnauthorized:C}}function epochTimeInSecRoundedDown(){return Math.floor(Date.now()/1e3)}function millieSecondsToSeconds(g){return g/1e3}function secondsToMillieSeconds(g){return 1e3*g}function getRequestToken(g){const f=ln.getHeaderValue(g,an.HEADERS.SKYPE_TOKEN);if(f)return f;const S=ln.getHeaderValue(g,an.HEADERS.AUTHORIZATION);if(S){const g=S.split(" ");if(2===g.length)return g[1]}}function getParkTypeName(g){switch(g){case"none":return"None";case"teamPark":return"TeamPark";case"callPark":return"CallParkV2";case"serverHold":return"ServerHold";case"serverHoldV2":return"MusicOnHoldV2";case"sharedLinePark":return"SharedLinePark";case"sharedLineParkV2":return"SharedLineAppearanceV2";default:return"UnknownType"}}function getPluginlessStateTypeFromWire(g){switch(g){case"raiseHands":return"raiseHands";case"ufd":return"ufd";case"attendeeModalitiesUnrestricted":return"attendeeModalitiesUnrestricted";case"attendeeAudioRestricted":return"attendeeAudioRestricted";case"attendeeVideoRestricted":return"attendeeVideoRestricted";case"attendeeVideoUnrestricted":return"attendeeVideoUnrestricted";case"spotlight":return"spotlight";case"weatherPerson":return"weatherPerson";case"sharingLayoutType":return"sharingLayoutType";case"manageBreakoutRooms":return"manageBreakoutRooms";case"togetherMode":return"togetherMode";case"consentToRecording":return"consentToRecording";case"denyConsentToRecording":return"denyConsentToRecording";case"clientMediaUfd":return"clientMediaUfd";case"serverMediaUfd":return"serverMediaUfd";case"dhhSigner":return"dhhSigner";case"signLanguageInterpreter":return"signLanguageInterpreter";default:throw"Invalid state type when converting PublishType to PublishStateType."}}function getPluginlessStateType(g){switch(g){case"raiseHands":return"raiseHands";case"ufd":return"ufd";case"attendeeModalitiesUnrestricted":return"attendeeModalitiesUnrestricted";case"attendeeAudioRestricted":return"attendeeAudioRestricted";case"attendeeVideoRestricted":return"attendeeVideoRestricted";case"attendeeVideoUnrestricted":return"attendeeVideoUnrestricted";case"spotlight":return"spotlight";case"weatherPerson":return"weatherPerson";case"sharingLayoutType":return"sharingLayoutType";case"manageBreakoutRooms":return"manageBreakoutRooms";case"togetherMode":return"togetherMode";case"consentToRecording":return"consentToRecording";case"denyConsentToRecording":return"denyConsentToRecording";case"clientMediaUfd":return"clientMediaUfd";case"serverMediaUfd":return"serverMediaUfd";case"dhhSigner":return"dhhSigner";case"signLanguageInterpreter":return"signLanguageInterpreter";default:throw"Invalid state type when converting PublishStateType to PublishType."}}function getParticipantInvitationData(g){let f={};return g.additionalData&&g.customHeaderContext?f="object"==typeof g.additionalData?{...g.additionalData,customContext:g.customHeaderContext}:{additionalData:g.additionalData,customContext:g.customHeaderContext}:!g.additionalData&&g.customHeaderContext?f={customContext:g.customHeaderContext}:g.additionalData&&!g.customHeaderContext&&(f=g.additionalData),f}function parseDisplayNameSourceFromWire(g){if(!g)return;let f="unknown";return"substrate"===g&&(f="substrate"),f}var cn=class _Participant{static isInLobby(g,f){for(const S of g)if(S.endpointId===f&&S.isLobby)return!0;return!1}static isParticipantServerMuted(g){for(const f of g)if(f.mediaStreams&&!f.mappedTo)for(const g of f.mediaStreams)if("audio"===g.type&&!0===g.serverMuted)return!0;return!1}static fromWireParticipant(g){return assertNotNull(g,"invalid wireParticipant"),assertNotNullOrEmpty(g.id,"participant must have valid Id"),new _Participant({id:g.id,displayName:g.displayName,languageId:g.languageId,acceptedBy:g.acceptedBy})}static getPluginlessStateTypeFromWire(g){return getPluginlessStateTypeFromWire(g)}static findOrCreateTypeState(g,f){let S=f.typeStates.findIndex((f=>f.type===g));if(-1===S){const v={participantStates:[],type:g};f.typeStates.push(v),S=f.typeStates.length-1}return S}static processPublishedStates(g,f){const S={typeStates:[]};S.typeStates=[];const v=g;return Ji.forEach(v,(g=>{const v=this.findOrCreateTypeState(this.getPluginlessStateTypeFromWire(g.stateType),S),C={id:f,publishedState:{content:g.content,stateId:g.stateId,typeRank:g.typeRank}};S.typeStates[v].participantStates.push(C)})),S}static fromRosterEndpoints(g){let f=[],S=!1,v=!1,C=!1,_=!1;return f=Object.keys(g).map((f=>{let T,I,b,A=[],P=!1,R=0;if(g[f].call&&(S=!0,A=g[f].call.mediaStreams||null,R=g[f].call.serverMuteVersion||0,I=g[f].call.appliedInteractivityLevel||"unknown",b=g[f].call.negotiationTag),g[f].lobby&&(P=!0,v=!0,A=g[f].lobby.mediaStreams||null),g[f].broadcast?.sessionInformation&&(T=g[f].broadcast.sessionInformation.role||null),g[f].mappedParticipant&&(C=!0,A=g[f].mappedParticipant.mediaStreams||null),!g[f].capabilities&&g[f].endpointCapabilities){const S=g[f].endpointCapabilities;g[f].capabilities={implicitCallback:16&S?"enabled":"disabled",cloudAudioVideoConference:1&S?"enabled":"disabled",cloudScreenSharing:2&S?"enabled":"disabled",hostlessConference:4&S?"enabled":"disabled",autoJoinOnConflict:32&S?"enabled":"disabled",serverMuteUnmute:64&S?"enabled":"disabled",supportsCompressedServicePayload:128&S?"enabled":"disabled",cloudMerge:8&S?"enabled":"disabled"}}return _=_||!!g[f].streamLobby||!!g[f].stream,{endpointId:f,participantId:g[f].participantId||null,clientVersion:g[f].clientVersion||null,endpointMetadata:g[f].endpointMetadata||null,originalId:g[f].originalId||null,contentSharing:g[f].contentSharing||null,capabilities:g[f].capabilities||null,endpointType:g[f].endpointType||"default",deviceType:g[f].deviceType||void 0,clientEndpointCapabilities:g[f].clientEndpointCapabilities||void 0,mediaStreams:A,serverMuteVersion:R,broadcastMeetingRole:T,isLobby:P,endpointState:g[f].endpointState||null,publishedStates:g[f].publishedStates||null,callLinks:g[f].callLinks||null,appliedInteractivityLevel:I||"unknown",mappedTo:g[f].mappedTo||null,meetingGroupDetails:g[f].meetingGroupDetails,streamInformation:g[f].streamInformation,propertyBag:g[f].propertyBag,streamLobby:g[f].streamLobby,stream:g[f].stream,endpointMeetingRoles:g[f].endpointMeetingRoles,negotiationTag:b}})),{endpointDetails:f,participantHasCallModality:S,participantIsInLobby:v,participantHasMappedEndpoint:C,participantHasStreamEndpoint:_}}static fromRoster(g,f=!1){assertNotNull(g,`invalid rosterParticipant ${JSON.stringify(g)}`),assertNotNullOrEmpty(g.details.id,"participant must have valid Id");const S=g.endpoints||{},v=this.fromRosterEndpoints(S),C=v.endpointDetails,_=v.participantHasCallModality,T=v.participantHasMappedEndpoint,I=v.participantHasStreamEndpoint;let b=v.participantIsInLobby;return _||b||T||f||I?(_&&(b=!1),new _Participant({id:g.details.id,displayName:g.details.displayName,otpIdentity:g.details.otpIdentity,version:g.version||0,propertyBag:g.details.propertyBag||null,languageId:g.details.languageId,role:g.role||"",tenantId:g.details.tenantId||"",endpointDetails:C||[],acceptedBy:g.acceptedBy||"",isLobby:b,meetingRole:g.meetingRole,advancedMeetingRole:g.advancedMeetingRole,meetingRoles:g.meetingRoles,participantType:g.details.participantType,publishedStates:g.publishedStates||null,isIdentityMasked:g.details.isIdentityMasked,nonMaskedId:g.details.nonMaskedId||"",nonMaskedObjectId:g.details.nonMaskedObjectId||"",nonMaskedDisplayName:g.details.nonMaskedDisplayName||"",maskedIdSeqNumber:g.details.maskedIdSeqNumber||0,maskedId:g.details.maskedId||"",joinAsStreamingUser:g.joinAsStreamingUser,enableCaptcha:g.enableCaptcha})):null}static fromRosterSearchResults(g){assertNotNull(g,`invalid rosterParticipant ${JSON.stringify(g)}`),assertNotNullOrEmpty(g.details.id,"participant must have valid Id");const f=g.endpoints,{endpointDetails:S,participantHasCallModality:v,participantIsInLobby:C,participantHasMappedEndpoint:_,participantHasStreamEndpoint:T}=this.fromRosterEndpoints(f);let I=0;return v||T?I=3:C?I=10:_&&(I=3),{id:g.details.id,state:I,tenantId:g.details.tenantId||"",displayName:g.details.displayName,role:g.role||"",meetingRole:g.meetingRole,advancedMeetingRole:g.advancedMeetingRole,meetingRoles:g.meetingRoles,participantType:g.details.participantType,isServerMuted:this.isParticipantServerMuted(S),publishedStates:this.processPublishedStates(g.publishedStates,g.details.id),endpoints:S||[],isIdentityMasked:g.details.isIdentityMasked,nonMaskedId:g.details.nonMaskedId||"",nonMaskedDisplayName:g.details.nonMaskedDisplayName||"",nonMaskedObjectId:g.details.nonMaskedObjectId||"",maskedIdSeqNumber:g.details.maskedIdSeqNumber||0,maskedId:g.details.maskedId||"",joinAsStreamingUser:g.joinAsStreamingUser}}constructor(g){this.id=g.id,this.displayName=g.displayName||"",this.otpIdentity=g.otpIdentity,this.version=g.version,this.propertyBag=g.propertyBag,this.languageId=g.languageId||null,this.endpointDetails=g.endpointDetails||[],this.acceptedBy=g.acceptedBy,this.role=g.role,this.tenantId=g.tenantId,this.isLobby=g.isLobby,this.meetingRole=g.meetingRole,this.advancedMeetingRole=g.advancedMeetingRole,this.meetingRoles=g.meetingRoles,this.participantType=g.participantType,this.publishedStates=g.publishedStates,this.isIdentityMasked=g.isIdentityMasked,this.nonMaskedId=g.nonMaskedId,this.nonMaskedDisplayName=g.nonMaskedDisplayName,this.nonMaskedObjectId=g.nonMaskedObjectId,this.maskedIdSeqNumber=g.maskedIdSeqNumber,this.maskedId=g.maskedId,this.joinAsStreamingUser=g.joinAsStreamingUser,this.enableCaptcha=g.enableCaptcha}},dn={HANDLE_MEDIA_ACKNOWLEDGEMENT:"HandleMediaAcknowledgement",HANDLE_MEDIA_NEGOTIATION_FAILURE:"HandleMediaNegotiationFailure",HANDLE_MEDIA_ANSWER:"HandleMediaAnswer",HANDLE_MEDIA_ANSWER_FAILED:"HandleMediaAnswerFailed",HANDLE_MEDIA_OFFER:"HandleMediaOffer",REJECT_RENEGOTIATION:"RejectRenegotiation",HANDLE_RETARGET_COMPLETED:"HandleRetargetCompleted",HANDLE_MEDIA_ANSWER_TIMEOUT:"HandleMediaAnswerTimeout",HANDLE_MEDIA_ACKNOWLEDGEMENT_TIMEOUT:"HandleMediaAcknowledgementTimeout",ACCEPT_RENEGOTIATION:"AcceptRenegotiation",START_RENEGOTIATION:"StartRenegotiation",MEDIA_FSM_STATE_CHANGED:"MediaFsmStateChanged",ADD_MODALITY_TIMEOUT:"AddModalityTimeout",ADD_PARTICIPANT:"AddParticipant",ADD_PARTICIPANT_TIMEOUT:"AddParticipantTimeout",ADD_PARTICIPANT_WITH_REPLACES:"AddParticipantWithReplaces",ADD_PARTICIPANT_WITH_REPLACES_TIMEOUT:"AddParticipantWithReplacesTimeout",ADD_PARTICIPANTS_AND_MODALITY:"AddParticipantsAndModality",ADMIT_PARTICIPANT:"AdmitParticipant",ADMIT_PARTICIPANT_TIMEOUT:"AdmitParticipantTimeout",ADMIT:"Admit",ADMIT_TIMEOUT:"AdmitTimeout",ADMIT_FAILURE:"AdmitFailure",ADMIT_SUCCESS:"AdmitSuccess",CALL_ME_BACK:"CallMeBack",CALL_ME_BACK_TIMEOUT:"CallMeBackTimeout",REMOVE_PARTICIPANT:"RemoveParticipant",REMOVE_PARTICIPANT_OTHERS:"RemoveParticipantOthers",REMOVE_PARTICIPANT_SPECIFIED:"RemoveParticipantSpecified",REMOVE_PARTICIPANT_TIMEOUT:"RemoveParticipantTimeout",HANDLE_ADD_PARTICIPANT_SUCCESS:"HandleAddParticipantSuccess",HANDLE_ADD_PARTICIPANT_FAILURE:"HandleAddParticipantFailure",HANDLE_ADMIT_PARTICIPANT_SUCCESS:"HandleAdmitParticipantSuccess",HANDLE_ADMIT_PARTICIPANT_FAILURE:"HandleAdmitParticipantFailure",HANDLE_ADD_PARTICIPANT_MODALITY_FAILURE:"HandleAddParticipantModalityFailure",HANDLE_REMOVE_PARTICIPANT_SUCCESS:"HandleRemoveParticipantSuccess",HANDLE_REMOVE_PARTICIPANT_FAILURE:"HandleRemoveParticipantFailure",HANDLE_ROSTER_UPDATE:"HandleRosterUpdate",HANDLE_ROSTER_UPDATE_FAIL:"HandleRosterUpdateFail",HANDLE_CONVERSATION_UPDATE:"HandleConversationUpdate",HANDLE_LOCAL_PARTICIPANT_UPDATE:"HandleLocalParticipantUpdate",SET_SUBJECT:"SetSubject",SET_JOINED_FROM:"SetJoinedFrom",SET_DEVICETYPE:"SetDeviceType",GET_EMERGENCY_CONTENT:"GetEmergencyContent",SET_MULTIPARTY:"SetMultiparty",SET_GROUPID:"SetGroupId",SET_THREADID:"SetThreadId",SET_CALLOPTIONS:"SetCallOptions",SET_TRANSFER_CONTEXT:"SetTransferContext",START_CALL:"StartCall",JOIN_CALL:"JoinCall",START_OR_JOIN_CALL:"StartOrJoinCall",JOIN_CONVERSATION_WITHOUT_CALL_MODALITY:"JoinConversationWithoutCallModality",HANDLE_INCOMING_CALL:"HandleIncomingCall",END_CALL:"EndCall",END_WITH_BEACON:"EndWithBeacon",REJECT_WITH_FETCH_KEEP_ALIVE:"RejectWithFetchKeepAlive",END_WITH_FETCH_KEEP_ALIVE:"EndWithFetchKeepAlive",CONFLICTED_CALL:"ConflictedCall",SET_PROVISIONAL_ANSWER:"SetProvisionalAnswer",SET_PROVISIONAL_ANSWER_FAILED:"SetProvisionalAnswerFailed",ACCEPT_CALL:"AcceptCall",ACCEPT_CALL_FAILED:"AcceptCallFailed",HANDLE_CALL_ACCEPTANCE_ACK:"HandleCallAcceptanceAck",HANDLE_CALL_ACCEPTANCE:"HandleCallAcceptance",HANDLE_CALL_ACCEPTANCE_SYNC:"HandleCallAcceptanceSync",HANDLE_CALL_ACCEPTANCE_FAILED:"HandleCallAcceptanceFailed",HANDLE_CALL_ESTABLISHMENT_TIMEOUT:"HandleCallEstablishmentTimeout",HANDLE_CALL_END:"HandleCallEnd",HANDLE_CALL_PROGRESS:"HandleCallProgress",TROUTER_URL_CHANGED:"TrouterUrlChanged",TROUTER_STATE_CHANGED:"TrouterStateChanged",TROUTER_URL_CHANGED_TO_INVALID:"TrouterUrlChangedToInvalid",TROUTER_URL_UPDATE_FAILED:"TrouterUrlUpdateFailed",ADD_CONTENT_SHARING_MODALITY:"AddContentSharingModality",ACCEPTED_BEFORE_RINGING:"AcceptedBeforeRinging",LEAVE_CONTENT_SHARING:"LeaveContentSharing",DELETE_CONTENT_SHARING:"DeleteContentSharing",TAKE_CONTROL_CONTENT_SHARING:"TakeControlContentSharing",UPDATE_SESSION_STATE_CONTENT_SHARING:"UpdateSessionStateContentSharing",JOIN_CONTENT_SHARING:"JoinContentSharing",UPDATE_PARTICIPANT_STATE_CONTENT_SHARING:"UpdateParticipantStateContentSharing",HANDLE_CONTENT_SHARING_UPDATE:"HandleContentSharingUpdate",HANDLE_CONTENT_SHARING_END:"HandleContentSharingEnd",CONTENT_SHARING_START_FROM_ROSTER:"ContentSharingStartFromRoster",CONTENT_SHARING_END_FROM_ROSTER:"ContentSharingEndFromRoster",HANDLE_ADD_MODALITY_SUCCESS:"HandleAddModalitySuccess",HANDLE_ADD_MODALITY_FAILURE:"HandleAddModalityFailure",ADD_BROADCAST_MODALITY:"AddBroadcastModality",ADD_MODALITY:"AddModality",UPDATE_BROADCAST_DETAILS:"UpdateBroadcastDetails",WAITING_FOR_ADD_BROADCAST_MODALITY_COMPLETION:"WaitingForAddBroadcastModalityCompletion",WAITING_FOR_ADD_MODALITY_COMPLETION:"WaitingForAddModalityCompletion",MUTE:"Mute",NUDGE_PARTICIPANT_TIMEOUT:"NudgeParticipantTimeout",UNMUTE:"Unmute",UNMUTE_TIMEOUT:"UnmuteTimeout",HANDLE_UNMUTE_CONFIRM:"HandleUnmuteConfirm",HANDLE_UNMUTE_SUCCESS:"HandleUnmuteSuccess",HANDLE_UNMUTE_FAILURE:"HandleUnmuteFailure",APPROVE_UNMUTE:"ApproveUnmute",REJECT_UNMUTE:"RejectUnmute",HANDLE_CONTROL_VIDEO_STREAMING:"HandleControlVideoStreaming",HANDLE_DOMINANT_SPEAKER_CHANGED_COUNT:"HandleDominantSpeakerChangedCount",HANDLE_CSRC_INFO:"HandleCsrcInfo",SEND_WEBRTC_MEDIA_NOTIFICATION:"SendWebRtcMediaNotification",HANDLE_BALANCE_UPDATE:"HandleBalanceUpdate",TRANSFER_CALL:"TransferCall",PARK_CALL:"ParkCall",CALL_REDIRECT:"CallRedirect",CALL_REDIRECT_REQUEST_FAILED:"CallRedirectRequestFailed",TRANSFER_COMPLETION_FAILED:"TransferCompletionFailed",TRANSFER_REQUEST_RECEIVED:"TransferRequestReceived",HANDLE_PARK_REQUESTED:"HandleParkRequested",HANDLE_SERVER_HOLD:"HandleServerHold",DUPLICATE_MESSAGE_IGNORED:"DuplicateMessageIgnored",CORRELATION_ID_UPDATED:"CorrelationIdUpdated",UNKNOWN_MESSAGE_TYPE:"UnkownMessageType",FAILED_TO_HANDLE_MESSAGE:"FailedToHandleMessage",CONNECTIVITY_CHANGED:"ConnectivityChanged",TROUTER_DECODE_PAYLOAD_FAILURE:"TrouterDecodePayloadFailure",UPDATE_ENDPOINT_STATE:"UpdateEndpointState",UPDATE_ENDPOINT_STATE_SUCCESS:"UpdateEndpointStateSuccess",UPDATE_ENDPOINT_STATE_FAILURE:"UpdateEndpointStateFailure",BROKER_DECODE_PAYLOAD_FAILURE:"BrokerDecodePayloadFailure",BROKER_SUBSCRIPTION_TIMEOUT:"BrokerSubscriptionTimeout",BROKER_SUBSCRIPTION_SUCCESSFUL:"BrokerSubscriptionSuccessful",BROKER_SUBSCRIPTION_FAILED:"BrokerSubscriptionFailed",FAILED_TO_HANDLE_TROUTER_MESSAGE:"FailedToHandleTrouterMessage",FAILED_TO_HANDLE_BROKER_MESSAGE:"FailedToHandleBrokerMessage",BROKER_DISABLED_SUBSCRIBE_URL_PRESENT:"BrokerDisabledSubscribeUrlPresent",CONNECTED:"Connected",IN_LOBBY:"InLobby",STAGING:"Staging",MESSAGE_MISSING_BODY:"MessageMissingBody",BROADCAST_STATE_CHANGED:"BroadcastStateChanged",HANDLE_CALL_NOTIFICATION:"HandleCallNotification",HANDLE_INCOMING_CALL_REPLACEMENT:"HandleIncomingCallReplacement",HANDLE_PSTN_BALANCE_UPDATE:"HandlePstnBalanceUpdate",IGNORE_OLD_ROSTER:"IgnoreOldRoster",HANDLE_MEDIA_ACK:"HandleMediaAck",HANDLE_MEDIA_PROVISIONAL_ACK:"HandleMediaProvisionalAck",UPDATE_CALL_STATUS:"UpdateCallStatus",SEND_ATTACH:"SendAttach",REQUEST_NEW_OFFER:"RequestNewOffer",HANDLE_NEW_OFFER:"HandleNewOffer",UPDATE_CONVERSATION_LINKS:"UpdateConversationLinks",UPDATE_CONVERSATION_LINKS_SUCCESS:"UpdateConversationLinksSuccess",UPDATE_CONVERSATION_LINKS_FAILED:"UpdateConversationLinksFailed",PROCESS_INITIAL_OFFER:"ProcessInitialOffer",SEND_PROGRESS:"SendProgress",SEND_PROGRESS_FAILED:"SendProgressFailed",PROCESS_CALL_ACCEPTANCE:"ProcessCallAcceptance",ACCEPTANCE_USER_IN_LOBBY:"AcceptanceUserInLobby",REJECT_INCOMING_CALL:"RejectIncomingCall",SEND_KEEP_ALIVE:"SendKeepAlive",SEND_KEEP_ALIVE_FAILED:"SendKeepAliveFailed",SEND_CONVERSATION_KEEP_ALIVE_FAILED:"SendConversationKeepAliveFailed",START_AUDIO:"StartAudio",STOP_AUDIO:"StopAudio",UPDATE_MEETING_ROLE:"UpdateMeetingRole",UPDATE_MEETING_ROLE_TIMEOUT:"UpdateMeetingRoleTimeout",PREHEAT_ENABLING:"EnablingPreheat",PREHEAT_DISABLING:"DisablingPreheat",PREHEAT_DISABLED:"PreheatDisabled",TRANSFER_REQUEST_SENT:"TransferRequestSent",CALL_REDIRECT_REQUEST_SENT:"CallRedirectRequestSent",TRANSFER_REQUEST_FAILED:"TransferRequestFailed",SEND_ACCEPT_TRANSFER:"SendAcceptTransfer",SEND_ACCEPT_TRANSFER_FAIL:"SendAcceptTransferFail",WAITING_FOR_TRANSFER_COMPLETION:"WaitingForTransferCompletion",WAITING_FOR_TRANSFER_COMPLETION_FAIL:"WaitingForTransferCompletionFail",WAITING_FOR_TRANSFER_ACCEPTANCE_FAIL:"WaitingForTransferAcceptanceFail",WAITING_FOR_TRANSFER_ACCEPTANCE:"WaitingForTransferAcceptance",TRANSFER_COMPLETED:"TransferCompleted",SEND_COMPLETE_TRANSFER:"SendCompleteTransfer",SEND_COMPLETE_TRANSFER_FAILED:"SendCompleteTransferFailed",PICKUP_CODE_SET:"PickupCodeSet",ADD_PARTICIPANT_WITH_PICKUP_CODE:"AddParticipantWithPickupCode",ADD_PARTICIPANT_WITH_PICKUP_CODE_TIMEOUT:"AddParticipantWithPickupCodeTimeout",PUBLISH_STATE:"PublishState",PUBLISH_STATE_FAILURE:"PublishStateFailure",REMOVE_STATE:"RemoveState",REMOVE_STATE_FAILURE:"RemoveStateFailure",UPDATE_MEETING_SETTINGS:"UpdateMeetingSettings",UPDATE_MEETING_SETTINGS_FAILURE:"UpdateMeetingSettingsFailure",UPDATE_ENDPOINT_METADATA_SUCCESS:"UpdateEndpointMetadataSuccess",UPDATE_ENDPOINT_METADATA_FAILURE:"UpdateEndpointMetadataFailure",SEARCH_PARTICIPANTS:"SearchParticipants",GET_ALL_PARTICIPANTS:"GetAllParticipants",SEARCH_PARTICIPANTS_FAILURE:"SearchParticipantsFailure",GET_ALL_PARTICIPANTS_FAILURE:"GetAllParticipantsFailure",PARK_REQUEST:"SendParkRequest",PARK_REQUEST_FAILED:"ParkRequestFailed",WAITING_FOR_PARK_COMPLETION:"WaitingForParkCompletion",WAITING_FOR_PARK_COMPLETION_TIMEOUT:"WaitingForParkCompletionTimeout",PARK_COMPLETED:"ParkCompleted",PARK_FAILED:"ParkFailed",SEND_UNPARK_REQUEST:"SendUnparkRequest",UNPARK_REQUEST_FAILED:"UnparkRequestFailed",WAITING_FOR_UNPARK_COMPLETION:"WaitingForUnparkCompletion",WAITING_FOR_UNPARK_COMPLETION_TIMEOUT:"WaitingForUnparkCompletionTimeout",UNPARK_COMPLETED:"UnparkCompleted",UNPARK_FAILED:"UnparkFailed",UPDATE_MEETING_LIVE_STATE:"UpdateMeetingLiveState",WAITING_FOR_UPDATE_MEETING_LIVE_STATE_COMPLETION:"WaitingForUpdateMeetingLiveStateCompletion",UPDATE_MEETING_LIVE_STATE_REQUEST_FAILED:"UpdateMeetingLiveStateRequestFailed",UPDATE_MEETING_LIVE_STATE_RESPONSE_FAILURE:"UpdateMeetingLiveStateResponseFailure",UPDATE_MEETING_LIVE_STATE_RESPONSE_SUCCESS:"UpdateMeetingLiveStateResponseSuccess",UPDATE_MEETING_GROUPS:"UpdateMeetingGroups",UPDATE_PARTICIPANT_INTERPRETATION_STATE:"UpdateParticipantInterpretationState",UPDATE_PARTICIPANTS_PROPERTIES:"UpdateParticipantsProperties",JOIN_MEETING_GROUP:"JoinMeetingGroup",LEAVE_MEETING_GROUP:"LeaveMeetingGroup",INCOMING_PROXIED_MESSAGES:"incomingProxiedMessages",WAITING_FOR_UPDATE_MEETING_GROUPS_COMPLETION:"WaitingForUpdateMeetingGroupsCompletion",UPDATE_MEETING_GROUPS_REQUEST_FAILED:"UpdateMeetingGroupsRequestFailed",UPDATE_MEETING_GROUPS_REQUEST_COMPLETED:"UpdateMeetingGroupsRequestCompleted",UPDATE_MEETING_GROUPS_RESPONSE_FAILURE:"UpdateMeetingGroupsResponseFailure",UPDATE_MEETING_GROUPS_RESPONSE_SUCCESS:"UpdateMeetingGroupsResponseSuccess",SET_MEETING_LAYOUT:"SetMeetingLayout",WAITING_FOR_SET_MEETING_LAYOUT_COMPLETION:"WaitingForSetMeetingLayoutCompletion",SET_MEETING_LAYOUT_REQUEST_FAILED:"SetMeetingLayoutRequestFailed",SET_MEETING_LAYOUT_RESPONSE_FAILURE:"SetMeetingLayoutResponseFailure",SET_MEETING_LAYOUT_RESPONSE_SUCCESS:"SetMeetingLayoutResponseSuccess",WAITING_FOR_UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION:"WaitingForUpdateParticipantInterpretationStateCompletion",UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT:"UpdateParticipantInterpretationStateTimeout",UPDATE_PARTICIPANT_INTERPRETATION_STATE_REQUEST_FAILED:"UpdateParticipantInterpretationStateRequestFailed",UPDATE_PARTICIPANT_INTERPRETATION_STATE_REQUEST_COMPLETED:"UpdateParticipantInterpretationStateRequestCompleted",UPDATE_PARTICIPANT_INTERPRETATION_STATE_RESPONSE_FAILED:"UpdateParticipantInterpretationStateResponseFailed",UPDATE_PARTICIPANT_INTERPRETATION_STATE_RESPONSE_COMPLETED:"UpdateParticipantInterpretationStateResponseCompleted",WAITING_FOR_UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION:"WaitingForUpdateParticipantsPropertiesCompletion",UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT:"UpdateParticipantsPropertiesTimeout",UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED:"UpdateParticipantsPropertiesResponseFailed",UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_COMPLETED:"UpdateParticipantsPropertiesResponseCompleted",WAITING_FOR_JOIN_MEETING_GROUP_COMPLETION:"WaitingForJoinMeetingGroupCompletion",JOIN_MEETING_GROUP_REQUEST_FAILED:"JoinMeetingGroupRequestFailed",JOIN_MEETING_GROUP_REQUEST_COMPLETED:"JoinMeetingGroupRequestCompleted",JOIN_MEETING_GROUP_RESPONSE_FAILED:"JoinMeetingGroupRequestFailed",JOIN_MEETING_GROUP_RESPONSE_COMPLETED:"JoinMeetingGroupRequestCompleted",WAITING_FOR_LEAVE_MEETING_GROUP_COMPLETION:"WaitingForLeaveMeetingGroupCompletion",LEAVE_MEETING_GROUP_REQUEST_FAILED:"LeaveMeetingGroupRequestFailed",LEAVE_MEETING_GROUP_REQUEST_COMPLETED:"LeaveMeetingGroupRequestCompleted",LEAVE_MEETING_GROUP_RESPONSE_FAILED:"LeaveMeetingGroupRequestFailed",LEAVE_MEETING_GROUP_RESPONSE_COMPLETED:"LeaveMeetingGroupRequestCompleted",SUBSCRIBE_URL_FOUND:"SubscribeUrlFound",SUBSCRIBE_URL_MISSING:"SubscribeUrlMissing",SEND_MESSAGE_COMPLETION:"SendMessageCompletion",SEND_MESSAGE_TIMEOUT:"SendMessageTimeout",DISABLE_PREHEAT_SUCCEEDED:"DiablePreheatSucceeded",ASYNC_DISABLE_PREHEAT_SUCCEEDED:"AsyncDisablePreheatSucceeded",DISABLE_PREHEAT_FAILED:"DiablePreheatFailed",ASYNC_DISABLE_PREHEAT_FAILED:"AsyncDiablePreheatFailed",ASYNC_DISABLE_PREHEAT_TIMEOUT:"AsyncDiablePreheatTimeout",DISABLE_PREHEAT_RESPONSE_RECEIVED:"DisablePreheatResponseReceived",SET_STREAM_INFORMATION_RECEIVED:"StreamInformationReceived",UPDATE_MEDIA_DESCRIPTIONS:"UpdateMediaDescriptions",UPDATE_MEDIA_DESCRIPTIONS_FAILED:"UpdateMediaDescriptionsFailed",NUDGE_TO_JOIN_REALTIME:"NudgeToJoinAsRealtime",UPDATE_MEETING_STATES:"UpdateMeetingStates",WAITING_FOR_UPDATE_MEETING_STATES_COMPLETION:"WaitingForUpdateMeetingStatesCompletion",UPDATE_MEETING_STATES_RESPONSE_SUCCESS:"UpdateMeetingStatesResponseSuccess",UPDATE_MEETING_STATES_RESPONSE_FAILURE:"UpdateMeetingStatesResponseFailure",UPDATE_MONITOR_SESSION:"UpdateMonitorSession",UPDATE_MONITOR_SESSION_REQUEST_FAILED:"UpdateMonitorSessionRequestFailed",UPDATE_MONITOR_SESSION_REQUEST_COMPLETED:"UpdateMonitorSessionRequestCompleted",UPDATE_MONITOR_SESSION_RESPONSE_FAILED:"UpdateMonitorSessionResponseFailed",UPDATE_MONITOR_SESSION_RESPONSE_COMPLETED:"UpdateMonitorSessionResponseCompleted",WAITING_FOR_UPDATE_MONITOR_SESSION_COMPLETION:"WaitingForUpdateMonitorSessionCompletion"},hn={SEND_MEDIA_ANSWER:{name:"SendMediaAnswer",controller:0},START_RENEGOTIATION:{name:"StartRenegotiation",controller:0},SEND_MEDIA_ACKNOWLEDGEMENT:{name:"SendMediaAcknowledgement",controller:0},SEND_MEDIA_REJECTION:{name:"SendMediaRejection",controller:0},ADD_PARTICIPANT:{name:"AddParticipant",controller:1},ADD_PARTICIPANT_WITH_REPLACES:{name:"AddParticipantWithReplaces",controller:1},NUDGE_PARTICIPANT:{name:"NudgeParticipant",controller:1},REMOVE_PARTICIPANT_NONE:{name:"RemoveParticipant",controller:1},REMOVE_PARTICIPANT_OTHERS:{name:"RemoveParticipantOthers",controller:1},REMOVE_PARTICIPANT_SPECIFIED:{name:"RemoveParticipantSpecified",controller:1},ADMIT_PARTICIPANT:{name:"AdmitParticipant",controller:1},ADMIT:{name:"Admit",controller:1},BROKER_SUBSCRIBE:{name:"BrokerSubscribe",controller:2},CALL_ME_BACK:{name:"CallMeBack",controller:1},SEND_ACCEPTANCE:{name:"SendAcceptance",controller:0},SEND_ACCEPTANCE_ACKNOWLEDGEMENT:{name:"SendAcceptanceAcknowledgement",controller:0},END_CALL:{name:"EndCall",controller:1},CANCEL_CALL:{name:"CancelCall",controller:1},REJECT_CALL:{name:"RejectCall",controller:0},JOIN_CONVERSATION:{name:"JoinConversation",controller:1},JOIN_CONVERSATION_WITHOUT_CALL_MODALITY:{name:"JoinConversationWithoutCallModality",controller:1},LEAVE_CONVERSATION:{name:"LeaveConversation",controller:1},DELETE_CONVERSATION:{name:"DeleteConversation",controller:1},START_CALL:{name:"StartCall",controller:1},PLACE_NUDGE_CALL:{name:"PlaceNudgeCall",controller:5},UPDATE_CONVERSATION_LINKS:{name:"UpdateConversationLinks",controller:1},SEND_CONVERSATION_KEEP_ALIVE:{name:"SendConversationKeepAlive",controller:1},SEND_CALL_ATTACH:{name:"SendCallAttach",controller:0},SEND_CALL_PROGRESS:{name:"SendCallProgress",controller:0},SEND_KEEP_ALIVE:{name:"SendKeepAlive",controller:0},ADD_CONTENT_SHARING_MODALITY:{name:"AddContentSharingModality",controller:1},DELETE_CONTENT_SHARING:{name:"DeleteContentSharing",controller:3},TAKE_CONTROL_CONTENT_SHARING:{name:"TakeControlContentSharing",controller:3},UPDATE_SESSION_STATE_CONTENT_SHARING:{name:"UpdateSessionStateContentSharing",controller:3},JOIN_CONTENT_SHARING:{name:"JoinContentSharing",controller:3},UPDATE_PARTICIPANT_STATE_CONTENT_SHARING:{name:"UpdateParticipantStateContentSharing",controller:3},UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS:{name:"UpdateContentSharingNotificationLinks",controller:3},MUTE_ALL:{name:"MuteAll",controller:1},MUTE_ALL_SYNC:{name:"MuteAllSync",controller:1},MUTE_SPECIFIED:{name:"MuteSpecified",controller:1},MUTE_SPECIFIED_SYNC:{name:"MuteSpecifiedSync",controller:1},MUTE_MYSELF:{name:"MuteMyself",controller:1},UNMUTE:{name:"Unmute",controller:1},UNMUTE_SYNC:{name:"UnmuteMyselfSync",controller:1},SEND_CONTROL_VIDEO_STREAMING:{name:"SendControlVideoStreaming",controller:0},SEND_APPLY_CHANNEL_PARAMETERS:{name:"SendApplyChannelParameters",controller:0},APPROVE_UNMUTE:{name:"ApproveUnmute",controller:5},REJECT_UNMUTE:{name:"RejectUnmute",controller:5},SEND_CALL_REDIRECT_REQUEST:{name:"SendCallRedirectRequest",controller:0},SEND_TRANSFER_REQUEST:{name:"SendTransferRequest",controller:0},SEND_PARK_REQUEST:{name:"SendParkRequest",controller:0},SEND_SHARED_LINE_PARK_REQUEST:{name:"SharedLinePark",controller:0},SEND_SERVER_HOLD_REQUEST:{name:"ServerHoldRequest",controller:0},PARK_REQUEST:{name:"ParkRequest",controller:0},SEND_UNPARK_REQUEST:{name:"UnparkRequest",controller:0},TRANSFER_ACCEPTANCE:{name:"TransferAcceptance",controller:0},TRANSFER_COMPLETION:{name:"TransferCompletion",controller:0},TRANSFER_COMPLETION_FAILED:{name:"TransferCompletionFailed",controller:0},UPDATE_ENDPOINT_STATE:{name:"UpdateEndpointState",controller:1},DISABLE_PREHEAT:{name:"DisablePreheat",controller:5},REQUEST_NEW_OFFER:{name:"RequestNewOffer",controller:0},UPDATE_ENDPOINT_METADATA:{name:"UpdateEndpointMetadata",controller:1},UPDATE_MEETING_ROLE_ATTENDEE:{name:"UpdateMeetingRoleToAttendee",controller:1},UPDATE_MEETING_ROLE_PRESENTER:{name:"UpdateMeetingRoleToPresenter",controller:1},UPDATE_MEETING_ROLE_ORGANIZER:{name:"UpdateMeetingRoleToOrganizer",controller:1},ADD_PARTICIPANT_WITH_PICKUP_CODE:{name:"AddParticipantWithPickupCode",controller:1},PUBLISH_STATE:{name:"PublishState",controller:1},REMOVE_STATE:{name:"RemoveState",controller:1},UPDATE_MEETING_SETTINGS:{name:"UpdateMeetingSettings",controller:1},ADD_PARTICIPANTS_AND_MODALITY:{name:"AddParticipantsAndModality",controller:1},ADD_BROADCAST_MODALITY:{name:"AddBroadcastModality",controller:1},ADD_MODALITY:{name:"AddModality",controller:1},SEARCH_PARTICIPANTS:{name:"SearchParticipants",controller:1},GET_ALL_PARTICIPANTS:{name:"GetAllParticipants",controller:1},UPDATE_MEETING_LIVE_STATE:{name:"UpdateMeetingLiveState",controller:1},UPDATE_MEETING_GROUPS:{name:"UpdateMeetingGroups",controller:1},SET_MEETING_LAYOUT:{name:"SetMeetingLayout",controller:1},UPDATE_PARTICIPANT_INTERPRETATION_STATE:{name:"UpdateParticipantInterpretationState",controller:1},JOIN_MEETING_GROUP:{name:"JoinMeetingGroup",controller:1},LEAVE_MEETING_GROUP:{name:"LeaveMeetingGroup",controller:1},SEND_PROXIED_MESSAGE:{name:"SendProxiedMessage",controller:1},UPDATE_PARTICIPANTS_PROPERTIES:{name:"UpdateParticipantsProperties",controller:1},UPDATE_MEDIA_DESCRIPTIONS:{name:"UpdateMediaDescriptions",controller:0},UPDATE_MEETING_STATES:{name:"UpdateMeetingStates",controller:1},UPDATE_MONITOR_SESSION:{name:"UpdateMonitorSession",controller:0}},un={EVENT_SOURCE:{TROUTER:"Trouter",BROKER:"Broker",UDP:"UDP",LOCAL:"Local"},SOURCE:{NGC_SOURCE:"SkypeConcore"},EVENT_TYPE:{CONVERSATION_CALL_MODALITY:"skypecosi_concore_web_csa_conversation_callmodality",CONVERSATION_CONTENT_SHARING:"skypecosi_concore_web_csa_conversation_contentsharing",CONVERSATION_HTTP_REQUEST:"skypecosi_concore_web_csa_conversation_httprequest",CONVERSATION_TOKEN:"skypecosi_concore_web_csa_conversation_token"},EXTENSIONS:{DATA_VERSION:"DataVersion",DIRECTION:"Direction",CONTENT_SHARING_DIRECTION:"ContentSharingDirection",CONNECTED_DURATION_IN_MS:"ConnectedDurationInMsecs",PREHEATED_CALL_SETUP_DURATION_IN_S:"PreheatedCallSetupDurationInSeconds",CALL_CANCELATION_DURATION_IN_S:"CallCancelationDurationInSeconds",IS_PREHEATED:"IsPreheated",TIME_TO_RING_IN_MS:"TimeToRingInMsecs",CALL_TERMINATING_END:"CallTerminatingEnd",NETWORK_REQUESTS_PENDING:"NetworkRequestsPending",NETWORK_REQUESTS_COMPLETED:"NetworkRequestsCompleted",LOCAL_OPERATIONS_PERFORMED:"LocalOperationsPerformed",TROUTER_WAIT_OPERATIONS:"TrouterWaitOperations",CALL_START_TIME:"CallStartTime",CALL_END_TIME:"CallEndTime",IS_GROUP_CALL:"IsGroupCall",IS_HOSTLESS_CALL:"IsHostLessCall",IS_CAST_CALL:"IsCastCall",IS_HUDDLE_GROUP_CALL:"IsHuddleGroupCall",IS_MEETUP_CALL:"IsMeetupCall",IS_ON_BEHALF_OF_CALL:"IsOnBehalfOfCall",IS_SDP_IN_CALL_NOTIFICATION:"SdpInCallNotification",CALL_END_CODE:"Code",CALL_END_SUB_CODE:"SubCode",CALL_PHRASE:"Phrase",CALL_END_RESULT_CATEGORIES:"ResultCategories",CALL_END_CAUSE_ID:"CauseId",CONFLICTING_CALL_ID:"ConflictingCallId",CONTENT_SHARING_END_CODE:"ContentSharingEndReasonServiceCode",CONTENT_SHARING_END_SUB_CODE:"ContentSharingEndReasonServiceSubCode",CONVERSATION_SERVICE_URL:"ConversationServiceUrl",CONTENT_SHARING_SERVICE_URL:"ContentSharingServiceUrl",MEETING_INFO:"MeetingInfo",JOINED_FROM:"JoinedFrom",RESULT_VALUE:"ResultValue",RESULT_DETAIL:"ResultDetail",RESULT_CAUSE_ID:"ResultCauseId",RESULT_CODE:"ResultCode",LOCAL_OFFER_ANSWER_GENERATION_TIMESTAMPS:"LocalOfferAnswerGenerationTimestamps",SELF_PARTICIPANT_ROLE:"SelfParticipantRole",SCENARIO:"Scenario",CALLER_TYPE:"Caller_Type",CALLEE_TYPE:"Callee_Type",CALL_TYPE:"Call_Type",TEST_CONTEXT_ID:"Test_Context_Id",OUTGOING_MODALITIES:"Outgoing_Modalities",INCOMING_MODALITIES:"Incoming_Modalities",OFFERED_MODALITIES:"CallOfferredModalities",ANSWERED_MODALITIES:"CallAnsweredModalities",VBSS_OPERATIONS:"VBSS_Operations",CHANGING_CORRELATION_ID_NEW_ID:"ChangingCorrelationId_NewId",CHANGING_CORRELATION_ID_OLD_ID:"ChangingCorrelationId_OldId",MESSAGING_CHANNEL:"MessagingChannel",EVENT_TIMESTAMP_BAG:"EventTimestampBag",ROSTER_UPDATES_BAG:"RosterUpdatesBag",NETWORK_REQUESTS_BAG:"NetworkRequestBag",CLIENT_INFORMATION:"ClientInformation",ECS_ETAG:"EcsEtag",APPLICATION_TYPE:"ApplicationType",RING:"Ring",TENANT_ID:"TenantId",USER_HEX_CID:"UserHexCID",ACS_RESOURCE_ID:"AcsResourceId",REGION:"Region",PARTITION:"Partition",CALL_END_CLIENT_SUB_CODE:"CallEventCallEndClientSubCode",CALL_END_CLIENT_PHRASE:"CallEventCallEndClientPhrase",MEETING_CODE:"MeetingCode",MEETING_URL:"MeetingJoinUrl",BROADCAST_MEETING_ROLE:"BroadcastMeetingRole",MEETING_ROLE:"MeetingRole",ADVANCED_MEETING_ROLE:"AdvancedMeetingRole",MEETING_ROLES:"MeetingRoles",PARTICIPANT_TYPE:"ParticipantType",DISPLAY_NAME:"DisplayName",AUDIO_ONLY_WATERMARK:"ClientSupportsAudioOnlyWatermark",CLIENT_SUPPORT_WATERMARK:"ClientSupportsWatermark",TARGET_APPLICATION_TYPE:"TargetApplicationType",IS_REINVITELESS:"IsReinviteless",CLIENT_TYPE:"ClientType",CLIENT_SUPPORTS_PREVENT_SCREEN_CAPTURE:"ClientSupportsPreventScreenCapture"},MESSAGING_CHANNEL:{TROUTER:"Trouter",BROKER:"Broker"},SIGNALING_CONFIG:"JsCsaConfig",SIGNALING_CONFIG_FLAGS:{BROKER_OUTGOING_ENABLED:"BrokerOutgoingEnabled",BROKER_INCOMING_ENABLED:"BrokerIncomingEnabled",BROKER_REQUEST_BATCHING_ENABLED:"BrokerRequestBatchingEnabled",BROKER_EXCLUSIVELY_ENABLED:"BrokerExclusivelyEnabled",SUPPORTS_COMPRESSED_PAYLOAD:"SupportsCompressedPayload",SYNC_TROUTER_RESPONSE:"SyncTrouterResponse",SERVER_MUTE_UNMUTE:"serverMuteUnmute",HANDLE_OFFER_FROM_NOTIFICATION:"handleMediaOfferFromPushNotification",HANDLE_NEW_OFFER_REQUEST:"handleNewOfferRequest",SEND_PROGRESS_FROM_CC:"sendProgressFromCC",INTERNAL_HTTP_DISPATCHER:"internalHttpDispatcher",ENABLE_TOKEN_CACHE:"enableTokenCache",ENABLE_TOKEN_PREFETCH:"enableTokenPrefetch",REQUEST_HEDGING:"requestHedging",SUPPORT_MEDIA_RETARGET_WHILE_INCOMING_RENEGOTIATION:"supportMediaRetargetWhileIncomingRenegotiation",ENABLE_ERROR_CODE_IMPROVEMENTS_FOR_NETWORK_FAILURES:"enableErrorCodeImprovementsForNetworkFailures",ENABLE_CALL_ESTABLISHMENT_TIMEOUTS_FOR_START_OR_JOIN_CALL:"enableCallEstablishmentTimeoutsForStartJoinCall",ENABLE_TOKEN_CACHE_FOR_GENERIC_TOKEN_API:"enableTokenCacheForGenericTokenAPI",ENABLE_LONG_OUTGOING_1TO1_SETUP:"enableLongOutgoing1To1SetupTimeoutForWeb"},CONTEXT_ID:{CORRELATION_ID:"CorrelationId",SHARED_CORRELATION_ID:"SharedCorrelationId",SIGNALING_SESSION_ID:"SignalingSessionId",GROUP_ID:"GroupId",THREAD_ID:"ThreadId",TEAMS_MESSAGEID:"TeamsMessageId",TEAMS_MEETINGINFO:"TeamsMeetingInfo",ENDPOINT_ID:"EndpointId",PARTICIPANT_ID:"ParticipantId",DATA_VERSION:"DataVersion",CONTENT_SHARING_ID:"ContentSharingSessionId",CONTENT_SHARING_CORRELATION_ID:"ContentSharingCorrelationId"},CALL_TERMINATING_END:{LOCAL:"Local",REMOTE:"Remote"},RESULT_VALUE:{SUCCESS:"Success",FAILURE:"Failure"},DIRECTION:{INCOMING:"Incoming",OUTGOING:"Outgoing"},ROLE:{CALLER:"caller",CALLEE:"callee",JOIN:"join",JOIN_FOR_ROSTER_ONLY:"joinForRosterOnly",PREHEAT:"preheat"},VBSS_OPERATION:{START:"Start",STOP:"Stop",REJECTED:"Rejected",REMOTE_START:"RemoteStart",TIMEOUT:"Timeout",CALL_END:"CallEnd"},LOCAL_OFFER_ANSWER_OPERATIONS:{INITIAL_OFFER_GENERATION_STARTED:"InitialOfferGenerationStarted",INITIAL_OFFER_GENERATION_ENDED:"InitialOfferGenerationEnded",FINAL_ANSWER_PROCESSING_STARTED:"FinalAnswerProcessingStarted",FINAL_ANSWER_PROCESSING_ENDED:"FinalAnswerProcessingEnded",PROVISIONAL_ANSWER_PROCESSING_STARTED:"ProvisonalAnswerProcessingStarted",PROVISIONAL_ANSWER_PROCESSING_ENDED:"ProvisonalAnswerProcessingEnded",NEGOTIATION_COMPLETED:"NegotiationCompleted",INITIAL_OFFER_PROCESSING_STARTED:"InitialOfferProcessingStarted",INITIAL_OFFER_PROCESSING_ENDED:"InitialOfferProcessingEnded",FINAL_ANSWER_GENERATION_STARTED:"FinalAnswerGenerationStarted",FINAL_ANSWER_GENERATION_ENDED:"FinalAnswerGenerationEnded",PROVISIONAL_ANSWER_GENERATION_STARTED:"ProvisionalAnswerGenerationStarted",PROVISIONAL_ANSWER_GENERATION_ENDED:"ProvisionalAnswerGenerationEnded",RENEGOTIATION_OFFER_GENERATION_STARTED:"RenegotiationOfferGenerationStarted",RENEGOTIATION_OFFER_GENERATION_ENDED:"RenegotiationOfferGenerationEnded",RENEGOTIATION_ANSWER_PROCESSING_STARTED:"RenegotiationAnswerProcessingStarted",RENEGOTIATION_ANSWER_PROCESSING_ENDED:"RenegotiationAnswerProcessingEnded",RENEGOTIATION_OFFER_PROCESSING_STARTED:"RenegotiationOfferProcessingStarted",RENEGOTIATION_OFFER_PROCESSING_ENDED:"RenegotiationOfferProcessingEnded",RENEGOTIATION_ANSWER_GENERATION_STARTED:"RenegotiationAnswerGenerationStarted",RENEGOTIATION_ANSWER_GENERATION_ENDED:"RenegotiationAnswerGenerationEnded"},TROUTER_WAIT_OPERATION:{STARTED:"Started",ENDED:"Ended",FAILED:"Failed"},TOKEN_TELEMETRY_EVENT:{TOKEN_TELEMETRY:"TokenTelemetry"}};function setDefaultsForSignalingConfig(g){const f=!0,S="enabled",v=!1,C=!1,_=!0,T=!0,I=!0,b=!1,A=!1,P=!0,R=!0,M=!0,w=!0,O=!0,D=!1,N=!1,k=!1,L=!1,F=!1,x=!0,U=!0,V=!0,B=3,H=4e3,$=!1,j=!1,G=!1,q=!1,W=!1,z=!0,K={conversationKeepAliveTimeoutSec:2700,promotionUnmuteTimeoutSec:1e4},J=!1,Y=!1,Q=!1,X=!1,Z=3600,ee=86400,te=30,ie=!1,ne=!0,re=!0,se=60,ae="https://calling.teams.microsoft.com",oe=!0,le=!1,ce=!1,de=!1,he=!1,ue=!1,ge=!1,pe=0,me=0,fe=!1,Se=!1,ve=!1,Ce=!1,ye=!0,Ee=!1,_e=!1,Te=!1,Ie=!1,be=!1;g.cloudScreenSharingFlag="disabled"===g.cloudScreenSharingFlag?g.cloudScreenSharingFlag:S,g.isWebRtcEnabled="undefined"==typeof RTCIceGatherer,g.shouldServiceSendNGCUpgradeMessages=setDefault(g.shouldServiceSendNGCUpgradeMessages,_),g.isGVCOutgoingEnabled=setDefault(g.isGVCOutgoingEnabled,f),g.supportsCompressedServicePayload=setDefault(g.supportsCompressedServicePayload,T),g.supportsSynchronousTrouterResponse=setDefault(g.supportsSynchronousTrouterResponse,I),g.supportsHostlessGroupCalls=setDefault(g.supportsHostlessGroupCalls,P),g.doHostlessCalling=setDefault(g.doHostlessCalling,v),g.brokerExclusively=setDefault(g.brokerExclusively,D),g.brokerEnabledOutgoing=setDefault(g.brokerEnabledOutgoing,M),g.brokerEnabledIncoming=setDefault(g.brokerEnabledIncoming,w),g.brokerRequestBatching=setDefault(g.brokerRequestBatching,O),g.handleMediaOfferFromPushNotification=setDefault(g.handleMediaOfferFromPushNotification,x),g.handleNewOfferRequest=setDefault(g.handleNewOfferRequest,N),g.autoJoinOnConflict=setDefault(g.autoJoinOnConflict,R),g.endConflictedCall=setDefault(g.endConflictedCall,b),g.autoResolveConflictedCall=setDefault(g.autoResolveConflictedCall,A),g.shouldServiceSendCallEventMessages=setDefault(g.shouldServiceSendCallEventMessages,C),g.forceTrouterReconnectOnNetworkOnline=setDefault(g.forceTrouterReconnectOnNetworkOnline,U),g.attemptHttpRequestWithCachedSkypetoken=setDefault(g.attemptHttpRequestWithCachedSkypetoken,V),g.useInternalHttpDispatcher=setDefault(g.useInternalHttpDispatcher,k),g.enableTokenCache=setDefault(g.enableTokenCache,L),g.enableTokenPrefetch=setDefault(g.enableTokenPrefetch,F),g.hedgeDelayMs=setDefault(g.hedgeDelayMs,H),g.hedgeMaxParallelAttempts=setDefault(g.hedgeMaxParallelAttempts,B),g.useInternalHttpDispatcher&&(g.httpRequestDispatcher=new $e(g.logger)),g.enableQuickSendAcceptanceAck=setDefault(g.enableQuickSendAcceptanceAck,$),g.supportMediaRetargetWhileIncomingRenegotiation=setDefault(g.supportMediaRetargetWhileIncomingRenegotiation,j),g.callingServiceSupportsAADTokens=setDefault(g.callingServiceSupportsAADTokens,J),g.callingServiceSupportsCAETokens=setDefault(g.callingServiceSupportsCAETokens,Y),g.aadTokenExpirationTimeInSeconds=setDefault(g.aadTokenExpirationTimeInSeconds,Z),g.caeTokenExpirationTimeInSeconds=setDefault(g.caeTokenExpirationTimeInSeconds,ee),g.disableTokenMigrationHeader=setDefault(g.disableTokenMigrationHeader,Q),g.enablePublishTokenTelemetry=setDefault(g.enablePublishTokenTelemetry,X),g.forceClearExpiredTokens=setDefault(g.forceClearExpiredTokens,ie),g.enableRefreshToken=setDefault(g.enableRefreshToken,ne),g.refreshTimeBeforeTokenTimeoutInSeconds=setDefault(g.refreshTimeBeforeTokenTimeoutInSeconds,te),g.enableCallEstablishmentTimeoutsForStartJoinCall=setDefault(g.enableCallEstablishmentTimeoutsForStartJoinCall,G),g.csaTimeoutConfiguration=mergeObjects(g.csaTimeoutConfiguration,K),g.reportPreviousErrorsForTimeout=setDefault(g.reportPreviousErrorsForTimeout,de),g.callingTokenLogicalUrl=setDefault(g.callingTokenLogicalUrl,ae),g.enableAsyncDisablePreheat=setDefault(g.enableAsyncDisablePreheat,he),g.forceLowercaseHttpHeaders=setDefault(g.forceLowercaseHttpHeaders,ue),g.enableResolveScreenSharingWhenNegotiationComplete=setDefault(g.enableResolveScreenSharingWhenNegotiationComplete,ge),g.maxReinvitelessMediaForVideoForWeb=setDefault(g.maxReinvitelessMediaForVideoForWeb,pe),g.maxReinvitelessMediaForVBSSForWeb=setDefault(g.maxReinvitelessMediaForVBSSForWeb,me),g.enableRefreshTokenRetry=setDefault(g.enableRefreshTokenRetry,re),g.enableRefreshTokenRetryInSeconds=setDefault(g.enableRefreshTokenRetryInSeconds,se),g.enableConversationTypeUpdateOnCallEnd=setDefault(g.enableConversationTypeUpdateOnCallEnd,W),g.supportMissingTokenTypesInResponse=setDefault(g.supportMissingTokenTypesInResponse,oe),g.useSkypeTokenWhenNoAuthenticateHeader=setDefault(g.useSkypeTokenWhenNoAuthenticateHeader,le),g.enableAutoPromotion=setDefault(g.enableAutoPromotion,fe),g.enableBatchedSendMessageStatus=setDefault(g.enableBatchedSendMessageStatus,ve),g.enableBatchedReceiveMessage=setDefault(g.enableBatchedReceiveMessage,Se),g.enableAddParticipantEnhancements=setDefault(g.enableAddParticipantEnhancements,Ce),g.enableTokenCacheForGenericTokenAPI=setDefault(g.enableTokenCacheForGenericTokenAPI,ce),g.disableRealTimeModeFromRoster=setDefault(g.disableRealTimeModeFromRoster,ye),g.enableLongOutgoing1To1SetupTimeoutForWeb=setDefault(g.enableLongOutgoing1To1SetupTimeoutForWeb,q),g.checkAttendeeRoleInCreateContentSharing=setDefault(g.checkAttendeeRoleInCreateContentSharing,z),g.enableSpecificErrorCodesForCallEnd=setDefault(g.enableSpecificErrorCodesForCallEnd,Ee),g.enableSplitConversationEndUrl=setDefault(g.enableSplitConversationEndUrl,_e),g.enableFetchRequestWithKeepAlive=setDefault(g.enableFetchRequestWithKeepAlive,Te),g.enableFetchApi=setDefault(g.enableFetchApi,Ie),g.enableFetchApiForBeacon=setDefault(g.enableFetchApiForBeacon,be)}function setDefault(g,f){return null==g?f:g}function mergeObjects(g,f){return(f||g)&&{...f,...g}}var gn=class{constructor(){this.skypeTokenContext={},this.aadTokenContext={},this.caeTokenContext={}}getTokenContext(g){return 4===g?this.aadTokenContext:8===g?this.caeTokenContext:1===g?this.skypeTokenContext:void 0}getTokenExpiry(g,f){return 4===g?this.aadTokenContext?.expiryTime:8===g?this.caeTokenContext?.expiryTime:1===g?this.skypeTokenContext?.expiryTime:(f?.info("[getTokenExpiry] unrecognized token type, return Number.MAX_VALUE"),Number.MAX_VALUE)}getToken(g,f,S,v){return 8&g&&this.caeTokenContext?.token&&this.caeTokenContext.token!==v?{token:this.caeTokenContext.token,tokenType:8}:4&g&&this.aadTokenContext?.token&&this.aadTokenContext.token!==v?{token:this.aadTokenContext.token,tokenType:4}:1&g&&this.skypeTokenContext?.token&&this.skypeTokenContext.token!==v?{token:this.skypeTokenContext.token,tokenType:1}:(S?.info(`[getToken] no cached token found of token type: ${g}`),null)}setToken(g,f,S,v){switch(g){case 4:this.aadTokenContext.factorsJson=S,this.aadTokenContext.tokenType=g,this.aadTokenContext.token=f,this.aadTokenContext.expiryTime=v;break;case 1:this.skypeTokenContext.factorsJson=S,this.skypeTokenContext.tokenType=g,this.skypeTokenContext.token=f,this.skypeTokenContext.expiryTime=v;break;case 8:this.caeTokenContext.factorsJson=S,this.caeTokenContext.tokenType=g,this.caeTokenContext.token=f,this.caeTokenContext.expiryTime=v;break;default:throw new Error(`Invalid tokenType ${g}`)}}clearExpiredTokens(g){const f=Math.round(Date.now()/1e3);this.caeTokenContext?.expiryTime<=f&&(this.resetToken(8),g?.info("[cacheTokenManager] reset expired cae token")),this.aadTokenContext?.expiryTime<=f&&(this.resetToken(4),g?.info("[cacheTokenManager] reset expired aad token")),this.skypeTokenContext?.expiryTime<=f&&(this.resetToken(1),g?.info("[cacheTokenManager] reset expired skype token"))}resetToken(g){8===g?this.caeTokenContext={}:4===g?this.aadTokenContext={}:1===g&&(this.skypeTokenContext={})}},pn=class{constructor(g){this.timers={},this.startTimer=(g,f,S,v)=>{this.logger.info(`startTimer called for :  ${g} with timeoutInSeconds : ${S}s`);const C=window.setTimeout(f,1e3*S),_=v?`${g}${v}`:g;this.timers[_]=C},this.stopTimer=(g,f)=>{this.logger.info(`stopTimer called for : ${g}`);const S=f?`${g}${f}`:g;this.timers.hasOwnProperty(S)&&(clearTimeout(this.timers[S]),delete this.timers[S])},this.dispose=()=>{this.logger.info("timeoutManager :: dispose"),Object.keys(this.timers).forEach((g=>{this.stopTimer(g)}))},this.logger=g}},mn=3600,fn=class{constructor(g,f,S,v){this.tokenProvider=f,this.tokenCachingEnabled=!1,this.enableTokenCacheForGenericTokenAPI=!1,this.cachedToken="",this.lastTokenType=1,this.lastToken="",this.clientSupportsGenericTokenAPI=!1,this.stopTimerFlag=!1,this.tokensPromiseMap={},this.logger=g.createChild("TokenManager"),S&&this.updateTokenSettings(S),this.cacheTimers=new pn(g),this.cacheTokenManager=new gn,this.telemetryManager=v,this.nextRefreshTimePointInSeconds=Number.MAX_VALUE}deletePromisesByTriggeredByRefresh(g,f){if(this.tokensPromiseMap[g]){const S=this.tokensPromiseMap[g];for(let v=S.length-1;v>=0;v--)S[v]?.tokenRequestOptions.triggeredByRefresh===f&&this.tokensPromiseMap[g].splice(v,1)}}startTokenRefreshTimer(g){const f="startTokenRefreshTimer";if(!this.enableRefreshToken)return void this.logger.info("[startTokenRefreshTimer] token refresh is disabled");if(this.stopTimerFlag)return this.logger.info("[startTokenRefreshTimer] stopTimerFlag=true so cancel timer"),void this.cacheTimers.dispose();this.logger.info(`[startTokenRefreshTimer] starting token refresh timer timeToStartInMilliseconds=${g}`);const S=epochTimeInSecRoundedDown(),v=millieSecondsToSeconds(g),C=S+v;this.nextRefreshTimePointInSeconds===Number.MAX_VALUE||this.nextRefreshTimePointInSeconds<S||C<this.nextRefreshTimePointInSeconds?(this.logger.info("[startTokenRefreshTimer] cancelling current refresh timer to create new one with shorter time"),this.cacheTimers.stopTimer(f),this.nextRefreshTimePointInSeconds=C,this.logger.info(`[startTokenRefreshTimer] start new timer with timeout=${v} at time=${S}`),this.cacheTimers.startTimer(f,(()=>{this.nextRefreshTimePointInSeconds=Number.MAX_VALUE,this.refreshToken()}),v)):this.logger.info("[startTokenRefreshTimer] no need to set a new refresh timer")}async refreshTokenWithContext(g){const f={triggeredByRefresh:!0},S=newGuid2(),v={causeId:S},C=Date.now();let _,T,I,b=2;this.logger.info(`[${S}][refreshTokenWithContext] refreshing token tokenType=${g.tokenType} factorsJson=${g.factorsJson}`);let A=null;try{const f=this.onTokenRequired({factorsJson:g.factorsJson,tokenType:g.tokenType,requestMetadataJson:v,invalidToken:void 0,isUnauthorized:void 0,triggeredByRefresh:!0}),C=await this.timeoutPromiseRace(f,this.enableRefreshTokenRetryInSeconds,"ActiveRefresh Token Timeout");_=Date.now(),I=C?.causeId,A=C?.tokenType,this.lastTokenType=A,this.lastToken=C.token,b=1,this.logger.info(`[${S}][refreshTokenWithContext] refresh token success for factorsJson ${g.factorsJson} and tokenType ${g.tokenType}`)}catch(f){T=f,I=T?.causeId,f?.timeOut?(this.logger.info(`[${S}][refreshTokenWithContext] refresh token timeout, UI did not respond with token in time ${getPrintableObject(f)}`),b=5):(this.logger.info(`[${S}][refreshTokenWithContext] failed to refresh token, UI did not respond with token ${getPrintableObject(f)}`),b=2),_=Date.now(),this.deletePromisesByTriggeredByRefresh(g.factorsJson,!0)}finally{f&&(f.requestCauseId=S,f.responseCauseId=I,f.supportTokenApi=this.clientSupportsGenericTokenAPI,f.requestTokenFactors=g.factorsJson,f.tokenRequestTime=C,f.tokenResponseTime=_,f.tokenRequestStatus=b,f.requestTokenType=g.tokenType,f.foundInCache=!1,f.responseTokenType=A,f.errorCode=T?.errorCode,f.errorSubCode=T?.errorSubCode,this.sendTokenTelemetry(f))}}refreshToken(){if(!this.clientSupportsGenericTokenAPI)return void this.logger.info("[refreshToken] refresh token is not supported due to new Token Api is not enabled");if(!this.enableTokenCacheForGenericTokenAPI)return void this.logger.info("[refreshToken] refresh token is not supported due to caching being disabled");const g=this.cacheTokenManager.getTokenContext(4),f=this.cacheTokenManager.getTokenContext(8),S=this.cacheTokenManager.getTokenContext(1);if(!g&&!f&&!S)return void this.logger.info("[refreshToken] no cached tokens available to refresh");const v=epochTimeInSecRoundedDown()+this.refreshTimeBeforeTokenTimeoutInSeconds;let C=Number.MAX_VALUE,_=!1;if(g)if(g.expiryTime>v){const f=g?.expiryTime-v;f<C&&(C=f)}else g.expiryTime<=v&&(this.refreshTokenWithContext(g),_=!0);if(f)if(f.expiryTime>v){const g=f?.expiryTime-v;g<C&&(C=g)}else f.expiryTime<=v&&(this.refreshTokenWithContext(f),_=!0);if(S)if(S.expiryTime>v){const g=S?.expiryTime-v;g<C&&(C=g)}else S.expiryTime<=v&&(this.refreshTokenWithContext(S),_=!0);_&&this.enableRefreshTokenRetry&&this.enableRefreshTokenRetryInSeconds>0&&this.enableRefreshTokenRetryInSeconds<C&&(C=this.enableRefreshTokenRetryInSeconds),C>=0&&C!==Number.MAX_VALUE&&this.startTokenRefreshTimer(secondsToMillieSeconds(C))}async getTokenWithTokenType(g,f=!1,S,v){this.logger.info(`[${g}][getTokenWithTokenType] call with factorJson=${S?.factorsJson} and request tokenType ${S?.tokenType}`);const{factorsJson:C,requestMetadataJson:_,invalidToken:T,isUnauthorized:I}=S||{},b=Date.now(),A=S?.tokenType;let P,R,M,w=2,O=null;this.clearExpiredTokens(),this.startTokenRefreshTimer(1);try{if(f)this.invalidateCachedTokenWithTokenType(A,T,C);else if(this.enableTokenCacheForGenericTokenAPI){const f=this.cacheTokenManager.getToken(A,C,this.logger,T);if(f?.token)return this.logger.info(`[${g}][getTokenWithTokenType] returning cached token for factorsJson ${C} and request tokenType ${A}, response tokenType ${f.tokenType}`),w=3,P=Date.now(),O=f.tokenType,this.lastToken=f.token,this.lastTokenType=O,f}this.logger.info(`[${g}][getTokenWithTokenType] fetching new token for factorsJson ${C} and tokenType ${A}`);const S=_||{};S.causeId=g;const v=this.onTokenRequired({factorsJson:C,tokenType:A,requestMetadataJson:S,invalidToken:T,isUnauthorized:I,triggeredByRefresh:!1}),b=await this.timeoutPromiseRace(v,an.TIMEOUT_VALUES_IN_SECONDS.TOKEN_REQUIRED_TIMEOUT,"Token not received from UI in time");return P=Date.now(),M=b?.causeId,O=b?.tokenType,this.lastToken=b?.token,this.lastTokenType=O,w=1,this.logger.info(`[${g}][getTokenWithTokenType] fetching new token success for factorsJson ${C} and tokenType ${A}`),b}catch(f){throw this.logger.info(`[${g}][getTokenWithTokenType] failed to fetch token ${getPrintableObject(f)}`),R=f,M=R?.causeId,R.timeOut&&(w=4),this.deletePromisesByTriggeredByRefresh(C,!1),f}finally{const f=!v?.tokenTelemetryData,C=f?{}:v?.tokenTelemetryData;C&&(C.requestCauseId=g,C.responseCauseId=M,C.supportTokenApi=this.clientSupportsGenericTokenAPI,C.requestTokenFactors=S?.factorsJson,C.tokenRequestTime=b,C.tokenResponseTime=P,C.tokenRequestStatus=w,C.requestTokenType=S?.tokenType,C.foundInCache=3===w,C.responseTokenType=O,C.timeToResponse=P?P-b:P,C.errorCode=R?.errorCode,C.errorSubCode=R?.errorSubCode),(!v||f&&!v.signalingSession)&&(this.logger?.info("[getTokenWithTokenType] TokenContext is not provided, sending token telemetry to Token table"),this.sendTokenTelemetry(C))}}async onTokenRequired(g){const{factorsJson:f,tokenType:S,requestMetadataJson:v,invalidToken:C,isUnauthorized:_,triggeredByRefresh:T}=g;if(this.logger.info(`[onTokenRequired] factorsJson=${f} tokenType=${S}`),!S)return this.logger.info(`[onTokenRequired] factorsJson=${f} with no token type`),Promise.reject({errorCode:an.HTTP_STATUS_CODES.UNAUTHORIZED,errorSubCode:0,causeId:v?.causeId});if(this.tokensPromiseMap[f]&&!T)for(const g of this.tokensPromiseMap[f])if(g.tokenRequestOptions.tokenType===S)return this.logger.info(`[onTokenRequired] factorsJson=${f} and tokenType ${S} has pending request`),g.defered.promise;this.tokensPromiseMap[f]||(this.tokensPromiseMap[f]=[]);const I=new dt;return this.tokensPromiseMap[f].push({tokenRequestOptions:g,defered:I}),this.tokenCallback({factorsJson:f,tokenType:S,requestMetadataJson:v,invalidToken:C,isUnauthorized:_}),I.promise}setTokenCaching(g,f){this.tokenCachingEnabled!==g&&(this.logger.info(`[authTokenManager]setTokenCaching=${g}`),this.tokenCachingEnabled=g)}setTokenCachingForGenericTokenAPI(g,f){this.enableTokenCacheForGenericTokenAPI!==g&&(this.logger.info(`[authTokenManager]setTokenCachingForGenericTokenAPI=${g}`),this.enableTokenCacheForGenericTokenAPI=g)}calculateTokenExpiry(g,f,S){const{factorsJson:v,tokenType:C}=f;let _=S-epochTimeInSecRoundedDown(),T=_,I=S;if(_&&_>0&&_>this.refreshTimeBeforeTokenTimeoutInSeconds){switch(C){case 4:_>this.aadTokenExpirationTimeInSeconds&&(_=this.aadTokenExpirationTimeInSeconds);break;case 8:_>this.caeTokenExpirationTimeInSeconds&&(_=this.caeTokenExpirationTimeInSeconds);break;default:_>mn&&(_=mn)}T=_-this.refreshTimeBeforeTokenTimeoutInSeconds,I=T+epochTimeInSecRoundedDown()}return this.logger.info(`[${g}][calculateTokenExpiry] calculate expiry to ${I} tokenType=${C} factorsJson=${v}`),I}addToCache(g,f,S,v){this.clearExpiredTokens(),this.cacheTokenManager.setToken(g,f,S,v)}clearExpiredTokens(){this.forceClearExpiredTokens&&this.cacheTokenManager.clearExpiredTokens(this.logger)}async getToken(g,f=!1,S,v){if(this.clientSupportsGenericTokenAPI){this.logger.info(`[${g}][getToken] callingTokenAPI is enabled so using new API to fetch it`);const{token:C}=await this.getTokenWithTokenType(g,f,S,v);return C}const C=Date.now();let _,T,I=2;try{if(f&&this.invalidateCachedToken(g),this.cachedToken&&this.tokenCachingEnabled)return this.logger.info(`[${g}][getToken] returning cached token`),I=3,this.lastTokenType=1,Promise.resolve(this.cachedToken);this.logger.info(`[${g}][getToken] fetching new token`);const S=await this.tokenProvider();return _=Date.now(),S?(this.tokenCachingEnabled&&(this.cachedToken=S),I=1,this.lastToken=S,this.lastTokenType=1,this.logger.info(`[${g}][getToken] fetching new token success`),S):(this.logger.info(`[${g}][getToken] received empty token`),Promise.reject("Received empty token"))}catch(f){throw this.logger.info(`[${g}][getToken] failed to fetch token=${getPrintableObject(f)}`),T=f,this.cachedToken="",f}finally{const f=v?.tokenTelemetryData;f&&(f.requestCauseId=g,f.supportTokenApi=this.clientSupportsGenericTokenAPI,f.requestTokenFactors=S?.factorsJson,f.tokenRequestTime=C,f.tokenResponseTime=_,f.tokenRequestStatus=I,f.requestTokenType=S?.tokenType,f.foundInCache=3===I,f.responseTokenType=this.lastTokenType,f.timeToResponse=_?_-C:_,f.errorCode=T?.errorCode,f.errorSubCode=T?.errorSubCode)}}invalidateCachedToken(g){this.cachedToken&&(this.logger.info(`[${g}][invalidateCachedToken]`),this.cachedToken="")}invalidateCachedTokenWithTokenType(g,f,S){8===g&&this.cacheTokenManager.getToken(8,S,this.logger)?.token===f&&(this.cacheTimers.stopTimer(S,g.toString()),this.cacheTokenManager.resetToken(8)),4===g&&this.cacheTokenManager.getToken(4,S,this.logger)?.token===f&&(this.cacheTimers.stopTimer(S,g.toString()),this.cacheTokenManager.resetToken(4)),1===g&&this.cacheTokenManager.getToken(1,S,this.logger)?.token===f&&(this.cacheTimers.stopTimer(S,g.toString()),this.cacheTokenManager.resetToken(1))}getLastToken(g){return this.logger.info(`[${g}][getLastToken]`),this.lastToken}async timeoutPromiseRace(g,f,S){let v;const C=new Promise(((g,C)=>{v=window.setTimeout((()=>{C({phrase:S,timeOut:!0})}),secondsToMillieSeconds(f))}));return Promise.race([g.then((g=>(clearTimeout(v),g))),C])}getLastTokenType(g){return this.logger.info(`[${g}][getLastTokenType] lastTokenType=${this.lastTokenType}`),this.lastTokenType}updateTokenSettings(g){const{clientSupportsGenericTokenAPI:f,aadTokenExpirationTimeInSeconds:S,caeTokenExpirationTimeInSeconds:v,refreshTimeBeforeTokenTimeoutInSeconds:C,enablePublishTokenTelemetry:_,enableRefreshToken:T,forceClearExpiredTokens:I,enableRefreshTokenRetry:b,enableRefreshTokenRetryInSeconds:A}=g;this.logger.info(`updateTokenSettings ${JSON.stringify(g)}`),this.clientSupportsGenericTokenAPI=f??this.clientSupportsGenericTokenAPI,this.aadTokenExpirationTimeInSeconds=S??this.aadTokenExpirationTimeInSeconds,this.caeTokenExpirationTimeInSeconds=v??this.caeTokenExpirationTimeInSeconds,this.refreshTimeBeforeTokenTimeoutInSeconds=C??this.refreshTimeBeforeTokenTimeoutInSeconds,this.enablePublishTokenTelemetry=_??this.enablePublishTokenTelemetry,this.forceClearExpiredTokens=I??this.forceClearExpiredTokens,this.enableRefreshToken=T??this.enableRefreshToken,this.enableRefreshTokenRetry=b??this.enableRefreshTokenRetry,this.enableRefreshTokenRetryInSeconds=A??this.enableRefreshTokenRetryInSeconds}updateToken(g,f,S,v,C){if(this.logger.info(`[${v}][updateToken] UI replies with a token with factorsJson=${g} updateMetadata=${JSON.stringify(f)} tokenExpirySecSinceEpoch?=${C}`),f.error){this.logger.info(`[${v}][updateToken] UI replies with error ${f.error} for factorsJson ${g}`);for(const S of this.tokensPromiseMap[g])S.tokenRequestOptions.requestMetadataJson.causeId===v&&S.defered.reject({phrase:f.error?.phrase,errorCode:f.error?.code,errorSubCode:f.error?.subCode,causeId:v});return}if(!S){this.logger.info(`[${v}][updateToken] received empty token`);for(const f of this.tokensPromiseMap[g])f.tokenRequestOptions.requestMetadataJson.causeId===v&&f.defered.reject({phrase:"Received empty token",causeId:v});return}if(C>epochTimeInSecRoundedDown()&&this.enableTokenCacheForGenericTokenAPI){this.logger.info(`[${v}][updateToken] caching Token with tokenType=${f.tokenType}`);const _={factorsJson:g,tokenType:f.tokenType,invalidToken:S};this.addToCache(f.tokenType,S,g,this.calculateTokenExpiry(v,_,C))}if(!this.tokensPromiseMap[g]){this.logger.warn(`[updateToken]: UI tries to update token with invalid factorsJson=${g}`);const S={responseCauseId:v,supportTokenApi:this.clientSupportsGenericTokenAPI,requestTokenFactors:g,tokenResponseTime:Date.now(),tokenRequestStatus:6,responseTokenType:f.tokenType};return void this.sendTokenTelemetry(S)}if(this.tokensPromiseMap[g]){const C=this.tokensPromiseMap[g];for(let _=C.length-1;_>=0;_--)(C[_]?.tokenRequestOptions.tokenType&f.tokenType)>0&&(C[_].defered.resolve({token:S,tokenType:f.tokenType,causeId:v}),this.tokensPromiseMap[g].splice(_,1))}if(this.logger.info(`[${v}][updateToken] resolved and upateToken with factorsJson=${g} tokenType=${f.tokenType}`),0===this.tokensPromiseMap[g].length&&delete this.tokensPromiseMap[g],4!==f.tokenType&&8!==f.tokenType&&1!==f.tokenType)return;if(Object.keys(this.tokensPromiseMap).length>0)for(const C of Object.values(this.tokensPromiseMap))for(let _=C.length-1;_>=0;_--){const T=C[_];T.tokenRequestOptions.factorsJson!==g&&(T.tokenRequestOptions.tokenType&f.tokenType)>0&&!T.tokenRequestOptions.isUnauthorized&&(T.defered.resolve({token:S,tokenType:f.tokenType,causeId:v}),C.splice(_,1))}for(const g of Object.keys(this.tokensPromiseMap))0===this.tokensPromiseMap[g].length&&delete this.tokensPromiseMap[g];const _=C-epochTimeInSecRoundedDown();this.startTokenRefreshTimer(_>=0?secondsToMillieSeconds(_):0)}setTokenRequiredCallBack(g){this.tokenCallback=g}setDisableTimerFlag(g){this.logger.info(`[setDisableTimerFlag] set disableTimerFlag to ${g}`),this.stopTimerFlag=g}sendTokenTelemetry(g){if(!this.enablePublishTokenTelemetry)return;const f={};f[un.TOKEN_TELEMETRY_EVENT.TOKEN_TELEMETRY]=JSON.stringify(g),this.telemetryManager?(this.logger.info("[sendTokenTelemetry] sending token telemetry:",f),this.telemetryManager.sendEvent(un.EVENT_TYPE.CONVERSATION_TOKEN,f)):this.logger.warn("[sendTokenTelemetry] telemetryManager is undefined, cannot send token telemetry")}dispose(){this.cacheTimers&&this.cacheTimers.dispose()}},Sn={build:(g,f,S,v)=>new fn(g,f,S,v)},vn=class{constructor(g){this.piiScrubber=this.getPiiScrubber(g)}scrubParticipantsList(g){const f=[];return Array.isArray(g)&&g.forEach((g=>f.push(this.scrubMriOrOmit(g)))),f}scrubMriOrOmit(g){return"string"==typeof g?this.piiScrubber.mri(g):this.piiScrubber.omit(g)}getPiiScrubber(g){return g&&"function"==typeof g.omit&&"function"==typeof g.mri?g:{omit:()=>"<pii:omit/>",mri:()=>"<pii:mri/>"}}},Cn=__toESM2(M);function getMediaLabel(g){switch(g){case 0:return"main-audio";case 1:return"main-video";case 2:return"applicationsharing-video";case 3:return"data"}throw new Error("Invalid media type")}function mapMediaTypeStringToMediaType(g){switch(g){case"audio":return 0;case"video":return 1;case"applicationsharing-video":case"xapplicationsharing-video":return 2;case"data":return 3;default:return}}function hasParticipantLegId(g,f){return g.endpoints?.endpointDetails?.some((g=>g.participantId===f))??!1}function findSelfEndpointDetailUsingParticipantLegId(g,f){return g.endpoints?.endpointDetails.find((g=>g.participantId===f))}function findParticipantUsingParticipantLegId(g,f){return g.participants.find((g=>hasParticipantLegId(g,f)))}function hasStagingGroup(g){return!!g?.meetingGroupDetails?.groups&&Object.keys(g.meetingGroupDetails.groups).some((g=>"stagingGroup"===g))}function getSourceIdForMediaType(g,f){let S=-1;try{if(g.endpoints)e:for(const v of g.endpoints.endpointDetails)if(void 0!==v?.mediaStreams){for(const g of v.mediaStreams)if(mapMediaTypeStringToMediaType(g.type)===f){S=g.sourceId;break e}}else S=Ai}catch(g){return-1}return S}function getSourceId(g,f,S){if(!g?.endpoints)return-1;const v=g.endpoints.endpointDetails.find((g=>g?.participantId===f));if(!v?.mediaStreams)return getSourceIdForMediaType(g,S);const C=v.mediaStreams.find((({type:g})=>mapMediaTypeStringToMediaType(g)===S));return C?C.sourceId:-1}function getParticipantIdForSourceId(g,f,S){try{if(!g.endpoints)return;for(const v of g.endpoints.endpointDetails)if(v?.mediaStreams)for(const g of v.mediaStreams)if(S===g.sourceId&&mapMediaTypeStringToMediaType(g.type)===f)return v.participantId??null;return}catch(g){return}}function isScreenSharerStream(g){return"sendonly"===g.direction&&"applicationsharing-video"===g.label}function getSharingParticipantLeg(g){if(g.endpoints?.endpointDetails)return 1===g.endpoints.endpointDetails.length?g.endpoints.endpointDetails[0].participantId:g.endpoints.endpointDetails.find((g=>g?.mediaStreams?.some(isScreenSharerStream)))?.participantId}function getParticipantLegFromStreamSourceId(g,f){return g.endpoints?.endpointDetails?.find((g=>g.mediaStreams?.find((g=>g.sourceId===f))))}function processTransactionResponse(g){let f={};if(g.stateId)f.result=g.stateId;else if(g.results){const{results:S}=g;1===S.length&&S[0].stateId&&(f.result=S[0].stateId);const v={};g.results.forEach((g=>{const{result:S}=g,C=getParticipantId(g);(void 0===f.code||S.code>f.code)&&(f.code=S.code,f.subCode=S.subCode),v[C]=g})),f.result=JSON.stringify(v)}else g.result&&(f={code:g.result.code,phrase:g.result.phrase,subCode:g.result.subCode,resultCategories:g.result.resultCategories},g.additionalDetail&&(f.result=g.additionalDetail));return f}function getParticipantId(g){return g.participantId||g.participant&&g.participant.id}var yn=class{constructor(g,f){this.broadcastContext=null,this.broadcastControllerUrl="",this.broadcastCallbackUrl="",this.broadcastState=null,this.setContext=(g=null)=>{this.logger.info("BroadcastSession :: set broadcast context",g),this.broadcastContext=g},this.getContext=()=>(this.logger.info("BroadcastSession :: get broadcast context",this.broadcastContext||null),this.broadcastContext||null),this.signalingSession=g,this.signalingSessionCallback=f,this.logger=g.logger.createChild((()=>"[Broadcast]"))}handleBroadcastStateChanged(g){const f=g.body;this.broadcastState=f;const S=extractCauseIdFromMessage(g);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.BROADCAST_STATE_CHANGED,g),this.logger.info(`[${S}] broadcast state changed=${this.broadcastState}`),this.updateBroadcastMetadata(S)}updateBroadcastCallbackUrl(g){const f=get2(this.signalingSession,rn.CONV_BROADCAST_UPDATE);this.broadcastCallbackUrl!==f&&(this.broadcastCallbackUrl=f,this.logger.info(`[${g}] broadcast callback url changed=${this.broadcastCallbackUrl}`),this.updateBroadcastMetadata(g))}handleBroadcastDetailsChanged(g,f){this.signalingSession.telemetryHelper.recordEvent(dn.UPDATE_BROADCAST_DETAILS,{causeId:f}),g.activeModalities&&g.activeModalities.broadcast&&g.activeModalities.broadcast.controller!==this.broadcastControllerUrl&&(this.broadcastControllerUrl=g.activeModalities.broadcast.controller,this.broadcastAdditionalData=g.activeModalities.broadcast,this.logger.info(`[${f}] broadcast controller changed=${this.broadcastControllerUrl}`),this.signalingSessionCallback.onBroadcastMeetingConnected(an.SUCCESS_TRANSACTION_END,f),this.updateBroadcastMetadata(f)),!this.broadcastControllerUrl||g.activeModalities&&g.activeModalities.broadcast||(this.broadcastControllerUrl="",this.broadcastContext=null,this.logger.info(`[${f}] broadcast controller changed=${this.broadcastControllerUrl}`),this.updateBroadcastMetadata(f),this.signalingSessionCallback.onBroadcastMeetingEnded(an.SUCCESS_TRANSACTION_END,f))}handleAddBroadcastModalitySuccess(g,f){this.logger.info(`[${f}][handleAddBroadcastModalitySuccess]`)}handleAddBroadcastModalityFailure(g,f){this.logger.info(`[${f}][handleAddBroadcastModalityFailure]`);const S={...g.modalityFailure.broadcast};this.signalingSessionCallback.onBroadcastMeetingEnded(S,f)}updateBroadcastMetadata(g){const f={broadcastControllerUrl:this.broadcastControllerUrl,broadcastStateCallbackUrl:this.broadcastCallbackUrl,broadcastState:this.broadcastState,broadcastAdditionalData:this.broadcastAdditionalData};this.logger.info(`[${g}] update broadcast metadata=${f}`),this.signalingSessionCallback.onBroadcastMeetingUpdated&&this.signalingSessionCallback.onBroadcastMeetingUpdated(f,g)}},En="http://broker.invalid/",_n=30,Tn=5,In=1,bn=class{constructor(g){this._signalingSession=g,this.baseUrl=En,this.currentSubscriptionUrl=null,this._currentSubscriptionTimeoutInSec=_n,this._subscribers=[],this._disposed=!1,this._reportedResultCount=0,this._subscriptionRetryBackoffInSec=Tn,this._notifySubscribers=g=>{this._logger.info("_notifySubscribers"),Promise.resolve().then((()=>{g.split(",").forEach((g=>{const f=parseRawHttpMessage(decodeMessage(g));let S=f.body;isEncodedMessage(f.headers)&&isMessageEncodingSupported(f.headers)&&(S=decodeMessage(S));const v={url:f.url,body:JSON.parse(S),headers:f.headers};this._logger.info("message length=",S.length,"n. of subscribers",this._subscribers.length),this._subscribers.forEach((g=>g(v)))}))})).catch((g=>{this._logger.error("_notifySubscribers, failed to decode message",g),this._signalingSession.telemetryHelper.recordEvent(dn.BROKER_DECODE_PAYLOAD_FAILURE)}))},this._subscribeToBroker=(g,f)=>{if(this._disposed)return void this._logger.warn("_subscribeToBroker, disposed, ignore subscription");const S=causeId2();this._logger.info("_subscribeToBroker, url: ",g,",timeout in sec",f),this.currentSubscriptionUrl=g,this._currentSubscriptionTimeoutInSec=f,this._clearAllPendingTimeouts(),this._setSubscriptionTimeout(f),this._signalingSession.http.sendGetRequest({url:this.currentSubscriptionUrl,requestName:hn.BROKER_SUBSCRIBE.name,customHeaders:this._getBrokerRequestHeaders(S),payload:null,skipHttpTelemetry:!this._reportSubscriptionInTelemetry(),causeId:causeId2(),operationType:"BrokerSubscribe"}).then(this._handleSubscriptionSuccess).catch(this._handleSubscriptionFailure)},this._clearAllPendingTimeouts=()=>{this._cancelRequestTimer&&(this._cancelRequestTimer.stop(),this._cancelRequestTimer=null),this._retryRequestTimer&&(this._retryRequestTimer.stop(),this._retryRequestTimer=null)},this._abortPendingRequest=()=>{this._signalingSession.http.cancelRequestIfPending(hn.BROKER_SUBSCRIBE.name,causeId2())},this._setSubscriptionTimeout=g=>{this._cancelRequestTimer=ht.build((()=>{this._disposed||(this._signalingSession.http.hasPendingRequest(hn.BROKER_SUBSCRIBE.name)?(this._logger.warn("timeout subscription"),this._signalingSession.telemetryHelper.recordEvent(dn.BROKER_SUBSCRIPTION_TIMEOUT),this._signalingSession.http.cancelRequestIfPending(hn.BROKER_SUBSCRIBE.name,causeId2())):this._logger.error("Unable to resolve timeout deferred, it is not defined!"))}),"TIMEOUT").start(1e3*g)},this._handleSubscriptionSuccess=g=>{if(this._disposed)this._logger.warn("_handleSubscriptionSuccess, disposed, ignore subscription success");else if(this._reportSubscriptionInTelemetry(g)&&this._signalingSession.telemetryHelper.recordEvent(dn.BROKER_SUBSCRIPTION_SUCCESSFUL),g?.response){const f=g.response;this._logger.info("_handleSubscriptionSuccess, response",f),f.message&&this._notifySubscribers(f.message);const S=f.nextSubscribeUrl||this.currentSubscriptionUrl,v=f.expirationTimeInSec||this._currentSubscriptionTimeoutInSec;this._subscribeToBroker(S,v)}else this._logger.info("_handleSubscriptionSuccess, empty response")},this._handleSubscriptionFailure=g=>{if(this._disposed)return void this._logger.warn("_handleSubscriptionFailure, disposed, ignore subscription");if(g.status>=400&&g.status<500&&401!==g.status&&this.isNotNetworkErrors(g.status))return void this._logger.warn(`_handleSubscriptionFailure, received status ${g.status}, stop subscribing`);const f=getPrintableObject(g);this._logger.error("_handleSubscriptionFailure failed, re-subscribing",f),this._reportSubscriptionInTelemetry()&&this._signalingSession.telemetryHelper.recordEvent(dn.BROKER_SUBSCRIPTION_FAILED),this._retryRequestTimer=ht.build((()=>{this._subscribeToBroker(this.currentSubscriptionUrl,this._currentSubscriptionTimeoutInSec)}),"RETRY").start(1e3*this._subscriptionRetryBackoffInSec)},this._reportSubscriptionInTelemetry=g=>(this._reportedResultCount++,this._reportedResultCount<=In),this._getBrokerRequestHeaders=g=>{const f=new ln;return f.set(an.HEADERS.CONTENT_TYPE,an.CONTENT_TYPE.JSON),this._signalingSession.signalingAgentConfig.brokerRequestBatching&&f.set(an.HEADERS.BROKER_USE_BATCHING_HEADER_NAME,"1"),f},this._logger=this._signalingSession.logger.createChild("Broker"),this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration?.brokerRetryBackOffInSec&&(this._subscriptionRetryBackoffInSec=this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration.brokerRetryBackOffInSec)}subscribeToBroker(g){this._logger.info("subscribeToBroker called."),this._abortPendingRequest(),this._clearAllPendingTimeouts(),this._subscribeToBroker(g,this._currentSubscriptionTimeoutInSec)}onBrokerMessage(g){this._logger.info("onBrokerMessage callback added"),this._subscribers.push(g)}dispose(){this._disposed=!0,this._logger.info("dispose"),this._subscribers=[],this._clearAllPendingTimeouts(),this._abortPendingRequest()}isNotNetworkErrors(g){return 490!==g&&496!==g&&498!==g&&499!==g}},An=class{constructor(g){this.requests={},this.logger=g}clear(g,f){const S=f||{code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((f=>{try{const v=parseInt(f,10);Object.keys(this.requests[v]).forEach((f=>{this.rejectOperation(v,f,g,S)}))}catch(g){this.logger.warn(`CallOperations: clear error = ${g}`)}}))}hasOperation(g,f){return this.requests.hasOwnProperty(g.valueOf())&&this.requests[g.valueOf()].hasOwnProperty(f)}getAllOperations(){return this.requests}getOperation(g,f){return this.hasOperation(g,f)?this.requests[g.valueOf()][f]:null}setOperation(g,f,S){return!this.hasOperation(g,f)&&(this.hasOwnProperty(g.valueOf())||(this.requests[g.valueOf()]={}),this.requests[g.valueOf()][f]=S,!0)}rejectOperation(g,f,S,v){if(this.hasOperation(g,f)){const S=g.valueOf(),C=this.requests[S][f].promise;delete this.requests[S][f],C.reject(v)}}resolveOperation(g,f,S,v){if(this.hasOperation(g,f)){const v=g.valueOf(),C=this.requests[v][f].promise;delete this.requests[v][f],C.resolve(S)}}},Pn=class{constructor(g){this.logger=g,this.localRequests=new An(g)}dispose(g,f,S){this.logger.info(`[${S}][dispose]`),this.rejectAllPendingOperations(g,f)}hasPendingOperation(g,f,S){return this.logger.info(`[${S}][hasPendingOperation] ${g} ${scrubMriOrOmit(f)}}`),this.localRequests.hasOperation(g,f)}rejectPendingOperation(g,f,S,v,C){this.logger.info(`[${C}][rejectPendingOperation] ${g} ${f} reason: ${S} endCode: ${v}`),this.localRequests.rejectOperation(g,f,S,v)}resolvePendingOperation(g,f,S,v){this.logger.info(`[${v}][resolvePendingOperation]: ${scrubMriOrOmit(f)}`),this.localRequests.resolveOperation(g,f,S,v)}setPendingOperation(g,f,S,v){return this.logger.info(`[${v}][setPendingOperation] ${g} value: ${S}`),this.localRequests.setOperation(g,f,S)}rejectAllPendingOperations(g,f){this.logger.info("rejectLocalQueuedOperations"),this.localRequests.clear(g,f)}};function getPayload(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"content cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},to:[]},contentSharing:{identifier:f.contentIdentifier,subject:f.subject,sessionState:f.sessionState,sequenceNumber:f.sequenceNumber,links:{sessionUpdate:get2(g,rn.CONV_CONTENT_SHARING_UPDATE),sessionEnd:get2(g,rn.CONV_CONTENT_SHARING_END)}},links:{addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE)}}}}function getPayload2(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{contentSharing:{links:{sessionUpdate:get2(g,rn.CONV_CONTENT_SHARING_UPDATE),sessionEnd:get2(g,rn.CONV_CONTENT_SHARING_END)}},participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}function getPayload3(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{contentSharingTransactionEnd:f,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}function getPayload4(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}function getPayload5(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},links:{sessionUpdate:get2(g,rn.CONV_CONTENT_SHARING_UPDATE),sessionEnd:get2(g,rn.CONV_CONTENT_SHARING_END)}}}}function getPayload6(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}function getPayload7(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"sessionState cannot be null"),assertNotNull(S,"sequenceNumber cannot be null"),{payload:{sessionUpdateSequenceNumber:S,sessionState:f,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}}}}var Rn=class{constructor(){this.msElapsed=0,this.isPaused=!1,this.startTime=(new Date).getTime(),this.pause=()=>{this.isPaused||(this.msElapsed+=(new Date).getTime()-this.startTime,this.isPaused=!0)},this.resume=()=>{this.isPaused&&(this.isPaused=!1,this.startTime=(new Date).getTime())},this.duration=()=>this.isPaused?this.msElapsed:this.msElapsed+(new Date).getTime()-this.startTime,this.durationInMinutes=()=>{const g=this.duration()/6e4;return Math.ceil(g)},this.durationInSeconds=()=>{const g=this.duration()/1e3;return Math.ceil(g)}}};function build3(){return new Rn}var Mn=class{constructor(g,f,S,v){this.signalingSession=g,this.correlationId=f,this.sessionId=null,this.fsmState=an.CONTENT_SHARING_FSM_STATE.IDLE,this.addSessionPromise=null,this.removeSessionPromise=null,this.confirmInRosterPromise=null,this.links={},this.lastUpdateSequenceNumber=-1,this.nextClientSequenceNumberToUse=1,this.disposed=!1,this.isPresenter=!1,this.FSM_STATES=an.CONTENT_SHARING_FSM_STATE,this.logger=g.logger.createChild((()=>`[${this.fsmState}][cs=${this.sessionId}][cc=${this.correlationId}]`)),S&&(this.sessionId=S),v&&(this.links=v)}start(g,f,S,v){if(this.logger.info(`[${v}][start]`),assertNotNullOrEmpty(g,"Correct addModality url is not provided"),!this.checkState("start",this.FSM_STATES.IDLE,this.addSessionPromise))return Promise.reject(null);this.addSessionPromise=S,this.confirmInRosterPromise=defer(),this.fsmState=this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.addTelemetryOperation(hn.ADD_CONTENT_SHARING_MODALITY.name,{causeId:v});const C=new ln;return C.set(an.HEADERS.CONTENT_SHARING_CORRELATION_ID,this.correlationId),this.signalingSession.http.sendPostRequest({url:g,payload:getPayload(this.signalingSession,f),requestName:hn.ADD_CONTENT_SHARING_MODALITY.name,customHeaders:C,onceTrouterReady:()=>{this.startContentSharingTimer(v)},causeId:v}).then((()=>{this.disposed||(this.presenterMri=this.signalingSession.participantManager.localParticipant.id,this.isPresenter=!0)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${v}][start] error: ${getPrintableObject(f)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise(getPrintableObject(g),f.error)),Promise.reject(null)}))}delete(g,f){this.logger.info(`[${f}][delete]`);let S=!1;if(this.fsmState===this.FSM_STATES.IDLE)return this.logger.info(`[${f}][delete] skipped because state is already ${this.fsmState}`),g.resolve(),Promise.resolve();if(this.fsmState===this.FSM_STATES.CONTENT_SHARING_START_INITIATED)S=!0,this.rejectPendingPromise("Session delete called before start was finished");else if(!this.checkState("delete",this.FSM_STATES.CONTENT_SHARING_CONNECTED,g))return Promise.reject(null);S||assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],"Correct controller url is not set"),this.removeSessionPromise=g,this.fsmState=this.FSM_STATES.CONTENT_SHARING_DELETE_INITIATED;const v=build3(),C=this.addTelemetryOperation(hn.DELETE_CONTENT_SHARING.name,{causeId:f});return(S?Promise.resolve(void 0):this.signalingSession.http.sendDeleteRequest({url:this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],requestName:hn.DELETE_CONTENT_SHARING.name,payload:getPayload3(this.signalingSession,{code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED}),causeId:f})).then((()=>{if(!this.disposed){const g={success:!0,duration:v.duration()};S&&(g.skipReason="Session delete called before start was finished"),this.updateTelemetryOperation(C,g),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${f}][delete] error: ${getPrintableObject(S)}`),!this.disposed){const g={success:!1,duration:v.duration()};this.updateTelemetryOperation(C,g),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}return Promise.reject(null)}))}join(g,f){if(this.logger.info(`[${f}][join]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],"Correct joinContentSharing url is not provided"),!this.checkState("join",this.FSM_STATES.IDLE,g))return;this.lastUpdateSequenceNumber=-1,this.nextClientSequenceNumberToUse=1,this.addSessionPromise=g,this.fsmState=this.FSM_STATES.CONTENT_SHARING_JOIN_INITIATED;const S=build3(),v=this.addTelemetryOperation(hn.JOIN_CONTENT_SHARING.name,{causeId:f});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],payload:getPayload2(this.signalingSession),requestName:hn.JOIN_CONTENT_SHARING.name,causeId:f}).then((g=>{if(!this.disposed){const f={success:!0,duration:S.duration()};this.updateTelemetryOperation(v,f),this.processStartOrJoinSuccess(g.response),this.resolvePendingPromise(g.response)}})).catch((g=>{const C=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${f}][join] error: ${getPrintableObject(C)}`),!this.disposed){const f={success:!1,duration:S.duration()};this.updateTelemetryOperation(v,f);const _=C.error;this.rejectPendingPromise(getPrintableObject(g),_)}}))}takeControl(g,f){if(this.logger.info(`[${f}][takeControl]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_TAKE_CONTROL],"correct contentSharingTakeControl url is not provided"),!this.checkState("takeControl",this.FSM_STATES.CONTENT_SHARING_CONNECTED,g))return;const S=build3(),v=this.addTelemetryOperation(hn.TAKE_CONTROL_CONTENT_SHARING.name,{causeId:f});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_TAKE_CONTROL],payload:getPayload4(this.signalingSession),requestName:hn.TAKE_CONTROL_CONTENT_SHARING.name,withoutTrouter:!0,causeId:f}).then((f=>{if(!this.disposed){const C={success:!0,duration:S.duration()};this.updateTelemetryOperation(v,C);const _={contentIdentifier:f.response.identifier,presenter:f.response.presenter.id,subject:f.response.subject||null,sessionState:f.response.sessionState||null};g.resolve(_)}})).catch((C=>{const _=getErrorForXHRFailure(C,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${f}][takeControl] error: ${getPrintableObject(_)}`),!this.disposed){const f={success:!1,duration:S.duration()};this.updateTelemetryOperation(v,f);const T=new Error(getPrintableObject(C));T.endCode=_.error,g.reject(T)}}))}updateSessionState(g,f,S){if(this.logger.info(`[${S}][updateSessionState]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],"Correct sendUpdateSessionState url is not provided"),!this.checkState("updateSessionState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,f))return;const v=build3(),C=this.addTelemetryOperation(hn.UPDATE_SESSION_STATE_CONTENT_SHARING.name,{causeId:S});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],payload:getPayload7(this.signalingSession,g,this.nextClientSequenceNumberToUse++),requestName:hn.UPDATE_SESSION_STATE_CONTENT_SHARING.name,causeId:S}).then((()=>{if(!this.disposed){const g={success:!0,duration:v.duration()};this.updateTelemetryOperation(C,g),f.resolve()}})).catch((g=>{const _=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${S}][updateSessionState] error: ${getPrintableObject(_)}`),!this.disposed){const S={success:!1,duration:v.duration()};this.updateTelemetryOperation(C,S);const T=new Error(getPrintableObject(g));T.endCode=_.error,f.reject(T)}}))}updateParticipantState(g,f){if(this.logger.info(`[${f}][updateParticipantState]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],"correct confirmContentSharingView url is not provided"),!this.checkState("updateParticipantState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,g))return;const S=build3(),v=this.addTelemetryOperation(hn.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,{causeId:f});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],payload:getPayload6(this.signalingSession),requestName:hn.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,withoutTrouter:!0,causeId:f}).then((()=>{if(!this.disposed){const f={success:!0,duration:S.duration()};this.updateTelemetryOperation(v,f),g.resolve()}})).catch((C=>{const _=getErrorForXHRFailure(C,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${f}][updateParticipantState] error: ${getPrintableObject(_)}`),!this.disposed){const f={success:!1,duration:S.duration()};this.updateTelemetryOperation(v,f);const T=new Error(getPrintableObject(C));T.endCode=_.error,g.reject(T)}}))}updateNotificationLinks(g){if(this.logger.info(`[${g}][updateNotificationLinks]`),assertNotNullOrEmpty(this.links[an.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],"correct notificationLinks url is not provided"),!this.checkState("updateState",this.FSM_STATES.CONTENT_SHARING_CONNECTED))return;const f=build3(),S=this.addTelemetryOperation(hn.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,{causeId:g});this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],payload:getPayload5(this.signalingSession),requestName:hn.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,withoutTrouter:!0,causeId:g}).then((()=>{if(!this.disposed){const g={success:!0,duration:f.duration()};this.updateTelemetryOperation(S,g)}})).catch((v=>{const C=getErrorForXHRFailure(v,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${g}][updateNotificationLinks] error: ${getPrintableObject(C)}`),!this.disposed){const g={success:!1,duration:f.duration()};this.updateTelemetryOperation(S,g)}}))}confirmInRoster(){this.confirmInRosterPromise&&this.confirmInRosterPromise.isPending&&(this.logger.info("Confirmed in roster"),this.confirmInRosterPromise.resolve())}handleAddModalitySuccess(g,f){return this.logger.info(`[${f}][handleAddModalitySuccess]`),this.checkState("handleAddModalitySuccess",this.FSM_STATES.CONTENT_SHARING_START_INITIATED)?g.modalitySuccess&&g.modalitySuccess.contentSharing?(this.addTelemetryOperation(dn.HANDLE_ADD_MODALITY_SUCCESS,{causeId:f}),this.processStartOrJoinSuccess(g.modalitySuccess.contentSharing),this.confirmInRosterPromise.promise.then((()=>{delete this.confirmInRosterPromise,this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY),this.resolvePendingPromise(g.modalitySuccess.contentSharing)})),!0):(this.addTelemetryOperation(dn.HANDLE_ADD_MODALITY_SUCCESS,{causeId:f,skipReason:"no content sharing blob"}),this.logger.info(`[${f}][handleAddModalitySuccess] ignored because modalitySuccess was missing or did not contain content sharing blob`),!1):(this.logger.info(`[${f}][handleAddModalitySuccess] ignored because session is not waiting to start`),!1)}handleAddModalityFailure(g,f){if(this.logger.info(`[${f}][handleAddModalityFailure]`),!this.checkState("handleAddModalityFailure",[this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.FSM_STATES.CONTENT_SHARING_CONNECTED]))return!1;if(!g.modalityFailure||!g.modalityFailure.contentSharing)return this.addTelemetryOperation(dn.HANDLE_ADD_MODALITY_FAILURE,{causeId:f,skipReason:"no content sharing blob"}),!1;const S=g.modalityFailure.contentSharing;this.addTelemetryOperation(dn.HANDLE_ADD_MODALITY_FAILURE,{reason:S,causeId:f});const v={...S};return this.sendTelemetryData(v),this.rejectPendingPromise(v.phrase,v),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY),!0}handleStartFromRoster(g,f){this.logger.info(`[${f}][handleStartFromRoster]`),this.addTelemetryOperation(dn.CONTENT_SHARING_START_FROM_ROSTER,{causeId:f})}handleStopFromRoster(g,f){this.logger.info(`[${f}][handleStopFromRoster]`),this.addTelemetryOperation(dn.CONTENT_SHARING_END_FROM_ROSTER,{causeId:f}),this.sendTelemetryData(g)}handleStop(g,f){if(this.logger.info(`[${f}][handleStop]`),this.isSelfInitiatedAction(g))return this.logger.info(`[${f}][handleStop]handleStop skipped because session was ended by self`),!1;const S={...g.contentSharingTransactionEnd};return this.addTelemetryOperation(dn.HANDLE_CONTENT_SHARING_END,{causeId:f}),this.sendTelemetryData(S),!0}handleUpdate(g,f){return this.logger.info(`[${f}][handleUpdate]`),g.sequenceNumber<=this.lastUpdateSequenceNumber?(this.logger.info(`handleUpdate skipped because of old sequence number: last received ${this.lastUpdateSequenceNumber}, update contained ${g.sequenceNumber}`),this.addTelemetryOperation(dn.HANDLE_CONTENT_SHARING_UPDATE,{causeId:f,skipReason:"old sequence number"}),!1):(this.lastUpdateSequenceNumber=g.sequenceNumber,this.isPresenter=g.presenter.id===this.signalingSession.participantManager.localParticipant.id,this.addTelemetryOperation(dn.HANDLE_CONTENT_SHARING_UPDATE,{causeId:f}),!0)}dispose(g,f){this.logger.info(`[${f}][dispose]`),this.disposed=!0,this.rejectPendingPromise("call ended",g||{code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED}),this.addTelemetryOperation(dn.HANDLE_CALL_END,{causeId:f}),this.sendTelemetryData(g)}rejectPendingPromise(g,f){this.logger.info("rejectPendingPromise");const S=new Error(g);f&&(S.endCode=f),this.removeSessionPromise&&(this.removeSessionPromise.reject(S),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.reject(S),this.addSessionPromise=null)}resolvePendingPromise(g){this.logger.info("resolvePendingPromise");let f=null;g&&(f={sessionId:g.sessionId,correlationId:g.contentSharingCorrelationId,contentIdentifier:g.identifier,presenter:g.presenter.id,subject:g.subject||null,sessionState:g.sessionState||null}),this.removeSessionPromise&&(this.removeSessionPromise.resolve(f),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.resolve(f),this.addSessionPromise=null)}processStartOrJoinSuccess(g){this.logger.info("processStartOrJoinSuccess"),this.sessionId=g.sessionId,this.fsmState=this.FSM_STATES.CONTENT_SHARING_CONNECTED,this.lastUpdateSequenceNumber=-1,this.links[an.LINKS.CONTENT_SHARING_CONTROLLER]=g.links.contentSharingController,this.links[an.LINKS.CONTENT_SHARING_TAKE_CONTROL]=g.links.takeControl,this.links[an.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE]=g.links.updateSessionState,this.links[an.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE]=g.links.sync,this.links[an.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS]=g.links.notificationLinks,this.links[an.LINKS.CONTENT_SHARING_LEAVE]=g.links.leave}checkState(g,f,S){let v;if(v="string"==typeof f?this.fsmState===f:f.indexOf(this.fsmState)>-1,v)return!0;{const v=`${g} requires state ${f}, but state is ${this.fsmState}`;return this.logger.error(v),S&&S.reject(v),!1}}isSelfInitiatedAction(g){return g.presenter.participantId===this.signalingSession.participantManager.localParticipant.participantId}startContentSharingTimer(g){this.logger.info("startContentSharingTimer"),this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY,(()=>{this.addTelemetryOperation(dn.ADD_MODALITY_TIMEOUT,{causeId:g}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise("timed out waiting for ContentSharing to start",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT})}),an.TIMEOUT_VALUES_IN_SECONDS.ADD_MODALITY_TIMEOUT)}addTelemetryOperation(g,f){return this.signalingSession.telemetryHelper.addContentSharingOperation(this.correlationId,g,f)}updateTelemetryOperation(g,f){this.signalingSession.telemetryHelper.updateContentSharingOperation(this.correlationId,g,f)}sendTelemetryData(g){this.signalingSession.telemetryHelper.sendContentSharingTelemetryData(this.correlationId,this.signalingSession.sessionId,this.isPresenter,g,this.links[an.LINKS.CONTENT_SHARING_CONTROLLER],this.sessionId)}},wn=class{constructor(g,f){this.contentSharingToStartCallWith=null,this.contentSharingSessions={},this.DEFAULT_STOP_REASON={code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.REMOTE_USER_INITIATED},this.DEFAULT_STOP_ID="8:unknown",this.deleteContentSharingAsync=(g,f)=>{this.logger.info(`[${f}][deleteContentSharingAsync]`);const S=defer();let v=this.contentSharingSessions[g];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===g&&(v=this.pendingSessionToStart),v){const always=()=>{this.contentSharingSessions[g]&&delete this.contentSharingSessions[g]};v.delete(S,f).then(always,always)}else this.rejectBecauseOfMissingSession(g,S);return S.promise},this.signalingSession=g,this.signalingSessionCallback=f,this.logger=g.logger.createChild((()=>"[ContentSharingManager]")),this.lastProcessedSequenceNumber=-1,this.lastProcessedSequenceNumberForParticipant={}}startContentSharingAsync(g,f,S,v,C,_,T){if(this.logger.info(`startContentSharingAsync called for: ${g}`),this.pendingSessionToStart){const g="There is already a ContentSharing session start pending";return this.logger.error(g),Promise.reject(new Error(g))}const I={contentIdentifier:g,subject:S||null,sessionState:f||null,sequenceNumber:1},b=defer(),A=new Mn(this.signalingSession,T||newGuid2());return this.pendingSessionToStart=A,C?(this.logger.info("Call connected, send content sharing request out immediately"),A.start(v,I,b,_)):(this.logger.info("Content sharing is to be started when startOutgoingCall is called"),A.addSessionPromise=b,A.fsmState=an.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED,this.contentSharingToStartCallWith=I),b.promise.then((()=>{this.contentSharingSessions.hasOwnProperty(A.correlationId)||(this.contentSharingSessions[A.correlationId]=A),this.pendingSessionToStart=null})).catch((()=>{this.pendingSessionToStart=null})),b.promise}joinContentSharingAsync(g,f){this.logger.info(`[${f}][joinContentSharingAsync]`);const S=defer(),v=this.contentSharingSessions[g];return v?v.join(S,f):this.rejectBecauseOfMissingSession(g,S),S.promise}updateContentSharingSessionStateAsync(g,f,S){this.logger.info(`[${S}][updateContentSharingSessionStateAsync][sessionState=${JSON.stringify(f)}]`);const v=defer(),C=this.contentSharingSessions[g];return C?C.updateSessionState(f,v,S):this.rejectBecauseOfMissingSession(g,v),v.promise}takeContentSharingControlAsync(g,f){this.logger.info(`[${f}][takeContentSharingControlAsync]`);const S=defer(),v=this.contentSharingSessions[g];return v?v.takeControl(S,f):this.rejectBecauseOfMissingSession(g,S),S.promise}updateContentSharingParticipantStateAsync(g,f){this.logger.info(`[${f}][updateContentSharingParticipantStateAsync]`);const S=defer(),v=this.contentSharingSessions[g];return v?v.updateParticipantState(S,f):this.rejectBecauseOfMissingSession(g,S),S.promise}updateContentSharingNotificationLinksAsync(g){this.logger.info(`[${g}][updateContentSharingNotificationLinksAsync]`);for(const f of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(f)){const S=this.contentSharingSessions[f];S&&S.updateNotificationLinks(g)}}getContentSharingInfoToStartSharing(){if(this.contentSharingToStartCallWith){const g=this.pendingSessionToStart,f=an.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED;g&&g.fsmState===f||(this.contentSharingToStartCallWith=null,this.pendingSessionToStart=null)}return this.contentSharingToStartCallWith}dispose(g,f){this.logger.info(`[${f}][dispose]`);for(const S of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(S)){const v=this.contentSharingSessions[S];v&&v.dispose(g,f)}}handleContentSharingUpdate(g){const f=g.body,S=extractCauseIdFromMessage(g),v=this.contentSharingSessions[f.contentSharingCorrelationId];v?v.handleUpdate(f,S)&&this.signalingSessionCallback.onContentSharingUpdated({sessionId:f.sessionId,correlationId:f.contentSharingCorrelationId,contentIdentifier:f.identifier,presenter:f.presenter.id,subject:f.subject||null,sessionState:f.sessionState||null},S):this.logger.info(`[${S}][handleContentSharingUpdate][failed][reason=no session with correlation ID ${f.correlationId}]`)}handleAddModalitySuccess(g,f){this.logger.info(`[${f}][handleAddModalitySuccess]`);const S=this.pendingSessionToStart;S?S.handleAddModalitySuccess(g,f):this.logger.info(`[${f}][handleAddModalitySuccess]Ignoring handleAddModalitySuccess because not waiting for one`)}handleAddModalityFailure(g,f){this.logger.info(`[${f}][handleAddModalityFailure]`);const S=this.pendingSessionToStart;S?S.handleAddModalityFailure(g,f):this.logger.info(`[${f}][handleAddModalityFailure]Ignoring handleAddModalityFailure because not waiting for one`)}handleIncomingContentSharingFromRoster(g,f,S){if(this.logger.info(`[${S}] handleIncomingContentSharingFromRoster: isFullRoster ${f} content ${getPrintableObject(g)}`),("MultiPartyEndpoint"===g.type||f)&&this.lastProcessedSequenceNumber>g.sequenceNumber)return void this.logger.info(`[${S}] handleIncomingContentSharingFromRoster invalid roster current sequenceNumber ${g.sequenceNumber} lastProcessedSequenceNumber ${this.lastProcessedSequenceNumber}`);const{sessionsWithPresenters:v,sessionsWithoutPresenters:C}=this.parseContentSharingSessionsFromRoster(g);this.startSessionsFromRoster(v,S),this.stopSessionsFromRoster(C,S),this.lastProcessedSequenceNumber=g.sequenceNumber}handleContentSharingEnd(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info("handleContentSharingEnd : ",getPrintableObject(f));const v=this.contentSharingSessions[f.contentSharingCorrelationId];if(!v)return void this.logger.info("Ignoring contentSharingEnd since there is no corresponding sharing ongoing");if(!v.handleStop(f,S))return;const C={...f.contentSharingTransactionEnd};this.raiseContentSharingStopped(f.contentSharingCorrelationId,S,f.presenter.id,C)}parseContentSharingSessionsFromRoster(g){const f={},S={},v=new Set;for(const S of Object.keys(g.participants)){const C=g.participants[S];if("Delta"===g.type&&this.lastProcessedSequenceNumberForParticipant.hasOwnProperty(S)&&C.version<=this.lastProcessedSequenceNumberForParticipant[S])continue;if(C.version=C.version||-1,this.lastProcessedSequenceNumberForParticipant[S]=C.version,v.add(C.details.id),!C.endpoints)continue;const _=this.signalingSession.participantManager.localParticipant.participantId;for(const g of Object.keys(C.endpoints)){const S=C.endpoints[g],v=S?.contentSharing?.sessionInformation;"presenter"===v?.role&&(f[v.contentSharingCorrelationId]={presenterId:C.details.id,sessionInfo:v,selfEndpointIsPresenter:S.participantId===_})}}for(const g of Object.keys(this.contentSharingSessions))!f[g]&&v.has(this.contentSharingSessions[g].presenterMri)&&(S[g]=this.contentSharingSessions[g]);return{sessionsWithPresenters:f,sessionsWithoutPresenters:S}}stopSessionsFromRoster(g,f){this.logger.info(`[${f}][stopSessionsFromRoster]`);for(const S of Object.keys(g))this.logger.info(`[${f}][stopSessionsFromRoster] stopping session with correlationId ${S}`),this.stopSession(g[S],f)}stopSession(g,f){this.logger.info(`[${f}][stopSession] Stopping session ${g.sessionId}`),g.handleStopFromRoster(this.DEFAULT_STOP_REASON,f),this.raiseContentSharingStopped(g.correlationId,f)}startSessionsFromRoster(g,f){this.logger.info(`[${f}][startSessionsFromRoster]`);for(const S of Object.keys(g)){this.logger.info(`[${f}][startSessionsFromRoster]`);const v=this.contentSharingSessions[S],C=g[S];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===S?this.pendingSessionToStart.confirmInRoster():v&&v.confirmInRoster(),v)v&&(this.contentSharingSessions[S].presenterMri=C.presenterId,this.logger.info(`[${f}][startSessionsFromRoster]Session ${S} is already present locally`));else{if(C.selfEndpointIsPresenter){this.logger.info(`[${f}][startSessionsFromRoster]This endpoint is presenting, dont fire callback`);continue}this.logger.info(`[${f}][startSessionsFromRoster]New sharing session found. Raising ContentSharingStarted`),this.raiseContentSharingStarted(C.presenterId,C.sessionInfo,f).handleStartFromRoster(C.presenterId,f)}}}raiseContentSharingStopped(g,f,S,v){this.logger.info(`[${f}][raiseContentSharingStopped]`),this.signalingSessionCallback.onContentSharingStopped({sessionId:this.contentSharingSessions[g].sessionId,correlationId:g,endedBy:S||this.DEFAULT_STOP_ID,reason:v||this.DEFAULT_STOP_REASON},f),delete this.contentSharingSessions[g]}raiseContentSharingStarted(g,f,S){this.logger.info(`[${S}][raiseContentSharingStarted]`);const v=new Mn(this.signalingSession,f.contentSharingCorrelationId,f.contentSharingSessionId,{[an.LINKS.CONTENT_SHARING_CONTROLLER]:f.contentSharingController});v.presenterMri=g,this.contentSharingSessions[v.correlationId]=v;const C={sessionId:f.contentSharingSessionId,correlationId:f.contentSharingCorrelationId,contentIdentifier:f.identifier,presenter:g,subject:f.subject||null,sessionState:f.sessionState||null};return this.signalingSessionCallback.onContentSharingStarted(C,S),v}rejectBecauseOfMissingSession(g,f){const S=`There is no ContentSharing session with the correlation ID ${g}`;this.logger.error(S),f&&f.reject(new Error(S))}},On={Default:{retryIntervalsMs:[200,1e3,5e3],maxRequestAttempts:4,perRequestTimeoutMs:45e3,perAttemptTimeoutMs:15e3,perRequestTimeoutWithHedgingMs:45e3,perAttemptTimeoutWithHedgingMs:3e4,hedgeDelayMs:4e3},BrokerSubscribe:{retryIntervalsMs:[100,200,500],maxRequestAttempts:4,perRequestTimeoutMs:3e4,perAttemptTimeoutMs:3e4,perRequestTimeoutWithHedgingMs:45e3,perAttemptTimeoutWithHedgingMs:3e4}},Dn={CallSetup:{requestHedgingCapability:["disabled"],hedgeDelayMs:4e3},Other:{requestHedgingCapability:["disabled"]},BrokerSubscribe:{requestHedgingCapability:["disabled"]}},Nn="HttpRequestDispatcherFactory";function reportTokenTelemetryData(g,f,S){f?.signalingSession?f.signalingSession.telemetryHelper?.addTokenTelemetry(g,f?.tokenTelemetryData):S?.info("[reportTokenTelemetryData] signaling session is not available, cannot send token telemetry")}function get3(g,f){const{signalingSession:S,operation:v,causeId:C,data:_,customHeaders:T={},forceFetchToken:I,tokenRequestOptions:b,useFetch:A,fetchUseKeepAlive:P}=g;if(S.disposed)return Promise.reject("Session already disposed");const handleFailure=g=>{const f="string"==typeof g?new Error(g):g;throw S.signalingAgent.clientSupportsGenericTokenAPI?g.timeOut?f.tokenTimeoutError=!0:(f.tokenError=!0,f.tokenErrorSubCode=g.errorSubCode):f.skypeTokenError=!0,f};let R=!1;const M={signalingSession:S,tokenTelemetryData:{}};return S.signalingAgent.authTokenManager.getToken(C,I,b,M).catch((v=>(reportTokenTelemetryData(g.requestId,M,f),!I&&isAppOnline(S)&&S.signalingAgentConfig.attemptHttpRequestWithCachedSkypetoken&&S.signalingAgent.authTokenManager.getLastToken(C)?(R=!0,f?.info(`[${C}][requestBuilder] failed to fetch token, using lastToken`),Promise.resolve(S.signalingAgent.authTokenManager.getLastToken(C))):(f?.info(`[${C}][requestBuilder] getToken failed with error ${v}`),handleFailure(v))))).then((I=>{if(S.disposed)throw new Error("token returned too late. Object is already disposed");reportTokenTelemetryData(g.requestId,M,f);const b=new ln;if(b.set(an.HEADERS.CORRELATION_ID,S.correlationId),b.set(an.HEADERS.MESSAGE_ID,newMessageId(C)),b.set(an.HEADERS.CLIENT_USER_AGENT,S.signalingAgentConfig.clientInformation),S.signalingAgent.clientSupportsGenericTokenAPI){const g=S.signalingAgent.authTokenManager.getLastTokenType(C);switch(S.signalingAgentConfig.disableTokenMigrationHeader||b.set(an.HEADERS.TOKEN_MIGRATION,"True"),g){case 8:case 4:b.set(an.HEADERS.AUTHORIZATION,`${an.HEADERS.BEARER_KEYWORD} ${I}`),b.delete(an.HEADERS.SKYPE_TOKEN);break;case 1:b.set(an.HEADERS.SKYPE_TOKEN,I),b.delete(an.HEADERS.AUTHORIZATION);break;default:throw new Error(`Error in RequestBuilder. TokenType ${g} is not supported`)}}else b.set(an.HEADERS.SKYPE_TOKEN,I);const w=S.participantManager.localParticipant;w&&(w.ring&&b.set(an.HEADERS.RING,w.ring),w.region&&b.set(an.HEADERS.REGION,w.region),w.partition&&b.set(an.HEADERS.PARTITION,w.partition));const O=_?.payload?JSON.stringify(_.payload):null,D={headers:{...b?.getAll(),...T},payload:O,usedCachedSkypetoken:R,reporting:{serviceName:v?`${Nn}-${v}`:Nn},useFetch:A,fetchUseKeepAlive:P};return S.telemetryHelper.addNetworkOperationStarted(v),D})).catch(handleFailure)}function isAppOnline(g){const f=isTrouterAndNavigatorConnected(g.signalingAgentConfig.trouterServiceProvider);return 3===f||1===f}var kn=500,Ln=1e4,Fn=4,xn=3e3,Un=3;function build4(g){return new Vn(g.causeId,g.logger,g.dispatcher,g.requestType,g.url,g.request,g.attemptFailureCallback,g.authRequiredCallback,g.settings)}var Vn=class{constructor(g,f,S,v,C,_,T,I,b){this.causeId=g,this.logger=f,this.dispatcher=S,this.requestType=v,this.url=C,this.request=_,this.onRequestFailed=T,this.authRequiredCallback=I,this.settings=b,this.requestsSent=0,this.otherAttemptSuccessful=!1,this.pendingAttempts=[],this.hedgeDelayMs=xn,this.hedgeMaxParallelAttempts=Un,this.stopStandardRetryTimer=()=>{this.standardRetryTimer&&(this.standardRetryTimer.stop(),this.standardRetryTimer=null)},this.stopHedgeTimer=()=>{this.hedgeTimer&&(this.hedgeTimer.stop(),this.hedgeTimer=null)},this.stopAttemptTimeoutTimer=g=>{try{g.timeoutTimer&&(g.timeoutTimer.stop(),this.logger.info("attempt timer stopped"))}catch(g){this.logger.info(`stopAttemptTimeoutTimer error ${g}`)}},this.stopRequestTimer=()=>{try{this.requestTimer&&(this.requestTimer.stop(),this.logger.info("Request timer stopped"))}catch(g){this.logger.info(`stopRequestTimer error ${g}`)}this.requestTimer=null},this.canScheduleNextAttempt=()=>{if(this.stackError===an.HTTP_STACK_ERROR.REQUEST_ABORTED||this.otherAttemptSuccessful||this.requestsSent>=this.settings.maxRequestAttempts)return this.logger.info(`canScheduleNextAttempt stack error ${this.stackError} otherAttemptSuccessful ${this.otherAttemptSuccessful} exceeded max attempt ${this.requestsSent>=this.settings.maxRequestAttempts}`),!1;if(this.settings.enableRequestHedging){const g=this.pendingAttempts.length<this.hedgeMaxParallelAttempts;return g||this.logger.info(`canScheduleNextAttempt enableRequestHedging attempts sent: ${this.pendingAttempts.length} max attempts: ${this.hedgeMaxParallelAttempts}`),g}{const g=this.requestsSent<this.settings.retryIntervalsMs.length;return g||this.logger.info(`canScheduleNextAttempt attempts sent: ${this.requestsSent} max attempts: ${this.settings.retryIntervalsMs.length}`),g}},this.scheduleNextRequest=g=>{this.settings.enableRequestHedging?(this.logger.info("scheduleNextRequest with hedging"),this.hedgeTimer=ht.build((()=>{this.attempt(),this.canScheduleNextAttempt()&&this.scheduleNextRequest(!1)}),"HEDGE").start(this.getNextDelay(g))):(this.logger.info("scheduleNextRequest with retry"),this.standardRetryTimer=ht.build((()=>{this.attempt()}),"RETRY").start(this.getNextDelay(g)))},this.standardizeFailedRequest=(g,f)=>{let S;const v=this.logger.createChild("[standardizeFailedRequest]");try{if(this.stackError===an.HTTP_STACK_ERROR.REQUEST_TIMEOUT)v.info("request timed out"),S=en.REQUEST_TIMEOUT;else if(this.stackError===an.HTTP_STACK_ERROR.REQUEST_ABORTED)v.info("request aborted"),S=en.REQUEST_ABORTED;else if(f&&f.status===an.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT)v.info("request attempt timed out"),S=en.ATTEMPT_TIMEOUT;else if(f&&[an.HTTP_STACK_ERROR.ATTEMPT_ABORTED,an.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL].indexOf(f.status)>-1)v.info("request attempt aborted"),S=en.ATTEMPT_ABORTED;else if(g){if(v.info(`request ${getPIISafeRequest(g)}`),g.request?.response){const f=g;S={response:{..."string"==typeof f?.request?.response?f?.response?.data:f?.request?.response,headers:f.response?.headers},status:f.request.status,statusText:f.request.statusText,readyState:f.request.readyState}}else g.status||g.statusCode||g.response?S={response:g.response,status:[void 0,null,""].indexOf(g.status)>-1?g.statusCode:g.status,statusText:g.statusText,readyState:g.readyState}:(v.info("Local http stack error"),S={response:an.CALL_END_SUB_CODE.LOCAL_HTTP_STACK_ERROR,status:an.CALL_END_CODE.LOCAL_HTTP_STACK_ERROR,statusText:"LocalHTTPStackError",readyState:g.readyState||0});this.isBrowserOffline()&&0===S.status&&4===S.readyState&&(v.info("offline"),S={response:an.HTTP_STACK_ERROR.CANNOT_CONNECT,status:an.HTTP_STATUS_CODES.OFFLINE,statusText:"offline",readyState:S.readyState}),g.response?.message&&(g.response.message.operationFailure||g.response.message.broadcastOperationFailure)?S={response:g.response.message}:!g.response&&g.body?.operationFailure&&(S={response:g.body})}else v.info("no response"),S={response:an.HTTP_STACK_ERROR.NONE,status:an.HTTP_STATUS_CODES.OTHER,statusText:"Empty Response",readyState:0}}catch(g){v.info(`Failed to handle error ${g}`),S={response:"",status:an.HTTP_STATUS_CODES.OTHER,statusText:"FailedToHandleError",readyState:0}}return S},this.hasPendingAttempts=()=>this.pendingAttempts.some((g=>g.pending)),this.getRequestFromStatus=g=>g?.request?.status||0,this.isBrowserOffline=()=>navigator&&!1===navigator.onLine,this.logger=f.createChild(`[${this.causeId}][Dispatcher]`),this.logger.info(`created request, url=${C}`),!isNaN(this.settings.hedgeDelayMs)&&this.settings.hedgeDelayMs>=kn&&this.settings.hedgeDelayMs<=Ln&&(this.hedgeDelayMs=this.settings.hedgeDelayMs),!isNaN(this.settings.hedgeMaxParallelAttempts)&&this.settings.hedgeMaxParallelAttempts>=0&&this.settings.hedgeMaxParallelAttempts<=Fn&&(this.hedgeMaxParallelAttempts=this.settings.hedgeMaxParallelAttempts),(isNaN(this.settings.perAttemptTimeoutMs)||this.settings.perAttemptTimeoutMs<=0)&&(this.settings.perAttemptTimeoutMs=15e3),(isNaN(this.settings.perRequestTimeoutMs)||this.settings.perRequestTimeoutMs<=0)&&(this.settings.perRequestTimeoutMs=45e3),(isNaN(this.settings.maxRequestAttempts)||this.settings.maxRequestAttempts<=0)&&(this.settings.maxRequestAttempts=4),(isNaN(this.settings.perRequestTimeoutWithHedgingMs)||this.settings.perRequestTimeoutWithHedgingMs<=0)&&(this.settings.perRequestTimeoutWithHedgingMs=45e3),(isNaN(this.settings.perAttemptTimeoutWithHedgingMs)||this.settings.perAttemptTimeoutWithHedgingMs<=0)&&(this.settings.perAttemptTimeoutWithHedgingMs=3e4)}sendRequest(){this.stackError=an.HTTP_STACK_ERROR.NONE;const timeoutCallback=()=>{this.stackError=an.HTTP_STACK_ERROR.REQUEST_TIMEOUT,this.cancelAllAttempts(an.HTTP_STACK_ERROR.REQUEST_TIMEOUT)};return this.logger.info("send api called"),this.requestTimer=ht.build(timeoutCallback,"REQUEST_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perRequestTimeoutWithHedgingMs:this.settings.perRequestTimeoutMs),new Promise(((g,f)=>{this.resolve=g,this.reject=f,this.scheduleNextRequest(!0)}))}cancelRequest(){this.logger.info("cancelRequest"),this.stackError=an.HTTP_STACK_ERROR.REQUEST_ABORTED,this.cancelAllAttempts(an.HTTP_STACK_ERROR.ATTEMPT_ABORTED)}cancelOtherAttempts(g){this.pendingAttempts.splice(g-1,1),this.cancelAllAttempts(an.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL)}cancelAllAttempts(g){this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.pendingAttempts.forEach((f=>{f.status=g,f.cancelDeferred.resolve(),this.stopAttemptTimeoutTimer(f)})),this.stopRequestTimer()}getRequestMethod(g){switch(g){case 0:return this.dispatcher.getAsync.bind(this.dispatcher);case 1:return this.dispatcher.postAsync.bind(this.dispatcher);case 2:return this.dispatcher.putAsync.bind(this.dispatcher);case 3:return this.dispatcher.removeAsync.bind(this.dispatcher);default:return null}}async queueAttempt(g){const f=g&&this.isNotRetryable(g);if(this.logger.info("queueAttempt"),f||!this.canScheduleNextAttempt())return this.logger.info(`unable to retry isNotRetryable ${f} ${JSON.stringify(g)}`),this.stopHedgeTimer(),this.stopRequestTimer(),void(this.hasPendingAttempts()||(this.settings.reportPreviousErrorsForTimeout&&g===en.ATTEMPT_TIMEOUT&&this.previousAttempt?this.reject(this.previousAttempt):this.reject(g)));if(this.isAuthFailedStatus(g)){this.logger.info("auth failed"),this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.stopRequestTimer();try{const f=g?.response?.headers,S=getRequestToken(this.request?.headers),v=g.response?.status===an.HTTP_STATUS_CODES.UNAUTHORIZED&&g.response?.operationFailure?.subCode===an.CALL_END_SUB_CODE.CONVERSATION_TERMINATION_INTERACTION_REQUIRED,C=await this.authRequiredCallback(f,S,{IPCAFailure:v});this.request=C}catch(f){return void this.reject(g)}}this.previousAttempt=g,this.hedgeTimer?this.logger.info("scheduleNextRequest ignored as there's already active hedge timer"):this.scheduleNextRequest(!1)}attempt(){if(this.logger.info("attempt to send request"),this.stackError===an.HTTP_STACK_ERROR.REQUEST_ABORTED||this.otherAttemptSuccessful)return;const g=(new Date).getTime();this.requestsSent++;const f=this.requestsSent,S=defer();this.request.timeout=S.promise;const v={cancelDeferred:S,status:an.HTTP_STACK_ERROR.NONE,timeoutTimer:null,pending:!0},timeoutRequest=()=>{v.status=an.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT,v.cancelDeferred.resolve()},C=ht.build(timeoutRequest,"ATTEMPT_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perAttemptTimeoutWithHedgingMs:this.settings.perAttemptTimeoutMs);v.timeoutTimer=C,this.pendingAttempts.push(v),this.getRequestMethod(this.requestType)(this.url,this.request).then((S=>{if(this.logger.info(`attempt successful, request response=${getPIISafeRequestResponse(S)} status=${this.getRequestFromStatus(S)}`),this.otherAttemptSuccessful)throw"Other attempt succesful";if(this.stackError===an.HTTP_STACK_ERROR.REQUEST_ABORTED)throw"Session disposed";if(!S)throw"Invalid response";v.pending=!1,this.otherAttemptSuccessful=!0,this.stopRequestTimer(),this.stopHedgeTimer(),this.stopAttemptTimeoutTimer(v),this.cancelOtherAttempts(f),this.resolve({success:!0,request:S.request,response:S.response,attempt:this.requestsSent,attemptStartTimestamp:g,attemptResponseTimestamp:(new Date).getTime()})})).catch((f=>{v.pending=!1,this.stopAttemptTimeoutTimer(v);const S=this.standardizeFailedRequest(f,v);this.logger.info(`attempt failed, request: ${getPIISafeRequest(f)} status=${S.status}`),this.onRequestFailed({abandoned:this.otherAttemptSuccessful,success:!1,request:S,attempt:this.requestsSent,attemptStartTimestamp:g,attemptResponseTimestamp:(new Date).getTime()}),this.queueAttempt(S)}))}getNextDelay(g){let f;if(g)f=0;else if(this.settings.enableRequestHedging)f=this.hedgeDelayMs;else{if(!(this.requestsSent<=this.settings.retryIntervalsMs.length))throw"Unable to get next delay";f=this.settings.retryIntervalsMs[this.requestsSent-1]}return this.logger.info(`next delay= ${f} ms`),f}isRequestWithStatus(g,f){return!!g&&f.indexOf(g.status)>-1}isNotRetryable(g){return!isRetryable(g?.status)}isAuthFailedStatus(g){return this.isRequestWithStatus(g,[an.HTTP_STATUS_CODES.UNAUTHORIZED])}},Bn={1:"POST",0:"GET",2:"PUT",3:"DELETE"},Hn=class{constructor(g,f){this.signalingSession=g,this.callStartTime=f,this.pendingRequests={},this.sendGetRequest=g=>this.sendRequest(0,g),this.sendPostRequest=g=>this.sendRequest(1,g),this.sendPutRequest=g=>this.sendRequest(2,g),this.sendDeleteRequest=g=>this.sendRequest(3,g),this.cancelRequestIfPending=(g,f,S,v)=>{this.logger.info(`[${f}][cancelRequestIfPending]`),this.pendingRequests[g]?S?this.hasPendingRequest(g,S)&&this.cancelRequest(g,S,f,v):Object.keys(this.pendingRequests[g]).forEach((S=>this.cancelRequest(g,S,f,v))):this.logger.info(`[${f}][cancelRequestIfPending]no pending request with name=${g}`)},this.cancelAllRequests=g=>{this.logger.info(`[${g}][cancelAllRequests]`);const f=[];return Object.keys(this.pendingRequests).forEach((S=>{Object.keys(this.pendingRequests[S]).forEach((v=>{f.push(this.cancelRequest(S,v,g))}))})),Promise.all(f).catch((()=>{}))},this.hasPendingRequest=(g,f)=>!!this.pendingRequests[g]&&Boolean(f?this.pendingRequests[g][f]:this.pendingRequests[g]),this.cancelRequest=(g,f,S,v)=>{try{return this.pendingRequests[g][f].dispatcher&&this.pendingRequests[g][f].dispatcher.cancelRequest(),this.pendingRequests[g][f].aborted=!0,this.pendingRequests[g][f].errorDetails=v,this.logger.info(`[${S}][cancelRequest]Request=${g} aborted ${v?`with errorDetails ${JSON.stringify(v)}`:""}`),this.pendingRequests[g][f].requestPromise.catch((()=>{}))}catch(v){return this.logger.warn(`[${S}][cancelRequest]Unable to cancel request=${g}, requestId=${f}`),Promise.resolve()}},this.buildRequestTelemetry=(g,f,S,v)=>({name:`${Bn[g]}-${f.requestName}`,url:f.url,eventStart:S-this.callStartTime,trouterReady:-1,requestReady:-1,status:-1,attempts:[],rtt:-1,uid:f.requestId,causeId:f.causeId,requestDispatcherConfig:v,enableRequestHedging:this.shouldEnableRequestHedging(v)}),this.addPendingRequest=g=>(this.pendingRequests[g.requestName]||(this.pendingRequests[g.requestName]={}),this.pendingRequests[g.requestName][g.requestId]={dispatcher:null,requestPromise:null,aborted:!1},this.pendingRequests[g.requestName][g.requestId]),this.sendRequest=(g,f)=>{if(!f.url){this.logger.error(f.requestName,"Link does not exist");const g={code:an.CALL_END_CODE.HTTP_OTHER_ERROR,subCode:an.CALL_END_SUB_CODE.MISSING_REQUEST_URI,phrase:`Link does not exist for requestName: ${f.requestName}.`};return Promise.reject(g)}f.requestId||(f.requestId=newGuid2()),f.causeId||(f.causeId=causeId2());let S=!1,v=!1;const C=this.logger.createChild(`[${f.causeId}][${f.requestName}]`);C.info("[scheduled]");const _=this.getInternalHttpDispatcherConfig(f.requestName,f.operationType);let T;f.skipHttpTelemetry||(f.skipHttpTelemetry=!1);const I=build3(),b=(new Date).getTime(),A=[],P=this.buildRequestTelemetry(g,f,b,_),updateRequestTelemetry=()=>{this.signalingSession.disposed?this.logger.info("Unable to record telemetry, session disposed"):this.signalingSession.telemetryHelper.updateNetworkRequest(P)},deleteRequestTelemetry=()=>{this.signalingSession.telemetryHelper.deleteNetworkRequest(P)};updateRequestTelemetry();const logRequestAttempt=(g,S,_)=>{if(!g?.request)return void this.logger.warn(f.requestName,"missing request details, unable to record for telemetry!");C.info(`[finished][status=${g.request.status}][statusText=${g.request.statusText}][retryCount=${g.attempt}]`);const T=g.request.status,I=g.request.response?.operationFailure?.subCode,A={status:T,statusSubCode:I,start:g.attemptStartTimestamp-b,end:g.attemptResponseTimestamp-b,online:isTrouterAndNavigatorConnected(this.signalingSession.signalingAgentConfig.trouterServiceProvider)};g.abandoned&&(A.abandoned=!0),g.request.statusText&&(A.statusText=g.request.statusText),!S&&v||(P.status=T,P.statusSubCode=_||I),(S||!v&&T>=200&&T<400)&&(v=!0),P.attempts.push(A),updateRequestTelemetry()};if(this.hasPendingRequest(f.requestName,f.requestId))return this.logger.warn(f.requestName,f.requestId,"is already pending request!!"),this.pendingRequests[f.requestName][f.requestId].requestPromise;T=this.addPendingRequest(f);const recordTelemetryAndCleanup=(g,S,v,_)=>{if(g&&f.skipHttpTelemetry)return this.logger.info("Skipping telemetry"),void deleteRequestTelemetry();C.info(`[steps=${A}]`),this.pendingRequests[f.requestName][f.requestId].aborted&&(P.aborted=!0),this.hasPendingRequest(f.requestName,f.requestId)?(delete this.pendingRequests[S][v],Object.keys(this.pendingRequests[S]).length||delete this.pendingRequests[S]):this.logger.warn("Unable to clean up!"),this.signalingSession.disposed||(_&&(P.error=_),P.rtt=I.duration(),this.signalingSession.telemetryHelper.addNetworkOperationCompleted(f.requestName,g,I.duration()),updateRequestTelemetry(),this.signalingSession.telemetryHelper.sendHttpTelemetryData(P.uid))},checkIfNotDisposed=g=>(...S)=>{if(this.signalingSession.disposed){const g=`[${f.causeId}][${f.requestName}][failed][reason=Session disposed]`;throw C.info("[failed][reason=Session disposed]"),new Error(g)}if(this.hasPendingRequest(f.requestName,f.requestId)&&this.pendingRequests[f.requestName][f.requestId].aborted){let g;const S=`[${f.causeId}][${f.requestName}][failed][reason=request already aborted]`,v=this.pendingRequests[f.requestName][f.requestId].errorDetails;throw v?(g=v,g.phrase=S):g=S,C.info(`${S}`),new Error(JSON.stringify(g))}return g(...S)},R=checkIfNotDisposed((()=>(A.push("[waitForTrouter]"),f.withoutTrouter?Promise.resolve():this.signalingSession.ensureMessageChannelReady(f.requestName)))),M=checkIfNotDisposed((()=>(A.push("[trouterReady]"),P.trouterReady=I.duration(),f.onceTrouterReady&&f.onceTrouterReady(),updateRequestTelemetry(),Promise.resolve()))),w=checkIfNotDisposed((()=>{const S=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,v=this.signalingSession.signalingAgentConfig.enableFetchApi||f.useFetch,C=getTokenMetadata(this.signalingSession.signalingAgentConfig,S,g,f,!1,void 0,this.logger);return A.push("[buildRequest]"),get3({signalingSession:this.signalingSession,operation:f.requestName,data:f.payload,customHeaders:f.customHeaders?.getAll(),causeId:f.causeId,tokenRequestOptions:C,requestId:f.requestId,useFetch:v,fetchUseKeepAlive:f.fetchUseKeepAlive},this.logger)})),O=checkIfNotDisposed((g=>{A.push("[failedToBuildRequestOptions]");const f={request:{status:an.HTTP_STATUS_CODES.OTHER,statusText:"Local error"},attempt:1,success:!1,attemptResponseTimestamp:(new Date).getTime(),attemptStartTimestamp:(new Date).getTime()};let v;return g&&(g.skypeTokenError?(f.request={status:an.CALL_END_SKYPE_TOKEN_ERROR.code,statusText:an.CALL_END_SKYPE_TOKEN_ERROR.phrase},v=an.CALL_END_SKYPE_TOKEN_ERROR.subCode):g.tokenError?(f.request={status:an.CALL_END_TOKEN_ERROR.code,statusText:an.CALL_END_TOKEN_ERROR.phrase},v=g.errorSubCode&&g.errorSubCode>0?g.errorSubCode:an.CALL_END_TOKEN_ERROR.subCode):g.tokenTimeoutError&&(S?(f.request={status:an.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.code,statusText:an.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.phrase},v=an.CALL_END_TOKEN_TIMEOUT_INTERACTIVITY_REQUIRED.subCode,g.tokenInteractivityRequiredTimeout=!0):(f.request={status:an.CALL_END_TOKEN_TIMEOUT_ERROR.code,statusText:an.CALL_END_TOKEN_TIMEOUT_ERROR.phrase},v=an.CALL_END_TOKEN_TIMEOUT_ERROR.subCode))),logRequestAttempt(f,!1,v),Promise.reject(g)})),D=checkIfNotDisposed((g=>(A.push("[requestBuilt]"),P.requestReady=I.duration(),g.usedCachedSkypetoken&&(P.usedCachedSkypetoken=g.usedCachedSkypetoken),updateRequestTelemetry(),Promise.resolve(g)))),authRequiredCallback=(v,C,_)=>{A.push("[authRequired]"),_?.IPCAFailure&&(S=!0);const T=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,I=getTokenMetadata(this.signalingSession.signalingAgentConfig,T,g,f,!0,v,this.logger);return I.invalidToken=C,get3({signalingSession:this.signalingSession,operation:f.requestName,data:f.payload,customHeaders:f.customHeaders?.getAll(),causeId:f.causeId,forceFetchToken:!0,tokenRequestOptions:I,requestId:f.requestId},this.logger)},N=checkIfNotDisposed((S=>{A.push("[sendRequest]");const v={..._,enableRequestHedging:this.shouldEnableRequestHedging(_),hedgeDelayMs:_.hedgeDelayMs,hedgeMaxParallelAttempts:this.signalingSession.signalingAgentConfig.hedgeMaxParallelAttempts,retryIntervalsMs:f.disableRetry||!_.retryIntervalsMs?[]:_.retryIntervalsMs,reportPreviousErrorsForTimeout:this.signalingSession.signalingAgentConfig.reportPreviousErrorsForTimeout},C=build4({logger:this.logger,causeId:f.causeId,dispatcher:this.signalingSession.signalingAgentConfig.httpRequestDispatcher,url:f.url,request:S,requestType:g,authRequiredCallback:authRequiredCallback,attemptFailureCallback:g=>{logRequestAttempt(g,!1)},settings:v});return T.dispatcher=C,updateRequestTelemetry(),C.sendRequest()})),k=checkIfNotDisposed((async g=>(logRequestAttempt(g,!0),C.info("[success]"),recordTelemetryAndCleanup(!0,f.requestName,f.requestId),g))),onFailure=g=>{const S=getPrintableObject(g);return recordTelemetryAndCleanup(!1,f.requestName,f.requestId,S),!g||g.readyState||g.status?C.info(`[failed][reason=${S}]`):C.info(`[failed][offline][reason=${S}]`),Promise.reject(g)},L=Promise.resolve().then(R).then(M).then(w).catch(O).then(D).then(N).then(k).catch(onFailure);return T.requestPromise=L,L},this.logger=this.signalingSession.logger.createChild("[HTTP]")}getInternalHttpDispatcherConfig(g,f="Other"){let S={...On.Default,...Dn[f],...On[g]};return this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap&&(S={...S,...this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap[f]}),this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap&&(S={...S,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap.Default,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap[g]}),this.logger.info(`getInternalHttpDispatcherConfig request type: ${g} config: ${safeJsonStringify(S)}`),S}shouldEnableRequestHedging(g){return!!(this.signalingSession.getMeetingInfo()&&g.requestHedgingCapability.indexOf("enabledForMeetings")>-1)||!this.signalingSession.multiParty&&g.requestHedgingCapability.indexOf("enabledForP2PCalls")>-1||!!(this.signalingSession.multiParty&&g.requestHedgingCapability.indexOf("enabledForGroupCalls")>-1)||g.requestHedgingCapability.indexOf("enabled")>-1}};function getPayload8(g,f,S){assertNotNull(g,"signalingSession cannot be null");let v=[];S&&(v=getMediaTypes(S),g.telemetryHelper.addOutgoingModalities(v));const C=causeId2();return{payload:{mediaNegotiation:{callModalities:v,sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},links:{mediaAnswer:get2(g,rn.MEDIA_ANSWER,C),rejection:get2(g,rn.MEDIA_REJECTION,C)},mediaContent:f}}}}function getPayload9(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{mediaNegotiationFailure:{sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},code:f.code,subCode:f.subCode,phrase:f.phrase},debugContent:{callId:g.correlationId,endpointId:g.participantManager.localParticipant.endpointId}}}}function getPayload10(g,f,S){assertNotNull(g,"signalingSession cannot be null");let v=[];return S&&(v=getMediaTypes(S),g.telemetryHelper.addOutgoingModalities(v)),{payload:{mediaAnswer:{callModalities:v,sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},links:{mediaAcknowledgement:get2(g,rn.MEDIA_ACKNOWLEDGEMENT)},clientContentForMediaController:g.webRtcSignalingManager.getClientUrls(),mediaContent:f},debugContent:{callId:g.correlationId,endpointId:g.participantManager.localParticipant.endpointId}}}}var $n=class{constructor(g,f,S){this.telemetryHelper=S,this.vbssInitiated=!1,this.disposed=!1,this.fsmState=an.MEDIA_RENEGOTIATION_FSM_STATE.IDLE,this.fsmStateCauseId="",this.links={},this.renegotiationOffersSeenSoFar=[],this.isOutgoingRenegotiationInProgress=()=>this.fsmState===an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION||this.fsmState===an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.isIncomingRenegotiationInProgress=()=>this.fsmState===an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION||this.fsmState===an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.acceptRenegotiationAsync=(g,f,S)=>{this.logger.info(`[${S}][acceptRenegotiationAsync][mediaTypes=${f}]`),this.signalingSession.telemetryHelper.recordEvent(dn.ACCEPT_RENEGOTIATION,{mediaTypes:f,causeId:S}),assertNotNullOrEmpty(this.links[an.LINKS.MEDIA_ANSWER],"MediaAnswer link not set");const v=defer();switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,S);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,S);break;default:return this.logger.info(`[${S}][acceptRenegotiationAsync]there is no incoming media renegotiation offer to accept`),v.reject(new Error("there is no incoming media renegotiation offer to accept")),v.promise}const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT,this.handleMediaAnswerAcknowledgmentTimeout.bind(this,S),an.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_ACKNOWLEDGEMENT_TIMEOUT)};return this.signalingSession.http.sendPostRequest({url:this.links[an.LINKS.MEDIA_ANSWER],payload:getPayload10(this.signalingSession,g,f),requestName:hn.SEND_MEDIA_ANSWER.name,onceTrouterReady:onceTrouterReady,causeId:S}).then((g=>{v.resolve(g.response)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][acceptRenegotiationAsync] error: ${getPrintableObject(f)}`),this.disposed||this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),v.reject(new Error(`acceptRenegotiationAsync failed because : ${getPrintableObject(g)}`))})),v.promise},this.startRenegotiationAsync=(g,f,S,v)=>{this.logger.info(`[${v}][startRenegotiationAsync][mediaTypes=${S}]`),this.signalingSession.telemetryHelper.recordEvent(dn.START_RENEGOTIATION,{causeId:v,mediaTypes:S}),assertNotNullOrEmpty(f,"MediaRenegotiation link not set");const C=defer();switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,v);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:case an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.logger.info(`[${v}][startRenegotiationAsync][failed] can only be performed with no current outstanding renegotiations, previous negotiation causeId=${this.fsmStateCauseId}`),this.signalingSessionCallback.onMediaRenegotiationRejection(this.getGlareError(),v),Promise.resolve(null);default:return this.logger.info(`[${v}][startRenegotiationAsync][failed] can only be performed on an established call`),C.reject(new Error("media renegotiation can only be performed on an established call")),C.promise}const _=S&&arrayContains(S,an.MEDIA_TYPES.SCREEN_SHARER);_?(this.vbssInitiated=!0,this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.START)):!_&&this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.STOP));const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER,this.handleMediaAnswerTimeout.bind(this),an.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_TIMEOUT)};return this.signalingSession.http.sendPostRequest({url:f,payload:getPayload8(this.signalingSession,g,S),requestName:hn.START_RENEGOTIATION.name,onceTrouterReady:onceTrouterReady,causeId:v}).then((g=>{C.resolve(g.response)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${v}][startRenegotiationAsync] error: ${getPrintableObject(f)}`),!this.disposed){switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,v);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,v)}this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER)}C.reject(new Error(`startRenegotiationAsync failed because : ${getPrintableObject(g)}`))})),C.promise},this.handleMediaAcknowledgment=(g,f)=>{this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ACKNOWLEDGEMENT,{causeId:f}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),this.signalingSession.saveMediaControllerLinksIfAny(g),this.signalingSession.saveUpdatedCallLinksIfAny(g),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!0,f)},this.onCallConnected=g=>{this.logger.info("onCallConnected"),this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,g)},this.handleMediaNegotiationFailure=g=>{const f=extractCauseIdFromMessage(g);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_MEDIA_NEGOTIATION_FAILURE,g),this.handleMediaNegotiationFailureInternal(g.body.mediaNegotiationFailure,g.origin,f)},this.handleMediaAnswer=(g,f)=>{switch(this.logger.info(`[${f}][handleMediaAnswer]`),this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ANSWER,{causeId:f}),this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,f);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,f);break;default:return}this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER);let S=[];g.mediaAnswer.callModalities&&g.mediaAnswer.callModalities.length>0&&(S=getMediaTypes(g.mediaAnswer.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(S));const v={provisional:!1,renegotiation:!0,mediaTypes:S,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(g.mediaAnswer.mediaContent),mediaContent:g.mediaAnswer.mediaContent};this.signalingSession.http.sendPostRequest({url:g.mediaAnswer.links.mediaAcknowledgement,payload:null,requestName:hn.SEND_MEDIA_ACKNOWLEDGEMENT.name,causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);this.logger.info(`[${f}][handleMediaAnswer] error: ${getPrintableObject(S)}`),this.signalingSession.disposed||this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ANSWER_FAILED,{causeId:f})})),this.signalingSessionCallback.onAnswer(v,f)},this.handleMediaNegotiationOffer=g=>{const f=g.body,S=g.headers,v=extractCauseIdFromMessage(g);this.logger.info(`[${v}][handleMediaNegotiationOffer]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_MEDIA_OFFER,g);const C=isDuplicateMessage(S,this.renegotiationOffersSeenSoFar);switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,v),this.raiseMediaRenegotiationOffer(f,v);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,v),this.raiseMediaRenegotiationOffer(f,v);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:if(this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.supportMediaRetargetWhileIncomingRenegotiation){this.raiseMediaRenegotiationOffer(f,v);break}this.rejectAndLog(v,C,f);break;default:this.rejectAndLog(v,C,f)}},this.rejectRenegotiationAsync=(g,f)=>{this.logger.info(`[${f}][rejectRenegotiationAsync]`),this.signalingSession.telemetryHelper.recordEvent(dn.REJECT_RENEGOTIATION,{rejectionData:g,causeId:f}),assertNotNullOrEmpty(this.links[an.LINKS.MEDIA_REJECTION],"MediaRejection link not set");const S=g||{code:an.CALL_END_CODE.NOT_ACCEPTABLE_HERE,subCode:an.CALL_END_SUB_CODE.MEDIA_ANSWER_PROCESSING_ERROR,phrase:an.CALL_END_PHRASE.MEDIA_ANSWER_ERROR};switch(this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:return this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,f),this.rejectMediaRenegotiation(this.links[an.LINKS.MEDIA_REJECTION],S,f);case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,f),this.rejectMediaRenegotiation(this.links[an.LINKS.MEDIA_REJECTION],S,f);default:return this.logger.error(`[${f}][rejectRenegotiationAsync][failed] There is no incoming media renegotiation offer to reject`),Promise.resolve(null)}},this.handleRetargetCompleted=g=>{const f=g.body.retargetCompleted,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleRetargetCompleted][details=${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_RETARGET_COMPLETED,g,getPIISafeObject(f)),0===f.code?this.signalingSessionCallback.onReTargetCompletedSuccess(S):this.signalingSessionCallback.onReTargetCompletedFailure(f,S)},this.dispose=()=>{this.logger.info("mediaRenegotiationManager :: dispose"),this.disposed=!0},this.getGlareError=()=>({code:an.CALL_END_CODE.GLARE_ERROR,subCode:an.CALL_END_SUB_CODE.MEDIA_GLARE_ERROR,phrase:an.CALL_END_PHRASE.RENEGOTIATION_IN_PROGRESS,previousNegotiationCauseId:this.fsmStateCauseId}),this.handleMediaNegotiationFailureInternal=(g,f,S)=>{switch(this.logger.info(`[${S}][handleMediaNegotiationFailureInternal][failureData=${getPIISafeObject(g)}]`),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.fsmState){case an.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,S);break;case an.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(an.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,S);break;default:return}this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.REJECTED)),this.signalingSession.telemetryHelper.addIncomingModalities(["Rejected"]),this.signalingSessionCallback.onMediaRenegotiationRejection({code:g.code,subCode:g.subCode,phrase:g.phrase},S)},this.signalingSession=g,this.signalingSessionCallback=f,this.logger=g.logger.createChild((()=>`[RenegotiationManager][${this.fsmState}][stateCauseId=${this.fsmStateCauseId}]`))}rejectAndLog(g,f,S){this.logger.error(`[${g}][handleMediaNegotiationOffer] Cannot handle the incoming mediaRenegotiation offer in present callstate. Either call not connected or renegotiation in progress. isDuplicateOffer=${f}`),f||this.rejectMediaRenegotiation(S.mediaNegotiation.links.rejection,this.getGlareError(),g)}setFsmState(g,f){this.fsmState=g,this.fsmStateCauseId=f,this.logger.info(`[setFsmState]state=${g}`),this.telemetryHelper.recordEvent(dn.MEDIA_FSM_STATE_CHANGED,{state:g,causeId:f})}raiseMediaRenegotiationOffer(g,f){this.logger.info(`[${f}][raiseMediaRenegotiationOffer]`),this.links[an.LINKS.MEDIA_ANSWER]=g.mediaNegotiation.links.mediaAnswer,this.links[an.LINKS.MEDIA_REJECTION]=g.mediaNegotiation.links.rejection;let S=[];g.mediaNegotiation.callModalities&&g.mediaNegotiation.callModalities.length>0&&(S=getMediaTypes(g.mediaNegotiation.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(S),arrayContains(S,an.MEDIA_TYPES.SCREEN_SHARER)&&this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.REMOTE_START));const v={mediaTypes:S,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(g.mediaNegotiation.mediaContent),mediaContent:g.mediaNegotiation.mediaContent,renegotiation:!0};this.signalingSessionCallback.onOffer(v,f)}rejectMediaRenegotiation(g,f,S){this.logger.info(`[${S}][rejectMediaRenegotiation][rejectionData=${getPIISafeObject(f)}]`);const v=defer();return this.signalingSession.http.sendPostRequest({url:g,payload:getPayload9(this.signalingSession,f),requestName:hn.SEND_MEDIA_REJECTION.name,causeId:S}).then((g=>{v.resolve(g.response)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][rejectMediaRenegotiation] error: ${getPrintableObject(f)}`),v.reject(new Error(`rejectMediaRenegotiation failed because : ${getPrintableObject(g)}`))})),v.promise}handleMediaAnswerTimeout(g){this.logger.info(`[${g}][handleMediaAnswerTimeout]`),this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(un.VBSS_OPERATION.TIMEOUT)),this.signalingSession.telemetryHelper.addIncomingModalities(["Timeout"]),this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ANSWER_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.handleMediaNegotiationFailureInternal({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.MEDIA_FINAL_ANSWER_TIMEOUT,phrase:an.CALL_END_PHRASE.MEDIA_FINAL_ANSWER_TIMEOUT},un.EVENT_SOURCE.LOCAL,g)}handleMediaAnswerAcknowledgmentTimeout(g){this.logger.info(`[${g}][handleMediaAnswerAcknowledgmentTimeout]`),this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ACKNOWLEDGEMENT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT);const f={reason:"timed out waiting for Media Answer Acknowledgement"};this.signalingSessionCallback.onMediaAcknowledgementFailure(!0,f,g)}},jn=class{constructor(){this.requests={}}clear(g,f){const S=f||{code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((f=>{this.rejectOperation(f,g,S)}))}hasOperation(g){return this.requests.hasOwnProperty(g)}getAllOperations(){return this.requests}getOperation(g){return this.hasOperation(g)?this.requests[g]:null}setOperation(g,f){return!this.hasOperation(g)&&(this.requests[g]=f,!0)}rejectOperation(g,f,S){const v=new Error(f);if(S&&(v.endCode=S),this.hasOperation(g)){const f=this.requests[g].promise;delete this.requests[g],f.reject(v)}}resolveOperation(g,f){if(this.hasOperation(g)){const S=this.requests[g].promise;delete this.requests[g],S.resolve(f)}}},Gn=class{constructor(g){this.logger=g,this.localAddParticipantRequests=new jn,this.localAdmitParticipantRequests=new jn,this.localCallMeBackRequests=new jn,this.localRemoveParticipantEndpointRequests=new jn,this.localRemoveParticipantRequests=new jn,this.localUpdateParticipantInterpretationStateRequest=new jn,this.participantIdMriMap=new Map}dispose(g,f,S){this.logger.info(`[${S}][dispose]`),this.rejectAllPendingOperations(g,f)}getAllPendingOperations(g,f){this.logger.info(`[${f}][getAllPendingOperations] ${g}`);const S=this.getOperationTable(g);return S?S.getAllOperations():null}getPendingOperation(g,f,S){this.logger.info(`[${S}][getPendingOperation] ${g} ${f}`);const v=this.getOperationTable(g);return v?v.getOperation(f):null}getRnlMri(g,f){this.logger.info(`[${f}][getRnlMri] ${g}`);for(const f of g)if(this.participantIdMriMap.has(f))return this.participantIdMriMap.get(f);return""}hasPendingOperation(g,f,S){this.logger.info(`[${S}][hasPendingOperation] ${g} ${scrubMriOrOmit(f)}`);const v=this.getOperationTable(g);return!!v&&v.hasOperation(f)}rejectPendingOperation(g,f,S,v,C){this.logger.info(`[${C}][rejectPendingOperation] ${g} ${scrubMriOrOmit(f)} reason: ${S}`);const _=this.getOperationTable(g);_&&_.rejectOperation(f,S,v)}resolvePendingOperation(g,f,S,v){this.logger.info(`[${v}][resolvePendingOperation]: ${scrubMriOrOmit(f)}`);const C=this.getOperationTable(g);C&&C.resolveOperation(f,S)}setPendingOperation(g,f,S,v){this.logger.info(`[${v}][setPendingOperation] ${g} ${scrubMriOrOmit(f)} value: ${S}`);const C=this.getOperationTable(g);if(!C)return!1;if(0===g){const g=S&&S.participant&&S.participant.participantId;g&&this.participantIdMriMap.set(g,f)}return C.setOperation(f,S)}setParticipantIdToMriMapping(g,f,S,v){v?(this.logger.info(`[${S}][setParticipantIdMriMap] ${mriOrId(g)}: ${scrubMriOrOmit(f)} clear mapping.`),this.participantIdMriMap.delete(g)):g&&f&&(this.logger.info(`[${S}][setParticipantIdMriMap] ${mriOrId(g)}: ${scrubMriOrOmit(f)}`),this.participantIdMriMap.set(g,f))}getOperationTable(g){switch(g){case 0:return this.localAddParticipantRequests;case 1:return this.localAdmitParticipantRequests;case 2:return this.localCallMeBackRequests;case 4:return this.localRemoveParticipantEndpointRequests;case 3:return this.localRemoveParticipantRequests;case 5:return this.localUpdateParticipantInterpretationStateRequest;default:return null}}rejectAllPendingOperations(g,f){this.logger.info("rejectLocalQueuedOperations"),this.localAddParticipantRequests.clear(g,f),this.localAdmitParticipantRequests.clear(g,f),this.localCallMeBackRequests.clear(g,f),this.localRemoveParticipantRequests.clear(g,f),this.localRemoveParticipantEndpointRequests.clear(g,f),this.localUpdateParticipantInterpretationStateRequest.clear(g,f)}};function getPayload11(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");const C=S.groupId?{id:S.groupId}:null,_=S.threadId?{threadId:S.threadId,messageId:S.messageId||null}:null;let T=[],I={};f&&f.length>0?(T=f.map((f=>({id:f.nonMaskedId?f.nonMaskedId:f.id,assertedId:f.assertedId,displayName:f.displayName,participantId:f.participantId,replacementDetails:3===S.replacementType?g.getReplacementDetailsByParticipantLegOfCall(S.callIdToReplace,f.id,f.replacementParticipantId):void 0}))),I={addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE)}):I={addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE)};const b={payload:{disableUnmute:S&&S.disableUnmute,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},to:T},participantInvitationData:getParticipantInvitationData(S),replacementDetails:3===S.replacementType?void 0:v,groupContext:C,groupChat:_,links:I}};return S&&S.alternateId&&(b.payload.participants.from.alternateId=S.alternateId),S?.callingLineIdentity&&(b.payload.participants.from.callingLineIdentity=S.callingLineIdentity),S?.clientScenario&&(b.payload.debugContent={clientScenario:S.clientScenario}),b}function getPayload12(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");const C=f.map((g=>(assertNotNull(g,"remoteParticipant cannot be null"),{id:g.id,assertedId:g.assertedId,displayName:g.displayName,participantId:g.participantId})));return{payload:{disableUnmute:S&&S.disableUnmute,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,alternateId:S?S.alternateId:null,callingLineIdentity:S?S.callingLineIdentity:null},to:C},participantInvitationData:getParticipantInvitationData(S),replacementDetails:v,links:{addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE)},debugContent:{clientScenario:S.clientScenario}}}}function getPayload13(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},to:[{id:f.id,displayName:f.displayName}]},links:{admitFailure:get2(g,rn.CONV_ADMIT_PARTICIPANT_FAILURE),admitSuccess:get2(g,rn.CONV_ADMIT_PARTICIPANT_SUCCESS)},debugContent:{causeId:S}}}}function getPayload14(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},mediaTypes:["audio"]}}}function getPayload15(g,f,S,v=!1,C=null){assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"muteScope be null"),assertNotNull(S,"participantList cannot be null");const _={from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:f,muteParticipants:S,mediaTypes:["audio"]};return v&&(_.links={clientCallback:get2(g,rn.MUTE_UNMUTE_ASYNC,C)},_.operationId=C),{payload:_}}function getPayload16(g,f,S,v,C,_){assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"participantsIds cannot be null");const T=g.groupId?{id:g.groupId}:null,I=v?{threadId:v,messageId:C||null}:null,b=[];return f.forEach((g=>{const f={id:g};b.push(f)})),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},invitationType:an.INVITATION_TYPE.NUDGE,to:b},participantInvitationData:_,groupContext:T,groupChat:I,links:{nudgeParticipantSuccess:get2(g,rn.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:get2(g,rn.CONV_NUDGE_PARTICIPANT_FAILURE)}}}}function getPayload17(g,f,S){assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"participantsIds cannot be null");const v=[];return f.forEach((g=>{const f={id:g};v.push(f)})),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},invitationType:an.INVITATION_TYPE.NUDGE,to:v},participantInvitationData:S,links:{nudgeParticipantSuccess:get2(g,rn.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:get2(g,rn.CONV_NUDGE_PARTICIPANT_FAILURE),addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE)}}}}function getPayload18(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{transactionEnd:f}}}function getPayload19(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:S,toEndpoints:[{id:f.id,endpointId:f.endpointId}]},links:{removeParticipantSuccess:get2(g,rn.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:get2(g,rn.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function getPayload20(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},to:[{id:f.id,displayName:f.displayName}]},links:{removeParticipantSuccess:get2(g,rn.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:get2(g,rn.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function getPayload21(g,f=!1,S=null){assertNotNull(g,"signalingSession cannot be null");const v={from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},mediaTypes:["audio"]};return f&&(v.links={clientCallback:get2(g,rn.MUTE_UNMUTE_ASYNC,S)},v.operationId=S),{payload:v}}function getPayload22(g,f,S,v=""){assertNotNull(S&&"specified"===S,"Only non-null non-empty scope of 'specified' is supported."),assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"participantsIds cannot be null");const C=[];return f.forEach((g=>{const f={id:g,meetingRole:v};C.push(f)})),{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:S,to:C}}}function getUpdateParticipantInterpretationStatePayload(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"options cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id},to:f,links:{updateParticipantInterpretationStateStatus:get2(g,rn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS)},operationId:S}}}var qn=__toESM2(M),Wn=class{constructor(g,f){this.participantManager=g,this.logger=f,this.handleRosterUpdate=(g,f,S,v)=>{if("Delta"===g.type||"MultiPartyEndpoint"===g.type){if(void 0===g.sequenceNumber&&(g.sequenceNumber=this.lastRosterUpdateSeqNumber),this.logger.info(`[${v}][handleRosterUpdate][sequenceNumber=${g.sequenceNumber}]`),this.rostersInLifetime.add(g.sequenceNumber),"Delta"===g.type)this.logger.info(`[${v}][handleRosterUpdate], RosterType: Delta, isFullRoster: ${S}`),this.handleDeltaRoster(g,S,f,v);else{if(this.logger.info(`[${v}][handleRosterUpdate], RosterType: MultiPartyEndpoint`),this.isRosterStale(g,v))return this.participantManager.signalingSession.telemetryHelper.recordEvent(dn.IGNORE_OLD_ROSTER,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,sequenceNumber:g.sequenceNumber,causeId:v}),void this.logger.info(`[${v}][handleRosterUpdate] Ignoring old roster update: received ${g.sequenceNumber}, but already handled ${this.lastRosterUpdateSeqNumber}`);for(const S of Object.keys(g.participants)){const C=cn.fromRoster(g.participants[S]);this.handleRosterParticipant(C,f,v)}this.checkForRemovedParticipants(f,g.participants,v),this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(g.participantCounts,v)}if(g.sequenceNumber>this.lastRosterUpdateSeqNumber){this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(g.participantCounts,v),this.lastRosterUpdateSeqNumber=g.sequenceNumber,this.firstRosterUpdateSeqNumber<0&&(this.firstRosterUpdateSeqNumber=this.lastRosterUpdateSeqNumber);const f=Object.keys(g.participants||0).length;this.participantCountInFirstRoster<0&&(this.participantCountInFirstRoster=f),this.maxConcurrentParticipantsDuringLeg=Math.max(this.maxConcurrentParticipantsDuringLeg,f)}this.recordTelemetry(g,S,v),this.participantManager.signalingSessionCallback.onRosterHandlingComplete()}else this.logger.warn(`[${v}][handleRosterUpdate][sequenceNumber=${g.sequenceNumber}] invalid roster type ${g.type}`)},this.isRosterStaleFromFull=(g,f)=>(this.logger.info(`[${f}][isRosterStale] ${g.sequenceNumber<this.lastFullRosterSeqNumber}`),g.sequenceNumber<this.lastFullRosterSeqNumber),this.isRosterStale=(g,f)=>(this.logger.info(`[${f}][isRosterStale] ${g.sequenceNumber<this.lastRosterUpdateSeqNumber}`),g.sequenceNumber<this.lastRosterUpdateSeqNumber),this.updateLocalParticipantFromSubscribe=(g,f)=>{this.logger.info(`[${f}][updateLocalParticipantFromSubscribe]`),this.updateLocalParticipant(g,f)},this.handleParticipantAcceptedBy=(g,f,S)=>{const v=f.hasOwnProperty(g.id),C=g.id===g.acceptedBy.id;this.logger.info(`[${S}][RosterManager::handleParticipantAcceptedBy] oldParticipantInRoster: ${v}`),this.participantManager.participantOperationHandler.setParticipantIdToMriMapping(g.participantId,g.id,S,!0),v&&!C&&this.handleRemovedDeltaRosterParticipant(new cn({id:g.id}),this.lastRosterUpdateSeqNumber,f,S)},this.lastRosterUpdateSeqNumber=-1,this.lastFullRosterSeqNumber=-1,this.firstRosterUpdateSeqNumber=-1,this.tombstoneSequence=new Map,this.latestRosterVersionForActiveParticipants=new Map,this.rostersInLifetime=new Set,this.maxConcurrentParticipantsDuringLeg=-1,this.participantCountInFirstRoster=-1}recordTelemetry(g,f,S){const v={participantCountInLastRoster:Object.keys(g.participants||0).length,participantCountInFirstRoster:this.participantCountInFirstRoster,sequenceNumberOfLastRoster:this.lastRosterUpdateSeqNumber,sequenceNumberOfLastFullRoster:this.lastFullRosterSeqNumber,sequenceNumberOfFirstRoster:this.firstRosterUpdateSeqNumber,rosterType:g.type,isFullRoster:f,maxConcurrentParticipantsDuringLeg:this.maxConcurrentParticipantsDuringLeg,totalParticipantsDuringLifetimeOfLeg:this.tombstoneSequence.size+this.latestRosterVersionForActiveParticipants.size,countOfMissingNotifications:this.getMissingNotificiations()};this.logger.info(`[recordTelemetry] data ${JSON.stringify(v,null,4)}`),this.participantManager.signalingSession.telemetryHelper.recordRosterEvent(v,dn.HANDLE_ROSTER_UPDATE,S)}getMissingNotificiations(){const g=this.lastRosterUpdateSeqNumber-this.firstRosterUpdateSeqNumber+1-this.rostersInLifetime.size;return g>0?g:0}isParticipantRosterStale(g,f){if(this.logger.info(`[isParticipantRosterStale], rosterParticipantVersion ${f}`),f){if(this.tombstoneSequence.has(g))return f<=this.tombstoneSequence.get(g);if(this.latestRosterVersionForActiveParticipants.has(g))return f<=this.latestRosterVersionForActiveParticipants.get(g)}return!1}handleDeltaRoster(g,f,S,v){if(this.logger.info(`[${v}][handleDeltaRoster] isFullRoster ${f}`),this.isRosterStaleFromFull(g,v))return this.participantManager.signalingSession.telemetryHelper.recordEvent(dn.IGNORE_OLD_ROSTER,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,lastFullRosterSeqNumber:this.lastFullRosterSeqNumber,sequenceNumber:g.sequenceNumber,causeId:v}),void this.logger.info(`[${v}][handleRosterUpdate] Ignoring old roster update: received ${g.sequenceNumber}, but already handled full roster ${this.lastFullRosterSeqNumber}`);if(f){for(const f of Object.keys(S))if(!g.participants.hasOwnProperty(f)&&!this.isParticipantRosterStale(f,g.sequenceNumber)){const C=new cn({id:f});this.logger.info(`[${v}][handleRosterUpdate] participant missing from delta, full roster`),this.handleRemovedDeltaRosterParticipant(C,g.sequenceNumber,S,v)}this.lastFullRosterSeqNumber=g.sequenceNumber}else if(!g?.participants)return void this.logger.warn(`[${v}][handleRosterUpdate] participants blob empty in delta roster`);for(const f of Object.keys(g.participants)){const C=g.participants[f];if(!this.isParticipantRosterStale(f,C.version)){let g=cn.fromRoster(C);C.state&&"active"===C.state?(this.logger.info(`[${v}][handleDeltaRoster] participant active`),this.handleRosterParticipant(g,S,v),this.tombstoneSequence.has(f)&&this.tombstoneSequence.delete(f),this.latestRosterVersionForActiveParticipants.set(f,C.version)):C.state&&"inactive"===C.state?(g=g||new cn({id:C.details.id}),this.logger.info(`[${v}][handleDeltaRoster] participant inactive`),this.handleRemovedDeltaRosterParticipant(g,C.version,S,v)):this.logger.info(`[${v}][handleDeltaRoster] unexpected participant state ${C.state}`)}}this.handleRemoveParticipantRequests(this.getActiveParticipants(g.participants),v)}getRnlMri(g,f){const S=this.participantManager.participantOperationHandler;if(g){const v=this.getRnlParticipantIdsFromRoster(g,f);return S.getRnlMri(v,f)}return""}handleRemovedDeltaRosterParticipant(g,f,S,v){const C=g.id,_=this.getRnlMri(g,v);let T="";S.hasOwnProperty(C)?T=C:S.hasOwnProperty(_)&&(T=_),T&&this.handleRemovedParticipant(S,T,v),this.tombstoneSequence.set(C,f),this.latestRosterVersionForActiveParticipants.has(C)&&this.latestRosterVersionForActiveParticipants.delete(C)}handleRemovedParticipant(g,f,S){const v=this.participantManager.signalingSessionCallback,C=this.participantManager.signalingSession;!1!==g[f]&&(tryRemoveKeyFromHashTable(this.participantManager.connectedRemoteParticipantIds,f),this.logger.info(`[${S}][handleRemovedParticipant] ${scrubMriOrOmit(f)} removed from roster`),v.onParticipantRemoved({id:f},S),C.clearParticipantCallLinks(f))}getActiveParticipants(g){const f={};for(const S of Object.keys(g))"inactive"!==g[S].state&&(f[S]=g[S]);return f}handleRosterParticipant(g,f,S){if(!g)return void this.logger.info(`[handleRosterParticipant][${S}] rosterParticipant processing skipped because null.`);if(g.id===this.participantManager.localParticipant.id){this.updateLocalParticipant(g,S);const f=this.getLocalEndpoint(),v=!(!f?.stream&&!f?.streamLobby),C=0===this.participantManager.signalingSession.callMode;return this.logger.info(`[handleRosterParticipant][${S}] isStreaming:${v} isInitialMode:${C}`),void(v&&C?this.participantManager.signalingSession.configureStreamingMode(S):v||this.participantManager.signalingSession.setRealTimeState(1,S))}const v=this.participantManager.participantOperationHandler,C=this.participantManager.signalingSession,_=this.participantManager.signalingSessionCallback,T=g.id,I=this.getRnlMri(g,S),b=this.getRnlParticipantIdsFromRoster(g,S);C.remoteCaller&&-1!==b.indexOf(C.remoteCaller.participantId)&&(g.displayName=C.remoteCaller.displayName),tryAddNewKeyToHashTable(this.participantManager.connectedRemoteParticipantIds,g.id,!0);const A=f.hasOwnProperty(g.id),P=f.hasOwnProperty(I);(A||P)&&(f[g.id]=!1),v.hasPendingOperation(0,g.id,S)&&this.isParticipantInCall(g)?(this.logger.info(`participant ${scrubMriOrOmit(g.id)} appears in roster. Resolving AddParticipant request`),C.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,g.id),v.resolvePendingOperation(0,g.id,g,S)):I&&v.hasPendingOperation(0,I,S)&&this.isParticipantInCall(g)?(this.logger.info(`RNL participant ${scrubMriOrOmit(I)} appears in roster. Resolving AddParticipant request`),C.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,I),v.resolvePendingOperation(0,I,g,S)):v.hasPendingOperation(1,g.id,S)&&this.isParticipantInCall(g)&&(this.logger.info(`participant: ${scrubMriOrOmit(g.id)} appears in roster. Resolving AdmitParticipant request`),C.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,g.id),v.resolvePendingOperation(1,g.id,g,S));for(const f of g.endpointDetails)v.hasPendingOperation(0,f.participantId,S)&&this.isParticipantInCall(g)&&(this.logger.info(`participant ${scrubMriOrOmit(g.id)} appears in roster. Resolving AddParticipant request`),C.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,f.participantId),v.resolvePendingOperation(0,f.participantId,g,S));A?(this.logger.info(`participantIds=[${b}] updated ${scrubMriOrOmit(g.id)}`),_.onParticipantUpdated(g,S),C.setParticipantCallLinks(g)):P?(this.logger.info(`RNL participant participantIds=[${b}] removed old ${scrubMriOrOmit(I)} and added new ${scrubMriOrOmit(T)}`),_.onParticipantRemoved({id:I},S,!0),C.clearParticipantCallLinks(I),_.onParticipantJoined(g,S),C.setParticipantCallLinks(g)):v.hasPendingOperation(3,g.id,S)?this.logger.info(`participantIds=[${b}] ignored ${scrubMriOrOmit(g.id)}`):(this.logger.info(`participantIds=[${b}] joined ${scrubMriOrOmit(g.id)}`),_.onParticipantJoined(g,S),C.setParticipantCallLinks(g))}getLocalEndpoint(){return qn.find(this.participantManager.localParticipant.endpointDetails,(g=>this.participantManager.localParticipant.endpointId===g.endpointId))}getRnlParticipantIdsFromRoster(g,f){const S=[];for(const f of g.endpointDetails)S.push(f.participantId);return this.logger.info(`[${f}][getRnlParticipantIdsFromRoster] ${JSON.stringify(S)}`),S}isParticipantInCall(g){return g.endpointDetails?.[0]&&!g.endpointDetails[0].isLobby}updateLocalParticipant(g,f){const S=this.participantManager.localParticipant,v=this.participantManager.signalingSession,C=this.participantManager.signalingSessionCallback;v.setParticipantCallLinks(g),this.logger.info(`[${f}][updateLocalParticipant]`);let _=!1;if(g?.endpointDetails){const T=qn.find(g.endpointDetails,(g=>S.endpointId===g.endpointId)),I=qn.find(S.endpointDetails,(g=>S.endpointId===g.endpointId));_=hasStagingGroup(T),T?.isLobby&&!I?.isLobby?v.telemetryHelper.recordEvent(dn.IN_LOBBY,{causeId:f}):!T||T.isLobby||I&&!I.isLobby||(_?v.telemetryHelper.recordEvent(dn.STAGING,{causeId:f}):v.telemetryHelper.recordEvent(dn.CONNECTED,{causeId:f})),T?.broadcastMeetingRole&&S&&S.broadcastMeetingRole!==T.broadcastMeetingRole&&(S.broadcastMeetingRole=T.broadcastMeetingRole,v.telemetryHelper.setBroadcastMeetingRole(T.broadcastMeetingRole)),C.onMeetingGroupDetailsUpdated(T?.meetingGroupDetails,f)}if(g?.meetingRole&&v.telemetryHelper.setMeetingRole(g.meetingRole),g?.advancedMeetingRole&&v.telemetryHelper.setAdvancedMeetingRole(g.advancedMeetingRole),g?.meetingRoles&&v.telemetryHelper.setMeetingRoles(g.meetingRoles),g?.participantType&&v.telemetryHelper.setParticipantType(g.participantType),g&&(S.endpointDetails=g.endpointDetails||[],S.acceptedBy=g.acceptedBy,S.role=g.role,S.meetingRole=g.meetingRole,S.advancedMeetingRole=g.advancedMeetingRole,S.meetingRoles=g.meetingRoles,S.participantType=g.participantType,S.tenantId=g.tenantId,S.isLobby=g.isLobby,S.publishedStates=g.publishedStates,S.isStaging=_,S.version=g.version,S.propertyBag=g.propertyBag,S.isIdentityMasked=g.isIdentityMasked,S.maskedIdSeqNumber=g.maskedIdSeqNumber,S.maskedId=g.maskedId,void 0!==g?.joinAsStreamingUser&&(S.joinAsStreamingUser=g.joinAsStreamingUser),void 0!==g?.enableCaptcha&&(S.enableCaptcha=g.enableCaptcha),void 0!==g?.otpIdentity&&(S.otpIdentity=g.otpIdentity),this.participantManager.localParticipant.fromRoster=!0,C.onSelfParticipantUpdated(S,f)),this.isParticipantInCall(g)){const S=this.participantManager.participantOperationHandler,C=this.getRnlMri(g,f);C&&S.hasPendingOperation(0,C,f)&&(this.logger.info(`RNL participant ${scrubMriOrOmit(C)} appears in roster. Resolving AddParticipant request`),v.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,C),S.resolvePendingOperation(0,C,g,f))}}checkForRemovedParticipants(g,f,S){const v=this.participantManager.signalingSessionCallback,C=this.participantManager.signalingSession,_=this.participantManager.participantOperationHandler;this.logger.info(`[${S}][checkForRemovedParticipants]`);for(const f of Object.keys(g))g.hasOwnProperty(f)&&!1!==g[f]&&!_.hasPendingOperation(0,f,S)&&(tryRemoveKeyFromHashTable(this.participantManager.connectedRemoteParticipantIds,f),this.logger.info(`[${S}][checkForRemovedParticipants] ${scrubMriOrOmit(f)} removed from roster`),v.onParticipantRemoved({id:f},S),C.clearParticipantCallLinks(f));this.handleRemoveParticipantRequests(f,S)}handleRemoveParticipantRequests(g,f){const S=this.participantManager.signalingSession,v=this.participantManager.participantOperationHandler;this.logger.info(`handleRemoveParticipantRequests [${f}] dynamicRosterParticipants`);const C=[];Object.keys(g).forEach((f=>{const S=cn.fromRoster(g[f]);S&&S.endpointDetails&&S.endpointDetails.forEach((g=>{g.originalId&&C.push(g.originalId)}))}));const _=v.getAllPendingOperations(3,f);for(const T of Object.keys(_))-1!==C.indexOf(T)||g.hasOwnProperty(T)||(this.logger.info(`[${f}][handleRemoveParticipantRequests] ${scrubMriOrOmit(T)} no longer appears in roster. Resolving RemoveParticipant request`),tryRemoveKeyFromHashTable(this.participantManager.connectedRemoteParticipantIds,T),S.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,T),v.resolvePendingOperation(3,T,{id:T},f))}},zn=class{constructor(g,f,S,v){this.connectedRemoteParticipantIds={},this.disposed=!1,this.unmuteApprovalLinks={},this._asyncMuteUnmuteDefers=new Map,this.muteAsyncEnabled=!1,this.unmuteAsyncEnabled=!1,this.setLocalParticipantId=(g,f)=>{g&&(this.logger.info(`[${f}][setLocalParticipantId][participantId=${g}]`),this.localParticipant.participantId=g,this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId))},this.setEnableMuteAsync=g=>{this.muteAsyncEnabled=g},this.setEnableUnmuteAsync=g=>{this.unmuteAsyncEnabled=g},this.admitParticipantAsync=(g,f,S)=>{const v=`[${S}][admitParticipantAsync]`;this.logger.info(`${v}${this.piiUtils.scrubMriOrOmit(g.id)}`);const C=defer();return this.participantOperationHandler.hasPendingOperation(1,g.id,S)?(this.logger.info(`${v}there is an existing pending request to admit the participant ${this.piiUtils.scrubMriOrOmit(g.id)}`),C.reject(new Error("there is an existing pending request to admit the participant"))):(this.participantOperationHandler.setPendingOperation(1,g.id,{participant:g,promise:C,causeId:S},S),this.sendNetworkRequestForAdmittingParticipant(g,f,S)),C.promise},this.addParticipantsAsync=(g,f,S,v,C)=>{const _=`[${C}][addParticipantsAsync]`,T=g.map((g=>this.piiUtils.scrubMriOrOmit(g.id)));this.logger.info(`${_} remoteParticipantsIds: ${T}`);const I=[],b=[];return g.forEach((g=>{const f=defer(),S=3===v.replacementType?g.participantId:g.id;this.connectedRemoteParticipantIds.hasOwnProperty(g.id)?(this.logger.info(`${_}the given participant is already connected to the call ${this.piiUtils.scrubMriOrOmit(g.id)}`),f.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(0,S,C)?(this.logger.info(`${_}there is an existing pending request to add the participant ${this.piiUtils.scrubMriOrOmit(g.id)}`),f.reject(new Error("there is an existing pending request to add the participant"))):(g.participantId||(g.participantId=newGuid2(),this.logger.info(`participantId created ${g.participantId}`)),this.participantOperationHandler.setPendingOperation(0,S,{participant:g,promise:f,causeId:C},C),I.push(g)),b.push(f.promise)})),S&&this.sendNetworkRequestForAddingParticipant(I,f,v,C),b},this.nudgeParticipantsAsync=(g,f,S,v,C,_,T,I)=>(this.logger.info(`[${v}][nudgeParticipantAsync] ${this.piiUtils.scrubParticipantsList(g)}`),S?this.sendNetworkRequestForNudgingParticipants(g,f,v,C,_,T,I):Promise.reject(`[${v}][nudgeParticipantAsync] Call not started`)),this.updateMeetingRolesAsync=(g,f,S,v=causeId2())=>{const C=defer();if(!g||g.length<1){const g=`[${v}][updateMeetingRolesAsync] participantsInfo cannot be empty or null`,f=new Error(g);f.endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),C.reject(f)}else if(f)if(S){let _;"attendee"===f?_=hn.UPDATE_MEETING_ROLE_ATTENDEE.name:"presenter"===f?_=hn.UPDATE_MEETING_ROLE_PRESENTER.name:"organizer"===f?_=hn.UPDATE_MEETING_ROLE_ORGANIZER.name:C.reject(new Error(`[${v}] Invalid meetingRole value(${f})`)),this.logger.info(`[${v}][updateMeetingRolesAsync][meetingRole=${f}]`),this.signalingSession.ensureMessageChannelReady(_).then((()=>{this.sendNetworkRequestForUpdatingMeetingRoles(g,f,S,_,v,C)})).catch((g=>{const f=getPrintableObject(g);this.logger.info(`[${v}][updateMeetingRolesAsync][failed][reason=${f}]`);const S={...getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig).error};C.reject(S)}))}else{const g=`[${v}][updateMeetingRolesAsync] updateMeetingRoleUrl cannot be empty or null`,f=new Error(g);f.endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),C.reject(f)}else{const g=`[${v}][updateMeetingRolesAsync] meetingRole cannot be empty or null`,f=new Error(g);f.endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),C.reject(f)}return C.promise},this.updateParticipantInterpretationStateAsync=(g,f,S)=>{const v=`[${S}][updateParticipantInterpretationStateAsync]`,C=g.map((g=>this.piiUtils.scrubMriOrOmit(g.id)));this.logger.info(`${v} remoteParticipantsIds: ${C}`);const _=[],T=[];return g.forEach((g=>{const f=defer();this.participantOperationHandler.hasPendingOperation(5,g.id,S)?(this.logger.info(`${v}there is an existing pending request to update the participant ${this.piiUtils.scrubMriOrOmit(g.id)}`),f.reject(new Error("there is an existing pending request to update the participant"))):(this.participantOperationHandler.setPendingOperation(5,g.id,{option:g,promise:f,causeId:S},S),_.push(g)),T.push(f.promise)})),this.sendNetworkRequestToUpdateParticipantInterpretationState(_,f,g,S),T},this.callMeBackAsync=(g,f,S)=>{this.logger.info(`[${S}][callMeBackAsync] ${this.piiUtils.scrubMriOrOmit(g.id)}`);const v=defer();return this.connectedRemoteParticipantIds.hasOwnProperty(g.id)?(this.logger.info(`the given participant is already connected to the call : ${this.piiUtils.scrubMriOrOmit(g.id)}`),v.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(2,g.id,S)?(this.logger.info(`there is an existing pending request to call back the participant : ${this.piiUtils.scrubMriOrOmit(g.id)}`),v.reject(new Error("there is an existing pending request to call back the participant"))):(this.participantOperationHandler.setPendingOperation(2,g.id,{participant:g,promise:v},S),this.sendNetworkRequestForCallMeBack(g,f,S)),v.promise},this.isRosterStale=(g,f)=>this.rosterManager.isRosterStale(g,f),this.removeParticipantAsync=(g,f,S)=>{this.logger.info(`[${S}][removeParticipantAsync] ${this.piiUtils.scrubMriOrOmit(g.id)}`),assertNotNullOrEmpty(f,"correct removeParticipantUrl is not provided");const v=defer();if(this.participantOperationHandler.hasPendingOperation(3,g.id,S))this.logger.info(`there is an existing pending request to remove the participant ${this.piiUtils.scrubMriOrOmit(g.id)}`),v.reject(new Error("there is an existing pending request to remove the participant"));else{this.participantOperationHandler.setPendingOperation(3,g.id,{participant:g,promise:v},S);const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g.id),this.participantOperationHandler.rejectPendingOperation(3,g.id,"timed out waiting for participant to not show up in roster",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:an.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},S)}),an.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,g.id)};this.signalingSession.http.sendPostRequest({url:f,payload:getPayload20(this.signalingSession,g),requestName:hn.REMOVE_PARTICIPANT_NONE.name,onceTrouterReady:onceTrouterReady,causeId:S}).catch((f=>{const v=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][removeParticipantAsync][failed][reason=${getPrintableObject(v)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g.id),this.participantOperationHandler.rejectPendingOperation(3,g.id,f,v.error,S))}))}return v.promise},this.removeParticipantEndpointAsync=(g,f,S,v)=>{this.logger.info(`[${v}][removeParticipantEndpointAsync] ${truncate(g.endpointId,8)} [endPointScope] ${S}`),assertNotNullOrEmpty(f,"correct removeParticipantUrl is not provided");const C=defer();let _="";switch(S){case"all":_=hn.REMOVE_PARTICIPANT_OTHERS.name;break;case"specified":_=hn.REMOVE_PARTICIPANT_SPECIFIED.name;break;default:return Promise.reject(`invalid scope ${S} removeParticipantEndpointAsync`)}this.participantOperationHandler.setPendingOperation(4,g.endpointId,{participant:g,promise:C,scope:S},v);const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g.endpointId),this.participantOperationHandler.rejectPendingOperation(4,g.endpointId,"timed out waiting for participant endpoint sync response from service",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:an.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},v))}),an.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,g.endpointId)};return this.signalingSession.http.sendPostRequest({url:f,payload:getPayload19(this.signalingSession,g,S),requestName:_,onceTrouterReady:onceTrouterReady,causeId:v}).then((g=>{if(g.response?.code)if(-1!==[an.HTTP_STATUS_CODES.OK,an.HTTP_STATUS_CODES.CREATED].indexOf(g.response.code))this.logger.info(`[${v}][removeParticipantEndpointAsync][endPointScope] ${S} [passed][reason=${getPrintableObject(g.response)}]`),C.resolve(g.response);else{const f=new Error("invalid service response for removeParticipantEndpoint");f.endCode={code:g.response.code,subCode:g.response.subcode,phrase:g.response.reason},this.logger.info(`[${v}][removeParticipantEndpointAsync][endPointScope] ${S} [failed][reason=${getPrintableObject(g.response)}]`),C.reject(f)}C.resolve()})).catch((f=>{const C=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${v}][removeParticipantEndpointAsync][endPointScope] ${S} [failed][reason=${getPrintableObject(C)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g.endpointId),this.participantOperationHandler.rejectPendingOperation(4,g.endpointId,getPrintableObject(f),C.error,v))})),C.promise},this.getParticipantsToInitiateCallWith=()=>{this.logger.info("getParticipantsToInitiateCallWith");const g=[],f=this.participantOperationHandler.getAllPendingOperations(0,causeId2());for(const S of Object.keys(f))f.hasOwnProperty(S)&&f[S]&&g.push(f[S].participant);return g},this.initializeForIncomingCall=g=>{this.logger.info("initializeForIncomingCall"),this.participantOperationHandler.dispose("incoming calls cannot add/remove participants until call is connected",null,causeId2())},this.handleAddParticipantSuccess=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAddParticipantSuccess(${f.participantInfos?"new format":"old format"})]${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_PARTICIPANT_SUCCESS,g),this.internalHandleCallMeBackSuccess(f,S)||this.signalingSession.telemetryHelper.recordEvent(dn.HANDLE_ADD_PARTICIPANT_SUCCESS),this.signalingSession.signalingAgentConfig.enableAddParticipantEnhancements&&this.internalHandleAcceptedByParticipants(f,S)},this.handleAddParticipantFailure=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAddParticipantFailure(${f.participantInfos?"new format":"old format"})][${getPrintableObject(f)}]`),f.modalityFailure?(this.logger.info(`[${S}][handleAddParticipantFailure][modalityFailure=${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_PARTICIPANT_MODALITY_FAILURE,g)):this.internalHandleAddParticipantFailure(g,S)},this.handleAdmitParticipantSuccess=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAdmitParticipantSuccess][${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADMIT_PARTICIPANT_SUCCESS,g),f.participants&&this.internalHandleAdmitParticipantSuccess(g,S)},this.handleAdmitParticipantFailure=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAdmitParticipantFailure][${getPrintableObject(f)}]`),f.participants&&this.internalHandleAdmitParticipantFailure(g,S)},this.handleRemoveParticipantFailure=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleRemoveParticipantFailure][${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_REMOVE_PARTICIPANT_FAILURE,g);for(const g of Object.keys(f.participants))f.participants.hasOwnProperty(g)&&this.internalHandleRemoveParticipantFailure(g,f.participants[g],S)},this.handleRemoveParticipantSuccess=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleRemoveParticipantSuccess][${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_REMOVE_PARTICIPANT_SUCCESS,g)},this.handleUnmuteConfirmRequest=g=>{const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleUnmuteConfirmRequest][${getPrintableObject(f)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_UNMUTE_CONFIRM,g),this.unmuteApprovalLinks[f.from.id]={approve:f.links.approveUnmute,reject:f.links.rejectUnmute},this.signalingSessionCallback.onUnmuteRequested(f.from.id,S)},this.approveUnmuteRequestAsync=(g,f)=>{this.logger.info(`[${f}][approveUnmuteRequestAsync]`);const S=defer();return this.unmuteApprovalLinks.hasOwnProperty(g)?(this.signalingSession.ensureMessageChannelReady(hn.APPROVE_UNMUTE.name).then((()=>{this.muteUnmute(hn.APPROVE_UNMUTE.name,getPayload14(this.signalingSession),S,this.unmuteApprovalLinks[g].approve,f)})).catch((g=>{const v=getPrintableObject(g);this.logger.info(`[${f}][approveUnmuteRequestAsync][failed][reason=${v}]`),S.reject(new Error(g))})),S.promise):(S.reject(new Error("no unmute links found for given participant")),S.promise)},this.rejectUnmuteRequestAsync=(g,f,S)=>{this.logger.info(`[${f}][rejectUnmuteRequestAsync]`);const v=defer();if(!this.unmuteApprovalLinks.hasOwnProperty(g))return v.reject(new Error("no unmute links found for given participant")),v.promise;const C=S||{code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UNMUTE_REQUEST_REJECTED,phrase:an.CALL_END_PHRASE.UNMUTE_REQUEST_REJECTED};return this.signalingSession.ensureMessageChannelReady(hn.REJECT_UNMUTE.name).then((()=>{this.muteUnmute(hn.REJECT_UNMUTE.name,getPayload18(this.signalingSession,C),v,this.unmuteApprovalLinks[g].reject,f)})).catch((g=>{const S=getPrintableObject(g);this.logger.info(`[${f}][rejectUnmuteRequestAsync][failed][reason=${S}]`),v.reject(new Error(g))})),v.promise},this.handleRosterUpdate=(g,f,S)=>{const v=this.getCurrentParticipantsInCallModality(!1);this.rosterManager.handleRosterUpdate(g,v,f,S)},this.updateLocalParticipantFromSubscribe=(g,f)=>{this.localParticipant.fromRoster||this.rosterManager.updateLocalParticipantFromSubscribe(g,f)},this.muteAsync=(g,f,S,v)=>{this.logger.info(`[${v}][muteAsync][muteScope=${f}]`);let C="specified";const _=[];let T=hn.MUTE_SPECIFIED;switch(f){case an.MUTE_SCOPE.MYSELF:T=hn.MUTE_MYSELF,_.push({id:this.localParticipant.id});break;case an.MUTE_SCOPE.EVERYONE_ELSE:T=hn.MUTE_ALL_SYNC,C="all",S.forEach((g=>{_.push({id:g})}));break;case an.MUTE_SCOPE.SPECIFIED_PARTICIPANTS:assertNotNullOrEmpty(S,`[${v}]array of participantIds must be specified for SPECIFIED_PARTICIPANTS mute scope`),T=hn.MUTE_SPECIFIED_SYNC,S.forEach((g=>{_.push({id:g})}));break;default:assert2(!1,`[${v}]muteScope is a required param. please pass in a valid value.`)}const I=defer();if(f===an.MUTE_SCOPE.SPECIFIED_PARTICIPANTS){const g=this.areParticipantsConnectedToCall(S);if(!g.result)return I.reject(new Error(`[${v}]specified participant is not connected to call yet. Id = ${g.participant}`)),I.promise}const b=this.muteAsyncEnabled&&(f===an.MUTE_SCOPE.SPECIFIED_PARTICIPANTS||f===an.MUTE_SCOPE.EVERYONE_ELSE);return this.signalingSession.ensureMessageChannelReady(T.name).then((()=>{this.muteUnmute(T.name,getPayload15(this.signalingSession,C,_,b,v),I,g,v,!1,b)})).catch((g=>{const f=getPrintableObject(g),S=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);this.logger.info(`[${v}][muteAsync][failed][reason=${f}]`),I.reject(S)})),I.promise},this.unmuteAsync=(g,f)=>{this.logger.info(`[${f}][unmuteAsync]`);const S=defer();return this.signalingSession.ensureMessageChannelReady(hn.UNMUTE_SYNC.name).then((()=>{this.muteUnmute(hn.UNMUTE_SYNC.name,getPayload21(this.signalingSession,this.unmuteAsyncEnabled,f),S,g,f,!0,this.unmuteAsyncEnabled)})).catch((g=>{const v=getPrintableObject(g);this.logger.info(`[${f}][unmuteAsync][failed][reason=${v}]`),S.reject(new Error(g))})),S.promise},this.dispose=(g,f)=>{this.logger.info(`[${f}][dispose]`),this.disposed=!0,this.participantOperationHandler.dispose("call ended",g,f),this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId),this._asyncMuteUnmuteDefers.forEach(((f,S)=>{f.reject(g)})),this._asyncMuteUnmuteDefers.clear()},this.handleMuteUnmuteAsyncResponse=g=>{const f=extractCauseIdFromMessage(g),S=this.logger.createFnLogger("handleMuteUnmuteAsyncResponse",f);if(!g.body)return void S.error("ignored. Empty message body.");const v={info:g.body.muteUnmuteResponseAsync,operationId:g.body.operationId};if(S.info(`Received async response for mute/unmute operation, operation id = ${v.operationId}.`),this.disposed)return void S.info("ignored. Call disposed.");if(!v.operationId)return void S.error("operationId is undefined.");const C=this._asyncMuteUnmuteDefers.get(v.operationId);C?(C.resolve(v),this._asyncMuteUnmuteDefers.delete(v.operationId)):S.warn(`cannot find deferred promise for operation id [${v.operationId}].`)},this.internalHandleAcceptedByParticipants=(g,f)=>{if(g?.participantInfos){const S=g.participantInfos,v=this.getCurrentParticipantsInCallModality(!1);this.logger.info(`[${f}][internalHandleAcceptedByParticipants] handling participants with acceptedBy blob.`);for(const g of S)if(g?.acceptedBy){const S=g.id;this.participantOperationHandler.hasPendingOperation(0,S,f)&&(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,S),this.logger.info(`[${f}][internalHandleAcceptedByParticipants] ${this.piiUtils.scrubMriOrOmit(S)} added using a different MRI. Resolving operation.`),this.participantOperationHandler.resolvePendingOperation(0,S,void 0,f)),this.rosterManager.handleParticipantAcceptedBy(g,v,f)}}},this.internalHandleCallMeBackSuccess=(g,f)=>{let S=!1;if(g?.participantInfos){const v=g.participantInfos;for(const g of v){const v=g.id;this.internalHandleCallMeBackSuccessHelper(v,f)&&(S=!0)}}else if(g?.participants)for(const v of g.participants)this.internalHandleCallMeBackSuccessHelper(v,f)&&(S=!0);return S},this.signalingSession=g,this.signalingSessionCallback=f,this.localParticipant=S,this.localParticipant.endpointId||(this.localParticipant.endpointId=this.signalingSession.getEndpointId());const C=truncate(this.localParticipant.endpointId,8);this.logger=v.createChild((()=>`[PM][${C}]`)),this.piiUtils=g.piiUtils,this.participantOperationHandler=new Gn(g.logger.createChild((()=>`[ParticipantOperationHandler][${C}]`))),this.rosterManager=new Wn(this,g.logger.createChild((()=>`[RosterManager][${C}]`))),this.localParticipant.participantId||(this.localParticipant.participantId=newGuid2()),"string"==typeof g.signalingAgentConfig.languageCode?this.localParticipant.languageId=g.signalingAgentConfig.languageCode:"function"==typeof g.signalingAgentConfig.languageCode&&(this.localParticipant.languageId=g.signalingAgentConfig.languageCode()),g.telemetryHelper.setParticipantId(this.localParticipant.participantId),g.telemetryHelper.setEndPointId(this.localParticipant.endpointId)}handleUpdateParticipantInterpretationStateCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.operationId;if(this.disposed)return void this.logger.info(`[${S}][handleUpdateParticipantInterpretationStateCompletion] ignored. Call disposed.`);v||this.logger.warn(`[${S}][handleUpdateParticipantInterpretationStateCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleUpdateParticipantInterpretationStateCompletion] starts`);const C=g.body;if(C.participantInfos)for(const f of C.participantInfos)if(this.logger.info(f),this.participantOperationHandler.hasPendingOperation(5,f.participant.id,S))if(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,f.participant.id),f.transactionEnd.code===an.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${S}]Update participant interpretation state succeeded for: ${this.piiUtils.scrubMriOrOmit(f.participant.id)}`),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_RESPONSE_COMPLETED,g),this.participantOperationHandler.resolvePendingOperation(5,f.participant.id,void 0,S);else{const v=f.transactionEnd.reason;this.logger.info(`[${S}]Update participant interpretation state failed for: ${this.piiUtils.scrubMriOrOmit(f.participant.id)} reason : ${getPrintableObject(v)}`);const C=this.getCallEndGivenParticipantFailure(v);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_RESPONSE_FAILED,g,C),this.participantOperationHandler.rejectPendingOperation(5,f.participant.id,C.phrase,C,S)}}setEnableCaptcha(g,f){this.logger.info(`[${f}][setEnableCaptcha] value:${g}`),this.localParticipant.enableCaptcha=g,this.signalingSessionCallback.onSelfParticipantUpdated(this.localParticipant,f)}areParticipantsConnectedToCall(g){this.logger.info(`areParticipantsConnectedToCall : ${getPrintableObject(g)}`);const f=this.getCurrentParticipantsInCallModality(!0);for(const S of g)if(!f.hasOwnProperty(S))return this.logger.info(`areParticipantsConnectedToCall : returning false for :${this.piiUtils.scrubMriOrOmit(S)}`),{result:!1,participant:S};return this.logger.info("areParticipantsConnectedToCall : returning true"),{result:!0}}muteUnmute(g,f,S,v,C,_,T=!1){const I=this.logger.createFnLogger("muteUnmute",C);assert2(2!==this.signalingSession.callMode,"mute/unmute operations are not allowed in streaming mode"),I.info(`operation=${g}, isAsync=${T}`),v?(_&&this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UNMUTE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent(dn.UNMUTE_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UNMUTE);const g=new Error("timed out waiting for response to request");g.endCode={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UNMUTE_REQUEST_TIMEOUT,phrase:an.CALL_END_PHRASE.UNMUTE_REQUEST_TIMEOUT},S.reject(g)}}),an.TIMEOUT_VALUES_IN_SECONDS.UNMUTE_TIMEOUT),T&&this._asyncMuteUnmuteDefers.set(C,S),this.signalingSession.http.sendPostRequest({url:v,payload:f,requestName:g,withoutTrouter:!0,causeId:C}).then((f=>{if(!this.disposed)if(T)I.info(`Inline response received for async operation, operation id: ${C}.`);else{if(f.response?.muteUnmuteResponse){const v={info:f.response.muteUnmuteResponse,operationId:f.response.operationId};switch(g){case hn.UNMUTE_SYNC.name:case hn.MUTE_ALL_SYNC.name:case hn.MUTE_SPECIFIED_SYNC.name:S.resolve(v)}}S.resolve()}})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);I.info(`operation failed, reason=${getPrintableObject(f)}`),this.disposed||(_&&this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UNMUTE),S.reject(f.error))}))):S.reject(new Error(`[${C}][muteUnmute] cannot be performed now, the link is not yet available`))}sendNetworkRequestForUpdatingMeetingRoles(g,f,S,v,C,_){if(!S){const g=`[${C}][sendNetworkRequestForUpdatingMeetingRoles] failed because correct updateMeetingRoleUrl is not provided`;new Error(g).endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),_.reject()}if(!g){const g=`[${C}][sendNetworkRequestForUpdatingMeetingRoles] failed because participants list is empty or null`,f=new Error(g);f.endCode={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:g},this.logger.info(g),_.reject(f)}const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent(dn.UPDATE_MEETING_ROLE,{causeId:C}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE);const g=new Error(`[${C}] Timed out waiting for response to request`);g.endCode={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MEETING_ROLE_TIMEOUT},_.reject(g)}}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_ROLE_TIMEOUT)};this.signalingSession.http.sendPostRequest({url:S,payload:getPayload22(this.signalingSession,g,"specified",f),requestName:v,onceTrouterReady:onceTrouterReady,causeId:C}).then((g=>{_.resolve(g.response)})).catch((g=>{const f=getPrintableObject(g);this.logger.info(`[${C}][sendNetworkRequestForUpdatingMeetingRoles] failed: ${f}`);const S=new Error(`[${C}][CS response] Forbidden request`),v=getErrorForXHRFailure(g,this.signalingSession.signalingAgentConfig);S.code=v.error.code,S.subCode=v.error.subCode,S.phrase=v.error.phrase,this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE),_.reject(S))}))}sendNetworkRequestForNudgingParticipants(g,f,S,v,C,_,T){if(f){const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(dn.NUDGE_PARTICIPANT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,g?g.join():""))}),an.TIMEOUT_VALUES_IN_SECONDS.NUDGE_PARTICIPANT_TIMEOUT,g?g.join():"")},I=_||C?getPayload16(this.signalingSession,g,C,_,T,v):getPayload17(this.signalingSession,g,v);return this.signalingSession.http.sendPostRequest({url:f,payload:I,requestName:hn.NUDGE_PARTICIPANT.name,onceTrouterReady:onceTrouterReady,causeId:S}).then((()=>{})).catch((f=>{const v=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${S}][sendNetworkRequestForNudgingParticipant][failed][reason=${getPrintableObject(v)}]`),this.disposed||this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,g?g.join():""),Promise.reject(v.error)}))}return this.logger.info(`[${S}][sendNetworkRequestForNudgingParticipant] failed because correct nudgeParticipantUrl is not provided`),Promise.reject("Missing nudgeParticipant url")}sendNetworkRequestForAddingParticipant(g,f,S,v=causeId2()){if(f){let C=hn.ADD_PARTICIPANT.name,_=dn.ADD_PARTICIPANT_TIMEOUT,T={};switch(S.replacementType){case 2:C=hn.ADD_PARTICIPANT_WITH_PICKUP_CODE.name,_=dn.ADD_PARTICIPANT_WITH_PICKUP_CODE_TIMEOUT,T.unparkContent={pickupCode:S.pickupCode};break;case 1:C=hn.ADD_PARTICIPANT_WITH_REPLACES.name,_=dn.ADD_PARTICIPANT_WITH_REPLACES_TIMEOUT,T=this.signalingSession.getCallReplacementDetailsForCall(S.callIdToReplace,v);break;case 3:C=hn.ADD_PARTICIPANT_WITH_REPLACES.name,_=dn.ADD_PARTICIPANT_WITH_REPLACES_TIMEOUT,T=this.signalingSession.getReplacementDetailsByParticipantLegOfCall(S.callIdToReplace,g[0].id,g[0].replacementParticipantId,v);break;default:C=hn.ADD_PARTICIPANT.name,_=dn.ADD_PARTICIPANT_TIMEOUT,T=null}const onceTrouterReady=()=>{g.forEach((g=>{const f=3===S.replacementType?g.participantId:g.id;this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(_,{causeId:v}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,f),this.participantOperationHandler.rejectPendingOperation(0,f,"timed out waiting for participant to show up in roster",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},v))}),an.TIMEOUT_VALUES_IN_SECONDS.ADD_PARTICIPANT_TIMEOUT,f)}))},I=S.threadId||S.groupId?getPayload11(this.signalingSession,g,S,T):getPayload12(this.signalingSession,g,S,T);this.signalingSession.http.sendPostRequest({url:f,payload:I,requestName:C,onceTrouterReady:onceTrouterReady,causeId:v}).catch((f=>{const C=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${v}][sendNetworkRequestForAddingParticipant] failed:${getPrintableObject(f)}`),this.disposed||g.forEach((g=>{const _=3===S.replacementType?g.participantId:g.id;this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,_),this.participantOperationHandler.rejectPendingOperation(0,_,f,C.error,v)}))}))}else this.logger.info(`[${v}][sendNetworkRequestForAddingParticipants] failed because correct addParticipantUrl is not provided`),g.forEach((g=>{const f=3===S.replacementType?g.participantId:g.id;this.participantOperationHandler.rejectPendingOperation(0,f,"correct addParticipantUrl is not provided",{code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:an.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},v)}))}sendNetworkRequestToUpdateParticipantInterpretationState(g,f,S,v=causeId2()){if(f){const C=hn.UPDATE_PARTICIPANT_INTERPRETATION_STATE.name,_=dn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT,onceTrouterReady=()=>{const f={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT};g.forEach((g=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.logger.info(`[${v}][sendNetworkRequestToUpdateParticipantInterpretationState] timed out`),this.signalingSession.telemetryHelper.recordEvent(_,{causeId:v}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,g.id),this.participantOperationHandler.rejectPendingOperation(5,g.id,"timed out waiting to update particiant interpretation state",f,v))}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION_TIMEOUT,g.id)}))},T=getUpdateParticipantInterpretationStatePayload(this.signalingSession,S,v);this.signalingSession.http.sendPostRequest({url:f,payload:T,requestName:C,onceTrouterReady:onceTrouterReady,causeId:v}).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${v}][sendNetworkRequestToUpdateParticipantInterpretationState] failed:${getPrintableObject(f)}`),this.disposed||g.forEach((g=>{this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,g.id),this.participantOperationHandler.rejectPendingOperation(5,g.id,f,S.error,v)}))}))}else{this.logger.info(`[${v}][sendNetworkRequestToUpdateParticipantInterpretationState] failed because correct updateParticipantUrl is not provided`);const f={code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:an.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_URL_MISSING};g.forEach((g=>{this.participantOperationHandler.rejectPendingOperation(5,g.id,"correct updateParticipantUrl is not provided",f,v)}))}}sendNetworkRequestForCallMeBack(g,f,S){if(f){const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(dn.CALL_ME_BACK_TIMEOUT,{causeId:S}),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,g.id),this.participantOperationHandler.rejectPendingOperation(2,g.id,"timed out waiting for call me back success response",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},S))}),an.TIMEOUT_VALUES_IN_SECONDS.CALL_ME_BACK_TIMEOUT,g.id)},v={groupId:this.signalingSession.groupId,threadId:this.signalingSession.threadId,messageId:this.signalingSession.teamsMessageId};this.signalingSession.http.sendPostRequest({url:f,payload:getPayload11(this.signalingSession,[g],v),requestName:hn.CALL_ME_BACK.name,onceTrouterReady:onceTrouterReady,causeId:S}).catch((f=>{const v=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][sendNetworkRequestForCallMeBack] failed: ${getPrintableObject(v)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,g.id),this.participantOperationHandler.rejectPendingOperation(2,g.id,f,v.error,S))}))}else this.logger.info(`[${S}][sendNetworkRequestForCallMeBack] failed because correct addParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(2,g.id,"correct addParticipantUrl is not provided",{code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:an.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},S)}sendNetworkRequestForAdmittingParticipant(g,f,S){if(f){const onceTrouterReady=()=>{this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(dn.ADMIT_PARTICIPANT_TIMEOUT),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,g.id),this.participantOperationHandler.rejectPendingOperation(1,g.id,"timed out waiting for participant to show up in roster",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},S))}),an.TIMEOUT_VALUES_IN_SECONDS.ADMIT_PARTICIPANT_TIMEOUT,g.id)};this.signalingSession.http.sendPostRequest({url:f,payload:getPayload13(this.signalingSession,g,S),requestName:hn.ADMIT_PARTICIPANT.name,onceTrouterReady:onceTrouterReady,causeId:S}).catch((f=>{const v=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);this.logger.info(`[${S}][sendNetworkRequestForAdmittingParticipant][failed][reason=${getPrintableObject(v)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,g.id),this.participantOperationHandler.rejectPendingOperation(1,g.id,f,v.error,S))}))}else this.logger.info(`[${S}][sendNetworkRequestForAdmittingParticipant] failed because correct admitParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(1,g.id,"correct admitParticipantUrl is not provided",{code:an.CALL_END_CODE.LOCAL_ERROR,subCode:an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:an.CALL_END_PHRASE.ADMIT_PARTICIPANT_URL_MISSING},S)}getCurrentParticipantsInCallModality(g){const f={},S=[an.PARTICIPANT_AUDIO_STATE.CONNECTED];return g||S.push(an.PARTICIPANT_AUDIO_STATE.CONNECTING,an.PARTICIPANT_AUDIO_STATE.RINGING),this.signalingSessionCallback.getRemoteParticipantCollection()?.forEach((g=>{S.some((f=>f===g.audioState))&&(f[g.mri]=!0)})),f}internalHandleRemoveParticipantFailure(g,f,S){if(this.participantOperationHandler.hasPendingOperation(3,g,S)){this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,g),this.logger.info(`[${S}][internalHandleRemoveParticipantFailure] failed for ${this.piiUtils.scrubMriOrOmit(g)} reason ${getPrintableObject(f)}`);const v=this.getCallEndGivenParticipantFailure(f);this.participantOperationHandler.rejectPendingOperation(3,g,v.phrase,v,S)}}internalHandleCallMeBackSuccessHelper(g,f){if(this.participantOperationHandler.hasPendingOperation(2,g,f)){const S={id:g};return this.logger.info(`participant : ${this.piiUtils.scrubMriOrOmit(g)} was successfully added. Resolving CallMeBack request`),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,g),this.participantOperationHandler.resolvePendingOperation(2,S.id,S,f),!0}return!1}internalHandleAddParticipantFailure(g,f=causeId2()){const S=g.body;if(S.participantInfos)S.participantInfos.forEach((S=>{const v=[S.participant.participantId],C=this.participantOperationHandler.getRnlMri(v,f)||S.participant.id;this.rejectAddParticipantFailure(C,S.transactionEnd,g,f)}));else if(S.participants)for(const v of Object.keys(S.participants))this.rejectAddParticipantFailure(v,S.participants[v],g,f)}rejectAddParticipantFailure(g,f,S,v){const C=this.getCallEndGivenParticipantFailure(f);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_PARTICIPANT_FAILURE,S,C),this.participantOperationHandler.hasPendingOperation(0,g,v)?(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,g),this.logger.info(`participantAdd failed for : ${this.piiUtils.scrubMriOrOmit(g)} reason : ${getPrintableObject(f)}`),this.participantOperationHandler.rejectPendingOperation(0,g,C.phrase,C,v)):this.participantOperationHandler.hasPendingOperation(2,g,v)&&(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.CALL_ME_BACK,g),this.logger.info(`callMeBack failed for : ${this.piiUtils.scrubMriOrOmit(g)} reason : ${getPrintableObject(f)}`),this.participantOperationHandler.rejectPendingOperation(2,g,C.phrase,C,v))}internalHandleAdmitParticipantSuccess(g,f){const S=g.body;for(const g of S.participants)this.participantOperationHandler.hasPendingOperation(1,g,f)&&(this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,g),this.logger.info(`Admit participant success for : ${this.piiUtils.scrubMriOrOmit(g)}`),this.participantOperationHandler.resolvePendingOperation(1,g,void 0,f))}internalHandleAdmitParticipantFailure(g,f){const S=g.body;for(const v of Object.keys(S.participants))if(this.participantOperationHandler.hasPendingOperation(1,v,f)){this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,v);const C=S.participants[v];this.logger.info(`Admit participant failed for : ${this.piiUtils.scrubMriOrOmit(v)} reason : ${getPrintableObject(C)}`);const _=this.getCallEndGivenParticipantFailure(C);this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADMIT_PARTICIPANT_FAILURE,g,_),this.participantOperationHandler.rejectPendingOperation(1,v,_.phrase,_,f)}}getCallEndGivenParticipantFailure(g){let f={code:g.code,subCode:g.subCode,phrase:g.phrase,resultCategories:g.resultCategories};return g.code===an.CALL_END_CODE.CALL_MODALITY_FAILURE&&g.callControllerTransactionEnd?f={...g.callControllerTransactionEnd}:g.code===an.CALL_END_CODE.ATC_CONTROLLER_FAILURE&&g.atcControllerTransactionEnd?f={...g.atcControllerTransactionEnd}:g.code===an.CALL_END_CODE.CVA_CONTROLLER_FAILURE&&g.cvaControllerTransactionEnd&&(f={...g.cvaControllerTransactionEnd}),f}};function getPayload23(g,f){assertNotNull(g,"signalingSession cannot be null"),assertNotNullOrEmpty(f,"sendMessageOptions cannot be null or empty");const S=[];for(const v of f){const f=0===v.scope?"all":"specified",C=[];v.to&&Object.keys(v.to).forEach((g=>{v.to[g].participantLegIdMap?Object.keys(v.to[g].participantLegIdMap).forEach((f=>{C.push({id:g,level:v.to[g].level,endpointId:v.to[g].participantLegIdMap[f].endpointId,participantId:f})})):C.push({id:g,level:v.to[g].level})})),S.push({links:{sendMessageStatus:get2(g,rn.SEND_MESSAGE_STATUS)},operationId:v.operationId,payload:v.payload,scope:f,to:C,type:v.type})}return{payload:{from:{displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,id:g.participantManager.localParticipant.id,languageId:g.participantManager.localParticipant.languageId??"",participantId:g.participantManager.localParticipant.participantId},messageContent:S}}}function mapMriToResolveString(g,f){return`${g}-${f}`}function mapLegIdToResolveString(g,f){return`${g}-${f}`}function mapMriAndPropertyNameToResolveString(g,f,S){return`${g}_${f}_${S}`}var Kn=class{constructor(g){this.signalingSession=g,this.scopeAllOperations=new Map,this.mriOperations=new Map,this.legOperations=new Map,this.logger=g.logger.createChild((()=>"[ProxiedMessageNotificationManager]"))}sendProxiedMessageAsync(g,f,S){this.logger.createChild("sendProxiedMessageAsync",g).info(`Url: ${S}`);const v=[],C=[];for(const S of f)if(0!==S.scope){if(1===S.scope)for(const f in S.to)if("participant"===S.to[f].level){const _=mapMriToResolveString(f,S.operationId),T=defer();this.mriOperations.set(_,T),v.push(T.promise),C.push(_),this.startTimeout(g,"participant",_)}else if("endpoint"===S.to[f].level)for(const _ in S.to[f].participantLegIdMap){const f=mapLegIdToResolveString(_,S.operationId),T=defer();this.legOperations.set(f,T),v.push(T.promise),C.push(f),this.startTimeout(g,"endpoint",f)}}else{const f=defer();this.scopeAllOperations.set(S.operationId,f),v.push(f.promise),C.push(S.operationId),this.startTimeout(g,"all",S.operationId)}return this.sendProxiedMessageNetworkRequest(g,f,S,C),v}sendProxiedMessageNetworkRequest(g,f,S,v){const C=getPayload23(this.signalingSession,f),_=this.logger.createChild("sendProxiedMessageNetworkRequest",g);_.info(`Url: ${S}`),this.signalingSession.http.sendPostRequest({url:S,requestName:hn.SEND_PROXIED_MESSAGE.name,payload:C,causeId:g}).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingSession.signalingAgentConfig);if(_.info(`failed:${getPrintableObject(f)}`),this.signalingSession.disposed)_.info("signaling session is already disposed.");else for(const f of v){this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,f);let v=null;this.scopeAllOperations.has(f)?(v=this.scopeAllOperations.get(f),this.scopeAllOperations.delete(f)):this.mriOperations.has(f)?(v=this.mriOperations.get(f),this.mriOperations.delete(f)):this.legOperations.get(f)?(v=this.legOperations.get(f),this.legOperations.delete(f)):_.warn(`could not find resolveString:${f} to reject it.`),null!==v&&v.reject({transactionEnd:S.error,causeId:g,resolveString:f})}}))}startTimeout(g,f,S){const v=this.logger.createChild("startTimeout",g);v.info(`Creating timeout for level ${f} message with resolveString ${S}`),this.signalingSession.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,(()=>{this.signalingSession.telemetryHelper.recordEvent(dn.SEND_MESSAGE_TIMEOUT,{causeId:g,resolveString:S}),v.info(`timed out waiting for level [${f}] message with resolveString [${S}]`),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,S);const C="all"===f?this.scopeAllOperations:"participant"===f?this.mriOperations:"endpoint"===f?this.legOperations:null;null!==C?C.has(S)?(C.get(S).reject({transactionEnd:{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.CONVERSATION_NOTIFICATION_TIMEOUT,phrase:an.CALL_END_PHRASE.CONVERSATION_NOTIFICATION_TIMEOUT},causeId:g,resolveString:S}),C.delete(S)):v.warn(`Could not find resolveString [${S}] on map for ${f}. Will not reject promise.`):v.warn(`Could not find a operations map for ${f}. Will not reject promise.`)}),an.TIMEOUT_VALUES_IN_SECONDS.SEND_MESSAGE_COMPLETION_TIMEOUT,S)}handleProxiedMessageNotificationItem(g,f,S){if(f.info(`Message contains ${g.participantInfos?.length} participantInfos.`),0===this.scopeAllOperations.size&&0===this.mriOperations.size&&0===this.legOperations.size)return void f.info("Received statusMessage but there is no pending operation.");const v=g.operationId;if(this.scopeAllOperations.has(v)){f.info(`Scope all resolveString:${v}`),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,v);const g={transactionEnd:{code:0,subCode:0,phrase:""},causeId:S,resolveString:v};return this.scopeAllOperations.get(v).resolve(g),this.scopeAllOperations.delete(v),void this.signalingSession.telemetryHelper.recordEvent(dn.SEND_MESSAGE_COMPLETION,{causeId:S,operationId:v,level:"all"})}for(const C of g.participantInfos){const g=0===C.transactionEnd?.code,_=mapMriToResolveString(C.participant.id,v),T=mapLegIdToResolveString(C.participant.participantId,v);if(_&&this.mriOperations.has(_)){f.info(`Scope mri resolveString:${_}`);const T={transactionEnd:C.transactionEnd,causeId:S,resolveString:_};g?this.mriOperations.get(_).resolve(T):this.mriOperations.get(_).reject(T),this.mriOperations.delete(_),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,_),this.signalingSession.telemetryHelper.recordEvent(dn.SEND_MESSAGE_COMPLETION,{causeId:S,operationId:v,level:"mri"})}else if(T&&this.legOperations.has(T)){f.info(`Scope legId resolveString:${T}`);const _={transactionEnd:C.transactionEnd,causeId:S,resolveString:T};g?this.legOperations.get(T).resolve(_):this.legOperations.get(T).reject(_),this.legOperations.delete(T),this.signalingSession.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,T),this.signalingSession.telemetryHelper.recordEvent(dn.SEND_MESSAGE_COMPLETION,{causeId:S,operationId:v,level:"leg"})}else f.warn(`Could not map this participantInfo to any pending operation operationId:${v}`)}}handleProxiedMessageNotification(g){const f=extractCauseIdFromMessage(g),S=this.logger.createChild("handleProxiedMessageNotification",f);let v;v=Array.isArray(g.body?.statuses)?g.body.statuses:[g.body],S.info(`Received ${v.length} proxied message notification(s).`);for(const g of v)this.handleProxiedMessageNotificationItem(g,S,f)}};function getPayload24(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"broadcastContext cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},broadcast:f,links:{addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE)}}}}function getPayload25(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"broadcastContext cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},groupContext:f.groupContext?{id:f.groupContext.groupId}:null,groupChat:f.groupChat?{threadId:f.groupChat.threadId,messageId:f.groupChat.messageId}:null,links:{addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE)}}}}function getPayload26(g,f){return assertNotNull(g,"signalingSession cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},links:{admitAllStatus:get2(g,rn.CONV_ADMIT_ALL_STATUS)},operationId:f,debugContent:{causeId:f}}}}function getPayload27(g,f,S=!0){assertNotNull(g,"signalingSession cannot be null"),assertNotNull(f,"joinUrl cannot be null");const v={type:"Delta",rosterUpdate:get2(g,rn.CONV_ROSTER_UPDATE)},C=g.getEndpointCapabilities(),_={payload:{attach:{requireMediaContent:S,links:{end:get2(g,rn.END)},locationContent:g.getLocationContent(),networkContent:g.getNetworkContent(),areaContent:g.getAreaContent()},capabilities:null,endpointCapabilities:C,additionalActions:[{input:{capabilities:null,endpointCapabilities:C,conversationRequest:{applicationType:g.participantManager.localParticipant.applicationType,roster:v,links:{conversationEnd:get2(g,g.signalingAgentConfig.enableSplitConversationEndUrl?rn.CONV_END_JOIN:rn.CONV_END),conversationUpdate:get2(g,rn.CONV_UPDATE),localParticipantUpdate:get2(g,rn.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:get2(g,rn.RECEIVE_MESSAGE)}},endpointMetadata:g.endpointMetadata,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}}},name:"join",url:f,waitForResponse:!0}]}};return g.signalingAgentConfig.ecsEtag&&(_.payload.debugContent={ecsEtag:g.signalingAgentConfig.ecsEtag}),_.payload.additionalActions.length>0&&g.deviceType&&"default"!==g.deviceType&&(_.payload.additionalActions[0].input.conversationRequest.deviceType=g.deviceType),_}function getPayload28(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{callAcceptanceAcknowledgement:{links:{mediaRenegotiation:get2(g,rn.MEDIA_RENEGOTIATION),transfer:get2(g,rn.TRANSFER),replacement:get2(g,rn.REPLACE),balanceUpdate:get2(g,rn.BALANCE_UPDATE),retargetCompletion:get2(g,rn.RETARGET_COMPLETION),controlVideoStreaming:get2(g,rn.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:get2(g,rn.UPDATE_MEDIA_DESCRIPTIONS)}}}}}function getPayload29(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");const C=getMediaTypes(S);g.telemetryHelper.addOutgoingModalities(C);const _=g.getEndpointCapabilities();return{payload:{callAcceptance:{acceptedBy:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},acceptedCallModalities:C,capabilities:null,endpointCapabilities:_,clientEndpointCapabilities:0!==v?v:null,links:{mediaRenegotiation:get2(g,rn.MEDIA_RENEGOTIATION),transfer:get2(g,rn.TRANSFER),replacement:get2(g,rn.REPLACE),balanceUpdate:get2(g,rn.BALANCE_UPDATE),retargetCompletion:get2(g,rn.RETARGET_COMPLETION),controlVideoStreaming:get2(g,rn.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:get2(g,rn.UPDATE_MEDIA_DESCRIPTIONS)},clientContentForMediaController:g.webRtcSignalingManager.getClientUrls(),mediaContent:f,pstnContent:g.pstnContent,callKeepAliveInterval:null}}}}function getPayload30(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{callProgress:{sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},status:"ringing",phrase:"ringing"}}}}function getPayload31(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");const C=g.participantManager.localParticipant;return{payload:{invitationRedirection:{target:{type:f,endpointType:v,id:S},sender:{id:C.id,endpointId:C.endpointId,participantId:C.participantId,languageId:C.languageId}}}}}function getPayload32(g,f,S){assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f);const v={payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,languageId:g.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:an.CALL_END_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:f}};return S&&f.code===an.CALL_END_CODE.CANCEL&&(v.payload.callTransactionEnd.callQualityDiagnosticsInformation=S),v}function getPayload33(g,f,S,v){assertNotNull(g,"signalingSession cannot be null");let C=[];C=v.invitationType===an.INVITATION_TYPE.NUDGE&&Array.isArray(v.participantsToNudge)?v.participantsToNudge.map((g=>({id:g}))):g.participantManager.getParticipantsToInitiateCallWith(),g.signalingAgentConfig.doHostlessCalling||assert2(C.length>0,"remoteParticipants need to be set before a call can be made");const _={type:"Delta",rosterUpdate:get2(g,rn.CONV_ROSTER_UPDATE)},T=g.groupId?{id:g.groupId}:null,I=g.threadId?{threadId:g.threadId,messageId:g.teamsMessageId||null}:null,b=g.contentSharingManager.getContentSharingInfoToStartSharing(),A=null===b?null:{identifier:b.contentIdentifier,subject:b.subject,sessionState:b.sessionState,sessionUpdateSequenceNumber:b.sequenceNumber,links:{sessionUpdate:get2(g,rn.CONV_CONTENT_SHARING_UPDATE),sessionEnd:get2(g,rn.CONV_CONTENT_SHARING_END)}},P=g.broadcastSession?.getContext(),R=g.getEndpointCapabilities();1===C.length&&g.telemetryHelper.setCalleeType(C[0].id),g.numberOfOriginalInvitees=C.length;const M=[];C.forEach((f=>{const S={id:f.id};f.displayName&&(S.displayName=f.displayName),f.participantId&&(S.participantId=f.participantId),(v.callToVoicemail||g.transferContext&&g.transferContext.target&&"voicemail"===g.transferContext.target.endpointType)&&(S.endpointType="voicemail"),M.push(S)}));const w=g.transferContext?g.transferContext.transferor:null,O=g.transferContext?g.transferContext.transferContext:null,D={};v.callToVoicemail&&(v.voicemailResourcePath&&(D.localResourcePath=v.voicemailResourcePath),v.voicemailItemId&&(D.voicemailItemId=v.voicemailItemId));const N={payload:{conversationRequest:{conversationType:v.conversationType,subject:g.convSubject,suppressDialout:v.suppressDialout,applicationType:v.applicationType,targetApplicationType:v.targetApplicationType,roster:_,properties:{allowConversationWithoutHost:g.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:g.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:g.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:g.enableGroupCallMeetupGeneration},links:{conversationEnd:get2(g,g.signalingAgentConfig.enableSplitConversationEndUrl?v.subscribe?rn.CONV_END_SUBSCRIBE:rn.CONV_END_JOIN:rn.CONV_END),conversationUpdate:get2(g,rn.CONV_UPDATE),localParticipantUpdate:get2(g,rn.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE),addModalitySuccess:get2(g,rn.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:get2(g,rn.CONV_ADD_MODALITY_FAILURE),confirmUnmute:get2(g,rn.CONV_CONFIRM_UNMUTE),receiveMessage:get2(g,rn.RECEIVE_MESSAGE)}},broadcast:P,contentSharing:A,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,meetingRegistrationId:v.meetingRegistrationId,participantPin:v.participantPin},to:M},capabilities:null,endpointCapabilities:R,clientEndpointCapabilities:v.clientEndpointCapabilities?v.clientEndpointCapabilities:null,endpointMetadata:g.endpointMetadata,groupContext:T,groupChat:I,meetingInfo:g.getMeetingInfo(),meetingData:v.meetingData,meetingPreferences:v.meetingPreferences,endpointState:v.endpointState}};if(v.publishedStates?.publishedStates.length>0){let f=[];f=v.publishedStates.publishedStates.map((f=>{let S={};try{S=JSON.parse(f.content)}catch(f){g.logger.warn("createConversationRequest getPayload() failed to parse state.content")}return{stateType:f.type,level:f.level,content:S,sequenceNumber:g.getPublishStateSequenceNumber()}})),N.payload.publishedStates=f}g.deviceType&&"default"!==g.deviceType&&(N.payload.conversationRequest.deviceType=g.deviceType);const k=getMediaTypes(S);if(g.telemetryHelper.addOutgoingModalities(k),N.payload.callInvitation={callModalities:k,replaces:null,transferor:w||null,clientTransferContext:O,customContext:v.customHeaderContext||null,links:{progress:get2(g,rn.PROGRESS),mediaAnswer:get2(g,rn.MEDIA_ANSWER),acceptance:get2(g,rn.ACCEPT),redirection:get2(g,rn.REDIRECTION),end:get2(g,rn.END)},clientContentForMediaController:g.webRtcSignalingManager.getClientUrls(),pstnContent:g.pstnContent,emergencyContent:g.getEmergencyContent(),mediaContent:f,voicemailSettings:D,routingFlags:v.routingFlags,invitationData:v.invitationData,locationContent:g.getLocationContent(),networkContent:g.getNetworkContent(),areaContent:g.getAreaContent()},v.pickupCode&&(N.payload.callInvitation.unparkContent={pickupCode:parseInt(v.pickupCode,10)}),v.onBehalfOf&&(N.payload.callInvitation.onBehalfOf={id:v.onBehalfOf},v.onBehalfOfUserDisplayName&&(N.payload.callInvitation.onBehalfOf.displayName=v.onBehalfOfUserDisplayName)),v.callQueueContext&&(N.payload.callInvitation.callQueueContext=v.callQueueContext),v.scenario&&(N.payload.conversationRequest.scenario=v.scenario),v.alternateId&&(N.payload.participants.from.alternateId=v.alternateId),v.callingLineIdentity&&(N.payload.participants.from.callingLineIdentity=v.callingLineIdentity),v.invitationType===an.INVITATION_TYPE.NUDGE&&(N.payload.participants.invitationType=v.invitationType),g.signalingAgentConfig.ecsEtag&&(N.payload.debugContent={ecsEtag:g.signalingAgentConfig.ecsEtag}),v.clientEndpointDebugContent){N.payload.debugContent||(N.payload.debugContent={});try{N.payload.debugContent.clientDebugContent=JSON.parse(v.clientEndpointDebugContent)}catch(g){assert2(!1,`Failed to parse ${v.clientEndpointDebugContent}`)}}if(v.captchaContentJson)try{N.payload.conversationRequest.captchaContent=JSON.parse(v.captchaContentJson)}catch(g){assert2(!1,`Failed to parse ${v.captchaContentJson}`)}return v.participationPreferences&&(N.payload.participationPreferences=v.participationPreferences),N}function getPayload34(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:an.CALL_END_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED},callTransactionEnd:f}}}function getPayload35(g,f){return{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:f}}}function getPayload36(g,f,S,v,C){assertNotNull(g,"signalingSession cannot be null");const _={type:"Delta",rosterUpdate:get2(g,rn.CONV_ROSTER_UPDATE)},T=g.getEndpointCapabilities(),I=g.groupId?{id:g.groupId}:null,b=g.threadId?{threadId:g.threadId,messageId:g.teamsMessageId||null}:null,A={payload:{conversationRequest:{conversationType:v.conversationType,subject:g.convSubject,suppressDialout:v.suppressDialout,scenario:v.scenario,applicationType:v.applicationType,roster:_,properties:{allowConversationWithoutHost:g.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:g.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:g.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:g.enableGroupCallMeetupGeneration},links:{conversationEnd:get2(g,g.signalingAgentConfig.enableSplitConversationEndUrl?v.subscribe?rn.CONV_END_SUBSCRIBE:rn.CONV_END_JOIN:rn.CONV_END),conversationUpdate:get2(g,rn.CONV_UPDATE),localParticipantUpdate:get2(g,rn.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:get2(g,rn.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:get2(g,rn.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:get2(g,rn.RECEIVE_MESSAGE)}},groupContext:I,groupChat:b,participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,meetingRegistrationId:v.meetingRegistrationId,participantPin:v.participantPin}},capabilities:null,endpointCapabilities:T,clientEndpointCapabilities:v.clientEndpointCapabilities?v.clientEndpointCapabilities:null,endpointMetadata:g.endpointMetadata,meetingInfo:g.getMeetingInfo(),meetingData:v.meetingData,meetingPreferences:v.meetingPreferences,endpointState:v.endpointState}};if(v.publishedStates?.publishedStates.length>0){let f=[];f=v.publishedStates.publishedStates.map((f=>{let S={};try{S=JSON.parse(f.content)}catch(f){g.logger.warn("joinConversationRequest getPayload() failed to parse state.content")}return{stateType:f.type,level:f.level,content:S,sequenceNumber:g.getPublishStateSequenceNumber()}})),A.payload.publishedStates=f}if(v?.applyServerMute&&(A.payload.participants.from.applyServerMute=v.applyServerMute.value,v.applyServerMute.mediaTypes&&(A.payload.participants.from.mediaTypes=v.applyServerMute.mediaTypes)),g.deviceType&&"default"!==g.deviceType&&(A.payload.conversationRequest.deviceType=g.deviceType),!v.subscribe){const C=getMediaTypes(S);g.telemetryHelper.addOutgoingModalities(C),A.payload.callInvitation={callModalities:C,replaces:null,transferor:null,links:{progress:get2(g,rn.PROGRESS),mediaAnswer:get2(g,rn.MEDIA_ANSWER),acceptance:get2(g,rn.ACCEPT),redirection:get2(g,rn.REDIRECTION),end:get2(g,rn.END)},clientContentForMediaController:g.webRtcSignalingManager.getClientUrls(),mediaContent:f,pstnContent:g.pstnContent,locationContent:g.getLocationContent(),networkContent:g.getNetworkContent(),areaContent:g.getAreaContent(),sharedLineCallInvitationContent:v.sharedLineCallInvitationContent,invitationData:v.invitationData,callQueueContext:v.callQueueContext}}if(g.signalingAgentConfig.ecsEtag&&(A.payload.debugContent={ecsEtag:g.signalingAgentConfig.ecsEtag}),C&&(A.payload.debugContent||(A.payload.debugContent={}),A.payload.debugContent.causeId=C),v.clientEndpointDebugContent){A.payload.debugContent||(A.payload.debugContent={});try{A.payload.debugContent.clientDebugContent=JSON.parse(v.clientEndpointDebugContent)}catch(g){assert2(!1,`Failed to parse ${v.clientEndpointDebugContent}`)}}if(v.captchaContentJson)try{A.payload.conversationRequest.captchaContent=JSON.parse(v.captchaContentJson)}catch(g){assert2(!1,`Failed to parse ${v.captchaContentJson}`)}return v.callQueueContext&&(A.payload.conversationRequest.callQueueContext=v.callQueueContext),v.participationPreferences&&(A.payload.participationPreferences=v.participationPreferences),A}function getJoinMeetingGroupPayload(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},..."meetingGroupId"in f&&{meetingGroup:f.meetingGroupId},..."meetingGroupLabel"in f&&{meetingGroupLabel:f.meetingGroupLabel},...f.groupPreferences&&{groupPreferences:f.groupPreferences},links:{joinMeetingGroupStatus:get2(g,rn.JOIN_MEETING_GROUP_STATUS)},operationId:S}}}function getPayload37(g,f,S,v){assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f);const C={payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},scope:v&&"all"!==v?void 0:v},conversationTransactionEnd:{reason:"noError",code:an.CALL_END_CODE.SUCCESS,phrase:an.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:f}};return S&&f.code===an.CALL_END_CODE.CANCEL&&(C.payload.callTransactionEnd.callQualityDiagnosticsInformation=S),C}function getLeaveMeetingGroupPayload(g,f,S){assertNotNull(g,"signalingSession cannot be null");const{meetingGroupId:v}=f;return{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},meetingGroup:v,links:{leaveMeetingGroupStatus:get2(g,rn.LEAVE_MEETING_GROUP_STATUS)},operationId:S}}}function getPayload38(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),assertNotNull(S,"newOfferLink cannot be null"),{payload:{mediaOfferRequirements:{compatibleContentTypes:f,links:{offerReady:get2(g,rn.NEW_MEDIA_OFFER)}}}}}function getPayload39(g,f){return assertNotNull(f,"signalingSession cannot be null"),{payload:{callTransfer:{target:{id:f.participantManager.localParticipant.id},transferor:{details:{id:f.participantManager.localParticipant.id,endpointId:f.participantManager.localParticipant.endpointId,participantId:f.participantManager.localParticipant.participantId,languageId:f.participantManager.localParticipant.languageId},authorizationToken:null},parkType:g,links:{transferAcceptance:get2(f,rn.TRANSFER_ACCEPTANCE),transferCompletion:get2(f,rn.TRANSFER_COMPLETION)}}}}}function getPayload40(g,f,S){assertNotNull(g,"ParkRequestPayload: signalingSession cannot be null");const v={payload:{hold:{holdType:f,links:{holdCompletion:get2(g,rn.PARK_COMPLETION)}}}};return S&&(v.payload.debugContent=S),v}function getPayload41(g){return assertNotNull(g,"signalingSession cannot be null"),{payload:{callParticipantUpdate:{links:getLinksPayload(g,tn),clientContentForMediaController:g.webRtcSignalingManager.getClientUrls()}}}}function getPayload42(g,f,S,v,C,_){const T={payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},publishedState:{content:v,level:S,stateType:f,sequenceNumber:g.getPublishStateSequenceNumber()},scope:C}};if(_&&_.length>0){const g=_.map((g=>({id:g})));T.payload.to=g}return T}function getPayload43(g,f){return assertNotNull(g,"signalingSession cannot be null"),assertCallEndReason(f),{payload:{callEnd:f}}}function getPayload44(g,f,S,v){const C={from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},sequenceNumber:g.getPublishStateSequenceNumber(),scope:f};return"specified"===f?C.stateIds=S:C.stateType=v,{payload:C}}function getPayload45(g,f){return{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},searchOptions:f}}}function getPayload46(g,f){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,displayName:g.participantManager.localParticipant.displayName},...f,links:{setMeetingLayoutStatus:get2(g,rn.SET_MEETING_LAYOUT_STATUS)}}}}function getPayload47(){return{payload:{transferAcceptance:{}}}}function getPayload48(g,f,S,v,C){return assertNotNull(f,"signalingSession cannot be null"),assertNotNullOrEmpty(g,"transferTarget cannot be null OR empty"),{payload:{callTransfer:{target:{id:g,endpointType:"TransferTypeVoicemail"===v?"voicemail":void 0},transferor:{details:{id:f.participantManager.localParticipant.id,endpointId:f.participantManager.localParticipant.endpointId,participantId:f.participantManager.localParticipant.participantId,languageId:f.participantManager.localParticipant.languageId},authorizationToken:null},links:{transferAcceptance:get2(f,rn.TRANSFER_ACCEPTANCE),transferCompletion:get2(f,rn.TRANSFER_COMPLETION)},replacementDetails:S,disableForwardingAndUnanswered:C&&C.disableForwardingAndUnanswered,transferContext:C&&C.clientTransferContext}}}}function getPayload49(g){return{payload:{transferCompletion:g}}}function getPayload50(g,f){assertNotNull(g,"ResumePayload: signalingSession cannot be null");const S={payload:{resume:{links:{resumeCompletion:get2(g,rn.UNPARK_COMPLETION)}}}};return f&&(S.payload.debugContent=f),S}function getPayload51(g,f){return assertNotNull(f,"clientMetadataJson cannot be null"),{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},endpointMetadata:f}}}function getPayload52(g,f,S,v,C){assertNotNull(f,"clientStateJson cannot be null");const _={payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},endpointState:f}};if(C)try{_.payload.captchaContent=JSON.parse(C)}catch(f){g.logger.warn("updateEndpointState getPayload() failed to parse captchaContentJson")}if(S?.publishedStates.length>0){let f=[];f=S.publishedStates.map((f=>{let S={};try{S=JSON.parse(f.content)}catch(f){g.logger.warn("updateEndpointState getPayload() failed to parse stateType.content")}return{stateType:f.type,level:f.level,content:S,sequenceNumber:g.getPublishStateSequenceNumber()}})),_.payload.publishedStates=f}return v&&(_.payload.links={updateEndpointStateStatus:get2(g,rn.DISABLE_PREHEAT_ASYNC_STATUS)}),_}function getMeetingGroupsPayload(g,f,S){assertNotNull(g,"signalingSession cannot be null");const{scope:v,toGroup:C,fromGroup:_,participants:T}=f;"specified"===v&&assertNotNull(T,"participantsIds cannot be null");const I={from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,displayName:g.participantManager.localParticipant.displayName},scope:v,fromGroup:_,toGroup:C,links:{updateMeetingGroupsStatus:get2(g,rn.UPDATE_MEETING_GROUPS_STATUS)},operationId:S};return T&&(I.to=T.map((g=>({id:g.mri,endpointId:g.endpointId,participantId:g.participantId})))),{payload:I}}function getPayload53(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,displayName:g.participantManager.localParticipant.displayName},meetingLiveState:f,links:{updateMeetingLiveStateStatus:get2(g,rn.UPDATE_MEETING_LIVE_STATE_STATUS)},operationId:S}}}function getPayload54(g,f){const S={};return void 0!==f.allowRaiseHands&&(S.allowRaiseHands=f.allowRaiseHands),void 0!==f.attendeeRestrictions&&(S.attendeeRestrictions=f.attendeeRestrictions),void 0!==f.lockMeeting&&(S.lockMeeting=f.lockMeeting),void 0!==f.breakoutRoomsEnabled&&(S.breakoutRoomsEnabled=f.breakoutRoomsEnabled),void 0!==f.allowPresentersToManageBreakoutRooms&&(S.allowPresentersToManageBreakoutRooms=f.allowPresentersToManageBreakoutRooms),void 0!==f.disableMdpClientAudioRecording&&(S.disableMdpClientAudioRecording=f.disableMdpClientAudioRecording),void 0!==f.refreshSettings&&(S.refreshSettings=f.refreshSettings),void 0!==f.aiInterpretationEnabled&&(S.aiInterpretationEnabled=f.aiInterpretationEnabled),void 0!==f.groupCopilotDetails&&(S.groupCopilotDetails=f.groupCopilotDetails),{payload:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},meetingSettings:S,sequenceNumber:g.getPublishStateSequenceNumber()}}}function getPayload55(g,f,S,v){return assertNotNull(g,"signalingSession cannot be null"),{payload:{monitorContent:{sequenceId:g.getMonitorSequenceId(),monitorActionType:f,monitorData:S??{},links:{monitorCompletion:get2(g,rn.MONITOR_COMPLETION)}},debugContent:{causeId:v}}}}function getPayload56(g){assertNotNull(g,"signalingSession cannot be null");const f={type:"Delta",rosterUpdate:get2(g,nn.CONV_ROSTER_UPDATE)};return{payload:{participants:{from:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId}},roster:f,links:getLinksPayload(g,nn)}}}function getUpdateParticipantsPropertiesPayload(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId},to:f,links:{updateParticipantPropertiesStatus:get2(g,rn.UPDATE_PARTICIPANT_PROPERTIES_STATUS)},operationId:S}}}function getPayload57(g,f){return assertNotNull(g,"signalingSession cannot be null"),{payload:{mediaAnswer:{sender:{id:g.participantManager.localParticipant.id,displayName:g.participantManager.localParticipant.displayName,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId},mediaContent:f,pstnContent:g.pstnContent}}}}function getPayload58(g,f){return assertNotNull(g,"signalingSession cannot be null"),{payload:{UpdateMediaDescriptions:{mediaDescriptions:f}}}}function getPayload59(g,f,S){return assertNotNull(g,"signalingSession cannot be null"),{payload:{from:{id:g.participantManager.localParticipant.id,endpointId:g.participantManager.localParticipant.endpointId,participantId:g.participantManager.localParticipant.participantId,languageId:g.participantManager.localParticipant.languageId,displayName:g.participantManager.localParticipant.displayName},meetingStates:f,updateMeetingStatesStatus:get2(g,rn.UPDATE_MEETING_STATES_STATUS),operationId:S}}}var Jn=__toESM2(M),Yn=__toESM2(Ie()),Qn=["CorrelationId","SignalingSessionId","Region","ParticipantId","ClientInformation","ResultCode","ResultDetail","ResultValue","Direction","ClientType","MeetingRoles"],Xn=class{constructor(g,f){this.signalingSession=g,this.logger=f,this.logConversationCallModalityEvent=g=>{const f=this.createCallModalityEvent(g);this.logger.info("sending modality telemetry:",this.getStringifiedEventData(f)),f.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(un.EVENT_TYPE.CONVERSATION_CALL_MODALITY,f)},this.logConversationContentSharingEvent=g=>{g[un.CONTEXT_ID.CORRELATION_ID]=this.signalingSession.correlationId,g[un.EXTENSIONS.ECS_ETAG]=this.signalingSession.signalingAgentConfig.ecsEtag,this.logger.info("sending content sharing telemetry:",this.getStringifiedEventData(g)),g.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(un.EVENT_TYPE.CONVERSATION_CONTENT_SHARING,g)},this.logHttpTelemetryEvent=g=>{g[un.EXTENSIONS.ECS_ETAG]=this.signalingSession.signalingAgentConfig.ecsEtag,g[un.SIGNALING_CONFIG]=this.getSignalingAgentConfig(),this.logger.info("sending http telemetry:",this.getStringifiedEventData(g)),g.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(un.EVENT_TYPE.CONVERSATION_HTTP_REQUEST,g)},this.getHostDomainInfo=()=>"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>",this.getSignalingAgentConfig=()=>{const g=[],f=this.signalingSession.signalingAgentConfig;return f.supportsCompressedServicePayload&&g.push(un.SIGNALING_CONFIG_FLAGS.SUPPORTS_COMPRESSED_PAYLOAD),f.brokerEnabledOutgoing&&g.push(un.SIGNALING_CONFIG_FLAGS.BROKER_OUTGOING_ENABLED),f.brokerEnabledIncoming&&g.push(un.SIGNALING_CONFIG_FLAGS.BROKER_INCOMING_ENABLED),f.brokerRequestBatching&&g.push(un.SIGNALING_CONFIG_FLAGS.BROKER_REQUEST_BATCHING_ENABLED),f.brokerExclusively&&g.push(un.SIGNALING_CONFIG_FLAGS.BROKER_EXCLUSIVELY_ENABLED),f.supportsSynchronousTrouterResponse&&g.push(un.SIGNALING_CONFIG_FLAGS.SYNC_TROUTER_RESPONSE),f.handleMediaOfferFromPushNotification&&g.push(un.SIGNALING_CONFIG_FLAGS.HANDLE_OFFER_FROM_NOTIFICATION),f.handleNewOfferRequest&&g.push(un.SIGNALING_CONFIG_FLAGS.HANDLE_NEW_OFFER_REQUEST),f.sendProgressFromCC&&g.push(un.SIGNALING_CONFIG_FLAGS.SEND_PROGRESS_FROM_CC),f.useInternalHttpDispatcher&&g.push(un.SIGNALING_CONFIG_FLAGS.INTERNAL_HTTP_DISPATCHER),f.enableTokenCache&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_TOKEN_CACHE),f.enableTokenPrefetch&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_TOKEN_PREFETCH),f.supportMediaRetargetWhileIncomingRenegotiation&&g.push(un.SIGNALING_CONFIG_FLAGS.SUPPORT_MEDIA_RETARGET_WHILE_INCOMING_RENEGOTIATION),f.enableCallEstablishmentTimeoutsForStartJoinCall&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_CALL_ESTABLISHMENT_TIMEOUTS_FOR_START_OR_JOIN_CALL),f.enableTokenCacheForGenericTokenAPI&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_TOKEN_CACHE_FOR_GENERIC_TOKEN_API),f.enableLongOutgoing1To1SetupTimeoutForWeb&&g.push(un.SIGNALING_CONFIG_FLAGS.ENABLE_LONG_OUTGOING_1TO1_SETUP),g.push(un.SIGNALING_CONFIG_FLAGS.SERVER_MUTE_UNMUTE),g.join(",")},this.getStringifiedEventData=g=>{try{return JSON.stringify(g,Qn,4)}catch(g){return"invalid data"}},this.telemetryLogger=this.signalingSession.signalingAgentConfig.oneDsTelemetryLogger??this.signalingSession.signalingAgentConfig.telemetryManager}createCallModalityEvent(g){const f={};f.Type=un.SOURCE.NGC_SOURCE;const setEventProperty=(S,v=!1)=>{f[S]=v?JSON.stringify(g[S]):g[S]},setEventPropertyIfRecorded=(f,S=!1)=>{g.hasOwnProperty(f)&&setEventProperty(f,S)};if(f.ResultDetail=g[un.EXTENSIONS.RESULT_DETAIL],f.ResultValue=g[un.EXTENSIONS.RESULT_VALUE],f.ResultCode=g[un.EXTENSIONS.CALL_END_CODE],f.ResultCauseId=g[un.EXTENSIONS.RESULT_CAUSE_ID],f[un.SIGNALING_CONFIG]=this.getSignalingAgentConfig(),f[un.CONTEXT_ID.CORRELATION_ID]=this.signalingSession.correlationId,f[un.CONTEXT_ID.SIGNALING_SESSION_ID]=this.signalingSession.sessionId,setEventProperty(un.CONTEXT_ID.ENDPOINT_ID),setEventProperty(un.CONTEXT_ID.PARTICIPANT_ID),f[un.EXTENSIONS.ECS_ETAG]=this.signalingSession.signalingAgentConfig.ecsEtag,setEventProperty(un.EXTENSIONS.CONVERSATION_SERVICE_URL),setEventProperty(un.EXTENSIONS.CALL_START_TIME,!0),setEventProperty(un.EXTENSIONS.CALL_END_TIME,!0),setEventProperty(un.EXTENSIONS.MESSAGING_CHANNEL,!0),f[un.EXTENSIONS.IS_GROUP_CALL]=this.signalingSession.multiParty?"true":"false",f[un.EXTENSIONS.IS_HOSTLESS_CALL]=this.signalingSession.isHostLessCall?"true":"false",f[un.EXTENSIONS.IS_CAST_CALL]=this.signalingSession.isCastCall?"true":"false",f[un.EXTENSIONS.IS_HUDDLE_GROUP_CALL]=this.signalingSession.isHuddleGroupCall?"true":"false",f[un.EXTENSIONS.IS_ON_BEHALF_OF_CALL]=this.signalingSession.onBehalfOf?"true":"false",setEventProperty(un.EXTENSIONS.CLIENT_INFORMATION),setEventProperty(un.EXTENSIONS.IS_SDP_IN_CALL_NOTIFICATION),setEventProperty(un.EXTENSIONS.CALL_TERMINATING_END),setEventProperty(un.EXTENSIONS.CALL_END_CODE,!0),setEventProperty(un.EXTENSIONS.CALL_END_SUB_CODE,!0),setEventPropertyIfRecorded(un.CONTEXT_ID.SHARED_CORRELATION_ID),setEventPropertyIfRecorded(un.EXTENSIONS.DIRECTION),setEventPropertyIfRecorded(un.EXTENSIONS.SELF_PARTICIPANT_ROLE),setEventPropertyIfRecorded(un.EXTENSIONS.CONNECTED_DURATION_IN_MS,!0),setEventPropertyIfRecorded(un.EXTENSIONS.TIME_TO_RING_IN_MS,!0),setEventPropertyIfRecorded(un.EXTENSIONS.NETWORK_REQUESTS_COMPLETED),setEventPropertyIfRecorded(un.EXTENSIONS.NETWORK_REQUESTS_PENDING),setEventPropertyIfRecorded(un.EXTENSIONS.LOCAL_OPERATIONS_PERFORMED),setEventPropertyIfRecorded(un.EXTENSIONS.EVENT_TIMESTAMP_BAG),setEventPropertyIfRecorded(un.EXTENSIONS.ROSTER_UPDATES_BAG),setEventPropertyIfRecorded(un.EXTENSIONS.NETWORK_REQUESTS_BAG),setEventPropertyIfRecorded(un.EXTENSIONS.TROUTER_WAIT_OPERATIONS),setEventPropertyIfRecorded(un.EXTENSIONS.LOCAL_OFFER_ANSWER_GENERATION_TIMESTAMPS),setEventPropertyIfRecorded(un.EXTENSIONS.OUTGOING_MODALITIES),setEventPropertyIfRecorded(un.EXTENSIONS.INCOMING_MODALITIES),setEventPropertyIfRecorded(un.EXTENSIONS.OFFERED_MODALITIES),setEventPropertyIfRecorded(un.EXTENSIONS.ANSWERED_MODALITIES),setEventPropertyIfRecorded(un.EXTENSIONS.VBSS_OPERATIONS),setEventPropertyIfRecorded(un.EXTENSIONS.CALLER_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.CALLEE_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.SCENARIO),setEventPropertyIfRecorded(un.EXTENSIONS.PREHEATED_CALL_SETUP_DURATION_IN_S),setEventPropertyIfRecorded(un.EXTENSIONS.CALL_CANCELATION_DURATION_IN_S),setEventPropertyIfRecorded(un.EXTENSIONS.IS_PREHEATED),setEventPropertyIfRecorded(un.EXTENSIONS.ACS_RESOURCE_ID),setEventPropertyIfRecorded(un.EXTENSIONS.CALL_END_RESULT_CATEGORIES),setEventPropertyIfRecorded(un.EXTENSIONS.APPLICATION_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.RING),setEventPropertyIfRecorded(un.EXTENSIONS.REGION),setEventPropertyIfRecorded(un.EXTENSIONS.PARTITION),setEventPropertyIfRecorded(un.EXTENSIONS.JOINED_FROM),setEventPropertyIfRecorded(un.EXTENSIONS.MEETING_URL),setEventPropertyIfRecorded(un.EXTENSIONS.MEETING_CODE),setEventPropertyIfRecorded(un.EXTENSIONS.USER_HEX_CID),setEventPropertyIfRecorded(un.EXTENSIONS.BROADCAST_MEETING_ROLE),setEventPropertyIfRecorded(un.EXTENSIONS.MEETING_ROLE),setEventPropertyIfRecorded(un.EXTENSIONS.ADVANCED_MEETING_ROLE),setEventPropertyIfRecorded(un.EXTENSIONS.MEETING_ROLES,!0),setEventPropertyIfRecorded(un.EXTENSIONS.PARTICIPANT_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.DISPLAY_NAME),setEventPropertyIfRecorded(un.EXTENSIONS.AUDIO_ONLY_WATERMARK),setEventPropertyIfRecorded(un.EXTENSIONS.TARGET_APPLICATION_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.IS_REINVITELESS),setEventPropertyIfRecorded(un.EXTENSIONS.CLIENT_TYPE),setEventPropertyIfRecorded(un.EXTENSIONS.CONFLICTING_CALL_ID),this.signalingSession.callType&&(f[un.EXTENSIONS.CALL_TYPE]=this.signalingSession.callType),this.signalingSession.signalingAgentConfig.testCall&&(f[un.EXTENSIONS.TEST_CONTEXT_ID]="Test"),this.signalingSession.groupId&&(f[un.CONTEXT_ID.GROUP_ID]=scrubMriOrOmit(this.signalingSession.groupId)),this.signalingSession.threadId&&(f[un.CONTEXT_ID.THREAD_ID]=getLoggableThreadId(this.signalingSession.threadId)),this.signalingSession.teamsMessageId&&(f[un.CONTEXT_ID.TEAMS_MESSAGEID]=this.signalingSession.teamsMessageId),this.signalingSession.getMeetingInfo()){const g={...this.signalingSession.getMeetingInfo()};g.hasOwnProperty("organizerId")&&(g.organizerId=scrubMriOrOmit(g.organizerId)),f[un.CONTEXT_ID.TEAMS_MEETINGINFO]=JSON.stringify(g)}return this.signalingSession.multiParty&&0===this.signalingSession.numberOfOriginalInvitees&&g.hasOwnProperty(un.EXTENSIONS.SELF_PARTICIPANT_ROLE)&&g[un.EXTENSIONS.SELF_PARTICIPANT_ROLE]===un.ROLE.CALLER&&(f[un.EXTENSIONS.IS_MEETUP_CALL]="true"),f}};function getLogger(g,f){return new Xn(g,f)}var Zn=class{constructor(g,f,S){this.signalingSession=g,this.callStartTime=S,this.networkRequestsCompleted=[],this.networkRequestsStarted={},this.networkRequests={},this.localOperationsPerformed=[],this.recordedEvents=[],this.rosterUpdates=[],this.contentSharingOperationsPerformed={},this.outgoingModalities=[],this.incomingModalities=[],this.offeredModalities="",this.answeredModalities="",this.vbssOperations=[],this.vbssStarted=!1,this.localOfferAnswerGenerationTimestamps=[],this.trouterWaitOperations=[],this.telemetryData={},this.contentSharingBaseTelemetryData={},this.httpRequestTelemetryData={},this.connectedStopWatch=null,this.preheatedCallSetupDurationWatch=null,this.callCancelationDurationWatch=null,this.timeToRingStopWatch=null,this.isSdpInCallNotification=!1,this.isPreheated=0,this.isReinviteless=0,this.addBrokerChannel=()=>{this.setMessagingChannel(un.MESSAGING_CHANNEL.BROKER)},this.addTrouterChannel=()=>{this.setMessagingChannel(un.MESSAGING_CHANNEL.TROUTER)},this.addTrouterWaitOperation=g=>{this.trouterWaitOperations.push(this.recordOperation(g))},this.recordIncomingEvent=(g,f,S)=>{const v=extractCauseIdFromMessage(f),C={origin:f.origin,causeId:v,data:S};S||delete C.data,this.recordEvent(g,C)},this.recordIncomingEventCount=g=>{this.localOperationsPerformed.push(this.recordOperation(g));const f=this.recordedEvents.findIndex((f=>f[g]));if(-1!==f)this.recordedEvents[f][g]+=1;else{const f={};f[g]=1,this.recordedEvents.push(f)}},this.recordEvent=(g,f)=>{this.logger.debug("Event:",g,f),this.localOperationsPerformed.push(this.recordOperation(g));const S={};S[g]=this.timeSinceCallStart(),f&&(S.data=f),this.recordedEvents.push(S)},this.recordRosterEvent=(g,f,S)=>{this.localOperationsPerformed.push(this.recordOperation(f));const v={data:g,causeId:S},C={eventName:this.timeSinceCallStart(),data:v};this.rosterUpdates.push(C)},this.addOutgoingModalities=g=>{g&&this.outgoingModalities.push(g)},this.addIncomingModalities=g=>{g&&this.incomingModalities.push(g)},this.setOfferedModalities=(g,f)=>{this.offeredModalities=this.sdpTelemetryFormat(g,f)},this.setAnsweredModalities=(g,f)=>{this.answeredModalities=this.sdpTelemetryFormat(g,f)},this.setIsSdpInCallNotification=g=>{this.isSdpInCallNotification=g},this.addVbssOperations=g=>{g&&(g===un.VBSS_OPERATION.START?this.vbssStarted=!0:this.vbssStarted=!1,this.vbssOperations.push(this.recordOperation(g)))},this.addNetworkOperationStarted=g=>{tryAddNewKeyToHashTable(this.networkRequestsStarted,g,this.recordOperation(g))},this.addNetworkOperationCompleted=(g,f,S)=>{const v=f?un.RESULT_VALUE.SUCCESS:un.RESULT_VALUE.FAILURE,C=S?`${g}:${v}:${S}`:`${g}:${v}`;this.networkRequestsCompleted.push(this.recordOperation(C)),tryRemoveKeyFromHashTable(this.networkRequestsStarted,g)},this.updateNetworkRequest=g=>{this.networkRequests[g.uid]?Jn.assign(this.networkRequests[g.uid],g):this.networkRequests[g.uid]=g},this.deleteNetworkRequest=g=>{delete this.networkRequests[g.uid]},this.addContentSharingOperation=(g,f,S)=>{this.contentSharingOperationsPerformed[g]||(this.contentSharingOperationsPerformed[g]=[]);const v={[f]:this.timeSinceCallStart()};this.contentSharingOperationsPerformed[g].push(v);const C=this.contentSharingOperationsPerformed[g].length-1;return S&&this.updateContentSharingOperation(g,C,S),C},this.updateContentSharingOperation=(g,f,S)=>{if(!this.contentSharingOperationsPerformed[g])return;const v=this.contentSharingOperationsPerformed[g][f],C=[];for(const g of Object.keys(S))C.push(`${g}: ${S[g]}`);v.data=C.join(", ")},this.setDirection=g=>{this.telemetryData[un.EXTENSIONS.DIRECTION]=g},this.setEndPointId=g=>{this.telemetryData[un.CONTEXT_ID.ENDPOINT_ID]=g,this.contentSharingBaseTelemetryData[un.CONTEXT_ID.ENDPOINT_ID]=g,this.httpRequestTelemetryData[un.CONTEXT_ID.ENDPOINT_ID]=g},this.setParticipantId=g=>{this.telemetryData[un.CONTEXT_ID.PARTICIPANT_ID]=g,this.contentSharingBaseTelemetryData[un.CONTEXT_ID.PARTICIPANT_ID]=g,this.httpRequestTelemetryData[un.CONTEXT_ID.PARTICIPANT_ID]=g},this.addTokenTelemetry=(g,f)=>{g?this.networkRequests?.[g]?(this.networkRequests[g].tokenTelemetries||(this.networkRequests[g].tokenTelemetries=[]),this.networkRequests[g].tokenTelemetries.push(f)):this.logger.info(`[addTokenTelemtry] httprequest: ${g} is not found in networkRequests`):this.logger.error("[addTokenTelemetry] httprequest uid is undefined")},this.setConversationServiceUrl=g=>{this.telemetryData[un.EXTENSIONS.CONVERSATION_SERVICE_URL]=g},this.setMeetingInfo=g=>{g||(this.telemetryData[un.EXTENSIONS.MEETING_INFO]=g)},this.setJoinedFrom=g=>{this.telemetryData[un.EXTENSIONS.JOINED_FROM]=g},this.setMeetingCode=g=>{this.telemetryData[un.EXTENSIONS.MEETING_CODE]=g},this.setMeetingUrl=g=>{this.telemetryData[un.EXTENSIONS.MEETING_URL]=g},this.setBroadcastMeetingRole=g=>{this.telemetryData[un.EXTENSIONS.BROADCAST_MEETING_ROLE]=g},this.setMeetingRole=g=>{this.telemetryData[un.EXTENSIONS.MEETING_ROLE]=g},this.setAdvancedMeetingRole=g=>{this.telemetryData[un.EXTENSIONS.ADVANCED_MEETING_ROLE]=g},this.setParticipantType=g=>{this.telemetryData[un.EXTENSIONS.PARTICIPANT_TYPE]=g},this.setSelfParticipantRole=g=>{this.telemetryData[un.EXTENSIONS.SELF_PARTICIPANT_ROLE]=g},this.setDisplayName=g=>{const f=new Ue(g,1);this.telemetryData[un.EXTENSIONS.DISPLAY_NAME]=f},this.setAudioOnlyWatermark=g=>{this.telemetryData[un.EXTENSIONS.AUDIO_ONLY_WATERMARK]=g},this.setWatermarkSupport=g=>{this.telemetryData[un.EXTENSIONS.CLIENT_SUPPORT_WATERMARK]=g},this.setClientSupportsPreventScreenCapture=g=>{this.telemetryData[un.EXTENSIONS.CLIENT_SUPPORTS_PREVENT_SCREEN_CAPTURE]=g},this.setScenario=g=>{this.telemetryData[un.EXTENSIONS.SCENARIO]=g},this.setTargetApplicationType=g=>{g&&(this.telemetryData[un.EXTENSIONS.TARGET_APPLICATION_TYPE]=g)},this.setCallerType=g=>{g&&(this.telemetryData[un.EXTENSIONS.CALLER_TYPE]=g.split(":",1)[0])},this.setCalleeType=g=>{g&&(this.telemetryData[un.EXTENSIONS.CALLEE_TYPE]=g.split(":",1)[0])},this.setTerminatingData=g=>{this.telemetryData[un.EXTENSIONS.CALL_TERMINATING_END]=g.terminatingEnd,this.telemetryData[un.EXTENSIONS.CALL_END_CODE]=g.endCode||an.CALL_END_CODE.SUCCESS,this.telemetryData[un.EXTENSIONS.CALL_END_SUB_CODE]=g.endSubCode||an.CALL_END_SUB_CODE.SUCCESS,this.telemetryData[un.EXTENSIONS.CALL_PHRASE]=g.phrase||an.CALL_END_PHRASE.UNKNOWN,this.telemetryData[un.EXTENSIONS.RESULT_VALUE]=g.resultValue||un.RESULT_VALUE.SUCCESS,this.telemetryData[un.EXTENSIONS.RESULT_DETAIL]=g.resultDetail||"Call gracefully hungup",this.telemetryData[un.EXTENSIONS.RESULT_CAUSE_ID]=g.causeId||"unknown",this.telemetryData[un.EXTENSIONS.CALL_END_RESULT_CATEGORIES]=g.resultCategories||[],this.telemetryData[un.EXTENSIONS.CALL_END_CLIENT_SUB_CODE]=g.clientReasonSubCode,this.telemetryData[un.EXTENSIONS.CALL_END_CLIENT_PHRASE]=g.clientReasonPhrase},this.startCallInitializationWatch=g=>{this.timeToRingStopWatch=build3(),g&&(this.timeToRingStopWatch.msElapsed+=g)},this.startCallConnectedWatch=()=>{this.connectedStopWatch=build3()},this.setIsPreheated=()=>{this.isPreheated=1},this.startPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch=build3()},this.stopPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch.pause()},this.startCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=build3()},this.stopCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch&&this.callCancelationDurationWatch.pause()},this.getCallCancelationDuration=()=>this.callCancelationDurationWatch?this.callCancelationDurationWatch.durationInSeconds():0,this.resetCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=null},this.setOfferAnswerGenerationTimestamps=g=>{this.localOfferAnswerGenerationTimestamps.push(this.recordOperation(g))},this.setTimeToRingDuration=()=>{this.timeToRingStopWatch&&(this.telemetryData[un.EXTENSIONS.TIME_TO_RING_IN_MS]=this.timeToRingStopWatch.duration(),this.timeToRingStopWatch=null)},this.dispose=()=>{this.sendCallModalityTelemetryData()},this.setMessagingChannel=g=>{this.telemetryData[un.EXTENSIONS.MESSAGING_CHANNEL]||(this.telemetryData[un.EXTENSIONS.MESSAGING_CHANNEL]=[]),this.telemetryData[un.EXTENSIONS.MESSAGING_CHANNEL].some((f=>-1!==f.indexOf(g)))||this.telemetryData[un.EXTENSIONS.MESSAGING_CHANNEL].push(this.recordOperation(g))},this.sendHttpTelemetryData=g=>{const f={...this.httpRequestTelemetryData};f[un.CONTEXT_ID.CORRELATION_ID]=this.signalingSession.correlationId,f[un.CONTEXT_ID.SIGNALING_SESSION_ID]=this.signalingSession.sessionId,f[un.EXTENSIONS.CLIENT_INFORMATION]=this.signalingSession.signalingAgentConfig.clientInformation;const S=JSON.stringify({eventStart:this.callStartTime,events:this.networkRequests[g]});tryRemoveKeyFromHashTable(this.networkRequests,g),f[un.EXTENSIONS.NETWORK_REQUESTS_BAG]=S,this.telemetryLogger.logHttpTelemetryEvent(f)},this.sdpTelemetryFormat=(g,f)=>{if(!g)return"";const convertType=g=>{switch(g){case"main-audio":return"Audio";case"main-video":return"Video";case"applicationsharing-video":return"AppSharing";default:return}},convertDirection=g=>{switch(g){case"inactive":return"Inactive";case"sendonly":return f?"ReceiveFromPeer":"SendToPeer";case"recvonly":return f?"SendToPeer":"ReceiveFromPeer";default:return"Bidirectional"}},S={"main-audio":0,"main-video":0,"applicationsharing-video":0},v=[],C=Yn.parse(g);for(const g of C.media){const f=convertType(g.label);if(!f)continue;const C=S[g.label]++,_=convertDirection(g.direction);v.push(`${f}[${C}] = ${_}`)}return v.join(", ")},this.setReinviteless=g=>{this.isReinviteless=g?1:0},this.logger=g.logger,this.telemetryLogger=getLogger(g,this.logger),this.telemetryData[un.EXTENSIONS.CALL_START_TIME]=this.callStartTime,this.telemetryData[un.EXTENSIONS.CONVERSATION_SERVICE_URL]=g.signalingAgentConfig.conversationServiceUrl,this.fillCommonData(f,this.telemetryData),this.fillCommonData(f,this.httpRequestTelemetryData),this.fillCommonData(f,this.contentSharingBaseTelemetryData)}fillCommonData(g,f){f[un.EXTENSIONS.APPLICATION_TYPE]=g.applicationType,f[un.EXTENSIONS.RING]=g.ring,f[un.EXTENSIONS.TENANT_ID]=g.tenantId,f[un.EXTENSIONS.USER_HEX_CID]=g.userHexCID,f[un.EXTENSIONS.ACS_RESOURCE_ID]=g.acsResourceId,f[un.EXTENSIONS.REGION]=g.region,f[un.EXTENSIONS.PARTITION]=g.partition,f[un.EXTENSIONS.CLIENT_TYPE]=g.clientType}addChangingCorrelationId(g,f){this.telemetryData[un.EXTENSIONS.CHANGING_CORRELATION_ID_OLD_ID]=g,this.telemetryData[un.EXTENSIONS.CHANGING_CORRELATION_ID_NEW_ID]=f}addSharedCorrelationId(g){this.telemetryData[un.CONTEXT_ID.SHARED_CORRELATION_ID]=g}setMeetingRoles(g){this.telemetryData[un.EXTENSIONS.MEETING_ROLES]=g}setConflictingCallId(g){this.telemetryData[un.EXTENSIONS.CONFLICTING_CALL_ID]=g}sendContentSharingTelemetryData(g,f,S,v,C,_){const T={...this.contentSharingBaseTelemetryData},I=this.contentSharingOperationsPerformed[g];I&&(T[un.EXTENSIONS.EVENT_TIMESTAMP_BAG]=JSON.stringify(I)),T[un.CONTEXT_ID.CONTENT_SHARING_CORRELATION_ID]=g,T[un.CONTEXT_ID.SIGNALING_SESSION_ID]=f,T[un.CONTEXT_ID.CONTENT_SHARING_ID]=_||"",T[un.EXTENSIONS.CONTENT_SHARING_SERVICE_URL]=C,T[un.EXTENSIONS.CONTENT_SHARING_DIRECTION]=S?un.DIRECTION.OUTGOING:un.DIRECTION.INCOMING,T[un.EXTENSIONS.CALL_END_CODE]=v.code,T[un.EXTENSIONS.CALL_END_SUB_CODE]=v.subCode,T[un.EXTENSIONS.CALL_PHRASE]=v.phrase,T[un.EXTENSIONS.CALL_END_RESULT_CATEGORIES]=this.getResultCategoryString(v.resultCategories),T[un.EXTENSIONS.CALL_END_CAUSE_ID]=v.causeId,T[un.EXTENSIONS.CLIENT_INFORMATION]=this.signalingSession.signalingAgentConfig.clientInformation,delete this.contentSharingOperationsPerformed[g],this.telemetryLogger.logConversationContentSharingEvent(T)}recordOperation(g){return`${g}:${this.timeSinceCallStart()}`}timeSinceCallStart(){return(new Date).getTime()-this.callStartTime}sendCallModalityTelemetryData(){this.vbssStarted&&this.addVbssOperations(un.VBSS_OPERATION.CALL_END);const durationMsToS=g=>"number"==typeof g?g/1e3:0;if(this.telemetryData[un.EXTENSIONS.CLIENT_INFORMATION]=this.signalingSession.signalingAgentConfig.clientInformation,this.telemetryData[un.EXTENSIONS.CALL_END_TIME]=(new Date).getTime(),this.connectedStopWatch&&(this.telemetryData[un.EXTENSIONS.CONNECTED_DURATION_IN_MS]=this.connectedStopWatch.duration()),this.telemetryData[un.EXTENSIONS.IS_PREHEATED]=this.isPreheated,this.preheatedCallSetupDurationWatch&&(this.telemetryData[un.EXTENSIONS.PREHEATED_CALL_SETUP_DURATION_IN_S]=durationMsToS(this.preheatedCallSetupDurationWatch.duration())),this.callCancelationDurationWatch&&(this.telemetryData[un.EXTENSIONS.CALL_CANCELATION_DURATION_IN_S]=durationMsToS(this.callCancelationDurationWatch.duration())),this.networkRequestsCompleted.length&&(this.telemetryData[un.EXTENSIONS.NETWORK_REQUESTS_COMPLETED]=JSON.stringify(this.networkRequestsCompleted)),this.localOperationsPerformed.length&&(this.telemetryData[un.EXTENSIONS.LOCAL_OPERATIONS_PERFORMED]=JSON.stringify(this.localOperationsPerformed)),this.trouterWaitOperations.length&&(this.telemetryData[un.EXTENSIONS.TROUTER_WAIT_OPERATIONS]=JSON.stringify(this.trouterWaitOperations)),this.localOfferAnswerGenerationTimestamps.length&&(this.telemetryData[un.EXTENSIONS.LOCAL_OFFER_ANSWER_GENERATION_TIMESTAMPS]=JSON.stringify(this.localOfferAnswerGenerationTimestamps)),this.incomingModalities.length&&(this.telemetryData[un.EXTENSIONS.INCOMING_MODALITIES]=JSON.stringify(this.incomingModalities)),this.outgoingModalities.length&&(this.telemetryData[un.EXTENSIONS.OUTGOING_MODALITIES]=JSON.stringify(this.outgoingModalities)),this.offeredModalities.length&&(this.telemetryData[un.EXTENSIONS.OFFERED_MODALITIES]=this.offeredModalities),this.answeredModalities.length&&(this.telemetryData[un.EXTENSIONS.ANSWERED_MODALITIES]=this.answeredModalities),this.telemetryData[un.EXTENSIONS.CALL_END_RESULT_CATEGORIES]=this.getResultCategoryString(this.telemetryData[un.EXTENSIONS.CALL_END_RESULT_CATEGORIES]),this.telemetryData[un.EXTENSIONS.IS_SDP_IN_CALL_NOTIFICATION]=this.isSdpInCallNotification.toString(),this.vbssOperations.length&&(this.telemetryData[un.EXTENSIONS.VBSS_OPERATIONS]=JSON.stringify(this.vbssOperations)),this.recordedEvents.length){const g=JSON.stringify({eventStart:this.callStartTime,events:this.recordedEvents});this.telemetryData[un.EXTENSIONS.EVENT_TIMESTAMP_BAG]=g}if(this.rosterUpdates.length){const g=JSON.stringify({eventStart:this.callStartTime,events:this.rosterUpdates});this.telemetryData[un.EXTENSIONS.ROSTER_UPDATES_BAG]=g}const g=[];for(const f of Object.keys(this.networkRequestsStarted))g.push(this.networkRequestsStarted[f]);g.length>0&&(this.telemetryData[un.EXTENSIONS.NETWORK_REQUESTS_PENDING]=JSON.stringify(g)),this.telemetryData[un.EXTENSIONS.IS_REINVITELESS]=this.isReinviteless,this.telemetryLogger.logConversationCallModalityEvent(this.telemetryData)}getResultCategoryString(g){return g&&Array.isArray(g)?g.join(","):""}},er=class{constructor(g,f){this.disposed=!1,this.lastSeenSeqNumbers={},this.isDominantSpeakerInfoLinkEnabled=!0,this.clientUrlsGenerated=!1,this.getClientUrls=()=>{this.clientUrlsGenerated=!0;let g=null;return this.isWebRtcCall&&(g={controlVideoStreaming:get2(this.signalingSession,rn.CONTROL_VIDEO_STREAMING),csrcInfo:get2(this.signalingSession,rn.CSRC_INFO)},this.isDominantSpeakerInfoLinkEnabled&&(g.dominantSpeakerInfo=get2(this.signalingSession,rn.DOMINANT_SPEAKER_INFO))),g},this.handleDominantSpeakerInfo=g=>{const f=g.body;this.logger.debug("handleDominantSpeakerInfo : ",getPrintableObject(f)),this.signalingSession.telemetryHelper.recordIncomingEventCount(dn.HANDLE_DOMINANT_SPEAKER_CHANGED_COUNT),this.handleWebRtcNotification(an.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO,f.dominantSpeakerInformation)},this.handleControlVideoStreaming=g=>{const f=g.body;this.logger.debug("handleControlVideoStreaming: ",getPrintableObject(f)),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_CONTROL_VIDEO_STREAMING,g),this.handleWebRtcNotification(an.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING,f.controlVideoStreaming,!1)},this.handleCsrcInfo=g=>{const f=g.body;this.logger.debug("handleCsrcInfo : ",getPrintableObject(f)),this.signalingSession.telemetryHelper.recordIncomingEvent(dn.HANDLE_CSRC_INFO,g),this.handleWebRtcNotification(an.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO,f.csrcInfo)},this.sendWebRtcMediaNotificationAsync=({operation:g,requestUrl:f,requestBody:S,stackRetry:v=!0},C)=>{this.logger.info("sendWebRtcMediaNotificationAsync"),assert2(this.isWebRtcCall,"this is not a webrtc call"),assertNotNullOrEmpty(f,"correct media notification requestUrl is not provided"),assertNotNullOrEmpty(S,"media notification requestBody cannot be null or empty");const _=defer(),T={url:f,payload:{payload:S},requestName:g,withoutTrouter:!0,causeId:C};return v||(T.disableRetry=!0),this.signalingSession.http.sendPostRequest(T).then((()=>{this.disposed||_.resolve()})).catch((g=>{const f=getPrintableObject(g);if(this.logger.error(`sendWebRtcMediaNotificationAsync failed because : ${f}`),!this.disposed){const f=new Error(g);f.endCode=an.CALL_END_NETWORK_ERROR,_.reject(f)}})),_.promise},this.dispose=()=>{this.logger.info("WebRtcSignalingManager :: dispose"),this.disposed=!0},this.signalingSession=g,this.signalingSessionCallback=f,this.isWebRtcCall=g.signalingAgentConfig.isWebRtcEnabled,this.logger=g.logger,this.lastSeenSeqNumbers[an.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING]=-1,this.lastSeenSeqNumbers[an.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO]=-1,this.lastSeenSeqNumbers[an.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO]=-1}areClientURLsGenerated(){return this.clientUrlsGenerated}getIsDominantSpeakerInfoLinkEnabled(){return this.isDominantSpeakerInfoLinkEnabled}setIsDominantSpeakerInfoLinkEnabled(g){this.isDominantSpeakerInfoLinkEnabled=g}handleWebRtcNotification(g,f,S=!0){assert2(this.isWebRtcCall,"ignoring message in non-webrtc call");const v=this.lastSeenSeqNumbers[g];S&&f.sequenceNumber<=v?this.logger.info(`ignoring ${g} . Last seen seq = ${v} current seq = ${f.sequenceNumber}`):(f.sequenceNumber<=v&&this.logger.info(`let listener to handle older ${g} . Last seen seq = ${v} current seq = ${f.sequenceNumber}`),this.lastSeenSeqNumbers[g]=Math.max(f.sequenceNumber,this.lastSeenSeqNumbers[g]),this.signalingSessionCallback.onWebRtcMediaNotification(g,f))}},tr=class{constructor(g,f,S,v,C,_){this.disposed=!1,this.convSubject=null,this.groupId=null,this.threadId=null,this.incomingCallCallerId=null,this.incomingCallPayload=null,this.multiParty=!0,this.isIncomingCall=!1,this.isHostLessCall=!1,this.isCastCall=!1,this.isHuddleGroupCall=!1,this.numberOfOriginalInvitees=0,this.teamsMessageId=null,this.enableGroupCallMeetupGeneration=!1,this.meetingInfo=null,this.meetingDetails=null,this.emergencyContent=null,this.transferContext=null,this.callType="default",this.callMode=0,this.transferor=null,this.onBehalfOf=null,this.onBehalfOfUserDisplayName=null,this.callQueueContext=null,this.callQueueSupervisorContent=null,this.bannerContent=null,this.callPhoneLineType=null,this.endpointMetadata={},this.sessionId=newGuid2(),this.remoteCaller=null,this.acceptedElsewhereBy=null,this.parkAdditionalContextJson=null,this.serverHoldLocation=null,this.breakoutDetails=null,this.callLimits=null,this.complianceRecordingContent=null,this.backroomThreadId=null,this.streamThreadId=null,this.lobbyThreadId=null,this.conversationStartTime=null,this.realTimeState=0,this.disposing=!1,this.links={},this.provisionalMediaAnswersSeenSoFar=[],this.incomingTrouterMessagesSeenSoFar=[],this.incomingBrokerMessagesSeenSoFar=[],this.currentCallStatus=null,this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.convJoined=!1,this.keepAliveTimer=null,this.keepAliveInterval=null,this.keepAliveCount=1,this.conversationKeepAliveTimer=null,this.conversationKeepAliveInterval=null,this.conversationKeepAliveCount=1,this.remoteUser=null,this.mediaTypesToUse=null,this.lastUsedOutgoingMediaContent=null,this.lastUsedJoinCallOptions=null,this.originalRoleBeforePreheat="",this.endpointStateSequenceNumber=0,this.publishStateSequenceNumber=0,this.monitorSequenceId=0,this.requestedPublishedStatesWhileConnecting=null,this.linkUpdateRequested={conversationLinks:!1,keepAliveLinks:!1},this.incomingMessageSyncResponseCache={},this.isPreheatOnly=!1,this.callStartTime=(new Date).getTime(),this.callUsesMixer=!1,this.disablePreheatDefer=defer(),this.participantReplacementDetails={},this.meetingLiveStateSequenceNumber=0,this.meetingLayoutSequenceNumber=0,this.localParticipantUpdateSequenceNumber=0,this.isRedirectAllowed=!1,this.updateSequenceNumber=-1,this.isPromotingToRealtime=!1,this.streamInformationReceived=!1,this.startOrJoinConvResponseReceived=!1,this.updateParticipantsPromises={},this.updateEndpointState=(g,f=causeId2(),S,v)=>{this.logger.info(`[${f}][requestedEndpointState=${getPrintableObject(g,!0)}][captchaContentJson=${v}]`);const C=this.links[an.LINKS.UPDATE_ENDPOINT_STATE],_=this.getEndpointState();this.logger.info(`[${f}][currentEndpointState=${getPrintableObject(_,!0)}] startOrJoinConvResponseReceived=${this.startOrJoinConvResponseReceived}`);const T={..._,...g,endpointStateSequenceNumber:++this.endpointStateSequenceNumber};this.telemetryHelper.recordEvent(dn.UPDATE_ENDPOINT_STATE,{newEndpointState:T,causeId:f});const I=0===T?.endpointProperties?.preheatProperties&&this.isPreheatOnly;if(I&&(this.telemetryHelper.recordEvent(dn.PREHEAT_DISABLING,{causeId:f}),this.telemetryHelper.startPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallCancelationDurationWatch()),2===this.callMode&&I)return this.logger.info(`[${f}][updateEndpointState skipped as mode is streaming]`),this.handleEndpointStateUpdated(f,!0),Promise.resolve();if(!this.startOrJoinConvResponseReceived)return this.logger.info(`[${f}][updateEndpointState will be queued as we don't have a link yet]`),this.requestedEndpointStateWhileConnecting=g,this.requestedPublishedStatesWhileConnecting=S,I?this.disablePreheatDefer.promise:Promise.resolve();if(!this.shouldUpdateEndpointState(_,T)&&!this.http.hasPendingRequest(hn.UPDATE_ENDPOINT_STATE.name))return this.logger.info(`[${f}][updateEndpointState will ignore current update as there is nothing new to send]`),Promise.resolve();if(!C)return this.logger.info(`[${f}][updateEndpointState operation cannot be performed now, the link is not yet available]`),Promise.reject("No link");this.latestEndpointState=T;const b=this.signalingAgentConfig.enableAsyncDisablePreheat&&I;b&&this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT,(()=>{const g={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.DISABLE_PREHEAT_TIMEOUT,phrase:an.CALL_END_PHRASE.DISABLE_PREHEAT_TIMEOUT};this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject({response:g})}),an.TIMEOUT_VALUES_IN_SECONDS.DISABLE_PREHEAT_TIMEOUT);const A=this.http.sendPostRequest({url:C,requestName:hn.UPDATE_ENDPOINT_STATE.name,payload:getPayload52(this,T,S,b,v),causeId:f}).then((()=>(b&&(this.logger.info(`[${f}][updateEndpointState] asyncDisablePreheat: true`),this.telemetryHelper.recordEvent(dn.DISABLE_PREHEAT_RESPONSE_RECEIVED,{causeId:f})),Promise.resolve()))).catch((g=>{if(!b)throw g;this.disablePreheatDefer.reject(g)}));return(b?this.disablePreheatDefer.promise:A).then((()=>{this.logger.info(`[${f}][updateEndpointState] asyncDisablePreheat: ${b}`),this.telemetryHelper.recordEvent(b?dn.ASYNC_DISABLE_PREHEAT_SUCCEEDED:dn.DISABLE_PREHEAT_SUCCEEDED,{causeId:f}),this.disposed||this.handleEndpointStateUpdated(f,I)})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[${f}][updateEndpointState] error: ${getPrintableObject(S)}`),I&&(this.handleDisablePreheatError(S.error,b?dn.ASYNC_DISABLE_PREHEAT_FAILED:dn.DISABLE_PREHEAT_FAILED,f),this.stopCallPreheatTimer(),this.terminateEstablishedCall({code:S.error.code,subCode:S.error.subCode,phrase:S.error.phrase},{forEveryone:!1,causeId:f})),Promise.reject(S.error)}))},this.setParticipantCallLinks=g=>{g&&g.endpointDetails&&(this.participantReplacementDetails[g.id]={},g.endpointDetails.forEach((f=>{f&&f.callLinks&&(this.participantReplacementDetails[g.id][f.participantId]=f.callLinks)})))},this.clearParticipantCallLinks=g=>{this.participantReplacementDetails?.hasOwnProperty(g)&&delete this.participantReplacementDetails[g]},this.getReplacementDetailsByParticipantLeg=(g,f,S=causeId2())=>(this.logger.info(`[${S}]getReplacementDetailsByParticipantLeg: participantMri ${this.piiUtils.scrubMriOrOmit(g)} participantLegId ${f}`),this.participantReplacementDetails?.hasOwnProperty(g)&&this.participantReplacementDetails[g].hasOwnProperty(f)?{replaces:this.participantReplacementDetails[g][f].replacement,replacementTargetParticipantId:f}:(this.logger.info(`[${S}]getReplacementDetailsByParticipantLeg: unable to find replacement details for participantLegId ${f}`),{})),this.getReplacementDetailsByParticipantLegOfCall=(g,f,S,v=causeId2())=>{this.logger.info(`[${v}]getReplacementDetailsByParticipantLegOfCall: callId ${g} participantMri ${this.piiUtils.scrubMriOrOmit(f)} participantLegId ${S}`);const C=this.signalingAgent.getSignalingSession(g);return C?C.getReplacementDetailsByParticipantLeg(f,S,v):{}},this.getMriByParticipantLegOfCall=(g,f,S)=>{this.logger.info(`[${S}]getMriByParticipantLegOfCall: callId: ${g} participantLegId ${f}`);const v=this.signalingAgent.getSignalingSession(g);return v?v.getMriByParticipantLeg(f,S):""},this.getMriByParticipantLeg=(g,f)=>{this.logger.info(`getMriByParticipantLeg[${f}] participantLegId ${g}`);for(const f of Object.keys(this.participantReplacementDetails))if(f&&this.participantReplacementDetails.hasOwnProperty(f)&&this.participantReplacementDetails[f]?.hasOwnProperty(g))return f;return""},this.handleEndpointStateUpdated=(g,f)=>{this.requestedEndpointStateWhileConnecting=null,this.requestedPublishedStatesWhileConnecting=null,f&&this.handlePreheatDisabled(g)},this.handlePreheatDisabled=g=>{this.isPreheatOnly=!1,this.telemetryHelper.setSelfParticipantRole(this.originalRoleBeforePreheat),this.telemetryHelper.recordEvent(dn.PREHEAT_DISABLED,{causeId:g}),this.telemetryHelper.resetCallCancelationDurationWatch(),this.telemetryHelper.stopPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallConnectedWatch(),this.stopCallPreheatTimer(),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.resolve()},this.shouldUpdateEndpointState=(g,f)=>{if(!f)return!1;const S=f.state&&f.state.isMuted?1:0,v=f.endpointProperties&&1===f.endpointProperties.preheatProperties?1:0,C=g&&g.state&&g.state.isMuted?1:0,_=g&&g.endpointProperties&&1===g.endpointProperties.preheatProperties?1:0,T=g?.endpointProperties?.additionalEndpointProperties,I=f?.endpointProperties?.additionalEndpointProperties;return!!(S^C||v^_||I!==T)},this.setInitialTelemetry=(g,f)=>{let S,v;switch(g){case"Subscribe":this.telemetryHelper.recordEvent(dn.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY,{causeId:f.causeId,correlationId:f.correlationId}),this.telemetryHelper.setDirection(un.DIRECTION.OUTGOING),this.telemetryHelper.setSelfParticipantRole(un.ROLE.JOIN_FOR_ROSTER_ONLY),this.telemetryHelper.setConversationServiceUrl(f.conversationServiceUrl||this.signalingAgentConfig.conversationServiceUrl),this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);break;case"Acknowledge":this.telemetryHelper.recordEvent(dn.HANDLE_INCOMING_CALL,{causeId:f.causeId}),this.telemetryHelper.setDirection(un.DIRECTION.INCOMING),this.telemetryHelper.setSelfParticipantRole(un.ROLE.CALLEE),this.telemetryHelper.setCalleeType(this.participantManager.localParticipant.id);break;case"JoinCall":S=this.gatherTelemetryForStartOrJoin(f.joinCallOptions,f.causeId,f.offerGenerationTime),this.telemetryHelper.recordEvent(dn.JOIN_CALL,S),this.telemetryHelper.setDirection(un.DIRECTION.OUTGOING),this.telemetryHelper.setSelfParticipantRole(un.ROLE.JOIN);break;case"StartCall":case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":v=this.gatherTelemetryForStartOrJoin(f.callStartOptions,f.causeId,f.offerGenerationTime),this.telemetryHelper.recordEvent(dn.START_CALL,v),this.telemetryHelper.setDirection(un.DIRECTION.OUTGOING),this.telemetryHelper.setSelfParticipantRole(un.ROLE.CALLER),this.telemetryHelper.startCallInitializationWatch(f.offerGenerationTime),this.telemetryHelper.setMeetingInfo(this.getMeetingInfo())}},this.getParticipantIdForOfferAnswer=g=>{assertNotNull(g,"mediaContent should be a non null value"),this.logger.info("getParticipantIdForOfferAnswer");let f=null;return!this.remoteUser||this.groupId||this.threadId||g.newOffer||g.escalationOccurring||(f=this.remoteUser.id),f},this.getMeetingInfo=()=>this.meetingInfo,this.getEmergencyContent=()=>(this.telemetryHelper.recordEvent(dn.GET_EMERGENCY_CONTENT),this.emergencyContent),this.getEndpointId=()=>this.signalingAgent.endpointId,this.getConversationUrl=()=>this.links[an.LINKS.CONVERSATION_CONTROLLER],this.setJoinedFrom=g=>{!this.disposed&&g&&(this.telemetryHelper.recordEvent(dn.SET_JOINED_FROM),this.telemetryHelper.setJoinedFrom(g))},this.setMeetingCode=g=>{!this.disposed&&g&&this.telemetryHelper.setMeetingCode(g)},this.setMeetingUrl=g=>{!this.disposed&&g&&this.telemetryHelper.setMeetingUrl(g)},this.setSubject=g=>{this.disposed||(this.telemetryHelper.recordEvent(dn.SET_SUBJECT),assertNotNull(g,"subject should be a non null value"),this.convSubject=g)},this.setDeviceType=g=>{this.disposed||(this.telemetryHelper.recordEvent(dn.SET_DEVICETYPE),g&&(this.deviceType=g,this.logger.info("setDeviceType",this.deviceType)))},this.setOfferAnswerGenerationTimestamps=g=>{this.disposed||this.telemetryHelper.setOfferAnswerGenerationTimestamps(g)},this.setTimeToRingDuration=()=>{this.disposed||this.telemetryHelper.setTimeToRingDuration()},this.setGroupId=g=>{this.telemetryHelper.recordEvent(dn.SET_GROUPID),this.groupId!==g&&g&&(assert2(!this.groupId,"conversation groupId has already been set. It cannot be overwritten"),this.groupId=g)},this.setThreadId=g=>{this.telemetryHelper.recordEvent(dn.SET_THREADID),assertNotNull(g,"threadId should be a non null value"),this.threadId!==g&&(assert2(!this.threadId,"conversation threadId has already been set. It cannot be overwritten"),this.threadId=g)},this.setDisplayName=g=>{!this.disposed&&g&&this.telemetryHelper.setDisplayName(g)},this.setCallOptions=g=>{if(assertNotNull(g,"callOptions should be a non null value"),this.logger.info("setCallOptions",getPrintableObject(g)),this.telemetryHelper.recordEvent(dn.SET_CALLOPTIONS),g){this.teamsMessageId=g.teamsMessageId,this.meetingInfo=g.meetingInfo||null,this.emergencyContent=g.emergencyContent||null,this.enableGroupCallMeetupGeneration=g.enableGroupCallMeetupGeneration||!1,g.broadcastContext&&(this.broadcastSession=new yn(this,this.signalingSessionCallback),this.broadcastSession.setContext(g.broadcastContext));try{this.endpointMetadata=JSON.parse(g.endpointMetadata)}catch(g){this.logger.warn("Unable to parse endpoint metadata")}}},this.setTransferContext=g=>{assertNotNull(g,"transferContext should not be null"),this.logger.info("Transfer: setTransferContext",scrubObjectFields(g)),this.telemetryHelper.recordEvent(dn.SET_TRANSFER_CONTEXT),this.transferContext=g},this.muteAsync=(g,f,S=causeId2())=>(assert2(2!==this.callMode||g!==an.MUTE_SCOPE.MYSELF,"mute self operation is not allowed in streaming mode"),this.logger.info(`[${S}][muteAsync][scope=${g}]`),this.telemetryHelper.recordEvent(dn.MUTE,{causeId:S}),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,`[${S}]mute operation for all or specified only allowed in a connected call`),this.participantManager.muteAsync(this.links[an.LINKS.MUTE],g,f,S)),this.unmuteAsync=(g=causeId2())=>(assert2(2!==this.callMode,"unmute operation is not allowed in streaming mode"),this.logger.info(`[${g}][unmuteAsync]`),this.telemetryHelper.recordEvent(dn.UNMUTE,{causeId:g}),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"unmute operation only allowed in a connected call"),this.participantManager.unmuteAsync(this.links[an.LINKS.UNMUTE],g)),this.recordTelemetryForStartAudio=(g,f)=>(this.telemetryHelper.recordEvent(dn.START_AUDIO,{mediaNegotiationStatus:g,causeId:f}),Promise.resolve(null)),this.recordTelemetryForStopAudio=(g,f)=>(this.telemetryHelper.recordEvent(dn.STOP_AUDIO,{mediaNegotiationStatus:g,causeId:f}),Promise.resolve(null)),this.rejectUnmuteRequestAsync=(g,f=causeId2(),S)=>(assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"rejectUnmute operation only allowed in a connected call"),assertNotNullOrEmpty(g,"requestor must be specified"),this.logger.info(`[${f}][rejectUnmuteRequestAsync][rejectionReason=${S}]`),this.telemetryHelper.recordEvent(dn.REJECT_UNMUTE,{causeId:f,rejectionReason:S}),this.participantManager.rejectUnmuteRequestAsync(g,f,S)),this.approveUnmuteRequestAsync=(g,f=causeId2())=>(assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"approveUnmute operation only allowed in a connected call"),assertNotNullOrEmpty(g,"requestor must be specified"),this.logger.info(`[${f}][approveUnmuteRequestAsync]`),this.telemetryHelper.recordEvent(dn.APPROVE_UNMUTE,{causeId:f}),this.participantManager.approveUnmuteRequestAsync(g,f)),this.sendWebRtcMediaNotificationAsync=(g,f,S=causeId2())=>(assert2(2!==this.callMode,"sendWebRtcMediaNotification operation is not allowed in streaming mode"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"webRtc media notification can only be sent in a connected call"),this.telemetryHelper.recordEvent(dn.SEND_WEBRTC_MEDIA_NOTIFICATION,{causeId:S}),0===g?this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:hn.SEND_APPLY_CHANNEL_PARAMETERS.name,requestUrl:this.links[an.LINKS.APPLY_CHANNEL_PARAMETERS],requestBody:f,stackRetry:!1},S):this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:hn.SEND_CONTROL_VIDEO_STREAMING.name,requestUrl:this.links[an.LINKS.CONTROL_VIDEO_STREAMING],requestBody:f},S)),this.addParticipantsAsync=(g,f,S=causeId2())=>{assertNotNullOrEmpty(g,"remoteParticipants should be a non null value"),assert2(this.isCallOngoing()||this.isCallIdleOrRosterOnly(),"remoteParticipants can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${S}][addParticipantsAsync][addParticipantOptions=${getPrintableObject(f)}]\n            [remoteParticipantId=${g.map((g=>this.piiUtils.scrubMriOrOmit(g.id)))}]`);let v=dn.ADD_PARTICIPANT;switch(f.replacementType){case 2:v=dn.ADD_PARTICIPANT_WITH_PICKUP_CODE;break;case 1:case 3:v=dn.ADD_PARTICIPANT_WITH_REPLACES;break;default:v=dn.ADD_PARTICIPANT}this.telemetryHelper.recordEvent(v,{causeId:S}),f.groupId=this.groupId||f.groupId,f.threadId=this.threadId||f.threadId;const C=f.threadId||f.groupId?this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[an.LINKS.ADD_PARTICIPANT],_=this.participantManager.addParticipantsAsync(g,C,this.isCallConnectedOrConnectedForRoster(),f,S);return this.currentCallStatus||this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,S),_},this.addGroupModalityAsync=(g,f)=>{assert2(this.isCallOngoing(),"GroupModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${f}][addGroupModalityAsync][addGroupModalityOptions=${getPrintableObject(g)}]`);const S=dn.ADD_PARTICIPANTS_AND_MODALITY;this.telemetryHelper.recordEvent(S,{causeId:f});const v=getPayload11(this,null,g);return this.http.sendPostRequest({url:this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY],payload:v,requestName:hn.ADD_PARTICIPANTS_AND_MODALITY.name,causeId:f}).then((()=>{Cn.noop()})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);throw this.logger.info(`[${f}][sendNetworkRequestForAddingParticipant] failed:${getPrintableObject(S)}`),S.error}))},this.addModalityAsync=(g,f)=>{assert2(this.isCallOngoing(),"GroupModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${f}][addModalityAsync][modalityContext=${getPrintableObject(g)}]`),this.telemetryHelper.recordEvent(dn.ADD_MODALITY,{causeId:f});const S=getPayload25(this,g);return this.http.sendPostRequest({url:this.links[an.LINKS.ADD_MODALITY],payload:S,requestName:hn.ADD_MODALITY.name,causeId:f}).then((g=>(this.logger.info(`[${f}][addModalityAsync] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_ADD_MODALITY_COMPLETION,{causeId:f}),an.SUCCESS_TRANSACTION_END))).catch((g=>{const S=getErrorForXHRFailure(g);return this.logger.info(`[${f}][sendNetworkRequestForAddModalityAsync] failed:${getPrintableObject(S)}`),Promise.reject(S.error)}))},this.addBroadcastModalityAsync=(g,f)=>{if(assert2(this.isCallOngoing(),"BroadcastModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${f}][addBroadcastModalityAsync][addBroadcastContext=${getPrintableObject(this.addBroadcastModalityAsync)}]`),this.telemetryHelper.recordEvent(dn.ADD_BROADCAST_MODALITY,{causeId:f}),this.broadcastSession){const g="There is already a broadcast session";return this.logger.info(g),Promise.resolve(an.SUCCESS_TRANSACTION_END)}this.broadcastSession=new yn(this,this.signalingSessionCallback),this.broadcastSession.setContext(g);const S=getPayload24(this,g);return this.http.sendPostRequest({url:this.links[an.LINKS.ADD_MODALITY],payload:S,requestName:hn.ADD_BROADCAST_MODALITY.name,causeId:f}).then((g=>(this.logger.info(`[${f}][addBroadcastModalityAsync] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_ADD_BROADCAST_MODALITY_COMPLETION,{causeId:f}),an.SUCCESS_TRANSACTION_END))).catch((g=>{const S=getErrorForXHRFailure(g);return this.logger.info(`[${f}][sendNetworkRequestForAddBroadcastModalityAsync] failed:${getPrintableObject(S)}`),this.endBroadcastMeeting(f),Promise.reject(S.error)}))},this.nudgeParticipantsAsync=g=>{if(assertNotNull(g.participantsIds,"ParticipantsIds should be a non null value"),assert2(this.isCallOngoing(),"Participants can only be nudged before starting an outgoing call or to an ongoing call"),this.logger.info(`[${g.causeId}][nudgeParticipantsAsync][participantsIds=${this.piiUtils.scrubParticipantsList(g.participantsIds)}][invitationData=${g.invitationData}]`),void 0===g.participantsIds||g.participantsIds.length<1)return Promise.reject("List of participants to nudge is empty");this.telemetryHelper.recordEvent(dn.ADD_PARTICIPANT,{withNudge:an.INVITATION_TYPE.NUDGE,causeId:g.causeId});const f=this.groupId||g.newGroupId,S=this.threadId||g.newThreadId,v=this.teamsMessageId||g.newMessageId,C=S||f?this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[an.LINKS.ADD_PARTICIPANT];return this.participantManager.nudgeParticipantsAsync(g.participantsIds,C,this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,g.causeId,g.invitationData,f,S,v)},this.callMeBackAsync=(g,f=causeId2())=>(assertNotNull(g,"remoteParticipant should be a non null value"),this.logger.info(`[${f}][callMeBackAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(g.id)}]`),this.telemetryHelper.recordEvent(dn.CALL_ME_BACK,{causeId:f}),this.hasGroupModality()||assert2(!1,"threadId/groupId must be set before using call me back"),this.participantManager.callMeBackAsync(g,this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY],f)),this.removeParticipantAsync=(g,f=causeId2(),S="none")=>{switch(assertNotNull(g,"remoteParticipant should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"participants can only be removed from an ongoing call"),this.logger.info(`[${f}][removeParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(g.id)}] [removeEndpointScope] ${S}`),S){case"all":this.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT_OTHERS,{causeId:f});break;case"specified":this.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT_SPECIFIED,{causeId:f});break;default:this.telemetryHelper.recordEvent(dn.REMOVE_PARTICIPANT,{causeId:f})}return"none"!==S&&g.endpointId?this.participantManager.removeParticipantEndpointAsync(g,this.links[an.LINKS.REMOVE_PARTICIPANT],S,f):this.participantManager.removeParticipantAsync(g,this.links[an.LINKS.REMOVE_PARTICIPANT],f)},this.admitParticipantAsync=(g,f=causeId2())=>(assertNotNull(g,"remoteParticipant should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"remoteParticipants can only be admitted to an ongoing call"),this.hasGroupModality()||assert2(!1,"threadId/groupId must be set before admitting more participants to connected call"),this.logger.info(`[${f}][admitParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(g.id)}]`),this.telemetryHelper.recordEvent(dn.ADMIT_PARTICIPANT,{causeId:f}),this.participantManager.admitParticipantAsync(g,this.links[an.LINKS.ADMIT],f)),this.admitAsync=g=>{if(this.logger.info(`[${g}][admitAsync]`),this.telemetryHelper.recordEvent(dn.ADMIT,{causeId:g}),!this.links[an.LINKS.ADMIT_ALL]){const f={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.ADMIT_ALL_LINK_MISSING,phrase:an.CALL_END_PHRASE.ADMIT_ALL_URL_MISSING};return this.telemetryHelper.recordEvent(dn.ADMIT_FAILURE,{causeId:g,transactionEnd:f}),this.logger.warn(`admitAsync error ${getPrintableObject(f)}`),Promise.reject(f)}const f=defer();return this.callOperationHandler.setPendingOperation(0,g,{promise:f,causeId:g},g),this.sendNetworkRequestForAdmit(g),f.promise},this.updateMeetingRolesAsync=(g,f,S=causeId2())=>(assertNotNull(g,"participants array should be a non null value"),assertNotNull(f,"meetingRole should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"remote participant roles can only be updated in an ongoing call"),this.logger.info(`[${S}][updateMeetingRolesAsync][participants=${this.piiUtils.scrubMriOrOmit(g)}]`),this.participantManager.updateMeetingRolesAsync(g,f,this.links[an.LINKS.UPDATE_PARTICIPANT_ROLE],S)),this.startContentSharingAsync=(g,f,S,v,C=causeId2())=>(assertNotNull(g,"contentIdentifier should be a non null value"),assert2(this.isCallOngoing(),"contentSharing can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${C}][startContentSharingAsync]`),this.telemetryHelper.recordEvent(dn.ADD_CONTENT_SHARING_MODALITY,{causeId:C}),this.contentSharingManager.startContentSharingAsync(g,f,S,this.links[an.LINKS.ADD_MODALITY],this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,C,v)),this.deleteContentSharingAsync=(g,f=causeId2())=>(this.logger.info(`[${f}][deleteContentSharingAsync][correlationId=${g}]`),this.telemetryHelper.recordEvent(dn.DELETE_CONTENT_SHARING,{causeId:f,correlationId:g}),this.contentSharingManager.deleteContentSharingAsync(g,f)),this.joinContentSharingAsync=(g,f=causeId2())=>(this.logger.info(`[${f}][joinContentSharingAsync][correlationId=${g}]`),this.telemetryHelper.recordEvent(dn.JOIN_CONTENT_SHARING,{causeId:f,correlationId:g}),this.contentSharingManager.joinContentSharingAsync(g,f)),this.updateContentSharingSessionStateAsync=(g,f,S=causeId2())=>(assertNotNull(f,"sessionState should be a non null value"),this.telemetryHelper.recordEvent(dn.UPDATE_SESSION_STATE_CONTENT_SHARING,{causeId:S,correlationId:g}),this.logger.info(`[${S}][updateContentSharingSessionStateAsync][correlationId=${g}][sessionState=${f}]`),this.contentSharingManager.updateContentSharingSessionStateAsync(g,f,S)),this.takeContentSharingControlAsync=(g,f=causeId2())=>(this.telemetryHelper.recordEvent(dn.TAKE_CONTROL_CONTENT_SHARING,{causeId:f,correlationId:g}),this.logger.info(`[${f}][takeContentSharingControlAsync][correlationId=${g}]`),this.contentSharingManager.takeContentSharingControlAsync(g,f)),this.updateContentSharingParticipantStateAsync=(g,f=causeId2())=>(this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING,{causeId:f}),this.logger.info(`[${f}][updateContentSharingParticipantStateAsync][correlationId=${g}]`),this.contentSharingManager.updateContentSharingParticipantStateAsync(g,f)),this.configureEndpointStateForStartOrJoin=g=>{const f={endpointStateSequenceNumber:this.endpointStateSequenceNumber};let S=!1;if(g&&(g.muted&&(S=!0,Object.assign(f,{state:{isMuted:g.muted}})),g.isPreheatOnly||g.additionalEndpointProperties)){const v={};S=!0,g.isPreheatOnly&&(v.preheatProperties=1),g.additionalEndpointProperties&&(v.additionalEndpointProperties=g.additionalEndpointProperties),Object.assign(f,{endpointProperties:v})}if(S)return f},this.gatherTelemetryForStartOrJoin=(g,f,S)=>{const v={causeId:f};return g&&(g.invitationType===an.INVITATION_TYPE.NUDGE&&(v.withNudge=g.invitationType===an.INVITATION_TYPE.NUDGE),g.parkContext&&(v.unpark=!0,v.context=g.parkContext),g.isPreheatOnly&&(v.isPreheatOnly=!0),g.targetApplicationType&&(v.targetApplicationType=g.targetApplicationType,this.telemetryHelper.setTargetApplicationType(g.targetApplicationType))),v},this.startOutgoingCall=(g,f,S,v,C=causeId2())=>{if(assertNotNull(g,"mediaContent should be a non null value"),assertNotNull(g.blob,"outgoingSdp should be a non null value"),assert2(this.isCallIdleOrRosterOnly(),"a call is already in progress"),this.logger.info(`[${C}][startOutgoingCall][start] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${C}][startOutgoingCall][failed][reason=Session disposed]`);this.lastUsedJoinCallOptions={muted:S?S.muted:null,scenario:S?S.scenario:null,isPreheatOnly:S?S.isPreheatOnly:null,clientEndpointCapabilities:S?S.clientEndpointCapabilities:null,clientEndpointDebugContent:S?S.clientEndpointDebugContent:null},this.originalRoleBeforePreheat=un.ROLE.CALLER,S&&S.scenario&&this.telemetryHelper.setScenario(S.scenario),this.logger.info(`[${C}][startOutgoingCall]options=${getPrintableObject(this.gatherTelemetryForStartOrJoin(S,C,v))}`),this.isBrokerEnabledForOutgoingCall()&&this.setupBrokerChannel(),this.callUsesMixer=!(!S||!S.callUsesMixer),this.fsmState=an.SIGNALING_FSM_STATE.OUTGOING,this.meetingData=S?.meetingData,this.meetingPreferences=S?.meetingPreferences;const _={newCall:!0,suppressDialout:S&&S.suppressDialout||!1,conversationServiceUrl:this.signalingAgentConfig.conversationServiceUrl,onBehalfOf:S?S.onBehalfOf:null,onBehalfOfUserDisplayName:S?S.onBehalfOfUserDisplayName:null,callQueueContext:S?S.callQueueContext:null,callToVoicemail:!!S&&S.callToVoicemail,voicemailResourcePath:S?S.voicemailResourcePath:null,voicemailItemId:S?S.voicemailItemId:null,endpointState:this.configureEndpointStateForStartOrJoin(S),invitationType:S&&S.invitationType?S.invitationType:null,participantsToNudge:S&&Array.isArray(S.participantsToNudge)?S.participantsToNudge:null,routingFlags:S?S.routingFlags:null,parkContext:S?S.parkContext:null,pickupCode:S?S.pickupCode:null,scenario:S?S.scenario:null,isPreheatOnly:!!S&&S.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:S?S.clientEndpointCapabilities:0,clientEndpointDebugContent:S?S.clientEndpointDebugContent:null,invitationData:S?S.invitationData:null,conversationType:S?this.getConversationType(S.isEmergency,S.castCall,S.isHuddleGroupCall):null,meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,alternateId:S?S.alternateId:null,meetingRegistrationId:S?S.meetingRegistrationId:null,participantPin:S?S.participantPin:null,publishedStates:S?S.publishedStates:null,targetApplicationType:S?S.targetApplicationType:null,captchaContentJson:S?S.captchaContentJson:null,customHeaderContext:S?S.customHeaderContext:null,participationPreferences:S?S.participationPreferences:null};this.isCastCall=S&&S.castCall,this.isHuddleGroupCall=S&&S.isHuddleGroupCall,this.onBehalfOf=_.onBehalfOf,this.onBehalfOfUserDisplayName=_.onBehalfOfUserDisplayName,this.callQueueContext=_.callQueueContext,this.startOrJoinCall(_,hn.START_CALL.name,C,g,f)},this.joinGivenConversation=(g,f,S,v,C,_={},T=causeId2())=>{if(assertNotNull(f,"correlationId should be a non null value"),assertNotNullOrEmpty(g||this.getConversationUrl(),"conversationUrl should be a non null value"),assertNotNull(S,"mediaContent should be a non null value"),assertNotNull(S.blob,"outgoingSdp should be a non null value"),this.isPromotingToRealtime=2===this.callMode,assert2(this.isCallIdleOrRosterOnly()||this.isPromotingToRealtime,"a call is already in progress"),this.logger.info(`[${T}][joinGivenConversation][start][correlationId=${f}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${T}][joinGivenConversation][failed][reason=Session disposed]`);const I=this.gatherTelemetryForStartOrJoin(_,T,C);this.lastUsedJoinCallOptions=_,this.originalRoleBeforePreheat=un.ROLE.JOIN,this.telemetryHelper.startCallInitializationWatch(C),_&&_.scenario&&this.telemetryHelper.setScenario(_.scenario),this.logger.info(`[${T}][joinGivenConversation]options=${getPrintableObject(I)}`),this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=an.SIGNALING_FSM_STATE.OUTGOING,this.updateCorrelationId(f,T),this.meetingData=_?.meetingData,this.meetingPreferences=_?.meetingPreferences;const b={newCall:!1,suppressDialout:!0,conversationServiceUrl:g,endpointState:this.configureEndpointStateForStartOrJoin(_),scenario:_?_.scenario:null,isPreheatOnly:!!_&&_.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:_?_.clientEndpointCapabilities:0,clientEndpointDebugContent:_?_.clientEndpointDebugContent:null,conversationType:_?this.getConversationType(_.isEmergency,!1):null,meetingPreferences:this.meetingPreferences,meetingData:this.meetingData,meetingRegistrationId:_?.meetingRegistrationId,participantPin:_?.participantPin,sharedLineCallInvitationContent:_?.sharedLineCallInvitationContent,applyServerMute:_?.applyServerMute,publishedStates:_?.publishedStates,invitationData:_?.invitationData,captchaContentJson:_?.captchaContentJson,callQueueContext:_?.callQueueContext,participationPreferences:_?.participationPreferences};this.isCastCall=!1,this.startOrJoinCall(b,hn.JOIN_CONVERSATION.name,T,S,v)},this.subscribeToCall=(g,f,S=0,v,C=causeId2())=>{assertNotNull(f,"correlationId should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.IDLE,"a call is already in progress");let _=g;return _||(_=this.signalingAgentConfig.conversationServiceUrl,this.logger.info(`conversationServiceUrl passed is empty. so it is set to ${_}`)),assertNotNullOrEmpty(_,"conversationUrl should be a non null value"),this.logger.info(`[${C}][subscribeToCall][start][correlationId=${f}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed?(this.logger.warn(`[${C}][subscribeToCall][failed][reason=Session disposed]`),Promise.reject(an.CALL_END_CODE.CALL_DOES_NOT_EXIST)):(this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.lastUsedJoinCallOptions=v||{},this.lastUsedJoinCallOptions.clientEndpointCapabilities=S||this.lastUsedJoinCallOptions?.clientEndpointCapabilities,this.meetingData=v?.meetingData,this.meetingPreferences=v?.meetingPreferences,this.fsmState=an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY,this.updateCorrelationId(f,C),this.http.sendPostRequest({url:_,requestName:hn.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,operationType:"CallSetup",payload:getPayload36(this,null,null,{subscribe:!0,clientEndpointCapabilities:S,...v,applicationType:this.participantManager.localParticipant.applicationType,endpointState:this.configureEndpointStateForStartOrJoin({additionalEndpointProperties:v?.additionalEndpointProperties})},C),causeId:C}).then((g=>{this.disposed||(this.fsmState=an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,this.processConversationServiceResponseHeaders(g,C),this.processConversationServiceResponse(g.response,C,1),this.onCallStatusChanged(an.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY,C))})).catch((g=>{if(g.stack&&!this.isFatalException(g))return Promise.resolve();const f=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[${C}][subscribeToCall] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(f)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:f.telemetryEndSubCode,endSubCode:f.error.subCode,resultCategories:f.error.resultCategories,resultDetail:f.error.phrase||"SubscribeFailure",causeId:C}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,C,f.error),Promise.reject(f.error))})))},this.getCallReplacementDetailsForCall=(g,f=causeId2())=>{this.logger.info(`[${f}] getCallReplacementDetailsForCall callId ${g}`);const S=this.signalingAgent.getSignalingSession(g);return S?S.getCallReplacementDetails(f):{replaces:""}},this.getCallReplacementDetails=(g=causeId2())=>(this.logger.info(`[${g}] getCallReplacementDetails`),{replaces:this.links[an.LINKS.REPLACE]}),this.transferCallAsync=(g,f,S,v,C=causeId2())=>{this.logger.info(`[${C}] transferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(g)} transferType ${f} callTransferOptions: ${safeJsonStringify(v)}`),this.transferHelper(g,f,S,v,C)},this.redirectCall=(g,f=causeId2(),S)=>{const{id:v,endpointType:C,type:_}=g.redirectOptions;if(this.logger.info(`[${f}] redirectCall: targetId: ${this.piiUtils.scrubMriOrOmit(v)} targetEndpointType ${C}`),!this.isRedirectAllowed){const g={code:an.CALL_END_CODE.REJECT,phrase:an.CALL_END_PHRASE.CALL_REDIRECT_IS_NOT_ALLOWED};return Promise.reject(g)}this.telemetryHelper.recordEvent(dn.CALL_REDIRECT,{causeId:f});const T=getPayload31(this,_,v,C);return this.http.sendPostRequest({url:this.links[an.LINKS.REDIRECT],requestName:hn.SEND_CALL_REDIRECT_REQUEST.name,payload:T,causeId:f}).then((v=>(this.logger.info(`[${f}][redirectCall] succeeds. Leaving the call...`),this.telemetryHelper.recordEvent(dn.CALL_REDIRECT_REQUEST_SENT,{causeId:f,targetEndpointType:C}),this.terminateEstablishedCall(S,g)))).catch((g=>{const v=getErrorForXHRFailure(g);this.logger.info(`[${f}][redirectCall] error: ${getPrintableObject(v)}`);const _=v.error;return this.telemetryHelper.recordEvent(dn.CALL_REDIRECT_REQUEST_FAILED,{causeId:f,transactionEnd:_,endpointType:C}),this.disposed||(this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,endCode:S.code,endSubCode:S.subCode,clientReasonSubCode:S.clientReasonSubCode,clientReasonPhrase:S.clientReasonPhrase,resultDetail:S.phrase||"RedirectCall",resultCategories:S.resultCategories,causeId:f}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,S),this.dispose(S,f)),Promise.reject(_)}))},this.transferHelper=(g,f,S,v,C=causeId2())=>{assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet");let _=!1;this.logger.info(`[${C}][transferHelper][replacementDetails=${getPrintableObject(S)}] disableForwardingAndUnanswered=${v&&v.disableForwardingAndUnanswered}`),this.telemetryHelper.recordEvent(dn.TRANSFER_CALL,{causeId:C}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(C,_)}),an.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT),this.http.sendPostRequest({url:this.links[an.LINKS.TRANSFER],requestName:hn.SEND_TRANSFER_REQUEST.name,payload:getPayload48(g,this,S,f,v),causeId:C}).then((()=>{this.telemetryHelper.recordEvent(dn.WAITING_FOR_TRANSFER_ACCEPTANCE,{causeId:C}),_=!0})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${C}][transferCallAsync] error: ${getPrintableObject(f)}`),this.disposed||(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:an.CALL_END_CODE.NETWORK_ERROR,reason:getPrintableObject(g)}},C),this.telemetryHelper.recordEvent(dn.TRANSFER_REQUEST_FAILED,{causeId:C,...f.error}))})),this.telemetryHelper.recordEvent(dn.TRANSFER_REQUEST_SENT,{causeId:C,transferType:f})},this.consultTransferCallAsync=(g,f,S,v,C)=>{let _,T;if(this.logger.info(`[${v}] consultTransferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(f)} transferTargetParticipantLegId: ${S}`),S?(T=this.getMriByParticipantLegOfCall(g,S,v),_=this.getReplacementDetailsByParticipantLegOfCall(g,f,S,v)):(T=f,_=this.getCallReplacementDetailsForCall(g,v)),!T||!_){const C=_?"target mri corresponding not found":`unable to retrieve replacementDetails for transferTargetCallId: ${g}, transferTargetMri: ${f}, transferTargetParticipantLegId: ${S}`;return this.logger.info(`[${v}] consultTransferCallAsync: error: ${C}`),void this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:an.CALL_END_CODE.BAD_REQUEST,reason:C}},v)}this.transferHelper(T,"TransferTypeStandard",_,C,v)},this.isParkByTransfer=(g,f)=>{const S=["serverHold","sharedLinePark","teamPark"].indexOf(g)>-1;return this.logger.info(`[${f}][isParkByTransfer][context=${g}] result = ${S}`),S},this.parkCallAsync=(g,f=causeId2())=>{if(g&&"none"===g)throw{code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"};return assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet"),this.logger.info(`[${f}][parkCallAsync][context=${g}]`),this.telemetryHelper.recordEvent(dn.PARK_CALL,{causeId:f,parkType:getParkTypeName(g)}),this.isParkByTransfer(g,f)?this.parkByTransfer(g,f):this.park(g,f)},this.unparkAsync=(g,f=causeId2())=>{if(g&&"none"===g)throw{code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"};if(!this.links[an.LINKS.UNPARK])throw{code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark link not available"};this.logger.info(`[${f}][unparkAsync][context=${g}]`),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UNPARK_COMPLETION,(()=>{this.handleUnparkError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UNPARK_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UNPARK_COMPLETION_TIMEOUT},dn.WAITING_FOR_UNPARK_COMPLETION_TIMEOUT,f,g)}),an.TIMEOUT_VALUES_IN_SECONDS.UNPARK_COMPLETION_TIMEOUT);const S={causeId:f};return this.http.sendPostRequest({url:this.links[an.LINKS.UNPARK],requestName:hn.SEND_UNPARK_REQUEST.name,payload:getPayload50(this,S),causeId:f}).then((g=>(this.logger.info(`[${f}][unparkAsync] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UNPARK_COMPLETION,{causeId:f}),Promise.resolve()))).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${f}][unparkAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUnparkError(v.error,dn.UNPARK_REQUEST_FAILED,f,g),Promise.reject(v.error))}))},this.handleUpdateParticipantsPropertiesCompletion=g=>{const f=g.body,S=extractCauseIdFromMessage(g),v=this.logger.createChild(`[${S}][handleUpdateParticipantsPropertiesCompletion]`,this.correlationId),C={};if(this.disposed)v.info("ignored. Call disposed.");else{if(f.operationId||v.warn("operationId is undefined."),v.info("starts"),f.participantInfos)for(const g of f.participantInfos){if(!g.participant.id){v.warn("participant id is undefined."),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED,"participant id is undefined in response, property");continue}if(!g.participant.key){v.warn("property name (key) is undefined."),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED,"property name (key) is undefined in response");continue}const _=mapMriAndPropertyNameToResolveString(g.participant.id,f.operationId,g.participant.key),T={code:g.transactionEnd.code,subCode:g.transactionEnd.subCode,phrase:g.transactionEnd.phrase,resultCategories:g.transactionEnd.resultCategories};v.info(`Update participants properties completed for: ${this.piiUtils.scrubMriOrOmit(g.participant.id)} with transactionEnd ${getPrintableObject(T)}`),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_COMPLETED,{causeId:S,resolveId:this.piiUtils.scrubMriOrOmit(_),property:g.participant.key,result:getPrintableObject(T)}),C[_]=T,this.updateParticipantsPromises[f.operationId].delete(_)}this.checkAndCleanupPromisesForOperationId(f.operationId),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(C,f.operationId,S)}},this.getCallStatus=()=>this.currentCallStatus,this.processIncomingCallRequest=(g,f,S=causeId2())=>{assertNotNull(g,"request should be a non null value"),assertNotNullOrEmpty(g.body,"request should have a valid body"),assertNotNullOrEmpty(g.body.gp||g.body.cp,"request body should have payload"),assert2(this.isCallIdleOrRosterOnly(),"a call is already in progress");const v=this.logger.createChild(`[${S}][processIncomingCallRequest]`);if(this.callUsesMixer=g.fromMixer,v.info("[start]"),this.disposed)return void v.warn("processIncomingCallRequest canceled");this.telemetryHelper.startCallInitializationWatch(),this.isIncomingCall=!0,this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=an.SIGNALING_FSM_STATE.INCOMING,this.participantManager.initializeForIncomingCall();let C={};try{f&&(C=JSON.parse(f))}catch(g){v.warn("Unable to parse endpoint metadata")}this.endpointMetadata=C;try{let f;if(g?.body?.gp&&!isStringBase64(g.body.gp))v.info("unencoded payload, skipping decoding."),f=g.body.gp;else{const S=g.body.gp?atob(g.body.gp):decodeMessage(g.body.cp);f=JSON.parse(S)}if(!f.callNotification)throw v.info("[failed][reason=CallNotification missing]"),new Error("CallNotification is missing");v.info(`incoming call payload: ${safeJsonStringify(scrubObjectFields(f))}`),this.processIncomingCallPayload(f,S),this.incomingCallPayload=f}catch(g){this.endIncomingCallBecauseOfInvalidPayload(S)}},this.sendAttachToCall=(g=causeId2())=>(this.logger.info(`[${g}][sendAttachToCall]`),this.incomingCallPayload?(this.onCallStatusChanged(an.CALL_STATUS.IDLE,g),this.sendAttachToCallInternal(g)):(this.endIncomingCallBecauseOfInvalidPayload(g),Promise.reject(an.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD))),this.supportsNewOfferRequest=()=>this.signalingAgentConfig.handleNewOfferRequest,this.requestNewOffer=(g,f=causeId2())=>(this.telemetryHelper.recordEvent(dn.REQUEST_NEW_OFFER,{compatibleContentTypes:g,causeId:f}),this.signalingAgentConfig.handleNewOfferRequest?(assertNotNullOrEmpty(this.links[an.LINKS.NEW_OFFER],"newOffer link should be a non null value"),this.http.sendPostRequest({url:this.links[an.LINKS.NEW_OFFER],requestName:hn.REQUEST_NEW_OFFER.name,payload:getPayload38(this,g,this.links[an.LINKS.NEW_OFFER]),causeId:f}).then((g=>this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):Promise.resolve(g))).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[requestNewOffer][${f}] error ${getPrintableObject(S)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:S.telemetryEndSubCode,endSubCode:S.error.subCode,resultCategories:S.error.resultCategories,resultDetail:S.error.phrase||"RequestNewOfferFailure",causeId:f}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,S.error),this.dispose(S.error,f),Promise.reject(S.error))}))):Promise.reject("Disabled")),this.endAsync=(g,f={})=>{f.causeId=f.causeId||causeId2();const S=f.causeId;if(this.logger.info(`[${S}][endAsync][rejectionData=${g&&getPrintableObject(g)}][endCallForAll=${f.forEveryone}]`),this.disposed)return this.logger.warn(`[${S}][endAsync] canceled but session already disposed`),Promise.resolve(null);if(this.disposing=!0,this.telemetryHelper.recordEvent(dn.END_CALL,g?{code:g.code,subCode:g.subCode,causeId:S,callEndClientSubCode:g.clientReasonSubCode,callEndClientPhrase:g.clientReasonPhrase}:{causeId:S}),f.preventAllCallbacks){const g=Object.keys(this.signalingSessionCallback);for(const f of g)this.signalingSessionCallback[f]=Cn.noop}const v=this.mediaRenegotiationManager?.isIncomingRenegotiationInProgress()||this.mediaRenegotiationManager?.isOutgoingRenegotiationInProgress();if(this.telemetryHelper.stopCallCancelationDurationWatch(),this.fsmState===an.SIGNALING_FSM_STATE.INCOMING)return g.code===an.CALL_END_CODE.CALL_REDIRECTED?this.redirectCall(f,S,g):this.rejectIncomingCall(g,S);if(this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY)return this.cancelOutgoingCall(g,S);if(this.fsmState===an.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK)return this.rejectIncomingCall(g,S);if((this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED||v)&&f.forEveryone)return this.deleteConversation(g,S);if(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||v)return this.terminateEstablishedCall(g,f);{this.logger.info(`[${S}][endAsync] there is no call to cancel or end or reject in current state`);const f={code:isNaN(g?.code)?an.CALL_END_CODE.NOT_FOUND:g.code,subCode:isNaN(g?.subCode)?an.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED:g.subCode,phrase:g?.phrase||an.CALL_END_PHRASE.CALL_DOES_NOT_EXIST,resultCategories:g?.resultCategories||[Xi.ExpectedError],clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase};return this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultDetail:f.phrase||"CallDoesNotExist",endCode:f.code,endSubCode:f.subCode,resultCategories:f.resultCategories,causeId:S,clientReasonSubCode:f.clientReasonSubCode,clientReasonPhrase:f.clientReasonPhrase}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,S,f),this.dispose(f,S),Promise.resolve(null)}},this.handleIncomingMsgAsync=(g,f=an.INCOMING_MESSAGE_ORIGIN.TROUTER)=>{assertNotNull(g,"incoming message should be a non null value");const S=extractMessageIdFromMessage(g),v=defer(),C=g.body,_=g.url,T={...g,origin:f},I=extractCauseIdFromMessage(T);if(this.logger.info(`[${I}][handleIncomingMsgAsync][url=${_}][messageId=${S}]`),!C)return this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(dn.MESSAGE_MISSING_BODY,{origin:f,messageId:S,causeId:I}),v.reject(new Error("received message with no body")),v.promise;if(this.disposed)return this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=call is disposed]`),v.reject(this.getCallNotFoundTransactionEnd()),v.promise;if(this.isDuplicatedIncomingMessage(T))return this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=duplicate]`),this.telemetryHelper.recordEvent(dn.DUPLICATE_MESSAGE_IGNORED,{origin:f,messageId:S,causeId:I}),v.resolve(new Error("Message was already handled")),v.promise;this.checkCorrelationIdChange(g,I);const b={[sn.CALL_NOTIFICATION]:g=>{this.handleCallNotification(g)},[sn.MEDIA_ANSWER]:g=>{this.handleMediaAnswer(g)},[sn.MEDIA_ACKNOWLEDGEMENT]:g=>{this.handleMediaAcknowledgement(g)},[sn.CALL_ACCEPTANCE]:g=>{this.handleCallAcceptance(g)},[sn.CALL_END]:g=>{this.handleCallEnd(g,!1)},[sn.CALL_PROGRESS]:g=>{this.handleCallProgress(g)},[sn.CALL_ACCEPTANCE_ACKNOWLEDGEMENT]:g=>{this.handleCallAcceptanceAck(g)},[sn.MEDIA_NEGOTIATION]:g=>{this.mediaRenegotiationManager?.handleMediaNegotiationOffer(g)},[sn.MEDIA_NEGOTIATION_FAILURE]:g=>{this.mediaRenegotiationManager?.handleMediaNegotiationFailure(g)},[sn.BALANCE_UPDATE]:g=>{this.handlePSTNBalanceUpdate(g)},[sn.RETARGET_COMPLETED]:g=>{this.mediaRenegotiationManager?.handleRetargetCompleted(g)},[sn.CALL_TRANSFER]:g=>{this.handleTransferRequested(g)},[sn.TRANSFER_COMPLETION]:g=>{this.handleTransferCompletion(g)},[sn.TRANSFER_ACCEPTANCE]:g=>{this.handleTransferAcceptance(g)},[sn.PARK_COMPLETION]:g=>{this.handleParkCompletion(g)},[sn.UNPARK_COMPLETION]:g=>{this.handleUnparkCompletion(g)},[sn.UPDATE_MEETING_LIVE_STATE_RESPONSE]:g=>{this.handleUpdateMeetingLiveStateCompletion(g)},[sn.UPDATE_MEETING_GROUPS_RESPONSE]:g=>{this.handleUpdateMeetingGroupsCompletion(g)},[sn.SET_MEETING_LAYOUT_RESPONSE]:g=>{this.handleSetMeetingLayoutCompletion(g)},[sn.UPDATE_MEETING_STATES_RESPONSE]:g=>{this.handleUpdateMeetingStatesCompletion(g)},[sn.MONITOR_COMPLETION]:g=>{this.handleUpdateMonitorSessionCompletion(g)}},A={[rn.CONTROL_VIDEO_STREAMING]:g=>{this.webRtcSignalingManager.handleControlVideoStreaming(g)},[rn.DOMINANT_SPEAKER_INFO]:g=>{this.webRtcSignalingManager.handleDominantSpeakerInfo(g)},[rn.CSRC_INFO]:g=>{this.webRtcSignalingManager.handleCsrcInfo(g)},[rn.CONV_ROSTER_UPDATE]:g=>{this.handleRosterUpdate(g,!1)},[rn.NEW_MEDIA_OFFER]:g=>{this.handleNewMediaOffer(g)},[rn.CONV_ADD_PARTICIPANT_SUCCESS]:g=>{this.participantManager.handleAddParticipantSuccess(g)},[rn.CONV_ADD_PARTICIPANT_FAILURE]:g=>{this.participantManager.handleAddParticipantFailure(g)},[rn.CONV_ADMIT_PARTICIPANT_SUCCESS]:g=>{this.participantManager.handleAdmitParticipantSuccess(g)},[rn.CONV_ADMIT_PARTICIPANT_FAILURE]:g=>{this.participantManager.handleAdmitParticipantFailure(g)},[rn.CONV_ADMIT_ALL_STATUS]:g=>{this.handleAdmitAllStatus(g)},[rn.CONV_REMOVE_PARTICIPANT_SUCCESS]:g=>{this.participantManager.handleRemoveParticipantSuccess(g)},[rn.CONV_REMOVE_PARTICIPANT_FAILURE]:g=>{this.participantManager.handleRemoveParticipantFailure(g)},[rn.CONV_CONFIRM_UNMUTE]:g=>{this.participantManager.handleUnmuteConfirmRequest(g)},[rn.CONV_UPDATE]:g=>{this.handleConversationUpdate(g)},[rn.CONV_LOCAL_PARTICIPANT_UPDATE]:g=>{this.handleLocalParticipantUpdate(g)},[rn.CONV_ADD_MODALITY_SUCCESS]:g=>{this.handleAddModalitySuccess(g)},[rn.CONV_ADD_MODALITY_FAILURE]:g=>{this.handleAddModalityFailure(g)},[rn.CONV_BROADCAST_UPDATE]:g=>{this.broadcastSession.handleBroadcastStateChanged(g)},[rn.CONV_CONTENT_SHARING_UPDATE]:g=>{this.contentSharingManager?.handleContentSharingUpdate(g)},[rn.CONV_CONTENT_SHARING_END]:g=>{this.contentSharingManager?.handleContentSharingEnd(g)},[rn.CONV_END]:g=>{this.handleCallEnd(g,!1)},[rn.CONV_END_JOIN]:g=>{this.handleCallEnd(g,!1)},[rn.CONV_END_SUBSCRIBE]:g=>{this.handleCallEnd(g,!0)},[rn.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS]:g=>{this.participantManager.handleUpdateParticipantInterpretationStateCompletion(g)},[rn.UPDATE_PARTICIPANT_PROPERTIES_STATUS]:g=>{this.handleUpdateParticipantsPropertiesCompletion(g)},[rn.JOIN_MEETING_GROUP_STATUS]:g=>{this.handleJoinMeetingGroupCompletion(g)},[rn.LEAVE_MEETING_GROUP_STATUS]:g=>{this.handleLeaveMeetingGroupCompletion(g)},[rn.RECEIVE_MESSAGE]:g=>{this.handleReceiveMessage(g)},[rn.SEND_MESSAGE_STATUS]:g=>{this.proxiedMessageNotificationManager.handleProxiedMessageNotification(g)},[rn.DISABLE_PREHEAT_ASYNC_STATUS]:g=>{this.handleDisablePreheatCompletion(g)},[rn.MUTE_UNMUTE_ASYNC]:g=>{this.participantManager.handleMuteUnmuteAsyncResponse(g)}};try{const g=Object.keys(b).filter((g=>C.hasOwnProperty(g)))[0],f=this.signalingAgentConfig.enableSplitConversationEndUrl&&(stringEndsWith(T.url,rn.CONV_END_JOIN)||stringEndsWith(T.url,rn.CONV_END_SUBSCRIBE))?Object.keys(A).filter((g=>T.url&&stringEndsWith(T.url,g)))[1]:Object.keys(A).filter((g=>T.url&&stringEndsWith(T.url,g)))[0];g?b[g](T):f?A[f](T):(this.telemetryHelper.recordEvent(dn.UNKNOWN_MESSAGE_TYPE,{messageId:S}),this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=received unknown message]`)),v.resolve(!0)}catch(g){this.telemetryHelper.recordEvent(dn.FAILED_TO_HANDLE_MESSAGE,{messageId:S,error:getPrintableObject(g)}),this.logger.info(`[${I}][handleIncomingMsgAsync][failed][reason=${g.message}]`),v.reject(new Error(g.message))}return v.promise},this.canHandleIncomingMsgSync=g=>{if(this.signalingAgentConfig.supportsSynchronousTrouterResponse){const f=g.body;return Boolean(f.callAcceptance)}return!1},this.handleIncomingMsgSync=g=>{const f=extractMessageIdFromMessage(g),S=g.body,v=g.url,C=an.INCOMING_MESSAGE_ORIGIN.TROUTER,_={...g,origin:C},T=extractCauseIdFromMessage(_);this.logger.info(`[${T}][handleIncomingMsgSync][url=${v}][messageId=${f}]`);const I=_.headers;let b=an.HTTP_STATUS_CODES.OK,A="";const P=new ln;if(isDuplicateMessage(I,this.incomingTrouterMessagesSeenSoFar)){this.logger.info(`[${T}][handleIncomingMsgSync][failed][reason=duplicate]`);const g=getMessageResultFromCache(I,this.incomingMessageSyncResponseCache);if(g)return this.logger.info(`[${T}][handleIncomingMsgSync][cachedResponse]`),g;this.telemetryHelper.recordEvent(dn.DUPLICATE_MESSAGE_IGNORED,{origin:C,messageId:f,causeId:T}),this.logger.info(`[${T}][handleIncomingMsgSync][failed][reason=cachedResponseNotFound]`),b=an.HTTP_STATUS_CODES.BAD_REQUEST}else if(S){if(S.callAcceptance)try{A=safeJsonStringify(this.handleCallAcceptanceSync(_))}catch(g){this.telemetryHelper.recordEvent(dn.FAILED_TO_HANDLE_MESSAGE,{messageId:f,origin:C,causeId:T,error:getPrintableObject(g)}),this.logger.info(`[${T}][handleIncomingMsgSync][failed][reason=${g?.message}]`),b=an.HTTP_STATUS_CODES.BAD_REQUEST}}else this.logger.info(`[${T}][handleIncomingMsgSync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(dn.MESSAGE_MISSING_BODY,{origin:C,messageId:f,causeId:T}),b=an.HTTP_STATUS_CODES.BAD_REQUEST;I&&(I.get(an.HEADERS.CORRELATION_ID)&&P.set(an.HEADERS.CORRELATION_ID,I.get(an.HEADERS.CORRELATION_ID)),I.get(an.HEADERS.MESSAGE_ID)&&P.set(an.HEADERS.MESSAGE_ID,I.get(an.HEADERS.MESSAGE_ID)));const R={resultCode:b,responseBody:A,responseHeaders:P.getAll()};return cacheMessageResult(I,this.incomingMessageSyncResponseCache,R),this.logger.info(`[${T}][handleIncomingMsgSync][success][resultCode=${b}]`),R},this.acceptRenegotiationAsync=(g,f,S=causeId2())=>(assertNotNull(g.blob,"finalSdp should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${S}][acceptRenegotiationAsync][mediaTypes=${f}]`),this.mediaRenegotiationManager.acceptRenegotiationAsync(g,f,S)),this.setProvisionalAnswerAsync=(g,f=causeId2())=>{assertNotNull(g.blob,"sdp should be a non null value"),this.telemetryHelper.recordEvent(dn.SET_PROVISIONAL_ANSWER,{causeId:f});const S=defer();return this.fsmState!==an.SIGNALING_FSM_STATE.INCOMING?(this.logger.info(`[setProvisionalAnswerAsync][${f}] there is no incoming call to set provisional answer on.`),S.reject(new Error("there is no incoming call to set provisional answer on.")),S.promise):(this.http.sendPostRequest({url:this.links[an.LINKS.MEDIA_ANSWER],requestName:hn.SEND_MEDIA_ANSWER.name,payload:getPayload57(this,g),causeId:f}).then((g=>{this.disposed||this.onCallStatusChanged(an.CALL_STATUS.CONNECTING,f),S.resolve(null),this.disposed||(this.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_ACKNOWLEDGEMENT,{causeId:f}),this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(an.CALL_STATUS.RINGING,f),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!1,f))})).catch((g=>{const v=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[setProvisionalAnswerAsync][${f}] error: ${getPrintableObject(v)}`),this.disposed?S.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent(dn.SET_PROVISIONAL_ANSWER_FAILED,{causeId:f}),S.reject(v.error))})),S.promise)},this.startRenegotiationAsync=(g,f,S=causeId2())=>(assertNotNull(g,"mediaContent should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${S}][startRenegotiationAsync]`),this.mediaRenegotiationManager.startRenegotiationAsync(g,this.links[an.LINKS.MEDIA_RENEGOTIATION],f,S)),this.updateMediaDescriptionsAsync=(g=causeId2(),f)=>{assertNotNull(f,"mediaDescriptions should be a non null value"),assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"updateMediaDescriptions operations are only allowed when the call is connected");const S=this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS];return assertNotNull(S,"updateMediaDescriptionsUrl should be a non null value"),this.telemetryHelper.recordEvent(dn.UPDATE_MEDIA_DESCRIPTIONS,{causeId:g}),this.http.sendPostRequest({url:S,requestName:hn.UPDATE_MEDIA_DESCRIPTIONS.name,payload:getPayload58(this,f),causeId:g}).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingAgentConfig);return this.logger.info(`[updateMediaDescriptionsAsync][${g}] error: ${getPrintableObject(S)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent(dn.UPDATE_MEDIA_DESCRIPTIONS_FAILED,{causeId:g}),Promise.reject(S.error))}))},this.acceptAsync=(g,f,S,v=causeId2())=>{assertNotNull(g,"mediaContent should be a non null value"),assertNotNull(g.blob,"outgoingSdp should be a non null value"),this.logger.info(`[${v}][acceptAsync][mediaTypes=${f}]`),this.telemetryHelper.recordEvent(dn.ACCEPT_CALL,{causeId:v}),this.telemetryHelper.setAnsweredModalities(g.blob);const C=defer();return this.fsmState!==an.SIGNALING_FSM_STATE.INCOMING?(this.logger.warn("acceptAsync, there is no incoming call to accept"),C.reject(new Error("there is no incoming call to accept")),C.promise):(this.fsmState=an.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK,this.http.sendPostRequest({url:this.links[an.LINKS.ACCEPT],requestName:hn.SEND_ACCEPTANCE.name,payload:getPayload29(this,g,f,S),causeId:v}).then((g=>{this.disposed||(this.currentCallStatus===an.CALL_STATUS.IDLE&&(this.telemetryHelper.setTimeToRingDuration(),this.telemetryHelper.recordEvent(dn.ACCEPTED_BEFORE_RINGING,{causeId:v}),this.onCallStatusChanged(an.CALL_STATUS.CONNECTING,v)),g.response.callAcceptanceAcknowledgement&&(this.logger.info("acceptAsync, handling inlined callAcceptanceAcknowledgement"),this.internalHandleCallAcceptanceAck(g.response,v))),C.resolve(null)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[acceptAsync][${v}] error: ${getPrintableObject(f)}`),this.disposed?C.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=an.SIGNALING_FSM_STATE.INCOMING,this.telemetryHelper.recordEvent(dn.ACCEPT_CALL_FAILED,{causeId:v,xhrError:f}),C.reject(f.error))})),C.promise)},this.rejectRenegotiationAsync=(g,f=causeId2())=>(assert2(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED,"Renegotiation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${f}][rejectRenegotiationAsync][rejectionData=${g}]`),this.mediaRenegotiationManager.rejectRenegotiationAsync(g,f)),this.saveMediaControllerLinksIfAny=g=>{g.links&&(this.links[an.LINKS.CONTROL_VIDEO_STREAMING]=g.links.controlVideoStreaming||this.links[an.LINKS.CONTROL_VIDEO_STREAMING],this.links[an.LINKS.APPLY_CHANNEL_PARAMETERS]=g.links.applyChannelParameters||this.links[an.LINKS.APPLY_CHANNEL_PARAMETERS])},this.getInitialMediaOfferFromIncomingCallPayload=(g=causeId2())=>{if(!this.signalingAgentConfig.handleMediaOfferFromPushNotification)return null;const f=this.incomingCallPayload?.callNotification?.mediaContent?this.incomingCallPayload.callNotification.mediaContent:null;return this.telemetryHelper.setIsSdpInCallNotification(!!f),f},this.updateCorrelationId=(g,f=causeId2())=>{if(this.logger.info(`[${f}][updateCorrelationId][old=${this.correlationId}][new=${g}]`),this.correlationId!==g&&!this.disposed){const S=this.correlationId;this.correlationId=g,this.telemetryHelper&&this.telemetryHelper.recordEvent&&this.telemetryHelper.recordEvent(dn.CORRELATION_ID_UPDATED,{newId:this.correlationId,oldId:S,causeId:f}),this.signalingSessionCallback&&this.signalingSessionCallback.onCorrelationIdUpdated&&this.signalingSessionCallback.onCorrelationIdUpdated(this.correlationId,f)}},this.endIncomingCallBecauseOfInvalidPayload=g=>{this.logger.info(`[${g}][endIncomingCallBecauseOfInvalidPayload]`),this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const f={code:an.CALL_END_CODE.BAD_REQUEST,subCode:an.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD,phrase:an.CALL_END_PHRASE.BAD_NOTIFICATION_PAYLOAD,resultCategories:[Xi.UnexpectedServerError]};this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:f.code,endSubCode:f.subCode,resultDetail:f.phrase||"EndIncomingCall",resultCategories:f.resultCategories,causeId:g}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,g,f),this.dispose(f,g)},this.isDuplicatedIncomingMessage=g=>g.origin===an.INCOMING_MESSAGE_ORIGIN.BROKER&&isDuplicateMessage(g.headers,this.incomingBrokerMessagesSeenSoFar)||g.origin===an.INCOMING_MESSAGE_ORIGIN.TROUTER&&isDuplicateMessage(g.headers,this.incomingTrouterMessagesSeenSoFar),this.getEndpointState=()=>{let g;return g=this.startOrJoinConvResponseReceived?{...this.latestEndpointState}:{...this.requestedEndpointStateWhileConnecting},g},this.setMultiParty=(g,f)=>{const S=!!g;this.multiParty!==S&&(this.telemetryHelper.recordEvent(dn.SET_MULTIPARTY,{isMultiparty:S,causeId:f}),this.multiParty=S)},this.setupTrouterChannel=()=>{this.logger.info(`Broker config: outgoing=${this.signalingAgentConfig.brokerEnabledOutgoing?"enabled":"disabled"}incoming=${this.signalingAgentConfig.brokerEnabledIncoming?"enabled":"disabled"}batching=${this.signalingAgentConfig.brokerRequestBatching?"enabled":"disabled"}exclusive=${this.signalingAgentConfig.brokerExclusively?"enabled":"disabled"}`);const setTrouterUrl=g=>{g&&"string"==typeof g&&g.trim()&&(this.baseMessagingChannelUrl=this.previousTrouterUrl=this.currentTrouterUrl=g.trim(),this.telemetryHelper.addTrouterChannel())};this.brokerExclusiveEnabled()||(this.signalingAgentConfig.trouterServiceProvider?(2===this.signalingAgentConfig.trouterServiceProvider.state()&&this.signalingAgentConfig.trouterServiceProvider.getTrouterUrlAsync().then(setTrouterUrl),this.signalingAgentConfig.trouterServiceProvider.onStateChanged(this.onTrouterStateChanged)):(setTrouterUrl(this.signalingAgentConfig.trouterUrlGetter.trouterUrl()),this.signalingAgentConfig.trouterUrlGetter.trouterUrl.changed(this.onTrouterUrlChanged)))},this.isTrouterDisconnected=()=>{try{return 3===this.signalingAgentConfig.trouterServiceProvider.state()}catch(g){return!1}},this.forceTrouterConnectionCheck=()=>{try{return void this.signalingAgentConfig.trouterServiceProvider.checkConnection(!1)}catch(g){return}},this.navigatorOnlineCallback=()=>{this.disposed||(this.reportConnectivityStatus(),this.isTrouterDisconnected()&&this.signalingAgentConfig.forceTrouterReconnectOnNetworkOnline&&this.forceTrouterConnectionCheck())},this.navigatorOfflineCallback=()=>{this.reportConnectivityStatus()},this.reportConnectivityStatus=()=>{if(!this.disposed){const g=isTrouterAndNavigatorConnected(this.signalingAgentConfig.trouterServiceProvider);this.logger.info(`[Connectivity] status=${g}`),this.telemetryHelper.recordEvent(dn.CONNECTIVITY_CHANGED,{status:g})}},this.onTrouterStateChanged=(g,f)=>{const S=causeId2();this.logger.info(`[${S}][onTrouterStateChanged][state=${g}]`),this.disposed?this.logger.info("onTrouterStateChanged ignored"):(this.reportConnectivityStatus(),2===g&&(this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter(dn.TROUTER_STATE_CHANGED,S)))},this.setupConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.addEventListener&&(window.addEventListener("online",this.navigatorOnlineCallback),window.addEventListener("offline",this.navigatorOfflineCallback))}catch(g){return}},this.tearDownConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.removeEventListener&&(window.removeEventListener("online",this.navigatorOnlineCallback),window.removeEventListener("offline",this.navigatorOfflineCallback))}catch(g){return}},this.getTrouterUrlAsync=()=>this.signalingAgentConfig.trouterServiceProvider?this.signalingAgentConfig.trouterServiceProvider.getTrouterUrlAsync():this.signalingAgentConfig.trouterUrlGetter.getTrouterUrlAsync(),this.brokerExclusiveEnabled=()=>this.signalingAgentConfig.brokerEnabledOutgoing&&this.signalingAgentConfig.brokerEnabledIncoming&&this.signalingAgentConfig.brokerExclusively,this.isBrokerEnabledForOutgoingCall=()=>this.signalingAgentConfig.brokerEnabledOutgoing,this.isBrokerEnabledForIncomingCall=()=>this.signalingAgentConfig.brokerEnabledIncoming,this.setupBrokerChannel=()=>{this.brokerService||(this.logger.info("setupBrokerChannel, Enable broker"),this.brokerService=new bn(this),this.brokerService.onBrokerMessage((g=>{this.logger.info("setupBrokerChannel, message from broker",getPIISafeMessage(g)),this.handleIncomingMsgAsync(g,an.INCOMING_MESSAGE_ORIGIN.BROKER).catch((g=>{this.telemetryHelper.recordEvent(dn.FAILED_TO_HANDLE_BROKER_MESSAGE),this.logger.info("setupBrokerChannel, Failed to handle message from broker",g)}))})),this.baseMessagingChannelUrl||(this.telemetryHelper.addBrokerChannel(),this.baseMessagingChannelUrl=this.brokerService.baseUrl))},this.onTrouterUrlChanged=()=>{const g=causeId2();this.logger.info(`[${g}][onTrouterUrlChanged]`),this.disposed?this.logger.info("onTrouterUrlChanged ignored"):this.getTrouterUrlAsync().then((f=>{this.telemetryHelper.recordEvent(dn.TROUTER_URL_CHANGED,{url:f}),this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter(dn.TROUTER_URL_CHANGED,g)})).catch((g=>{this.logger.info(`Failed to update links to trouter: ${g}`)}))},this.updateLinksToTrouter=(g,f)=>{this.logger.info(`[${f}][updateLinksToTrouter][tag=${g}]`),this.ensureLatestTrouterUrl(g).then((()=>{this.previousTrouterUrl!==this.currentTrouterUrl?(this.previousTrouterUrl=this.currentTrouterUrl,this.updateConversationLinks(),this.updateKeepAliveUrl(),this.contentSharingManager?.updateContentSharingNotificationLinksAsync(f),this.broadcastSession&&this.broadcastSession.updateBroadcastCallbackUrl(f)):this.logger.info(`[${f}][updateLinksToTrouter]skip updating links, url did not change`)})).catch((g=>{this.disposed||this.telemetryHelper.recordEvent(dn.TROUTER_URL_UPDATE_FAILED,{causeId:f}),this.logger.info(`[${f}][updateLinksToTrouter][failed][reason=${getPrintableObject(g)}]`)}))},this.updateLinks=(g,f)=>{this.ensureLatestTrouterUrl(dn.TROUTER_URL_CHANGED).then((()=>{g(f)})).catch((g=>{this.disposed||this.telemetryHelper.recordEvent(dn.TROUTER_URL_UPDATE_FAILED,{causeId:f}),this.logger.warn("Failed to update links")}))},this.startCallPreheatTimer=g=>{this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT,(()=>{this.handleCallEstablishmentTimeout(g,an.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,"Preheat timed out!"),this.terminateEstablishedCall({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,phrase:"Preheat timed out!"},{forEveryone:!1,causeId:g})}),an.TIMEOUT_VALUES_IN_SECONDS.MAX_PREAHEATED_TIMEOUT)},this.stopCallPreheatTimer=()=>{this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT)},this.updateKeepAliveUrl=()=>{this.logger.info("updateKeepAliveUrl"),this.links.hasOwnProperty(an.LINKS.KEEPALIVE)?(this.linkUpdateRequested.keepAliveLinks=!1,this.logger.info("updateKeepAliveUrl, sending request"),this.sendToKeepAliveUrl(getPayload41(this))):this.linkUpdateRequested.keepAliveLinks=!0},this.updateConversationLinks=(g=causeId2())=>{this.logger.info(`[${g}][updateConversationLinks]`),this.telemetryHelper.recordEvent(dn.UPDATE_CONVERSATION_LINKS,{causeId:g}),this.links.hasOwnProperty(an.LINKS.NOTIFICATION_LINKS)?(this.linkUpdateRequested.conversationLinks=!1,this.logger.info("updateConversationLinks, sending request"),this.sendToUpdateConversationLinks(!0)):this.linkUpdateRequested.conversationLinks=!0},this.sendAttachToCallInternal=(g=causeId2())=>{this.telemetryHelper.recordEvent(dn.SEND_ATTACH,{causeId:g}),this.logger.info(`[${g}][sendAttachToCallInternal]`);const f=new ln;return this.signalingAgentConfig.sendProgressFromCC&&f.set(an.HEADERS.CACHE_SKYPE_TOKEN,"1"),this.http.sendPostRequest({url:this.incomingCallPayload.callNotification.links.attach,customHeaders:f,requestName:hn.SEND_CALL_ATTACH.name,payload:getPayload27(this,this.incomingCallPayload.conversationInvitation.conversationController,!this.getInitialMediaOfferFromIncomingCallPayload()),causeId:g}).then((f=>{if(!this.disposed){this.processAttachResponse(this.incomingCallPayload,f,g);const S=f.response.additionalActionResponses;S&&S.length>0&&this.processConversationServiceResponse(S[0].output,g,0),this.onCallStatusChanged(an.CALL_STATUS.RINGING,g),this.telemetryHelper.setTimeToRingDuration(),this.handleBrokerSubscription(f.response.callInvitation,g)}})).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingAgentConfig);this.logger.info(`[${g}][sendAttachToCallInternal] error: ${getPrintableObject(f)} xhrError: ${getPrintableObject(S)}`),this.disposed||(this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:S.telemetryEndSubCode,endSubCode:S.error.subCode,resultCategories:S.error.resultCategories,resultDetail:S.error.phrase||"SendAttachtoCallFailure",causeId:g}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,g,S.error),this.dispose(S.error,g))}))},this._processCallAcceptance=(g,f)=>{if(this.logger.info(`[${f}][_processCallAcceptance]`),this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING){this.processCallAcceptance(g.body,f),this.telemetryHelper.setTimeToRingDuration();try{this.multiParty||this.callUsesMixer||this.participantManager.handleRosterUpdate(this.getFakeRoster(g.body),!0,f)}catch(S){const v={code:an.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:an.CALL_END_SUB_CODE.CALL_ACCEPTANCE_INVALID_SERVICE_RESPONSE,phrase:S?.toString()};throw this.logger.info(`[${f}][_processCallAcceptance] ${safeJsonStringify(v)}`),this.telemetryHelper.recordRosterEvent(g,dn.HANDLE_ROSTER_UPDATE_FAIL,f),v}}},this.restartKeepAliveInterval=(g,f=!1,S)=>{this.disposed||(window.clearInterval(this.keepAliveTimer),f&&(this.telemetryHelper.recordEvent(dn.SEND_KEEP_ALIVE_FAILED,S),S?.code===an.RESOURCE_NOT_FOUND_ERROR.code)?this.logger.info(`[${g}][restartKeepAliveInterval] keepAlive stopped since last request returned NOT_FOUND.`):this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval))},this.isCallOngoing=()=>this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===an.SIGNALING_FSM_STATE.IDLE,this.isCallIdleOrRosterOnly=()=>this.fsmState===an.SIGNALING_FSM_STATE.IDLE||this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,this.isCallConnectedOrConnectedForRoster=()=>this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,_&&(this.callStartTime=_),this.signalingSessionCallback=f,this.signalingAgentConfig=S,this.signalingAgent=C,this.urlIdentifier=v,this.piiUtils=new vn(S.piiScrubber),this.isHostLessCall=S.doHostlessCalling||!1,this.logger=S.logger.createChild((()=>`CSA[${this.correlationId}][${this.fsmState}]`),this.correlationId,!0),this.updateCorrelationId(v),this.logger.info(`[endpointId=${truncate(this.signalingAgent.endpointId,8)}]`),this.logger.info(`[participantId=${g.participantId}]`),this.callOperationHandler=new Pn(this.logger.createChild((()=>`[CallOperationHandler][${g.participantId}]`))),this.http=new Hn(this,this.callStartTime),this.telemetryHelper=new Zn(this,g,this.callStartTime),this.mediaRenegotiationManager=new $n(this,f,this.telemetryHelper),this.participantManager=new zn(this,f,g,new Ge(this.logger)),this.proxiedMessageNotificationManager=new Kn(this),this.timeoutManager=new pn(this.logger),this.contentSharingManager=new wn(this,f),this.webRtcSignalingManager=new er(this,f),this.pstnContent={emergencyCallCountry:S.emergencyCallCountry||"",platformName:S.clientInformation,publicApiCall:!1},this.setupTrouterChannel(),this.setupConnectionCheck()}onPromotionCompleted(g,f,S){this.logger.info(`[${S}][onPromotionCompleted] isFailed=${g} error=${getPrintableObject(f)}]`),this.isPromotingToRealtime=!1,this.signalingSessionCallback.onPromotionCompleted(g,f,S)}setRealTimeState(g,f){let S=g;(2===g&&1===this.realTimeState||1===g&&2===this.realTimeState)&&(S=3),S!==this.realTimeState&&(this.logger.info(`[${f}][setRealTimeState] changed: input=${g} old=${this.realTimeState}, new=${S}`),this.realTimeState=S,3===S?this.setCallMode(1,f):0!==this.callMode||2!==S&&(this.signalingAgentConfig.disableRealTimeModeFromRoster||1!==S)||this.setCallMode(1,f))}setCallMode(g,f){this.callMode!==g&&(this.logger.info(`[${f}][setCallMode] oldMode=${this.callMode}, newMode=${g}`),this.callMode=g,this.signalingSessionCallback.onCallModeChanged(this.callMode,f))}configureStreamingMode(g){2!==this.callMode?(this.logger.info(`[${g}][configureStreamingMode]`),this.setCallMode(2,g),this.cleanUpDueToStreaming(g),this.onCallStatusChanged(an.CALL_STATUS.CONNECTED,g)):this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT)}updateDominantSpeakerHistoryMessageSubscription(g){this.webRtcSignalingManager.getIsDominantSpeakerInfoLinkEnabled()!==g&&(this.logger.info(`Signaling dominant speaker history subscription updated: ${g}`),this.webRtcSignalingManager.setIsDominantSpeakerInfoLinkEnabled(g),this.webRtcSignalingManager.areClientURLsGenerated()&&this.updateKeepAliveUrl())}cleanUpDueToStreaming(g){this.setRealTimeState(0,g),this.fsmState=an.SIGNALING_FSM_STATE.CONNECTED,this.isPromotingToRealtime=!1,this.provisionalMediaAnswersSeenSoFar=[],this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=new $n(this,this.signalingSessionCallback,this.telemetryHelper),this.keepAliveTimer&&window.clearInterval(this.keepAliveTimer),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const f={code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.DOWNGRADE_TO_STREAMING_CLIENT,phrase:an.CALL_END_PHRASE.DOWNGRADE_TO_STREAMING_CLIENT},S=hn;for(const v of Object.keys(S))0!==S[v].controller&&4!==S[v].controller&&3!==S[v].controller||this.http.cancelRequestIfPending(S[v].name,g,void 0,f)}updateEndpointMetadata(g,f=causeId2()){let S={};try{S=JSON.parse(g)}catch(g){return Promise.reject("Invalid metadata")}return this.http.sendPutRequest({url:this.links[an.LINKS.UPDATE_ENDPOINT_METADATA],requestName:hn.UPDATE_ENDPOINT_METADATA.name,payload:getPayload51(this,S),causeId:f}).then((()=>{this.telemetryHelper.recordEvent(dn.UPDATE_ENDPOINT_METADATA_SUCCESS,{causeId:f})})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[${f}][updateEndpointMetadata] error: ${getPrintableObject(S)}`),this.telemetryHelper.recordEvent(dn.UPDATE_ENDPOINT_METADATA_FAILURE,{...S.error}),Promise.reject(S.error)}))}isOneToOnePSTNCall(){return this.signalingSessionCallback.isOneToOnePstnCall()}getLocationContent(){return this.isOneToOnePSTNCall()?tryParse(this.locationInfoContent):null}getNetworkContent(){return this.isOneToOnePSTNCall()?tryParse(this.networkInfoContent):null}getAreaContent(){return this.isOneToOnePSTNCall()?tryParse(this.areaContent):null}setLocationInfo(g,f,S){this.locationInfoContent=g,this.networkInfoContent=f,this.areaContent=S}setStreamInformationReceived(){this.disposed||this.streamInformationReceived||(this.streamInformationReceived=!0,this.telemetryHelper.recordEvent(dn.SET_STREAM_INFORMATION_RECEIVED))}getEndpointCapabilities(){let g=0;return this.signalingAgentConfig.brokerEnabledIncoming&&(g|=16),this.signalingAgentConfig.isGVCJoiningEnabled&&(g|=1),"disabled"!==this.signalingAgentConfig.cloudScreenSharingFlag&&(g|=2),this.signalingAgentConfig.supportsHostlessGroupCalls&&(g|=4),this.signalingAgentConfig.autoJoinOnConflict&&(g|=32),this.signalingAgentConfig.supportsCompressedServicePayload&&(g|=128),this.signalingAgentConfig.enableAutoPromotion&&(g|=65536),this.signalingAgentConfig.enableBatchedSendMessageStatus&&(g|=16384),this.signalingAgentConfig.enableBatchedReceiveMessage&&(g|=8192),g|=64,g|=1024,this.signalingAgent?.accountConfig?.clientSupportsAudioOnlyWatermark&&(g|=4096,this.telemetryHelper.setAudioOnlyWatermark(!0)),this.signalingAgent?.accountConfig?.clientSupportsWatermark&&(g|=2048,this.telemetryHelper.setWatermarkSupport(!0)),this.signalingAgent?.accountConfig?.clientSupportsPreventScreenCapture&&(g|=131072,this.telemetryHelper.setClientSupportsPreventScreenCapture(!0)),(this.getMaxReinvitelessMediaForVBSSForWeb()||this.getMaxReinvitelessMediaForVideoForWeb())&&(this.telemetryHelper.setReinviteless(this.callUsesMixer),g|=512),g}handleAdmitAllStatus(g){const f=g.body?.transactionResponse,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAdmitAllStatus][${getPrintableObject(f)}]`);const v=f?.operationId;if(v&&this.callOperationHandler.hasPendingOperation(0,v,S)){this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT,v);const g=f?.result?.code,C=f?.result?.subCode,_=f?.result?.resultCategories,T=f?.additionalDetail;if(0===g||g>=200&&g<300){const f={code:g,subCode:C,resultCategories:_,result:safeJsonStringify(T)};this.telemetryHelper.recordEvent(dn.ADMIT_SUCCESS,{causeId:v,transactionEnd:f}),this.callOperationHandler.resolvePendingOperation(0,v,f,S)}else{const T={code:g||an.CALL_END_CODE.BAD_REQUEST,subCode:C||0,resultCategories:_,result:f,phrase:an.CALL_END_PHRASE.BAD_SERVICE_RESPONSE};this.telemetryHelper.recordEvent(dn.ADMIT_FAILURE,{causeId:v,transactionEnd:T}),this.callOperationHandler.rejectPendingOperation(0,v,"AdmitAllStatus response contains failure",T,S)}}else this.logger.warn(`[${S}][handleAdmitAllStatus] invalid admitAllStatus response or no pending operation. operationId=${v}`)}sendNetworkRequestForAdmit(g){const onceTrouterReady=()=>{this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.ADMIT,(()=>{this.telemetryHelper.recordEvent(dn.ADMIT_TIMEOUT,{causeId:g}),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT,g),this.callOperationHandler.rejectPendingOperation(0,g,"timed out waiting for admit operation",{code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.ADMIT_TIMEOUT,phrase:an.CALL_END_PHRASE.ADMIT_TIMEOUT},g)}),an.TIMEOUT_VALUES_IN_SECONDS.ADMIT_TIMEOUT,g)};this.http.sendPostRequest({url:this.links[an.LINKS.ADMIT_ALL],requestName:hn.ADMIT.name,payload:getPayload26(this,g),causeId:g,onceTrouterReady:onceTrouterReady}).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingAgentConfig);this.telemetryHelper.recordEvent(dn.ADMIT_FAILURE,{causeId:g,...S.error}),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.ADMIT,g),this.callOperationHandler.rejectPendingOperation(0,g,f,S.error,g)}))}getConversationType(g,f,S){return g?"emergencyGroupCall":f?"cast":S?"huddleGroupCall":null}getMaxReinvitelessMediaForVideoForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVideoForWeb}getMaxReinvitelessMediaForVBSSForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVBSSForWeb}convertParkType(g){return"teamPark"===g?"TransferTypeTeamPark":"sharedLinePark"===g?"TransferTypeSharedLinePark":"serverHold"===g?"TransferTypeServerHold":(this.logger.info(`convertParkType, parkType: ${g} is unknown`),"none")}parkByTransfer(g,f){this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(f)}),an.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT);const S=this.getNetworkRequestName(g);return this.http.sendPostRequest({url:this.links[an.LINKS.TRANSFER],requestName:S,payload:getPayload39(g,this),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[${f}][parkByTransfer] error: ${getPrintableObject(S)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:an.CALL_END_CODE.NETWORK_ERROR,reason:getPrintableObject(g)}},f),this.telemetryHelper.recordEvent(dn.TRANSFER_REQUEST_FAILED,{causeId:f,...S.error}),Promise.reject(S.error))})),this.telemetryHelper.recordEvent(dn.TRANSFER_REQUEST_SENT,{causeId:f,transferType:this.convertParkType(g)}),Promise.resolve()}park(g,f){this.logger.info(`[${f}][park] context ${g}`),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.PARK_COMPLETION,(()=>{this.handleParkError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.PARK_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.PARK_COMPLETION_TIMEOUT},dn.WAITING_FOR_PARK_COMPLETION_TIMEOUT,f,g)}),an.TIMEOUT_VALUES_IN_SECONDS.PARK_COMPLETION_TIMEOUT);const S=this.getHoldTypeInRequest(g),v={causeId:f};return this.http.sendPostRequest({url:this.links[an.LINKS.PARK],requestName:hn.PARK_REQUEST.name,payload:getPayload40(this,S,v),causeId:f}).then((g=>{this.logger.info(`[${f}][park] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_PARK_COMPLETION,{causeId:f}),assertNotNull(g.response.holdResponse.links,"server response does not include park links"),this.links[an.LINKS.UNPARK]=g.response.holdResponse.links.resume})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${f}][park] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleParkError(v.error,dn.PARK_REQUEST_FAILED,f,g),Promise.reject(v.error))})),Promise.resolve()}getHoldTypeInRequest(g){switch(g){case"serverHoldV2":return"musicOnHold";case"sharedLineParkV2":return"sharedLineAppearance";case"callPark":return"callPark";default:return null}}handleParkError(g,f,S,v){this.disposed?this.logger.info("handleParkError ignored"):(this.logger.info(`[${S}] handleParkError reject reason: ${getPrintableObject(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.PARK_COMPLETION),this.signalingSessionCallback.onParkCompleted&&(this.telemetryHelper.recordEvent(f,{...g,parkContext:v,causeId:S}),this.signalingSessionCallback.onParkCompleted(g,S)),this.links[an.LINKS.UNPARK]=void 0)}handleParkCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.holdCompletion;this.handleOperationCompletionCommon(v,S,void 0,getPrintableObject(f),"handleParkCompletion",an.TIMEOUT_OPERATIONS.PARK_COMPLETION,dn.PARK_COMPLETED,dn.PARK_FAILED,this.signalingSessionCallback.onParkCompleted,this.handleParkError.bind(this))}handleUnparkError(g,f,S,v){this.disposed?this.logger.info("handleUnparkError ignored"):(this.logger.info(`[${S}] handleUnparkError reject reason: ${g}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.signalingSessionCallback.onUnparkCompleted&&(this.telemetryHelper.recordEvent(f,{...g,parkContext:v,causeId:S}),this.signalingSessionCallback.onUnparkCompleted(g,S)),this.links[an.LINKS.UNPARK]=void 0)}handleUnparkCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g);if(this.disposed)return void this.logger.info(`[${S}]handleUnparkCompletion ignored`);this.logger.info(`[${S}][handleUnparkCompletion] body ${getPrintableObject(f)}`);const v=f.resumeCompletion;v.code===an.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.telemetryHelper.recordEvent(dn.UNPARK_COMPLETED,{...v,causeId:S}),this.signalingSessionCallback.onUnparkCompleted(v,S),this.links[an.LINKS.UNPARK]=void 0):this.handleUnparkError(v,dn.UNPARK_FAILED,S)}getNetworkRequestName(g){return{none:null,teamPark:hn.SEND_PARK_REQUEST.name,sharedLinePark:hn.SEND_SHARED_LINE_PARK_REQUEST.name,serverHold:hn.SEND_SERVER_HOLD_REQUEST.name}[g]}updateMeetingsGroupsAsync(g,f){this.logger.info(`[${g}][updateMeetingsGroupsAsync] scope=${f.scope}`),this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_GROUPS,{causeId:g,options:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION,(()=>{this.handleUpdateMeetingGroupsError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT},dn.WAITING_FOR_UPDATE_MEETING_GROUPS_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT);const S=getMeetingGroupsPayload(this,f,g);return this.http.sendPostRequest({url:this.links[an.LINKS.UPDATE_MEETING_GROUPS],requestName:hn.UPDATE_MEETING_GROUPS.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][updateMeetingsGroupsAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UPDATE_MEETING_GROUPS_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${g}][updateMeetingsGroupsAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingGroupsError(v.error,dn.UPDATE_MEETING_GROUPS_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}updateMonitorSessionAsync(g,f){this.logger.info(`[${f}][updateMonitorSessionAsync]`),this.telemetryHelper.recordEvent(dn.UPDATE_MONITOR_SESSION,{causeId:f,options:g}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION,(()=>{this.handleUpdateMonitorSessionError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT},dn.WAITING_FOR_UPDATE_MONITOR_SESSION_COMPLETION,f,g)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MONITOR_SESSION_COMPLETION_TIMEOUT);const S=getPayload55(this,g.monitorActionType,g.monitorData,f);return this.http.sendPostRequest({url:this.links[an.LINKS.UPDATE_MONITOR_SESSION],requestName:hn.UPDATE_MONITOR_SESSION.name,payload:S,causeId:f}).then((g=>{this.logger.info(`[${f}][updateMonitorSessionAsync] response: ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UPDATE_MONITOR_SESSION_COMPLETION,{causeId:f})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${f}][updateMonitorSessionAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMonitorSessionError(v.error,dn.UPDATE_MONITOR_SESSION_REQUEST_FAILED,f,g),Promise.reject(v.error))}))}updateParticipantInterpretationStateAsync(g,f){return assertNotNullOrEmpty(f,"options should be a non null value"),this.logger.info(`[${g}][updateParticipantInterpretationStateAsync]`),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANT_INTERPRETATION_STATE,{causeId:g,options:f}),this.participantManager.updateParticipantInterpretationStateAsync(f,this.links[an.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE],g)}async sendProxiedMessageAsync(g,f){return f&&0!==f.length?this.links[an.LINKS.SEND_MESSAGE]?this.proxiedMessageNotificationManager.sendProxiedMessageAsync(g,f,this.links[an.LINKS.SEND_MESSAGE]):Promise.reject({code:an.VALIDATION.VALIDATION_FAILED,subCode:an.VALIDATION.NULL_OR_EMPTY,phrase:"missing url for CONSTANTS.LINKS.SEND_MESSAGE"}):Promise.reject({code:an.VALIDATION.VALIDATION_FAILED,subCode:an.VALIDATION.NULL_OR_EMPTY,phrase:"options should be a non empty array"})}async updateParticipantsPropertiesAsync(g,f,S,v){this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES,{causeId:v,updateParticipantsPropertiesContext:g});const C=this.links[an.LINKS.UPDATE_PARTICIPANTS_PROPERTIES],_=[],T=g.scope;if("self"===T){const f={id:this.participantManager.localParticipant.id,propertyBag:g.propertyBag};_.push(f)}else{if("specified"!==T)return Promise.reject("This scope is not Supported");{const f=g.participants;for(const g of f){const f={id:g.id,propertyBag:g.propertyBag};_.push(f)}}}return this.sendNetworkRequestForUpdateParticipantsProperties(_,f,C,S,v)}sendNetworkRequestForUpdateParticipantsProperties(g,f,S,v,C){const _=this.logger.createChild(`[${C}][sendNetworkRequestForUpdateParticipantsProperties]`,this.correlationId);if(S){const onceTrouterReady=()=>{const g={code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT};this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,(()=>{this.handleUpdateParticipantsPropertiesOnTimeout(f,g,dn.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT,v,C)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION_TIMEOUT,v)},T=getUpdateParticipantsPropertiesPayload(this,g,v);return this.updateParticipantsPromises[v]=f,this.http.sendPostRequest({url:S,payload:T,requestName:hn.UPDATE_PARTICIPANTS_PROPERTIES.name,onceTrouterReady:onceTrouterReady,causeId:C}).then((g=>{_.info(`response: ${getPrintableObject(g)}`)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);_.info(`failed: ${getPrintableObject(f)}`);const S={...f.error};return this.disposed||(this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,v),delete this.updateParticipantsPromises[v]),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED,{causeId:C,transactionEnd:S}),Promise.reject(S)}))}{const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_LINK_MISSING,phrase:"updateParticipantsProperties link is missing"};return _.warn(g),this.telemetryHelper.recordEvent(dn.UPDATE_PARTICIPANTS_PROPERTIES_RESPONSE_FAILED,{causeId:C,error:g}),Promise.reject(g)}}checkAndCleanupPromisesForOperationId(g){this.updateParticipantsPromises[g]&&(0===this.updateParticipantsPromises[g].size?(delete this.updateParticipantsPromises[g],this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,g)):this.logger.info(`remaining promises for the operation  ${g} (count: ${this.updateParticipantsPromises[g].size}):\n                ${this.piiUtils.scrubMriOrOmit(safeJsonStringify(this.updateParticipantsPromises[g]))}`))}handleUpdateParticipantsPropertiesOnTimeout(g,f,S,v,C){if(this.disposed)return void this.logger.info("handleUpdateParticipantsPropertiesOnTimeout ignored");this.logger.createChild(`[${C}][handleUpdateParticipantsPropertiesOnTimeout]`,this.correlationId).info(`reason: ${f}`),this.telemetryHelper.recordEvent(S,{...f,causeId:C});const _={};g.forEach((g=>{_[g]=f,this.updateParticipantsPromises[v].delete(g)})),this.checkAndCleanupPromisesForOperationId(v),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(_,v,C)}joinMeetingGroupAsync(g,f){this.logger.info(`[${g}][joinMeetingGroupAsync]`),this.telemetryHelper.recordEvent(dn.JOIN_MEETING_GROUP,{causeId:g,options:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION,(()=>{this.handleJoinMeetingGroupError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.JOIN_MEETING_GROUP_TIMEOUT,phrase:an.CALL_END_PHRASE.JOIN_MEETING_GROUP_TIMEOUT},dn.WAITING_FOR_JOIN_MEETING_GROUP_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.JOIN_MEETING_GROUP_COMPLETION_TIMEOUT);const S=getJoinMeetingGroupPayload(this,f,g);return this.http.sendPostRequest({url:this.links[an.LINKS.JOIN_MEETING_GROUP],requestName:hn.JOIN_MEETING_GROUP.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][joinMeetingGroupAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_JOIN_MEETING_GROUP_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${g}][joinMeetingGroupAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleJoinMeetingGroupError(v.error,dn.JOIN_MEETING_GROUP_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}leaveMeetingGroupAsync(g,f){this.logger.info(`[${g}][leaveMeetingGroupAsync]`),this.telemetryHelper.recordEvent(dn.LEAVE_MEETING_GROUP,{causeId:g,options:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION,(()=>{this.handleLeaveMeetingGroupError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.LEAVE_MEETING_GROUP_TIMEOUT,phrase:an.CALL_END_PHRASE.LEAVE_MEETING_GROUP_TIMEOUT},dn.WAITING_FOR_LEAVE_MEETING_GROUP_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.LEAVE_MEETING_GROUP_COMPLETION_TIMEOUT);const S=getLeaveMeetingGroupPayload(this,f,g);return this.http.sendPostRequest({url:this.links[an.LINKS.LEAVE_MEETING_GROUP],requestName:hn.LEAVE_MEETING_GROUP.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][leaveMeetingGroupAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_LEAVE_MEETING_GROUP_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${g}][leaveMeetingGroupAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleLeaveMeetingGroupError(v.error,dn.LEAVE_MEETING_GROUP_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}handleUpdateMeetingGroupsError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleUpdateMeetingGroupsError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleUpdateMeetingGroupsError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,updateMeetingGroupsOptions:C,causeId:S}),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(g,S,v))}handleUpdateMeetingGroupsCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.updateMeetingGroupsResponse.operationId;if(this.disposed)return void this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] ignored. Call disposed.`);v||this.logger.warn(`[${S}][handleUpdateMeetingGroupsCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] starts`);const{updateMeetingGroupsResponse:C}=f,_=processTransactionResponse(C);_.code===an.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] update meeting group succeeded`),this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_GROUPS_RESPONSE_SUCCESS,{..._,causeId:S})):(this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] update meeting group failed code=${_.code} subCode=${_.subCode}`),this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_GROUPS_RESPONSE_FAILURE,{..._,causeId:S})),this.logger.info(`[${S}][handleUpdateMeetingGroupsCompletion] completes`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(_,S,v)}handleJoinMeetingGroupError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleJoinedMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleJoinedMeetingGroupError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,joinMeetingGroupOptions:C,causeId:S}),this.signalingSessionCallback.onJoinMeetingGroupCompleted(g,S,v))}handleJoinMeetingGroupCompletion(g){const f=g.body.joinMeetingGroupResponse,S=extractCauseIdFromMessage(g),v=f.operationId;if(this.disposed)return void this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] ignored. Call disposed.`);v||this.logger.warn(`[${S}][handleJoinMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] starts`);const C=processTransactionResponse(f);C.code===an.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] join meeting group succeeded`),this.telemetryHelper.recordEvent(dn.JOIN_MEETING_GROUP_RESPONSE_COMPLETED,{...C,causeId:S})):(this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] join meeting group failed code=${C.code} subCode=${C.subCode}`),this.telemetryHelper.recordEvent(dn.JOIN_MEETING_GROUP_RESPONSE_FAILED,{...C,causeId:S})),this.logger.info(`[${S}][handleJoinMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onJoinMeetingGroupCompleted(C,S,v)}handleLeaveMeetingGroupError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleLeaveMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleLeaveMeetingGroupError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,leaveMeetingGroupOptions:C,causeId:S}),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(g,S,v))}handleLeaveMeetingGroupCompletion(g){const f=g.body.leaveMeetingGroupResponse,S=extractCauseIdFromMessage(g),v=f.operationId;if(this.disposed)return void this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] ignored. Call disposed.`);v||this.logger.warn(`[${S}][handleLeaveMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] starts`);const C=processTransactionResponse(f);C.code===an.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] leave meeting group succeeded`),this.telemetryHelper.recordEvent(dn.LEAVE_MEETING_GROUP_RESPONSE_COMPLETED,{...C,causeId:S})):(this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] leave meeting group failed code=${C.code} subCode=${C.subCode}`),this.telemetryHelper.recordEvent(dn.LEAVE_MEETING_GROUP_RESPONSE_FAILED,{...C,causeId:S})),this.logger.info(`[${S}][handleLeaveMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(C,S,v)}handleDisablePreheatError(g,f,S){this.disposed?this.logger.info(`[${S}][handleDisablePreheatError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleDisablePreheatError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),this.telemetryHelper.recordEvent(f,{...g,causeId:S}),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject(g))}handleDisablePreheatCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.transactionEnd;if(this.disposed)this.logger.info(`[${S}][handleDisablePreheatCompletion] ignored. Call disposed.`);else if(this.disablePreheatDefer.isPending()){if(this.logger.info(`[${S}][handleDisablePreheatCompletion] starts`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),v.code===an.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${S}][handleDisablePreheatCompletion] update endpoint state succeeded`),this.handleEndpointStateUpdated(S,!0);else if(this.logger.info(`[${S}][handleDisablePreheatCompletion] update endpoint state failed code=${v.code} subCode=${v.subCode}`),this.disablePreheatDefer.isPending()){const g={response:v};this.disablePreheatDefer.reject(g)}}else this.logger.info(`[${S}][handleDisablePreheatCompletion] ignored. Disable preheat promise is resolved/rejected.`)}handleReceiveMessage(g){const f=extractCauseIdFromMessage(g);if(this.disposed)return void this.logger.info(`[${f}][handleReceiveMessage] ignored. Call disposed.`);let S;S=Array.isArray(g.body?.messageContent)?g.body.messageContent:[g.body];let v="";const C=[];for(let g=0;g<S.length;g++){const f=S[g];v+=f?.operationId,g<S.length-1&&(v+=","),C.push({operationId:f.operationId,messageType:f.type,payload:f.payload,from:{[f.from.id]:{participantLegIdMap:{[f.from.participantId]:{...f.from.endpointId&&{endpointId:f.from.endpointId}}},level:"endpoint"}}})}this.logger.info(`[${f}][handleReceiveMessage] complete. OperationIds:${v}`),this.telemetryHelper.recordEvent(dn.INCOMING_PROXIED_MESSAGES,{causeId:f,operationIds:v}),this.signalingSessionCallback.onIncomingProxiedMessages(C,f)}publishStateAsync(g,f,S,v,C,_){this.logger.info(`[${S}][publishStateAsync][publishType=${g} publishLevel=${f}]`),this.telemetryHelper.recordEvent(dn.PUBLISH_STATE,{causeId:S,publishType:g,publishLevel:f});const T=this.links[an.LINKS.PUBLISH_STATE];if(!T){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PUBLISH_STATE_LINK_MISSING,phrase:"publish state link is missing"};return this.logger.warn(g),Promise.reject(g)}let I={};try{I=JSON.parse(v)}catch(g){const f={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_CONTENT,phrase:"publish state content is invalid"};return this.logger.warn(f),Promise.reject(f)}return this.http.sendPostRequest({url:T,requestName:hn.PUBLISH_STATE.name,payload:getPayload42(this,g,f,I,C,_),causeId:S,requestId:S}).then((g=>{if(g?.response?.publishStateResponse)return this.parsePublishStateResult(g,S);{const f=`Invalid CS response which does not contains publishStateResponse. Respone: ${g?.response?JSON.stringify(g.response):"no response"}`;throw this.logger.warn(f),{response:{code:an.CALL_END_CODE.DECODING_FAILED,subCode:an.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:f}}}})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${S}][publishStateAsync] error: ${getPrintableObject(f)}`);const v=f.error;return this.telemetryHelper.recordEvent(dn.PUBLISH_STATE_FAILURE,{causeId:S,transactionEnd:v}),Promise.reject(v)}))}getPublishStateSequenceNumber(){return++this.publishStateSequenceNumber}getMonitorSequenceId(){return++this.monitorSequenceId}parsePublishStateResult(g,f){let S={};if(g?.response?.publishStateResponse){if(g.response.publishStateResponse.stateId)return g.response.publishStateResponse.stateId;if(g.response.publishStateResponse.results){if(1===g.response.publishStateResponse.results.length){if(g.response.publishStateResponse.results[0].stateId)return g.response.publishStateResponse.results[0].stateId;this.logger.warn("invalid response format")}return g.response.publishStateResponse.results.forEach((g=>{S[g.participantId]={code:g.result.code,phrase:g.result.phrase,subCode:g.result.subCode}})),JSON.stringify(S)}if(g.response.publishStateResponse.result)return S={code:g.response.publishStateResponse.result.code,phrase:g.response.publishStateResponse.result.phrase,subCode:g.response.publishStateResponse.result.subCode,result:g.response.publishStateResponse.additionalDetail},JSON.stringify(S)}const v=`Invalid CS response which does not contains publishStateResponse. Respone: ${g?.response?JSON.stringify(g.response):"no response"}`;throw this.logger.warn(v),{response:{code:an.CALL_END_CODE.DECODING_FAILED,subCode:an.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:v}}}removeStateAsync(g,f,S,v){if(this.logger.info(`[${g}][removeStateAsync][scope=${f} publishType=${S} stateIds=${v}]`),this.telemetryHelper.recordEvent(dn.REMOVE_STATE,{causeId:g,scope:f,publishType:S,stateIds:v}),!S&&!v){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.REMOVE_STATE_MISSING_ARGUMENTS,phrase:"remove state operation miss arguments"};return this.logger.warn(g),Promise.reject(g)}const C=this.links[an.LINKS.REMOVE_STATE];if(!C){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.REMOVE_STATE_LINK_MISSING,phrase:"remove state link is missing"};return this.logger.warn(g),Promise.reject(g)}return this.http.sendPostRequest({url:C,requestName:hn.REMOVE_STATE.name,payload:getPayload44(this,f,v,S),causeId:g,requestId:g}).then((f=>this.parseRemoveStateResult(f,g))).catch((f=>{const S=getErrorForXHRFailure(f,this.signalingAgentConfig);this.logger.info(`[${g}][removeStateAsync] error: ${getPrintableObject(S)}`);const v=S.error;return this.telemetryHelper.recordEvent(dn.REMOVE_STATE_FAILURE,{causeId:g,transactionEnd:v}),Promise.reject(v)}))}parseRemoveStateResult(g,f){let S={};return g?.response?.removeStateResponse&&(g.response.removeStateResponse.results?g.response.removeStateResponse.results.forEach((g=>{S[g.stateId]={code:g.result.code,phrase:g.result.phrase,subCode:g.result.subCode}})):g.response.removeStateResponse.result&&(S={code:g.response.removeStateResponse.result.code,phrase:g.response.removeStateResponse.result.phrase,subCode:g.response.removeStateResponse.result.subCode,result:g.response.removeStateResponse.additionalDetail})),JSON.stringify(S)}updateMeetingSettingsAsync(g,f){this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_SETTINGS,{causeId:f,meetingSettings:g});const S=this.links[an.LINKS.UPDATE_MEETING_SETTINGS];if(!S){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_LINK_MISSING,phrase:"update meeting settings link is missing"};return this.logger.warn(g),Promise.reject(g)}if(!Object.keys(g).length){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_MISSING_ARGUMENTS,phrase:"update meeting settings missing arguments"};return this.logger.warn(g),Promise.reject(g)}return this.http.sendPutRequest({url:S,requestName:hn.UPDATE_MEETING_SETTINGS.name,payload:getPayload54(this,g),causeId:f,requestId:f}).then((()=>{Cn.noop()})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][updateMeetingSettingsAsync] error: ${getPrintableObject(S)}`);const v=S.error;throw this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_SETTINGS_FAILURE,{causeId:f,transactionEnd:v}),v}))}searchParticipantsAsync(g,f){this.logger.info(`[${f}][searchParticipantsAsync][queryOptions=${g}]`),this.telemetryHelper.recordEvent(dn.SEARCH_PARTICIPANTS,{causeId:f,queryOptions:g});const S=this.links[an.LINKS.SEARCH_PARTICIPANTS];if(!S){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_LINK_MISSING,phrase:"search participants link is missing"};return this.logger.warn(g),Promise.reject(g)}return this.http.sendPostRequest({url:S,requestName:hn.SEARCH_PARTICIPANTS.name,payload:getPayload45(this,g),causeId:f,requestId:f}).then((g=>{if(g?.response?.participants)return this.parseSearchParticipantsResult(g,f);{const f=`Invalid CS response which does not contain proper search results. Respone: ${g?.response?JSON.stringify(g.response):"no response"}`;throw this.logger.warn(f),{response:{code:an.CALL_END_CODE.DECODING_FAILED,subCode:an.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:f}}}})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][searchParticipantsAsync] error: ${getPrintableObject(S)}`);const v=S.error;return this.telemetryHelper.recordEvent(dn.SEARCH_PARTICIPANTS_FAILURE,{causeId:f,transactionEnd:v}),Promise.reject(v)}))}parseSearchParticipantsResult(g,f){const S=[];if(g?.response){const f=g.response.participants;if(f)for(const v of Object.keys(f))S.push(cn.fromRosterSearchResults(g.response.participants[v]))}return{participants:S}}getAllParticipantsAsync(g,f){this.logger.info(`[${f}][getAllParticipantsAsync][scope=${g}]`),this.telemetryHelper.recordEvent(dn.GET_ALL_PARTICIPANTS,{causeId:f,scope:g});const S=this.links[an.LINKS.GET_ALL_PARTICIPANTS];if(!S){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_LINK_MISSING,phrase:"get all participants link is missing"};return this.logger.warn(g),Promise.reject(g)}if("lobby"!==g){const g={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SCOPE,phrase:"get all participants scope is invalid"};return this.logger.warn(g),Promise.reject(g)}return this.http.sendPostRequest({url:S,requestName:hn.GET_ALL_PARTICIPANTS.name,payload:getPayload35(this,g),causeId:f,requestId:f}).then((g=>{if(g?.response)return{participants:g.response.participants};{const g="Invalid CS response which does not contain results.";throw this.logger.warn(g),{response:{code:an.CALL_END_CODE.DECODING_FAILED,subCode:an.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:g}}}})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][getAllParticipantsAsync] error: ${getPrintableObject(S)}`);const v=S.error;return this.telemetryHelper.recordEvent(dn.GET_ALL_PARTICIPANTS_FAILURE,{causeId:f,transactionEnd:v}),Promise.reject(v)}))}resetState(){this.currentCallStatus=null,this.fsmState=an.SIGNALING_FSM_STATE.IDLE}saveUpdatedCallLinksIfAny(g){g.links&&(this.logger.info(`saveUpdatedCallLinksIfAny, updated call links found, update to new links ${getPrintableObject(g)}`),this.links[an.LINKS.MEDIA_RENEGOTIATION]=g.links.mediaRenegotiation||this.links[an.LINKS.MEDIA_RENEGOTIATION],this.links[an.LINKS.TRANSFER]=g.links.transfer||this.links[an.LINKS.TRANSFER],this.links[an.LINKS.REPLACE]=g.links.replacement||this.links[an.LINKS.REPLACE],this.links[an.LINKS.HANGUP]=g.links.callLeg||this.links[an.LINKS.HANGUP],this.links[an.LINKS.KEEPALIVE]=g.links.callLeg||this.links[an.LINKS.KEEPALIVE],this.links[an.LINKS.PARK]=g.links.hold||this.links[an.LINKS.PARK],this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=g.links.updateMediaDescriptions||this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS],this.links[an.LINKS.UPDATE_MONITOR_SESSION]=g.links.monitor||this.links[an.LINKS.UPDATE_MONITOR_SESSION])}ensureMessageChannelReady(g){return this.disposed?(this.logger.info("ensureMessageChannelReady: error: call already disposed"),Promise.reject(this.getCallNotFoundTransactionEnd())):this.brokerService?(this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.STARTED}:${g}`),this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.ENDED}:${g}`),Promise.resolve()):this.ensureLatestTrouterUrl(g)}ensureLatestTrouterUrl(g){return this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.STARTED}:${g}`),this.getTrouterUrlAsync().then((f=>!f||"string"==typeof f&&!f.trim()?(this.telemetryHelper.recordEvent(dn.TROUTER_URL_CHANGED_TO_INVALID),this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.ENDED}:${g}`),Promise.reject(new Error("Invalid trouter url"))):this.disposed?(this.logger.info("ensureLatestTrouterUrl, trouterUrlGetter returned too late. Object is already disposed"),Promise.reject(this.getCallNotFoundTransactionEnd())):(this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.ENDED}:${g}`),this.baseMessagingChannelUrl=this.currentTrouterUrl=f,Promise.resolve()))).catch((f=>(this.disposed||this.telemetryHelper.addTrouterWaitOperation(`${un.TROUTER_WAIT_OPERATION.FAILED}:${g}`),this.logger.info(`ensureLatestTrouterUrl, failed because:${f}`),Promise.reject(f))))}signalTransferAcceptedAsync(g,f=causeId2()){return this.logger.info(`[signalTransferAcceptedAsync][${f}] transferType ${g}`),this.disposed?(this.logger.info(`[signalTransferAcceptedAsync][${f}] Call already ended, skip acceptance request`),Promise.reject({code:an.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(this.telemetryHelper.recordEvent(dn.SEND_ACCEPT_TRANSFER,{causeId:f,transferType:g}),this.http.sendPostRequest({url:this.links[an.LINKS.TRANSFER_ACCEPTANCE],requestName:hn.TRANSFER_ACCEPTANCE.name,payload:getPayload47(),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[signalTransferAcceptedAsync][${f}] error: ${getPrintableObject(S)}`),this.telemetryHelper.recordEvent(dn.SEND_ACCEPT_TRANSFER_FAIL,{causeId:f}),Promise.reject(S.error)})))}signalTransferCompletedAsync(g,f=causeId2()){return this.logger.info(`[signalTransferCompletedAsync][${f}] rejectReason ${g}`),this.disposed?(this.logger.info(`[signalTransferCompletedAsync][${f}]  Call already ended by transferor, skip completion request`),Promise.reject({code:an.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(0!==g.code?this.telemetryHelper.recordEvent(dn.TRANSFER_COMPLETION_FAILED,{code:g.code,subcode:g.subCode,causeId:f}):this.telemetryHelper.recordEvent(dn.TRANSFER_COMPLETED,{causeId:f}),this.telemetryHelper.recordEvent(dn.SEND_COMPLETE_TRANSFER,{causeId:f}),this.http.sendPostRequest({url:this.links[an.LINKS.TRANSFER_COMPLETION],requestName:hn.TRANSFER_COMPLETION.name,payload:getPayload49(g),causeId:f}).catch((g=>{this.telemetryHelper.recordEvent(dn.SEND_COMPLETE_TRANSFER_FAILED,{causeId:f});const S=getErrorForXHRFailure(g,this.signalingAgentConfig);return this.logger.info(`[signalTransferCompletedAsync][${f}] error: ${getPrintableObject(S)}`),Promise.reject(S.error)})))}async rejectCallWithFetchAndKeepAlive(g){this.telemetryHelper.recordEvent(dn.REJECT_WITH_FETCH_KEEP_ALIVE,{causeId:g});const f={code:an.CALL_END_CODE.REJECT,subCode:an.CALL_END_SUB_CODE.BEACON,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:[Xi.Success]};await this.http.sendDeleteRequest({url:this.links[an.LINKS.REJECT],requestName:hn.REJECT_CALL.name,payload:getPayload43(this,f),causeId:g??causeId2(),requestId:newGuid2(),useFetch:!0,fetchUseKeepAlive:!0})}async endCallWithFetchAndKeepAlive(g,f,S,v){this.telemetryHelper.recordEvent(dn.END_WITH_FETCH_KEEP_ALIVE,{causeId:v}),await this.http.sendPostRequest({url:g,requestName:hn.END_CALL.name,payload:f,causeId:v??causeId2(),requestId:newGuid2(),useFetch:!0,fetchUseKeepAlive:!0})}endWithBeacon(g){if(this.disposed)return!1;const setTerminatedState=()=>{this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,g,f),this.dispose(f,g)};if(this.signalingAgentConfig.enableFetchRequestWithKeepAlive&&window.Request?.prototype?.hasOwnProperty("keepalive")&&this.currentCallStatus===an.CALL_STATUS.RINGING)return this.rejectCallWithFetchAndKeepAlive(g),setTerminatedState(),!0;const f={code:an.CALL_END_CODE.SUCCESS,subCode:an.CALL_END_SUB_CODE.BEACON,phrase:an.CALL_END_PHRASE.LOCAL_USER_INITIATED},S=JSON.stringify(getPayload37(this,f).payload),v=-1===this.links[an.LINKS.LEAVE].indexOf("?")?"?":"&",C=this.signalingAgent?.authTokenManager?.getLastTokenType(g),_=this.signalingAgent?.authTokenManager?.getLastToken(g);let T="";switch(C){case 4:case 8:this.logger.info(`[endWithBeacon] with tokenType:${C},token size:${_.length},query parameter:access_token`),T=`${this.links[an.LINKS.LEAVE]}${v}access_token=${_}`;break;default:this.logger.info(`[endWithBeacon] with tokenType:${C},token size:${_.length},query parameter:skypeToken`),T=`${this.links[an.LINKS.LEAVE]}${v}skypeToken=${_}`}return this.signalingAgentConfig.enableFetchApiForBeacon&&window.Request?.prototype?.hasOwnProperty("keepalive")?(this.endCallWithFetchAndKeepAlive(T,S,f,g),setTerminatedState(),!0):!!navigator?.sendBeacon&&(this.telemetryHelper.recordEvent(dn.END_WITH_BEACON,{causeId:g}),navigator.sendBeacon(T,S))}setFsmState(g){this.fsmState=g}setIsHostless(g,f){const S=!!g;this.isHostLessCall!==S&&(this.logger.info(`[${f}][setIsHostless] isHostless=${S}`),this.isHostLessCall=S)}hasGroupModality(){return this.threadId||this.groupId}processConversationServiceResponseHeaders(g,f){this.logger.info(`[${f}][processConversationServiceResponseHeaders]`);try{const S=g.request.headers[an.HEADERS.CORRELATION_ID]||g.request.headers[an.HEADERS.CORRELATION_ID.toLowerCase()];this.updateCorrelationId(S,f)}catch(g){this.logger.info(`[${f}][processConversationServiceResponseHeaders] failed, reason=${getPrintableObject(g)}`)}}processConversationServiceResponse(g,f,S){const v=this.logger.createChild(`[${f}][processConversationServiceResponse]`);if(v.info(`responseType :${S}`),this.processConversationServiceUpdate(g,f),g.subscriptionDetails?.selfParticipant){const S=cn.fromRoster(g.subscriptionDetails.selfParticipant,!0);v.info("converted selfParticipant to Participant type"),this.participantManager.updateLocalParticipantFromSubscribe(S,f)}g.selfParticipant?.enableCaptcha&&this.participantManager.setEnableCaptcha(!0,f),this.handleBrokerSubscription(g,f),g.roster&&this.internalHandleRosterUpdate(g.roster,!0,f),0===S&&(this.startOrJoinConvResponseReceived=!0,this.handlePendingEndpointState(f))}processConversationServiceUpdate(g,f){const S=this.logger.createChild(`[${f}][processConversationServiceUpdate]`);S.info(),this.convJoined=!0;const v=g.sequenceNumber>=0?g.sequenceNumber:-1;v<this.updateSequenceNumber?S.info(`seqNum=${v} is less than latest seqNum=${this.updateSequenceNumber}`):(this.updateSequenceNumber=v,this.links[an.LINKS.CONVERSATION_CONTROLLER]=g.conversationController,this.links[an.LINKS.ADD_PARTICIPANT]=g.links.addParticipant,this.links[an.LINKS.ADD_PARTICIPANTS_AND_MODALITY]=g.links.addParticipantAndModality,this.links[an.LINKS.LEAVE]=g.links.leave,this.links[an.LINKS.NOTIFICATION_LINKS]=g.links.notificationLinks,this.links[an.LINKS.REMOVE_PARTICIPANT]=g.links.removeParticipant,this.links[an.LINKS.ADD_MODALITY]=g.links.addModality,this.links[an.LINKS.REMOVE_MODALITY]=g.links.removeModality,this.links[an.LINKS.MUTE]=g.links.mute||null,this.links[an.LINKS.UNMUTE]=g.links.unmute||null,this.links[an.LINKS.ADMIT]=g.links.admit||null,this.links[an.LINKS.ADMIT_ALL]=g.links.admitAll||null,this.links[an.LINKS.UPDATE_ENDPOINT_STATE]=g.links.updateEndpointState||null,this.links[an.LINKS.UPDATE_ENDPOINT_METADATA]=g.links.updateEndpointMetadata||null,this.links[an.LINKS.UPDATE_PARTICIPANT_ROLE]=g.links.updateParticipantRole||null,this.links[an.LINKS.PUBLISH_STATE]=g.links.publishState||null,this.links[an.LINKS.REMOVE_STATE]=g.links.removeState||null,this.links[an.LINKS.UPDATE_MEETING_SETTINGS]=g.links.updateMeetingSettings||null,this.links[an.LINKS.SEARCH_PARTICIPANTS]=g.links.searchParticipants||null,this.links[an.LINKS.GET_ALL_PARTICIPANTS]=g.links.getAllParticipants||null,this.links[an.LINKS.UPDATE_MEETING_LIVE_STATE]=g.links.updateMeetingLiveState||null,this.links[an.LINKS.UPDATE_MEETING_GROUPS]=g.links.updateMeetingGroups||null,this.links[an.LINKS.SET_MEETING_LAYOUT]=g.links.setMeetingLayout||null,this.links[an.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE]=g.links.updateParticipantInterpretationState||null,this.links[an.LINKS.UPDATE_PARTICIPANTS_PROPERTIES]=g.links.updateParticipantProperties||null,this.links[an.LINKS.JOIN_MEETING_GROUP]=g.links.joinMeetingGroup||null,this.links[an.LINKS.LEAVE_MEETING_GROUP]=g.links.leaveMeetingGroup||null,this.links[an.LINKS.SEND_MESSAGE]=g.links.sendMessage||null,this.links[an.LINKS.UPDATE_MEETING_STATES]=g.links.updateMeetingStates||null,this.convSubject=g.subject,g.state&&(this.setMultiParty(g.state.isMultiParty,f),this.setIsHostless(g.state.isHostless||!1,f),this.conversationType=g.state.conversationType,this.isCastCall="cast"===g.state.conversationType,this.isHuddleGroupCall="huddleGroupCall"===g.state.conversationType),g.activeModalities&&g.activeModalities.groupChat&&this.updateGroupChatIds(g.activeModalities.groupChat,f),g.activeModalities&&g.activeModalities.broadcast&&(this.broadcastSession||(this.broadcastSession=new yn(this,this.signalingSessionCallback)),this.broadcastSession.handleBroadcastDetailsChanged(g,f)),this.handleMeetingDetailsChanged(g,f),this.handleMeetingStatesChanged(g,f),this.linkUpdateRequested.conversationLinks?(S.info("Updating CS links as requested"),this.updateLinks(this.updateConversationLinks,f)):this.scheduleConversationKeepAlive(),g.meetingData&&(this.meetingData=g.meetingData),g.meetingInfo&&(this.meetingInfo=g.meetingInfo),g.region&&(this.region=g.region),g.callLimits&&(this.callLimits=g.callLimits),g.complianceRecordingContent&&(this.complianceRecordingContent=g.complianceRecordingContent),g.conversationStartTime&&(this.conversationStartTime=g.conversationStartTime),this.signalingSessionCallback.onConversationUpdated({conversationType:this.conversationType,groupId:this.groupId,threadId:this.threadId,teamsMessageId:this.teamsMessageId,isMultiParty:this.multiParty,commandUrlPresence:this.getCommandUrlPresence(),meetingData:this.meetingData,region:this.region,meetingInfo:this.meetingInfo,callLimits:this.callLimits,complianceRecordingContent:this.complianceRecordingContent,conversationStartTime:this.conversationStartTime,isHuddleGroupCall:this.isHuddleGroupCall,backroomThreadId:this.backroomThreadId,streamThreadId:this.streamThreadId,lobbyThreadId:this.lobbyThreadId},f))}processLocalParticipantUpdateResponse(g,f){this.logger.info(`[${f}][processLocalParticipantUpdateResponse]`),g.sequenceNumber&&g.sequenceNumber<this.localParticipantUpdateSequenceNumber||(this.breakoutDetails=g.breakoutDetails||{},this.signalingSessionCallback.onBreakoutDetailsUpdated(this.breakoutDetails,f),!0===g.nudgeToJoinAsRealtime&&(this.telemetryHelper.recordEvent(dn.NUDGE_TO_JOIN_REALTIME,{causeId:f}),this.signalingSessionCallback.onNudgeToJoinRealtime(f)))}handlePendingEndpointState(g){this.requestedEndpointStateWhileConnecting&&(this.logger.info(`[${g}][handlePendingEndpointState]sending pending endpoint state now that we are connected.`),this.updateEndpointState(this.requestedEndpointStateWhileConnecting,g,this.requestedPublishedStatesWhileConnecting).catch((g=>{this.isPreheatOnly&&this.disablePreheatDefer.isPending()&&(this.logger.info("handlePendingEndpointState failed"),this.disablePreheatDefer.reject(g))})))}handleMeetingDetailsChanged(g,f){this.logger.info(`[${f}][handleMeetingDetailsChanged]`),g.meetingDetails&&!Cn.isEqual(g.meetingDetails,this.meetingDetails)&&this.signalingSessionCallback.onMeetingDetailsUpdated&&(this.meetingDetails=g.meetingDetails,this.meetingDetails.meetingCapability?.meetingLiveState&&(this.meetingLiveStateSequenceNumber=this.meetingDetails.meetingCapability.meetingLiveState.seqNum,this.logger.info(`[${f}][handleMeetingDetailsChanged] update meeting seqNum as ${this.meetingLiveStateSequenceNumber}`)),this.signalingSessionCallback.onMeetingDetailsUpdated(this.meetingDetails,f))}handleMeetingStatesChanged(g,f){this.logger.info(`[${f}][handleMeetingStatesChanged]`),this.signalingSessionCallback.onMeetingStatesUpdated&&this.signalingSessionCallback.onMeetingStatesUpdated(g.meetingStates,f)}handleBrokerSubscription(g,f){this.logger.info(`[${f}][handleBrokerSubscription]`),g.links.subscribe?(this.telemetryHelper.recordEvent(dn.SUBSCRIBE_URL_FOUND,f),this.brokerService&&!Cn.isEqual(g.links.subscribe,this.brokerService.currentSubscriptionUrl)?this.brokerService.subscribeToBroker(g.links.subscribe):(this.logger.info(`[${f}][handleBrokerSubscription] broker subscribe ignored. Broker is disabled or subscribe url is same.`),this.telemetryHelper.recordEvent(dn.BROKER_DISABLED_SUBSCRIBE_URL_PRESENT,f))):this.telemetryHelper.recordEvent(dn.SUBSCRIBE_URL_MISSING,f)}cancelOutgoingCall(g,f){const S=defer();this.logger.info(`[${f}][cancelOutgoingCall][rejectionData=${g&&getPrintableObject(g)}]`);const v={code:isNaN(g?.code)?an.CALL_END_CODE.CANCEL:g.code,subCode:g?.subCode||an.CALL_END_SUB_CODE.SUCCESS,phrase:g?.phrase||an.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:g?.resultCategories||[Xi.Success],clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase};if(this.signalingAgentConfig.enableSpecificErrorCodesForCallEnd&&(v.code=an.CALL_END_CODE.CANCEL,v.subCode=an.CALL_END_SUB_CODE.SUCCESS,v.phrase=an.CALL_END_PHRASE.LOCAL_USER_INITIATED,v.resultCategories=[Xi.Success]),this.links.hasOwnProperty(an.LINKS.LEAVE)){this.logger.info(`[${f}][cancelOutgoingCall] cancelling outgoing call`),this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const g={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()},C={terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultDetail:v.phrase||"CancelOutgoingCall",endCode:v.code,endSubCode:v.subCode,causeId:f,clientReasonSubCode:v.clientReasonSubCode,clientReasonPhrase:v.clientReasonPhrase,resultCategories:v.resultCategories};this.http.sendPostRequest({url:this.links[an.LINKS.LEAVE],requestName:hn.CANCEL_CALL.name,payload:getPayload32(this,v,g),causeId:f}).then((g=>{this.disposed||(this.telemetryHelper.setTerminatingData(C),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f)),S.resolve(null)})).catch((g=>{const _=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[cancelOutgoingCall][${f}] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(_)}`),this.disposed||(this.telemetryHelper.setTerminatingData(C),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f)),S.resolve(null)}))}else this.logger.info(`[${f}][cancelOutgoingCall] Conversation Service Leave Url is not yet set. Cannot leave conversation. Disposing anyways.`),v.subCode=an.CALL_END_SUB_CODE.CONV_URL_NOT_SET,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultDetail:v.phrase||"CancelOutgoingCall",endCode:v.code,endSubCode:v.subCode,causeId:f,clientReasonSubCode:v.clientReasonSubCode,clientReasonPhrase:v.clientReasonPhrase,resultCategories:v.resultCategories}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f),S.resolve(null);return S.promise}terminateEstablishedCall(g,f){const S=f.causeId||causeId2();this.logger.info(`[${S}][terminateEstablishedCall]`);const v=defer();this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const C=this.convJoined?hn.LEAVE_CONVERSATION.name:hn.END_CALL.name,_=build3(),T={code:g?.code||an.CALL_END_CODE.SUCCESS,subCode:g?.subCode||an.CALL_END_SUB_CODE.SUCCESS,phrase:g?.phrase||an.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:g?.resultCategories,clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase};T.resultCategories=T.resultCategories||[Xi.Success];const I={terminatingEnd:un.CALL_TERMINATING_END.LOCAL,endCode:T.code,endSubCode:T.subCode,resultDetail:T.phrase||"TerminateEstablishedCall",causeId:S,clientReasonSubCode:T.clientReasonSubCode,clientReasonPhrase:T.clientReasonPhrase,resultCategories:T.resultCategories};return this.leaveConversation(T,f).then((()=>{this.logger.info(`[${S}][terminateEstablishedCall]success`),this.disposed||(this.telemetryHelper.setTerminatingData(I),this.telemetryHelper.addNetworkOperationCompleted(C,!0,_.duration()),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,S,T),this.dispose(T,S)),v.resolve(null)})).catch((g=>{const f=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${S}][terminateEstablishedCall][failed] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(f)}]`),this.disposed||(this.telemetryHelper.setTerminatingData(I),this.telemetryHelper.addNetworkOperationCompleted(C,!1,_.duration()),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,S,T),this.dispose(T,S)),v.resolve(null)})),v.promise}deleteConversation(g,f){this.logger.info(`[${f}][deleteConversation]`);const S=defer();this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const v=hn.DELETE_CONVERSATION.name,C=build3(),_={code:g?.code||an.CALL_END_CODE.SUCCESS,subCode:g?.subCode||an.CALL_END_SUB_CODE.SUCCESS,phrase:g?.phrase||an.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED,resultCategories:g?.resultCategories||[Xi.Success],clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase},T={terminatingEnd:un.CALL_TERMINATING_END.LOCAL,endCode:_.code,endSubCode:_.subCode,resultDetail:_.phrase,causeId:f,clientReasonSubCode:_.clientReasonSubCode,clientReasonPhrase:_.clientReasonPhrase,resultCategories:_.resultCategories};return this.deleteConversationController(_,f).then((()=>{this.logger.info(`[${f}][deleteConversation]success`),this.disposed||(this.telemetryHelper.setTerminatingData(T),this.telemetryHelper.addNetworkOperationCompleted(v,!0,C.duration()),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,_),this.dispose(_,f)),S.resolve(null)})).catch((g=>{const I=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][deleteConversation][failed] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(I)}`),this.disposed||(this.telemetryHelper.setTerminatingData(T),this.telemetryHelper.addNetworkOperationCompleted(v,!1,C.duration()),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,_),this.dispose(_,f)),S.resolve(null)})),S.promise}leaveConversation(g,f){const S=f.causeId||causeId2();if(this.convJoined){this.logger.info(`[${S}][leaveConversation]`);const v={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()};return this.http.sendPostRequest({url:this.links[an.LINKS.LEAVE],requestName:hn.LEAVE_CONVERSATION.name,payload:getPayload37(this,g,v,f.scope),withoutTrouter:!0,causeId:S})}return this.logger.info(`[${S}][leaveConversation] ignore, not joined to conversation`),Promise.resolve(void 0)}deleteConversationController(g,f){return this.convJoined?(this.logger.info(`[${f}][deleteConversationController]`),this.http.sendDeleteRequest({url:this.links[an.LINKS.CONVERSATION_CONTROLLER],requestName:hn.DELETE_CONVERSATION.name,payload:getPayload34(this,g),withoutTrouter:!0,causeId:f})):(this.logger.info(`[${f}][deleteConversationController]ignored, not joined to conversation`),Promise.resolve(void 0))}rejectIncomingCall(g,f){this.telemetryHelper.recordEvent(dn.REJECT_INCOMING_CALL,f),this.logger.info(`[${f}][rejectIncomingCall]`);const S=defer();this.fsmState=an.SIGNALING_FSM_STATE.IDLE;const v={code:isNaN(g?.code)?an.CALL_END_CODE.REJECT:g.code,subCode:g?.subCode||an.CALL_END_SUB_CODE.SUCCESS,phrase:g?.phrase||an.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:g?.resultCategories,clientReasonSubCode:g?.clientReasonSubCode,clientReasonPhrase:g?.clientReasonPhrase};v.resultCategories=v.resultCategories||[Xi.Success];const C={terminatingEnd:un.CALL_TERMINATING_END.LOCAL,endCode:v.code,endSubCode:v.subCode,resultDetail:v.phrase||"RejectCall",causeId:f,clientReasonSubCode:v.clientReasonSubCode,clientReasonPhrase:v.clientReasonPhrase,resultCategories:v.resultCategories};return this.http.sendDeleteRequest({url:this.links[an.LINKS.REJECT],requestName:hn.REJECT_CALL.name,payload:getPayload43(this,v),causeId:f}).then((g=>{this.disposed||(this.telemetryHelper.setTerminatingData(C),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f)),S.resolve(null)})).catch((g=>{const _=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[rejectIncomingCall][${f}] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(_)}`),this.disposed||(this.telemetryHelper.setTerminatingData(C),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,f,v),this.dispose(v,f)),S.resolve(null)})),S.promise}onCallStatusChanged(g,f,S){const v=`[${f}][onCallStatusChanged]`;if(this.logger.info(`${v}${this.currentCallStatus}=>${g}]`),this.disposed)this.logger.info(`${v}Call is already disposed!!`);else if(S&&this.logger.info(`${v}[statusCode=${getPrintableObject(S)}]`),this.isPromotingToRealtime)g===an.CALL_STATUS.CONNECTED&&this.onPromotionCompleted(!1,void 0,f);else if(this.isValidStateTransitions(g)){this.currentCallStatus=g;const v={callStatus:g,statusCode:S,causeId:f};this.isPreheatOnly&&(v.isPreheatOnly=!0),this.telemetryHelper.recordEvent(dn.UPDATE_CALL_STATUS,v),this.signalingSessionCallback.onCallStatusChanged(g,S,f),this.currentCallStatus===an.CALL_STATUS.CONNECTED&&(this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.telemetryHelper.resetCallCancelationDurationWatch(),this.isPreheatOnly&&this.startCallPreheatTimer(f))}}updateMeetingLiveStateAsync(g,f){this.logger.info(`[${g}][updateMeetingLiveStateAsync][options=${JSON.stringify(f)}]`),this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_LIVE_STATE,{causeId:g,meetingLiveStateOptions:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,(()=>{this.handleUpdateMeetingLiveStateError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT},dn.WAITING_FOR_UPDATE_MEETING_LIVE_STATE_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT);const S=getPayload53(this,{...f,sequenceNumber:this.meetingLiveStateSequenceNumber},g);return this.http.sendPostRequest({url:this.links[an.LINKS.UPDATE_MEETING_LIVE_STATE],requestName:hn.UPDATE_MEETING_LIVE_STATE.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][updateMeetingLiveStateAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UPDATE_MEETING_LIVE_STATE_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S,this.signalingAgentConfig);return this.logger.info(`[${g}][updateMeetingLiveStateAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingLiveStateError(v.error,dn.UPDATE_MEETING_LIVE_STATE_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}updateMeetingStatesAsync(g,f){const S=this.logger.createChild(`[${g}][updateMeetingStatesAsync]`,this.correlationId);if(S.info(`meetingStatesOptions: ${JSON.stringify(f)}`),!f)return Promise.reject({code:an.VALIDATION.VALIDATION_FAILED,subCode:an.VALIDATION.NULL_OR_EMPTY,phrase:"meetingStatesOptions should be a non empty object"});this.telemetryHelper.recordEvent(dn.UPDATE_MEETING_STATES,{causeId:g,meetingStatesOptions:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,(()=>{for(const S in f.meetingStates)this.handleUpdateMeetingStatesError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT},dn.WAITING_FOR_UPDATE_MEETING_STATES_COMPLETION,g,f.operationId+"_"+S)}),an.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT);const v=getPayload59(this,{...f.meetingStates},g);return this.http.sendPostRequest({url:this.links[an.LINKS.UPDATE_MEETING_STATES],requestName:hn.UPDATE_MEETING_STATES.name,payload:v,causeId:g}).then((f=>{S.info(`response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_UPDATE_MEETING_STATES_COMPLETION,{causeId:g})})).catch((v=>{const C=getErrorForXHRFailure(v,this.signalingAgentConfig);if(S.error(`error: ${getPrintableObject(C)}`),!this.disposed){for(const S in f.meetingStates)this.handleUpdateMeetingStatesError(C.error,dn.UPDATE_MEETING_STATES_RESPONSE_FAILURE,g,f.operationId+"_"+S);return Promise.reject(C.error)}return Promise.reject(this.getCallNotFoundTransactionEnd())}))}handleUpdateMeetingLiveStateError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleUpdateMeetingLiveStateError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleUpdateMeetingLiveStateError] reject reason: ${g}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,updateMeetingGroupsOptions:C,causeId:S}),this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted&&this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted(g,S,v))}handleUpdateMeetingLiveStateCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.updateMeetingLiveStateResponse.result,C=f.updateMeetingLiveStateResponse.operationId;C||this.logger.warn(`[${S}][handleUpdateMeetingLiveStateCompletion] operationId is undefined.`),this.logger.info(`[${S}][handleUpdateMeetingLiveStateCompletion] meetingLiveUpdate completes with operationId=${C}`),this.handleOperationCompletionCommon(v,S,C,getPrintableObject(f),"handleUpdateMeetingLiveStateCompletion",an.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,dn.UPDATE_MEETING_LIVE_STATE_RESPONSE_SUCCESS,dn.UPDATE_MEETING_LIVE_STATE_RESPONSE_FAILURE,this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted,this.handleUpdateMeetingLiveStateError.bind(this))}handleUpdateMeetingStatesError(g,f,S,v){this.disposed?this.logger.info(`[${S}][handleUpdateMeetingStatesError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleUpdateMeetingStatesError] reject reason: ${g}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,causeId:S}),this.signalingSessionCallback.onUpdateMeetingStatesCompleted&&this.signalingSessionCallback.onUpdateMeetingStatesCompleted(g,S,v))}handleUpdateMeetingStatesCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.updateMeetingStatesResponse,C=f.operationId,_=this.logger.createChild(`[${S}][handleUpdateMeetingStatesCompletion]`,this.correlationId);C||_.warn("operationId is undefined.");for(const g of v)_.info(`UpdateMeetingStates completes with operationId=${C}.`),this.handleOperationCompletionCommon(g.transactionEnd,S,C+"_"+g.meetingStateName,getPrintableObject(f),"handleUpdateMeetingStatesCompletion",an.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,dn.UPDATE_MEETING_STATES_RESPONSE_SUCCESS,dn.UPDATE_MEETING_STATES_RESPONSE_FAILURE,this.signalingSessionCallback.onUpdateMeetingStatesCompleted,this.handleUpdateMeetingStatesError.bind(this))}handleUpdateMonitorSessionCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleUpdateMeetingStatesCompletion]`,this.correlationId);const v=f.monitorCompletion;this.handleOperationCompletionCommon(v,S,void 0,getPrintableObject(f),"handleUpdateMonitorSessionCompletion",an.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION,dn.UPDATE_MONITOR_SESSION_RESPONSE_COMPLETED,dn.UPDATE_MONITOR_SESSION_RESPONSE_FAILED,this.signalingSessionCallback.onUpdateMonitorSessionCompleted,this.handleUpdateMonitorSessionError.bind(this))}handleUpdateMonitorSessionError(g,f,S,v){this.disposed?this.logger.info(`[${S}][handleUpdateMonitorSessionError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleUpdateMonitorSessionError] reject reason: ${JSON.stringify(g)}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.UPDATE_MONITOR_SESSION_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,monitorOptions:v,causeId:S}),this.signalingSessionCallback.onUpdateMonitorSessionCompleted(g,S))}setMeetingLayoutAsync(g,f){this.logger.info(`[${g}][setMeetingLayoutAsync][options=${JSON.stringify(f)}]`),this.telemetryHelper.recordEvent(dn.SET_MEETING_LAYOUT,{causeId:g,setMeetingLayoutOptions:f}),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,(()=>{this.handleSetMeetingLayoutError({code:an.CALL_END_CODE.TIMEOUT,subCode:an.CALL_END_SUB_CODE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT,phrase:an.CALL_END_PHRASE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT},dn.WAITING_FOR_SET_MEETING_LAYOUT_COMPLETION,g,g,f)}),an.TIMEOUT_VALUES_IN_SECONDS.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT);const S=getPayload46(this,{...f,sequenceNumber:this.meetingLayoutSequenceNumber});return this.http.sendPostRequest({url:this.links[an.LINKS.SET_MEETING_LAYOUT],requestName:hn.SET_MEETING_LAYOUT.name,payload:S,causeId:g}).then((f=>{this.logger.info(`[${g}][setMeetingLayoutAsync] response: ${getPrintableObject(f)}`),this.telemetryHelper.recordEvent(dn.WAITING_FOR_SET_MEETING_LAYOUT_COMPLETION,{causeId:g})})).catch((S=>{const v=getErrorForXHRFailure(S);return this.logger.info(`[${g}][setMeetingLayoutAsync] error: ${getPrintableObject(v)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleSetMeetingLayoutError(v.error,dn.SET_MEETING_LAYOUT_REQUEST_FAILED,g,g,f),Promise.reject(v.error))}))}handleSetMeetingLayoutError(g,f,S,v,C){this.disposed?this.logger.info(`[${S}][handleSetMeetingLayoutError] ignored. Call disposed, err: ${JSON.stringify(g)}`):(this.logger.info(`[${S}][handleSetMeetingLayoutError] reject reason: ${g}`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION),this.telemetryHelper.recordEvent(f,{...g,updateMeetingGroupsOptions:C,causeId:S}),this.signalingSessionCallback.onSetMeetingLayoutCompleted&&this.signalingSessionCallback.onSetMeetingLayoutCompleted(g,S,v))}handleSetMeetingLayoutCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g),v=f.setMeetingLayoutResponse.result,C=f.setMeetingLayoutResponse.operationId;C||this.logger.warn(`[${S}][handleSetMeetingLayoutCompletion] operationId is undefined.`),this.handleOperationCompletionCommon(v,S,C,getPrintableObject(f),"handleSetMeetingLayoutCompletion",an.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,dn.SET_MEETING_LAYOUT_RESPONSE_SUCCESS,dn.SET_MEETING_LAYOUT_RESPONSE_FAILURE,this.signalingSessionCallback.onSetMeetingLayoutCompleted,this.handleSetMeetingLayoutError.bind(this))}handleOperationCompletionCommon(g,f,S,v,C,_,T,I,b,A){this.disposed?this.logger.info(`[${f}][${C}] ignored. Call disposed.`):(this.logger.info(`[${f}][${C}] body ${v}`),g.code===an.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(_),this.telemetryHelper.recordEvent(T,{...g,causeId:f}),b&&b(g,f,S)):A&&A(g,I,f,S))}isValidStateTransitions(g){if(this.currentCallStatus===an.CALL_STATUS.LOCAL_TERMINATED&&g===an.CALL_STATUS.CONNECTING)return!0;const orderOfCallState=g=>{switch(g){case an.CALL_STATUS.IDLE:case an.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY:return 0;case an.CALL_STATUS.CONNECTING:return 1;case an.CALL_STATUS.RINGING:return 2;case an.CALL_STATUS.CONNECTED:return 3;case an.CALL_STATUS.LOCAL_TERMINATED:case an.CALL_STATUS.REMOTE_TERMINATED:return 4;default:return-1}};return orderOfCallState(g)>orderOfCallState(this.currentCallStatus)}handlePSTNBalanceUpdate(g){const f=g.body.balanceUpdate,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handlePSTNBalanceUpdate]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_PSTN_BALANCE_UPDATE,g),f.updateBalance?this.signalingSessionCallback.onPSTNBalanceUpdate(f):this.logger.info(dn.HANDLE_PSTN_BALANCE_UPDATE,"this was a pstn keepAlive message - ignore")}handleCallAcceptanceAck(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleCallAcceptanceAck]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_ACCEPTANCE_ACK,g),this.internalHandleCallAcceptanceAck(f,S)}internalHandleCallAcceptanceAck(g,f){this.logger.info(`[${f}][internalHandleCallAcceptanceAck] ${getPrintableObject(g)}`),this.fsmState!==an.SIGNALING_FSM_STATE.CONNECTED&&(this.links[an.LINKS.MEDIA_RENEGOTIATION]=g.callAcceptanceAcknowledgement.links.mediaRenegotiation,this.links[an.LINKS.TRANSFER]=g.callAcceptanceAcknowledgement.links.transfer,this.links[an.LINKS.REPLACE]=g.callAcceptanceAcknowledgement.links.replacement,this.links[an.LINKS.HANGUP]=g.callAcceptanceAcknowledgement.links.callLeg,this.links[an.LINKS.KEEPALIVE]=g.callAcceptanceAcknowledgement.links.callLeg,this.links[an.LINKS.PARK]=g.callAcceptanceAcknowledgement.links.hold,this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=g.callAcceptanceAcknowledgement.links.updateMediaDescriptions,this.links[an.LINKS.UPDATE_MONITOR_SESSION]=g.callAcceptanceAcknowledgement.links.monitor,this.saveMediaControllerLinksIfAny(g.callAcceptanceAcknowledgement),this.scheduleKeepAlives(g.callAcceptanceAcknowledgement.callKeepAliveInterval),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(g.callAcceptanceAcknowledgement.callProperties?.isSharedLineAppearanceV2Activated),this.fsmState=an.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.INCOMING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(f),this.onCallStatusChanged(an.CALL_STATUS.CONNECTED,f),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${f}][internalHandleCallAcceptanceAck] updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,f)))}isFatalException(g){let f=!0;try{JSON.parse(g.message).code===an.CALL_END_CODE.CONFLICT&&(f=!1,this.logger.info("isFatalException: received non-fatal 409 error"))}catch(g){this.logger.error("isFatalException: failed to parse error")}return f}startOrJoinCall(g,f,S,v,C){if(this.logger.info(`[${S}]startOrJoinCall[${f}]`),this.disposed)return void this.logger.info(`[${S}][${f}] session already disposed, ignore`);this.telemetryHelper.recordEvent(dn.START_OR_JOIN_CALL,{causeId:S,requestName:f}),this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,S);const _=this.getConversationUrl()?this.getConversationUrl():g.conversationServiceUrl;this.telemetryHelper.setConversationServiceUrl(_),this.logger.info(`options.conversationServiceUrl ${g.conversationServiceUrl} conversationServiceUrl ${_}`),g.isPreheatOnly?(this.isPreheatOnly=!0,this.telemetryHelper.recordEvent(dn.PREHEAT_ENABLING,{causeId:S}),this.telemetryHelper.setSelfParticipantRole(un.ROLE.PREHEAT),this.telemetryHelper.setIsPreheated()):this.telemetryHelper.startCallCancelationDurationWatch(),this.mediaTypesToUse=C,this.lastUsedOutgoingMediaContent=v,this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);const T=!this.multiParty&&this.signalingAgentConfig.enableLongOutgoing1To1SetupTimeoutForWeb,I=T?an.TIMEOUT_VALUES_IN_SECONDS.LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:an.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT;this.logger.info(`[${S}][${f}]target endpointType = ${this.transferContext&&this.transferContext.target?this.transferContext.target.endpointType:"default"} timeout = ${I} LongerTimeout = ${T}`);const b=g.newCall?getPayload33(this,v,C,g):getPayload36(this,v,C,g,S);this.signalingAgentConfig.enableCallEstablishmentTimeoutsForStartJoinCall&&this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(S)}),I),this.signalingSessionCallback.onTransferredCallAcceptance(S),g.endpointState&&(this.latestEndpointState=g.endpointState),this.http.sendPostRequest({url:_,requestName:f,operationType:"CallSetup",payload:b,causeId:S}).then((g=>{this.disposed||(this.processConversationServiceResponseHeaders(g,S),this.processConversationServiceResponse(g.response,S,0),this.onCallStatusChanged(an.CALL_STATUS.CONNECTING,S))})).catch((g=>{if(g.stack&&!this.isFatalException(g))return;const v=getErrorForXHRFailure(g,this.signalingAgentConfig);if(this.logger.info(`[startOrJoinCall][${S}][${f}] error: ${getPrintableObject(g)} xhrError: ${getPrintableObject(v)}`),!this.disposed){if(this.isPromotingToRealtime)return void this.onPromotionCompleted(!0,v.error,S);this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,endCode:v.telemetryEndSubCode,endSubCode:v.error.subCode,resultCategories:v.error.resultCategories,resultDetail:v.error.phrase||"StartOrJoinCallFailure",causeId:S}),this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,S,v.error),this.dispose(v.error,S)}}))}processIncomingCallPayload(g,f){this.remoteUser=cn.fromWireParticipant(g.callNotification.from),this.participantManager.setLocalParticipantId(g.callNotification.to.participantId,f),g?(g.conversationInvitation&&(this.links[an.LINKS.CONVERSATION_CONTROLLER]=g.conversationInvitation.conversationController,this.setMultiParty(g.conversationInvitation.isMultiParty,f),this.setIsHostless(!!g.conversationInvitation.isHostless,f)),g.callNotification&&(this.links[an.LINKS.ATTACH]=g.callNotification.links?.attach,this.links[an.LINKS.REDIRECT]=g.callNotification.links?.redirection,this.onBehalfOf=g.callNotification.onBehalfOf?.id,this.onBehalfOfUserDisplayName=g.callNotification.onBehalfOf?.displayName,this.callQueueContext=g.callNotification.callQueueContext,this.callPhoneLineType=g.callNotification.callPhoneLineType,this.callType=g.callNotification.callType,this.incomingCallCallerId=g.callNotification.from?.id,this.callUsesMixer=!!g.callNotification.mediaContent?.fromMixer,this.isRedirectAllowed=!!g.callNotification.redirectionProperties?.isRedirectAllowed,this.callQueueSupervisorContent=g.callNotification.callQueueSupervisorContent,this.bannerContent=g.callNotification.bannerContent),g.debugContent&&this.updateCorrelationId(g.debugContent.callId,f),g.callNotification.transferor&&(this.transferor=g.callNotification.transferor.details?g.callNotification.transferor.details.id:null),g.groupChat&&this.updateGroupChatIds(g.groupChat,f),g.meetingData&&(this.meetingData=g.meetingData),g.meetingInfo&&(this.meetingInfo=g.meetingInfo)):this.logger.info(`[${f}][processIncomingCallPayload] empty incoming payload content`)}processAttachResponse(g,f,S){this.telemetryHelper.recordEvent(dn.PROCESS_INITIAL_OFFER,{causeId:S}),this.links[an.LINKS.MEDIA_ANSWER]=f.response.callInvitation.links.mediaAnswer,this.links[an.LINKS.ACCEPT]=f.response.callInvitation.links.acceptance,this.links[an.LINKS.REJECT]=f.response.callInvitation.links.callLeg,this.links[an.LINKS.REDIRECT]=f.response.callInvitation.links.redirection,this.links[an.LINKS.NEW_OFFER]=f.response.callInvitation.links.newOffer,this.signalingAgentConfig.sendProgressFromCC||this.sendProgress(f),this.remoteCaller=f.response.participants.from;const v=this.getInitialMediaOfferFromIncomingCallPayload()||f.response.callInvitation.mediaContent;this.telemetryHelper.setCallerType(this.getParticipantIdForOfferAnswer(v));const C=getMediaTypes(f.response.callInvitation.callModalities);this.telemetryHelper.addIncomingModalities(C),this.telemetryHelper.setOfferedModalities(v.blob,!0),this.callUsesMixer=v.fromMixer,this.isRedirectAllowed=!(!f.response.callInvitation.redirectionProperties||!f.response.callInvitation.redirectionProperties.isRedirectAllowed),this.signalingSessionCallback.onOffer({subject:g.conversationInvitation.subject,remoteParticipantId:this.getParticipantIdForOfferAnswer(v),remoteEndpointId:f.response.participants.from.endpointId,transferor:f.response.callInvitation.transferor,clientTransferContext:g.callNotification.transferContext,customHeaderContext:f.response.callInvitation.customContext,mediaTypes:C,mediaContent:v,renegotiation:!1,invitationData:f.response.callInvitation.invitationData,riskLevel:f.response.callInvitation.spamProperties&&f.response.callInvitation.spamProperties.riskLevel,stirAttestation:f.response.callInvitation.spamProperties&&f.response.callInvitation.spamProperties.stirAttestation,isRedirectAllowed:this.isRedirectAllowed},S)}sendProgress(g,f=causeId2()){this.logger.info(`[${f}][sendProgress]`),this.telemetryHelper.recordEvent(dn.SEND_PROGRESS,{causeId:f}),this.http.sendPostRequest({url:g.response.callInvitation.links.progress,requestName:hn.SEND_CALL_PROGRESS.name,payload:getPayload30(this),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][sendProgress] error: ${getPrintableObject(S)}`),this.disposed||this.telemetryHelper.recordEvent(dn.SEND_PROGRESS_FAILED,{causeId:f,...S.error})}))}handleCallNotification(g){const f=extractCauseIdFromMessage(g);if(this.logger.info(`[${f}][handleCallNotification]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_NOTIFICATION,g),!stringEndsWith(g.url,rn.REPLACE))throw new Error(`[${f}][handleCallNotification]IncomingCallNotification should not be received in handleIncomingMsg`);this.telemetryHelper.recordIncomingEvent(dn.HANDLE_INCOMING_CALL_REPLACEMENT,g),this.logger.info(`[${f}][handleCallNotification]replacementCallNotification`),this.signalingSessionCallback&&this.signalingSessionCallback.onIncomingCallReplacement(g.body,f)}handleMediaAnswer(g){this.telemetryHelper.recordIncomingEvent(dn.HANDLE_MEDIA_ANSWER,g);const f=g.body,S=extractCauseIdFromMessage(g);if(this.logger.info(`[${S}][handleMediaAnswer]`),this.mediaRenegotiationManager.isOutgoingRenegotiationInProgress())this.mediaRenegotiationManager.handleMediaAnswer(f,S);else if(this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED);else if(this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING){if(isDuplicateMessage(g.headers,this.provisionalMediaAnswersSeenSoFar))return void this.logger.info(`[${S}][handleMediaAnswer] ignoring provisional answer retried by service`);f.mediaAnswer.sender&&(this.remoteUser=f.mediaAnswer.sender),this.resetCallEstablishmentTimeout(S),f.mediaAnswer.noRingBack||(this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(an.CALL_STATUS.RINGING,S));const v=f.mediaAnswer.mediaContent;this.signalingSessionCallback.onAnswer({provisional:!0,renegotiation:!1,remoteEndpointId:f.mediaAnswer.sender?f.mediaAnswer.sender.endpointId:newGuid2(),remoteParticipantId:this.getParticipantIdForOfferAnswer(v),mediaContent:v},S)}}async _sendCallAcceptanceAcknowledgement(g,f){this.http.sendPostRequest({url:g.body.callAcceptance.links.acknowledgement,requestName:hn.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:getPayload28(this),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][_sendCallAcceptanceAcknowledgement] error: ${getPrintableObject(S)}`),this.disposed||this.telemetryHelper.recordEvent(dn.HANDLE_CALL_ACCEPTANCE_FAILED,{causeId:f,...S.error})}))}handleCallAcceptance(g){const f=extractCauseIdFromMessage(g);this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_ACCEPTANCE,g,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:f}),this.logger.info(`[${f}][handleCallAcceptance]enableQuickSendAcceptanceAck:\n            ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?(this._sendCallAcceptanceAcknowledgement(g,f),this._processCallAcceptance(g,f)):(this._processCallAcceptance(g,f),this.http.sendPostRequest({url:g.body.callAcceptance.links.acknowledgement,requestName:hn.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:getPayload28(this),causeId:f}).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig);this.logger.info(`[${f}][handleCallAcceptance] error: ${getPrintableObject(S)}`),this.disposed||this.telemetryHelper.recordEvent(dn.HANDLE_CALL_ACCEPTANCE_FAILED,{causeId:f,...S.error})})))}handleCallAcceptanceSync(g){const f=extractCauseIdFromMessage(g);this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_ACCEPTANCE_SYNC,g,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:f}),this.logger.info(`[${f}][handleCallAcceptanceSync] enableQuickSendAcceptanceAck:\n            ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?Cn.defer(this._processCallAcceptance,g,f):this._processCallAcceptance(g,f);const S=getPayload28(this).payload;return this.telemetryHelper.addNetworkOperationCompleted(hn.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,!0),S}getFakeRoster(g){const f=this.participantManager.getParticipantsToInitiateCallWith();let S;S=1===f.length?f[0].id:g.callAcceptance.acceptedBy.id;const v={id:S,displayName:g.callAcceptance.acceptedBy.id===S?g.callAcceptance.acceptedBy.displayName:"",languageId:g.callAcceptance.acceptedBy.languageId},C=g.callAcceptance.acceptedBy.endpointId;return{type:"MultiPartyEndpoint",participants:{[S]:{acceptedBy:g.callAcceptance.acceptedBy.id,details:v,endpoints:{[C]:{call:{},contentSharing:{},capabilities:g.callAcceptance.capabilities,participantId:g.callAcceptance.acceptedBy.participantId}}}}}}processCallAcceptance(g,f){this.logger.info(`[${f}][processCallAcceptance] ${getPrintableObject(g)}`),this.telemetryHelper.recordEvent(dn.PROCESS_CALL_ACCEPTANCE,{causeId:f}),this.fsmState=an.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(f);let S=!1;g.callAcceptance.controllerName===an.MISC.LOBBY_CALL_CONTROLLER&&(this.logger.info(`[${f}][processCallAcceptance] Controller name is lobby so putting user in lobby`),this.participantManager.localParticipant.isLobby=!0,this.participantManager.localParticipant.endpointDetails.push({isLobby:!0,endpointId:this.participantManager.localParticipant.endpointId,participantId:this.participantManager.localParticipant.participantId}),S=!0,this.telemetryHelper.recordEvent(dn.ACCEPTANCE_USER_IN_LOBBY,{causeId:f})),this.participantManager.localParticipant.isStaging=hasStagingGroup(g.callAcceptance),this.signalingSessionCallback.onMeetingGroupDetailsUpdated(g.callAcceptance.meetingGroupDetails,f),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(g.callAcceptance.callProperties?.isSharedLineAppearanceV2Activated),this.logger.info(`[${f}][processCallAcceptance] for localParticipant, isStaging is set to ${this.participantManager.localParticipant.isStaging}`);let v=this.mediaTypesToUse,C=newGuid2();g.callAcceptance.acceptedBy&&(this.remoteUser=cn.fromWireParticipant(g.callAcceptance.acceptedBy),C=g.callAcceptance.acceptedBy.endpointId),g.callAcceptance.acceptedCallModalities&&g.callAcceptance.acceptedCallModalities.length>0&&(v=g.callAcceptance.acceptedCallModalities);const _=g.callAcceptance.mediaContent;this.callUsesMixer=_.fromMixer;const T=getMediaTypes(v);this.telemetryHelper.addIncomingModalities(T),this.telemetryHelper.setAnsweredModalities(_.blob,!0),this.links[an.LINKS.MEDIA_RENEGOTIATION]=g.callAcceptance.links.mediaRenegotiation,this.links[an.LINKS.TRANSFER]=g.callAcceptance.links.transfer,this.links[an.LINKS.REPLACE]=g.callAcceptance.links.replacement,this.links[an.LINKS.HANGUP]=g.callAcceptance.links.callLeg,this.links[an.LINKS.KEEPALIVE]=g.callAcceptance.links.callLeg,this.links[an.LINKS.PARK]=g.callAcceptance.links.hold,this.links[an.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=g.callAcceptance.links.updateMediaDescriptions,this.links[an.LINKS.UPDATE_MONITOR_SESSION]=g.callAcceptance.links.monitor,this.saveMediaControllerLinksIfAny(g.callAcceptance),this.scheduleKeepAlives(g.callAcceptance.callKeepAliveInterval);const I=this.getParticipantIdForOfferAnswer(_);this.signalingSessionCallback.onAnswer({provisional:!1,renegotiation:!1,remoteEndpointId:C,remoteParticipantId:I,callAcceptedByNGCVoicemail:I===an.KNOWN_BOTS.VOICEMAIL_BOT_ID,mediaTypes:T,mediaContent:_},f),this.setRealTimeState(2,f),this.onCallStatusChanged(an.CALL_STATUS.CONNECTED,f),S&&this.signalingSessionCallback.onSelfParticipantUpdated(this.participantManager.localParticipant,f),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${f}][processCallAcceptance] Updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,f))}updateGroupChatIds(g,f){const S=this.groupId,v=this.threadId,C=this.teamsMessageId,_=this.backroomThreadId,T=this.streamThreadId,I=this.lobbyThreadId;this.groupId=g.groupId,this.threadId=g.threadId,this.teamsMessageId=g.messageId,this.backroomThreadId=g.backroomThreadId,this.streamThreadId=g.streamThreadId,this.lobbyThreadId=g.lobbyThreadId,this.groupId===S&&this.threadId===v&&this.teamsMessageId===C&&this.backroomThreadId===_&&this.streamThreadId===T&&this.lobbyThreadId===I||this.signalingSessionCallback.onConversationUpdated({conversationType:this.conversationType,groupId:this.groupId,threadId:this.threadId,teamsMessageId:this.teamsMessageId,isMultiParty:this.multiParty,commandUrlPresence:this.getCommandUrlPresence(),meetingData:this.meetingData,region:this.region,meetingInfo:this.meetingInfo,callLimits:this.callLimits,isHuddleGroupCall:this.isHuddleGroupCall,backroomThreadId:this.backroomThreadId,streamThreadId:this.streamThreadId,lobbyThreadId:this.lobbyThreadId},f)}handleCallEnd(g,f){let S=g.body.callEnd||g.body;const v=extractCauseIdFromMessage(g);if(this.logger.info(`[${v}][handleCallEnd][content=${getPrintableObject(S)}]`),this.telemetryHelper.recordEvent(dn.HANDLE_CALL_END,{origin:g.origin,code:S?S.code:"unknown",subCode:S?S.subCode:"unknown",resultCategories:S?S.resultCategories:[],causeId:v}),this.signalingAgentConfig.enableConversationTypeUpdateOnCallEnd&&(this.conversationType=S?.conversationType||this.conversationType,this.signalingSessionCallback.onConversationTypeUpdated(this.conversationType,v)),this.fsmState!==an.SIGNALING_FSM_STATE.IDLE)if(S.code===an.CALL_END_CODE.CONFLICT&&this.multiParty&&S.conversationUrl?.Location)this.handleConversationResolutionConflict(S,v);else{this.disposing=!0,S.callControllerTransactionEnd&&(this.logger.info("handleCallEnd: using CC end details specified in CS end"),S=S.callControllerTransactionEnd),S.broadcastOperationFailure&&(this.logger.info("handleCallEnd: using broadcastOperationFailure end details specified in CS end"),S=S.broadcastOperationFailure);const g=S.code===an.CALL_END_CODE.SUCCESS||S.code===an.CALL_END_CODE.CANCEL||S.code===an.CALL_END_CODE.REJECT;this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.REMOTE,resultDetail:S.phrase,resultValue:g?un.RESULT_VALUE.SUCCESS:un.RESULT_VALUE.FAILURE,endCode:S.code,endSubCode:S.subCode,resultCategories:S?S.resultCategories:[],causeId:v});const C={code:S.code,subCode:S.subCode,phrase:S.phrase,resultCategories:S.resultCategories,pickupCode:""},_=this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY;this.fsmState=an.SIGNALING_FSM_STATE.IDLE,S.acceptedElsewhereBy&&(this.acceptedElsewhereBy={id:S.acceptedElsewhereBy.id,displayName:S.acceptedElsewhereBy.displayName}),S.unparkContent&&(S.unparkContent.CallParkAdditionalContext&&(this.parkAdditionalContextJson=JSON.stringify(S.unparkContent.CallParkAdditionalContext),this.serverHoldLocation=S.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),S.unparkContent.pickupCode&&(C.pickupCode=S.unparkContent.pickupCode));const T=this.signalingAgentConfig.enableSplitConversationEndUrl;T&&_===f?(this.logger.info("fsmstate = SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY or OUTGOING_FOR_ROSTER_ONLY"),this.onCallStatusChanged(an.CALL_STATUS.REMOTE_TERMINATED,v,C),this.dispose(C,v)):T||(this.onCallStatusChanged(an.CALL_STATUS.REMOTE_TERMINATED,v,C),this.dispose(C,v))}else this.logger.info(`[${v}][handleCallEnd] not handling incoming callEnd since fsmstate = SIGNALING_FSM_STATE.IDLE`)}handleConversationResolutionConflict(g,f){this.logger.info(`[${f}][handleConversationResolutionConflict]`);const S={...g,phrase:g.phrase||"Conflict Resolution Error"};if(this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===an.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY)this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.http.cancelRequestIfPending(hn.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,f,void 0,S),this.subscribeToCall(g.conversationUrl.Location,g.correlationId,this.lastUsedJoinCallOptions?this.lastUsedJoinCallOptions.clientEndpointCapabilities:0,{meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,additionalEndpointProperties:this.lastUsedJoinCallOptions?.additionalEndpointProperties},f);else{this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const v={meetingData:this.meetingData,meetingPreferences:this.meetingPreferences};if(this.lastUsedJoinCallOptions){const g=this.lastUsedJoinCallOptions.scenario;v.muted=this.lastUsedJoinCallOptions.muted,v.scenario=`409Redirect${g||""}`,v.isPreheatOnly=this.lastUsedJoinCallOptions.isPreheatOnly,v.clientEndpointCapabilities=this.lastUsedJoinCallOptions.clientEndpointCapabilities,v.clientEndpointDebugContent=this.lastUsedJoinCallOptions.clientEndpointDebugContent,v.additionalEndpointProperties=this.lastUsedJoinCallOptions.additionalEndpointProperties}else v.scenario="409RedirectJoin";this.setInitialTelemetry("JoinCall",{correlationId:g.correlationId,causeId:f,conversationServiceUrl:g.conversationUrl.Location,joinCallOptions:v,offerGenerationTime:void 0}),this.http.cancelRequestIfPending(hn.JOIN_CONVERSATION.name,f,void 0,S),this.http.cancelRequestIfPending(hn.START_CALL.name,f,void 0,S),this.joinGivenConversation(g.conversationUrl.Location,g.correlationId,this.lastUsedOutgoingMediaContent,this.mediaTypesToUse,void 0,v,f)}}handleCallProgress(g){this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CALL_PROGRESS,g);const f=extractCauseIdFromMessage(g);this.logger.info(`[${f}][handleCallProgress]`);const S=g.body.callProgress;this.fsmState===an.SIGNALING_FSM_STATE.OUTGOING&&(this.telemetryHelper.setTimeToRingDuration(),this.resetCallEstablishmentTimeout(f),this.onCallStatusChanged(an.CALL_STATUS.RINGING,f),"forwarded"===S.status&&this.signalingSessionCallback.onCallForwarded({destinationType:S.forwardingDestinationType||"user"},f))}resetCallEstablishmentTimeout(g){const f=this.isOneToOnePSTNCall()?an.TIMEOUT_VALUES_IN_SECONDS.LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:an.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT;this.logger.info(`resetCallEstablishmentTimeout: ${f}s`),this.timeoutManager.stopTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.timeoutManager.startTimer(an.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(g)}),f)}handleMediaAcknowledgement(g){this.telemetryHelper.recordIncomingEvent(dn.HANDLE_MEDIA_ACK,g);const f=g.body,S=extractCauseIdFromMessage(g);this.currentCallStatus!==an.CALL_STATUS.CONNECTED?this.telemetryHelper.recordEvent(dn.HANDLE_MEDIA_PROVISIONAL_ACK,{causeId:S}):this.mediaRenegotiationManager.handleMediaAcknowledgment(f,S)}handleConversationUpdate(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleConversationUpdate]content=${getPrintableObject(f)}`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_CONVERSATION_UPDATE,g),this.processConversationServiceResponse(f,S,2)}endBroadcastMeeting(g){this.logger.info(`[${g}][endBroadcastMeeting]`),this.broadcastSession=null}handleLocalParticipantUpdate(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleLocalParticipantUpdate]content=${getPrintableObject(f)}`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_LOCAL_PARTICIPANT_UPDATE,g),this.processLocalParticipantUpdateResponse(f,S)}handleAddModalityFailure(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAddModalityFailure]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_MODALITY_FAILURE,g),f.modalityFailure.contentSharing?this.contentSharingManager?.handleAddModalityFailure(f,S):f.modalityFailure.groupChat?this.signalingSessionCallback.onChatModalitySetupFailed({code:f.modalityFailure.groupChat.code,subCode:f.modalityFailure.groupChat.subCode,phrase:f.modalityFailure.groupChat.phrase,resultCategories:f.modalityFailure.groupChat.resultCategories},S):f.modalityFailure.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalityFailure(f,S)}handleAddModalitySuccess(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleAddModalitySuccess]`),this.telemetryHelper.recordIncomingEvent(dn.HANDLE_ADD_MODALITY_SUCCESS,g),f.modalitySuccess.contentSharing?this.contentSharingManager?.handleAddModalitySuccess(f,S):f.modalitySuccess.groupChat?this.logger.info(`[${S}][handleAddModalitySuccess] group modality ${getPrintableObject(f.modalitySuccess.groupChat)}`):f.modalitySuccess.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalitySuccess(f,S)}handleTransferRequested(g){const f=g.body.callTransfer,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleTransferRequested]`),f.parkType?(this.telemetryHelper.recordIncomingEvent(dn.HANDLE_PARK_REQUESTED,g,{type:f.parkType}),this.telemetryHelper.addSharedCorrelationId(f.sharedCorrelationId)):"voicemail"===f.target.endpointType?(this.logger.info(`[${S}][handleTransferRequested] target endpointType = ${f.target.endpointType}`),this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_REQUEST_RECEIVED,g)):this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_REQUEST_RECEIVED,g),this.links[an.LINKS.TRANSFER_ACCEPTANCE]=f.links.transferAcceptance,this.links[an.LINKS.TRANSFER_COMPLETION]=f.links.transferCompletion,this.signalingSessionCallback.onTransferRequested?this.signalingSessionCallback.onTransferRequested(f,S):this.logger.info(`[${S}][handleTransferRequested] failed, no callback defined`)}handleTransferAcceptance(g){const f=extractCauseIdFromMessage(g);this.logger.info(`[${f}][handleTransferAcceptance]`),this.telemetryHelper.recordIncomingEvent(dn.WAITING_FOR_TRANSFER_COMPLETION,g),this.signalingSessionCallback.onTransferAccepted?this.signalingSessionCallback.onTransferAccepted(f):this.logger.info(`[${f}][handleTransferAcceptance]failed, no callback defined`)}handleTransferCompletion(g){const f=g.body,S=extractCauseIdFromMessage(g);this.logger.info(`[${S}][handleTransferCompletion]`),f.sharedCorrelationId&&this.telemetryHelper.addSharedCorrelationId(f.sharedCorrelationId),void 0!==f.unparkContent?.pickupCode&&(f.unparkContent.pickupCode=f.unparkContent.pickupCode.toString(),this.telemetryHelper.recordIncomingEvent(dn.PICKUP_CODE_SET,g)),this.signalingSessionCallback.onTransferCompleted?(g.body.transferCompletion&&(0===g.body.transferCompletion.code?this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_COMPLETED,g):(this.logger.info(`[${S}][handleTransferCompletion]-1-code: ${f.transferCompletion.code}, message: ${getPrintableObject(g)}`),this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_COMPLETION_FAILED,g,{code:f.transferCompletion.code,subcode:f.transferCompletion.subCode,resultCategories:f.transferCompletion.resultCategories}))),this.signalingSessionCallback.onTransferCompleted(f,S)):(g.body.transferCompletion&&(g.body.transferCompletion.code===an.CALL_END_CODE.NETWORK_ERROR?this.telemetryHelper.recordIncomingEvent(dn.WAITING_FOR_TRANSFER_COMPLETION_FAIL,g):this.telemetryHelper.recordIncomingEvent(dn.TRANSFER_COMPLETION_FAILED,g,{code:f.transferCompletion.code,subcode:f.transferCompletion.subCode,resultCategories:f.transferCompletion.resultCategories})),this.logger.info(`[${S}][handleTransferCompletion]failed, no callback defined`))}handleRosterUpdate(g,f){const S=g.body,v=extractCauseIdFromMessage(g);this.disposing||this.disposed?this.logger.info(`[${v}][handleRosterUpdate]failed=ignore call ending or ended`):this.internalHandleRosterUpdate(S,f,v)}handleNewMediaOffer(g){const f=extractCauseIdFromMessage(g);this.telemetryHelper.recordIncomingEvent(dn.HANDLE_NEW_OFFER,g);const S=g.body.mediaOfferReady.mediaContent;this.callUsesMixer=S.fromMixer,this.signalingSessionCallback.onNewOffer({mediaContent:S,renegotiation:!1},f)}internalHandleRosterUpdate(g,f,S){if(g&&"Delta"!==g.type&&"MultiPartyEndpoint"!==g.type)this.logger.warn(`[${S}][internalHandleRosterUpdate] roster.type=${g.type} is invalid`);else{this.logger.info(`[${S}][internalHandleRosterUpdate]`);try{this.participantManager.handleRosterUpdate(g,f,S),this.contentSharingManager?.handleIncomingContentSharingFromRoster(g,f,S)}catch(f){const v={code:an.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:an.CALL_END_SUB_CODE.ROSTER_HANDLING_INVALID_SERVICE_RESPONSE,phrase:f?.toString()};throw this.logger.info(`[${S}][internalHandleRosterUpdate] ${safeJsonStringify(v)}`),this.telemetryHelper.recordRosterEvent(g,dn.HANDLE_ROSTER_UPDATE_FAIL,S),v}}}scheduleKeepAlives(g){const f=.9*g*1e3;this.logger.info(`scheduleKeepAlives: every ${f} milliseconds`),this.keepAliveInterval=f,this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval)}scheduleConversationKeepAlive(){if(!this.conversationKeepAliveTimer&&!this.disposed){if(!this.conversationKeepAliveInterval){const g=getRandomizedTimeout(1e3*this.signalingAgentConfig.csaTimeoutConfiguration.conversationKeepAliveTimeoutSec);this.logger.info(`sendConversationKeepAlive: every ${g} milliseconds`),this.conversationKeepAliveInterval=g}this.conversationKeepAliveTimer=window.setInterval(this.sendConversationKeepAlive.bind(this),this.conversationKeepAliveInterval)}}sendConversationKeepAlive(){this.logger.info("sendConversationKeepAlive"),this.disposed?this.logger.info("sendConversationKeepAlive ignored"):(this.logger.info("sendConversationKeepAlive keepAlive count = "+this.conversationKeepAliveCount++),this.sendToUpdateConversationLinks(!0))}sendKeepAlive(){this.logger.info("sendKeepAlive"),this.disposed?this.logger.info("sendKeepAlive ignored"):(this.logger.info("sendKeepAlive keepAlive count = "+this.keepAliveCount++),this.sendToKeepAliveUrl(null))}sendToUpdateConversationLinks(g,f=causeId2()){if(this.disposed)return Promise.resolve();const S=this.logger.createChild(`[${f}][sendToUpdateConversationLinks]`,this.correlationId),v=g?getPayload56(this):{},C=g?hn.UPDATE_CONVERSATION_LINKS.name:hn.SEND_CONVERSATION_KEEP_ALIVE.name,_=this.links[an.LINKS.NOTIFICATION_LINKS];return S.info(`shouldUpdateUrl: ${g}, url: ${_}, payload: ${getPrintableObject(v)}`),_?(this.conversationKeepAliveTimer&&(window.clearInterval(this.conversationKeepAliveTimer),this.conversationKeepAliveTimer=0),this.http.sendPostRequest({url:_,payload:v,withoutTrouter:!0,requestName:C,causeId:f}).then((g=>{this.disposed||(this.telemetryHelper.recordEvent(dn.UPDATE_CONVERSATION_LINKS_SUCCESS,{causeId:f}),this.processConversationServiceResponse(g.response,f,2))})).catch((g=>{const S=getErrorForXHRFailure(g,this.signalingAgentConfig),v=isRetryable(S.error.code);this.logger.info(`[${f}][updateConversationLinks] error: ${getPrintableObject(S)}, retryable: ${v}`),this.disposed||(this.telemetryHelper.recordEvent(dn.UPDATE_CONVERSATION_LINKS_FAILED,{causeId:f,...S.error}),v?this.scheduleConversationKeepAlive():this.links[an.LINKS.NOTIFICATION_LINKS]=null)}))):Promise.resolve()}sendToKeepAliveUrl(g,f=causeId2()){const S=this.logger.createChild(`[${f}][sendToKeepAliveUrl]`,this.correlationId);return S.info(`payload: ${getPrintableObject(g)}`),window.clearInterval(this.keepAliveTimer),this.disposed?Promise.resolve():(this.telemetryHelper.recordEvent(dn.SEND_KEEP_ALIVE),this.http.sendPostRequest({url:this.links[an.LINKS.KEEPALIVE],payload:g,requestName:hn.SEND_KEEP_ALIVE.name,withoutTrouter:!0,causeId:f}).then((()=>{this.restartKeepAliveInterval(f)})).catch((g=>{const v=getErrorForXHRFailure(g,this.signalingAgentConfig);S.info(`error: ${getPrintableObject(v)}`),this.restartKeepAliveInterval(f,!0,v.error)})))}handleCallEstablishmentTimeout(g,f,S){const v={code:an.CALL_END_CODE.TIMEOUT,subCode:f||an.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:S||an.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT,resultCategories:[Xi.UnexpectedClientError]};this.isPromotingToRealtime?this.onPromotionCompleted(!0,v,g):(this.telemetryHelper.recordEvent(dn.HANDLE_CALL_ESTABLISHMENT_TIMEOUT),this.telemetryHelper.setTerminatingData({terminatingEnd:un.CALL_TERMINATING_END.LOCAL,resultValue:un.RESULT_VALUE.FAILURE,resultDetail:v.phrase,endCode:v.code,endSubCode:v.subCode,causeId:g,resultCategories:v.resultCategories}),this.fsmState=an.SIGNALING_FSM_STATE.IDLE,this.onCallStatusChanged(an.CALL_STATUS.LOCAL_TERMINATED,g,v),this.dispose(v,g))}handleCallTransferTimeout(g,f){if(this.disposed)return void this.logger.info("Transfer: handleCallTransferTimeout ignored");const S={code:an.CALL_END_CODE.TIMEOUT,phrase:an.CALL_END_PHRASE.TRANSFER_COMPLETION_TIMEOUT};this.signalingSessionCallback.onTransferCompleted&&(!1===f?this.telemetryHelper.recordEvent(dn.TRANSFER_COMPLETION_FAILED,{code:an.CALL_END_CODE.TIMEOUT,subcode:an.CALL_END_SUB_CODE.TRANSFER_COMPLETE_TIMEOUT,causeId:g}):!0===f&&this.telemetryHelper.recordEvent(dn.WAITING_FOR_TRANSFER_ACCEPTANCE_FAIL,{causeId:g}),this.signalingSessionCallback.onTransferCompleted({transferCompletion:S},g))}checkCorrelationIdChange(g,f){if(g&&g.headers){const S=g.headers.get(an.HEADERS.CORRELATION_ID);if(S&&S.length){const v=[rn.CONV_CONTENT_SHARING_UPDATE,rn.CONV_CONTENT_SHARING_END].some((f=>g.url&&stringEndsWith(g.url,f)));this.correlationId===S||v||(this.logger.info(`[${f}]checkCorrelationIdChange:${this.correlationId} => ${S}`),this.telemetryHelper.addChangingCorrelationId(this.correlationId,S),this.updateCorrelationId(S,f))}}}getCommandUrlPresence(){let g=0;return this.links[an.LINKS.MUTE]&&(g|=1),this.links[an.LINKS.UNMUTE]&&(g|=2),g}getCallNotFoundTransactionEnd(){return{code:an.CALL_END_CODE.CALL_DOES_NOT_EXIST,subCode:0,phrase:an.CALL_END_PHRASE.CALL_DOES_NOT_EXIST}}dispose(g,f){this.disposed||(this.logger.info(`[${f}][dispose] end reason ${getPrintableObject(g)}`),this.disposed=!0,this.disposing=!1,this.tearDownConnectionCheck(),this.conversationKeepAliveTimer&&(window.clearInterval(this.conversationKeepAliveTimer),this.conversationKeepAliveTimer=0),this.keepAliveTimer&&window.clearInterval(this.keepAliveTimer),this.brokerService&&this.brokerService.dispose(),this.http.cancelAllRequests(f).then((()=>{this.signalingAgent.onCallCompleted(this.sessionId,f),this.signalingAgentConfig.trouterUrlGetter&&this.signalingAgentConfig.trouterUrlGetter.trouterUrl.changed.off(this.onTrouterUrlChanged),this.signalingAgentConfig.trouterServiceProvider&&this.signalingAgentConfig.trouterServiceProvider.offStateChanged(this.onTrouterStateChanged),this.timeoutManager.dispose(),this.timeoutManager=null,this.participantManager.dispose(g,f),this.callOperationHandler.dispose("call ended",g,f),this.participantManager=null,this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=null,this.contentSharingManager?.dispose(g,f),this.contentSharingManager=null,this.telemetryHelper.dispose(),this.telemetryHelper=null,this.webRtcSignalingManager.dispose(),this.webRtcSignalingManager=null})))}};function build5(g,f,S,v,C,_){return new tr(g,f,S,v,C,_)}var ir=class{constructor(g){this.endpointId=newGuid2(),this.signalingSessions={},this.clientSupportsGenericTokenAPI=!1,this.getNewSignalingSession=(g,f,S,v)=>{const C=causeId2();assertNotNull(g,"selfParticipant should be a non null value"),assertNotNull(f,"signalingSessionCallback should be a non null value");const _=S||newGuid2();assertNotNullOrEmpty(_,"signalingSession id generated cannot be null or empty"),this.checkConfigChange(C);const T=build5(g,f,this.signalingAgentConfig,_,this,v),I=T.sessionId;return this.signalingSessions[I]=T,this.logger.info(`[${C}]Created new signalingSession with correlation ID ${_} and session ID ${I}`),T},this.resolvePotentialCallConflict=g=>{const f=causeId2();if(this.logger.info(`[${f}][resolvePotentialCallConflict]`),g.multiParty)return;const S=Object.values(this.signalingSessions).find((f=>this.isSessionInConflictingState(f,g)));if(!S)return;let v;if(v=g.isIncomingCall?this.getConflictingSessionToEnd(g,S):this.getConflictingSessionToEnd(S,g),!v)return;const C=v===g?S:g;return this.logger.info("Call conflict done.",` conflictingSession.correlationId=${S.correlationId}`,` conflictingSession.urlIdentifier=${S.urlIdentifier}`,` sessionToEnd.correlationId=${v.correlationId}`,` sessionToEnd.urlIdentifier=${v.urlIdentifier}`),v.telemetryHelper.setConflictingCallId(C.correlationId),v.telemetryHelper.recordEvent(dn.CONFLICTED_CALL),this.signalingAgentConfig.endConflictedCall?(this.endConflictedSession(v,f),v):void 0},this.handleIncomingNotification=g=>{if(assertNotNull(g,"request should be a non null value"),this.logger.info(`handleIncomingNotification to : ${g.url}`),!g.body&&!g.rawBody)return this.logger.error("request has no body"),this.buildNotificationResponse(an.HTTP_STATUS_CODES.BAD_REQUEST);let f=an.HTTP_STATUS_CODES.OK;const S=getIdFromUrl(g.url);if(S){const v=this.signalingSessions.hasOwnProperty(S);if(this.logger.info(`Is session found:${v}`),v){const f=this.signalingSessions[S];if(g.headers=new ln(g.headers),isEncodedMessage(g.headers))try{if(!isMessageEncodingSupported(g.headers))throw new Error("Unsupported encoding");const f=decodeMessage(g.rawBody),S=JSON.parse(f);g.body=S}catch(g){return f.telemetryHelper.recordEvent(dn.TROUTER_DECODE_PAYLOAD_FAILURE),this.buildNotificationResponse(an.HTTP_STATUS_CODES.BAD_REQUEST)}if(f.canHandleIncomingMsgSync(g))return f.handleIncomingMsgSync(g);window.setTimeout((()=>{if(this.signalingSessions.hasOwnProperty(S)){const f=this.signalingSessions[S];f.handleIncomingMsgAsync(g).catch((g=>{f&&f.telemetryHelper&&f.telemetryHelper.recordEvent(dn.FAILED_TO_HANDLE_TROUTER_MESSAGE),this.logger.error(`handling IncomingMsg failed with error: ${g}`)}))}}),0)}else this.logger.info(`Incoming message for session ID ${S}, but session was not found!`),f=an.HTTP_STATUS_CODES.NOT_FOUND}else this.logger.error(`Could not retrieve session ID from Url path. Path = ${g.url}`),f=an.HTTP_STATUS_CODES.BAD_REQUEST;const v=this.buildNotificationResponse(f);return this.logger.info(`Result code:${getPrintableObject(v)}`),v},this.onCallCompleted=(g,f)=>{this.signalingSessions.hasOwnProperty(g)?(delete this.signalingSessions[g],this.logger.info(`[${f}][onCallCompleted] Session ID ${g} found. Deleted from signalingSession table`)):this.logger.info(`[${f}][onCallCompleted] Session ID ${g} not found. Could not delete from signalingSession table`)},this.applyAuthTokenCacheConfig=g=>{this.signalingAgentConfig.enableTokenCache?(this.authTokenManager.setTokenCaching(!0,g),this.signalingAgentConfig.enableTokenPrefetch&&this.authTokenManager.getToken(g).then((()=>{this.logger.info(`[${g}] token prefetch success`)})).catch((f=>{this.logger.info(`[${g}] token prefetch failure, error=${getPrintableObject(f)}`)}))):this.authTokenManager.setTokenCaching(!1,g),this.signalingAgentConfig.enableTokenCacheForGenericTokenAPI?this.authTokenManager.setTokenCachingForGenericTokenAPI(!0,g):this.authTokenManager.setTokenCachingForGenericTokenAPI(!1,g)},this.endConflictedSession=(g,f)=>{this.logger.info("Call conflict, ending signalingSession with callId=",g.correlationId,"urlIdentifier=",g.urlIdentifier),g.endAsync({code:an.CALL_END_CODE.CONFLICT,subCode:an.CALL_END_SUB_CODE.CONFLICT_IN_NG,phrase:an.CALL_END_PHRASE.CONFLICT},{forEveryone:!1,causeId:f})},this.getConflictingSessionToEnd=(g,f)=>{if(!is1to1Mri(g.incomingCallCallerId)||!is1to1Mri(f.participantManager.localParticipant.id))return;const S=stripMri(g.incomingCallCallerId),v=f.participantManager.getParticipantsToInitiateCallWith();if(0===v.length)return;const C=stripMri(v[0].id),_=stripMri(f.participantManager.localParticipant.id);return C===S?_>S?g:f:void 0},this.isSessionInConflictingState=(g,f)=>{if(!g)return this.logger.info("Call conflict, ignore, session already disposed"),!1;const S=[an.CALL_STATUS.IDLE,an.CALL_STATUS.CONNECTING,an.CALL_STATUS.RINGING];return!g.multiParty&&S.indexOf(g.getCallStatus())>-1&&f.isIncomingCall!==g.isIncomingCall},this.buildNotificationResponse=(g,f)=>this.signalingAgentConfig.supportsSynchronousTrouterResponse?{resultCode:g,responseBody:f}:g,setDefaultsForSignalingConfig(g),this.signalingAgentConfig=g,this.logger=g.logger.createChild("SignalingAgent"),assertNotNull(g,"signalingAgentConfig should be a non null value"),this.logger.info(g.isWebRtcEnabled?"webRTC enabled":"ORTC enabled");const f={aadTokenExpirationTimeInSeconds:g.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:g.caeTokenExpirationTimeInSeconds,disableTokenMigrationHeader:g.disableTokenMigrationHeader,enablePublishTokenTelemetry:g.enablePublishTokenTelemetry,refreshTimeBeforeTokenTimeoutInSeconds:g.refreshTimeBeforeTokenTimeoutInSeconds,forceClearExpiredTokens:g.forceClearExpiredTokens,enableRefreshToken:g.enableRefreshToken,enableRefreshTokenRetry:g.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:g.enableRefreshTokenRetryInSeconds};this.authTokenManager=Sn.build(this.logger,g.skypeToken,f,g.telemetryManager),this.applyAuthTokenCacheConfig(causeId2()),ln.useLowerCaseHeaders=g.forceLowercaseHttpHeaders}updateSignalingAgentConfig(g){const f=causeId2(),S=JSON.stringify(g,((g,f)=>g?String(f):f));this.logger.info(`[${f}] updateSignalingAgentConfig, SignalingAgentConfig: ${S}`),this.logger.info(`[${f}] ecsEtag=${g.ecsEtag}`),setDefaultsForSignalingConfig(g),this.updatedSignalingAgentConfig=g,this.authTokenManager?.updateTokenSettings({aadTokenExpirationTimeInSeconds:g.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:g.caeTokenExpirationTimeInSeconds,refreshTimeBeforeTokenTimeoutInSeconds:g.refreshTimeBeforeTokenTimeoutInSeconds,disableTokenMigrationHeader:g.disableTokenMigrationHeader,enablePublishTokenTelemetry:g.enablePublishTokenTelemetry,forceClearExpiredTokens:g.forceClearExpiredTokens,enableRefreshToken:g.enableRefreshToken,enableRefreshTokenRetry:g.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:g.enableRefreshTokenRetryInSeconds}),ln.useLowerCaseHeaders=g.forceLowercaseHttpHeaders}updateUrls(g,f,S){this.logger.info(`updateUrls: conversationServiceUrl: ${g}, uploadLogRequestUrl: ${f}, enforceUrls: ${S}`),this.updatedSignalingAgentConfig=this.updatedSignalingAgentConfig||this.signalingAgentConfig,S||!this.updatedSignalingAgentConfig.isConversationServiceUrlFromEcs?this.updatedSignalingAgentConfig.conversationServiceUrl=g||this.updatedSignalingAgentConfig.conversationServiceUrl:this.updatedSignalingAgentConfig.conversationServiceUrl=this.updatedSignalingAgentConfig.conversationServiceUrl||g,S||!this.updatedSignalingAgentConfig.isUploadLogRequestUrlFromEcs?this.updatedSignalingAgentConfig.uploadLogRequestUrl=f||this.updatedSignalingAgentConfig.uploadLogRequestUrl:this.updatedSignalingAgentConfig.uploadLogRequestUrl=this.updatedSignalingAgentConfig.uploadLogRequestUrl||f}update(g){this.logger.info(`update accountConfiguration ${JSON.stringify(g)}`),g&&g.clientSupportsGenericTokenAPI!==this.clientSupportsGenericTokenAPI&&(this.clientSupportsGenericTokenAPI=g.clientSupportsGenericTokenAPI,this.authTokenManager.updateTokenSettings({clientSupportsGenericTokenAPI:this.clientSupportsGenericTokenAPI})),this.accountConfig=g}sendPushAsync(g,f,S,v,C=causeId2()){const _=new vn(this.signalingAgentConfig.piiScrubber),T=`sendPush[local participant mri = ${_.scrubMriOrOmit(g)}][recipientList = ${_.scrubMriOrOmit(f)}][headers = ${S})][causeId = ${C}]`;if(!g?.id)return this.logger.info(`${T} Empty localParticipantId`),Promise.reject("invalid localParticipantId");if(!f||0===f.length||f.every((g=>g&&""===g.id)))return this.logger.info(`${T} Empty recipientList`),Promise.reject("invalid recipientList");if(!S)return this.logger.info(`${T} Empty headers`),Promise.reject("invalid headers");if(!v||null===tryParse(v))return this.logger.info(`${T} Invalid body.`),Promise.reject("invalid body");const I={...tryParse(v),To:Array.from(f,(g=>g.id)),From:g.id},b=new ln(S);b.hasOwnPropertyCaseInsensitive(an.HEADERS.CORRELATION_ID)||b.set(an.HEADERS.CORRELATION_ID,generateGuid()),b.hasOwnPropertyCaseInsensitive(an.HEADERS.MESSAGE_ID)||b.set(an.HEADERS.MESSAGE_ID,generateGuid()),b.hasOwnPropertyCaseInsensitive(an.HEADERS.PARTICIPANT_ID)||b.set(an.HEADERS.PARTICIPANT_ID,generateGuid()),b.hasOwnPropertyCaseInsensitive(an.HEADERS.CONTENT_TYPE)||b.set(an.HEADERS.CONTENT_TYPE,"application/json"),b.hasOwnPropertyCaseInsensitive(an.HEADERS.CLIENT_USER_AGENT)&&b.set(an.HEADERS.CLIENT_USER_AGENT,b.get(an.HEADERS.CLIENT_USER_AGENT)+`/TsCallingVersion=${getTsCallingVersion2()}/Ovb=${getOvb2()}`);const A=this.signalingAgentConfig.httpRequestDispatcher.getRequestOptions("POST",b?.getAll(),JSON.stringify(I),3e4);return A.useFetch=this.signalingAgentConfig.enableFetchApi,new Promise(((g,f)=>{this.signalingAgentConfig.httpRequestDispatcher.postAsync(this.signalingAgentConfig.uploadLogRequestUrl||an.URL_DEFAULTS.UPLOAD_LOG_URL,A).then((()=>{g()})).catch((g=>{f(g)}))}))}getSignalingSession(g){for(const f of Object.keys(this.signalingSessions)){const S=this.signalingSessions[f];if(S.correlationId===g)return S}return null}updateToken(g,f,S,v,C){this.authTokenManager.updateToken(g,f,S,v,C)}setTokenRequiredCallBack(g){this.authTokenManager.setTokenRequiredCallBack(g)}resetAuthTokenManager(){this.setTokenRequiredCallBack(null),this.authTokenManager.setDisableTimerFlag(!0),this.authTokenManager.dispose()}checkConfigChange(g){this.updatedSignalingAgentConfig&&this.updatedSignalingAgentConfig!==this.signalingAgentConfig&&(this.signalingAgentConfig=this.updatedSignalingAgentConfig,this.updatedSignalingAgentConfig=null,this.applyAuthTokenCacheConfig(g))}},nr=/;aliases=.*$/i,rr="8:",sr=";aliases=",ar="2:",or="4:";function stripMriAliases(g){return g?g.replace(nr,""):g}function generateAliasedMri(g,f){let S=g;return f&&(S+=sr+ar+f),S}var isOneOfPhaseErrors=(g,f)=>f&&void 0!==f.phase&&!!g[f.phase],isPhaseError=(g,f)=>f&&void 0!==f.phase&&f.phase===g;function createPhaseExecutor(g){const f={},recordPhaseStep=g=>{const S={status:"Pending"};f[g]=S},recordStepDoneTelemetry=(g,S)=>{f[g].t=S,delete f[g].status},recordStepFailedTelemetry=(g,S,v)=>{f[g].status="Failed",f[g].t=S,f[g].reason=getPrintableObject(v)};return{execute:async(S,v)=>{const C=g.createChild(`[phase=${S}]`);recordPhaseStep(S),C.info("started");const _=(new Date).getTime();try{const g=await v(),f=+new Date-_;return C.logSuccess(`done, time=${f}`),recordStepDoneTelemetry(S,f),g}catch(g){const v=+new Date-_;throw C.logFailure(`time=${v}, error=${getPrintableObject(g)}`),recordStepFailedTelemetry(S,v,g),{phase:S,error:g,phases:f}}},executeSync:(S,v)=>{const C=g.createChild(`[phase=${S}]`);C.info("started"),recordPhaseStep(S);const _=(new Date).getTime();try{const g=v(),f=+new Date-_;return recordStepDoneTelemetry(S,f),C.logSuccess(`done, time=${f}`),g}catch(g){const v=+new Date-_;throw C.logFailure(`time=${v}, error=${getPrintableObject(g)}`),recordStepFailedTelemetry(S,v,g),{phase:S,error:g,phases:f}}},getTelemetryData:()=>f}}function callStateIsAnyOf(g,f){return-1!==f.indexOf(g)}var lr,cr,dr,hr={0:[1,2,8,6,10,11,9],1:[2,6,7,10,13],2:[1,3,6,7,9,10,13,14],3:[6,7,4,5,10,13],8:[1,11,10,2,9,6,7],4:[6,7,3,5,10,13],5:[6,7,3,4,10,13],9:[3,6,7,10,13],10:[3,6,7,9,4,5,13,15],13:[3,6,7,4,5],14:[3,6,7,10,13],15:[3,6,7,4,5,13],11:[12,1,2,6,7],12:[2,6,7],6:[7],7:[]};(g=>{let f;var S;let v;var C;let _;var T;let I;var b;(S=f=g.VideoEffectType||(g.VideoEffectType={})).Off="off",S.BackgroundBlur="blur",S.BackgroundReplacement="replacement",S.PresenterMode="presenterMode",S.None="none",(C=v=g.PowerPreference||(g.PowerPreference={})).Default="default",C.HighPerformance="high-performance",C.LowPower="low-power",(T=_=g.ProcessorType||(g.ProcessorType={})).Wasm="Wasm",T.Webgl2="Webgl2",(b=I=g.EffectQualityChangeReason||(g.EffectQualityChangeReason={}))[b.ExternalParam=0]="ExternalParam",b[b.Performance=1]="Performance",b[b.RendererSize=2]="RendererSize"})(lr||(lr={})),(g=>{let f;var S;let v;var C;let _;var T;let I;var b;let A;var P;(S=f=g.CallType||(g.CallType={}))[S.P2P=0]="P2P",S[S.Conference=1]="Conference",S[S.PSTN=2]="PSTN",S[S.BroadcastingConf=3]="BroadcastingConf",(C=v=g.AudioUsageMode||(g.AudioUsageMode={}))[C.Default=0]="Default",C[C.LongRangeSpeaker=1]="LongRangeSpeaker",C[C.Auditorium=2]="Auditorium",(T=_=g.AecPerfProfile||(g.AecPerfProfile={}))[T.Normal=0]="Normal",T[T.Soc=1]="Soc",T[T.Mobile=2]="Mobile",T[T.NoisyTimestamps=3]="NoisyTimestamps",(b=I=g.VqeMode||(g.VqeMode={}))[b.Off=0]="Off",b[b.SkypeNS=1]="SkypeNS",b[b.SkypeAEC=2]="SkypeAEC",b[b.SkypeVQE=3]="SkypeVQE",b[b.DeepNS=4]="DeepNS",b[b.DeepVQE=5]="DeepVQE",(P=A=g.AudioEffectType||(g.AudioEffectType={})).Off="Off",P.NoiseSuppressionDeep="Deep NS",P.NoiseSuppressionClassic="Classic NS",P.EchoCancellationClassic="Classic AEC",P.VoiceQualityEnhancementClassic="Classic VQE",P.VoiceQualityEnhancementDeep="Deep VQE"})(cr||(cr={})),(g=>{let f;var S;let v;var C;(S=f=g.FrameType||(g.FrameType={}))[S.None=0]="None",S[S.Software=1]="Software",S[S.Hardware=2]="Hardware",(C=v=g.LogLevel||(g.LogLevel={}))[C.Default=0]="Default",C[C.Debug=1]="Debug",C[C.Info=2]="Info",C[C.Warning=3]="Warning",C[C.Error=4]="Error"})(dr||(dr={}));var ur=M,gr=(g=>(g[g.CallStateChanged=0]="CallStateChanged",g[g.TrouterStateChanged=1]="TrouterStateChanged",g[g.MultiPartyModeSet=2]="MultiPartyModeSet",g[g.MediaRetargetSucceeded=3]="MediaRetargetSucceeded",g[g.MediaRetargetFailed=4]="MediaRetargetFailed",g))(gr||{}),pr=(g=>(g[g.StartModality=0]="StartModality",g[g.StopModality=1]="StopModality",g[g.StreamStateChanged=2]="StreamStateChanged",g[g.NegotiationStateChanged=3]="NegotiationStateChanged",g))(pr||{}),mr=(g=>(g[g.SelectSource=0]="SelectSource",g[g.AttachSource=1]="AttachSource",g[g.DetachSource=2]="DetachSource",g))(mr||{}),fr=(g=>(g[g.Available=0]="Available",g[g.Subscribe=1]="Subscribe",g[g.Subscribed=2]="Subscribed",g[g.Unsubscribe=3]="Unsubscribe",g[g.Unsubscribed=4]="Unsubscribed",g[g.RenderingStarted=5]="RenderingStarted",g[g.RenderingStopped=6]="RenderingStopped",g))(fr||{}),Sr=class{};Sr.agentEnvironmentId="agent_environment_id",Sr.correlationId="CorrelationId",Sr.participantId="participant_id",Sr.displayName="display_name",Sr.tenantId="TenantId",Sr.userHexCID="UserHexCID",Sr.acsResourceId="AcsResourceId",Sr.endpointId="endpoint_id",Sr.mediaLegId="media_leg_id",Sr.webMediaConfigIds="web_media_config_ids",Sr.tsCallingVersion="ts_calling_version",Sr.rpcSessionId="rpc_session_id";var vr=class{};vr.diagnostics="MediaDiagnostic",vr.qoeStats="QoE",vr.webrtcSession="webrtc_session",vr.webrtcSessionInitial="webrtc_session_initial",vr.realtimeTelemetry="realtimetelemetry",vr.webrtcMediaSession="webrtc_call_session",vr.mediaSession="pluginless_modality_session",vr.callSession="pluginless_call_session";var Cr=class{constructor(g){this.eventName=g,this.ended=!1,this.events=[]}setLocalUserId(g){this.localUserId=g}start(){this.ended||(this.startTime=Date.now())}end(g=0){this.ended||(this.ended=!0,this.resultCode=g)}asStatsRecord(g={}){if((0,ur.isEmpty)(this.events))return null;const f=(0,ur.uniqBy)(this.events,(g=>JSON.stringify(g))).map((g=>{const f={[g.type]:g.timestamp-this.startTime};return(0,ur.isEmpty)(g.data)||(f.data=g.data),f}));return{name:this.eventName,record:(0,ur.assign)({LocalUser:this.localUserId,ResultCode:String(this.resultCode),EventTimestampBag:JSON.stringify({eventStart:this.startTime,events:f})},g)}}add(g){!this.ended&&g.type&&((0,ur.isUndefined)(this.startTime)&&(this.startTime=Date.now()),(0,ur.isUndefined)(g.timestamp)&&(g.timestamp=Date.now()),this.events.push(g))}},yr=class _CallStats2 extends Cr{constructor(){super(vr.callSession)}callStateChanged(g){super.add({type:gr[0],data:_CallStats2.callStateToString[g]||g})}event(g){super.add({type:gr[g]})}};yr.callStateToString={0:"None",1:"Notified",2:"Connecting",3:"Connected",4:"LocalHold",5:"RemoteHold",6:"Disconnecting",7:"Disconnected",8:"Observing",10:"Lobby"};var Er=yr,_r=class _MediaModalityStats2 extends Cr{constructor(g,f){super(vr.mediaSession),this.mediaType=g,this.mediaDirection=f,this.streamDirection=_MediaModalityStats2.mediaDirectionToStream[this.mediaDirection]}addEvent(g,f){super.add({type:g,data:f})}lifecycle(g){this.addEvent(pr[g])}streamStateChanged(g,f=this.streamDirection){const S=pr[2];this.addEvent(S,{state:_MediaModalityStats2.streamStateToString[g],direction:_MediaModalityStats2.streamDirectionToString[f]})}negotiationStateChanged(g,f,S=this.streamDirection){const v=pr[3];this.addEvent(v,{state:_MediaModalityStats2.negotiationStateToString[g],reason:f})}asStatsRecord(g={}){return super.asStatsRecord((0,ur.assign)({MediaType:_MediaModalityStats2.mediaTypeToString[this.mediaType],Role:_MediaModalityStats2.mediaDirectionToRole[this.mediaDirection]},g))}};_r.negotiationStateToString={started:"NegotiationStarted",rejected:"NegotiationRejected",completed:"NegotiationCompleted"},_r.streamStateToString={created:"StreamCreated",started:"StreamStarted",active:"StreamActive",inactive:"StreamInactive",stopped:"StreamStopped",removed:"StreamRemoved",failed:"StreamFailed",cancelled:"StreamCancelled"},_r.streamDirectionToString={send:"Send",receive:"Receive"},_r.mediaTypeToString={0:"Audio",1:"Video",2:"ScreenShare",3:"Data"},_r.mediaDirectionToRole={1:"Receiver",2:"Sender",4:"Bidirectional"},_r.mediaDirectionToStream={1:"receive",2:"send"};var Tr=_r,Ir=class extends Tr{constructor(){super(0,4)}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}},br=class extends Tr{constructor(g){super(g,2),this.mediaType=g}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}event(g){super.addEvent(mr[g])}},Ar=class extends Tr{constructor(g,f){super(g,1),this.mediaType=g,this.remoteParticipantId=f,this.rendererCounter=0}newRendererId(){return this.rendererCounter+=1,String(this.rendererCounter)}event(g,f,S){super.addEvent(fr[g],(0,ur.isUndefined)(S)?{rendererId:f}:{rendererId:f,sourceId:S})}asStatsRecord(){return super.asStatsRecord({TargetUser:this.remoteParticipantId})}},Pr=class{constructor(){this.allStats=[],this.ended=!1}setLocalUserId(g){this.localUserId=g}get call(){return this.callStats||this.startCall()}get audio(){return this.audioStats||this.newSession(0)}get video(){return this.videoStats||this.newSession(1)}get screenShare(){return this.sharingStats||this.newSession(2)}renderer(g,f){let S=this.renderingStats[f];return S||(S=this.renderingStats[f]=this.receive(g,f)),S}startCall(){return this.callStats?this.callStats:(this.callStats=new Er,this.callStats.start(),this.addStats(this.callStats))}endCall(g=0){this.ended=!0,this.call.end(g),this.allStats.forEach((g=>g.end())),this.cleanUp()}cleanUp(){this.audioStats&&(this.audioStats.stop(),this.audioStats=null),this.videoStats&&(this.videoStats.stop(),this.videoStats=null),this.sharingStats&&(this.sharingStats.stop(),this.sharingStats=null)}newSession(g){let f;switch(g){case 0:f=this.audioStats=new Ir;break;case 1:f=this.videoStats=new br(g);break;case 2:f=this.sharingStats=new br(g)}return this.addStats(f)}receive(g,f){const S=new Ar(g,f);return S.start(),this.addStats(S)}buildStatsRecords(){return this.allStats.map((g=>g.asStatsRecord())).filter((g=>!!g))}addStats(g){return this.ended||(this.allStats.push(g),g.setLocalUserId(this.localUserId)),g}},Rr=class _CallTelemetryBuilder2{constructor(){this.startTime=Date.now(),this.localStats=new Pr,this.tsCallingVersion=getTsCallingVersion2()}setRpcSessionId(g){this.rpcSessionId=g}setCallId(g){this.callId=g}setTenantId(g){this.tenantId=g}setUserHexCID(g){this.userHexCID=g}setParticipantId(g){this.participantId=g}setDisplayName(g){this.displayName=g}setEndpointId(g){this.endpointId=g}setMediaLegId(g){this.mediaLegId=g}setMediaStats(g){this.mediaStats=g}setAcsResourceId(g){this.acsResourceId=g}appendDataChannelInfo(g){this.mediaStats?.data&&g&&(this.mediaStats.data.DataHandlers=g)}appendSharingControlInfo(g){this.mediaStats?.data&&(this.mediaStats.data.SharingControlEnabled=g?"true":"false")}appendMediaControlPlaneInfo(g){this.mediaStats?.data&&g&&(this.mediaStats.data.MediaControlPlane=g)}appendTerminationInfo(g,f){this.mediaStats?.data&&(this.mediaStats.data.TerminatedReason=`${g}`,this.mediaStats.data.TerminatedState=`${f}`)}appendPictureInPictureInfo(g){this.mediaStats?.data&&g&&(this.mediaStats.data.PictureInPicture=g)}appendCallDeviceManagerInfo(g){this.mediaStats?.data&&g&&(this.mediaStats.data.CallDeviceManager=g)}async buildVDItelemetryReport(g){const{transport:f,rpc:S,rpcRemote:v,transportRemote:C}=await g.getStats(this.startTime);return{CallId:this.callId,ParticipantId:this.participantId,Transport:JSON.stringify(f),Rpc:JSON.stringify(S),Rpc_Remote:JSON.stringify(v),Transport_Remote:JSON.stringify(C)}}buildFromMediaStats(){return"WebRtcMediaStats"===this.mediaStats?.type?[this.buildEvent(this.mediaStats.data,vr.webrtcSession)]:[]}buildShortCallEvent(g){const f={};return f[Sr.correlationId]=this.callId||"",f[Sr.participantId]=this.participantId||"",f[Sr.displayName]=new Ue(this.displayName||"",1),f[Sr.tenantId]=this.tenantId||"",f[Sr.tsCallingVersion]=this.tsCallingVersion||"",f[Sr.rpcSessionId]=this.rpcSessionId||"",f.metrics_TerminationReason_code=new Ue(g.data.metrics.TerminationReason_code,0),f.metrics_TerminationReason_subCode=new Ue(g.data.metrics.TerminationReason_subCode,0),f.metrics_eventType=new Ue(g.eventType,0),[{eventName:vr.webrtcMediaSession,props:this.buildProps(g.data,null,f)}]}buildMediaTelemetry(){if(!this.mediaStats)return;const g=this.buildEvent(this.mediaStats.data,null).props,f={};return Object.keys(g).forEach((S=>{void 0===g[S].piiKind?f[S]=g[S]:f[S]=g[S].value})),f}buildMidCallTelemetry(g){if(!this.mediaStats)return[];const f=this.buildEvent(this.mediaStats.data,vr.webrtcSession),S=f.props,v=g.reduce(((g,f)=>(S[f]&&(g[f]=S[f]),g)),{});return[{eventName:f.eventName,props:v}]}buildFromCallSetupStats(g){return"WebRtcMediaStats"===this.mediaStats?.type?(this.mediaStats.data.trouterUrl=g,[this.buildEvent(this.mediaStats.data,vr.webrtcSessionInitial)]):[]}buildFromLocalStats(){return this.localStats.buildStatsRecords().map((g=>this.buildEvent(g.record,g.name)))}buildEvent(g,f){const S={};return S[Sr.agentEnvironmentId]=_CallTelemetryBuilder2.agentEnvironmentId,S[Sr.correlationId]=this.callId||"",S[Sr.tenantId]=this.tenantId||"",S[Sr.userHexCID]=this.userHexCID||"",S[Sr.participantId]=this.participantId||"",S[Sr.displayName]=new Ue(this.displayName||"",1),S[Sr.endpointId]=this.endpointId||"",S[Sr.mediaLegId]=this.mediaLegId||"",S[Sr.webMediaConfigIds]=this.webMediaConfigIds||"",S[Sr.tsCallingVersion]=this.tsCallingVersion||"",S[Sr.acsResourceId]=this.acsResourceId||"",S[Sr.rpcSessionId]=this.rpcSessionId||"",{eventName:f,props:this.buildProps(g,null,S)}}normalizeKey(g){return g.replace(/[^a-zA-Z0-9._]/g,"_")}buildProps(g,f,S){return Object.keys(g).forEach((v=>{const C=this.normalizeKey(v),_=f?`${f}_${C}`:C,T=g[v];if((0,ur.isString)(T))S[_]=this.getPiiAwareValue(v,T);else if((0,ur.isArray)(T)){if(T.length>0){const g=T,f=g.map((g=>g.value)).toString();S[_]=new Ue(f,g[0].type)}}else if((0,ur.isObject)(T))if(T.__VALUE__){const g=T;(0,ur.isBoolean)(g.value)&&(g.value=g.value?"true":"false"),S[_]=new Ue(g.value,g.type)}else this.buildProps(T,_,S)})),S}getPiiAwareValue(g,f){return _CallTelemetryBuilder2.piiProps.hasOwnProperty(g)?new Ue(f,_CallTelemetryBuilder2.piiProps[g]):f}build(){return(0,ur.flatten)([this.buildFromMediaStats(),this.buildFromLocalStats()])}};Rr.agentEnvironmentId=generateGuid(),Rr.piiProps={IPAddr:13,MACAddr:13,IPAddress:13,OpaqueData:0,LocalSite:13,RemoteSite:13,BaseAddress:13,LocalAddress:13,RemoteAddress:13,NetworkName:12,LocalUser:10,TargetUser:10,[Sr.displayName]:1};var Mr=Rr,wr=M;function convertReason(g){return g?getTerminationCode(g.code,g.subCode):0}function convertSignalingEndpointDetails(g,f){const S={clientVersion:g.clientVersion,participantId:g.participantId,endpointId:g.endpointId,endpointType:g.endpointType,endpointMetadata:g.endpointMetadata,originalId:g.originalId,capabilities:g.capabilities,clientEndpointCapabilities:g.clientEndpointCapabilities,mappedTo:g.mappedTo,meetingGroupDetails:g.meetingGroupDetails,endpointMeetingRoles:g.endpointMeetingRoles};return g.mediaStreams&&(S.mediaStreams=g.mediaStreams),g.appliedInteractivityLevel&&(S.appliedInteractivityLevel=g.appliedInteractivityLevel),g.deviceType&&(S.deviceType=g.deviceType),g.streamInformation&&32&f&&(S.streamInformation=g.streamInformation),g.propertyBag&&(S.propertyBag=g.propertyBag),g.negotiationTag&&(S.negotiationTag=g.negotiationTag),S}function getTerminationCode(g,f=null){if(g===Fi.Success)switch(f){case xi.RemovedFromConversation:case xi.RemovedFromCall:return 44;case xi.DeniedInLobby:return 55;case xi.TimedOutInLobby:return 56;default:return 1}if(null!==f&&f>=2e5&&f<=299999){const g=f-2e5;return Vi[g]?Vi[g]:0}return null!==f&&f>=4e5&&f<=499999?Bi[g]?Bi[g]:43:g===Fi.Forbidden?f===xi.UserBlocked?64:f===xi.PolicyRestriction?62:f===xi.AnonymousJoinDisabledByPolicy?66:f===xi.NoLobbyForBroadcastJoin?67:f===xi.NotAllowedDueToInformationBarrier?68:f===xi.TeamParkPolicyDisabled?70:f===xi.B2bJoinDisabledByPolicy?71:(Fi.Success,8):g===Fi.PreconditionFailed&&f===xi.InsufficientCapabilities?63:g===Fi.ServiceUnavailable?f===xi.BroadcastLimitReached?69:48:g===Fi.InternalServerError?7:g===Fi.ConfParticipantCountLimitReached?f===xi.MaxLobbyParticipantLimitReached?73:59:Ui[g]?Ui[g]:g}function getCSAEndCode(g){if(1===g)return Fi.Success;const f=Object.keys(Ui).filter((f=>Ui[f]===g));if(f.length>=1)for(const S of f){const f=parseInt(S);if(f&&Ui[f]===g)return f}return Fi.UnknownError}function getMediaState(g,f){if(void 0!==f&&3!==f&&1!==f)return{mediaType:g,isDisabled:0===f,label:getMediaLabel(g)}}function getCallStartOptions(g){if(g.sendMediaModalities)return g;const f={mediaStates:[]};let S=getMediaState(0,g.audioDirection?g.audioDirection:4);return S&&f.mediaStates.push(S),S=getMediaState(1,g.withVideo?4:g.videoDirection),S&&f.mediaStates.push(S),S=getMediaState(2,g.screenshareDirection?g.screenshareDirection:1),S&&f.mediaStates.push(S),g.sendMediaModalities=f,g}function convertRedirectOptions(g){const f=convertRedirectionTargetIdType(g.type),S=convertRedirectionEndpointType(g.endpointType);return{type:f,id:g.id,endpointType:S}}function convertRedirectionTargetIdType(g){if("mri"===g)return"mri";throw"Unknown RedirectionTargetIdType"}function convertRedirectionEndpointType(g){switch(g){case"voicemail":return"voicemail";case"default":return"default";default:throw"Unknown RedirectionEndpointType"}}var Or=class{constructor(g){this.mediaStateConfiguration=g}isDisabled(g){if(this.mediaStateConfiguration?.mediaStates){const f=this.mediaStateConfiguration.mediaStates.find((f=>f.mediaType===g));return!!f&&!!f.isDisabled}return!1}isInactiveOrDisabled(g){if(this.mediaStateConfiguration?.mediaStates){const f=this.mediaStateConfiguration.mediaStates.find((f=>f.mediaType===g));return!f||!!f.isDisabled}return!1}isSending(g){return!!this.mediaStateConfiguration?.mediaStates&&!!this.mediaStateConfiguration.mediaStates.find((f=>f.mediaType===g&&!f.isDisabled))}disableModality(g){this.setModality(g,!0)}enableModality(g){this.setModality(g,!1)}removeModality(g){this.mediaStateConfiguration?.mediaStates&&(0,wr.remove)(this.mediaStateConfiguration.mediaStates,(f=>f.mediaType===g))}setCallAcceptOptions(g){const f=this.isDisabled(1),S=this.isDisabled(2),v=this.isSending(3);if(g.sendMediaModalities)this.mediaStateConfiguration=g.sendMediaModalities;else{void 0===g.answerMediaType&&(g.answerMediaType=g.withVideo?1:0);const f={mediaStates:[]};switch(g.answerMediaType){case 0:f.mediaStates.push(getMediaState(0,4));break;case 1:f.mediaStates.push(getMediaState(0,4)),f.mediaStates.push(getMediaState(1,4));break;case 2:f.mediaStates.push(getMediaState(1,0))}this.mediaStateConfiguration=f}f&&this.setModality(1,!0),S&&this.setModality(2,!0),v&&this.setModality(3,!1),g.sendMediaModalities=this.mediaStateConfiguration}setModality(g,f){if(this.mediaStateConfiguration?.mediaStates){const S=this.mediaStateConfiguration.mediaStates.find((f=>f.mediaType===g));S?S.isDisabled=f:this.mediaStateConfiguration.mediaStates.push({mediaType:g,isDisabled:f,label:getMediaLabel(g)})}}};function hasValue2(g){return g||!1===g||""===g||0===g}function scrubCallOptions(g){const f={};hasValue2(g.callStartTime)&&(f.callStartTime=g.callStartTime),hasValue2(g.callVoicemailStartOptions)&&(f.callVoicemailStartOptions=g.callVoicemailStartOptions),hasValue2(g.invitationType)&&(f.invitationType=g.invitationType),hasValue2(g.meetingPreferences)&&(f.meetingPreferences=g.meetingPreferences),hasValue2(g.parkContext)&&(f.parkContext=g.parkContext),hasValue2(g.pickupCode)&&(f.pickupCode=g.pickupCode),hasValue2(g.participantsToNudge)&&(f.participantsToNudgeSize=g.participantsToNudge.length);const S=g.callStartOptions;if(S){const g={};hasValue2(S.additionalEndpointProperties)&&(g.additionalEndpointProperties=S.additionalEndpointProperties),hasValue2(S.clientEndpointCapabilities)&&(g.clientEndpointCapabilities=S.clientEndpointCapabilities),hasValue2(S.connectionType)&&(g.connectionType=S.connectionType),hasValue2(S.invitationDataJson)&&(g.invitationDataJson=S.invitationDataJson),hasValue2(S.isCast)&&(g.isCast=S.isCast),hasValue2(S.isHuddleGroupCall)&&(g.isHuddleGroupCall=S.isHuddleGroupCall),hasValue2(S.label)&&(g.label=S.label),hasValue2(S.maxVideoChannels)&&(g.maxVideoChannels=S.maxVideoChannels),hasValue2(S.maxVbssChannels)&&(g.maxVbssChannels=S.maxVbssChannels),hasValue2(S.mediaConfiguration)&&(g.mediaConfiguration=S.mediaConfiguration),hasValue2(S.muteFlags)&&(g.muteFlags=S.muteFlags),hasValue2(S.muted)&&(g.muted=S.muted),hasValue2(S.negotiationTag)&&(g.negotiationTag=S.negotiationTag),hasValue2(S.preheatFlags)&&(g.preheatFlags=S.preheatFlags),hasValue2(S.ringOthers)&&(g.ringOthers=S.ringOthers),hasValue2(S.routingFlags)&&(g.routingFlags=S.routingFlags),hasValue2(S.scenario)&&(g.scenario=S.scenario),hasValue2(S.screenshareDirection)&&(g.screenshareDirection=S.screenshareDirection),hasValue2(S.sendMediaModalities)&&(g.sendMediaModalities=S.sendMediaModalities),hasValue2(S.sharedLineCallInvitationContentJson)&&(g.sharedLineCallInvitationContentJson=S.sharedLineCallInvitationContentJson),hasValue2(S.targetApplicationType)&&(g.targetApplicationType=S.targetApplicationType),hasValue2(S.captchaContentJson)&&(g.captchaContentJson=S.captchaContentJson),hasValue2(S.callQueueContext)&&(g.callQueueContext=S.callQueueContext),hasValue2(S.clientEndpointDebugContent)&&(g.clientEndpointDebugContentSize=S.clientEndpointDebugContent.length),hasValue2(S.alternateId)&&(g.alternateId=scrubMriOrOmit(S.alternateId)),hasValue2(S.callKey)&&(g.callKeySize=S.callKey.length),hasValue2(S.encryptedKey)&&(g.encryptedKeySize=S.encryptedKey.length),f.callStartOptions=g}return f}function getAgentMediaType(g){switch(g){case 0:return"Audio";case 1:return"Video";case 2:return"ScreenShare"}throw new Error("MediaType required")}function getSkypeMediaType(g){switch(g){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2}throw new Error("MediaType required")}function mapMonitorActionType(g){switch(g){case 0:return"Monitor";case 1:return"Whisper";case 2:return"Barge";case 3:return"Takeover";default:return}}var Dr={NEGOTIATION_COMPLETED:"NegotiationCompleted",INITIAL:{OFFER_GENERATION_STARTED:"InitialOfferGenerationStarted",OFFER_GENERATION_ENDED:"InitialOfferGenerationEnded",ANSWER_PROCESSING_STARTED:"InitialAnswerProcessingStarted",ANSWER_PROCESSING_ENDED:"InitialAnswerProcessingEnded",OFFER_PROCESSING_STARTED:"InitialOfferProcessingStarted",OFFER_PROCESSING_ENDED:"InitialOfferProcessingEnded",ANSWER_GENERATION_STARTED:"InitialAnswerGenerationStarted",ANSWER_GENERATION_ENDED:"InitialAnswerGenerationEnded"},RENEGOTIATION:{OFFER_GENERATION_STARTED:"RenegotiationOfferGenerationStarted",OFFER_GENERATION_ENDED:"RenegotiationOfferGenerationEnded",ANSWER_PROCESSING_STARTED:"RenegotiationAnswerProcessingStarted",ANSWER_PROCESSING_ENDED:"RenegotiationAnswerProcessingEnded",OFFER_PROCESSING_STARTED:"RenegotiationOfferProcessingStarted",OFFER_PROCESSING_ENDED:"RenegotiationOfferProcessingEnded",ANSWER_GENERATION_STARTED:"RenegotiationAnswerGenerationStarted",ANSWER_GENERATION_ENDED:"RenegotiationAnswerGenerationEnded"}},Nr=class{constructor(g,f){this.mediaSession=g,this.signalingSession=f,this.operationNames=Dr.INITIAL,this.configureModalitiesAsync=this.mediaSession.configureModalitiesAsync.bind(this.mediaSession),this.getAllowedModalities=this.mediaSession.getAllowedModalities.bind(this.mediaSession),this.rejectNegotiationAsync=this.mediaSession.rejectNegotiationAsync.bind(this.mediaSession),this.createRemoteRenderer=this.mediaSession.createRemoteRenderer.bind(this.mediaSession),this.getStatsAsync=this.mediaSession.getStatsAsync.bind(this.mediaSession),this.getLastKnownStats=this.mediaSession.getLastKnownStats.bind(this.mediaSession),this.getCallTechnicalInfo=this.mediaSession.getCallTechnicalInfo.bind(this.mediaSession),this.muteHold=this.mediaSession.muteHold.bind(this.mediaSession),this.muteInputAsync=this.mediaSession.muteInputAsync.bind(this.mediaSession),this.unmuteInputAsync=this.mediaSession.unmuteInputAsync.bind(this.mediaSession),this.muteOutputAsync=this.mediaSession.muteOutputAsync.bind(this.mediaSession),this.unmuteOutputAsync=this.mediaSession.unmuteOutputAsync.bind(this.mediaSession),this.getSpeakerVolume=this.mediaSession.getSpeakerVolume.bind(this.mediaSession),this.setSpeakerVolume=this.mediaSession.setSpeakerVolume.bind(this.mediaSession),this.terminate=this.mediaSession.terminate.bind(this.mediaSession),this.createAudioElement=this.mediaSession.createAudioElement.bind(this.mediaSession),this.getSessionConfig=this.mediaSession.getSessionConfig.bind(this.mediaSession),this.getDiagnostics=this.mediaSession.getDiagnostics.bind(this.mediaSession),this.getIncomingRawAudioStream=this.mediaSession.getIncomingRawAudioStream.bind(this.mediaSession),this.getUnmixedAudioProvider=this.mediaSession.getUnmixedAudioProvider.bind(this.mediaSession),this.useNullAudioStreamClient=this.mediaSession.useNullAudioStreamClient.bind(this.mediaSession),this.getSubscriptionManager=this.mediaSession.getSubscriptionManager.bind(this.mediaSession),this.configureSpatialAudio=this.mediaSession.configureSpatialAudio.bind(this.mediaSession),this.setParticipantSpatialAudioPositions=this.mediaSession.setParticipantSpatialAudioPositions.bind(this.mediaSession),this.setCallConstraints=this.mediaSession.setCallConstraints.bind(this.mediaSession),this.startMediaDescriptionsUpdateAsync=this.mediaSession.startMediaDescriptionsUpdateAsync.bind(this.mediaSession),this.completeMediaDescriptionsUpdateAsync=this.mediaSession.completeMediaDescriptionsUpdateAsync.bind(this.mediaSession),this.rejectMediaDescriptionsUpdateAsync=this.mediaSession.rejectMediaDescriptionsUpdateAsync.bind(this.mediaSession),this.registerRemoteQualityStateChangedEvent=this.mediaSession.registerRemoteQualityStateChangedEvent.bind(this.mediaSession),this.getMediaControlPlaneInstance=this.mediaSession.getMediaControlPlaneInstance.bind(this.mediaSession)}enableTeamsRealTimeTelemetry(){this.mediaSession.enableTeamsRealTimeTelemetry()}getMediaStatsReport(){return this.mediaSession.getMediaStatsReport()}processOfferAsync(g,f){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_STARTED),this.mediaSession.processOfferAsync(g,f).then((g=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_ENDED),g)))}createAnswerAsync(g,f){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_STARTED),this.mediaSession.createAnswerAsync(g,f).then((f=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_ENDED),g||(this.operationNames=Dr.RENEGOTIATION),f)))}createOfferAsync(g,f){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_STARTED),this.mediaSession.createOfferAsync(g,f).then((g=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_ENDED),g)))}processAnswerAsync(g,f,S,v=!1){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_STARTED),this.mediaSession.processAnswerAsync(g,f,S,v).then((()=>{this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_ENDED),this.operationNames=Dr.RENEGOTIATION}))}completeNegotiationAsync(g){return this.mediaSession.completeNegotiationAsync(g).then((g=>(this.signalingSession.setOfferAnswerGenerationTimestamps(Dr.NEGOTIATION_COMPLETED),g)))}sendDtmf(g){return this.mediaSession.sendDtmf?this.mediaSession.sendDtmf(g):Promise.reject("Not Implemented")}reconnectAsync(g,f=!1,S){return this.mediaSession.reconnectAsync(g,f,S)}completeEscalationAsync(g){return this.mediaSession.completeEscalationAsync(g)}rejectEscalationAsync(g,f){return this.mediaSession.rejectEscalationAsync(g,f)}getAcceptedTypes(){return this.mediaSession.getAcceptedTypes()}getLocalMediaTrackId(g){return this.mediaSession.getLocalMediaTrackId?this.mediaSession.getLocalMediaTrackId(g):null}processNotification(g,f){this.mediaSession.processNotification(g,f)}};function handleServerMutedVersion(g,f,S){if(void 0===f?.serverMuteVersion||void 0===S?.serverMuteVersion||S.serverMuteVersion>=f.serverMuteVersion)return;const v=S&&S.mediaStreams,C=v&&v.filter((g=>"audio"===g.type||"audio-teleconferencing"===g.type)),_=f&&f.mediaStreams,T=_&&_.filter((g=>"audio"===g.type||"audio-teleconferencing"===g.type));C&&C.length&&(S.serverMuteVersion=f.serverMuteVersion,C[0].serverMuted=T[0].serverMuted,g.info(`handleServerMutedVersion: patching server muted state in audio streams updated:${JSON.stringify(C[0])} as we encountered stale muteServerVersion. Updated to ${f.serverMuteVersion}`))}function handleMuteUnmuteParticipantInfo(g,f,S,v){if("success"!==S.reason||void 0===f||S.serverMuteVersion<=f.serverMuteVersion)return g.info(`handleMuteUnmuteParticipantInfo: ignoring updating since we encountered invalid state: ${S.reason} serverMuteVersion: ${S.serverMuteVersion}`),!1;const C=f&&f.mediaStreams,_=C&&C.filter((g=>"audio"===g.type||"audio-teleconferencing"===g.type));return!!_&&(_[0].serverMuted=v,f.serverMuteVersion=S.serverMuteVersion,g.info(`handleMuteUnmuteParticipantInfo: updating since we encountered valid state serverMuteVersion: ${S.serverMuteVersion} to: ${v} streams: ${_[0].sourceId}`),!0)}var kr=R;function scrub(g,f,S,v){const C=JSON.stringify(g),_=JSON.parse(C);return _&&(scrubOneTypeOfParams(g,_,f,kr.pii.Omit),scrubOneTypeOfParams(g,_,S,kr.pii.Mri),scrubOneTypeOfParams(g,_,v,kr.pii.UserName)),JSON.stringify(_)}function scrubOneTypeOfParams(g,f,S,v){S?.forEach((S=>{g[S]&&(f[S]=v(g[S]))}))}function scrubSignalingParticipant(g){return`id=${kr.pii.Mri(g.id)}, participantId=${g.participantId}`}function scrubITransferContext(g){const f=[],S=["transferorMri","targetMri"];return scrub(scrubObjectFields(g),f,S)}var Lr=M,Fr=C.setImmediate?g=>{C.setImmediate(g)}:g=>{(0,Lr.defer)(g)},xr=class _DeferHandler2{constructor(){this.deferredOperations=new Map,this.deferredOperationsNames=[],this.isRunning=!1}setLogger(g){this._logger=g.createChild("[DeferHandler]")}setDeferToQueueMicrotask(g){g&&C.queueMicrotask?_DeferHandler2.defer=g=>C.queueMicrotask(g):_DeferHandler2.defer=Fr}createDeferRunner(g){const f={};return S=>this.runDeferred(f,S,g)}runDeferredWithoutDedup(g,f){const S={};this.runDeferred(S,g,f)}runDeferred(g,f,S){this.deferredOperations.has(g)||(this.deferredOperations.set(g,f),S&&this.deferredOperationsNames.push(" "+S),this.isRunning||(this.isRunning=!0,this._startDeferalTime=Date.now(),this.causeId=generateCauseId(),this._logger?.info(`[${this.causeId}]Deferring operations`),_DeferHandler2.defer((()=>{this._timeToRun=Date.now()-this._startDeferalTime,this.deferredOperations.forEach((g=>{_DeferHandler2.runWithTryCatch(g)})),this.deferredOperations.clear(),this.isRunning=!1,this._logger?.info(`[${this.causeId}]Deferred operations ran after ${this._timeToRun}ms | Completed after ${Date.now()-this._startDeferalTime}ms | Operations:${this.deferredOperationsNames}`),this.deferredOperationsNames=[]}))))}static runWithTryCatch(g){try{g&&g()}catch(g){}}};xr.defer=Fr;var Ur=xr,Vr=class{};Vr.instance=new Ur;var Br=M,Hr={send:"sendonly",receive:"recvonly",sendReceive:"sendrecv"},$r={audio:"audio",video:"video",sharing:"applicationsharing-video",audioteleconference:"audio-teleconferencing",xsharing:"xapplicationsharing-video"},jr=class extends Ke{constructor(g,f,S){super(f),this.mediaSession=g,this.isAvailable=!1,this.mediaSessionInitPromise=new dt,this.currentIsStreaming=!1,g&&this.mediaSessionInitPromise.resolve(),this.id=S,this.logger=f.createChild(`Stream[${this.id}]`)}set isStreaming(g){this.currentIsStreaming=g,this.logger.info(`isStreaming has changed to ${this.currentIsStreaming}`),this.raiseChanged()}get isStreaming(){return this.currentIsStreaming}update({sourceId:g=null,direction:f=Hr.receive,participantId:S=null,endpointId:v=null}={},C,_){this.logger.info(`[${C}][update before]  sourceId=${g}, direction=${f}, isAvailable=${this.isAvailable}, participantId=${S}, endpointId=${truncate(v,8)}, ${this.negotiationTag?`, negotiationTag=${this.negotiationTag}`:""}`),this.id=g;const T=f===Hr.sendReceive||f===Hr.send;this.isAvailable!==T&&(this.negotiationTag=_?.get(v)),this.isAvailable=T,this.mediaSession?.getSessionConfig().config.streamAvailabilityConsiderModalities&&this.getIsModalityDisabled()&&(this.logger.info(`Disabling current modality, disabled: ${JSON.stringify(this.mediaSession?.getDisabledModalities?.()||"")}`),this.isAvailable=!1),this.participantId=S,this.endpointId=v,this.logger.info(`[${C}][update after]  sourceId=${g}, direction=${f}, isAvailable=${this.isAvailable}, participantId=${S}, endpointId=${truncate(v,8)}, ${this.negotiationTag?`, negotiationTag=${this.negotiationTag}`:""}`),this.raiseChanged()}setMediaSession(g,f){const S=g?.getAllowedModalities?.()||{};this.logger.info(`[${f}][setMediaSession] ${JSON.stringify(S)}`),this.mediaSession=g,g?this.mediaSessionInitPromise.resolve():this.mediaSessionInitPromise.reject(new Error("MediaSession is null"))}isActive(){return this.isAvailable&&this.isStreaming}getIsModalityDisabled(){return!1}},Gr=class extends jr{},qr=M,Wr=class extends jr{constructor(g,f,S,v,C,_){super(void 0,g,f),this.configProvider=S,this.streamOptions=v,this.telemetryLogger=C,this.callInfo=_,this.type=2,this.finalTelemetrySent=!1,this.player=new Dt(g.createChild("UmsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger),this.isAvailable=!0}getStreamOptions(){return this.streamOptions}getDiagnosticData(){return JSON.stringify({id:this.id,type:this.type,rank:this.rank,isAvailable:this.isAvailable,isStreaming:this.isStreaming})}getStats(){const g=this.player.getSnapshotTelemetryReport(),f={isAvailable:this.isAvailable,isStreaming:this.isStreaming,...g};return(0,qr.isEqual)(this.lastStreamStats,f)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=f),{id:this.id,type:this.type,timestampUpdated:this.streamStatsUpdatedTimestamp,rank:this.rank,...this.lastStreamStats}}stop(){return Promise.resolve(void 0)}async start(g){if(this.logger.info("[start]: Starting UMS stream"),!this.renderer){if(await this.player.configure(this.streamOptions),!(await this.player.loadPlayer(g)).setupSucceeded)return this.player.stop(),this.logger.error("[start]: Failed to load UMS player"),Promise.reject("Failed to load UMS player");this.renderer=this.player.getRenderer()}return this.isStreaming=!0,this.renderer}sendSnapshotTelemetry(){const g=this.player.getSnapshotTelemetryReport();this.logger.debug(`[sendSnapshotTelemetry] sending snapshot telemetry report: ${JSON.stringify(g)}`);const f={...this.callInfo,...g};this.telemetryLogger.sendEvent({eventName:"live_events",props:f})}sendTelemetry(g){if(this.finalTelemetrySent)return;g&&(this.finalTelemetrySent=!0);const f=this.player.getTelemetryReport();this.logger.debug(`[sendTelemetry] sending telemetry report: ${JSON.stringify(f)}`);const S={...this.callInfo,...f};this.telemetryLogger.sendEvent({eventName:"live_events",props:S})}};function toMediaAgentScalingMode(g){switch(g){case 1:return"crop";case 0:return"stretch";default:return"fit"}}var zr=class extends Ke{constructor(){super(...arguments),this.isRendering=!1,this.frameType=-1}get rendererType(){return 0}captureFrame(){if(this.renderer.captureFrame)return this.renderer.captureFrame();throw new Error("Not implemented yet")}async getStats(){if(this.renderer.getStats)return this.renderer.getStats();throw new Error("Renderer does not support stats")}async setScalingMode(g){this.renderer.setScalingMode(toMediaAgentScalingMode(g))}async cameraAutoControl(g){throw new Error("Not implemented")}async getCameraManualControlStates(g){throw new Error("Not implemented")}async setCameraManualControlStates(g){throw new Error("Not implemented")}async enumerateCameraManualControls(){throw new Error("Not implemented")}async isCameraAdvancedControlCapable(){throw new Error("Not implemented")}onVideoSizeChanged(g,f){this.streamSize={width:g,height:f},this.event("videoSizeChanged").raise(g,f),this.raiseChanged()}},Kr=class extends zr{constructor(g,f,S){super(),this.renderer=f.createPreviewRenderer(g,S),this.renderer.on("onVideoSizeChanged",((g,f)=>this.onVideoSizeChanged(g,f)))}onVideoSizeChanged(g,f){this.isRendering=g>0&&f>0,super.onVideoSizeChanged(g,f)}setVideoMirroring(g){this.renderer.setVideoMirroring(g)}startVideoAsync(){return this.renderer.startVideoAsync()}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer=null)}},Jr=class extends zr{constructor(g,f,S,v,C){super(),this.logger=g,this.target=f,this.rendererStats=v,this.configProvider=C,this.subscriptionActive=!1,this.firstFrameRendered=!1,this.rendererId=v.newRendererId(),this.renderer=S.createRemoteRenderer(f),this.renderer.on("onVideoSizeChanged",((g,f)=>this.onVideoSizeChanged(g,f))),this.renderer.on("onVideoStateChanged",(g=>this.onVideoStateChanged(g))),this.renderer.on("onIsRenderingChanged",(g=>this.onIsRenderingChanged(g)))}toString(){return`rvr:${this.rendererId}`}onVideoStateChanged(g){this.rendererStats.streamStateChanged(g.stream)}onVideoSizeChanged(g,f){this.configProvider.config.videoIsRenderingCheck&&this.setIsRendering(g>0&&f>0),super.onVideoSizeChanged(g,f)}setIsRendering(g){this.isRendering!==g&&(this.isRendering=g,this.logger.info(`isRendering has changed to ${this.isRendering}`),this.rendererStats.event(this.isRendering?5:6,this.rendererId),this.isRendering&&!this.firstFrameRendered&&(this.firstFrameRendered=!0,this.event("firstFrameRendered").raise()))}onIsRenderingChanged(g){this.setIsRendering(g),this.raiseChanged()}subscribeVideoAsync(g){this.currentVideoStream=g,this.rendererStats.event(1,this.rendererId,g.id);const f=this.renderer.subscribeVideoAsync(g.id,1===g.type);return this.subscriptionActive=!0,f.then((()=>{this.rendererStats.event(2,this.rendererId,g.id),this.watchStream(g)})),f}watchStream(g){this.changeSub&&this.changeSub.dispose(),this.changeSub=g.changed((()=>{g.isAvailable?this.subscriptionActive||this.subscribeVideoAsync(g):(this.subscriptionActive=!1,this.rendererStats.event(3,this.rendererId),this.renderer.unsubscribeNow(),this.rendererStats.event(4,this.rendererId))}))}dispose(){this.renderer&&(this.subscriptionActive&&(this.rendererStats.event(3,this.rendererId),this.currentVideoStream&&!this.currentVideoStream.isAvailable&&this.renderer.unsubscribeNow()),this.renderer.dispose(),this.subscriptionActive&&this.rendererStats.event(4,this.rendererId),this.renderer=null,this.currentVideoStream=null),this.changeSub&&(this.changeSub.dispose(),this.changeSub=null)}},Yr=class extends Ke{constructor(g,f,S){super(S),this.getRawStream=g,this.disposeStream=f,this.logger=S,this.isClientDisposed=!1,this.clientId=uniqueId()}get isDisposed(){return this.isClientDisposed}notifyStreamChange(){this.logger.info(`clientId:${this.clientId} - Stream changed`),this.raiseChanged(),this.event("notifiedOnStreamChanged").raise(this.clientId)}async getMediaStream(){return this.checkDisposed(),this.logger.info(`clientId:${this.clientId} - Stream requested`),this.event("rawStreamRequested").raise(this.clientId),this.getRawStream()}dispose(){this.checkDisposed(),this.disposeStream?.(),this.isClientDisposed=!0,this.event("clientDisposed").raise(this.clientId),super.dispose(),this.logger.info(`clientId:${this.clientId} - Raw stream client disposed`)}checkDisposed(){if(this.isClientDisposed)throw new Error("Raw stream client is already disposed")}},Qr=class{constructor(g,f){this.stream=g,this.rawBaseClient=new Yr((async()=>this.stream),(()=>this.dispose()),f)}client(){return this.rawBaseClient}updateAndNotifyClient(g){this.rawBaseClient&&(this.stream=g,this.rawBaseClient.notifyStreamChange())}dispose(){this.rawBaseClient=null,this.stream=null}},Xr=class{constructor(g,f,S){this.videoStream=g,this.subscriptionManager=f,this.logger=S,this.subscriptionActive=!1,this.modality=0===g.type?qt.MODALITY.video:qt.MODALITY.sharing,this.createSubscription(),this.rawBaseClient=new Yr((async()=>this.subscriptionClient?.subscribedStream),(()=>this.unsubscribeVideo()),S),this.videoStream.changed((()=>{this.rawBaseClient?.isDisposed||(this.logger.info(`isAvailable: ${g.isAvailable}, subscriptionActive: ${this.subscriptionActive}`),g.isAvailable?this.subscriptionActive||this.createSubscription():(this.subscriptionActive=!1,this.unsubscribeVideo()))}))}client(){return this.rawBaseClient}createSubscription(){this.rawBaseClient?.isDisposed?this.logger.error("createSubscription skipped, raw stream client disposed: stream already exists"):(this.logger.info("createSubscription: Creating new subscription"),this.subscriptionClient=this.subscriptionManager.subscribeVideo(this.modality,this.videoStream.mediaSourceId),this.setClientSubscription(),this.subscriptionActive=!0)}unsubscribeVideo(){this.logger.info("unsubscribeVideo: Disposing subcription"),this.subscriptionClient?.unsubscribe(),this.subscriptionClient?.dispose(),this.subscriptionClient=null}setClientSubscription(){this.logger.info("setClientSubscription: setting onMediaStreamChanged callback"),this.subscriptionClient.setOnMediaStreamChangedHandler((()=>this.rawBaseClient?.notifyStreamChange()))}},Zr=class{constructor(g){this.logger=g,this.handlerMap=new Map}dispose(){this.logger.info("dispose"),this.handlerMap.forEach((g=>g.client().dispose())),this.handlerMap.clear()}handlerAdded(g){const f=g.client();f.on("clientDisposed",(()=>this.deleteRawStreamManagerById(f.clientId))),this.handlerMap.set(f.clientId,g)}deleteRawStreamManagerById(g){this.handlerMap.delete(g)}},es=class extends Zr{constructor(g){super(g)}streamChanged(g){this.handlerMap.forEach((f=>f.updateAndNotifyClient(g)))}createIRawStreamClient(g,f){const S=new Qr(g,this.logger);super.handlerAdded(S);const v=S.client();return this.logger.info(`[${f}] - clientId:${v.clientId}, client created`),v}updateHandlers(g){g.forEach(((g,f)=>{this.handlerMap.has(f)||this.handlerMap.set(f,g)}))}},ts=class extends Zr{constructor(g){super(g)}createIRawStreamClient(g,f,S){const v=new Xr(g,f,this.logger);super.handlerAdded(v);const C=v.client();return this.logger.info(`[${S}] - clientId:${C.clientId}, client created`),C}},is=M,ns=class extends jr{constructor(g,f,S,v){super(g,S,v),this.rendererStats=f,this.rawIncomingVideoStreamManager=new ts(this.logger.createChild(`rawVideoStream, [sourceId:${this.id}]`)),this.type=0}get mediaSourceId(){return this.id}getDiagnosticData(){return JSON.stringify({id:this.id,msi:this.mediaSourceId,rank:this.rank,type:this.type,isAvailable:this.isAvailable,isStreaming:this.isStreaming})}getStats(){const g={isAvailable:this.isAvailable,isStreaming:this.isStreaming};return(0,is.isEqual)(this.lastStreamStats,g)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=g),{id:this.id,type:this.type,timestampUpdated:this.streamStatsUpdatedTimestamp,msi:this.mediaSourceId,rank:this.rank,...this.lastStreamStats}}stop(){return this.mediaSessionInitPromise.reject(new Error("Video stream stopped")),Promise.resolve(void 0)}getRawStream(g=generateCauseId()){return this.logger.info(`[${g}] - getRawStream called for incoming video stream`),this.rawIncomingVideoStreamManager.createIRawStreamClient(this,this.mediaSession.getSubscriptionManager(),g)}start(g,f){return this.logger.info(`video start: target=${g}, options=${JSON.stringify(f)}`),this.mediaSessionInitPromise.promise.then((()=>new Jr(this.logger.createChild("RemoteVideoRenderer"),g,this.mediaSession,this.rendererStats,this.mediaSession?.getSessionConfig()))).then((g=>(f&&g.setScalingMode(f.scalingMode),this.logger.info(`subscribeVideoAsync: videoRenderer=${g}, id=${this.id}`),g.subscribeVideoAsync(this).catch((f=>{throw g.dispose(),f})).then((()=>(this.isStreaming=!0,g))))))}update(g,f,S){this.logger.info(`[${f}][update] stream=${JSON.stringify(g)}`);const v=this.isAvailable;super.update(g,f,S),this.isAvailable&&this.isAvailable!==v&&this.rendererStats.event(0)}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().video}},rs=class extends ns{constructor(g,f,S,v){super(g,f,S,v),this.type=1}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().sharing}},ss=1,as=2,os=3,ls=class _PluginlessCallStreamManager extends Ke{constructor(g,f,S,v){super(),this.participantId=g,this.mediaSession=f,this.localStats=S,this.audioSourceIds=[],this.streams={},this.lastUmsStreamId=1;const C=S.receive(1,g),_=S.receive(2,g);this.audio=new Gr(f,v,ss);const T=new ns(f,C,v,as),I=new rs(f,_,v,os),b=this.mediaSession?.getSessionConfig()?.config.participantStreamInitialSubscriptions;b&&(T.changed((()=>this.event("streamChanged").raise())),I.changed((()=>this.event("streamChanged").raise()))),this.streams[0]=[T],this.streams[1]=[I],this.streams[2]=[],this.logger=v.createChild("PluginlessCallStreamManager")}setMediaSession(g,f){this.logger.info(`[${f}][setMediaSession]`),this.mediaSession=g,[[this.audio],this.streams[0],this.streams[1]].forEach((S=>S.forEach((S=>S.setMediaSession(g,f)))))}updateStreams(g,f,S,v){this.logger.info(`[${f}][updateStreams]`);const filterAndSortStreams=f=>g.filter((g=>f.includes(g.type))).sort(_PluginlessCallStreamManager.compareStreams);let C=filterAndSortStreams([$r.audio]);0===C.length&&(C=filterAndSortStreams([$r.audioteleconference])),C.length>0&&(this.audioSourceIds=C.map((g=>g.sourceId)));const _=C[0];_&&this.audio.update(_,f),this.updateMediaStreams(filterAndSortStreams([$r.video]),0,f,S),v?this.updateMediaStreams(filterAndSortStreams([$r.sharing,$r.xsharing]),1,f,S):this.updateMediaStreams(filterAndSortStreams([$r.sharing]),1,f,S)}hasAudioSource(g){return this.audioSourceIds.some((f=>f===g))||this.audio.id===g}useUmsStream(g,f,S,v,C,_){this.logger.info(`[${_}][useUmsStream] Updating ums streams`);const T=this.getUmsInformation(g,v),I=this.streams[2],b=I.filter((g=>!T.some((f=>_PluginlessCallStreamManager.compareUmsStreams(g,f)))));b.forEach((g=>(0,Br.remove)(I,g))),b.length&&this.logger.info(`[${_}][useUmsStream] Removing ${b.length} ums streams`),T.forEach((g=>{let v=I.find((f=>_PluginlessCallStreamManager.compareUmsStreams(f,g)));v||(v=new Wr(this.logger.createChild("UmsStream"),this.lastUmsStreamId++,f,g,C,S),this.logger.info(`[${_}][useUmsStream] Adding ums stream with metadata: ${JSON.stringify(g)}`),I.push(v))}))}getUmsStreamMetadata(g,f){let S=null,v=null;if(S=g.find((function(g){return"MiddleLaneUltraLowLatency"===g.deliveryPipelineType&&f===g.isPrimary})),S){const g=S.urls;if(g&&g.length>0){S.identifier||this.logger.warn(`[getUmsStreamMetadata]: no ums stream identifier found, isPrimary: ${f}`);const C=S.decryptionKey?.id,_=S.decryptionKey?.value;C&&_||this.logger.warn(`[getUmsStreamMetadata]: no valid ums stream decryption key found, isPrimary: ${f}`);const T=S.deliveryPipelineType||void 0;v={url:g[0],streamDeliveryPipeline:T,decryptionKey:C&&_?{id:C,value:_}:null}}else this.logger.info(`[getUmsStreamMetadata]: no ums URLs found, isPrimary: ${f}`)}else this.logger.info(`[getUmsStreamMetadata]: no ums stream information found, isPrimary: ${f}`);return v}getUmsInformation(g,f){const S=[];let v=null,C=null;for(const f in g){const S=g[f].streams;if(S){if(v)this.logger.info(`[getUmsInformation]: primary ums stream already found, skipping finding primary stream for participant: ${f}`);else{const g=this.getUmsStreamMetadata(S,!0);g?v=g:this.logger.info(`[getUmsInformation]: no primary ums stream found for participant: ${f}`)}if(C)this.logger.info(`[getUmsInformation]: alternate ums stream already found, skipping finding alternate stream for participant: ${f}`);else{const g=this.getUmsStreamMetadata(S,!1);g?C=g:this.logger.info(`[getUmsInformation]: no alternate ums stream found for participant: ${f}`)}}else this.logger.warn(`[getUmsInformation]: no stream information found for participant: ${f}`)}return(v||C)&&S.push({stream:v,altStream:C,threadId:f}),S}static compareStreams(g,f){const S="sendonly"===g.direction||"sendrecv"===g.direction,v="sendonly"===f.direction||"sendrecv"===f.direction;return S&&!v?-1:v&&!S?1:f.sourceId-g.sourceId}static compareUmsStreams(g,f){const S=g.getStreamOptions();return _PluginlessCallStreamManager.compareUmsStreamMetadata(S.stream,f.stream)&&_PluginlessCallStreamManager.compareUmsStreamMetadata(S.altStream,f.altStream)}static compareUmsStreamMetadata(g,f){return!g&&!f||!(!g&&f||g&&!f)&&g.decryptionKey.id===f.decryptionKey.id&&g.decryptionKey.value===f.decryptionKey.value&&g.url===f.url}updateMediaStreams(g,f,S,v){const C=this.streams[f],_=C.filter((f=>!g.some((g=>g.sourceId===f.id))));_.forEach((g=>(0,Br.remove)(C,g))),_.length&&this.logger.info(`[${S}][updateMediaStreams] Removing ${_.length} streams of type ${f}`),g.forEach(((_,T)=>{let I=C.find((g=>g.id===_.sourceId));I||(0===f?I=new ns(this.mediaSession,this.localStats.receive(1,this.participantId),this.logger,_.sourceId):1===f&&(I=new rs(this.mediaSession,this.localStats.receive(2,this.participantId),this.logger,_.sourceId)),this.logger.info(`[${S}][updateMediaStreams] Adding stream ${_.sourceId} of type ${f}`),C.push(I),I.changed((()=>this.event("streamChanged").raise()))),I.update(_,S,v),I.rank=g.length-T}))}},cs={0:[1],1:[2,6,3,4,5,7,8],2:[6,3,4,8],3:[1,4,5,8],7:[3,4,8],4:[],5:[3,4,8],6:[3,4],8:[3,5,4]},ds={0:"Disconnected",1:"Connecting",2:"Ringing",3:"Connected",5:"Connected",4:"Disconnected",7:"Connecting"},hs=class extends Ke{constructor(g,f,S,v,C,_=generateCauseId(),T=[]){super(S),this.mri=g,this.callTelemetry=C,this.cachedMediaStreams=T,this.state=0,this.voiceLevel=0,this.isServerMuted=!1,this.endpointType="default",this.balanceUpdates={},this._raiseChangeDeferRunner=Vr.instance.createDeferRunner("CallParticipant.RaiseChange"),this.filteredParticipantEndpointDetails={},this.recordTelemetryForStateChange=(g,f,S,v)=>{if(v){const v="_SetParticipantStateInvalid",C={state:f,reason:S,endpoints:[]};this.endpoints?.endpointDetails?.length&&(C.endpoints=getEndpointInformationForTelemetry(this.endpoints.endpointDetails)),this.callTelemetry.recordEvent(v,C,g)}},this.checkIfIncomingServerMutedIsUpdated=g=>{g.endpointDetails.forEach((g=>{const f=this.filteredParticipantEndpointDetails[g.participantId];void 0!==f&&handleServerMutedVersion(this.logger,f,g)}))},this.handleServerMutedInfoUpdate=g=>{let f=!1;for(const S of g){const g=this.filteredParticipantEndpointDetails[S.participantId];handleMuteUnmuteParticipantInfo(this.logger,g,S,!0)&&(f=!0)}f&&this.updateIsServerMuted()},this.id=this.mri,this.logger=S.createChild((()=>`ICallParticipant[${scrubMriOrOmit(this.id)}][${this.state}]`)),this.logger.info(`[${_}]created`),this.streamManager=new ls(this.id,f,v,this.logger),this.streamManager.on("streamChanged",(()=>this.raiseChanged()))}get audio(){return this.streamManager.audio}get streams(){return this.streamManager.streams}getDiagnosticData(){return JSON.stringify({id:scrubMriOrOmit(this.id),state:this.state,isServerMuted:this.isServerMuted})}async getDiagnosticDataAsync(){return this.getDiagnosticData()}isSameParticipantsMri(g){return this.id===g}setMediaSession(g,f=generateCauseId()){this.streamManager.setMediaSession(g,f)}applyCachedMediaStreams(g=generateCauseId()){const f=this.logger.createFnLogger("applyCachedMediaStreams",g);this.cachedMediaStreams?.length?(f.info("applying cachedMediaStreams"),this.updateStreams(this.cachedMediaStreams,g,!1)):f.info("cachedMediaStreams is empty")}updateStreams(g,f=generateCauseId(),S=!1,v,C=!1){this.logger.createFnLogger("updateStreams",f).info(`isStreamingMode=${S} mediaStreams=${safeJsonStringify(g)}`),g?.length&&(this.cachedMediaStreams=g),S||(this.streamManager.updateStreams(g,f,v,C),this.raiseChangedDeferred())}hasAudioSource(g){return this.streamManager.hasAudioSource(g)}raiseChangedDeferred(){this._raiseChangeDeferRunner((()=>this.raiseChanged()))}updateIsServerMuted(){if(!Object.values(this.filteredParticipantEndpointDetails).length)return void this._updateIsServerMuted(!1);let g=!1;Object.values(this.filteredParticipantEndpointDetails).forEach((f=>{const filterAndSortStreams=g=>f.mediaStreams?.filter((f=>f.type===g)).sort(ls.compareStreams);let S=filterAndSortStreams($r.audio)?.[0];S||(S=filterAndSortStreams($r.audioteleconference)?.[0]);const v=!!S?.serverMuted,C=f.endpointState?.state;!1!==v||!1!=!!C?.isMuted||(g=!0)}));const f=!g;this._updateIsServerMuted(f)}_updateIsServerMuted(g){g!==this.isServerMuted&&(this.isServerMuted=g,this.logger.info(`_updateIsServerMuted updating to: ${this.isServerMuted}`),this.raiseChanged())}updateVoiceLevel(g){this.voiceLevel!==g&&(this.voiceLevel=g,this.raiseChanged())}setState(g,f,S){if(this.state===g)return;const v=this.logger.createFnLogger("setState",S);if(3===this.state&&6===g)return void v.info("Ignore Connected->EarlyMedia transition, it is a race between media and signaling");const C=cs[this.state].indexOf(g)>=0;this.recordTelemetryForStateChange(S,g,f,!C),C?(v.info(`state=${this.state}->${g} reason=${this.stateReason}->${f}`),this.state=g,this.stateReason=f,this.raiseChangedDeferred()):v.logFailure(`Invalid state transition ${this.state}->${g} attempted`)}processParticipantDetails(g,f,S){const v=this.logger.createFnLogger("processParticipantDetails","");this.role=g.role,this.meetingRole=g.meetingRole,this.advancedMeetingRole=g.advancedMeetingRole,this.meetingRoles=g.meetingRoles,this.participantType=g.participantType,this.displayName=g.displayName,this.tenantId=g.tenantId,this.propertyBag=g.propertyBag,this.version=g.version,this.otpIdentity=g.otpIdentity,this.isIdentityMasked=!!g.isIdentityMasked,this.nonMaskedId=g.nonMaskedId,this.nonMaskedDisplayName=g.nonMaskedDisplayName,this.nonMaskedObjectId=g.nonMaskedObjectId,this.maskedIdSeqNumber=g.maskedIdSeqNumber,this.maskedId=g.maskedId,this.joinAsStreamingUser=g.joinAsStreamingUser,g.endpointDetails?.length&&(this.endpoints={endpointDetails:[]},this.participantCapabilities={canConference:!1,canShareScreen:!1,canMerge:!0},this.checkIfIncomingServerMutedIsUpdated(g),this.filteredParticipantEndpointDetails={},g.endpointDetails.forEach((g=>{const v=convertSignalingEndpointDetails(g,f);if(this.endpoints.endpointDetails.push(v),!v.mappedTo){if(this.filteredParticipantEndpointDetails[g.participantId]={endpointId:g.endpointId,serverMuteVersion:g.serverMuteVersion,endpointState:g.endpointState,mediaStreams:g.mediaStreams},g.capabilities&&(this.participantCapabilities.canConference||"enabled"!==g.capabilities.cloudAudioVideoConference||(this.participantCapabilities.canConference=!0),this.participantCapabilities.canShareScreen||"enabled"!==g.capabilities.cloudScreenSharing||(this.participantCapabilities.canShareScreen=!0),this.participantCapabilities.canMerge||"enabled"!==g.capabilities.cloudMerge||(this.participantCapabilities.canMerge=!0)),this.contentSharingRole=0,g.contentSharing&&g.contentSharing.sessionInformation){const f=g.contentSharing.sessionInformation;"attendee"===f.role?this.contentSharingRole=1:"presenter"===f.role&&(this.contentSharingRole=2)}v.streamInformation&&S&&S()}})),this.updateIsServerMuted(),v.info(`endpointDetails=${getPIISafeEndpointDetails(this.endpoints)}`),this.raiseChangedDeferred())}toCafeParticipant(){return{audioState:ds[this.state],mri:this.mri}}getSourceIdForMediaType(g){const f=getSourceIdForMediaType(this,g);return-1===f&&this.logger.warn("getSourceIdForMediaType failed"),f}useUmsStream(g,f,S,v,C,_){this.streamManager.useUmsStream(g,f,S,v,C,_),this.raiseChangedDeferred()}hasSourceId(g,f){return void 0!==getParticipantIdForSourceId(this,g,f)}},us=class extends Ke{constructor(g,f,S,v,C,_="",T,I){super(),this.callTelemetry=g,this.signalingSession=S,this.contentSharingGuid=v,this.contentSharingIdentity=C,this.state=_,this.subject=T,this.handleOperationFailure=(g,f,S)=>{S.logFailure(g);const v=this.getTerminatedReasonFromError(g);return f.updateStatusTo&&(this.contentSharingStatus=f.updateStatusTo,this.rejectContentSharing(v)),Promise.reject(v)},this._logger=f.createChild((()=>`[ContentSharingSession][${this.contentSharingGuid}]`)),this.contentSharingStatus=0,this.contentSharingTerminationReason=null,this.contentSharingState=_,this._callOperationHandler=new Li(this._logger,this.callTelemetry),I&&(this.sessionId=I)}get contentSharingStatus(){return this.status}set contentSharingStatus(g){if(this._logger.info(`[set contentSharingStatus][currentStatus=${this.status}][newStatus=${g}]`),this.callTelemetry.recordEvent("_SetContentSharingStatus",{newStatus:g,oldStatus:this.status}),this.status!==g&&7!==this.status&&8!==this.status){if(this._logger.info(`[set contentSharingStatus] Changing content sharing status to: ${g}`),this.status=g,7===this.status){const g={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"[set contentSharingStatus] Content sharing is disconnected"};this._callOperationHandler.maybeResolveOperation("StopContentSharing"),this._callOperationHandler.rejectPendingOperations(g)}if(2===this.status||5===this.status){const g={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Content sharing cannot be ended when not presenting"};this._callOperationHandler.maybeRejectOperation("StopContentSharing",g)}3===this.status&&(this._callOperationHandler.maybeResolveOperation("StartContentSharing"),this._callOperationHandler.maybeResolveOperation("TakeContentSharingControl")),this.raiseChanged()}}get contentSharingState(){return this.state}set contentSharingState(g){this.state!==g&&(this.state=g,this.raiseChanged())}startContentSharing(g=generateCauseId()){const f=this._logger.createFnLogger("StartContentSharing",g);if(0!==this.contentSharingStatus){const S=`[${g}][startContentSharing][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.startContentSharingAsync(this.contentSharingIdentity,this.contentSharingState,this.subject,this.contentSharingGuid,g).then((g=>{this.sessionId=g.sessionId,this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"StartContentSharing",updateStatusTo:8},f))),this._callOperationHandler.waitForOperation("StartContentSharing")}joinContentSharing(g=generateCauseId()){const f=this._logger.createFnLogger("JoinContentSharing",g);if(2!==this.contentSharingStatus){const S=`[${g}][joinContentSharing][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.joinContentSharingAsync(this.contentSharingGuid,g).then((g=>(this.contentSharingStatus=4,this.contentSharingState=g.sessionState,this.presenterId=g.presenter,Promise.resolve()))).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"JoinContentSharing",updateStatusTo:8},f)))}updateContentSharingSessionState(g,f,S=generateCauseId()){const v=this._logger.createFnLogger("UpdateContentSharingSessionState",S);if(3!==this.contentSharingStatus){const g=`[${S}][updateContentSharingSessionState][failed][reason=InvalidState]`,f={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:g};return v.logFailure(`state=${this.contentSharingStatus}, reason=${g}`),Promise.reject(f)}return this.signalingSession.updateContentSharingSessionStateAsync(this.contentSharingGuid,f,S).then((()=>Promise.resolve())).catch((f=>this.handleOperationFailure(f,{causeId:S,operation:"UpdateContentSharingSessionState",operationId:g},v)))}takeContentSharingControl(g=generateCauseId()){const f=this._logger.createFnLogger("TakeContentSharingControl",g);if(5!==this.contentSharingStatus){const S=`[${g}][updateContentSharingSessionState][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.takeContentSharingControlAsync(this.contentSharingGuid,g).then((()=>{this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"TakeContentSharingControl"},f))),this._callOperationHandler.waitForOperation("TakeContentSharingControl")}updateContentSharingParticipantStateToViewer(g=generateCauseId()){const f=this._logger.createFnLogger("UpdateParticipantState",g);if(4!==this.contentSharingStatus){const S=`[${g}][updateContentSharingSessionState][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.updateContentSharingParticipantStateAsync(this.contentSharingGuid,g).then((()=>(this.contentSharingStatus=this.presenterId===this.signalingSession.participantManager.localParticipant.id?3:5,Promise.resolve()))).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"UpdateParticipantState"},f)))}stopContentSharing(g=generateCauseId()){const f=this._logger.createFnLogger("StopContentSharing",g);if(2===this.contentSharingStatus||4===this.contentSharingStatus||5===this.contentSharingStatus){const S=`[${g}][stopContentSharing][failed][reason=InvalidState]`,v={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:S};return f.logFailure(`state=${this.contentSharingStatus}, reason=${S}`),Promise.reject(v)}return this.signalingSession.deleteContentSharingAsync(this.contentSharingGuid,g).then((()=>(this.contentSharingStatus=7,this._callOperationHandler.waitForOperation("StopContentSharing")))).catch((S=>this.handleOperationFailure(S,{causeId:g,operation:"StopContentSharing"},f)))}dispose(g=generateCauseId()){const f={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Call ended"};this._callOperationHandler.rejectPendingOperations(f,g),this.contentSharingStatus=7,this.contentSharingState="",super.dispose()}rejectContentSharing(g={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"[rejectContentSharing] Content sharing is disconnected"}){if(7!==this.status&&8!==this.status)throw new Error(`Tried to reject content sharing with status=${this.status}`);this._callOperationHandler.maybeResolveOperation("StopContentSharing"),this._callOperationHandler.rejectPendingOperations(g)}getTerminatedReasonFromError(g){const f=g?.endCode?.code||0,S={terminatedReason:32,terminatedReasonCode:f,terminatedReasonSubCode:g?.endCode?.subCode||0,errorMessage:g};switch(f){case Fi.NotFound:S.terminatedReason=34,S.errorMessage="Active session not found on server";break;case Fi.Forbidden:S.terminatedReason=8,S.errorMessage="Failed due to insufficient permissions"}return S}};__decorateClass([callOperation("StartContentSharing"),__decorateParam(0,causeId)],us.prototype,"startContentSharing",1),__decorateClass([callOperation("JoinContentSharing"),__decorateParam(0,causeId)],us.prototype,"joinContentSharing",1),__decorateClass([callOperation("UpdateContentSharingSessionState"),__decorateParam(0,operationId),__decorateParam(2,causeId)],us.prototype,"updateContentSharingSessionState",1),__decorateClass([callOperation("TakeContentSharingControl"),__decorateParam(0,causeId)],us.prototype,"takeContentSharingControl",1),__decorateClass([callOperation("UpdateParticipantState"),__decorateParam(0,causeId)],us.prototype,"updateContentSharingParticipantStateToViewer",1),__decorateClass([callOperation("StopContentSharing",{waitFor:"StartContentSharing"}),__decorateParam(0,causeId)],us.prototype,"stopContentSharing",1);var gs,ps=class{constructor(g){this.value=g,this.next=void 0}},ms=class{constructor(){this.length=0}enqueue(g){const f=new ps(g);this.front?(this.rear.next=f,this.rear=f):(this.front=f,this.rear=f),this.length++}dequeue(){if(!this.front)return;const g=this.front;return this.front===this.rear?(this.front=void 0,this.rear=void 0):this.front=this.front.next,this.length--,g.value}peek(){return this.front?.value}size(){return this.length}back(){return this.rear?.value}},fs=M,Ss=class{constructor(g){this.comparator=g,this.heap=[]}enqueue(g){this.heap.push(g),this.bubbleUp()}dequeue(){const g=this.peek();if(void 0!==g){const g=this.heap.pop();this.size()>0&&(this.heap[0]=g,this.bubbleDown())}return g}peek(){return this.heap[0]}size(){return this.heap.length}bubbleUp(){let g=this.size()-1,f=this.getParentIndex(g);for(;!this.isRoot(g)&&this.comparator(this.heap[g],this.heap[f]);)[this.heap[f],this.heap[g]]=[this.heap[g],this.heap[f]],g=f,f=this.getParentIndex(g)}bubbleDown(){if(this.size()<=1)return;let g=this.getRootIndex(),f=this.getLeftIndex(g),S=this.getRightIndex(g);for(;this.heap[f]&&this.comparator(this.heap[f],this.heap[g])||this.heap[S]&&this.comparator(this.heap[S],this.heap[g]);)!this.heap[S]||this.comparator(this.heap[f],this.heap[S])?([this.heap[g],this.heap[f]]=[this.heap[f],this.heap[g]],g=f):([this.heap[g],this.heap[S]]=[this.heap[S],this.heap[g]],g=S),f=this.getLeftIndex(g),S=this.getRightIndex(g)}getRootIndex(){return 0}isRoot(g){return 0===g}getLeftIndex(g){return 2*g+1}getRightIndex(g){return 2*g+2}getParentIndex(g){return Math.floor((g-1)/2)}},vs=class{constructor(g,f,S){this.maxPacketRate=f,this.rateLimiterCheckInterval=S,this.maxDataRate=0,this.packetsEndTimeForPacketRate=0,this.packetsEndTimeForBitrate=0,this.maxDataRate=g/8}canSend(g){if(0===this.maxDataRate&&0===this.maxPacketRate)return!0;const f=Jt();if(this.maxPacketRate&&this.packetsEndTimeForPacketRate>f+this.rateLimiterCheckInterval)return!1;if(this.maxDataRate&&this.packetsEndTimeForBitrate>f+this.rateLimiterCheckInterval)return!1;const S=this.maxPacketRate?1e3/this.maxPacketRate:0,v=this.maxDataRate?g.length/this.maxDataRate*1e3:0;return this.packetsEndTimeForPacketRate=Math.max(this.packetsEndTimeForPacketRate,f)+S,this.packetsEndTimeForBitrate=Math.max(this.packetsEndTimeForBitrate,f)+v,!0}},Cs=class{constructor(g){this.dataIds=new Map,this.maxBitrate=g.config.webrtcDataChannel.maxBitrate,this.maxPacketRate=g.config.webrtcDataChannel.maxPacketRate,this.maxQueueSize=g.config.webrtcDataChannel.maxQueueSize,g.config.webrtcDataChannel.dataIds.forEach((g=>{this.dataIds.set(g.dataId,g)}))}getMaxBitrate(g){return this.dataIds.get(g)?.maxBitrate??this.maxBitrate}getMaxPacketRate(g){return this.dataIds.get(g)?.maxPacketRate??this.maxPacketRate}getMaxQueueSize(g){return this.dataIds.get(g)?.maxQueueSize??this.maxQueueSize}getConfig(g){const f=this.dataIds.get(g)||{dataId:g};return f.maxBitrate=f.maxBitrate??this.maxBitrate,f.maxPacketRate=f.maxPacketRate??this.maxPacketRate,f.maxQueueSize=f.maxQueueSize??this.maxQueueSize,f.priorityWeight=f.priorityWeight??1,f}},ys=class{constructor(g,f,S){this.dataIdConfig=f,this.rateLimiterCheckInterval=S,this.timeOffset=0,this.packets=new ms,this.startTime=g(),this.finishTime=this.startTime,this.rateLimiter=new vs(f.maxBitrate,f.maxPacketRate,this.rateLimiterCheckInterval),this.getCurrentTime=g,this.stats={bufferSize:f.maxQueueSize,remainingBytes:0,remainingPackets:0}}enqueue(g){if(0===g.length)return 0;const f=(0,fs.sumBy)(g,(g=>g.length)),S=this.dataIdConfig.maxQueueSize;if(S&&this.stats.remainingBytes+f>S)throw new Error(`dataId ${this.dataIdConfig.dataId} send queue is full`);const v=this.getCurrentTime();let C=0;return 0===this.packets.size()?(this.startTime=v,this.finishTime=v,this.timeOffset=0,C=v):C=this.finishTime,g.forEach((g=>{C+=g.length*this.dataIdConfig.priorityWeight,this.packets.enqueue({finishTime:C,packet:g}),this.stats.remainingBytes+=g.length,this.stats.remainingPackets++})),this.finishTime=C,f}dequeue(){const g=this.peek();if(void 0!==g){if(!this.rateLimiter.canSend(g.packet))return;this.packets.dequeue(),this.stats.remainingBytes-=g.packet.length,this.stats.remainingPackets--}return g}updateTimeOffset(){this.packets.size()?this.timeOffset=this.getCurrentTime()-this.startTime:(this.startTime=this.getCurrentTime(),this.finishTime=this.startTime,this.timeOffset=0)}peek(){if(0===this.packets.size())return;const g=this.packets.peek();return{finishTime:g.finishTime+this.timeOffset,packet:g.packet}}getConfig(){return this.dataIdConfig}getStats(){return(0,fs.clone)(this.stats)}},Es=class{constructor(g){this.senders=new Map,this.currentVirtualClock=0,this.dataIdConfigManager=new Cs(g),this.virtualTimeQueue=new Ss(((g,f)=>g.minTime<f.minTime)),this.sendStats={bufferSize:0,remainingBytes:0,remainingPackets:0},this.rateLimiterCheckInterval=g.config.webrtcDataChannel.rateLimiterCheckInterval}getPacketsToSend(g){if(0===this.virtualTimeQueue.size())return[];const f=[],S=[];for(;g>=0&&this.virtualTimeQueue.size();){const v=this.virtualTimeQueue.peek();if(v.size>g)break;this.virtualTimeQueue.dequeue();const C=v.dataId,_=this.senders.get(C);if(void 0!==_.peek()){const v=_.dequeue();if(void 0!==v){f.push(v.packet),this.sendStats.remainingBytes-=v.packet.length,g-=v.packet.length,this.sendStats.remainingPackets--,this.currentVirtualClock=Math.max(this.currentVirtualClock,v.finishTime);const S=_.peek();S&&this.virtualTimeQueue.enqueue({dataId:C,minTime:S.finishTime,size:S.packet.length})}else S.push(C)}}return S.forEach((g=>{const f=this.senders.get(g);f.updateTimeOffset();const S=f.peek();S&&this.virtualTimeQueue.enqueue({dataId:g,minTime:S.finishTime,size:S.packet.length})})),f}appendPackets(g,f){let S=this.senders.get(g);void 0===S&&(S=new ys((()=>this.currentVirtualClock),this.dataIdConfigManager.getConfig(g),this.rateLimiterCheckInterval),this.senders.set(g,S));const v=S.getStats(),C=S.enqueue(f);if(this.sendStats.remainingBytes+=C,this.sendStats.remainingPackets+=f.length,0===v.remainingPackets){const f=S.peek();void 0!==f&&this.virtualTimeQueue.enqueue({dataId:g,minTime:f.finishTime,size:f.packet.length})}}getStats(g){if(void 0===g)return(0,fs.clone)(this.sendStats);const f=this.senders.get(g);return void 0===f?{bufferSize:this.dataIdConfigManager.getMaxQueueSize(g),remainingBytes:0,remainingPackets:0}:f.getStats()}},_s=class{constructor(g){this.data={protocolCounters:{},id:void 0,label:void 0,ordered:void 0,negotiated:void 0},this.data.id=g.id,this.data.label=g.label,this.data.ordered=g.ordered,this.data.negotiated=g.negotiated,this.data.protocol=g.protocol||void 0,this.data.maxPacketLifeTime=g.maxPacketLifeTime??void 0,this.data.maxRetransmits=g.maxRetransmits??void 0}recordProtocolEvent(g,f,S){this.data.protocolCounters[S]||(this.data.protocolCounters[S]={});const v=this.data.protocolCounters[S];switch(v[g]||(v[g]={successful:0,failed:0,fragmented:0,dismissed:0}),f){case 0:v[g].successful++;break;case 1:v[g].failed++;break;case 2:v[g].fragmented++;break;case 3:v[g].dismissed++}}recordError(g){this.data.error=g}getObjectRef(){return this.data}},Ts=class{constructor(g,f,S){this.dataId=g,this.diagnostics=f,this.logger=S,this.pendingFragments=[]}depacketize(g){const f=new DataView(g.buffer),S=63&f.getUint8(2);if(S!==this.dataId)throw new Error(`Invalid packet dataId: ${this.dataId} !== ${S}`);const v=11,C=((15&f.getUint8(0))<<8)+f.getUint8(1),_=128&f.getUint8(2),T=f.getUint16(3),I=f.getUint8(5),b=f.getUint32(6),A=f.getUint8(10);if(_){this.pendingFragments.length&&this.logger.warn(`Unfinished message: dataId: ${this.dataId} seqNum: ${T}`),this.remainingPackets=I,0!==I&&this.diagnostics.recordProtocolEvent("recv",2,S),this.pendingFragments=[],this.sourceId=b,this.recipients=[];for(let g=0;g<A;g++){const S=f.getUint32(v+4*g);this.recipients.push(S)}}else{if(0===this.pendingFragments.length)return this.logger.safe.error(`No start flag dataId: ${this.dataId} seqNum: ${T}`),this.diagnostics.recordProtocolEvent("recv",3,S),null;if(this.nextSeqNum!==T)return this.logger.safe.error(`Invalid sequence number: dataId: ${this.dataId} seqNum: ${T}`),this.diagnostics.recordProtocolEvent("recv",3,S),null;this.remainingPackets-=1}if(this.nextSeqNum=T+1&65535,this.pendingFragments.push(g.slice(C)),0===this.remainingPackets){const g=this.pendingFragments.reduce(((g,f)=>g+f.length),0),f=new Uint8Array(g);let S=0;for(const g of this.pendingFragments)f.set(g,S),S+=g.length;return this.pendingFragments=[],{dataId:this.dataId,sourceId:this.sourceId,data:f,recipients:this.recipients}}return null}},Is=class{constructor(g){this.dataId=g,this.seqNum=0}packetize(g){if(g.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${g.dataId}`);const f=11,S=f+4*g.recipients.length,v=new Uint8Array(g.data.length+S),C=new DataView(v.buffer);C.setUint8(0,16+(S>>8)),C.setUint8(1,255&S),C.setUint8(2,128|63&g.dataId),C.setUint16(3,this.seqNum),C.setUint8(5,0),C.setUint32(6,g.sourceId),C.setUint8(10,g.recipients.length);for(let S=0;S<g.recipients.length;S++)C.setUint32(f+4*S,g.recipients[S]);return v.set(g.data,S),this.seqNum+=1,[v]}},bs=class{constructor(g,f,S){this.dataId=g,this.fragmentationSize=f,this.diagnostics=S,this.seqNum=0}packetize(g){if(g.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${g.dataId}`);const f=11,S=f+4*g.recipients.length,v=[],C=this.fragmentationSize-S;if(C<0)throw new Error(`message dataId: ${this.dataId} payload size: ${S} exceeds limit`);let _=g.data.length?Math.ceil(g.data.length/C):1;const T=_-1;T>0&&this.diagnostics.recordProtocolEvent("send",2,this.dataId);let I=g.data.length,b=!0,A=0;for(;_>0;){const P=Math.min(I,C),R=new Uint8Array(P+S),M=new DataView(R.buffer);M.setUint8(0,16+(S>>8)),M.setUint8(1,255&S),b?(b=!1,M.setUint8(2,128|63&g.dataId)):M.setUint8(2,63&g.dataId),M.setUint16(3,this.seqNum),M.setUint8(5,T),M.setUint32(6,g.sourceId),M.setUint8(10,g.recipients.length);for(let S=0;S<g.recipients.length;S++)M.setUint32(f+4*S,g.recipients[S]);R.set(g.data.slice(A,A+P),S),A+=P,v.push(R),this.seqNum+=1,_-=1,I-=P}return v}},As=class extends Ht{constructor(g,f,S,v){super(),this.dataChannel=g,this.sessionDiagnostics=f,this.stateInternal="Created",this.packetizers=new Map,this.depacketizers=new Map,this.sendScheduleTimer=0,this.pendingPackets=new ms,this.sourceIdInternal=Ai,this.label=g.label,this.diagnostics=this.sessionDiagnostics.newDataChannelDiagnostics(g),this.logger=S.createChild(`[WebRtcDataChannel ${this.label}]`),this.logger.safe.info(`Created with settings ${stringifyObject2(this.getDataChannelSettings(g))}`),this.bufferedAmountLowThreshold=v.config.webrtcDataChannel.bufferedAmountLowThreshold,this.bufferedAmountHighThreshold=v.config.webrtcDataChannel.bufferedAmountHighThreshold,this.fragmentationSize=v.config.webrtcDataChannel.enableFragmentation?v.config.webrtcDataChannel.fragmentationSize:0,v.config.webrtcDataChannel.enableSendScheduler&&(this.sendScheduler=new Es(v)),this.rateLimiterCheckInterval=v.config.webrtcDataChannel.rateLimiterCheckInterval,this.discardOnSendFailure=v.config.webrtcDataChannel.discardOnSendFailure,this.subscribeOnDataChannelEvents()}getDataIdStats(g){return this.sendScheduler?.getStats(g)}get state(){return this.stateInternal}set sourceId(g){this.sourceIdInternal=g}setDataChannel(g){this.dataChannel&&(this.logger.info(`Replacing internal data channel ${this.label}:${this.dataChannel.id} with ${g.label}:${g.id} with settings ${stringifyObject2(this.getDataChannelSettings(g))}`),this.unsubscribeOnDataChannelEvents(),this.dataChannel.close()),this.dataChannel=g,this.diagnostics=this.sessionDiagnostics.newDataChannelDiagnostics(g),this.subscribeOnDataChannelEvents()}dispose(){this.logger.info("dispose"),this.dataChannel&&(this.logger.info(`dataChannel.close ${this.dataChannel.id}`),this.unsubscribeOnDataChannelEvents(),this.dataChannel.close(),this.dataChannel=null,this.setState("Destroyed"),super.dispose())}sendMessage(g,f=this.sourceIdInternal,S,v=[]){try{this.packetizers.has(g)||(this.fragmentationSize?this.packetizers.set(g,new bs(g,this.fragmentationSize,this.diagnostics)):this.packetizers.set(g,new Is(g)));const C=this.packetizers.get(g).packetize({dataId:g,sourceId:f,data:S,recipients:v});void 0!==this.sendScheduler?(this.sendScheduler.appendPackets(g,C),this.scheduleSend()):C.forEach((g=>{this.dataChannel.send(g)})),this.diagnostics.recordProtocolEvent("send",0,g)}catch(f){throw this.logger.unsafe.warn(`Failed to construct protocol message: ${stringifyObject2(f)}`),this.diagnostics.recordProtocolEvent("send",1,g),f}}scheduleSend(){if("Connected"!==this.state)return;const sendPacket=g=>{try{this.dataChannel.send(g)}catch(g){return this.logger.unsafe.warn(`Failed to send message: ${stringifyObject2(g)}`),!1}return!0};if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){const g=Date.now();let f=this.bufferedAmountHighThreshold-this.dataChannel.bufferedAmount;for(;this.pendingPackets.size();){const g=this.pendingPackets.peek();if(g.length>f)break;if(!sendPacket(g))break;this.pendingPackets.dequeue(),f-=g.length}if(0===this.pendingPackets.size()&&f>0){const g=this.sendScheduler.getPacketsToSend(f);for(const f of g)if(!1===sendPacket(f)&&!1===this.discardOnSendFailure){this.pendingPackets.enqueue(f);break}}if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){if(this.sendScheduleTimer)return;if(this.sendScheduler.getStats().remainingPackets>0){const f=Math.max(g+this.rateLimiterCheckInterval-Date.now(),20);this.sendScheduleTimer=window.setTimeout((()=>{this.sendScheduleTimer=0,this.scheduleSend()}),f)}}}}subscribeOnDataChannelEvents(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onmessage=g=>{const f=new Uint8Array(g.data),S=63&f[2];try{this.depacketizers.has(S)||this.depacketizers.set(S,new Ts(S,this.diagnostics,this.logger));const g=this.depacketizers.get(S).depacketize(f);g&&(this.diagnostics.recordProtocolEvent("recv",0,S),this.event("onmessage").raise(S,g.sourceId,g.data))}catch(g){this.logger.unsafe.warn(`Failed to parse incoming message: ${stringifyObject2(g)}`),this.diagnostics.recordProtocolEvent("recv",1,S)}},this.dataChannel.onerror=g=>{const f=g?.target,S=stringifyObject2(g?.error??g);this.logger.safe.warn(`onerror: label:${f.label} id:${f.id} ${S} `),this.diagnostics.recordError(S)},"open"===this.dataChannel.readyState&&this.dataChannel.id%2==0&&(this.logger.safe.info(`readyState is already 'open' label:${this.dataChannel.label} id:${this.dataChannel.id}`),this.setState("Connected")),this.dataChannel.onopen=g=>{const f=g.target;this.logger.safe.info(`onopen label:${f.label} id:${f.id}`),f.id%2==0&&this.setState("Connected")},this.dataChannel.onclose=g=>{const f=g.target;this.logger.safe.info(`onclose label:${f.label} id:${f.id}`),this.setState("Closed")},this.dataChannel.onclosing=g=>{const f=g.target;this.logger.safe.debug(`onclosing label:${f.label} id:${f.id}`),this.setState("Closed")},void 0!==this.sendScheduler&&(this.dataChannel.bufferedAmountLowThreshold=this.bufferedAmountLowThreshold,this.dataChannel.onbufferedamountlow=()=>{this.scheduleSend()})}unsubscribeOnDataChannelEvents(){this.dataChannel.onmessage=null,this.dataChannel.onerror=null,this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onclosing=null,this.dataChannel.onbufferedamountlow=null}setState(g){this.stateInternal=g,this.event("onStateChanged").raise(),"Connected"===g&&void 0!==this.sendScheduler&&this.scheduleSend()}getDataChannelSettings(g){return{ordered:g.ordered,maxRetransmits:g.maxRetransmits,maxPacketLifeTime:g.maxPacketLifeTime}}},Ps="main-channel",Rs=class extends Ht{constructor(g,f,S,v){const C=S.createChild("PluginlessDataChannel");super(C),this.pc=g,this.diagnostics=f,this.configProvider=v,this._state="Inactive",this.logger=C,this.subscribeOnDatachannel()}get state(){return this._state}getDataChannel(g){if(!this.dataChannel){this.logger.safe.info(`[${g}] creating new dataChannel`);try{const g=this.configProvider.config.dataChannelDebugInitSettings||{};this.dataChannel=new As(this.pc.createDataChannel(Ps,g),this.diagnostics,this.logger,this.configProvider),this.subscribeForDataChannelEvents()}catch(f){const S=stringifyObject2(f);return this.logger.safe.error(`[${g}] createDataChannel failed: ${S}`),this.diagnostics.createChannelFailReason=S,this.setState("Failed"),null}}return this.dataChannel}updateDataModalityState(g){"Failed"!==this._state&&"Disabled"!==this._state&&(g===qt.MEDIA_STATE.sendReceive?this.setState("Active"):g===qt.MEDIA_STATE.inactive&&this.setState("Inactive"))}disable(){this.setState("Disabled")}dispose(){this.stopDataChannel(),this.pc=null,super.dispose()}subscribeOnDatachannel(){this.pc.ondatachannel=g=>{this.onDataChannel(g.channel)}}onDataChannel(g){this.logger.safe.info(`onDataChannel id=${g.id} label=${g.label}`),g.id%2==0?this.dataChannel?(this.logger.safe.info("Found existing data channel, replacing"),this.dataChannel.setDataChannel(g)):(this.dataChannel=new As(g,this.diagnostics,this.logger,this.configProvider),this.subscribeForDataChannelEvents()):this.logger.safe.info(`onDataChannel ignoring id ${g.id}`)}subscribeForDataChannelEvents(){this.dataChannel.on("onStateChanged",(()=>{"Closed"===this.dataChannel.state&&(this.stopDataChannel(),this.setState("Inactive"))}))}setState(g){if(this._state!==g){this.diagnostics.dataChannelSessionState=g;const f=generateCauseId();this._state=g,this.logger.safe.info(`[${f}] SessionDataChannelState changed, state=${this._state}`),"Inactive"===this._state||"Disabled"===this._state?this.stopDataChannel():"Active"===this._state&&this.getDataChannel(f),this.event("onStateChanged").raise(this._state)}}stopDataChannel(){this.dataChannel&&(this.logger.safe.info("stopDataChannel"),this.dataChannel.dispose(),this.dataChannel=null)}},Ms=class extends Ke{constructor(g){super(),this.mainChannel=null,this.sourceId=Ai,this._state="Inactive",this.dataHandlers=new Map,this.dataHandlerTelemetry=new Map,this.startTime=Date.now(),this.sendMessage=async(g,f,S)=>{if(!this.mainChannel||"Connected"!==this.mainChannel.state||"Active"!==this.state)throw new Error("No active data channel to send data from");this.mainChannel.sendMessage(g,this.sourceId,f,S)},this.logger=g.createChild("PluginlessDataChannel")}get state(){return this._state}registerSessionDataChannel(g,f){this.sessionDataChannel&&this.stop(f),this.sessionDataChannel=g,this.subscribeForSessionDataChannelEvents()}setDataChannelSourceId(g){this.logger.debug(`setDataChannelSourceId ${g}`),this.mainChannel&&(this.mainChannel.sourceId=g),this.sourceId=g}requestDataChannelHandler(g){return this.sessionDataChannel.getDataChannel(g)}async sendUserEvents(g,f){if(!this.mainChannel)throw this.logger.info("sendUserEvents() no data channel available"),new Error("Main DataChannel is not active");{const S=f?f.map((g=>parseInt(g,10))):[];this.mainChannel.sendMessage(0,this.sourceId,(new TextEncoder).encode(g),S)}}async addHandler(g,f){if(this.logger.info(`Adding handler with dataId ${g}`),this.dataHandlers.get(g))throw new Error(`Data Id ${g} is already registered`);const S={isStarted:!1,handler:f};this.dataHandlers.set(g,S),this.recordDataHandlerEvent(g,"added"),"Connected"===this.mainChannel?.state&&this.startHandler(g,S)}async removeHandler(g){if(this.logger.info(`Removing handler with dataId ${g}`),!this.dataHandlers.has(g))throw new Error(`Handler associated with Data Id ${g} is not attached`);const f=this.dataHandlers.get(g);f.isStarted&&this.stopHandler(g,f),this.dataHandlers.delete(g)}async updateNegotiationTag(g){}getTelemetry(){if(!this.dataHandlerTelemetry.size)return"";const g={};for(const[f,S]of this.dataHandlerTelemetry)g[f]=S;return JSON.stringify(g)}start(g){this.mainChannel?this.logger.info(`[${g}] already started`):(this.logger.info(`[${g}] starting`),this.mainChannel=this.sessionDataChannel.getDataChannel(g),this.subscribeForMainDataChannelEvents())}stop(g){this.mainChannel&&(this.logger.info(`[${g}] stopping`),this.mainChannel.dispose(),this.mainChannel=null)}dispose(){this.stop(void 0),this.sessionDataChannel=null,super.dispose()}setConfigProviderView(g){this.configProviderView=g}subscribeForMainDataChannelEvents(){this.mainChannel.on("onmessage",((g,f,S)=>{this.dataHandlers.has(g)&&(this.recordDataHandlerEvent(g,"recvd"),this.dataHandlers.get(g).handler.onDataReceived(g,S,f)),this.event("remoteUserEventsReceived").raise(g.toString(),(new TextDecoder).decode(S))})),this.onMainChannelStateChanged(),this.mainChannel.on("onStateChanged",(()=>this.onMainChannelStateChanged()))}onMainChannelStateChanged(){if(this.mainChannel)switch(this.mainChannel.state){case"Connected":this.startHandlers();break;case"Closed":case"Destroyed":this.stopHandlers()}}startHandlers(){for(const[g,f]of this.dataHandlers.entries())f.isStarted||this.startHandler(g,f)}stopHandlers(){for(const[g,f]of this.dataHandlers.entries())f.isStarted&&this.stopHandler(g,f)}startHandler(g,f){this.logger.info(`Starting dataHandler id: ${g}`),f.handler.onStarted(g,((f,S)=>(this.recordDataHandlerEvent(g,"sent"),this.sendMessage(g,f,S))),(()=>{const f=this.mainChannel?.getDataIdStats(g);if(void 0!==f){const g={bufferSize:f.bufferSize,remainingBytes:f.remainingBytes,remainingPackets:f.remainingPackets};return Promise.resolve(g)}return Promise.reject(new Error(`Stats of dataId ${g} is not available`))})),f.isStarted=!0,this.recordDataHandlerEvent(g,"started")}stopHandler(g,f){this.logger.info(`Stopping dataHandler id: ${g}`),f.handler.onStopped(g),f.isStarted=!1,this.recordDataHandlerEvent(g,"removed")}subscribeForSessionDataChannelEvents(){this.sessionDataChannel.on("onStateChanged",(g=>{const f=generateCauseId();switch(g){case"Active":this.start(f),this.setState("Active");break;case"Inactive":this.stop(f),this.setState("Inactive");break;case"Failed":this.stop(f),this.setState("Failed");break;case"Disabled":this.stop(f),this.setState("Disabled");break;default:this.logger.warn(`[${f}] unhandled SessionDataChannelState ${g}`)}}))}recordDataHandlerEvent(g,f){this.dataHandlerTelemetry.has(g)||this.dataHandlerTelemetry.set(g,[{}]);const S=this.dataHandlerTelemetry.get(g);let v=S[S.length-1];if("added"===f&&void 0!==v.added){v={},S.push(v);const g=this.configProviderView?.config.maxStoredDataChannelValues??15;S.length>g&&S.shift()}switch(f){case"added":case"started":case"removed":v[f]=Date.now()-this.startTime;break;case"recvd":case"sent":v[f]=isNaN(v[f])?1:v[f]+1}}setState(g){this._state!==g&&(this._state=g,this.logger.info(`PluginlessDataChannelState changed, state=${this._state}`),this.event("onDataChannelStateUpdated").raise(this._state))}},ws=__toESM2(be());(g=>{const f=7,S=3;function encodeMouseEvent(g){if(!g)return new Uint8Array(0);g.buttonType||(g.buttonType=0),g.xPos||(g.xPos=0),g.yPos||(g.yPos=0),g.wheelRotation||(g.wheelRotation=0);const S=new ArrayBuffer(f),v=new DataView(S),C=(3&g.type)<<0,_=(7&g.buttonType)<<2,T=(g.buttonDown?1:0)<<5,I=(g.wheelButtonDown?1:0)<<6,b=0;return v.setUint8(0,1),v.setUint8(1,C|_|T|I|b),v.setUint16(2,g.xPos,!0),v.setUint16(4,g.yPos,!0),v.setUint8(6,g.wheelRotation),new Uint8Array(S)}function encodeKeyboardEvent(g){const f=new ArrayBuffer(S),v=new DataView(f),C=(3&g.codeType)<<0,_=0,T=(g.keyUp?1:0)<<4,I=(g.repeat?1:0)<<5,b=0,A=0;return v.setUint8(0,0),v.setUint8(1,C|_|T|I|b|A),v.setUint8(2,g.code),new Uint8Array(f)}function decodeEventType(g){return g[0]}function decodeMouseEvent(g){if(1!==g[0]||g.length!==f)return null;const S=new DataView(g.buffer),v=S.getUint8(1);return{type:3&v,buttonType:v>>2&7,buttonDown:!!(v>>5&1),wheelButtonDown:!!(v>>6&1),xPos:S.getUint16(2,!0),yPos:S.getUint16(4,!0),wheelRotation:S.getUint8(6)}}function decodeKeyboardEvent(g){if(0!==g[0]||g.length!==S)return null;const f=new DataView(g.buffer),v=f.getUint8(1);return{codeType:3&v,code:f.getUint8(2),repeat:!!(v>>5&1),keyUp:!!(v>>4&1)}}g.encodeMouseEvent=encodeMouseEvent,g.encodeKeyboardEvent=encodeKeyboardEvent,g.decodeEventType=decodeEventType,g.decodeMouseEvent=decodeMouseEvent,g.decodeKeyboardEvent=decodeKeyboardEvent})(gs||(gs={}));var Os=M,Ds=R,Ns=3e4,ks=1e4,Ls=2e3,Fs=6,xs="",Us=class extends _i{constructor(g,f,S,v,C,_,T,I,b){super(g,v,(()=>this.recordedEvents.length>100)),this.auditLogger=f,this.config=S,this.negotiationTag=C,this.callId=_,this.participantId=T,this.endpointId=I,this.dataSourceId=b,this.messagesFromUnknownSender={},this.tsCallingVersion=getTsCallingVersion2()}setCallId(g){this.callId=g}setParticipantId(g){this.participantId=g}setDataSourceId(g){this.dataSourceId=g}callStateChanged(g){this.recordEvent("CallState",{state:g})}dataChannelAvailable(g){g?this.recordEvent("DataChannelAvailable"):this.recordEvent("DataChannelUnavailable")}shutdownSession(g){this.negotiationTag&&this.negotiationTag!==g?this.recordEvent("ShutdownByOtherSession",null,g):this.recordEvent("Shutdown")}recordProtocolMessage(g,f){g||(f in this.messagesFromUnknownSender||(this.messagesFromUnknownSender[f]=0),this.messagesFromUnknownSender[f]++)}sendAuditEvent(g,f,S,v,C){if(!this.auditLogger)return void this.logger.warn("AuditLogger is not set");const getValue2=g=>g??"",_={TenantId:getValue2(this.tenantId),CorrelationId:getValue2(this.callId),ParticipantId:getValue2(this.participantId),EndpointId:getValue2(this.endpointId),TsCallingVersion:getValue2(this.tsCallingVersion),sharingNegotiationTag:getValue2(this.negotiationTag),timestamp:Date.now(),eventType:f,role:toSharingControlRole(this.role),initiator:toSharingControlRole(S),controlCauseId:g,viewerParticipantId:getValue2(C.participantId),viewerEndpointId:getValue2(C.endpointId),viewerDataSourceId:getValue2(C.dataSourceId),sharerParticipantId:getValue2(v.participantId),sharerEndpointId:getValue2(v.endpointId),sharerDataSourceId:getValue2(v.dataSourceId)};try{this.auditLogger.sendEvent({eventName:"mdsc_gtc_audit",props:_})}catch(g){this.logger.error("Failed to send audit event",g)}}},Vs=class extends Us{constructor(g,f,S,v,C,_,T,I,b,A){super(g,f,S,v,C,_,T,I,b),this.role=2;const P=getSharingParticipantLeg(A);if(P){this.sharerParticipantId=P;const g=(0,Os.find)(A.endpoints.endpointDetails,(g=>g.participantId===P));g&&(this.sharerEndpointId=g.endpointId,this.sharerClientVersion=g.clientVersion)}}startHandshake(g){this.recordOperation("AvailableHandshake",g)}delayHandshakeSending(g,f,S){const v={delay:f,maxDelay:S};this.updateOperationData("AvailableHandshake",v,g)}handshakeSucceeded(g,f){const S={retries:f};this.recordOperationSuccess("AvailableHandshake",S,null,g)}handshakeFailed(g,f,S){const v={retries:f,reason:toAvailableHandshakeTerminatedString(S)};this.recordOperationFailure("AvailableHandshake",v,null,g)}requestControl(g,f){this.recordOperation("ControlRequest",g,g),this.recordAuditEvent(g,2,"ControlRequest",f)}requestControlAccepted(g,f){this.recordOperationSuccess("ControlRequest",g,g),this.recordAuditEvent(g,1,"ControlRequestAccepted",f),this.recordAuditEvent(g,2,"ControlStarted",f)}requestControlRejected(g,f,S){const v={reason:toControlTerminatedReason(f)};2===f?this.recordOperationTimeout("ControlRequest",v,g,g):this.recordOperationFailure("ControlRequest",v,g,g),this.recordAuditEvent(g,1,"ControlRequestDeclined",S)}controlGiven(g,f){this.recordEvent("ControlGiven",{sharerSourceId:f},g),this.recordAuditEvent(g,1,"ControlGiven",f),this.recordAuditEvent(g,2,"ControlStarted",f)}controlTerminated(g,f,S,v){const C={sharerSourceId:S,reason:toControlTerminatedReason(f)};this.recordEvent("ControlTerminated",C,g);const _=v?1:2;this.recordAuditEvent(g,_,"ControlTerminated",S)}recordAuditEvent(g,f,S,v){if(this.config.disableAudit)return;const C={participantId:this.sharerParticipantId,endpointId:this.sharerEndpointId,dataSourceId:v},_={participantId:this.participantId,endpointId:this.endpointId,dataSourceId:this.dataSourceId};this.sendAuditEvent(g,S,f,C,_)}getEvent(g,f){const getValue2=g=>g??"";return{CorrelationId:getValue2(this.callId),ParticipantId:getValue2(this.participantId),EndpointId:getValue2(this.endpointId),NegotiationTag:getValue2(this.negotiationTag),TsCallingVersion:getValue2(this.tsCallingVersion),TenantId:getValue2(this.tenantId),SharerParticipantId:getValue2(this.sharerParticipantId),SharerClientVersion:getValue2(this.sharerClientVersion),EventTimestampBag:super.getEventTimestampBag(g,f),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},Bs=class extends Us{constructor(g,f,S,v,C,_,T,I,b){super(g,f,S,v,C,_,T,I,b),this.role=1}availableAckChanged(g){g?this.recordEvent("AvailableAckEnabled"):this.recordEvent("AvailableAckDisabled")}controlRequest(g,f,S){this.recordOperation("ControlRequest",g,g),this.recordAuditEvent(g,2,"ControlRequest",f,S)}controlRequestAccept(g,f,S){const v={status:"accepting",participantId:S};this.updateOperationData("ControlRequest",v,g,g),this.recordAuditEvent(g,1,"ControlRequestAccepted",f,S)}controlRequestAccepted(g,f,S){const v={participantId:S};this.recordOperationSuccess("ControlRequest",v,g,g),this.recordAuditEvent(g,2,"ControlStarted",f,S)}controlRequestRejected(g,f,S,v){const C={reason:toControlTerminatedReason(f),participantId:v};4===f?this.recordOperationTimeout("ControlRequest",C,g,g):this.recordOperationFailure("ControlRequest",C,g,g),this.recordAuditEvent(g,1,"ControlRequestDeclined",S,v)}giveControl(g,f,S){this.recordOperation("GiveControl",g,g),this.recordAuditEvent(g,1,"ControlGiven",f,S)}giveControlSucceeded(g,f,S){const v={participantId:S};this.recordOperationSuccess("GiveControl",v,g,g),this.recordAuditEvent(g,2,"ControlStarted",f,S)}giveControlFailed(g,f,S,v){const C={reason:toControlTerminatedReason(f)};this.recordOperationTimeout("GiveControl",C,g,g),this.recordAuditEvent(g,1,"ControlGiveFailed",S,v)}controlTerminated(g,f,S,v,C){const _={controllerSourceId:v,reason:toControlTerminatedReason(f)};this.recordEvent("ControlTerminated",_,g);const T=C?2:1;this.recordAuditEvent(g,T,"ControlTerminated",S,v)}recordAuditEvent(g,f,S,v,C){if(this.config.disableAudit)return;const _=getParticipantLegFromStreamSourceId(v,C)??v.endpoints?.endpointDetails?.[0],T={participantId:_?.participantId,endpointId:_?.endpointId,dataSourceId:C},I={participantId:this.participantId,endpointId:this.endpointId,dataSourceId:this.dataSourceId};this.sendAuditEvent(g,S,f,I,T)}getEvent(g,f){const getValue2=g=>void 0===g?"":g;return{CorrelationId:getValue2(this.callId),ParticipantId:getValue2(this.participantId),EndpointId:getValue2(this.endpointId),NegotiationTag:getValue2(this.negotiationTag),TsCallingVersion:getValue2(this.tsCallingVersion),TenantId:getValue2(this.tenantId),EventTimestampBag:this.getEventTimestampBag(g,f),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},Hs=class extends Ke{constructor(g,f,S,v){super(g),this._logger=g,this._call=f,this._telemetryLoggers=S,this._config=v,this.controlState=0,this._role=0,this._enabled=!1,this._availableAckEnabled=!0,this._clientConfiguration={},this._dataChannelAvailable=!1,this._availableHandshakeSent=!1,this._controlRequest=null,this._controlRequestSubscription=null,this._controlCauseId=null,this._controllerParticipant=null,this._controllerParticipantSubscription=null,this._controllerSourceId=null,this._screenSharingVideoRenderer=null,this._screenSharingVideoRendererSubscriptions=[],this._sharerParticipant=null,this._pendingSharer=null,this._controlCapturer=null,this._captureEventSubscription=null,this._mouseControlEventSubscription=null,this._keyboardControlEventSubscription=null,this._requestControlTimer=null,this._grantControlTimer=null,this._acceptControlTimer=null,this._terminateControlTimer=null,this._delayedSendHandshakeTimer=null,this._availableAckTimer=null,this._retryAttempt=0,this._raiseRenderedAtViewer=null,this._participantSubscriptions={},this._viewerSessionLastTerminatedReason=0,this._completedViewerSessions=[],this.isEscalationInProgress=!1,this._logger.info("constructor"),this._callId=this._call.callId,this._call.on("callIdChanged",(g=>{this._callId=g,this._recordSessionTelemetry((f=>f.setCallId(g)))})),this._participantId=this._call.participantId,this._call.on("callLegIdChanged",(g=>{this._participantId=g,this._recordSessionTelemetry((f=>{f.setParticipantId(g),f.setDataSourceId(this.getLocalEndpointDataSourceId())}))})),this._endpointId=this._call.endpointId}get role(){return this._role}setAdapters(g,f,S){this._controlInjector=g,this._rendererAdapter=f,this._dataChannelAdapter=S,this._dataChannelAdapter.on("stateChange",(g=>{this._onDataChannelStatusChanged(g),this._recordSessionTelemetry((f=>f.dataChannelAvailable(g)))})),this._dataChannelAdapter.on("protocolMessage",((g,f,S,v)=>this.processProtocolMessage(g,f,S,v))),this._dataChannelAdapter.on("controlMessage",((g,f)=>this.processControlMessage(g,f)))}testSetControlInjector(g){}enableScreenSharingControl(g,f,S,v){if(this._logger.info(`enableScreenSharingControl() enabled=${g} disabledReason=${f}`),this._availableAckEnabled!==g||this._allowControlForUser!==v){if(this._allowControlForUser=v,g)this._raiseScreenSharingControlCapableEvent(!0,xs);else{if(0===f){const g={reason:2,detail:S};this.event("sharingControlError").raise(g)}this._raiseScreenSharingControlCapableEvent(!1,xs)}this._availableAckEnabled!==g&&this._recordSharerSessionTelemetry((f=>f.availableAckChanged(g)),!1),this._availableAckEnabled=g}}_canEnableGiveControl(){return this._controlInjector.canBeEnabled()}setRaiseRenderedAtViewer(g){this._raiseRenderedAtViewer=g}setScreenSharingControlFeatureFlag(g,f){this._logger.info(`setScreenSharingControlFeatureFlag() enabled=${g} clientConfiguration=${JSON.stringify(f)}`),this._enabled=g,this._availableAckEnabled=g,this._clientConfiguration={...f},this._enabled&&this._handleCallState(this._callState)}isScreenSharingControlEnabled(){return this._enabled}isInternalViewerControlEnabled(){return!this._clientConfiguration.externalViewerControlInitialization}isInternalSharerControlEnabled(){return!this._clientConfiguration.externalSharerControlInitialization}_disposeRenderer(g){this._disposeControlCapturer(g);for(const g of this._screenSharingVideoRendererSubscriptions)g.dispose();this._screenSharingVideoRendererSubscriptions=[],this._screenSharingVideoRenderer=null}setRenderer(g,f){this._logger.info("setRenderer");const S=generateCauseId();if(this._disposeRenderer(S),!g)return Promise.resolve();const v=f||this._rendererAdapter.getTarget(g);return asap((()=>{this._setViewingRenderer(g,v)}))}_isDataChannelActive(){return this._dataChannelAdapter.isActive()&&this._dataChannelAvailable}_raiseScreenSharingControlCapableEvent(g,f,S){if(this._enabled&&this._isDataChannelActive()){this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=true, capable=${g}, role=${this._role}`);const v={capable:g,id:f,disabledBySharer:S};this.event("sharingControlCapable").raise(v)}else{this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=false, capable=${g}, role=${this._role}`);const S={capable:!1,id:f};this.event("sharingControlCapable").raise(S)}}initControlForSharer(g){this._logger.info(`initControlForSharer() negotiationTag: ${g}`),this._isSharing()&&this._logger.warn("initControlForSharer() when already sharing"),this._resetControlState(),this._screenSharingVideoRenderer=null,this._disposeControlCapturer(),this._logger.info(`role is changing from=${this._role} to=1`),this._role=1,this._availableHandshakeSent=!1,this._raiseScreenSharingControlCapableEvent(this._canEnableGiveControl(),xs),this._initiateSharerSessionTelemetry(g)}enableControlInjector(g){this._logger.info(`enableControlInjector() trackId: ${g}`),this._canEnableGiveControl()?this._controlInjector.enableInjector(g).catch((g=>{const f={reason:0,detail:JSON.stringify({errorMsg:g})};this.event("sharingControlError").raise(f)})):this._logger.info("enableControlInjector() give control cannot be enabled")}shutdownControlForSharer(){if(this._logger.info("shutdownControlForSharer()"),this._isSharing()||this._logger.warn("shutdownControlForSharer() when not sharing"),this._controlRequest){this._logger.warn("Rejecting pending control requests");const g=this._getDataSourceIdForParticipantLeg(this._controlRequest),f=this._controlRequest;this._clearControlRequest(),this._raiseControlRequestCanceled(f),this._sendControlRejectRequest(f.causeId,5,f.participant,g)}if(this._controllerParticipant){const g={inControl:!1,id:this._controllerParticipant.participant.id,terminatedReason:5};this._recordSharerSessionTelemetry((f=>f.controlTerminated(this._controlCauseId,g.terminatedReason,this._controllerParticipant.participant,this._controllerSourceId))),this.event("sharingControlChanged").raise(g)}this._finalizeSharerSessionTelemetry(),this._teardownSharerRemoteControl(),this._controlInjector.disableInjector().catch((g=>{const f={reason:0,detail:JSON.stringify({errorMsg:g})};this.event("sharingControlError").raise(f)})),this._resetControlState(),this._resetParticipantSubscriptions(),this._availableAckEnabled=this._enabled,this._logger.info(`role is changing from=${this._role} to=0`),this._role=0}_resetParticipantSubscriptions(){this._logger.info("resetParticipantSubscriptions() Stopping tracking all participant state changes"),(0,Os.each)(this._participantSubscriptions,(g=>{g.dispose()})),this._participantSubscriptions={}}_initiateViewerSessionTelemetry(g,f,S){if(!S&&!f)return null;if(!S&&(0,Os.find)(this._completedViewerSessions,(g=>f===g)))return null;if(this._currentViewerSessionTelemetry){if(this._currentViewerSessionTelemetry.negotiationTag===f)return null;this._finalizeViewerSessionTelemetry(f)}return this._logger.info(`Initiating new viewer session telemetry for ${f}`),this._currentViewerSessionTelemetry=new Vs(this._logger,this._telemetryLoggers?.gtcAudit,this._config,(new Date).getTime(),f,this._callId,this._participantId,this._endpointId,this.getLocalEndpointDataSourceId(),g),this._currentViewerSessionTelemetry.callStateChanged(this._callState),this._isDataChannelActive()&&this._currentViewerSessionTelemetry.dataChannelAvailable(!0),this._currentViewerSessionTelemetry}_recordViewerSessionTelemetry(g,f=!0){this._currentViewerSessionTelemetry?g&&g(this._currentViewerSessionTelemetry):f&&this._logger.error("Cannot record telemetry without current session")}_finalizeViewerSessionTelemetry(g){if(!this._currentViewerSessionTelemetry)return;this._currentViewerSessionTelemetry.shutdownSession(g);const f=this._currentViewerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_viewer_session",f),this._currentViewerSessionTelemetry.negotiationTag&&this._completedViewerSessions.push(this._currentViewerSessionTelemetry.negotiationTag),this._currentViewerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentViewerSessionTelemetry.messagesFromUnknownSender).length&&Ds.RootToolsManager.logExternalForDDL("ScreenSharingControl_viewer: messages received from unkonwn sender",JSON.stringify(f.ProtocolMessages)),this._currentViewerSessionTelemetry=null}_initiateSharerSessionTelemetry(g){if(this._currentSharerSessionTelemetry){if(this._currentSharerSessionTelemetry.negotiationTag===g)return null;this._finalizeSharerSessionTelemetry(this._currentSharerSessionTelemetry.negotiationTag)}this._logger.info(`Initiating new sharer session telemetry for ${g}`),this._currentSharerSessionTelemetry=new Bs(this._logger,this._telemetryLoggers?.gtcAudit,this._config,(new Date).getTime(),g,this._callId,this._participantId,this._endpointId,this.getLocalEndpointDataSourceId()),this._isDataChannelActive()&&this._currentSharerSessionTelemetry.dataChannelAvailable(!0)}_recordSharerSessionTelemetry(g,f=!0){this._currentSharerSessionTelemetry?g&&g(this._currentSharerSessionTelemetry):f&&this._logger.error("Cannot record telemetry without current session")}_finalizeSharerSessionTelemetry(g){if(!this._currentSharerSessionTelemetry)return;this._currentSharerSessionTelemetry.shutdownSession(g);const f=this._currentSharerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_sharer_session",f),this._currentSharerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentSharerSessionTelemetry.messagesFromUnknownSender).length&&Ds.RootToolsManager.logExternalForDDL("ScreenSharingControl_sharer: messages received from unkonwn sender",JSON.stringify(f.ProtocolMessages)),this._currentSharerSessionTelemetry=null}_recordSessionTelemetry(g){g&&(this._currentSharerSessionTelemetry&&g(this._currentSharerSessionTelemetry),this._currentViewerSessionTelemetry&&g(this._currentViewerSessionTelemetry))}_sendTelemetryEvent(g,f){this._logger.info(`Sending event ${g}: `),Object.keys(f).forEach((g=>{this._logger.info(`     ${g} => ${f[g]}`)})),this._telemetryLoggers?.media?.sendEvent({eventName:g,props:f})}reportSharingSessionChangeForViewer(g,f){f&&this._initiateViewerSessionTelemetry(g,f,!1)}initControlForViewer(g,f){if(this._logger.info(`initControlForViewer(${scrubMriOrOmit(g?.id)}, ${f})`),g){if(this._isViewing()&&this._logger.warn("initControlForViewer: called when already viewing"),3!==this._callState)return this._logger.info(`initControlForViewer: postponed until call is connected, callState=${this._callState}`),this._pendingNegotiationTag=f,void(this._pendingSharer=g);this._logger.info(`role is changing from=${this._role} to=2`),this._role=2,this._sharerParticipant?this._sharerParticipant.id!==g.id&&(this._logger.info(`initControlForViewer: sharer switched, new sharer id=${scrubMriOrOmit(g.id)}`),this._availableHandshakeSent=!1,4===this.controlState&&this._terminateControl(!1)):(this._logger.info(`initControlForViewer: setting sharer to id=${scrubMriOrOmit(g.id)}`),this._sharerParticipant=g,this._availableHandshakeSent=!1),this._initiateViewerSessionTelemetry(g,f,!0),this._enabled&&this._isDataChannelActive()&&!this._availableHandshakeSent&&(this._resetControlState(),this._sharerParticipant=g,this._logger.info("initControlForViewer: sending Available message to sharer"),this._startAvailableHandshake())}else this._logger.warn("initControlForViewer: Sharer undefined, ignoring")}shutdownControlForViewer(g){if(this._logger.info(`shutdownControlForViewer() isViewing: ${this._isViewing()}`),this._pendingSharer=null,(!g||g.id===this._sharerParticipant?.id)&&this._isViewing()){if(this._logger.info(`shutdownControlForViewer: sharerParticipant id=${g?scrubMriOrOmit(g.id):null}`),1===this.controlState){if(this._sharerParticipant){const g=this._getSharerDataSourceId();this._sendRequest({action:2,terminatedReason:6,causeId:this._controlCauseId},g)}else this._logger.warn("shutdownControlForViewer: sharer participant is null");const g={inControl:!1,id:xs,terminatedReason:6};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:g,details:""}))):this._logger.error("shutdownControlForViewer: Unexpected, no promise could be resolved, controlState=RequestSent")}else if(4===this.controlState){const g={inControl:!1,id:xs,terminatedReason:6};this._recordViewerSessionTelemetry((f=>f.controlTerminated(this._controlCauseId,g.terminatedReason,this._controllerSourceId,!1))),this.event("sharingControlChanged").raise(g)}this._teardownViewerRemoteControl(),this._resetControlState(),this._screenSharingVideoRenderer=null,this._terminateAvailableHandshake&&this._terminateAvailableHandshake(2),this._availableHandshakeSent=!1,this._finalizeViewerSessionTelemetry(),2===this._role?(this._logger.info(`_raiseScreenSharingControlCapableEvent  with user role=${this._role}, MRI=${xs}, isCapable=false`),this._raiseScreenSharingControlCapableEvent(!1,xs)):this._logger.warn(`can't call _raiseScreenSharingControlCapableEvent, role=${this._role}`),this._logger.info(`role is changing from=${this._role} to=0`),this._role=0}}_resetControlRequest(g){this._clearControlRequest(),this._controlRequest=g,this._registerParticipantListener(g),3===g.participantState&&(this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${scrubMriOrOmit(g.participant.id)}`),this.event("sharingIncomingControlRequest").raise(g.participant.id))}_clearControlRequest(){this._logger.info("_clearControlRequest()"),this._stopListeningToParticipantChanges(this._controlRequest),this._controlRequest=null}_stopListeningToParticipantChanges(g){this._controlRequestSubscription&&(this._logger.info(`_stopListeningToParticipantChanges: stopping tracking changes for ${scrubMriOrOmit(g.participant.id)}`),this._controlRequestSubscription.dispose(),this._controlRequestSubscription=null)}_registerParticipantListener(g){this._logger.info(`_registerParticipantListener: tracking changes for ${scrubMriOrOmit(g.participant.id)}`),this._logger.info(`request.participantState: ${g.participantState} | request.participant.state: ${g.participant.state}`),this._controlRequestSubscription=g.participant.changed((()=>{if(g.participant.state!==g.participantState)switch(this._logger.info(`request.participantState about to changed from: ${g.participantState} to: ${g.participant.state}`),g.participantState=g.participant.state,g.participantState){case 3:this.event("sharingIncomingControlRequest").raise(g.participant.id),this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${scrubMriOrOmit(g.participant.id)}`);break;case 0:case 5:case 4:this.denyControlRequest().catch((g=>{this._logger.info(`It is ok if denyControlRequest rejects here as screensharing may have just been stopped. Err: ${g}`)})),this._logger.info(`_registerParticipantListener: participant ${scrubMriOrOmit(g.participant.id)} is no longer connected. resetting`),this._clearControlRequest(),this._raiseControlRequestCanceled(g);break;case 1:case 2:case 6:case 7:this._logger.info(`participantState: ${g.participantState}, participantId: ${scrubMriOrOmit(g.participant.id)}`);break;default:this._logger.error(`_registerParticipantListener: Unexpected participantState ${g.participantState} unhandled`)}}))}_resetControllerParticipant(g){this._controllerParticipantSubscription&&(this._logger.info(`_resetControllerParticipant: stopping tracking changes for ${scrubMriOrOmit(this._controllerParticipant.participant.id)}`),this._controllerParticipantSubscription.dispose(),this._controllerParticipantSubscription=null),g&&(this._logger.info(`_resetControllerParticipant: tracking changes for ${scrubMriOrOmit(g.participant.id)}`),this._controllerParticipantSubscription=g.participant.changed((()=>{3!==g.participant.state&&this.handleParticipantRemoved(g.participant.id)}))),this._controlCauseId=g?.causeId??null,this._controllerParticipant=g}handleParticipantRemoved(g){if(this._participantSubscriptions[g]&&(this._logger.info(`handleParticipantRemoved(): Stopping tracking state changes for ${scrubMriOrOmit(g)}`),this._participantSubscriptions[g].dispose(),delete this._participantSubscriptions[g]),this._isSharing()){if(this._controllerParticipant&&this._controllerParticipant.participant.id===g){this._logger.info("handleParticipantRemoved: controller left call, tearing down control session"),this._teardownSharerRemoteControl(),this.controlState=0;const f=5;this._recordSharerSessionTelemetry((g=>g.controlTerminated(this._controlCauseId,f,this._controllerParticipant.participant,this._controllerSourceId,!0))),this._resetControllerParticipant();const S={inControl:!1,id:g,terminatedReason:f};this.event("sharingControlChanged").raise(S)}this._raiseScreenSharingControlCapableEvent(!1,g)}else if(this._sharerParticipant&&this._sharerParticipant.id===g&&4===this.controlState){this._logger.info("handleParticipantRemoved: sharer left call, tearing down control session"),this._teardownViewerRemoteControl(),this.controlState=0;const g={inControl:!1,id:xs,terminatedReason:6};this.event("sharingControlChanged").raise(g)}}callStateChanged(g){this._callState=g,this._recordSessionTelemetry((f=>f.callStateChanged(g))),this.isScreenSharingControlEnabled()&&this._handleCallState(g)}setIsEscalationInProgress(g){this.isEscalationInProgress=g}_getHandshakeDelay(){if(!this._config.handshakeSendDelay?.minParticipantThreshold)return 0;let g=0;if(this._call.participants.length>=this._config.handshakeSendDelay.minParticipantThreshold)for(const f of this._call.participants)f.endpoints?.endpointDetails.some((g=>"interactive"===g.appliedInteractivityLevel))&&g++;if(g<=this._config.handshakeSendDelay.minParticipantThreshold)return 0;const f=Math.ceil((g-this._config.handshakeSendDelay.minParticipantThreshold)/this._config.handshakeSendDelay.increaseEveryN);return Math.min(this._config.handshakeSendDelay.maxDelay,f*this._config.handshakeSendDelay.delayPerN)}_handleCallState(g){switch(g){case 3:this._handleCallConnected();break;case 7:this._handleCallDisconnected();break;case 4:case 5:this.isInternalViewerControlEnabled()&&this.shutdownControlForViewer()}}_handleCallConnected(){this._logger.info("_handleCallConnected()"),this._pendingSharer&&(this.initControlForViewer(this._pendingSharer,this._pendingNegotiationTag),this._pendingSharer=null)}_handleCallDisconnected(){this._logger.info("_handleCallDisconnected()"),this._isSharing()?this.isInternalSharerControlEnabled()&&this.shutdownControlForSharer():this.isInternalViewerControlEnabled()&&this.shutdownControlForViewer()}_videoSizeChanged(g,f){null!==this._controlCapturer&&this._controlCapturer.updateVideoSize(g,f)}_onRenderStarted(){const g={action:11,terminatedReason:0};if(this._sharerParticipant){const f=this._getSharerDataSourceId();this._sendRequest(g,f)}else this._logger.error("Attempted to send sharing rendered message to null sharerParticipant")}_setViewingRenderer(g,f){try{this._screenSharingVideoRenderer=g,this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeVideoSizeChangedEvent(this._screenSharingVideoRenderer,((g,f)=>{this._videoSizeChanged(g,f)}))),this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeRenderStartedEvent(this._screenSharingVideoRenderer,(()=>{this._onRenderStarted()})));let S=1;g.streamSize&&g.streamSize.width>0&&g.streamSize.height>0&&(S=g.streamSize.width/g.streamSize.height),this._controlCapturer=new ws.SlimCoreElectronControlCapturer(this._logger,f,!0,S),4===this.controlState?(this._logger.info("_setViewingRenderer: detected local state is controlling"),this._setupViewerRemoteControl()):this._teardownViewerRemoteControl()}catch(g){this._logger.error(`_setViewingRenderer: unable to set _screenSharingVideoRenderer error=${g}`)}}_onDataChannelStatusChanged(g){this._logger.info(`_onDataChannelStatusChanged(): Data channel status=${g}, isEscalationInProgress=${this.isEscalationInProgress}`),g?this._dataChannelAvailable||(this._dataChannelAvailable=!0,this._recordSessionTelemetry((g=>g.dataChannelAvailable(!0))),this._enabled&&(this._isViewing()?this._availableHandshakeSent||(this._sharerParticipant?(this._logger.info("_onDataChannelStatusChanged: sending Available message to sharer"),this._startAvailableHandshake()):this._logger.error("Unexpected null _sharerParticipant trying to send Available to sharer")):this._isSharing()&&(this.isEscalationInProgress||this._raiseScreenSharingControlCapableEvent(!0,xs)))):this._dataChannelAvailable&&(this._recordSessionTelemetry((g=>g.dataChannelAvailable(!1))),this._dataChannelAvailable=!1,this._availableHandshakeSent=!1,this._terminateAvailableHandshake&&this._terminateAvailableHandshake(3),this.isEscalationInProgress||this._raiseScreenSharingControlCapableEvent(!1,xs))}_isSharing(){return 1===this._role}_isViewing(){return 2===this._role}_handleAvailableRequest(g,f,S){if(this._isSharing())return this._enabled&&this._availableAckEnabled&&this._canEnableGiveControl()?f?.id?void(this._allowControlForUser&&"function"==typeof this._allowControlForUser?this._allowControlForUser(f).then((v=>{v?this._acceptAvailableRequest(g.handshakeId,f,S):this._rejectAvailableRequest(g.handshakeId,S,1)})):this._acceptAvailableRequest(g.handshakeId,f,S)):(this._logger.info("Unknown sender. Rejecting available ack"),void this._rejectAvailableRequest(g.handshakeId,S,10)):(this._logger.info(`Rejecting available ack - enabled=${this._enabled}, availableAck=${this._availableAckEnabled}, controlInjector=${this._canEnableGiveControl()}`),void this._rejectAvailableRequest(g.handshakeId,S,9));this._logger.warn(`Ignoring available request since role=${this._role} is not sharing. Expecting for viewer side retries`)}_acceptAvailableRequest(g,f,S){this._raiseScreenSharingControlCapableEvent(!0,f.id),this._participantSubscriptions[f.id]||(this._logger.info(`Tracking participant status for ${scrubMriOrOmit(f.id)}`),this._participantSubscriptions[f.id]=f.changed((()=>{3!==f.state&&(this._logger.info(`Participant ${scrubMriOrOmit(f.id)} is not connected. removing`),this.handleParticipantRemoved(f.id))}))),this._logger.info(`Acking Available for handShake:${S}:${g}`),this.event("controlAvailableHandshake").raise(g,S,3),this._sendRequest({action:9,terminatedReason:0,handshakeId:g},S)}_rejectAvailableRequest(g,f,S){this._logger.info(`Rejecting Available for handShake:${f}:${g}`),this.event("controlAvailableHandshake").raise(g,f,7,this._getAvailableHandshakeTerminatedFromControlTerminated(S)),this._sendRequest({action:10,terminatedReason:S,handshakeId:g},f)}processProtocolMessage(g,f,S,v){return asap((()=>{this._processProtocolMessage(g,f,S,v)}))}_raiseControlRequestCanceled(g){this.event("sharingIncomingControlRequestCancelled").raise(g.participant.id)}_handleControlRequest(g,f,S,v){this._recordSharerSessionTelemetry((S=>S.controlRequest(v,g,f))),this._enabled?this._controlRequest?(this._logger.warn("Sharer is already processing a control request...rejecting new requests"),this._sendControlRejectRequest(v,3,g,f)):this._controllerParticipant&&this._controllerParticipant.participant===g?this._controllerParticipant.participantId&&this._controllerParticipant.participantId!==S?(this._logger.warn(`rejecting control request from second endpoint. participantId: ${S}`),this._sendControlRejectRequest(v,3,g,f)):(this._logger.warn("Got control request for someone already in control"),this._resetControllerParticipant(),this._resetControlRequest({participant:g,participantState:g.state,participantId:S,causeId:v})):g?(this._logger.info(`resetControlRequest for participantId: ${S}`),this._resetControlRequest({participant:g,participantState:g.state,participantId:S,causeId:v})):this._logger.error("Got ControlRequest message but could not find a sender participant, ignoring"):(this._logger.warn("Sharer control is disabled - rejecting request"),this._sendControlRejectRequest(v,9,g,f))}_handleAcceptRequest(g,f){if(1===this.controlState){const S=this._sendRequest({action:5,terminatedReason:0},f);this._logger.info(`_handleAcceptRequest controlMessage.action: ${toControlActionString(g.action)} _sendRequest isSent: ${S}`),S?(this._setupViewerRemoteControl(),this.controlState=4,this._requestControlPromise?this._requestControlPromise.resolve():this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${toControlActionString(g.action)}`),this._recordViewerSessionTelemetry((g=>g.requestControlAccepted(this._controlCauseId,f)))):this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:void 0,details:"request control is accepted, but failed to send ack"}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)} action=${toControlActionString(g.action)}`),this._cancelRequestControlTimer()}else this._logger.warn(`AcceptRequest message received in controlState=${toControlStateString(this.controlState)}`)}_handleRejectRequest(g,f){if(1===this.controlState){this._logger.info(`_handleRejectRequest: controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(0)}`),this.controlState=0;const S={inControl:!1,id:xs,terminatedReason:g.terminatedReason};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:S,details:""}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${toControlActionString(g.action)}`),this._recordViewerSessionTelemetry((S=>S.requestControlRejected(this._controlCauseId,g.terminatedReason,f))),this._cancelRequestControlTimer(),this._controlCauseId=null}else this._logger.warn(`RejectRequest message received in controlState=${toControlStateString(this.controlState)} reason=${g.terminatedReason}`)}_handleCancelControlRequest(g,f){if(this._logger.info(`_handleCancelControlRequest action=${toControlActionString(g.action)} sender=${f}, controlRequest participantId: ${this._controlRequest.participantId}, controlRequest participantState: ${this._controlRequest.participantState}:`),this._controlRequest){const S=this._controlRequest;this._logger.info(`_handleCancelControlRequest action=${toControlActionString(g.action)} sender=${f}, about to raise: _raiseControlRequestCanceled state: ${this._controlRequest.participantState} `),this._recordSharerSessionTelemetry((v=>v.controlRequestRejected(g.causeId,g.terminatedReason,S.participant,f))),this._clearControlRequest(),this._raiseControlRequestCanceled(S)}}_handleGiveControl(g,f,S){const v=this._sendRequest({action:5,terminatedReason:0},f);if(this._logger.info(`_handleGiveControl: controlMessage.action: ${toControlActionString(g.action)} _sendRequest isSent: ${v}`),this._controlCauseId=g.causeId,v){this._setupViewerRemoteControl(),this._logger.info(`controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(4)}`),this.controlState=4,this._recordViewerSessionTelemetry((g=>g.controlGiven(this._controlCauseId,f)));const S={inControl:!0,id:xs,terminatedReason:g.terminatedReason};this.event("sharingControlChanged").raise(S)}}_handleAck(g,f,S){if(2===this.controlState)if(this._controllerParticipant&&this._controllerParticipant.participant.id===f.id){const f=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);S!==f&&this._logger.warn(`acknowledging source id: ${S} does not match requesting source id: ${f}`),this._logger.info(`Setting up remote control for controller source id=${f}`),this._setupSharerRemoteControl(f),this._logger.info(`controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(3)}`),this.controlState=3;const v={inControl:!0,id:this._controllerParticipant.participant.id,terminatedReason:g.terminatedReason};this.event("sharingControlChanged").raise(v),this._grantControlPromise?(this._grantControlPromise.resolve(),this._cancelGrantControlTimer(),this._recordSharerSessionTelemetry((g=>g.giveControlSucceeded(this._controlCauseId,this._controllerParticipant.participant,f)))):this._acceptControlPromise?(this._acceptControlPromise.resolve(),this._cancelAcceptControlTimer(),this._recordSharerSessionTelemetry((g=>g.controlRequestAccepted(this._controlCauseId,this._controllerParticipant.participant,f)))):this._logger.error(`Unexpected, no promise could be resolved - controlState=WaitingForControlAck action=${toControlActionString(g.action)}`)}else f?this._logger.warn(`Ignoring ack from participant that does not match controller id=${scrubMriOrOmit(f.id)}`):this._logger.warn(`Ignoring ack from null participant source id=${S}`);else 5===this.controlState?(this._logger.info(`controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(0)}`),this.controlState=0,this._resetControllerParticipant(),this._terminateControlPromise?(this._terminateControlPromise.resolve(),this._cancelTerminateControlTimer()):this._logger.error(`Unexpected, no promise could be resolved - controlState=WaitingForTerminateAck action=${toControlActionString(g.action)}`)):this._logger.warn(`Unexpected ack in control controlState=${toControlStateString(this.controlState)}`)}_handleTerminate(g,f,S){let v;this._isViewing()?(this._teardownViewerRemoteControl(),v=xs,this._recordViewerSessionTelemetry((f=>f.controlTerminated(this._controlCauseId,g.terminatedReason,S,!0)))):(this._teardownSharerRemoteControl(),f?v=f.id:this._logger.error("Got terminate message but could not find a sender participant!"),this._recordSharerSessionTelemetry((f=>f.controlTerminated(this._controlCauseId,g.terminatedReason,this._controllerParticipant.participant,S,!0)))),this._logger.info(`controlMessage action: ${toControlActionString(g.action)}, controllerId: ${v}`),this._logger.info(`controlState: ${toControlStateString(this.controlState)}, about to be changed to: ${toControlStateString(0)}`),this.controlState=0,this._resetControllerParticipant();const C={inControl:!1,id:v,terminatedReason:g.terminatedReason};this.event("sharingControlChanged").raise(C),8===g.action&&this._sendRequest({action:5,terminatedReason:0},S)}_handleAvailableAck(g){this._terminateAvailableHandshake&&(this._logger.info(`_handleAvailableAck: terminate available handshake reason: 1,handshakeId: ${g.handshakeId}`),this._terminateAvailableHandshake(1,g.handshakeId)),2===this._role?this._raiseScreenSharingControlCapableEvent(!0,xs):this._logger.info(`Ignoring AvailableAck as viewer session is not initialized, role: ${this._role}`)}_handleAvailableNack(g){this._logger.info(`_handleAvailableNack: action=${toControlActionString(g.action)} terminate reason: ${toControlTerminatedReason(g.terminatedReason)}`),this._viewerSessionLastTerminatedReason=g.terminatedReason,10!==g.terminatedReason?(this._terminateAvailableHandshake&&(this._terminateAvailableHandshake(this._getAvailableHandshakeTerminatedFromControlTerminated(g.terminatedReason),g.handshakeId),this._logger.info(`_handleAvailableNack: terminateAvailableHandshake reason=${toControlTerminatedReason(g.terminatedReason)}`)),1===g.terminatedReason?(this._logger.warn("_handleAvailableNack: control terminate reason: SharerDenied"),this._raiseScreenSharingControlCapableEvent(!0,xs,!0)):this._raiseScreenSharingControlCapableEvent(!1,xs)):this._logger.warn("_handleAvailableNack: control terminate reason: UnknownSender")}_handleRenderedAtViewer(g,f){this._raiseRenderedAtViewer&&(f?(this._logger.info(`raiseRenderedAtViewer senderId=${scrubMriOrOmit(f.id)}, action=${toControlActionString(g.action)}`),this._raiseRenderedAtViewer(f.id)):this._logger.error("Got RenderedAtViewer message but could not find a sender participant!"))}_processProtocolMessage(g,f,S,v){let C;this._recordSessionTelemetry((g=>g.recordProtocolMessage(f,v)));try{C=JSON.parse(g)}catch(g){return void this._logger.error("Error parsing controlMessage")}switch(f||this._logger.warn(`protocol message from unknown sender with sourceId=${v}`),this._logger.info(`_processProtocolMessage action=${toControlActionString(C.action)}, sourceId=${v}`),C.action){case 0:this._handleAvailableRequest(C,f,v);break;case 1:this._handleControlRequest(f,v,S,C.causeId);break;case 3:this._handleAcceptRequest(C,v);break;case 4:this._handleRejectRequest(C,v);break;case 2:this._handleCancelControlRequest(C,v);break;case 6:this._handleGiveControl(C,v,f);break;case 5:this._handleAck(C,f,v);break;case 8:case 7:this._handleTerminate(C,f,v);break;case 9:this._handleAvailableAck(C);break;case 10:this._handleAvailableNack(C);break;case 11:this._handleRenderedAtViewer(C,f);break;default:this._logger.error(`Unknown request action received on control protocol data sink, action=${toControlActionString(C.action)}`)}}_getAvailableHandshakeTerminatedFromControlTerminated(g){switch(g){case 10:return 6;case 1:return 7;default:return 0}}_sendRequest(g,f){if(f<0)return this._logger.warn(`Unexpected: invalid sourceID=${f}`),!1;this._logger.info(`_sendRequest() action=${toControlActionString(g.action)} recipient sourceid=${f}`);const S={type:0,message:JSON.stringify(g)},v=[f];return this._dataChannelAdapter.sendProtocolMessage(stringToBuffer(JSON.stringify(S)),v),!0}async processControlMessage(g,f){if(f===this._controllerSourceId){if(3===this.controlState)return this._processControlMessage(g,f);this._logger.debug(`Ignoring control message, wrong controlState. Expected: RemoteControlling, got: ${toControlStateString(this.controlState)}`)}else this._logger.debug(`Ignoring control message, wrong sourceId. Expected: ${f}, got: ${this._controllerSourceId}`)}_processControlMessage(g,f){return this._controlInjector.injectRawInput(g,f)}_resetControlState(){this._logger.info("_resetControlState()"),this.controlState=0,this._resetControllerParticipant(),this._sharerParticipant=null,this._controlCauseId=null,this._clearControlRequest(),this._cancelRequestControlTimer(),this._cancelAcceptControlTimer(),this._cancelGrantControlTimer(),this._cancelTerminateControlTimer()}_setupSharerRemoteControl(g){this._logger.info(`_setupSharerRemoteControl() sourceId=${g}`),this._controllerSourceId=g,this._controlInjector.showVirtualCursor(g).catch((f=>{const S={reason:3,detail:JSON.stringify({sourceId:g,errorMsg:f})};this.event("sharingControlError").raise(S)}))}_teardownSharerRemoteControl(){this._logger.info("_teardownSharerRemoteControl()"),this._controllerSourceId=null,this._controlInjector.showVirtualCursor(0).catch((g=>{const f={reason:3,detail:JSON.stringify({sourceId:0,errorMsg:g})};this.event("sharingControlError").raise(f)}))}_setupViewerRemoteControl(){this._logger.info("_setupViewerRemoteControl()"),this._setCapturerMode(3)}_teardownViewerRemoteControl(){this._logger.info("_teardownViewerRemoteControl()"),this._setCapturerMode(0)}_clearCapturerEventSubscriptions(){this._logger.info("_clearCapturerEventSubscriptions()"),this._captureEventSubscription&&(this._captureEventSubscription.dispose(),this._captureEventSubscription=null),this._mouseControlEventSubscription&&(this._mouseControlEventSubscription.dispose(),this._mouseControlEventSubscription=null),this._keyboardControlEventSubscription&&(this._keyboardControlEventSubscription.dispose(),this._keyboardControlEventSubscription=null)}sendRemoteControlEvent(g,f){if(f)switch(g){case"mouseControlEvent":this._sendControlEvent(gs.encodeMouseEvent(f));break;case"keyboardControlEvent":this._sendControlEvent(gs.encodeKeyboardEvent(f));break;default:return void this._logger.error("sendRemoteControlEvent: Invalid type=",g)}else this._logger.error("sendRemoteControlEvent: Invalid argument.")}_sendControlEvent(g){if(!this._isDataChannelActive()||!this._sharerParticipant||4!==this.controlState)return void this._logger.error(`_sendControlEvent: Dropping message - No data channel or wrong controlState. dataConnected: ${this._isDataChannelActive()} controlState: ${toControlStateString(this.controlState)})`);const f=[this._getSharerDataSourceId()];this._dataChannelAdapter.sendControlMessage(g,f)}_setCapturerMode(g){this._logger.info(`_setCapturerMode() capturerMode=${g}`),this._controlCapturer?(this._controlCapturer.setCaptureMode(g),this._clearCapturerEventSubscriptions(),1===g?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(g=>{0===g&&this.event("sharingRendererClicked").raise()})):2===g?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(g=>{1===g?this.event("sharingRendererMouseEntering").raise():2===g&&this.event("sharingRendererMouseLeaving").raise()})):3===g&&(this._mouseControlEventSubscription=this._controlCapturer.on("mouseControlEvent",(g=>{this._sendControlEvent(gs.encodeMouseEvent(g))})),this._keyboardControlEventSubscription=this._controlCapturer.on("keyboardControlEvent",(g=>{this._sendControlEvent(gs.encodeKeyboardEvent(g))})),this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(g=>{1===g?this.event("sharingRendererMouseEntering").raise():2===g&&this.event("sharingRendererMouseLeaving").raise()})))):this._logger.info("_controlCapturer not set, relying on external controlCapturer")}setPointerImage(g,f){return this._logger.warn("setPointerImage is deprecated. Use setLocalPointerImage or setRemotePointerImage"),g?this.setRemotePointerImage(g,f):this.setLocalPointerImage(f)}setLocalPointerImage(g){return 0===g.length?Promise.reject(new Error("setLocalPointerImage invalid image length")):this._setPointerImage(0,g)}async setRemotePointerImage(g,f){if(!g)throw new Error("setRemotePointerImage participant is null");if(0===f.length)throw new Error("setRemotePointerImage invalid image length");const S=this._getParticipantsDataSourceIds(g);if(0===S.length)throw new Error("setRemotePointerImage unable to map participant to sourceIds");this._logger.info(`set pointer image for ${S.length} sources`);for(const g of S)await this._setPointerImage(g,f)}_setPointerImage(g,f){return this._isSharing()||this._logger.warn("_setPointerImage called when not sharing"),this._controlInjector.setPointerImage(g,f)}startPointerMode(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`startPointerMode called in bad control controlState=${toControlStateString(this.controlState)}`)):this._isViewing()?asap((()=>{this._setCapturerMode(2)})):Promise.reject(new Error("startPointerMode when not viewing")):Promise.reject(new Error("startPointerMode when data channel not active")):Promise.reject(new Error("startPointerMode when feature not enabled"))}stopPointerMode(){return 0!==this.controlState?Promise.reject(new Error(`stopPointerMode called in bad control controlState=${toControlStateString(this.controlState)}`)):this._isViewing()?asap((()=>{this._setCapturerMode(1)})):Promise.reject(new Error("stopPointerMode when not viewing"))}_startAvailableHandshake(){const g=this._getSharerDataSourceId(),f=generateGuid(),S=this._getHandshakeDelay(),v=Math.floor(Math.random()*S);if(this._logger.info(`_startAvailableHandshake() - handshakeId: ${g}:${f} ${v>0?`delay: ${v}ms maxDelay: ${S}ms`:""}}`),this._terminateAvailableHandshake&&(this._logger.warn("Replacing existing availble handshake"),this._terminateAvailableHandshake(4)),this._recordViewerSessionTelemetry((g=>g.startHandshake(f))),g<0)this._logger.warn(`_startAvailableHandshake() - sharer: ${scrubMriOrOmit(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(f);else{const sendAvailableHandshake=()=>{this.event("controlAvailableHandshake").raise(f,g,1),this._sendRequest({action:0,terminatedReason:0,handshakeId:f},g)||this._logger.error("Failed to send Available message to sharer, will retry after backoff"),this._waitForAvailableAck(f)};v>0?(this._delayedSendHandshakeTimer=window.setTimeout(sendAvailableHandshake,v),this._recordViewerSessionTelemetry((g=>g.delayHandshakeSending(f,v,S)))):sendAvailableHandshake()}this._availableHandshakeSent=!0,this._terminateAvailableHandshake=(S=0,v)=>{this._logger.info(`_terminateAvailableHandshake() - handshakeId: ${g}:${f}, status: ${S}`),1===S?this._recordViewerSessionTelemetry((g=>g.handshakeSucceeded(f,this._retryAttempt))):(this._logger.error(`GTC handshake terminated with code ${S}, last terminated reason: ${toControlTerminatedReason(this._viewerSessionLastTerminatedReason)}`),Ds.RootToolsManager.logExternalForDDL(`GTC handshake terminated with code ${S},`,this._viewerSessionLastTerminatedReason.toString()),this._recordViewerSessionTelemetry((g=>g.handshakeFailed(f,this._retryAttempt,S)))),this._terminateAvailableHandshake=null,this.event("controlAvailableHandshake").raise(f,g,1===S?5:6,S),v&&v!==f&&this._logger.warn(`AvailableSeries: Got handshake from another series - expected: ${f}, received: ${v}`),this._availableAckTimer&&(clearTimeout(this._availableAckTimer),this._availableAckTimer=null),this._delayedSendHandshakeTimer&&(clearTimeout(this._delayedSendHandshakeTimer),this._delayedSendHandshakeTimer=null),this._retryAttempt=0}}_waitForAvailableAck(g){this._logger.info("_waitForAvailableAck()"),this._availableAckTimer=window.setTimeout((()=>{this._logger.warn(`No Ack received for Available message from attempt=${this._retryAttempt}`),this._availableAckTimer=null;const f=this._getSharerDataSourceId();if(this._retryAttempt<=Fs)f>=0?(this._logger.info(`Re-sending Available message handshakeId: ${f}:${g}`),this.event("controlAvailableHandshake").raise(g,f,2),this._sendRequest({action:0,terminatedReason:0,handshakeId:g},f)):this._logger.warn(`_waitForAvailableAck() - sharer: ${scrubMriOrOmit(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(g);else{if(this._logger.error("Reached Available retry limit! Control capability will be false"),this._terminateAvailableHandshake)this._terminateAvailableHandshake(5);else{const g={reason:4,detail:JSON.stringify({sourceId:f,errorMsg:`Timed out after ${this._retryAttempt} tries`})};this.event("sharingControlError").raise(g)}this._raiseScreenSharingControlCapableEvent(!1,xs)}}),Ls*++this._retryAttempt)}requestControl(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`requestControl called in bad controlState=${toControlStateString(this.controlState)}`)):this._isViewing()?this._sharerParticipant?this._requestControlPromise?Promise.reject(new Error("request control promise has not been resolved yet while requesting control")):this._terminateControlPromise?Promise.reject(new Error("terminate control promise has not been resolved yet while requesting control")):this._requestControl():Promise.reject(new Error("requestControl unexpected null sharer")):Promise.reject(new Error("requestControl when not viewing")):Promise.reject(new Error("requestControl when data channel not active")):Promise.reject(new Error("requestControl when feature not enabled"))}_requestControl(){const g=this._controlCauseId=generateCauseId();this._logger.info(`_requestControl(), controlState: ${this.controlState}, controlCauseId: ${g}`),this._requestControlPromise=new dt;const always=()=>{this._requestControlPromise=null};this._requestControlPromise.promise.then(always,always);const f=this._getSharerDataSourceId();if(!this._sendRequest({action:1,terminatedReason:0,causeId:g},f)){const g={inControl:!1,id:xs,terminatedReason:7};return this._requestControlPromise.reject(new Error),this._logger.error("_requestControl(): failed to send the request."),Promise.reject(new Error(JSON.stringify({controlInfo:g,details:""})))}return this._recordViewerSessionTelemetry((S=>S.requestControl(g,f))),this.controlState=1,this._requestControlTimer=window.setTimeout((()=>{if(1===this.controlState){this.controlState=0,this._controlCauseId=null,this._logger.warn("No response to control request - canceling"),this._sendRequest({action:2,terminatedReason:2,causeId:g},f)||this._logger.error("Failed to send the cancel control request");const S={inControl:!1,id:xs,terminatedReason:2};this._recordViewerSessionTelemetry((v=>v.requestControlRejected(g,S.terminatedReason,f))),this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:S,details:"we did not get any response to the control - terminating control"}))):this._logger.error("Unexpected, no promise could be resolved - controlState=RequestSent")}else this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:void 0,details:"request control - times out in bad state - do nothing"}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)}`);this._requestControlTimer=null}),Ns),this._requestControlPromise.promise}_cancelRequestControlTimer(){this._requestControlTimer&&(this._requestControlPromise&&this._requestControlPromise.reject(new Error("cancelled by _cancelRequestControlTimer")),clearTimeout(this._requestControlTimer),this._requestControlTimer=null)}cancelControl(){return this._enabled?this._isDataChannelActive()?1!==this.controlState?Promise.reject(new Error(`cancelControl called in bad state=${toControlStateString(this.controlState)}`)):this._isViewing()?this._sharerParticipant?this._requestControlPromise?this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while cancelling control")):this._cancelControl():Promise.reject(new Error("Request control promise has been resolved while cancelling control")):Promise.reject(new Error("cancelControl unexpected null sharer")):Promise.reject(new Error("cancelControl when not viewing")):Promise.reject(new Error("cancelControl when data channel not active")):Promise.reject(new Error("cancelControl when feature not enabled"))}_cancelControl(){this._logger.info("_cancelControl()");const g=this._getSharerDataSourceId();if(1!==this.controlState)return Promise.reject(new Error("Cancel control - in bad state - do nothing"));if(this._cancelRequestControlTimer(),this.controlState=0,this._logger.info("Viewer cancels the control"),!this._sendRequest({action:2,terminatedReason:8,causeId:this._controlCauseId},g))return Promise.reject(new Error("Failed to send cancel control request"));{const f={inControl:!1,id:xs,terminatedReason:8};this._recordViewerSessionTelemetry((S=>S.requestControlRejected(this._controlCauseId,f.terminatedReason,g))),this._controlCauseId=null,this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:f,details:""})))}return new Promise(((g,f)=>{g()}))}acceptControlRequest(){return this._enabled?this._isDataChannelActive()?this._controlRequest?this._isSharing()?this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while accepting control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while accepting control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while accepting control")):this._acceptControlRequest():Promise.reject(new Error("acceptControlRequest when not sharing")):Promise.reject(new Error("acceptControlRequest while no control request pending")):Promise.reject(new Error("acceptControlRequest when data channel not active")):Promise.reject(new Error("acceptControlRequest when feature not enabled"))}async _acceptControlRequest(){this._logger.info("_acceptControlRequest()"),this._acceptControlPromise=new dt;const always=()=>{this._acceptControlPromise=null};if(this._acceptControlPromise.promise.then(always,always),this._controllerParticipant){this._logger.warn("_acceptControlRequest called while another participant already has control - terminating control");try{await this._terminateControl(!1)}catch(g){this._logger.error("_acceptControlRequest: failed to gracefully terminate control of previous controller",g)}this._resetControllerParticipant()}const g=this._getDataSourceIdForParticipantLeg(this._controlRequest),f=this._controlRequest.participant.id,S=this._controlRequest.causeId,v=this._controlRequest.participant;return this._sendControlAcceptRequest(S,v,g)?(this._resetControllerParticipant(this._controlRequest),this._clearControlRequest(),this.controlState=2,this._acceptControlTimer=window.setTimeout((()=>{if(2===this.controlState){this.controlState=0,this._resetControllerParticipant(),this._logger.error("No ack received when accepting control request - terminating control"),this._sendRequest({action:7,terminatedReason:4,causeId:S},g)||this._logger.error("Failed to send the TerminateNoAck request");const C={inControl:!1,id:f,terminatedReason:4};this._recordSharerSessionTelemetry((f=>f.controlRequestRejected(S,C.terminatedReason,v,g))),this.event("sharingControlChanged").raise(C),this._acceptControlPromise?this._acceptControlPromise.reject(new Error("No ack received when accept control - terminating control")):this._logger.error("Unexpected, no promise could be resolved - controlState=WaitingForControlAck")}else this._acceptControlPromise?this._acceptControlPromise.reject(new Error("accept control - times out in bad state - do nothing")):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)}`);this._acceptControlTimer=null}),ks),this._acceptControlPromise.promise):(this._logger.error("Failed to send the accept control request"),this._acceptControlPromise.reject(new Error),Promise.reject(new Error("Failed to send the accept control request!")))}_sendControlAcceptRequest(g,f,S){const v=this._sendRequest({action:3,terminatedReason:0,causeId:g},S);return this._recordSharerSessionTelemetry((v=>v.controlRequestAccept(g,f,S))),v}_sendControlRejectRequest(g,f,S,v){const C=this._sendRequest({action:4,terminatedReason:f},v);return this._recordSharerSessionTelemetry((C=>C.controlRequestRejected(g,f,S,v))),C}_cancelAcceptControlTimer(){this._acceptControlTimer&&(this._acceptControlPromise&&this._acceptControlPromise.reject(new Error("cancelled by _cancelAcceptControlTimer")),clearTimeout(this._acceptControlTimer),this._acceptControlTimer=null)}denyControlRequest(){return this._enabled?this._isDataChannelActive()?this._controlRequest?this._isSharing()?this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while denying control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while denying control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while denying control")):this._denyControlRequest():Promise.reject(new Error("denyControlRequest when not sharing")):Promise.reject(new Error("denyControlRequest while no control request pending")):Promise.reject(new Error("denyControlRequest when data channel not active")):Promise.reject(new Error("denyControlRequest when feature not enabled"))}_denyControlRequest(){this._logger.info("_denyControlRequest()");const g=this._getDataSourceIdForParticipantLeg(this._controlRequest),f=this._sendControlRejectRequest(this._controlRequest.causeId,1,this._controlRequest.participant,g);return this._clearControlRequest(),f?Promise.resolve():Promise.reject(new Error("Failed to send the deny control requst"))}grantControl(g){return this._enabled?this._isDataChannelActive()?this._controlRequest?Promise.reject(new Error("grantControl called while control request pending")):this._isSharing()?g?this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while granting control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while granting control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while granting control")):this._grantControl(g):Promise.reject(new Error("grantControl null participant")):Promise.reject(new Error("grantControl when not sharing")):Promise.reject(new Error("grantControl when data channel not active")):Promise.reject(new Error("grantControl when feature not enabled"))}_grantControl(g){this._logger.info("_grantControl()"),this._grantControlPromise=new dt;const always=()=>{this._grantControlPromise=null};if(this._grantControlPromise.promise.then(always,always),3===this.controlState){if(this._controllerParticipant.participant?.id===g.id)return this._logger.warn("_grantControl called for participant who already has control"),this._grantControlPromise.resolve(),new Promise(((g,f)=>{g()}));{this._logger.warn("_grantControl called while another participant already has control - terminating control"),this._teardownSharerRemoteControl();const g=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);this._sendRequest({action:7,terminatedReason:5},g)||this._logger.error("Failed to send the terminateNoAck request")}}const f=this._mapParticipantToSourceId(g),S=generateCauseId(),v=this._sendRequest({action:6,terminatedReason:0,causeId:S},f);if(this._recordSharerSessionTelemetry((v=>v.giveControl(S,g,f))),!v)return this._logger.error("Failed to send the grant control request"),this._grantControlPromise.reject(new Error),Promise.reject(new Error("Failed to send the grant control request!"));const C=this._getParticipantIdForDataSourceId(g,f);return this._resetControllerParticipant({participant:g,participantState:g.state,participantId:C,causeId:S}),this.controlState=2,this._grantControlTimer=window.setTimeout((()=>{2===this.controlState?(this.controlState=0,this._resetControllerParticipant(),this._logger.error("No ack received when granting control - terminating control"),this._sendRequest({action:7,terminatedReason:4},f)||this._logger.error("Failed to send the terminateNoAck request"),this._recordSharerSessionTelemetry((v=>v.giveControlFailed(S,4,g,f))),this._grantControlPromise?this._grantControlPromise.reject(new Error("No ack received when granting control - terminating control")):this._logger.error("Unexpected, no promise could be resolved - controlState=WaitingForControlAck")):this._grantControlPromise?this._grantControlPromise.reject(new Error("Grant control - times out in bad state - do nothing")):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)}`),this._grantControlTimer=null}),ks),this._grantControlPromise.promise}_cancelGrantControlTimer(){this._grantControlTimer&&(this._grantControlPromise&&this._grantControlPromise.reject(new Error("cancelled by _cancelGrantControlTimer")),clearTimeout(this._grantControlTimer),this._grantControlTimer=null)}_mapParticipantToSourceId(g){return this._dataChannelAdapter.isActive()?getSourceIdForMediaType(g,3):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getParticipantsDataSourceIds(g){const f=[];try{if(g?.endpoints?.endpointDetails){if(1===g.endpoints.endpointDetails.length){const S=g.endpoints.endpointDetails[0];if(!S?.mediaStreams)return f.push(Ai),f}for(const S of g.endpoints.endpointDetails)if(S?.mediaStreams)for(const g of S.mediaStreams)if(3===mapMediaTypeStringToMediaType(g.type)){if(f.push(g.sourceId),f.length>=8)return this._logger.error("Excessive amount of data streams"),f;break}}}catch(g){this._logger.error(`_getParticipantsDataSourceIds caught exception error=${g}`)}return f}_getParticipantIdForDataSourceId(g,f){return getParticipantIdForSourceId(g,3,f)}_getDataSourceIdForParticipantId(g,f){return this._dataChannelAdapter.isActive()?getSourceId(g,f,3):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getDataSourceIdForParticipantLeg(g){return this._getDataSourceIdForParticipantId(g.participant,g.participantId)}_getSharerDataSourceId(){const g=getSharingParticipantLeg(this._sharerParticipant);return g?this._getDataSourceIdForParticipantId(this._sharerParticipant,g):(this._logger.warn("Unable to identify the sharer participantId, falling back to first data channel"),this._mapParticipantToSourceId(this._sharerParticipant))}getLocalEndpointDataSourceId(){const g=findSelfEndpointDetailUsingParticipantLegId(this._call,this._participantId);if(g?.mediaStreams){const f=g.mediaStreams.find((({type:g})=>3===mapMediaTypeStringToMediaType(g)));return f?.sourceId??-1}return-1}terminateControl(g){if(this._isViewing()){if(4!==this.controlState)return Promise.reject(new Error("terminateControl called while not in control"));if(!this._sharerParticipant)return Promise.reject(new Error("terminateControl called but _sharerParticipant is null"))}else{if(!this._isSharing())return Promise.reject(new Error("terminateControl called but not sharing nor viewing"));if(!this._controllerParticipant)return Promise.reject(new Error("terminateControl called but controllerParticipant is null"))}return this._requestControlPromise?Promise.reject(new Error("Request control promise has not been resolved yet while terminating control")):this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while terminating control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while terminating control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while terminating control")):this._terminateControl(!0,g)}_terminateControl(g,f){this._logger.info("_terminateControl()"),this._terminateControlPromise=new dt;const always=()=>{this._terminateControlPromise=null};this._terminateControlPromise.promise.then(always,always);let S=0;const v=g?8:7;let C,_;if(this._isViewing()){if(4!==this.controlState)return this._logger.error("Local viewer called terminateControl when not controlling"),this._terminateControlPromise.reject(new Error),Promise.reject(new Error("Local viewer called terminateControl when not controlling"));this._teardownViewerRemoteControl(),S=f??6,C=this._getSharerDataSourceId(),this._recordViewerSessionTelemetry((g=>g.controlTerminated(this._controlCauseId,S,C))),_=xs,this._logger.info(`Terminating remote control reason: ${toControlTerminatedReason(S)},  recipient: ${C}, controllerId: ${_}`)}else{if(3!==this.controlState||!this._controllerParticipant)return this._logger.error("Local sharer called terminateControl when no one is in control"),this._terminateControlPromise.reject(new Error),Promise.reject(new Error("Local sharer called terminateControl when no one is in control"));this._teardownSharerRemoteControl(),S=f??5,C=this._getDataSourceIdForParticipantLeg(this._controllerParticipant),this._recordSharerSessionTelemetry((g=>g.controlTerminated(this._controlCauseId,S,this._controllerParticipant.participant,C))),_=scrubMriOrOmit(this._controllerParticipant.participant.id),this._logger.info(`Terminating control on the sharer side, reason: ${toControlTerminatedReason(S)}, recipient: ${C}, controllerId: ${_}`)}const T={action:v,terminatedReason:S};if(!this._sendRequest(T,C)){if(g)return this._logger.error("Failed to send the terminate control request"),this._terminateControlPromise.reject(new Error),Promise.reject(new Error("Failed to send the grant control request!"));this._logger.error("Failed to send the terminateNoAck request")}this.controlState=g?5:0;const I={inControl:!1,id:_,terminatedReason:T.terminatedReason};return this._logger.info(`raising event sharingControlChanged reason=${toControlTerminatedReason(I.terminatedReason)} controlState=${toControlStateString(this.controlState)}`),this.event("sharingControlChanged").raise(I),g?(this._terminateControlTimer=window.setTimeout((()=>{5===this.controlState?(this.controlState=0,this._resetControllerParticipant(),this._logger.error("No ack received when terminating control - resending terminate request"),this._sendRequest({action:7,terminatedReason:4},C)||this._logger.error("Failed to send the terminateNoAck request"),this._terminateControlPromise?this._terminateControlPromise.reject(new Error("No ack received when terminating control - resending terminate request")):this._logger.error("Unexpected, no promise could be resolved - controlState=WaitingForTerminateAck")):this._terminateControlPromise?this._terminateControlPromise.reject(new Error("terminate control - times out in bad state - do nothing")):this._logger.error(`Unexpected, no promise could be resolved - controlState=${toControlStateString(this.controlState)}`),this._terminateControlTimer=null}),ks),this._terminateControlPromise.promise):(this._terminateControlPromise.resolve(),new Promise(((g,f)=>{g()})))}_cancelTerminateControlTimer(){this._terminateControlTimer&&(this._terminateControlPromise&&this._terminateControlPromise.reject(new Error("cancelled by _cancelTerminateControlTimer")),clearTimeout(this._terminateControlTimer),this._terminateControlTimer=null,this._logger.info("_cancelTerminateControlTimer()"))}_disposeControlCapturer(g=generateCauseId()){this._logger.info(`_disposeControlCapturer causeId: ${g}`),this._clearCapturerEventSubscriptions(),this._controlCapturer&&(this._controlCapturer.dispose(g),this._controlCapturer=null)}dispose(g){this._logger.info(`dispose causeId: ${g}`),this._dataChannelAdapter.dispose(g),this._resetControlState(),this._disposeRenderer(g),this._cancelRequestControlTimer(),this._cancelAcceptControlTimer(),this._cancelGrantControlTimer(),this._cancelTerminateControlTimer(),this._terminateAvailableHandshake&&this._terminateAvailableHandshake(2),this._call=null,this._resetParticipantSubscriptions(),this._finalizeViewerSessionTelemetry(),this._finalizeSharerSessionTelemetry(),super.dispose(g)}};function toAvailableHandshakeTerminatedString(g){switch(g){case 1:return"Succeeded";case 2:return"Shutdown";case 3:return"DataChannel";case 4:return"Replaced";case 5:return"TimedOut";case 6:return"UnknownSender";case 7:return"SharerDenied";default:return"Unknown"}}function toControlActionString(g){switch(g){case 0:return"Available";case 1:return"ControlRequest";case 2:return"CancelControlRequest";case 3:return"AcceptRequest";case 4:return"RejectRequest";case 5:return"Ack";case 6:return"GiveControl";case 7:return"TerminateNoAck";case 8:return"Terminate";case 9:return"AvailableAck";case 10:return"AvailableNack";case 11:return"RenderedAtViewer";default:return"Unknown"}}function toControlStateString(g){switch(g){case 0:return"None";case 1:return"RequestSent";case 2:return"WaitingForControlAck";case 3:return"RemoteControlling";case 4:return"LocalControlling";case 5:return"WaitingForTerminateAck";default:return"Unknown"}}function toControlTerminatedReason(g){switch(g){case 0:return"None";case 1:return"SharerDenied";case 2:return"SharerNoResponse";case 3:return"SharerBusy";case 4:return"AckTimeout";case 5:return"SharerTerminated";case 6:return"ViewerTerminated";case 7:return"DataChannelError";case 8:return"ViewerCancelled";case 9:return"SharerControlDisabled";case 10:return"UnknownSender";case 11:return"MultipleSharers";default:return"Unknown"}}function toSharingControlRole(g){switch(g){case 1:return"Sharer";case 2:return"Viewer";default:return"Unknown"}}var $s=(g=>(g[g.LEFT=0]="LEFT",g[g.RIGHT=1]="RIGHT",g[g.MIDDLE=2]="MIDDLE",g[g.BACK=3]="BACK",g[g.FORWARD=4]="FORWARD",g))($s||{}),js=(g=>(g[g.SCAN_CODE=0]="SCAN_CODE",g[g.VIRTUAL_KEY=1]="VIRTUAL_KEY",g[g.RECOGNITION_INPUT=2]="RECOGNITION_INPUT",g))(js||{}),Gs=class{constructor(g){this.logger=g}toEdgeControlMouseEvent(g){let f;switch(g.type){case 0:return{event:this.toMouseMoveEvent(g),apiName:"injectMouseMoveEvent"};case 1:return{event:this.toMouseWheelEvent(g),apiName:"injectMouseWheelEvent"};case 2:return{event:this.toMouseButtonPressedEvent(g),apiName:"injectMouseButtonEvent"};default:throw f=`Uncovered mouse control event type. Event: ${g}`,this.logger.error(f),Error(f)}}toEdgeControlKeyboardEvent(g){return{event:{repeat:g.repeat,keyUp:g.keyUp,codeType:js[g.codeType],keyCode:g.code},apiName:"injectKeyEvent"}}toMouseMoveEvent(g){return{xPos:g.xPos,yPos:g.yPos}}toMouseWheelEvent(g){return{wheelButtonDown:g.wheelButtonDown,wheelRotation:g.wheelRotation}}toMouseButtonPressedEvent(g){return{xPos:g.xPos,yPos:g.yPos,button:$s[g.buttonType],buttonDown:g.buttonDown}}};async function pngBase64ToBitmap(g,f,S){return new Promise(((v,C)=>{const _=Buffer.from(g,"base64"),T=document.createElement("canvas").getContext("2d"),I=new Blob([_],{type:"image/png"});let b=new Image;b.onload=()=>{T.drawImage(b,0,0,b.width,b.height,0,0,f,S);const g=T.getImageData(0,0,f,S);window.URL.revokeObjectURL(b.src),b=null,v(Array.from(g.data))},b.onerror=g=>{C(g)},b.src=window.URL.createObjectURL(I)}))}var qs="ncbjelpjchkpbikbpkcchkhkblodoama",Ws=class{constructor(g){this.logger=g}async sendInjectInputEventMessage(g,f){return this.logger.info("EdgeControlInjectorApi - sendInjectInputEventMessage"),new Promise(((S,v)=>{window.top.chrome.runtime.sendMessage(qs,{api:g,deviceId:this.virtualInputDeviceId,event:f},(g=>{g.error?v(g.error.message):S(0)}))}))}async createInputDeviceId(g,f,S){this.virtualInputDeviceId&&this.logger.warn("EdgeControlInjectorApi - createInputDeviceId virtual input already exists.");try{this.virtualInputDeviceId=await this.sendCreateInputDeviceMessage(g,S)}catch(g){this.logger.error(`EdgeControlInjectorApi - createInputDevice failed, error: ${JSON.stringify(g)}`),f()}}async sendSetLocalUserAvatarMessage(g){const f=await this.generateAvatarBitmap(g);return new Promise(((g,S)=>{const v=window.top;f&&v.chrome.runtime.sendMessage(qs,{api:"setLocalUserAvatar",avatarBitmap:f},(f=>{f.error?S(f.error.message):g()}))}))}async sendCloseVirtualInputDeviceMessage(){const g=this.virtualInputDeviceId;return g?(this.logger.info("EdgeControlInjectorApi - sendCloseVirtualInputDeviceMessage called"),new Promise(((f,S)=>{const v=window.top;v.chrome.runtime.sendMessage(qs,{api:"closeInputDevice",deviceId:g},(g=>{g?g.error?S(g.error.message):(this.virtualInputDeviceId=null,f(g.deviceId)):S(v.chrome.runtime.lastError.message)}))}))):(this.logger.info("EdgeControlInjectorApi - VirtualInputDevice does not exists, nothing to close."),Promise.resolve())}async sendCreateInputDeviceMessage(g,f){this.logger.info("EdgeControlInjectorApi - sendCreateInputDeviceMessage called");const S=await this.generateAvatarBitmap(f);return new Promise(((f,v)=>{const C=window.top,messageCallback=g=>{g?g.deviceId?f(g.deviceId):g.error?v(g.error.message):v("Error: Unexpected response from API"):v(C.chrome.runtime.lastError.message)};S?C.chrome.runtime.sendMessage(qs,{api:"createInputDevice",mediaStreamTrackId:g,avatarBitmap:S},messageCallback):C.chrome.runtime.sendMessage(qs,{api:"createInputDevice",mediaStreamTrackId:g},messageCallback)}))}async generateAvatarBitmap(g){if(!g)return null;try{const f=32;return{width:f,height:f,data:await pngBase64ToBitmap(g,f,f)}}catch(g){return this.logger.error(`EdgeControlInjectorApi - generateAvatarBitmap error: ${JSON.stringify(g)}, continue without avatar.`),null}}};async function sendIsVirtualInputSupportedMessage(g){return new Promise(((f,S)=>{g.info("EdgeControlInjectorApi - sendIsVirtualInputSupportedMessage");const v=window.top;v.chrome.runtime.sendMessage(qs,{api:"isVirtualInputSupported"},(g=>{g?g.error?f(g.error.message):f(g):S(v.chrome.runtime.lastError?.message)}))}))}var zs,Ks,Js=class{constructor(g,f,S){this.logger=g,this.sharingTrackId=f,this.onInitErrorCallback=S,this.images=new Map,this.controlEventConverter=new Gs(g),this.edgeApi=new Ws(this.logger)}showVirtualCursor(g,f){if(this.logger.info(`EdgeControlInjector - showVirtualCursor, id: ${g} sharingTrackId: ${this.sharingTrackId}`),f){this.edgeApi.createInputDeviceId(this.sharingTrackId,this.onInitErrorCallback,this.images[g]);const f=this.images[0];f?this.edgeApi.sendSetLocalUserAvatarMessage(f):this.logger.error("EdgeControllerInjector - local avatar is missing, continue without local avatar")}else this.edgeApi.sendCloseVirtualInputDeviceMessage()}setAvatar(g,f){this.logger.info(`${g} EdgeControlInjector - setAvatar, id: ${g}, data: ${JSON.stringify(f)}`),this.images[g]=f}async injectMouseEvent(g,f){this.logger.info(`${g} EdgeControlInjector - injectMouseEvent ${JSON.stringify(f)}`);const S=this.controlEventConverter.toEdgeControlMouseEvent(f);return this.edgeApi.sendInjectInputEventMessage(S.apiName,S.event)}async injectKeyboardEvent(g,f){const S=this.controlEventConverter.toEdgeControlKeyboardEvent(f);return this.edgeApi.sendInjectInputEventMessage(S.apiName,S.event)}injectClipboardText(g,f){return this.logger.info(`${g} EdgeControlInjector - injectClipboardText is unimplemented`),Promise.resolve(0)}dispose(g){this.logger.info("EdgeControlInjector - dispose"),this.edgeApi.sendCloseVirtualInputDeviceMessage()}},Ys="undefined"!=typeof navigator&&void 0!==navigator.mediaDevices?.getUserMedia,Qs=(g=>(g.AVD="43",g.Citrix="44",g.VMware="45",g))(Qs||{});function setAgentPlatformInfo(g=""){const f=g.match(new RegExp("^SkypeSpaces/(\\d+)/"));f?.length&&Object.values(Qs).includes(f[1])&&(Ks=f[1]),overrideGetUserMediaIfNeeded()}function isVdiPlatform(){return!!Ks}function getVdiPlatform(){return Ks}function overrideGetUserMediaIfNeeded(){"undefined"!=typeof window&&"undefined"!=typeof navigator&&(void 0!==navigator.webkitGetUserMedia&&"undefined"!=typeof webkitRTCPeerConnection&&isVdiPlatform()?(window.RTCPeerConnection=webkitRTCPeerConnection,navigator.getUserMedia=(g,f,S)=>{const polyfillDeviceId=g=>{g?.deviceId?.exact&&(g.mandatory||(g.mandatory={}),g.mandatory.sourceId=g.deviceId.exact,delete g.deviceId)};return g&&(polyfillDeviceId(g.audio),polyfillDeviceId(g.video)),navigator.webkitGetUserMedia(g,f,S)}):Ys&&overrideGumSourceFromWebkit())}function overrideGumSourceFromWebkit(){navigator.getUserMedia=function(g,f,S){return navigator.mediaDevices.getUserMedia(g).then(f).catch(S)}}"undefined"!=typeof window&&"undefined"!=typeof navigator&&(zs=window,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,window.MediaStream=window.MediaStream||window.webkitMediaStream||window.mozMediaStream||window.msMediaStream,window.AudioContext=window.AudioContext||window.webkitAudioContext);var Xs={window:zs},Zs=class{constructor(g){this.logger=g,this.activeSourceId=0,this.pendingPointerImages=new Map}static create(g,f){return g.config.enableGiveControl?isVdiPlatform()||window.ControlInjector?new ta(f):et.isBrowser("EdgeAnaheim")?new ea(f):new ia(f):new ia(f)}async enableInjector(g){this.injector&&this.logger.warn("Control injector already present when enabling injector");try{this.injector=this.createInjector(g)}catch(g){throw this.logger.error(`Control injector creation failed: ${g}`),g}this.pendingPointerImages.forEach(((g,f)=>{this.injector.setAvatar(f,g)})),this.pendingPointerImages.clear()}async disableInjector(){this.injector||this.logger.warn("Control injector not present when disabling injector"),this.logger.info("ControlInjector disposed"),this.injector.dispose(),this.injector=null}async setPointerImage(g,f){this.injector?this.injector.setAvatar(g,f):this.pendingPointerImages.set(g,f)}async showVirtualCursor(g){if(this.logger.info(`showVirtualCursor ${g} ${this.activeSourceId}`),!this.injector)throw new Error("Control injector not present");g?(this.activeSourceId&&this.injector.showVirtualCursor(this.activeSourceId,!1),this.injector.showVirtualCursor(g,!0),this.activeSourceId=g):this.activeSourceId&&(this.injector.showVirtualCursor(this.activeSourceId,!1),this.activeSourceId=0)}async injectRawInput(g,f){if(!this.injector)throw new Error("Control injector not present");const S=this.injector;return new Promise(((v,C)=>{let _,T;const I=gs.decodeEventType(g);switch(I){case 1:_=gs.decodeMouseEvent(g),S.injectMouseEvent(f,_).then((g=>0===g?v():C()));break;case 0:T=gs.decodeKeyboardEvent(g),S.injectKeyboardEvent(f,T).then((g=>0===g?v():C()));break;default:this.logger.error(`Invalid event type in raw input: ${I}`),C()}}))}},ea=class extends Zs{constructor(g){super(g.createChild("EdgeControlInjector")),this.edgeVirtualInputSupported=!1,sendIsVirtualInputSupportedMessage(g).then((f=>{this.edgeVirtualInputSupported=f,g.info(`Edge supports virtual input device: ${JSON.stringify(this.edgeVirtualInputSupported)}`)})).catch((f=>{g.info(`Edge IsVirtualInputSupported: ${JSON.stringify(f)}`)}))}canBeEnabled(){return this.edgeVirtualInputSupported}createInjector(g){if(!this.edgeVirtualInputSupported)return void this.logger.info("Edge doesn't support give control");const f=new Js(this.logger,g,(()=>{this.logger.error("An error occured, disabling control injector."),this.disableInjector()}));return this.logger.info("Edge ControlInjector created"),f}},ta=class extends Zs{constructor(g){super(g.createChild("WindowControlInjector"))}canBeEnabled(){return!!window.ControlInjector}createInjector(g){const f=window.ControlInjector(g);return this.logger.info("Window ControlInjector created"),f}},ia=class extends Zs{constructor(g){super(g.createChild("NoopControlInjector"))}canBeEnabled(){return!1}createInjector(){throw new Error("Control injector creation is disabled")}},na=class{constructor(g){this.logger=g,this.logger.info("RendererAdapter")}getTarget(g){return g.target}subscribeVideoSizeChangedEvent(g,f){const S=g;return S.streamSize&&f(S.streamSize.width,S.streamSize.height),S.renderer.on("onVideoSizeChanged",f)}subscribeRenderStartedEvent(g,f){return g.renderer.on("onVideoStarted",((g,S)=>f()))}};function bufferToString(g){return String.fromCharCode.apply(null,g)}var ra=class extends Ke{constructor(g,f){super(g),this.logger=g,this._call=f}isActive(){return!(!this.protocolSendFunc||!this.controlSendFunc)}sendProtocolMessage(g,f){return this.protocolSendFunc?this.protocolSendFunc(g,f):(this.logger.error("Cannot send protocol message, ProtocolHandler hasn't started"),Promise.resolve())}sendControlMessage(g,f){return this.controlSendFunc?this.controlSendFunc(g,f):(this.logger.error("Cannot send control message, ControlHandler hasn't started"),Promise.resolve())}getProtocolHandler(){return{onStarted:async(g,f)=>{this.logger.info(`ProtocolHandler started for ${g}`),this.protocolSendFunc=f,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async g=>{this.logger.info(`ProtocolHandler stopped for ${g}`);const f=this.isActive();this.protocolSendFunc=null,f&&this.event("stateChange").raise(!1)},onDataReceived:async(g,f,S)=>{if(1===g){const g=JSON.parse(bufferToString(f)),v=this._call.mapDataChannelSourceIdToParticipant(S);let C;return v&&(C=getParticipantIdForSourceId(v,3,S)),this.event("protocolMessage").raise(g.message,v,C,S)}}}}getControlHandler(){return{onStarted:async(g,f)=>{this.logger.info(`ControlHandler started for ${g}`),this.controlSendFunc=f,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async g=>{this.logger.info(`ControlHandler stopped for ${g}`);const f=this.isActive();this.controlSendFunc=null,f&&this.event("stateChange").raise(!1)},onDataReceived:async(g,f,S)=>{if(2===g)return this.event("controlMessage").raise(f,S)}}}},sa=class extends Hs{constructor(g,f,S,v,C,_){const T={disableAudit:C.getEcsConfig("SkypeCalling","gtcAuditDisabled")??!1},I=C.getEcsConfig("SkypeCalling","gtcHandshakeSendDelay");if(I)try{T.handshakeSendDelay=JSON.parse(I)}catch(f){g.error(`Failed to parse ecs config gtcAvailableAckDelay: ${stringifyObject2(f)}`)}super(g.createChild("ScreenSharingControl"),S,v,T),this.dataChannel=f;const b=Zs.create(_,g),A=new na(this._logger),P=new ra(this._logger,S);this.setAdapters(b,A,P)}setupDataHandlers(){this.dataChannel.addHandler(1,this.getProtocolHandler()),this.dataChannel.addHandler(2,this.getControlHandler())}startOrStopControlForViewer(g,f,S){if(g&&"nonInteractive"!==S?.appliedInteractivityLevel){if(f&&0===this.role){const g=f.streams[1].find((g=>g.isAvailable))?.negotiationTag;this.initControlForViewer(f,g)}}else 2===this.role&&this.shutdownControlForViewer()}getProtocolHandler(){return this._dataChannelAdapter.getProtocolHandler()}getControlHandler(){return this._dataChannelAdapter.getControlHandler()}};function createParticipantListFromMriMap(g){const f=[];for(const S in g)if(g[S].participantLegIdMap)for(const v in g[S].participantLegIdMap){const C=g[S].participantLegIdMap[v].endpointId;f.push({id:S,mri:S,participantId:v,...C&&{endpointId:C}})}else f.push({id:S,mri:S});return f}function mapParticipantScope(g){switch(g){case 1:return"specified";case 0:return"all";case 3:return"attendees";case 2:return"presenters";case 4:return"self";default:return"none"}}var aa={};__export2(aa,{addReceiveDirectionality:()=>addReceiveDirectionality,allowDataChannel:()=>allowDataChannel,areNegotiatedDirectionsAcceptable:()=>areNegotiatedDirectionsAcceptable,areNegotiatedDirectionsFulfilled:()=>areNegotiatedDirectionsFulfilled,areSendDirectionsFulfilled:()=>areSendDirectionsFulfilled,canUseWebrtc1_0:()=>canUseWebrtc1_0,convertToCodecInfo:()=>convertToCodecInfo,getAllowedCodecs:()=>getAllowedCodecs,getSrtpInfo:()=>getSrtpInfo,hasReceiveDirectionality:()=>hasReceiveDirectionality,hasSendDirectionality:()=>hasSendDirectionality,invertModalities:()=>invertModalities,ipAddressConverter:()=>ipAddressConverter,ipV4RegExp:()=>la,ipV6RegExp:()=>ca,ipv4AddressConverter:()=>ipv4AddressConverter,ipv6AddressConverter:()=>ipv6AddressConverter,isOnHold:()=>isOnHold,mediaTypeToModality:()=>mediaTypeToModality,modalityToMediaType:()=>modalityToMediaType,negotiateDirectionality:()=>negotiateDirectionality,negotiateModalities:()=>negotiateModalities,parseCandidateString:()=>parseCandidateString,preferSdesSrtp:()=>preferSdesSrtp,printMediaStream:()=>printMediaStream,removeChangedSendDirection:()=>removeChangedSendDirection,removeSendDirectionality:()=>removeSendDirectionality,scrubConstraints:()=>scrubConstraints,scrubDevices:()=>scrubDevices,scrubObjectExcludingFields:()=>scrubObjectExcludingFields,scrubObjectFields:()=>scrubObjectFields2,scrubSelectedDevices:()=>scrubSelectedDevices,sendStreamsToModalities:()=>sendStreamsToModalities,shouldDisableAudioSendersTroughSetParams:()=>shouldDisableAudioSendersTroughSetParams,shouldDisableVideoSendersTroughSetParams:()=>shouldDisableVideoSendersTroughSetParams});var oa=class _UserAgentConfig extends Ht{constructor(g){super(),this.isAudioOutputSelectionSupportedValue=!1,g.on("configUpdated",(()=>this.updateConfig())),this.updateConfig(),this.isRollbackSupported()}get isAudioOutputSelectionSupported(){return this.isAudioOutputSelectionSupportedValue}get isBrowserRollbackSupported(){return this.isRollbackSupportedValue}static hasApplyConstraints(){return void 0!==MediaStreamTrack.prototype.applyConstraints}static hasPermissionsApi(){return void 0!==navigator.permissions}static get hardwareConcurrency(){return window.navigator.hardwareConcurrency}static get unmaskedGlRenderer(){if(this.renderer)return this.renderer===qt.MEDIA_ERROR.webGlRendererError?void 0:this.renderer;try{const g=document.createElement("canvas").getContext("webgl"),f=g?.getExtension("WEBGL_debug_renderer_info"),S=f&&g.getParameter(f.UNMASKED_RENDERER_WEBGL);return this.renderer=S,S}catch{return void(this.renderer=qt.MEDIA_ERROR.webGlRendererError)}}async isRollbackSupported(){let g;try{if(g=Xs.window.RTCPeerConnection&&new Xs.window.RTCPeerConnection({sdpSemantics:"unified-plan"}),g){const f=await g.createOffer();await g.setLocalDescription(f),await g.setLocalDescription({type:"rollback"}),this.isRollbackSupportedValue=!0}}catch(g){this.isRollbackSupportedValue=!1}finally{g?.close()}}static async isCodecsSupported(g){const f={format:"annexb"},S=1280,v=720,C=["no-preference","prefer-software","prefer-hardware"],_=[];for(const T of g)for(const g of C){const C=await(window.VideoEncoder?.isConfigSupported({codec:T,hardwareAcceleration:g,hevc:f,width:S,height:v})),I=await(window.VideoDecoder?.isConfigSupported({codec:T,hardwareAcceleration:g,hevc:f}));if(C||I){const g={name:T,mode:C?.config.hardwareAcceleration,encode:C?.supported,decode:I?.supported};_.push(g)}}return _}static async hasH264CodecSupport(g){const f="v=0\no=- 596983 0 IN IP4 127.0.0.1\ns=session\nc=IN IP4 0.0.0.0\nt=0 0\na=msid-semantic: WMS *\nm=video 3480 RTP/SAVPF 107 99\na=rtpmap:107 H264/90000\na=rtpmap:99 rtx/90000\na=fmtp:107 max-fs=240;max-mbps=3600;max-br=208;max-fps=1500;profile-level-id=42C02A;packetization-mode=1\na=fmtp:99 apt=107\na=setup:actpass\na=mid:video\na=recvonly\na=rtcp-mux\na=ice-ufrag:CvYq\na=ice-pwd:axsjsa0GOz3kz6TuGvNgJZWO\na=fingerprint:sha-256 34:DF:5C:15:60:FF:28:3E:E8:96:4B:F8:85:61:E4:C0:57:D1:60:82:21:FD:BC:D2:90:41:06:FA:03:FD:12:A2\n",S=Xs.window.RTCPeerConnection&&new Xs.window.RTCPeerConnection;if(!S)return!1;try{return await S.setRemoteDescription({sdp:f,type:"offer"}),!0}catch(f){return g.error("H264 not supported",f),!1}finally{try{S.close()}catch(g){}}}static hasMediaApi(){return navigator.getUserMedia&&"undefined"!=typeof RTCPeerConnection}static hasCapabilitiesApi(){return!!Xs.window.RTCRtpReceiver?.getCapabilities}static isAudioOutputSelectionSupportedByBrowser(){return!!Xs.window?.HTMLAudioElement?.prototype.setSinkId}updateConfig(){const g=_UserAgentConfig.isAudioOutputSelectionSupportedByBrowser();g!==this.isAudioOutputSelectionSupportedValue&&(this.isAudioOutputSelectionSupportedValue=g,this.event("isAudioOutputSelectionSupportedChanged").raise())}static hasUnifiedPlanSupport(){let g;try{g=Xs.window.RTCPeerConnection&&new Xs.window.RTCPeerConnection({sdpSemantics:"unified-plan"})}catch(g){return!1}let f=!1;return g&&(f=!!g.addTransceiver,g.close()),f}static hasEncodedStreamsApi(){return!!RTCRtpReceiver.prototype.createEncodedStreams||_UserAgentConfig.hasScriptTransformApi()}static hasScriptTransformApi(){return!!window.RTCRtpScriptTransform}static isWakeLockSupported(){return!!window.navigator.wakeLock}},la=RegExp(/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/),ca=RegExp(/^\[?(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|:((:[0-9a-fA-F]{1,4}){1,5}|:)((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,5}([0-9a-fA-F]{1,4})?:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\]?(?::\d{1,5})?$/);function invertDirectionality(g){switch(g){case qt.MEDIA_STATE.send:return qt.MEDIA_STATE.receive;case qt.MEDIA_STATE.receive:return qt.MEDIA_STATE.send;default:return g}}function negotiateDirectionality(g,f){const S=hasSendDirectionality(g)&&hasSendDirectionality(f),v=hasReceiveDirectionality(g)&&hasReceiveDirectionality(f);return S&&v?qt.MEDIA_STATE.sendReceive:S?qt.MEDIA_STATE.send:v?qt.MEDIA_STATE.receive:g===qt.MEDIA_STATE.inactive&&f||g&&f===qt.MEDIA_STATE.inactive?qt.MEDIA_STATE.inactive:void 0}function invertModalities(g){const f={},S=invertDirectionality(g.audio);S&&(f.audio=S);const v=invertDirectionality(g.video);v&&(f.video=v);const C=invertDirectionality(g.sharing);C&&(f.sharing=C);const _=invertDirectionality(g.data);return _&&(f.data=_),f}function removeSendDirectionality(g){return g===qt.MEDIA_STATE.sendReceive?qt.MEDIA_STATE.receive:void 0}function hasSendDirectionality(g){return g===qt.MEDIA_STATE.send||g===qt.MEDIA_STATE.sendReceive}function hasReceiveDirectionality(g){return g===qt.MEDIA_STATE.receive||g===qt.MEDIA_STATE.sendReceive}function addReceiveDirectionality(g){return hasReceiveDirectionality(g)?g:g===qt.MEDIA_STATE.send?qt.MEDIA_STATE.sendReceive:qt.MEDIA_STATE.receive}function isOnHold(g){return!(g.audio!==qt.MEDIA_STATE.inactive||g.video&&g.video!==qt.MEDIA_STATE.inactive||g.sharing&&g.sharing!==qt.MEDIA_STATE.inactive)}function negotiateModalities(g,f){const S={},v=negotiateDirectionality(g.audio,f.audio);v&&(S.audio=v);const C=negotiateDirectionality(g.video,f.video);C&&(S.video=C);const _=negotiateDirectionality(g.sharing,f.sharing);_&&(S.sharing=_);const T=negotiateDirectionality(g.data,f.data);return T&&(S.data=T),S}function isNegotiatedDirectionAcceptable(g,f,S){const v=hasSendDirectionality(g)&&hasSendDirectionality(f)||!hasSendDirectionality(g)&&!hasSendDirectionality(S),C=!S||hasReceiveDirectionality(g)&&hasReceiveDirectionality(f)||!hasReceiveDirectionality(g)&&!hasReceiveDirectionality(S);return v&&C}function areNegotiatedDirectionsAcceptable(g,f,S){return isNegotiatedDirectionAcceptable(g.audio,f.audio,S.audio)&&isNegotiatedDirectionAcceptable(g.video,f.video,S.video)&&isNegotiatedDirectionAcceptable(g.sharing,f.sharing,S.sharing)&&isNegotiatedDirectionAcceptable(g.data,f.data,S.data)}function areNegotiatedDirectionsFulfilled(g,f){function isNegotiatedDirectionFulfilled(g,f){const S=hasSendDirectionality(g)===hasSendDirectionality(f),v=hasReceiveDirectionality(g)===hasReceiveDirectionality(f)||hasReceiveDirectionality(g)&&!f;return S&&v}return isNegotiatedDirectionFulfilled(g.audio,f.audio)&&isNegotiatedDirectionFulfilled(g.video,f.video)&&isNegotiatedDirectionFulfilled(g.sharing,f.sharing)&&isNegotiatedDirectionFulfilled(g.data,f.data)}function areSendDirectionsFulfilled(g,f){const isSendDirectionFulfilled=(g,f)=>hasSendDirectionality(g)===hasSendDirectionality(f);return isSendDirectionFulfilled(g.audio,f.audio)&&isSendDirectionFulfilled(g.video,f.video)&&isSendDirectionFulfilled(g.sharing,f.sharing)&&isSendDirectionFulfilled(g.data,f.data)}function getSrtpInfo(g){const f={dtls:!1,sdes:!1};return f.dtls=!!g.fingerprint,g.media.forEach((g=>{f.dtls=f.dtls||!!g.fingerprint,f.sdes=f.sdes||!!g.crypto})),f}function removeChangedSendDirection(g,f){if(!f||isEmpty(f))return g;const S={};return forOwn(g,((g,v)=>{v===qt.MODALITY.data?S[v]=removeChangedDataSendDirection(g,f[v]):S[v]=removeChangedMediaSendDirection(g,f[v])})),S}function removeChangedMediaSendDirection(g,f){return hasSendDirectionality(g)&&!hasSendDirectionality(f)?removeSendDirectionality(g)||f:g}function removeChangedDataSendDirection(g,f){return hasSendDirectionality(g)&&!hasSendDirectionality(f)?f:g}function parseCandidateString(g){const f=(g||"").split(" ");return{component:f[1],protocol:f[2],priority:f[3],ip:f[4],port:f[5],type:f[7]}}function modalityToMediaType(g){switch(g){case"audio":return"Audio";case"video":return"Video";case"sharing":return"ScreenShare";default:return null}}function mediaTypeToModality(g){switch(g){case"Audio":return"audio";case"Video":return"video";case"ScreenShare":return"sharing";default:return null}}function sendStreamsToModalities(g){const f={};return keys(g).forEach((S=>f[S]=!!g[S])),f}function scrubObjectFields2(g,f,S){if(!g)return g;const v={...g};for(const[C,_]of Object.entries(g))"object"==typeof _?v[C]=scrubObjectFields2(_,f):_&&f.includes(C)&&(v[C]=S?S(_):scrubMriOrOmit(_));return v}function scrubObjectExcludingFields(g,f,S){if(!g)return g;const v={...g};for(const[C,_]of Object.entries(g))"object"==typeof _?v[C]=scrubObjectExcludingFields(_,f):_&&!f.includes(C)&&(v[C]=S?S(_):scrubMriOrOmit(_));return v}function scrubSelectedDevices(g){return g?scrubObjectExcludingFields(g,[]):g}function scrubDevices(g,f){if(!g)return g;const S=scrubObjectFields2(g,["deviceId","groupId","guid"]);return scrubObjectFields2(S,["label"],(g=>scrubDeviceLabelPii(g,f)))}function scrubConstraints(g){return scrubObjectFields2(g,["sourceId","deviceId"])}function preferSdesSrtp(g,f){return!(!g.config.webrtcForceSdesForS1||!g.config.checkSupportForWebrtc_1_0||g.mediaConfig.simulcastSessionEnabled)||(f?g.config.preferSdesSrtpPstn:g.config.preferSdesSrtp)}function canUseWebrtc1_0(g){return!g||oa.hasUnifiedPlanSupport()}function allowDataChannel(g){return!!g.configProvider.mediaConfig.simulcastSessionEnabled&&(g.config.isPstnCall?g.configProvider.config.enableDataChannelPstn:g.configProvider.config.enableDataChannel)}function getAllowedCodecs(g,f){switch(f){case qt.MEDIA_TYPE.audio:return g.config.allowedAudioCodecs;case qt.MEDIA_TYPE.video:return g.config.allowedVideoCodecs;default:return[]}}function convertToCodecInfo(g){return g.map((g=>{const f={codec:g.mimeType.split("/").pop(),rate:g.clockRate};return g.channels&&(f.encoding=g.channels),g.sdpFmtpLine&&(f.fmtpLine=g.sdpFmtpLine),f}))}function printMediaStream(g){return`${g?.id}:${JSON.stringify(g?.getTracks().map((g=>g.id)))}}`}function ipAddressConverter(g){try{if(la.test(g))return ipv4AddressConverter(g);if(ca.test(g))return ipv6AddressConverter(g)}catch(f){return g}return g}function ipv6AddressConverter(g){let f,S=g.lastIndexOf("]")+1,v="",C="";S>0?(f=g.substring(0,S),C=g.substring(S)):(f=g,S=f.length);const _=f.lastIndexOf(":");if(f.includes(".")){const g=ipv4AddressConverter(f.substring(_+1,S-1-_));v=f.substring(0,_+1)+g}else _<f.length-1||":"===f[_-1]&&f.match(/:/g).length<7?v=f.substring(0,_+1)+"x":7===f.match(/:/g).length&&(v=f.substring(0,_)+"0:x");return v?C?v+"]"+C:"["===g.substring(0,1)?(v=v.substring(1),v):v:g}function ipv4AddressConverter(g){const f=g.substring(0,g.lastIndexOf(".")+1)+"x",S=g.lastIndexOf(":");return S>0?f+g.substring(S):f}function shouldDisableVideoSendersTroughSetParams(g,f,S){return!(!f&&!S)&&(S?g.config.disableSendersTroughSetParametersVideo&&(S===qt.MODALITY.sharing||S===qt.MODALITY.video):g.config.disableSendersTroughSetParametersVideo&&("Video"===f.mediaType||"ScreenShare"===f.mediaType))}function shouldDisableAudioSendersTroughSetParams(g,f){return g.config.disableSendersTroughSetParametersAudio&&"Audio"===f.mediaType}function getStreamInformation(g){let f=[];return g.forEach((g=>{try{let S=f.find((f=>f.participantId===g.participantId&&f.endpointId===g.endpointId));S||(S={participantId:g.participantId,endpointId:g.endpointId},f.push(S)),"audio"!==g.type&&"audioteleconference"!==g.type||(S.serverMuted=g.serverMuted),S[g.type]=g.direction}catch(g){f=[]}})),f}var da=M,ha=M,ua={maxOutgoingResolution:({settings:g})=>getMaxOutgoingResolution(g),maxParticipantResolutions:({settings:g})=>getMaxParticipantResolutions2(g),maxIncomingStreams:({settings:g})=>getMaxIncomingStreams2(g),maxSimulcastLayers:({settings:g})=>getMaxSimulcastLayers2(g),outgoingVideoLimit:({settings:g,constraints:f})=>getOutgoingVideoLimit2(g,f)},convertSettingsToCallConstraints=(g,f,S)=>(g.info(`Converting settings to constraints and mapping, [requestedConstraints=${JSON.stringify(S)}], [settings=${JSON.stringify(f)}]`),convertConstraints((0,ha.cloneDeep)(S),(0,ha.cloneDeep)(f))),convertConstraints=(g,f)=>Object.keys(g).reduce(((S,v)=>{const C=ua[v]?ua[v]({constraints:g,settings:f}):void 0;return C&&(S[v]=C),S}),{}),getMaxParticipantResolutions2=g=>g.multiviewResolutionLimits,getMaxOutgoingResolution=g=>g.outgoingVideoLimit?.maxResolution,getOutgoingVideoLimit2=(g,f)=>{const S=f?.outgoingVideoLimit;if(!S)return;const{outgoingVideoLimit:v={}}=deepClone(g);if("number"==typeof S)return v?.maxResolution;const C=Object.keys(S).reduce(((g,f)=>{const S=v?.[f];return S&&(g[f]=S),g}),{});return Object.keys(C).length?C:void 0},getMaxIncomingStreams2=g=>g.numVideoChannelsGvc,getMaxSimulcastLayers2=g=>{const f=g.specCompliantSimulcast,S=f.video?.layerScaleFactors,v=f.sharing?.layerScaleFactors,C=S?.length?Math.max(...S):1,_=v?.length?Math.max(...S):1;return Math.min(C,_)},ga=M,isVideoLimit=g=>{const f=["maxResolution","maxBitrate","maxFramerate"],isValidVideoLimitKey=g=>f.includes(g),S=Object.entries(g);return 0!==S.length&&S.every((([g,f])=>(0,ga.isNumber)(f)&&isValidVideoLimitKey(g)))},isVideoLimitOrResolution=g=>!!(0,ga.isNumber)(g)||!!isVideoLimit(g)&&!isEmpty(g),pa={maxIncomingStreams:ga.isNumber,maxSimulcastLayers:ga.isNumber,maxOutgoingResolution:ga.isNumber,maxParticipantResolutions:g=>!!isDefined2(g)&&(!!(0,ga.isNumber)(g)||"more"in g&&Object.values(g).every((g=>(0,ga.isNumber)(g)))),outgoingVideoLimit:g=>!!isDefined2(g)&&isVideoLimitOrResolution(g)},removeInvalidConstraints=g=>(g=JSON.parse(JSON.stringify(g)),Object.entries(pa).reduce(((f,[S,v])=>(v(g[S])&&(f[S]=g[S]),f)),{}));function arrayMergeCustomizer2(g,f){if(Array.isArray(g))return f.slice()}var deepMergeConstraints=(g,f)=>{for(const S in f){const v=g[S],C=f[S];g[S]="object"==typeof C?deepMergeConstraints({...v},C):getMinDefined(v,C)}return g},ma=class{constructor(g,f,S,v,C,_,T){this.logger=g,this.defaultSettings=f,this._mediaConfig=S,this._userAgentConfig=v,this._countryCode=C,this.platformCallConstraintsProvider=_,this.currentCallConstraints=T,this.mergedConstraints={},this.callConstraintsTelemetry=[],this.iceTransportPolicy=qt.ICE_TRANSPORT_POLICY.all,this.validIceTransportPolicies=[qt.ICE_TRANSPORT_POLICY.all,qt.ICE_TRANSPORT_POLICY.relay],this.mergeConstraintsTelemetryWithGlobal(),this.mergedConstraints=this.mergeConstraintsWithGlobal(this.currentCallConstraints),this.settings=this.mergeSettings((0,da.cloneDeep)(this.defaultSettings))}get config(){return this.settings}get mediaConfig(){return this._mediaConfig}get userAgentConfig(){return this._userAgentConfig}get countryCode(){return this._countryCode}addCallConstraintsTelemetryEvent(g,f){const S={timestamp:(new Date).getTime(),type:f,value:g};arrayLimitedPush22(this.callConstraintsTelemetry,S,this.config.numCallConstraintsEvents)}getCallConstraintsTelemetry(){return this.callConstraintsTelemetry}getCallConstraints(){return this.mergedConstraints}setCallConstraints(g={}){this.addCallConstraintsTelemetryEvent(g,"requested"),this.logger.safe.debug("Saving new call constraints",JSON.stringify(g));const f=this.transformConstraints(removeInvalidConstraints(g));return this.logger.safe.debug("Validated call constraints",JSON.stringify(f)),this.mergedConstraints=this.mergeConstraintsWithGlobal(f),this.settings=this.mergeSettings((0,da.cloneDeep)(this.defaultSettings)),convertSettingsToCallConstraints(this.logger,this.settings,f)}getIceTransportPolicy(){return this.settings.iceTransportPolicyForced||this.iceTransportPolicy}setIceTransportPolicy(g){this.validIceTransportPolicies.includes(g)?(this.logger.info(`Setting transport policy to ${this.iceTransportPolicy}`),this.iceTransportPolicy=g):this.logger.debug(`Unknown incoming transport policy, using ${this.iceTransportPolicy}`)}overrideMaxSessionBandwidth(g){return this.defaultSettings.maxBandwidthInKbps!==g&&(this.defaultSettings.maxBandwidthInKbps=g,this.settings.maxBandwidthInKbps=g,this.mediaConfig.maxBandwidthInKbps=g,!0)}transformConstraints(g){const f=(0,da.cloneDeep)(g);return"maxOutgoingResolution"in f&&(f.outgoingVideoLimit={maxResolution:f.maxOutgoingResolution},delete f.maxOutgoingResolution),"number"==typeof f.outgoingVideoLimit&&(f.outgoingVideoLimit={maxResolution:f.outgoingVideoLimit}),f}mergeConstraintsTelemetryWithGlobal(){this.platformCallConstraintsProvider.callConstraintsTelemetry.forEach((g=>arrayLimitedPush22(this.callConstraintsTelemetry,g,this.defaultSettings.numCallConstraintsEvents)))}mergeConstraintsWithGlobal(g={}){const f=this.transformConstraints(this.platformCallConstraintsProvider.constraints);if(!Object.keys(f).length)return g;const S=(0,da.cloneDeep)(g);return deepMergeConstraints(S,f),this.logger.safe.debug(`Merging call constraints ${JSON.stringify(g)} and global constraints ${JSON.stringify(f)}. Result: ${JSON.stringify(S)}`),S}mergeSettings(g){if(!g.enablePlatformCallConstraints||!g.enablePlatformCallConstraintsPerCall)return g;const f=convertCallConstraintsToSettings(this.logger,g,this.mergedConstraints);return this.logger.safe.info(`Merging settings with platform call constraints: ${stringifyObject2(f)}`),(0,da.assign)({},g,f,arrayMergeCustomizer2)}},fa=M,Sa=[qt.MODALITY.audio,qt.MODALITY.video,qt.MODALITY.sharing],va=class{constructor(g,f,S,v,C){this.peerConnection=f,this.mediaManager=S,this.reinvitelessContext=C,this.entityTransceiverMap=new Map,this.logger=g.createChild("TM"),this.configProvider=v.configProvider,this.isMultiparty=v.config.isConference,this.isPstnCall=v.config.isPstnCall,this.isParkedCall=v.config.isParkedCall,this.numVideoChannels=this.isMultiparty&&this.configProvider.config.numVideoChannelsGvc||1,v.configProvider.config.enableRollbackHandler&&this.mediaManager.setRollbackUpdateHandler(this.handleMediaEntitiesRollback.bind(this))}getTransceivers(){return this.peerConnection.getTransceivers().filter(isActiveTransceiver)}assureTransceivers(g){this.assureNegotiatedOrder(),this.addModalities(g),this.logTransceiversInfo("assureTransceivers"),this.setDirections(g)}syncTransceivers(g){this.syncWithMediaEntities(),this.setDirections(g)}assureNegotiatedOrder(){const g=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((f=>{-1!==Sa.indexOf(f.getModality())&&(isActiveTransceiverInPc(this.entityTransceiverMap.get(f),g)||this.createTransceiverForEntity(f))}))}addModalities(g){const f=this.mediaManager.isEmpty();this.isMultiparty||!f||this.isPstnCall||(g.video=g.video||"inactive",g.sharing=g.sharing||"inactive"),this.configProvider.config.webrctRemoveVideoModalitiesForPstn&&this.isPstnCall&&!this.isParkedCall&&(delete g.video,delete g.sharing);for(const S of Sa){if(this.mediaManager.getMediaEntitiesByModality(S)[0]||!g[S])continue;const v=S===qt.MODALITY.video?this.numVideoChannels:1;(0,fa.times)(v,(g=>{const v=this.mediaManager.createMediaEntity(S);v.setExtension("reinviteless",f&&this.reinvitelessContext.maxStreamsForModality[S]>g),this.createTransceiverForEntity(v)}))}}createTransceiverForEntity(g){const f=g.getModality();this.logger.safe.info(`createTransceiver: modality=${f}`);const S=f===qt.MODALITY.audio?qt.MEDIA_TYPE.audio:qt.MEDIA_TYPE.video,v=g.getSimulcastContext(),C=this.createTransceiver(S,v);this.setCodecPreferences(C,S,!0),this.setExtensionPreferences(C,f),this.entityTransceiverMap.set(g,C),g.setExtension("unnegotiatedModality",!0)}setCodecPreferences(g,f,S){const v=getAllowedCodecs(this.configProvider,f);if(!v?.length||!oa.hasCapabilitiesApi()||this.configProvider.config.filterCodecsInSdp)return;const C=Xs.window.RTCRtpReceiver.getCapabilities(f);if(!C)return;const _=[];if(S)for(const g of v){const f=C.codecs.filter((f=>isCodecsMatch(g,f)));_.push(...f)}else for(const g of C.codecs)v.some((f=>isCodecsMatch(f,g)))&&_.push(g);_.length&&g.setCodecPreferences&&g.setCodecPreferences(_)}setExtensionPreferences(g,f){if(!this.configProvider.config.headerExtensionsToUpdate?.[f])return;if(!g.getHeaderExtensionsToNegotiate||!g.setHeaderExtensionsToNegotiate)return void this.logger.safe.debug("setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate is not supported");const S=this.configProvider.config.headerExtensionsToUpdate[f],v=g.getHeaderExtensionsToNegotiate();for(const g of v){const f=S.find((f=>f.uri===g.uri));f&&(g.direction=f.direction)}try{g.setHeaderExtensionsToNegotiate(v)}catch(g){this.logger.safe.error(`setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate failed, err ${stringifyObject2(g)}`)}}async createSender(g,f,S){const v=await this.associateTrackWithTransceiver(g,f,S);if(!v)throw new Error(`Transceiver for modality=${S} is not found`);const C=this.findEntityForTransceiver(v),_=S!==qt.MODALITY.sharing||C?.getExtension("reinviteless")?qt.MEDIA_STATE.sendReceive:qt.MEDIA_STATE.send;return v.direction=_,this.logger.safe.info(`Replace track completed direction:${v.direction} for transceiver mid=${v.mid}`),v.sender}removeSender(g){this.removeSenderInternal(g,!1)}async removeSenderAsync(g){return this.removeSenderInternal(g,!0)}removeSenderInternal(g,f){if("closed"===(this.peerConnection.connectionState||this.peerConnection.iceConnectionState))return void this.logger.safe.info("Not removing sender from pc, connection is closed");const S=this.getTransceivers().find((f=>f.sender===g));if(!S)throw new Error(`Transceiver for sender with track=${g.track?.id} is not found`);const v=this.findEntityForTransceiver(S),C=!!v?.getExtension("reinviteless");this.logger.safe.info(`Remove sender with track=${g.track?.id} for transceiver mid=${S.mid}, reinviteless=${C}, doAsync=${f}`);let _=Promise.resolve();return C&&f?_=S.sender.replaceTrack(null):this.peerConnection.removeTrack(g),f?_:void 0}createTransceiver(g,f){const S={direction:"inactive"};return this.addSimulcastEnvelopeIfNeeded(S,f),this.peerConnection.addTransceiver(g,S)}addSimulcastEnvelopeIfNeeded(g,f){f?.shouldUseSimulcast()&&(g.sendEncodings=(0,fa.times)(f.config.layerScaleFactors.length,(g=>{const S={rid:`${f.ridList[g]}`,scaleResolutionDownBy:f.config.layerScaleFactors[g]};if(this.configProvider.config.specCompliantSimulcast?.disableTilde&&(S.active=!1),f.config.layerScalabilityModes?.length>0){const v=f.config.layerScalabilityModes[g];void 0!==v&&v.length>0?S.scalabilityMode=v:this.logger.safe.warn(`Scalability mode was not set for rid: ${S.rid}`)}return this.logger.safe.debug(`Added layer ${g} with rid: ${S.rid} SF: ${S.scaleResolutionDownBy} SM: ${S.scalabilityMode}`),S})))}async associateTrackWithTransceiver(g,f,S){const v=this.findAvailableTransceiverToSend(S);if(v){this.logger.safe.info(`Associate track=${g?.id} (${S}) with existing transceiver mid=${v.mid}`);try{if(this.isMultiparty&&shouldDisableVideoSendersTroughSetParams(this.configProvider,void 0,S)){this.logger.safe.info(`Disabling encodings for transceiver mid=${v.mid}`);const g=v.sender.getParameters();g.encodings.forEach((g=>g.active=!1)),await v.sender.setParameters(g)}await v.sender.replaceTrack(g),this.configProvider.config.useSetStreamsForSender&&v.sender.setStreams&&v.sender.setStreams(f)}catch(g){throw this.logger.safe.error(`replaceTrack failed, err ${JSON.stringify(g)}`),g}return v}return null}syncWithMediaEntities(){const g=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((f=>{let S=this.entityTransceiverMap.get(f);S=isActiveTransceiverInPc(S,g)?S:g.find((g=>g.mid===f.getMid())),this.entityTransceiverMap.set(f,S)})),this.logTransceiversInfo("syncWithMediaEntities")}getTransceiversByModality(g){return this.mediaManager.getMediaEntitiesByModality(g).map((g=>this.entityTransceiverMap.get(g))).filter(isActiveTransceiver)}setDirections(g){const f=!isOnHold(g);for(const S of Sa)for(const[v,C]of this.getTransceiversByModality(S).entries()){const _=this.findEntityForTransceiver(C);if(_?.getExtension("reinviteless")&&f){C.direction="sendrecv";continue}const T=g[S]||qt.MEDIA_STATE.inactive;C.direction=0===v&&C.currentDirection?T:removeSendDirectionality2(T)}this.logTransceiversInfo("setDirections")}handleMediaEntitiesRollback(g,f){g.forEach((g=>{const S=this.entityTransceiverMap.get(g),v=f.find((f=>f.getMid()===g.getMid()));this.entityTransceiverMap.set(v,S)})),this.logTransceiversInfo("handleMediaEntitiesRollback")}findAvailableTransceiverToSend(g){const f=this.mediaManager.getMediaEntitiesByModality(g)[0];return this.entityTransceiverMap.get(f)}findEntityForTransceiver(g){for(const[f,S]of this.entityTransceiverMap)if(S===g)return f}logTransceiversInfo(g){let f=`${g}: transceivers details:`;for(const g of Sa){const S=this.getTransceiversByModality(g);f+=` ${g}(${S.length}) [${S.map((g=>`mid=${g.mid}, direction=${g.direction}`)).join(";")}]`}this.logger.safe.debug(f)}};function isCodecsMatch(g,f){return!(!(0,fa.isUndefined)(g.channels)&&g.channels!==f.channels||!(0,fa.isUndefined)(g.clockRate)&&g.clockRate!==f.clockRate||!(0,fa.isUndefined)(g.mimeType)&&g.mimeType.toLowerCase()!==f.mimeType.toLowerCase()||!(0,fa.isUndefined)(g.sdpFmtpLine)&&-1===f.sdpFmtpLine.toLowerCase().indexOf(g.sdpFmtpLine.toLowerCase()))}function removeSendDirectionality2(g){let f=g;return hasSendDirectionality(g)&&(f=removeSendDirectionality(g)),f||qt.MEDIA_STATE.inactive}function isActiveTransceiver(g){return g&&"stopped"!==g.direction&&!g.stopped}function isActiveTransceiverInPc(g,f){return isActiveTransceiver(g)&&-1!==f.indexOf(g)}var Ca=class extends Ht{constructor(g,f,S){super(),this.configProvider=g,this.workerProvider=f,this.logger=S,this.transformsCollections=new Map}async initialize(){return this.configProvider.config.useInsertableStreams&&this.workerProvider&&oa.hasEncodedStreamsApi()&&(this.worker=new Ha(this.workerProvider,this.logger)),this.worker?this.worker.initialize():Promise.resolve()}initTransformsCollection(g,f,S){const v=oa.hasScriptTransformApi()||this.workerProvider;if(!this.configProvider.config.useInsertableStreams||!oa.hasEncodedStreamsApi()||v&&!this.isWorkerLoaded()||null===g.track)return null;if(!this.transformsCollections.has(g)){const v=this.worker?new Ea(this.worker,g):new ya(g);this.transformsCollections.set(g,{collection:v,mediaType:S,objType:f})}const C=this.transformsCollections.get(g);return this.event("onTransformsCollectionCreated").raise(C),C.collection}clearTransformsCollection(g){const f=this.transformsCollections.get(g);f&&(this.event("onTransformsCollectionCleared").raise(f),f.collection.clearTransforms())}dispose(){for(const g of this.transformsCollections.values())this.event("onTransformsCollectionCleared").raise(g),g.collection.clearTransforms();this.transformsCollections.clear(),this.worker?.dispose(),super.dispose()}isWorkerLoaded(){return!!this.worker?.isWorkerLoaded()}},ya=class{constructor(g){const{readable:f,writable:S}=g.createEncodedStreams();this.streamTransformer=new Ya(f,S)}addTransform(g){g.createBaseInstance(this.streamTransformer)}clearTransforms(){this.streamTransformer.clearTransforms()}},Ea=class{constructor(g,f){if(this.workerHandler=g,this.clientId=f.track.id,oa.hasScriptTransformApi())return void(f.transform=new RTCRtpScriptTransform(this.workerHandler.worker,{clientId:this.clientId}));const{readable:S,writable:v}=f.createEncodedStreams(),C=[S,v];this.workerHandler.sendTransformCommand(this.clientId,{operation:"init",readable:S,writable:v},C)}addTransform(g){g.createWorkerInstance(this.workerHandler,this.clientId)}clearTransforms(){this.workerHandler.sendTransformCommand(this.clientId,{operation:"clear"})}},_a=class{constructor(g,f=!1){this.logger=g,this.disabled=f,this.audioContext=new AudioContext,this.destination=this.audioContext.createMediaStreamDestination()}get stream(){return this.destination.stream}isSingleInputStream(){return 0===this.mixerImp?.mixerType}dispose(){this.audioContext.close(),this.audioContext=null}stopMixing(){this.disabled=!0,this.mixerImp?.reset()}startMixing(g){this.disabled=!1,this.mixerImp?.setupMixer(this.audioContext,this.destination,g)}setMixerType(g,f){this.mixerImp?.mixerType!==g&&(this.mixerImp?.reset(),this.mixerImp=this.createMixer(g),this.disabled||this.mixerImp.setupMixer(this.audioContext,this.destination,f))}setStreamSources(g){this.disabled||this.mixerImp.setStreamSources?.(g)}setParticipantSpatialAudioPositions(g){this.mixerImp.setParticipantSpatialAudioPositions?.(g)}createMixer(g){switch(g){case 0:return new Ia;case 1:return new ba(this.logger.createChild("MixingStreamsMixer"));case-1:return new Ta;default:throw new Error(`unknown mixer type: ${g}`)}}},Ta=class{constructor(){this.mixerType=-1}reset(){}setupMixer(g,f,S){}},Ia=class{constructor(){this.mixerType=0}reset(){this.sourceNode.disconnect()}setupMixer(g,f,S){this.sourceNode=g.createMediaStreamSource(S[0]),this.sourceNode.connect(f)}},ba=class{constructor(g){this.logger=g,this.sourcePositions=new Map,this.sourceNodes=[],this.pannerNodes=[],this.mixerType=1}reset(){this.logger.safe.info("resetting SpatialMultiStreamMixer");for(const g of this.sourceNodes)g.disconnect();this.sourceNodes=[];for(const g of this.pannerNodes)g.disconnect();this.pannerNodes=[]}setupMixer(g,f,S){(this.sourceNodes.length||this.pannerNodes.length)&&this.reset();for(const v of S){const S=g.createMediaStreamSource(v),C=new PannerNode(g,{panningModel:"HRTF"});S.connect(C),C.connect(f),this.sourceNodes.push(S),this.pannerNodes.push(C)}this.logger.safe.info(`setupMixer is done for ${S.length} streams.`)}setStreamSources(g){for(let f=0;f<g.length;f++)this.setStreamPosition(f,g[f])}setParticipantSpatialAudioPositions(g){this.sourcePositions=new Map(g.map((g=>[g.sourceId,g])))}setStreamPosition(g,f){const S=this.sourcePositions.get(f)??{sourceId:f,x:0,y:0},v=this.pannerNodes[g];v?(v.positionX.value=S.x,v.positionY.value=S.y):this.logger.warn(`panner node for stream ${g} is not found`)}},Aa=class extends Ht{constructor(g){super(),this.logger=g,this.mediaStreams=[],this.cnStream=null,this.isConfigured=!1,this.isNegotiated=!1,this.activeCodec="None"}get streams(){return this.mediaStreams}get comfortNoiseStream(){return this.cnStream}get configured(){return this.isConfigured}get active(){return this.isNegotiated}get codec(){return this.activeCodec}setupStreams(g,f){this.logger.safe.debug(`setup ${g} streams with extra Comfort Noise stream: ${f}`),this.mediaStreams=[];const S=[];for(;g--;){const g=new MediaStreamTrackGenerator({kind:"audio"});S.push(g),this.streams.push(new MediaStream([g]))}const v=f?new MediaStreamTrackGenerator({kind:"audio"}):null;return this.cnStream=v?new MediaStream([v]):null,this.event("onStreamsChanged").raise(),{streams:S.map((g=>g.writable)),cnStream:v?.writable}}setStreamSources(g){this.isNegotiated&&this.event("onStreamSourcesUpdated").raise(g)}setConfiguredState(g){this.isConfigured!==g&&(this.isConfigured=g,this.event("onConfiguredStateChanged").raise(this.isConfigured))}setNegotiatedState(g){this.isNegotiated!==g&&(this.isNegotiated=g,this.event("onActiveStateChanged").raise(this.isNegotiated))}setDetectedCodec(g){this.activeCodec!==g&&(this.activeCodec=g,this.event("onActiveCodecChanged").raise(this.activeCodec))}},Pa=0,Ra={MUCHv2:{CODEC:{NAME:"x-much2",RATE:48e3,ENCODING:2},SUBSTITUTION:{NAME:"L16",RATE:48e3,ENCODING:2},PT:113},SatinFB:{CODEC:{NAME:"SATINFB",RATE:48e3,ENCODING:2},SUBSTITUTION:{NAME:"L16",RATE:48e3,ENCODING:2},PT:109}},Ma=class{constructor(g,f,S,v){this.worker=g,this.clientId=f,this.transformType=S,this.listener=v,this.worker.subscribeClient(this.clientId,this.transformType,(g=>this.processMsg(g))),this.worker.sendTransformCommand(this.clientId,{operation:"add",transformType:this.transformType})}dispose(){this.worker.unsubscribeClient(this.clientId),this.worker.sendTransformCommand(this.clientId,{operation:"clear"})}processMsg(g){if(this.listener&&g.name in this.listener)return this.listener[g.name].apply(this.listener,g.args);throw`unexpected message received for transform type ${this.transformType}: ${JSON.stringify(g)}`}};function createAudioWasmDecoderProxy(g,f,S){return new wa(g,f,S)}var wa=class extends Ma{constructor(g,f,S){super(g,f,2,S)}init(g,f){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[g,f]}})}setCodec(g,f){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[g,f]}})}passWriteableStreams(g,f){const S=g.concat(f);this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"passWriteableStreams",args:[g,f]}},S)}setAvailableStreams(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setAvailableStreams",args:[g]}})}setRecvPayloads(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setRecvPayloads",args:[g]}})}debugLogging(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[g]}})}sendApiRecordingData(){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"sendApiRecordingData",args:[]}})}},Oa=class extends Ht{constructor(g,f,S,v){super(),this.logger=g,this.maxNumOfStreamsFactor=S,this.statsProvider=new Da,this.contributingSources=[],this.unmixedAudioProvider=new Aa(this.logger),this.codec="None",this.recvPayloads=[],this.initCompleted=!1,this.enabledApiRecording=!1;try{this.enabledApiRecording="true"===localStorage.getItem("enableApiRecording")}catch{}this.streamMixer=new _a(this.logger,v),this.unmixedAudioProvider.setConfiguredState(!!f.mediaConfig.spatialAudioEnabled),this.wasmHealerPullStrategy=f.config.useInsertableStreams?.audioWasmCodec?.wasmHealerPullStrategy||-1,this.injectWebMA()}get stream(){return this.streamMixer.stream}dispose(){super.dispose(),this.streamMixer.dispose(),this.imp?.dispose(),this.removeWebMA()}activateTransform(g){this.logger.safe.debug("Activating WASM decoder transform"),g.addTransform(this)}deactivateTransform(){this.logger.safe.debug("Deactivating WASM decoder transform"),this.imp.dispose(),this.imp=null,this.initCompleted=!1,this.codec="None",this.streamMixer.setMixerType(-1,[])}createBaseInstance(g){this.logger.warn("WASM decoder could only be instantiated in worker")}createWorkerInstance(g,f){this.imp=createAudioWasmDecoderProxy(g,f,this),this.imp.init(this.enabledApiRecording,this.wasmHealerPullStrategy)}setCodec(g){if(this.logger.safe.debug(`Setting codec to ${g}`),!this.initCompleted)return this.logger.safe.debug("Decoder is not initialized yet, postponing codec setting"),void(this.codec=g);this.codec!==g&&(this.codec=g,this.setCodecInternal())}setRecvPayloads(g){this.recvPayloads=g,this.initCompleted?this.imp.setRecvPayloads(g):this.logger.safe.debug("Decoder is not initialized yet, postponing Recv payload setting")}negotiationCompleted(g){this.logger.safe.debug(`Negotiation completed, negotiated=${g}`),this.unmixedAudioProvider.setNegotiatedState(g),g||(this.codec="None",this.imp?.setCodec(this.codec,this.streamMixer.isSingleInputStream()))}setParticipantSpatialAudioPositions(g){this.streamMixer.setParticipantSpatialAudioPositions(g)}disableStreamsMixer(g){g?this.streamMixer.stopMixing():this.streamMixer.startMixing(this.unmixedAudioProvider.streams.concat(this.unmixedAudioProvider.comfortNoiseStream??[]))}getStatsProvider(){return this.statsProvider}getUnmixedAudioProvider(){return this.unmixedAudioProvider}configureSpatialAudio(g){this.unmixedAudioProvider.setConfiguredState(g)}async storeApiRecording(){if(this.enabledApiRecording&&this.initCompleted)return this.recordingCompletePromise?.resolve(),this.recordingCompletePromise=new dt,this.imp.sendApiRecordingData(),this.recordingCompletePromise.promise}initDone(g,f){if(this.healerCapabilities=f,this.logger.safe.info(`Init done, errorCode=${g}`),0!==g)return void this.event("initFailed").raise(g);this.logger.safe.info(`healerCapabilities=${JSON.stringify(f)}`),this.initCompleted=!0;const S=Math.floor(this.healerCapabilities.maxNumStreamsPerPacket*this.maxNumOfStreamsFactor),v=this.unmixedAudioProvider.setupStreams(S,!0);this.imp.passWriteableStreams(v.streams,v.cnStream),this.setCodecInternal(),this.imp.setRecvPayloads(this.recvPayloads)}usedDecoderChanged(g){this.logger.safe.info(`Used decoder changed to custom=${g}, configured codec=${this.codec}`),this.event("usedDecoderChanged").raise(g),this.unmixedAudioProvider.setDetectedCodec(this.codec)}packetReceived(g,f,S,v){this.statsProvider.ssrc=f,this.statsProvider.addPushStats(g,v),this.contributingSources.length===S.length&&this.contributingSources.every(((g,f)=>g===S[f]))||(this.contributingSources=S,this.event("contributingSourcesChanged").raise(S))}newDataWrittenToStreams(g){const f=Array.from(new Int32Array(g));this.unmixedAudioProvider.setStreamSources(f),this.streamMixer.setStreamSources(f);const S=f.reduce(((g,f,S)=>(f===Pa&&g.push(S),g)),[]);this.imp?.setAvailableStreams(S)}packetDecoded(g,f,S){this.statsProvider.addPullStats(g,f,S,S.extra.samplingRatekHz*this.healerCapabilities.frameLengthMs)}apiRecordingAvailable(g,f,S){if(this.logger.safe.debug(`API recording available: errorCode=${g}, name=${f}, buffer length=${S.byteLength}`),this.recordingCompletePromise?.resolve(),0===S.byteLength)return;const v=new Blob([S],{type:"application/octet-stream"}),C=URL.createObjectURL(v),_=document.createElement("a");_.href=C,_.download=f,_.click()}setCodecInternal(){this.streamMixer.setMixerType(getStreamGeneratorType(this.codec),this.unmixedAudioProvider.streams.concat(this.unmixedAudioProvider.comfortNoiseStream??[])),this.imp.setCodec(this.codec,this.streamMixer.isSingleInputStream()),this.statsProvider.codecName=this.codec}injectWebMA(){const g=window.webMA;g&&(g.wasmDecoder={debugLogging:g=>this.imp?.debugLogging(g),sendApiRecordingData:()=>this.imp?.sendApiRecordingData()})}removeWebMA(){const g=window.webMA;g&&delete g.wasmDecoder}};function getStreamGeneratorType(g){switch(g){case"SatinFB":return 0;case"MUCHv2":return 1;case"None":return-1;default:throw new Error(`unknown codec: ${g}`)}}var Da=class{constructor(){this.customHealerStats={numSamplesPerFrame:0,FECPayloadDecodedSamples:0,concealSamples:0,stretchSamples:0,healedSamples:0,decodedSamples:0,redPacketsCount:0,pushProcessingTimes:{},pullProcessingTimes:{},pullProcessingTimePerStreamNumber:{},pullTimings:{},pullNumOfStreamsCounter:{}},this.inboudStats={silentConcealedSamples:0,concealedSamples:0,totalSamplesReceived:0,audioLevel:0,jitterBufferDelay:0,jitterBufferEmittedCount:0},this.decoderStats={pushCount:0,pushErrCount:0,pullCount:0,pullErrCount:0},this.packetPushProccesingTimes=new Na(0,1e3),this.packetPullProccesingTimes=new Na(0,1e3),this.numOfStreamsCounter=new Na(0,10),this.pullProcessingTimePerStreamNumber={},this.packetPullTimings=new Na(0,1e3)}get codecName(){return this.codec}set codecName(g){this.codec=g}addPushStats(g,f){this.decoderStats.pushCount++,this.decoderStats.pushErrCount+=0!==g?1:0,this.inboudStats.jitterBufferDelay+=f.webrtc.jitterBufferDelay,this.customHealerStats.packetDurationInMs=f.extra.packetDurationInMs,this.packetPushProccesingTimes.addSample(f.extra.processingTime),this.customHealerStats.cnpPushCount=f.extra.totalCountCNPackets,this.customHealerStats.redPacketsCount+=0!==f.extra.redundancyTimestampOffset?1:0}addPullStats(g,f,S,v){var C;this.decoderStats.pullCount++,this.decoderStats.pullErrCount+=0!==g?1:0,this.inboudStats.audioLevel=S.webrtc.audioLevel,this.inboudStats.totalAudioEnergy=S.webrtc.totalAudioEnergy,this.inboudStats.jitterBufferEmittedCount=S.webrtc.jitterBufferEmittedCount,this.inboudStats.totalSamplesReceived=S.webrtc.totalSamplesReceived,this.inboudStats.concealedSamples=S.webrtc.concealedSamples,this.inboudStats.silentConcealedSamples=S.webrtc.silentConcealedSamples,this.numOfStreamsCounter.addSample(f),this.customHealerStats.FECPayloadDecodedSamples=S.extra.FECPayloadDecodedSamples,this.customHealerStats.numSamplesPerFrame=v,this.customHealerStats.pullAdspPayloadType=S.extra.pullAdspPayloadType,this.customHealerStats.concealSamples=S.extra.concealSamples,this.customHealerStats.stretchSamples=S.extra.stretchSamples,this.customHealerStats.healedSamples=S.extra.healedSamples,this.customHealerStats.decodedSamples=S.extra.decodeSamples,this.packetPullProccesingTimes.addSample(S.extra.processingTime),this.customHealerStats.cnpPullCount=S.extra.totalCountCNGeneratedFrames,this.customHealerStats.cngSamples=S.extra.cngSamples,(C=this.pullProcessingTimePerStreamNumber)[f]??(C[f]=new Na(0,200)),this.pullProcessingTimePerStreamNumber[f].addSample(S.extra.processingTime),this.packetPullTimings.addSample(S.pullTiming)}getWebRtcCompatibleStats(){return this.inboudStats}getWasmStats(){this.customHealerStats.pushProcessingTimes=this.packetPushProccesingTimes.getFrequencies(),this.customHealerStats.pullProcessingTimes=this.packetPullProccesingTimes.getFrequencies(),this.customHealerStats.pullNumOfStreamsCounter=this.numOfStreamsCounter.getFrequencies(),this.customHealerStats.pullTimings=this.packetPullTimings.getFrequencies();for(const g of Object.keys(this.pullProcessingTimePerStreamNumber))this.customHealerStats.pullProcessingTimePerStreamNumber[g]=this.pullProcessingTimePerStreamNumber[g].getFrequencies();return this.customHealerStats}getDecoderStats(){return this.decoderStats}},Na=class{constructor(g,f){this.minSample=g,this.maxSample=f,this.frequencyDict={}}addSample(g){if(void 0===g)return;const f=Math.min(this.maxSample,Math.max(this.minSample,g));this.frequencyDict[f]=(this.frequencyDict[f]??0)+1}getFrequencies(){return{...this.frequencyDict}}};function createAudioWasmEncoderProxy(g,f,S){return new ka(g,f,S)}var ka=class extends Ma{constructor(g,f,S){super(g,f,3,S)}init(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[g]}})}setCodec(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[g]}})}debugLogging(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[g]}})}},La=["SatinFB"],Fa=class extends Ht{constructor(g){super(),this.logger=g,this.codec="None",this.injectWebMA()}dispose(){super.dispose(),this.imp?.dispose(),this.removeWebMA()}activateTransform(g){this.logger.safe.debug("Activating WASM encoder transform"),g.addTransform(this)}deactivateTransform(){this.logger.safe.debug("Deactivating WASM encoder transform"),this.imp.dispose(),this.imp=null,this.encodersInitCodes=void 0,this.codec="None"}createBaseInstance(g){this.logger.warn("WASM encoder could only be instantiated in worker")}createWorkerInstance(g,f){this.imp=createAudioWasmEncoderProxy(g,f,this),this.imp.init(La)}setCodec(g){if(this.logger.safe.debug(`Setting codec to ${g}`),!this.encodersInitCodes)return this.logger.safe.debug("Encoder is not initialized yet, postponing codec setting"),void(this.codec=g);this.codec!==g&&(this.codec=g,this.setCodecInternal())}isCodecAllowed(g){return La.includes(g)}negotiationCompleted(g){g||(this.codec="None",this.imp?.setCodec(this.codec))}initDone(g){this.logger.safe.info(`initDone: ${JSON.stringify(g)}`),this.encodersInitCodes=g,this.setCodecInternal()}packetEncoded(g){0!==g&&this.logger.safe.info(`encode failed: ${g}`)}setCodecInternal(){const g=this.encodersInitCodes[this.codec]??-2147024809;if("None"!==this.codec&&0!==g)return this.logger.safe.error(`WASM encoder is failed to init codec ${this.codec}, err code: ${g}`),void this.event("initCodecFailed").raise(g);this.imp.setCodec(this.codec)}injectWebMA(){const g=window.webMA;g&&(g.wasmEncoder={debugLogging:g=>this.imp?.debugLogging(g)})}removeWebMA(){const g=window.webMA;g&&delete g.wasmEncoder}},xa=M,Ua=class extends Ht{constructor(g,f,S){super(),this.encStreamsManager=g,this.logger=f,this.configProvider=S,this.isEnabled=!1,this.sessionStats=new Ba,this.subs=[],this.codecContext=this.configProvider.mediaConfig.audioCodecContext,this.codecConfig=this.configProvider.config.useInsertableStreams?.audioWasmCodec}get decoder(){return this.decoderImp}get encoder(){return this.encoderImp}init(g,f){if(!g||!this.codecContext||!this.codecConfig?.enable)return;this.isEnabled=!0;const S=this.codecConfig.maxNumOfStreamsFactor||1;this.decoderImp=new Oa(this.logger.createChild("AudioWasmDecoder"),this.configProvider,S,f),this.codecConfig.enableSend&&(this.encoderImp=new Fa(this.logger.createChild("AudioWasmEncoder"))),this.subscribeToStreamManagerEvents(this.encStreamsManager),this.subscribeToCodecsEvents()}dispose(){super.dispose(),this.unsubscribeFromEvents(),this.decoderImp?.dispose(),this.encoderImp?.dispose()}getSessionEvents(){return this.sessionStats.getSessionEvents()}prepareForNegotiation(g){if(!this.isEnabled)return;const f=this.decoderImp?.getUnmixedAudioProvider()?.configured?"MUCHv2":this.codecConfig.codec||"None";this.codecContext.codec!==f&&(this.codecContext.initSendFailed=!1),this.codecContext.lastUsedCodec=this.codecContext.codec,this.codecContext.codec=f,this.codecContext.enabledLocally=!this.codecContext.initFailed&&"None"!==f,this.codecContext.enabledForSend=this.codecContext.enabledLocally&&!this.codecContext.initSendFailed&&!!this.codecConfig?.enableSend&&this.encoder?.isCodecAllowed(f),this.logger.safe.info(`Audio codec state: context=${JSON.stringify(this.codecContext)}`),this.codecContext.initFailed||!g&&this.codecContext.disabledRemotely||(this.sessionStats.toggleState("None"!==f),this.decoderImp?.setCodec(f),this.encoderImp?.setCodec(this.codecContext.enabledForSend?f:"None"))}negotiationCompleted(){if(!this.isEnabled)return!1;const g=this.codecContext.enabledLocally&&!this.codecContext.disabledRemotely;return this.decoderImp?.negotiationCompleted(g),this.encoderImp?.negotiationCompleted(g),this.sessionStats.negotiationCompleted(g,this.codecContext.enabledForSend),g}configureSpatialAudio(g,f){return!!this.isEnabled&&(this.decoderImp?.configureSpatialAudio(g),(g&&"MUCHv2"!==this.codecContext.codec||!g&&"MUCHv2"===this.codecContext.codec)&&this.event("negotiationNeeded").raise(f),!0)}subscribeToStreamManagerEvents(g){this.subs.push(g.on("onTransformsCollectionCreated",(g=>this.handleTransformsCollectionCreated(g))),g.on("onTransformsCollectionCleared",(g=>this.handleTransformsCollectionCleared(g))))}handleTransformsCollectionCreated(g){"Audio"===g.mediaType&&(this.decoderImp&&"Receiver"===g.objType?this.decoderImp.activateTransform(g.collection):this.encoderImp&&"Sender"===g.objType&&this.encoderImp.activateTransform(g.collection))}handleTransformsCollectionCleared(g){"Audio"===g.mediaType&&(this.decoderImp&&"Receiver"===g.objType?this.decoderImp.deactivateTransform():this.encoderImp&&"Sender"===g.objType&&this.encoderImp.deactivateTransform())}subscribeToCodecsEvents(){this.decoderImp&&this.subs.push(this.decoderImp.on("initFailed",(g=>this.handleCodecInitFailed("decoder",g)))),this.encoderImp&&this.subs.push(this.encoderImp.on("initCodecFailed",(g=>this.handleCodecInitFailed("encoder",g))))}unsubscribeFromEvents(){this.subs.forEach((g=>g.dispose())),this.subs=[]}handleCodecInitFailed(g,f){"decoder"===g?this.codecContext.initFailed=!0:this.codecContext.initSendFailed=!0;const S=generateCauseId();this.logger.safe.warn(`[${S}] Audio ${g} init failed ${f}`),this.sessionStats.initFailed(f,g),this.event("negotiationNeeded").raise(S)}},Va=class _AudioCodecSessionStats2{constructor(){this.sessionEvents={negotiationAttempts:[],toggleCount:0,negotiatedCount:0,failedNegotiationCount:0,decoderInitError:0,encoderInitError:0}}toggleState(g){this.sessionEvents.toggleCount++,this.inProgressNegotiation={ts:Date.now(),enabled:g,negotiated:!1,sendEnabled:!1},arrayLimitedPush22(this.sessionEvents.negotiationAttempts,this.inProgressNegotiation,_AudioCodecSessionStats2.maxStoreNegotiations)}negotiationCompleted(g,f){this.inProgressNegotiation&&(this.sessionEvents.negotiatedCount+=g?1:0,this.sessionEvents.failedNegotiationCount+=this.inProgressNegotiation.enabled&&!g?1:0,this.inProgressNegotiation.negotiated=g,this.inProgressNegotiation.sendEnabled=f,this.inProgressNegotiation=void 0)}initFailed(g,f){"decoder"===f?this.sessionEvents.decoderInitError=g:this.sessionEvents.encoderInitError=g}getSessionEvents(){return(0,xa.clone)(this.sessionEvents)}};Va.maxStoreNegotiations=5;var Ba=Va,Ha=class{constructor(g,f){this.logger=f,this.clientsMap=new Map,this.loaded=!1,this.initDefer=new dt;try{this.worker=g.getWorker(this.logger),this.worker.onmessage=g=>this.handleEvent(g.data),this.worker.onerror=g=>{this.logger.safe.error(`error inside worker: ${g.message}`),this.initDefer.resolve()}}catch(g){this.logger.safe.error("failed to create worker"),this.initDefer.resolve()}}initialize(){return Promise.race([this.initDefer.promise,delay(5e3).then((()=>{this.loaded??this.logger.safe.warn("worker initialization timeout")}))])}isWorkerLoaded(){return this.loaded}sendTransformCommand(g,f,S=[]){const v={type:"transform",clientId:g,payload:f};this.worker?.postMessage(v,S)}subscribeClient(g,f,S){const v=this.clientsMap.get(g)??new Map;v.set(f,S),this.clientsMap.set(g,v)}unsubscribeClient(g){this.clientsMap.delete(g)}dispose(){const g={type:"generic",payload:{operation:"dispose"}};this.worker?.postMessage(g),this.worker?.terminate()}handleEvent(g){switch(g.type){case"init":this.initDefer.resolve(),this.loaded=!0,this.logger.safe.info("worker initialized");break;case"transform":{const f=this.clientsMap.get(g.payload.clientId),S=f?.get(g.payload.event.transformType);S?S(g.payload.event):this.logger.safe.error(`received event for unknown Client ${g.payload.clientId} or transformType ${g.payload.event.transformType}: ${g.payload.event.name}`)}break;case"log":switch(g.level){case"debug":this.logger.safe.debug(g.msg);break;case"info":this.logger.safe.info(g.msg);break;case"warn":this.logger.safe.warn(g.msg);break;case"error":this.logger.safe.error(g.msg);break;default:this.logger.safe.error(`unknown log level ${g.level}`)}break;default:this.logger.safe.error(`received unsupported event from worker ${g.type}`)}}},$a=7,ja=31,Ga=class{constructor(g){this.logger=g,this.transformType=0}transform(g){return this.processChunk(g),g}dispose(){}getStartCodeSize(g){const f=g.getUint32(0);return 1===f?4:256==(4294967040&f)?3:0}processChunk(g){if("key"!==g.type)return;const f=this.isH264KeyFrame(g.data)?`${this.getH264Profile(g.data)}(H264)`:"unknown";this.logger.info(`keyframe metadata: ${JSON.stringify(g.getMetadata())}, profile=${f}`)}isH264KeyFrame(g){if(g.byteLength<7)return!1;const f=new DataView(g),S=this.getStartCodeSize(f);return!!S&&(f.getUint8(S)&ja)===$a}getH264Profile(g){const f=new DataView(g),S=this.getStartCodeSize(f);return(16777215&f.getUint32(S)).toString(16)}},qa=class extends Ma{constructor(g,f){super(g,f,0,void 0)}},Wa=class{constructor(g){this.logger=g}createBaseInstance(g){this.imp=new Ga(this.logger.safe),g.addTransform(this.imp)}createWorkerInstance(g,f){this.imp=new qa(g,f)}},za=class{constructor(){this.transformType=1,this.muted=!1}transform(g){return this.muted?null:g}mute(g){this.muted=g}dispose(){}},Ka=class extends Ma{constructor(g,f){super(g,f,1,void 0)}mute(g){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"mute",args:[g]}})}},Ja=class{constructor(g){this.logger=g}createBaseInstance(g){this.imp=new za,g.addTransform(this.imp)}createWorkerInstance(g,f){this.imp=new Ka(g,f)}mute(g){this.logger.safe.info(`Dropping audio chunks: ${g}`),this.imp.mute(g)}},Ya=class{constructor(g,f){this.transforms=[];const S=new TransformStream({transform:(g,f)=>{let S=g;for(const g of this.transforms)if(S=g.transform(S),!S)return;f.enqueue(S)}});g.pipeThrough(S).pipeTo(f)}clearTransforms(){for(const g of this.transforms)g.dispose();this.transforms=[]}addTransform(g){this.transforms.push(g)}getTransform(g){return this.transforms.find((f=>f.transformType===g))}},Qa=class extends Ke{constructor(){super(),this.subs=[]}get streams(){return this.sessionAudioProvider?.streams??[]}get comfortNoiseStream(){return this.sessionAudioProvider?.comfortNoiseStream??null}get configured(){return this.sessionAudioProvider?.configured??!1}get active(){return this.sessionAudioProvider?.active??!1}get codec(){return this.sessionAudioProvider?.codec??"None"}setSessionStreamsProvider(g){this.unsubscribeFromStreamEvents(),this.sessionAudioProvider=g,this.subscribeForStreamEvents(),this.event("onStreamsChanged").raise(),this.event("onActiveStateChanged").raise(this.active)}dispose(){super.dispose(),this.unsubscribeFromStreamEvents()}subscribeForStreamEvents(){this.sessionAudioProvider&&this.subs.push(this.sessionAudioProvider.on("onStreamsChanged",(()=>this.event("onStreamsChanged").raise())),this.sessionAudioProvider.on("onStreamSourcesUpdated",(g=>this.event("onStreamSourcesUpdated").raise(g))),this.sessionAudioProvider.on("onConfiguredStateChanged",(g=>this.event("onConfiguredStateChanged").raise(g))),this.sessionAudioProvider.on("onActiveStateChanged",(g=>this.event("onActiveStateChanged").raise(g))),this.sessionAudioProvider.on("onActiveCodecChanged",(g=>this.event("onActiveCodecChanged").raise(g))))}unsubscribeFromStreamEvents(){this.subs.forEach((g=>g.dispose())),this.subs=[]}},Xa=class extends Ke{constructor(g,f,S,v,C){super(),this.allowVirtualDeviceInCall=g,this.defaultDeviceManager=f,this.logger=S,this.callStats=v,this.isMediaSending=C,this.stats=[],this.selectedVirtualDevice={camera:void 0,screenshare:void 0},this.subs=[this.defaultDeviceManager.on("onVirtualDevicesChanged",(()=>this.handleRegisteredDeviceChange()))],this.logger.info(`allowVirtualDeviceInCall: ${g}`)}get isVirtualDeviceEnabled(){return this.allowVirtualDeviceInCall}selectDevices(g){const f=this.defaultDeviceManager.getRegisteredDevices(),S=f.find((f=>f.id===g.camera)),v=f.find((f=>f.id===g.screenshare));this.logger.info(`Selecting virtual devices, camera: ${S?.id}, screenshare: ${v?.id}`);const C={camera:this.selectedVirtualDevice.camera?.id,screenshare:this.selectedVirtualDevice.screenshare?.id};g.camera!==C.camera||g.screenshare!==C.screenshare?(this.selectedVirtualDevice={camera:S,screenshare:v},this.addToCallStat({type:"VirtualDeviceSelected",payload:this.selectedVirtualDevice}),this.event("onSelectedVirtualDevicesChanged").raise(g,C)):this.logger.info("Virtual Device did not change.")}getSelectedDevices(){return Object.entries(this.selectedVirtualDevice).reduce(((g,[f,S])=>(g[f]=S?.id,g)),{})}getDeviceManager(g){return this.allowVirtualDeviceInCall?this.getDeviceManagersForVirtualDevice(g)[0]:this.defaultDeviceManager}getDeviceManagersForVirtualDevice(g){return"Video"===g&&this.selectedVirtualDevice.camera?(this.logger.info(`Using Virtual Device (DM), type: ${g}`),this.selectedVirtualDevice.camera.getDeviceManagers()):"ScreenShare"===g&&this.selectedVirtualDevice.screenshare?(this.logger.info(`Using Virtual Device (DM), type: ${g}`),this.selectedVirtualDevice.screenshare.getDeviceManagers()):(this.logger.info(`Using default DM, type: ${g}`),[this.defaultDeviceManager])}getDefaultDeviceManager(){return this.defaultDeviceManager}dispose(){this.stats=[],this.subs.forEach((g=>g.dispose())),super.dispose()}hasDevice(g){return this.defaultDeviceManager.id===g||[...this.selectedVirtualDevice.camera?.getDeviceManagers()??[],...this.selectedVirtualDevice.screenshare?.getDeviceManagers()??[]].some((f=>f?.id===g))}addToCallStat(g){const f=this.stats.push(g);this.callStats.appendCallDeviceManagerInfo({events:JSON.stringify(f)})}handleRegisteredDeviceChange(){const g=this.defaultDeviceManager.getRegisteredDevices(),{camera:f,screenshare:S}=this.selectedVirtualDevice;let v=!1,C=!1;f&&(v=g.some((g=>g.id===f.id)),this.logger.info(`Selected camera(${f.id}) in call, isCameraValid:${v}`)),S&&(C=g.some((g=>g.id===S.id)),this.logger.info(`Selected SS(${S.id}) in call, isScreenShareValid:${C}`)),this.selectDevices({camera:v?f.id:void 0,screenshare:C?S.id:void 0})}isModalityEnabled(g){return this.isMediaSending(getSkypeMediaType(g))}},Za=class{constructor(g,f){this.logger=g,this.configProvider=f,this.debounceMap=new Map,this.configProvider.config.remoteUFD?.enabled&&Object.keys(this.configProvider.config.remoteUFD.list).length&&this.logger.info(`Remote UFDs list: ${JSON.stringify(this.configProvider.config.remoteUFD.list)}`)}raiseIfNeeded(g,f,S){if(this.shouldBeRaised(g,f))if(this.configProvider.config.localUFDDebounceTime)S(this.getState(g));else{clearTimeout(this.debounceMap.get(g.type));const f=setTimeout(S,this.configProvider.config.remoteUFD.debounceTime,this.getState(g));this.debounceMap.set(g.type,f)}}dispose(){for(const g of this.debounceMap.values())clearTimeout(g);this.debounceMap.clear()}shouldBeRaised(g,f){return!(!this.configProvider.config.remoteUFD?.enabled||f>this.configProvider.config.remoteUFD.maxParticipantNumber||!this.configProvider.config.remoteUFD.list[g.type])}getState(g){return{type:"clientMediaUfd",level:"endpoint",content:JSON.stringify(g)}}},eo={reconnect:{metrics:["ReconnectAttempts","ReconnectConnectedCount","RetargetCompletedCount","TerminationReason_code","TerminationReason_subCode","UFDs"],Extensions:["StartTime","EndTime"]},rejectNegotiation:{metrics:["NetworkEvents","ErrorDetail","UFDs","RollbackNegotiation","TerminationReason_code","TerminationReason_subCode"],Extensions:["IceConnectionState","IceConnectionStatePrevious","StartTime","EndTime"]},visibilityHidden:qt.MEDIA_EVENT_FIELDS,lowBattery:qt.MEDIA_EVENT_FIELDS},to=class extends Ke{constructor(g){super(),this.configProvider=g}setDiagnosticsReport(g){this.diagnosticsReport=g}setEventType(g){if(!this.configProvider.config.smallCallTelemetry.enable)return;const f=Object.keys(this.configProvider.config.smallCallTelemetry.mediaUFDEventDictionary),S=this.getLastKnownMediaSessionStats();if(S&&(f?.forEach((f=>{if(f===g){const v=this.configProvider.config.smallCallTelemetry.mediaUFDEventDictionary[f],C={eventType:g,data:this.buildFromDictionary(S,v)};this.setTerminationCodeAndSubCodeToSuccess(C.data),this.event("sendSmallCallTelemetry").raise(C)}})),"reconnect"===g||"rejectNegotiation"===g||"visibilityHidden"===g||"lowBattery"===g)){const f={eventType:g,data:this.buildFromDictionary(S,eo[g])};void 0===f.data.metrics.TerminationReason_code&&this.setTerminationCodeAndSubCodeToSuccess(f.data),this.event("sendSmallCallTelemetry").raise(f)}}getEndCallSmallTelemetry(g){const f=this.getLastKnownMediaSessionStats(),S=this.buildFromDictionary(f,qt.MEDIA_EVENT_FIELDS);return g&&(S.metrics.TerminationReason_code=bi.CODE.SUCCESS,S.metrics.TerminationReason_subCode=bi.SUB_CODE.BEACON),{eventType:g?"tabClosed":"endCall",data:S}}getSmallTelemetryOnBatteryLow(){const g=this.getLastKnownMediaSessionStats(),f=this.buildFromDictionary(g,qt.MEDIA_EVENT_FIELDS);return this.setTerminationCodeAndSubCodeToSuccess(f),{eventType:"lowBattery",data:f}}getLastKnownMediaSessionStats(){if(!this.diagnosticsReport)return;const g=this.diagnosticsReport.rawRootRef.sessions.length;return this.diagnosticsReport.getSessionTelemetry(this.diagnosticsReport.rawRootRef.sessions[g-1]?.sessionId)}buildFromDictionary(g,f){const S={Extensions:{},metrics:{}};if(!g)return S;for(const v in f)g[v]&&(S[v]={},f[v].forEach((f=>{void 0!==g[v][f]&&(S[v][f]=g[v][f])})));return S}setTerminationCodeAndSubCodeToSuccess(g){void 0===g.metrics.TerminationReason_code&&(g.metrics.TerminationReason_code=bi.CODE.SUCCESS,g.metrics.TerminationReason_subCode=bi.CODE.SUCCESS)}},io=class extends Ke{constructor(g,f){super(),this.diagnostics=g,this.configProvider=f,this.hasSentLowBatteryEvent=!1,navigator?.getBattery?.().then((g=>{this.batteryManager=g,g.addEventListener("levelchange",this.onLevelChange.bind(this))}))}dispose(){this.batteryManager&&this.batteryManager.removeEventListener("levelchange",this.onLevelChange)}onLevelChange(g){const f=100*g.level;this.diagnostics.setBatteryLevel(f),f<=this.configProvider.config.lowBatteryThreshold&&!this.hasSentLowBatteryEvent&&(this.event("batteryStatusChanged").raise(f),this.hasSentLowBatteryEvent=!0)}},no=[1,2,9,10,11,12,30,27,28],ro="remote",so="remote",ao=class extends Ke{constructor(g,f){super(),this.isStreaming=g,this.mediaType=f}},oo=class _PluginlessCall2 extends Ke{constructor(g,f,S,v,C,_,T,I,b,A,P,R,M,w,O,D,N,k){super(S),this.signalingAgent=g,this.mediaAgent=f,this.logger=S,this.telemetryLoggers=v,this.currentUserSkypeIdentity=C,this.groupId=_,this.threadId=T,this.ecsProvider=A,this.trouterService=P,this.accountConfiguration=R,this.vdi3diagnostics=k,this.participants=[],this.isServerMuted=!1,this.isSpeakerMuted=!1,this.isVideoOn=!1,this.isScreenSharingOn=!1,this.callStartedAt=null,this.callHeldAt=null,this.conversationStartTime=null,this.callType=-1,this.failureType=2,this.isEmergency=!1,this.contentSharingSessions=[],this.endpoints={endpointDetails:[]},this.isPreheatEnabled=!1,this.localMediaStreams=[],this.enableRealtimeTelemetry=!1,this.isSharedLineAppearanceV2Activated=!1,this.enableCaptcha=!1,this.requestedHoldState=!1,this.mediaStateConfigurationHelper=new Or({mediaStates:[getMediaState(0,4)]}),this.canToggleAudio=!0,this.canToggleVideo=!0,this.connectCallPromise=Promise.resolve(),this.canToggleScreenSharing=!0,this.callUsesMixer=!1,this.isEscalationInProgress=!1,this.retryOutgoingRenegotiation={retry:!1,causeId:""},this.isHoldInProgress=!1,this.isMuteOnHold=!1,this.callSetupFailed=!1,this.isSomeoneSharing=!1,this.isSomeoneStreamingVideo=!1,this.activeTalkersHistory=[],this.callGotConnected=!1,this.mediaRelayWhiteListingIssue=!1,this.signalingSessionCallOptions=null,this.tsCallingTelemetryReported=!1,this.isCallSetupTelemetrySent=!1,this._isAudioStreamConnected=!1,this._wasAudioStreamConnected=!1,this._callInLobby=!1,this._callIsSetupComplete=!1,this._transferState=0,this._parkState=0,this._muteState=0,this._callCreationTime=(new Date).getTime(),this._commandUrlPresence=0,this._capabilities={canMuteOthers:!1,canUnmuteSelf:!1},this._spamRiskLevel=null,this._spamStirAttestation=null,this._callMode=0,this._isUpdatePropertiesSpecifiedAllowedByEcs=!1,this._deferUsingMicrotask=!1,this._enableResolveScreenSharingWhenNegotiationComplete=!1,this._publishedStatesModified=0,this._participantPublishedStatesMap={},this._endpointPublishedStatesMap={},this._participantChangedEventSkipConfig={skipParticipantsUpdatesOnCall:!0},this._dominantSpeakerChangedEventSkipConfig={skipDominantSpeakerUpdatesOnCall:!0},this.receiveOnlyAudioOnCallStart=!1,this.lastContributingSourceReport=Date.now(),this.instanceNumber=_PluginlessCall2.instanceCount++%1e3,this._enableMuteAsync=!1,this._enableUnmuteAsync=!1,this._enableEndpointMeetingRoleCheckForClientCapability=!1,this._enableUserMeetingRolesCheckForClientCapability=!1,this._enableAddModalityGeneric=!1,this._delayedElevationPending=!1,this._delayedElevationQueued=!1,this.maxVbssChannels=0,this.startVM=(g,f,S,v,C)=>this.signalingSession.startOutgoingCall(S,v,{voicemailResourcePath:f.callVoicemailStartOptions.voicemailResourcePath,voicemailItemId:f.callVoicemailStartOptions.voicemailItemId,callToVoicemail:!0},Date.now()-C,g),this.getSignalingSessionCallOptions=g=>{const f={suppressDialout:!g.callStartOptions.ringOthers,isPreheatOnly:1==(1&g.callStartOptions.preheatFlags),onBehalfOf:this.onBehalfOfMri,onBehalfOfUserDisplayName:this.onBehalfOfUserDisplayName,callQueueContext:g.callStartOptions?.callQueueContext,muted:1==(1&g.callStartOptions.muteFlags),invitationType:g.invitationType,participantsToNudge:g.participantsToNudge,routingFlags:g.callStartOptions&&g.callStartOptions.routingFlags,parkContext:g.parkContext,pickupCode:g.pickupCode,scenario:g.callStartOptions&&g.callStartOptions.scenario,callUsesMixer:this.callUsesMixer,clientEndpointCapabilities:g.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:g.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:g.meetingPreferences,alternateId:g.callStartOptions?g.callStartOptions.alternateId:null,meetingRegistrationId:g.callStartOptions?g.callStartOptions.meetingRegistrationId:"",participantPin:g.callStartOptions?g.callStartOptions.participantPin:"",additionalEndpointProperties:g.callStartOptions?.additionalEndpointProperties||null,publishedStates:g.callStartOptions?.publishedStates||null,targetApplicationType:g.callStartOptions?.targetApplicationType,isHuddleGroupCall:g.callStartOptions?.isHuddleGroupCall,captchaContentJson:g.callStartOptions?.captchaContentJson,customHeaderContext:g.callStartOptions?.customHeaderContext,participationPreferences:g.callStartOptions?.participationPreferences,callingLineIdentity:g.callStartOptions?g.callStartOptions.callingLineIdentity:null},S=g.callStartOptions?.invitationDataJson;if(S)try{f.invitationData=JSON.parse(S)}catch(g){throw new Error(`Invalid JSON in invitationData: ${S}`)}return f},this.startOutgoingCall=(g,f,S,v,C)=>this.signalingSession.startOutgoingCall(S,v,this.getSignalingSessionCallOptions(f),Date.now()-C,g),this.joinGivenConversation=(g,f,S,v,C,_)=>{const T=1==(1&f.callStartOptions.muteFlags),I=1==(1&f.callStartOptions.preheatFlags),b=f.callStartOptions?.invitationDataJson,A=f.callStartOptions?.sharedLineCallInvitationContentJson;this.logger.info(`[${g}][joinGivenConversation] muted=${T}, isPreheatOnly=${I},\n            sharedLineCallInvitationContentJson=${A}, invitationDataJson=${b},\n            captchaContentJson=${!!f?.callStartOptions?.captchaContentJson}`);const P={muted:T,isPreheatOnly:I,clientEndpointCapabilities:f.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:f.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:f.meetingPreferences,meetingRegistrationId:f.callStartOptions?f.callStartOptions.meetingRegistrationId:"",participantPin:f.callStartOptions?f.callStartOptions.participantPin:"",additionalEndpointProperties:f?.callStartOptions?.additionalEndpointProperties,applyServerMute:f?.applyServerMute,publishedStates:f?.callStartOptions.publishedStates,invitationData:f?.callStartOptions.invitationDataJson,captchaContentJson:f?.callStartOptions.captchaContentJson,callQueueContext:f?.callStartOptions.callQueueContext,participationPreferences:f?.callStartOptions.participationPreferences};if(A)try{P.sharedLineCallInvitationContent=JSON.parse(A)}catch(g){throw new Error(`Invalid JSON in sharedLineCallInvitationContent: ${A}`)}if(b)try{P.invitationData=JSON.parse(b)}catch(g){throw new Error(`Invalid JSON in invitationDataJson: ${b}`)}return this.signalingSession.joinGivenConversation(_,this.callId,S,v,Date.now()-C,P,g)},this.getParticipantByLegId=(g,f,S)=>{this.logger.info(`getMriByParticipantLegId[${S}] participantLegId ${g}`);for(const S of f.participants)for(const f of S.endpoints.endpointDetails)if(f&&f.participantId&&f.participantId===g)return S;return null},this.executeCallTransfer=(g,f,S,v)=>{this._setTransferState(1);const C=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,f,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return 0===S?this.signalingSession.transferCallAsync(g,"TransferTypeStandard",void 0,v,f):2===S&&this.signalingSession.transferCallAsync(g,"TransferTypeVoicemail",void 0,v,f),C},this.executeConsultCallTransfer=(g,f,S,v,C)=>{this._setTransferState(1);const _=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,v,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return this.signalingSession.consultTransferCallAsync(g,f,S,v,C),_},this.createUpdateParticipantPromise=(g,f)=>this._callOperationHandler.createPendingOperation("UpdateParticipantsProperties",g,f),this._getCallEndOperation=()=>this._callOperationHandler.hasPendingOperation("StopCall")?this._callOperationHandler.waitForOperation("StopCall"):this._callOperationHandler.hasPendingOperation("Reject")?this._callOperationHandler.waitForOperation("Reject"):this._callOperationHandler.hasPendingOperation("CallRedirect")?this._callOperationHandler.waitForOperation("CallRedirect"):Promise.resolve(),this._onAcknowledgeError=(g,f,S,v)=>{S.logFailure(g);let C,_={code:2,success:!1,fatal:!0},T=7;throw isPhaseError("SendAttach",g)&&(C={code:Fi.InternalServerError,subCode:xi.AttachFailed,phrase:Gi.AttachFailed}),isPhaseError("ProcessIncomingCallRequest",g)&&(C={code:Fi.NotAcceptable,subCode:xi.AttachActionFailed,phrase:Gi.BadNotificationPayload},_={code:0,success:!1,fatal:!0}),isOneOfPhaseErrors(zi,g)&&(T=47),g?.error&&g.error.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer&&(C={code:Fi.MediaError,subCode:xi.MediaOfferProcessingError,phrase:Gi.IncompatibleOffer}),this.callTelemetry.updateOperationData("Acknowledge",{phases:v,error:getPIISafeObject(g)},f),this._callOperationHandler.maybeRejectOperation("Acknowledge",_,void 0,f),this.stopInternal({rejectReason:C,causeId:f,terminatedReason:T}),_},this._onAcknowledgeSuccess=(g,f,S)=>(g.logSuccess("success"),this.callTelemetry.updateOperationData("Acknowledge",{phases:f},S),{code:1,success:!0}),this._processOfferedModalities=(g,f)=>{this.handleOfferedModalities(g,f);const S=this.callUsesMixer?void 0:{modalityOverride:g};return this.updateMediaModalities(S,f)},this._handleOfferProcessingError=(g,f,S)=>(S.logFailure(`handleOfferProcessingError=${g}`),g?.error?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer?(this.callTelemetry.recordEvent("IncompatibleOffer",void 0,f),this.signalingSession.supportsNewOfferRequest()?(this.newOfferRequestDeferred=new dt,this.attachToCallAndGetOffer.promise.then((()=>this.mediaSession.rejectNegotiationAsync(g.error,f))).then((()=>this.signalingSession.requestNewOffer(this.mediaSession.getAcceptedTypes(),f))).then((()=>this.newOfferRequestDeferred.promise)).then((g=>this.mediaSession.processOfferAsync(g,f))).catch((g=>(this.callTelemetry.recordEvent("NewOfferFailed",getPrintableObject(g),f),Promise.reject(g))))):Promise.reject(g)):Promise.reject(g)),this._trySendProvisionalMediaAnswer=g=>Promise.resolve(void 0).then((()=>this.mediaSession.createAnswerAsync(!0,g))).then((g=>g.blob?(this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",void 0,generateCauseId(),{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.signalingSession.setProvisionalAnswerAsync(g).then((()=>this.mediaAcknowledgmentOperation))):Promise.resolve(void 0))),this.checkForCallIdUpdate=(g,f)=>{if(this.callId!==g){this.logger.info(`[${f}][checkForCallIdUpdate] old=${this.callId}, new=${g}`),this.setCallId(g);try{this.event("callIdChanged").raise(this.callId)}catch(g){this.logger.error(`Error raising call ID change: ${g}`)}this.raiseChanged()}},this.handleRemoteParticipantStateInOneToOneCall=g=>{if(!this.callUsesMixer&&3===this.state){const f=this.participants[0];f&&f.setState(3,void 0,g)}},this.handleRemoteParticipantJoinedInOneToOneCall=(g,f)=>{if(!this.callUsesMixer&&3===this.state){const S=this.participants.filter((f=>f.id===g.id))[0];S?S.setState(3,void 0,f):this.logger.logFailure(`[${f}][handleRemoteParticipantJoinedInOneToOneCall]unable to find particpant ${scrubMriOrOmit(g.id)}`)}},this.handleRemoteParticipantStateInObservingCall=(g,f,S)=>{const v=f.isLobby;if(8===this.state){const f=v?7:3;g.setState(f,void 0,S)}},this.getTelemetryFromPhaseExecution=g=>{const f={phase:g.phase,phases:g.phases,code:g.error&&g.error.code,subCode:g.error&&g.error.subCode,message:g.error&&g.error.message,error:g.error};return(f.code||f.message)&&delete f.error,f},this._setTransferState=g=>{this.transferState!==g&&(this.logger.info(`Transfer: state set: ${g}`),this._transferState=g,this.callTelemetry.recordEvent("_SetTransferState",{state:g}),this.raiseChanged())},this._setParkState=g=>{this.parkState!==g&&(this.logger.info(`Parking: state set: ${g}`),this._parkState=g,this.callTelemetry.recordEvent("_SetParkState",{state:g}),this.raiseChanged())},this.prepareNegotiationResultForTelemtry=g=>({isComplete:g.isComplete,activeModalities:g.activeModalities,configuredModalities:g.configuredModalities,initiator:scrubMriOrOmit(g.initiator),attemptedModalities:g.attemptedModalities,offeredModalities:g.offeredModalities}),this.prepareTelemetryForOfferAnswer=g=>g&&g.mediaContent&&{isRenegotiation:!!g.renegotiation,isEscalation:!!g.mediaContent.isTwoPartyToMultiPartyEscalation,mediaTypes:g.mediaTypes,newOffer:g.mediaContent.newOffer},this.updateLocalParticipantEndpoints=g=>{const f=this.logger.createFnLogger("updateLocalParticipantEndpoints",""),S=[];(0,Ki.forEach)(g,(g=>{const f=convertSignalingEndpointDetails(g,this.getSelfClientEndpointCapabilities());S.push(f)})),this.endpoints.endpointDetails=S;const v=this.getDataChannelSourceId();-1!==v&&this.dataChannel&&this.dataChannel.setDataChannelSourceId(v),f.info(`selfEndpointDetails=${getPIISafeEndpointDetails(this.endpoints)}`)},this.handleParticipantsMutedUpdated=(g,f)=>{const S=this.logger.createFnLogger("handleParticipantsMutedUpdated",f);if(void 0!==g?.info){this.logger.info(`handleParticipantsMutedUpdated: number of infos: ${Object.keys(g.info).length}`);for(const f of Object.keys(g.info)){const v=this.getParticipant(f);v?v.handleServerMutedInfoUpdate(g.info[f]):S.info(`Cannot find local participant ${scrubMriOrOmit(f)}`)}}else S.info("Ignored, no mute participant info.")},this.handleSelfUnmuteUpdatedInfo=(g,f)=>{const S=this.logger.createFnLogger("handleSelfUnmuteUpdatedInfo",f);if(void 0!==g?.info)for(const v of Object.keys(g.info)){const C=g.info[v];if(v===this.localSignalingParticipant.id){const g=(0,Ki.find)(C,(g=>g.participantId===this.localSignalingParticipant.participantId));if(void 0===g){S.info(`Cannot find local participant ${scrubMriOrOmit(v)}`);continue}const _=(0,Ki.find)(this.localSignalingParticipant.endpointDetails,(f=>f.participantId===g.participantId));handleMuteUnmuteParticipantInfo(this.logger,_,g,!1)&&this.handleSelfServerMutedState(f)}}else S.info("Ignored, no unmute participant info.")},this.state=0,this.terminatedReason=0,this.callStats=new Mr,this.callDeviceManager=this.createCallDeviceManager(),this.callTelemetry=new Ii(this.logger,this._callCreationTime),this.collectMediaStatsDeferred=new dt,this.setCallId(I),this.setGroupId(_),this.setThreadId(T),this.setMessageId(M),this.setSkypeId(this.currentUserSkypeIdentity.id),this.setParticipantId(b),this.setCallOrigin(0),this.vdi3diagnostics&&this.callStats.setRpcSessionId(this.vdi3diagnostics.getRPCSessionId()),this.logger=this.logger.createChild((()=>{const g=(this.endpointId||"").substr(0,8),f=(this.participantId||"").substr(0,8);return`Web/${this.instanceNumber}[${this.callId}][${g}][${f}][${this.state}]`})),this._enableMuteAsync=this.ecsProvider.getEcsConfig("SkypeCalling","enableAsyncMute"),this._enableUnmuteAsync=this.ecsProvider.getEcsConfig("SkypeCalling","enableAsyncUnmute"),this._enableEndpointMeetingRoleCheckForClientCapability=this.ecsProvider.getEcsConfig("SkypeCalling","enableEndpointMeetingRoleCheckForClientCapability"),this._enableUserMeetingRolesCheckForClientCapability=this.ecsProvider.getEcsConfig("SkypeCalling","enableUserMeetingRolesCheckForClientCapability"),this._enableAddModalityGeneric=this.ecsProvider.getEcsConfig("SkypeCalling","enableAddModalityGeneric"),this.initializeSignalingSession(b),this.signalingSession.setLocationInfo(w,O,N),this.streamManager=new ls(this.participantId,null,this.callStats.localStats,this.logger),this.mediaAgent&&(this.dataChannel=new Ms(this.logger),this.dataChannel.on("remoteUserEventsReceived",((g,f)=>this.event("remoteUserEventsReceived").raise(g,f))),this.dataChannel.on("onDataChannelStateUpdated",(g=>{"Failed"===g&&(this.logger.error("onDataChannelStateUpdated: datachannel creation failed, will remove data modality"),this.mediaStateConfigurationHelper.removeModality(3),this.updateSignalingDSHMessageSubscription(!0),this.updateMediaModalities())})),this.screenSharingControl=new sa(this.logger,this.dataChannel,this,this.telemetryLoggers,this.ecsProvider,this.mediaAgent.getConfigProvider()),this.mediaAgent.handleSendMidCallTelemetry(this.sendMidCallTelemetry.bind(this)),this.remoteUFDHandler=new Za(this.logger.createChild("remoteUFDHandler"),this.mediaAgent.getConfigProvider()),this.smallCallTelemetry=new to(this.mediaAgent.getConfigProvider()),this.smallCallTelemetry.on("sendSmallCallTelemetry",(g=>this.reportSmallCallEvent(g))));const L={enableErrorConversion:this.ecsProvider.getEcsConfig("SkypeCalling","enableErrorConversion")};this._deferUsingMicrotask=this.ecsProvider.getEcsConfig("SkypeCalling","deferUsingMicrotask"),Vr.instance.setDeferToQueueMicrotask(this._deferUsingMicrotask),Vr.instance.setLogger(S),this.logger.info(`operationHandlerEcsConfig: ${JSON.stringify(L)}`),this._preferredMpLocation=this.ecsProvider.getEcsConfig("SkypeCalling","preferredMpLocation"),this.logger.debug(`preferredMpLocation: ${this._preferredMpLocation}`),this._isUpdatePropertiesSpecifiedAllowedByEcs=this.ecsProvider.getEcsConfig("SkypeCalling","enableUpdateParticipantsSpecified"),this._enableResolveScreenSharingWhenNegotiationComplete=this.ecsProvider.getEcsConfig("SkypeCalling","enableResolveScreenSharingWhenNegotiationComplete"),this._callOperationHandler=new Li(this.logger,this.callTelemetry,L,void 0,((g,f)=>{this.preconditions(g,f)})),this._participantOperationHandler=new Li(this.logger,this.callTelemetry,L),this.setMeetingData(D),this.initializeLiveStreamConfigProvider()}get callMode(){return this._callMode}get callId(){return this._callId}get endpointId(){return this._endpointId}get isHostless(){return this.signalingSession.isHostLessCall}get transferState(){return this._transferState}get parkState(){return this._parkState}get capabilities(){return this._capabilities}get publishedStates(){return this._publishedStates}get dataChannelAdapter(){return this.dataChannel}get participantId(){try{const g=this.signalingSession?.participantManager?.localParticipant?.participantId;this._participantId=g||this._participantId}catch(g){this.logger.error("Error updating participantId")}return this._participantId}get displayName(){return this.localSignalingParticipant.displayName}get role(){return this.localSignalingParticipant.role}get meetingRole(){return this.localSignalingParticipant.meetingRole}get advancedMeetingRole(){return this.localSignalingParticipant.advancedMeetingRole}get meetingRoles(){return this.localSignalingParticipant.meetingRoles}get maskedIdentityDetails(){return{isIdentityMasked:this.localSignalingParticipant.isIdentityMasked,maskedIdSeqNumber:this.localSignalingParticipant.maskedIdSeqNumber,maskedId:this.localSignalingParticipant.maskedId}}get participantType(){return this.localSignalingParticipant.participantType}get isMuted(){return 2===this._muteState||3===this._muteState}get tenantId(){return this.localSignalingParticipant.tenantId}get mediaLegId(){return this._mediaLegId}get isIncomingOneOnOneVideoCall(){return this.isOneToOneCall()&&this.isSomeoneStreamingVideo}get mediaStreams(){return this.streamManager.streams}get origin(){return this._origin}get propertyBag(){return this.localSignalingParticipant.propertyBag}get version(){return this.localSignalingParticipant.version}get isAudioStreamConnected(){return this._isAudioStreamConnected}set isAudioStreamConnected(g){this._isAudioStreamConnected!==g&&(this._isAudioStreamConnected=g,this._wasAudioStreamConnected=this._wasAudioStreamConnected||g,this.raiseChanged())}setMeetingRole(g){g!==this.localSignalingParticipant.meetingRole&&(this.logger.info(`changing self role to [${g}]`),this.localSignalingParticipant.meetingRole=g,this.event("meetingRoleUpdated").raise(g))}setAdvancedMeetingRole(g){g!==this.localSignalingParticipant.advancedMeetingRole&&(this.logger.info(`changing self advanced meeting role to [${g}]`),this.localSignalingParticipant.advancedMeetingRole=g,this.event("advancedMeetingRoleUpdated").raise(g))}setMeetingRoles(g){(0,Ki.isEqual)(g,this.localSignalingParticipant.meetingRoles)||(this.logger.info(`changing self meeting roles to [${g}]`),this.localSignalingParticipant.meetingRoles=g,this.event("meetingRolesUpdated").raise(g))}setParticipantType(g){g!==this.localSignalingParticipant.participantType&&(this.logger.info(`changing self participant user type to [${g}]`),this.localSignalingParticipant.participantType=g,this.event("participantTypeUpdated").raise(g))}setPropertyBag(g){g&&!(0,Ki.isEqual)(g,this.localSignalingParticipant.propertyBag)&&(this.logger.info(`changing self participant property bag to [${g}]`),this.localSignalingParticipant.propertyBag=g,this.event("propertyBagUpdated").raise(g))}setPropertyRosterVersion(g){g!==this.localSignalingParticipant.version&&(this.logger.info(`changing self participant property version to [${g}]`),this.localSignalingParticipant.version=g,this.event("propertyRosterVersionUpdated").raise(g))}setMaskedIdentityDetails(g=!1,f,S){this.localSignalingParticipant.isIdentityMasked===g&&this.localSignalingParticipant.maskedIdSeqNumber===f&&this.localSignalingParticipant.maskedId===S||(this.localSignalingParticipant.isIdentityMasked=g,this.localSignalingParticipant.maskedIdSeqNumber=f,this.localSignalingParticipant.maskedId=S,this.logger.info(`self participant masked identity details updated to [${JSON.stringify(this.maskedIdentityDetails)}]`),this.event("maskedIdentityDetailsUpdated").raise(this.maskedIdentityDetails))}setIsSomeoneStreamingVideo(g){this.logger.debug(`setting isSomeoneStreamingVideo to [${g}]`),this.isSomeoneStreamingVideo=g}setJoinAsStreamingUser(g){g!==this.joinAsStreamingUser&&(this.logger.info(`setting self join as streaming user to [${g}]`),this.joinAsStreamingUser=g)}setOtpIdentity(g){g!==this.otpIdentity&&(this.logger.info("setting self participant optIdentity"),this.otpIdentity=g)}get spamRiskLevel(){return this._spamRiskLevel}set spamRiskLevel(g){g&&(this._spamRiskLevel=g)}isMultiVBSSEnabled(){return this.maxVbssChannels>=1}get spamStirAttestation(){return this._spamStirAttestation}set spamStirAttestation(g){g&&(this._spamStirAttestation=g)}getScreenHandle(g){if(!this.sharedScreenHandle){const f=!!this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled,S=!!this.mediaSession&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&!this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing,v=this.mediaStateConfigurationHelper.isSending(0)&&S&&f,C=3===g?.getType()?g?.getDeviceId():void 0,_=this.callDeviceManager.getDeviceManager(getAgentMediaType(2));_.setAudioSharingRequested(v),this.sharedScreenHandle=_.createDevicesHandle({audio:v,sharing:!0},"pluginlessCall:getScreenHandle()",C),this.sharedScreenHandle.on("onStreamStateChanged",((g,f)=>this.onSharingStreamStateChanged(g)))}return this.sharedScreenHandle}setCallOrigin(g){this.logger.info(`Set call origin to ${g}`),this._origin=g,this.callTelemetry.setCallOrigin(g),this.callTelemetry.recordEvent("_SetCallOrigin",{origin:g})}setMediaLegId(g){this._mediaLegId=g,this.callStats.setMediaLegId(g)}setCallId(g){this.callTelemetry.setCallId(g),this.callStats.setCallId(g),this._callId=g}setEndpointId(g){this._endpointId=g,this.logger.info(`[endpointId=${truncate(this._endpointId,8)}]`),this.callTelemetry.setEndpointId(g),this.callStats.setEndpointId(g)}setFailureType(g){this.callTelemetry.setFailureType(g),this.failureType=g}setParticipantId(g){this._participantId!==g&&(this._participantId=g,this.logger.info(`[participantId=${this._participantId}]`),this.callTelemetry.setParticipantId(this.participantId),this.event("callLegIdChanged").raise(this.participantId))}setDisplayName(g,f=generateCauseId()){this.logger.info(`[${f}][setDisplayName] displayName=${truncate(g,4)}`),this.localSignalingParticipant.displayName=g,"anonymous"===this.participantType&&(this.callStats.setDisplayName(g),this.callTelemetry.setDisplayName(g),this.signalingSession.setDisplayName(g))}setCallerMri(g){this.callerMri=g,this.logger.info(`[callerMri=${scrubMriOrOmit(this.callerMri)}]`)}setDisplayNameSource(g){this.displayNameSource=g,this.logger.info(`[displayNameSource=${this.displayNameSource}]`)}setTransferorMri(g){const f=stripMriAliases(g);f!==this.transferorMri&&(this.transferorMri=f,this.logger.info(`transferorMri: ${scrubMriOrOmit(this.transferorMri)}`),this.raiseChanged())}setGroupId(g,f=generateCauseId()){this.logger.info(`[${f}][setGroupId] groupId=${scrubMriOrOmit(g)}`),this.groupId!==g&&(this.groupId=g,this.callTelemetry.setGroupId(g),this.event("groupIdChanged").raise(g))}setMeetingData(g){if(g){if(g.meetingCode&&(!this.meetingData||this.meetingData&&g.meetingCode!==this.meetingData.meetingCode)){const f=g.meetingCode;this.logger.info(`[setMeetingData] meetingCode=${!!f}`),this.callTelemetry.setMeetingCode(f),this.signalingSession.setMeetingCode(f)}if(g.meetingUrl&&(!this.meetingData||this.meetingData&&g.meetingUrl!==this.meetingData.meetingUrl)){const f=g.meetingUrl.split("?")[0];this.logger.info(`[setMeetingData] meetingUrl=${!!g.meetingUrl}`),this.callTelemetry.setMeetingUrl(f),this.signalingSession.setMeetingUrl(f)}}this.meetingData=g}setHuddleGroupCall(g){this.isHuddleGroupCall!==!!g&&(this.logger.info(`[setHuddleGroupCall] new isHuddleGroupCall=${g}`),this.isHuddleGroupCall=g,this.callTelemetry.setIsHuddleGroupCall(!0))}onConversationStartTimeChanged(g,f=generateCauseId()){if(this.logger.info(`onConversationStartTimeChanged: Conv start time=${g}`),g&&this._rawConversationStartTime!==g){this.logger.info(`[${f}][onConversationStartTimeChanged] rawConvStartTime=${g}`);try{this.conversationStartTime=new Date(g),this._rawConversationStartTime=g,this.callTelemetry.setConversationStartTime(g)}catch(f){this.logger.warn(`Failed to parse the raw conv start timestamp. Error: ${f}, rawConvStartTime: ${g}`)}}}setComplianceRecordingContent(g,f){try{if(!(0,Ki.isEqual)(this.complianceRecordingContent,f)){this.complianceRecordingContent=f;const S=f?JSON.stringify(f):"";this.callTelemetry.setComplianceRecordingContentLength(S.length),this.logger.info(`[${g}][setComplianceRecordingContent] complianceRecordingContentLength=${S.length}`)}}catch(f){this.logger.error(`[${g}][setComplianceRecordingContent] ${f}`)}}setThreadId(g,f=generateCauseId()){this.threadId!==g&&(this.logger.info(`[${f}][setThreadId] threadId=${getLoggableThreadId(g)}`),this.threadId=g,this.callTelemetry.setThreadId(g))}setBackroomThreadId(g,f=generateCauseId()){this.backroomThreadId!==g&&(this.logger.info(`[${f}][setBackroomThreadId] backroomThreadId=${getLoggableThreadId(g)}`),this.backroomThreadId=g,this.callTelemetry.setBackroomThreadId(g))}setStreamThreadId(g,f=generateCauseId()){this.streamThreadId!==g&&(this.logger.info(`[${f}][setStreamThreadId] streamThreadId=${getLoggableThreadId(g)}`),this.streamThreadId=g,this.callTelemetry.setStreamThreadId(g))}setLobbyThreadId(g,f=generateCauseId()){this.lobbyThreadId!==g&&(this.logger.info(`[${f}][setLobbyThreadId] lobbyThreadId=${getLoggableThreadId(g)}`),this.lobbyThreadId=g,this.callTelemetry.setLobbyThreadId(g))}setMessageId(g,f=generateCauseId()){this.logger.info(`[${f}][setMessageId] messageId=${scrubMriOrOmit(g)}`),this.messageId=g,this.callTelemetry.setMessageId(g)}setSkypeId(g,f=generateCauseId()){this.skypeId!==g&&(this.logger.info(`[${f}][setSkypeId]`),this.skypeId=g,this.callTelemetry.setSkypeId(g))}setCallType(g,f){const S=this.logger.createFnLogger("setCallType",f);S.info(`current=${this.callType}, newValue: ${g}`),2!==this.callType||1!==g?g!==this.callType&&(this.callType=g,this.callTelemetry.setCallType(g),2===g&&this.callStats.localStats.call.event(2),this.raiseChanged()):S.logFailure("De-escalating to P2P should not happen!")}setConversationType(g,f){this.logger.createFnLogger("setConversationType",f).info(`current=${this.conversationType}, newValue=${g}`),g!==this.conversationType&&(this.conversationType=g,this.callTelemetry.setConversationType(g),this.raiseChanged())}setCallUsesMixer(g,f){this.callUsesMixer!==!!g&&(this.logger.info(`[${f}][setCallUsesMixer] new value=${g}`),this.callUsesMixer=g,this.callTelemetry.recordEvent("_CallUsesMixer",{newValue:g},f),this.dataChannel.setConfigProviderView(this.mediaSession?.getSessionConfig()))}_setMaxVbssChannels(g,f){this.logger.createFnLogger("MaxVbssChannels",f).info(`current=${this.maxVbssChannels}, newValue=${g}`),g!==this.maxVbssChannels&&(this.maxVbssChannels=g,this.callTelemetry.recordEvent("_setMaxVbssChannels",{MaxVbssChannels:g},f),this.raiseChanged())}setIsEscalationInProgress(g,f){this.logger.info(`[${f}][setIsEscalationInProgress] currentValue=${this.isEscalationInProgress}, newValue=${g}`),this.isEscalationInProgress=g,this.allowScreenSharingControl()&&this.screenSharingControl.setIsEscalationInProgress(g),this.callTelemetry.recordEvent("_EscalationInProgress",void 0,f)}setFromApplicationType(g,f){g&&(this.fromApplicationType=g,this.callTelemetry.recordEvent("_SetFromApplicationType",{fromApplicationType:g},f))}setEnableCaptcha(g){g!==this.localSignalingParticipant.enableCaptcha&&(this.logger.info(`setting self participant to enable captcha to [${g}]`),this.localSignalingParticipant.enableCaptcha=g,this.enableCaptcha=g)}processCallStartOptions(g,f){const S=this.logger.createFnLogger("_ProcessCallStartOptions",f);try{1&g.preheatFlags&&(this.isPreheatEnabled=!0)}catch(g){S.logFailure(g)}}getlocalScreenShareStream(){return(0,Ki.find)(this.localMediaStreams,(g=>2===g.mediaType))}setMeetingLayout(g,f){throw new Error("Method not implemented.")}async selectDevices(g){this.callDeviceManager.isVirtualDeviceEnabled?this.callDeviceManager.selectDevices(g):this.logger.error("allowVirtualDeviceInCall not enabled.")}async getSelectDevices(){return this.callDeviceManager.getSelectedDevices()}createStage(g){throw new Error("Method not implemented.")}updateDisplayName(g){this.logger.info("updating displayName"),this.setDisplayName(g),this.signalingSession.participantManager.localParticipant.displayName=g}init(g){if(this.logger.info(`init callInitOptions:${getPIISafeCallInitOptions(g)}`),this.signalingSessionCallOptions={teamsMessageId:g.messageId,enableGroupCallMeetupGeneration:g.enableGroupCallMeetupGeneration,meetingInfo:g.meetingInfo,emergencyContent:g.emergencyContent?JSON.parse(g.emergencyContent):void 0,broadcastContext:g.broadcastContext,endpointMetadata:g.endpointMetadata},this.setMessageId(g.messageId),this.onBehalfOfMri=g.onBehalfOf,this.onBehalfOfUserDisplayName=g.onBehalfOfUserDisplayName,g.threadId&&(this.setThreadId(g.threadId),this.signalingSession.setThreadId(g.threadId)),this.groupId&&this.signalingSession.setGroupId(this.groupId),this.signalingSession.setCallOptions(this.signalingSessionCallOptions),g.transferContext){switch(this.logger.info("Transfer: Call.init, set transferContext",scrubITransferContext(g.transferContext)),this.signalingSession.setTransferContext(g.transferContext.context),g.transferContext.transferType){case 1:this.setCallOrigin(2);break;case 0:this.setCallOrigin(1);break;case 2:this.setCallOrigin(3);break;default:throw new Error(`TransferType: ${g.transferContext.transferType} doesn't have a switch option`)}g.transferContext.context.callAcceptanceCallback?this._transferredCallAcceptanceCallback=g.transferContext.context.callAcceptanceCallback:this.logger.info("[failed]Transfer: Missing transferred call acceptance callback"),g.transferContext.transferorMri&&this.setTransferorMri(g.transferContext.transferorMri)}this.setIsEmergency(!!g.isEmergency),this.raiseChanged()}async initAsync(g){return this.init(g)}getIncomingRawAudioStream(g=generateCauseId()){if(!this.mediaSession)throw this.logger.error("can not execute getIncomingRawAudioStream as there is no mediaSession"),new Error("NoMediaSession");return this.mediaSession.getIncomingRawAudioStream(g)}getUnmixedAudioProvider(){return this.unmixedAudioProvider?Promise.resolve(this.unmixedAudioProvider):Promise.reject("No audio provider available")}setDeviceManager(g){}async startVideo(g,f=generateCauseId()){return this.startStopVideo(!0,f,g)}async stopVideo(g,f=generateCauseId()){return this.startStopVideo(!1,f,g)}async dumpVideoSourceImages(){return Promise.reject(60)}async hold(g,f=generateCauseId(),S,v){const C=this.logger.createFnLogger("Hold",f);return C.info(`[Hold][${f}] negotiationTag ${g} hold options: ${safeJsonStringify(S)}`),4===this.state?(C.logFailure("Trying to put a call on hold which is already held state, early resolving the promise"),Promise.resolve(void 0)):S?.isLocal?this.localHold(f,S,v):this.holdWithRenegotiate(f,S)}async holdWithRenegotiate(g,f){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,g,f):(this.logger.logFailure(`[Hold][${g}] Trying to hold a call in an invalid state: ${this.state}`),Promise.reject(`Trying to hold a call in an invalid state: ${this.state}`))}async localHold(g,f,S){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,g,f,S):(this.logger.logFailure(`[LocalHold][${g}] Trying to hold a call in an invalid state: ${this.state}`),Promise.reject(`Trying to hold a call in an invalid state: ${this.state}`))}async unhold(g,f=generateCauseId()){const S=this.logger.createFnLogger("Unhold",f);return 3===this.state?(S.logFailure("Trying to resume a call which is already in connected state, early resolving the promise"),Promise.resolve(void 0)):4===this.state?(S.info(`current hold state ${this.requestedHoldState}`),this.setHold(!1,f)):(S.logFailure(`Trying to resume a call in an invalid state: ${this.state}`),Promise.reject(`Trying to resume a call in an invalid state: ${this.state}`))}canMerge(g,f){const S=g.isOneToOneCall(),v=3===this.state,C=4===g.state,_=S&&v&&C;return this.logger.info(`[${f}][canMerge] Call ${g.callId} isOneToOne ${S} isCallConnected ${v} call.state ${this.state} isMergeOnHold ${C} mergeCall.state ${g.state} CanMerge result: ${_}`),_}async updateEndpointMetadata(g,f=generateCauseId()){return this.signalingSession.updateEndpointMetadata(g,f)}async sendDtmfTone(g){if(this.mediaSession){const f=this.toneToString(g);return f?(this.logger.info(`[${causeId}][sendDtmfTone]DtmfTone: <omitted>`),Promise.resolve(this.mediaSession.sendDtmf(f))):Promise.reject(new Error("Unsupported DtmfTone"))}return Promise.reject(new Error("no mediaSession"))}async setAudioUsageMode(g){return Promise.reject(60)}async setAudioMidcallConfig(g,f){return Promise.reject(60)}async setAudioMidcallConfigJson(g,f=generateCauseId()){if(!g)return Promise.reject(60);isDefined2(g.enableSpatialAudio)&&this.mediaSession?.configureSpatialAudio(g.enableSpatialAudio,f),g.noiseSuppressionMode&&await this.setNoiseSuppressionMode(g.noiseSuppressionMode,g.enableAEC)}async setParticipantSpatialAudioPositions(g,f=generateCauseId()){const S=g.map((g=>({sourceId:this.participants.find((f=>f.id===g.participantId))?.audio.id,x:g.x,y:g.y})));return this.mediaSession?.setParticipantSpatialAudioPositions(S,f)}async setNoiseSuppressionMode(g,f){return this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe||this.mediaSession.getSessionConfig().config.wasmdns.enableNoiseSuppression?"Auto"===g?this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe?this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaSession.getSessionConfig().config.wasmvqe.defaultVqeMode)):this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(this.mediaSession.getSessionConfig().config.wasmdns.noiseSuppressionMode,f))):this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe?this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(g,this.mediaSession.getSessionConfig().config.wasmvqe.enableAec))):this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(g,f))):Promise.resolve()}setInitialTelemetry(g,f,S,v){let C,_,T,I,b;switch(g){case"Subscribe":case"SubscribeWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("SUBSCRIBE"),S||this.callTelemetry.setOperationVariant(g,"CCWM"),this.signalingSession.setInitialTelemetry(g,{correlationId:this.callId,causeId:v,conversationServiceUrl:S});break;case"Acknowledge":0!==this.state&&8!==this.state&&this.callTelemetry.maybeRecordOperationSuccess(g,{code:4}),this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("callee"),this.signalingSession.setInitialTelemetry(g,{causeId:v});break;case"JoinCall":case"JoinWithMeetingData":this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("join"),1&f.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(g,"Preheat"),C=this.telemetryDataFromCallStartOptions(f.callStartOptions),C&&this.callTelemetry.updateOperationData(g,C,v),_=1==(1&f.callStartOptions.muteFlags),T=1==(1&f.callStartOptions.preheatFlags),I={muted:_,isPreheatOnly:T},this.signalingSession.setInitialTelemetry(g,{correlationId:this.callId,causeId:v,conversationServiceUrl:S,joinCallOptions:I,offerGenerationTime:Date.now()-f.callStartTime});break;case"StartCall":case"StartWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),1&f.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(g,"Preheat"),C=this.telemetryDataFromCallStartOptions(f.callStartOptions),C&&this.callTelemetry.updateOperationData(g,C,v),b=f.callStartOptions,this.signalingSession.setInitialTelemetry(g,{correlationId:this.callId,causeId:v,conversationServiceUrl:S,callStartOptions:b,offerGenerationTime:Date.now()-f.callStartTime});break;case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),this.signalingSession.setInitialTelemetry(g,{correlationId:this.callId,causeId:v,conversationServiceUrl:S,startCallOptions:f.callStartOptions,offerGenerationTime:Date.now()-f.callStartTime})}}async setHold(g,f,S,v){const C=this.logger.createFnLogger("setHold",f,`hold=${g}`);if(!this.canToggleAudio||this.callHoldResumeDeferred)return Promise.reject(new Error("can not set hold as it is already in progress"));this.callHoldResumeDeferred=new dt,this.isHoldInProgress=g,this.canToggleAudio=!1,this.canToggleVideo=!1,this.canToggleScreenSharing=!1,this.requestedHoldState=g;const always=()=>{this.canToggleAudio=!0,this.canToggleScreenSharing=!0,this.canToggleVideo=!0};C.info(`start, holdOptions: ${JSON.stringify(S)}`);const _=this.callHoldResumeDeferred.promise,T=g?"Hold":"Unhold",I={debugContent:{clientScenario:this.convertClientScenario(v)}};try{if(g?this.isMuteOnHold=S&&S.isLocal&&5!==this.state:this.prepareModalitiesForResume(f),!this.isMuteOnHold){const g=await this.updateMediaModalities(void 0,f);this.updateMediaState(g,f),this.updateScreenSharingState(g,f)}g&&(this.prepareModalitiesForHold(f),5===this.state&&this.finishCallHoldResume(),this.setCallState(4,f)),this.isMuteOnHold&&this.setMuteOnHold(g,f),always();const v={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(T,v,null,f,I)}catch(S){this.callTelemetry.recordOperationFailure(T,{error:getPIISafeObject(S)},null,f,I),C.logFailure(S),always(),this.callHoldResumeDeferred?.reject(new Error(`Failed setting hold state to ${g}`)),this.callHoldResumeDeferred=null}return _}transferCall(g){return this.logger.warn("transferCall is deprecated, please use callBlindTransfer instead"),this.callBlindTransfer(g)}callBlindTransfer(g,f=generateCauseId(),S){return this.executeCallTransfer(g,f,0,S)}callSafeTransfer(g,f=generateCauseId(),S){return this.executeCallTransfer(g,f,0,S)}transferCallToVoicemail(g,f=generateCauseId()){return this.executeCallTransfer(g.transferTargetMri,f,2,void 0)}callConsultativeTransfer(g,f=generateCauseId(),S,v){const C=this.logger.createFnLogger("ConsultativeTransfer",f);let _;g.participants.length>1?(_=this.getParticipantByLegId(S,g),_||(C.warn("getParticipantByLegId did not find a match in the participants list, defaulting to first participant"),_=g.participants[0])):_=g.participants[0];const T=_&&_.acceptedBy||_&&_.id;return C.info(`transferTargetParticipantLegId: ${S} targetMri: ${scrubMriOrOmit(T)}`),this.executeConsultCallTransfer(g.callId,T,S,f,v)}async consultativeTransferWithPickupCode(g,f){const S=this.logger.createFnLogger("ConsultativeTransferWithPickupCode",f);if(S.info(`pickup code: ${g}`),!g||isNaN(Number(g)))return S.info("pickup code cannot be empty"),Promise.reject(getRejectTransactionEnd("TransactionDisallowed"));const v=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,f,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),C=`4:${fi.SERVER_HOLD}`,_={unparkContent:{pickupCode:Number(g)}},T={disableForwardingAndUnanswered:!1};return this.signalingSession.transferCallAsync(C,"TransferTypeStandard",_,T,f),v}callRedirect(g,f=generateCauseId()){return this.logger.createFnLogger("CallRedirect",f).info(`redirectOptions: ${JSON.stringify(g)}`),this.stopInternal({terminatedReason:75,redirectOptions:g,causeId:f}).then((()=>({code:Fi.CallRedirected,subCode:xi.CallRedirectedSuccess,phrase:Gi.CallEndReasonRedirected,resultCategories:["Success"]})))}convertParkContext(g){switch(g){case 1:return"sharedLinePark";case 4:return"sharedLineParkV2";case 0:return"teamPark";case 3:return"serverHoldV2";case 5:return"callPark";default:return"serverHold"}}convertClientScenario(g){switch(g){case 0:return"breakoutRoom";case 1:return"musicOnHoldV2";case 2:return"sharedLineAppearanceV2";default:return}}park(g,f=generateCauseId()){const S=this.convertParkContext(g);return this.logger.info(`[${f}] [ParkCall] start -  context ${g} parkType ${S}`),5===g?(this.callTelemetry.recordOperation(`${getParkTypeName(S)}`,f),this._pendingParkPromise=this._callOperationHandler.createPendingOperation("CallParkV2",void 0,f)):this._pendingParkPromise=this._callOperationHandler.waitForOperation("ParkCall"),"serverHoldV2"!==S&&"callPark"!==S&&this._setParkState(1),this.signalingSession.parkCallAsync(S,f).catch((g=>{this.logger.info(`[${f}] [ParkCall] error in parkCallAsync (synchronous error) : ${getPIISafeObject(g)}. Hold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("ParkCall",{error:getPIISafeObject(g)},f)})),this._pendingParkPromise}async unpark(g,f){const S=this.convertParkContext(g);return this.logger.info(`[${f}] [UnparkCall] start -  context ${g} parkType ${S}`),this._pendingUnparkPromise=this._callOperationHandler.waitForOperation("UnparkCall"),this.signalingSession.unparkAsync(S,f).catch((g=>{this.logger.info(`[${f}] [UnparkCall] error in unparkAsync (synchronous error) : ${getPIISafeObject(g)}. Unhold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UnparkCall",{error:getPIISafeObject(g)},f)})),this._pendingUnparkPromise}getServerHoldLocation(){return this._pendingParkPromise.then((()=>(this.logger.info(`getServerHoldLocation ${this.serverHoldLocation}`),this.serverHoldLocation)))}getParkAdditionalContextJson(){return this._pendingParkPromise.then((()=>(this.logger.info(`getParkAdditionalContextJson ${this.parkAdditionalContextJson}`),this.parkAdditionalContextJson)))}getJoinBlob(){return Promise.resolve(JSON.stringify({conversationUrl:this.signalingSession.getConversationUrl(),conversationId:this.callId}))}getTechnicalInformationJson(){return Promise.resolve(JSON.stringify(this.mediaSession.getCallTechnicalInfo()))}isOneToOneCall(g=!1){if(g){const g=(this.state,[0,1]);return 1===this.callType&&g.includes(this.participants.length)}return 1===this.callType&&1===this.participants.length}setMuteOnHold(g,f){this.mediaSession.muteHold(g,f),g||(this.computeCallState(f),this.isMuteOnHold=!1),this.finishCallHoldResume()}finishCallHoldResume(g){g?this.callHoldResumeDeferred?.reject(g):this.callHoldResumeDeferred?.resolve(),this.isHoldInProgress=!1,this.callHoldResumeDeferred=null}computeCallState(g){let f=3;this._callInLobby?f=10:this.signalingSession.participantManager.localParticipant.isStaging&&(f=13),this.logger.info(`[${g}][computeCallState] the call state will be set to ${f}`),this.setCallState(f,g)}async prepareModalitiesForResume(g){this.mediaStateConfigurationHelper.isSending(1)&&await this.turnOnLocalVideoPreview(g)}async prepareModalitiesForHold(g){await this.turnOffLocalVideoPreview(g)}updateMediaState(g,f){this.setVideoOn(g.video===this.mediaAgent.constants.MEDIA_STATE.sendReceive||g.video===this.mediaAgent.constants.MEDIA_STATE.send,f),this.setAudioOn(g.audio===this.mediaAgent.constants.MEDIA_STATE.sendReceive||g.audio===this.mediaAgent.constants.MEDIA_STATE.send,f)}updateScreenSharingState(g,f){this.setScreenSharingOn(g.sharing===this.mediaAgent.constants.MEDIA_STATE.send,f)}onSharingStreamStateChanged(g){const f=generateCauseId();this.logger.info(`[${f}] Sharing stream state moved to ${g}`);const S={mediaType:2,mediaDirection:1,mediaStreamState:_PluginlessCall2.streamingStatetoMediaStreamState(g)};this.event("mediaStreamStateChanged").raise(S),this.callStats.localStats.screenShare.streamStateChanged(g),"stopped"===g&&(this.canToggleScreenSharing=!0,this.stopScreenSharing(),"screenSharingCall"!==this.conversationType||this.participants.some((g=>3===g.state))||this.stop(!0,f))}async startScreenSharing(g,f,S,v=generateCauseId()){this.allowScreenSharingControl()&&(this.screenSharingControl.isInternalViewerControlEnabled()&&this.screenSharingControl.shutdownControlForViewer(),this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.initControlForSharer(S));const C=this.logger.createFnLogger("StartScreenSharing",v);return C.info(`started. negotiationTag is ${S}`),this.canToggleScreenSharing?this.isScreenSharingOn?(C.logSuccess("Resolving early because screen sharing is already on"),Promise.resolve()):(this.screenSharingRenegotiationDeferred&&(C.logFailure("called before the renegotiation deferred for the previous one has been closed"),this.screenSharingRenegotiationDeferred.resolve()),this.screenSharingRenegotiationDeferred=new dt,this.callStats.localStats.newSession(2),this.callStats.localStats.screenShare.start(),this.mediaStateConfigurationHelper.isDisabled(2)&&C.info("sharing modality was skipped till now. Adding it now"),this.canToggleScreenSharing=!1,this.callStats.localStats.screenShare.event(0),this.getScreenHandle(g).acquire().then((()=>(C.logSuccess("sharing stream acquired"),this.mediaStateConfigurationHelper.enableModality(2),this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this._delayedElevationPending&&!this._delayedElevationQueued?this.triggerDelayedReconnectIfNeeded(v):Promise.resolve()))).then((()=>this.updateMediaModalities(void 0,v,S))).then((()=>(C.logSuccess("updateMediaModalities done"),this.callStats.localStats.screenShare.negotiationStateChanged("started"),this.setScreenSharingOn(!0,v),this.canToggleScreenSharing=!0,this.screenSharingRenegotiationDeferred.promise))).then((()=>{this.enableControlInjector(),this.callStats.localStats.screenShare.negotiationStateChanged("completed")})).catch((g=>{this.callTelemetry.updateOperationData("StartScreenSharing",{error:getPIISafeObject(g)},v),this.setScreenSharingOn(!1,v),this.mediaStateConfigurationHelper.removeModality(2),this.canToggleScreenSharing=!0,this.disposeSharingScreenHandle();const f=g.error;throw f&&f.code===Fi.GlareError?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),C.logFailure("starting screen sharing failure with reason glare")):"ScreenSharingStopped"===g.reason?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","sharingStopped"),C.logFailure("expected starting screen sharing failure with reason stopped")):(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","other"),C.logFailure(g)),g}))):Promise.reject(new Error("cannot start screen sharing"))}async stopScreenSharing(g,f,S=generateCauseId()){const v=this.logger.createFnLogger("StopScreenSharing",S);if(v.info(`started. negotiationTag is ${f}`),!this.canToggleScreenSharing)throw v.logFailure("cannot stop screen sharing"),new Error("cannot stop screen sharing");if(this.isScreenSharingOn||this._callOperationHandler.hasPendingOperation("StartScreenSharing")){this.screenSharingRenegotiationDeferred&&(this.screenSharingRenegotiationDeferred.reject({reason:"ScreenSharingStopped"}),this.screenSharingRenegotiationDeferred=null),this.mediaStateConfigurationHelper.removeModality(2),this.canToggleScreenSharing=!1,this.allowScreenSharingControl()&&this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.shutdownControlForSharer(),await this.updateMediaModalities(void 0,S,f),this.canToggleScreenSharing=!0,this.callStats.localStats.screenShare.stop(),this.disposeSharingScreenHandle(),this.mediaAgent.getDeviceManager().shareSystemSound(!1),this.mediaAgent.getDeviceManager().setAudioSharingRequested(!1);try{this.setScreenSharingOn(!1,S)}catch(g){throw v.logFailure(g),this.callTelemetry.updateOperationData("StopScreenSharing",{error:getPIISafeObject(g)},S),g}}else v.logFailure("screensharing is not on, ignore this operation")}async startDataChannel(g,f=generateCauseId()){if(!this.allowDataChannel())throw new Error("startDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.enableModality(3),await this.updateMediaModalities({},f)}async stopDataChannel(g,f=generateCauseId()){if(!this.allowDataChannel())throw new Error("stopDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.removeModality(3),await this.updateMediaModalities({},f)}allowDataChannel(){return this.mediaSession?!!this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled&&(this.isOneToOnePSTNCall()?this.mediaSession.getSessionConfig().config.enableDataChannelPstn:this.mediaSession.getSessionConfig().config.enableDataChannel):(this.logger.warn("datachannel not allowed as there is no mediaSession"),!1)}isInitialSignalingDSHSubscriptionEnabled(){const g=this.mediaSession?.getSessionConfig()?.config;return g?!this.allowDataChannel()||g.enableInitialSignalingDSHSubscription:(this.logger.warn("Initial signaling dsh subscription is enabled as there is no mediaSession, sessionConfig or sessionConfig.config"),!0)}allowScreenSharingControl(){return this.screenSharingControl?.isScreenSharingControlEnabled()&&this.allowDataChannel()}updateSignalingDSHMessageSubscription(g){this.signalingSession.updateDominantSpeakerHistoryMessageSubscription(g),g&&this.mediaSession?.getDiagnostics?.().dshDiagnostics.setCurrentActiveStrategy("signaling")}async sendUserEvents(g,f){return this.dataChannel.sendUserEvents(g,f)}async shareSystemSound(g,f=generateCauseId()){const S=this.logger.createFnLogger("ShareSystemSounds",f,`shareSystemSound=${g}`);if(!(this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing))return S.error("shareSystemSound not allowed"),Promise.reject(60);try{return void this.mediaAgent.getDeviceManager().shareSystemSound(g)}catch{return S.error("shareSystemSound failed with device error"),Promise.reject(58)}}async mute(g=generateGuid()){return this.isMuted?Promise.reject(getRejectTransactionEnd("TransactionDisallowed")):this.muteUnmute(!0,g)}async unmute(g=generateGuid()){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")&&await this._callOperationHandler.waitForOperation("_PromotionToRealtime"),this.muteUnmute(!1,g)}async muteSpeaker(g=generateCauseId()){return this.muteUnmuteSpeaker(!0,g)}async unmuteSpeaker(g=generateCauseId()){return this.muteUnmuteSpeaker(!1,g)}async getSpeakerVolume(g=generateCauseId()){return await this.mediaSession.getSpeakerVolume(g)}async setSpeakerVolume(g,f=generateCauseId()){return this.mediaSession.setSpeakerVolume(g,f)}async muteParticipants(g,f,S=generateGuid()){const v=this.logger.createFnLogger("MuteParticipants",S,`muteScope=${g}`);v.info(`callParticipants count=${f.length}`);const C=_PluginlessCall2.convertMuteScope(g);if(void 0===C)return v.logFailure(`Unrecognized ${g}`),Promise.reject(new Error("Unrecognized muteScope"));if(callStateIsAnyOf(this.state,[11,12]))return v.logFailure("Can not mute/unmute during preheat call"),Promise.reject(60);const _=[];return f.forEach((g=>{_.push(g.id)})),this.signalingSession.muteAsync(C,_,S).then((g=>this.handleParticipantsMutedUpdated(g,S))).catch((g=>(this.callTelemetry.updateOperationData("MuteParticipants",{error:getPIISafeObject(g)},S),v.logFailure(g),g?.endCode?Promise.reject(g.endCode):Promise.reject(g))))}async startAudio(g,f=generateCauseId()){const S=this.logger.createFnLogger("StartAudio",f);if(this.receiveOnlyAudioOnCallStart=!1,3!==this.state)return S.logFailure("Cannot startAudio when call is not connected"),Promise.reject(60);if(this.mediaStateConfigurationHelper.enableModality(0),this.callUsesMixer&&this.mediaStateConfigurationHelper.removeModality(1),this.mediaStateConfigurationHelper.isSending(1))try{await this.turnOnLocalVideoPreview(f)}catch(g){return S.logFailure(g),Promise.reject(25)}const v=await this.startStopAudio(!0,f);return await this.signalingSession.recordTelemetryForStartAudio(v),{code:v}}async stopAudio(g,f=generateCauseId()){const S=this.logger.createFnLogger("StopAudio",f);if(3!==this.state)return S.logFailure("Cannot stopAudio when call is not connected"),Promise.reject(60);this.mediaStateConfigurationHelper.removeModality(0);const v=await this.startStopAudio(!1,f);return await this.turnOffLocalVideoPreview(f),await this.signalingSession.recordTelemetryForStopAudio(v),{code:v}}assimilate(g,f,S,v=generateCauseId()){return Promise.reject(new Error("Not implemented"))}async merge(g,f,S=generateCauseId()){const v=this.logger.createFnLogger("MergeCall",S);v.error(`merge callId ${g.callId} callMergeOptions ${JSON.stringify(f)}`);const C=this.canMerge(g,S);if(!C)return v.info(`Error. ${getPrintableObject(C)}`),Promise.reject(getRejectTransactionEnd("TransactionDisallowed"));const _=[];return g.participants.forEach((g=>{_.push(this._callOperationHandler.createPendingOperation("MergeCall",g.id,S))})),(await this.mergeCallByAddParticipantWithReplaces(f,g.participants,g,1,"MergeCall",S,_,void 0))[0]}async mergeParticipants(g,f,S,v,C){const _=this.logger.createFnLogger("MergeParticipants",v),T=[];if(!g)return Promise.reject(getRejectTransactionEnd("Invalid callToMerge"));if(0===f.length)return Promise.reject(getRejectTransactionEnd("Invalid participantIds"));const I=[];for(const S of f){let f=findParticipantUsingParticipantLegId(g,S);if(!f&&findSelfEndpointDetailUsingParticipantLegId(g,S)&&(_.info("found self endpoint, use localSignalingParticipant"),f=this.localSignalingParticipant),f){const g=generateGuid(),C={id:f.id,participantId:g,replacementParticipantId:S,nonMaskedId:f.nonMaskedId};T.push(C),I.push(this._callOperationHandler.createPendingOperation("MergeParticipant",g,v))}else{const g={code:406,subCode:5201,phrase:`participantLegId ${S} is invalid!`};I.push(Promise.reject(getRejectTransactionEnd(g)))}}return this.mergeCallByAddParticipantWithReplaces(S,T,g,3,"MergeParticipant",v,I,C)}async mergeWithPickupCode(g,f,S=generateCauseId()){const v=this.logger.createFnLogger("MergeWithPickupCode",S);if(v.info(`mergeWithPickupCode: pickup code: ${g}, groupId: ${scrubMriOrOmit(f.groupId)}, threadId: ${getLoggableThreadId(f.threadId)} messageId: ${f.messageId}`),!g||isNaN(Number(g)))return v.info("mergeWithPickupCode: pickup code cannot be empty"),Promise.reject(getRejectTransactionEnd("mergeWithPickupCode: pickup code cannot be empty"));const C={additionalData:f.additionalData,groupId:f.groupId,threadId:f.threadId,messageId:f.messageId,replacementType:2,pickupCode:Number(g)},_={id:`4:${fi.SERVER_HOLD}`};return Promise.resolve().then((()=>Promise.all(this.signalingSession.addParticipantsAsync([_],C,S)))).then((g=>(g.length>0&&this.signalingNotifications.onParticipantJoined(g[0],S),Promise.resolve({code:0,subCode:0,phrase:"TransactionComplete"})))).catch((g=>{v.logFailure(`Participant was not added to call, error=${getPrintableObject(g)}`);const f=this._handleParticipantOperationFailure("MergeWithPickupCode",g,S,null,!0).reason;return Promise.reject(g?g.endCode:f||0)}))}async setMaxVideoChannels(g){return Promise.reject(60)}async setMaxVbssChannels(g){return Promise.reject(60)}async stop(g=!1,f=generateCauseId(),S,v){const C=this.logger.createFnLogger("StopAudio",f);if(6===this.state)return C.logFailure("Trying to stop a call which is already Disconnecting"),Promise.reject(new Error("cannot stop call in Disconnecting state"));if(7===this.state)return C.logFailure("Trying to stop a call which is already Disconnected"),Promise.reject(new Error("cannot stop call in Disconnected state"));if(this.disposedPromise)return C.logFailure("Call already ended"),Promise.reject("Call already ended");let _=0;1===this.state&&(_=10);const T=v?{clientReasonSubCode:v.clientSubCode,clientReasonPhrase:v.clientPhrase}:{};v?.clientSubCode===bi.SUB_CODE.VDI_DISCONNECTED&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.enabled&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.clientPhrases.includes(v?.clientPhrase)&&(T.code=bi.CODE.MEDIA_ERROR,T.subCode=bi.SUB_CODE.VDI_DISCONNECTED,T.phrase=Gi.CallEndReasonVDIdisconnect,T.resultCategories=["UnexpectedClientError"],_=4);const I={terminatedReason:_,forEveryone:g,causeId:f,...S,rejectReason:T};return this.stopInternal(I)}publishState(g,f){const S=getPluginlessStateType(g.type),v=this.getPluginlessPublishLevel(g.level),C=g.participantIds&&g.participantIds.length>0?"specified":void 0;return this.callTelemetry.setOperationVariant("PublishState","specified"===C?`${S}Specified`:`${S}None`,f),this.signalingSession.publishStateAsync(S,v,f,g.content,C,g.participantIds)}publishStatesForEveryone(g,f){const S=getPluginlessStateType(g.type),v=this.getPluginlessPublishLevel(g.level),C="all";return this.callTelemetry.setOperationVariant("PublishState",`${S}All`),this.signalingSession.publishStateAsync(S,v,f,g.content,C)}removeState(g,f){return this.signalingSession.removeStateAsync(f,"specified",void 0,g.stateIds).then((g=>Promise.resolve()))}removeStatesForEveryone(g,f){const S=getPluginlessStateType(g.type);return this.signalingSession.removeStateAsync(f,"all",S,void 0).then((g=>Promise.resolve()))}updateMeetingSettings(g,f){return this.signalingSession.updateMeetingSettingsAsync({allowRaiseHands:g.allowRaiseHands,attendeeRestrictions:g.attendeeRestrictions,lockMeeting:g.lockMeeting,breakoutRoomsEnabled:g.breakoutRoomsEnabled,allowPresentersToManageBreakoutRooms:g.allowPresentersToManageBreakoutRooms,disableMdpClientAudioRecording:g.disableMdpClientAudioRecording,refreshSettings:g.refreshSettings,aiInterpretationEnabled:g.aiInterpretationEnabled,groupCopilotDetails:g.groupCopilotDetails},f)}updateMeetingGroups(g,f){this.logger.info(`[UpdateMeetingGroups][${g}] options ${safeJsonStringify(f)}`);const S=this._callOperationHandler.waitForOperation("UpdateMeetingGroups",g),v={fromGroup:f.fromGroup,toGroup:f.toGroup,scope:mapParticipantScope(f.scope)};return f.participants&&(v.participants=createParticipantListFromMriMap(f.participants)),this.signalingSession.updateMeetingsGroupsAsync(g,v).catch((f=>{this.logger.info(`[${g}] [UpdateMeetingGroups] error in updateMeetingGroups (synchronous error) : ${getPIISafeObject(f)}. updateMeetingGroupsPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingGroups",{error:getPIISafeObject(f)},g)})),S}updateMeetingLiveState(g,f){return this.logger.info(`[UpdateMeetingLiveState][${g}] options ${safeJsonStringify(f)}`),this.signalingSession.updateMeetingLiveStateAsync(g,f).catch((f=>{this.logger.info(`[${g}] [UpdateMeetingLiveState] error in updateMeetingLiveState (synchronous error) : ${getPIISafeObject(f)}. promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingLiveState",{error:getPIISafeObject(f)},g)})),this._callOperationHandler.waitForOperation("UpdateMeetingLiveState",g)}updateMeetingStates(g,f=generateCauseId()){var S;this.logger.info(`[UpdateMeetingStates][${f}]`);const v={},C=[];g.operationId=g.operationId||f;for(const _ of Object.keys(g.meetingStates)){const T=g.operationId+"_"+_;C.push(T);const I=this._callOperationHandler.createPendingOperation("UpdateMeetingStates",T,f);v[S=g.operationId]??(v[S]={}),v[g.operationId][_]=I,this.callTelemetry.recordOperation("UpdateMeetingStates",f,T)}return Promise.resolve().then((()=>this.signalingSession.updateMeetingStatesAsync(f,g))).then((g=>{for(const S of C)this.callTelemetry.updateOperationData("UpdateMeetingStates",{data:getPIISafeObject(g)},f,S)})).catch((g=>{for(const S of C)this.callTelemetry.updateOperationData("UpdateMeetingStates",{error:getPIISafeObject(g)},f,S);this.logger.logFailure(g)})).then((()=>v))}async updateParticipantInterpretationState(g,f){if(this.logger.info(`[UpdateParticipantInterpretationState][${g}] options ${safeJsonStringify(f)}`),0===f.length)return Promise.reject(getRejectTransactionEnd("Invalid UpdateParticipantInterpretationState options"));const S=this.signalingSession.updateParticipantInterpretationStateAsync(g,f),v=[];f.forEach((f=>{v.push(this._callOperationHandler.createPendingOperation("UpdateParticipantInterpretationState",f.id,g))}));for(let v=0;v<S.length;v++){const C=S[v],_=f[v];C.then((()=>{this.logger.logSuccess(`updateParticipantInterpretationState succeeded for [id=${scrubMriOrOmit(_.id)}]`);const f={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess("UpdateParticipantInterpretationState",f,_.id,g),this._callOperationHandler.maybeResolveOperation("UpdateParticipantInterpretationState",f,_.id,g)})).catch((f=>{this.logger.error(`[${g}] [UpdateParticipantInterpretationState] error in updateParticipantInterpretationState (synchronous error) : ${getPIISafeObject(f)}. updateParticipantInterpretationStatePromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateParticipantInterpretationState",{error:getPIISafeObject(f)},g);const S=this._handleParticipantOperationFailure("UpdateParticipantInterpretationState",f,g,_.id).reason,v=f?.endCode||S||0;this._callOperationHandler.maybeRejectOperation("UpdateParticipantInterpretationState",v,_.id,g)}))}return Promise.resolve(v)}async updateParticipantsProperties(g,f){const S=this.logger.createFnLogger("UpdateParticipantsProperties",f);if(S.info(`options ${scrubMriOrOmit(safeJsonStringify(g))}`),!g)return Promise.reject(getRejectTransactionEnd("Invalid input: UpdateParticipantsPropertiesContext"));const v={},C=g.scope,_=g.operationId,T=new Set;if("self"===C){const S=this.signalingSession.participantManager.localParticipant.id;for(const C in g.propertyBag){const g=mapMriAndPropertyNameToResolveString(S,_,C),I=this.createUpdateParticipantPromise(g,f);v[g]={[S]:I},T.add(g),this.callTelemetry.recordOperation("UpdateParticipantsProperties",f,scrubMriOrOmit(g))}}else{if("specified"!==C||!this._isUpdatePropertiesSpecifiedAllowedByEcs)return Promise.reject("This scope is not supported.");{const S=g.participants;for(const g of S){const S=g.id;for(const C in g.propertyBag){const g=mapMriAndPropertyNameToResolveString(S,_,C),I=this.createUpdateParticipantPromise(g,f);v[g]={[S]:I},T.add(g),this.callTelemetry.recordOperation("UpdateParticipantsProperties",f,scrubMriOrOmit(g))}}}}return S.info(`promises created: ${scrubMriOrOmit(safeJsonStringify(v))}`),this.signalingSession.updateParticipantsPropertiesAsync(g,T,_,f).catch((g=>{const C=getPrintableObject(g);S.info(`[failed][reason=${C}]`);const _={...g};this.callTelemetry.updateOperationData("UpdateParticipantsProperties",{error:getPIISafeObject(C)},f);for(const g of Object.keys(v))this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",_,g,f)})),Promise.resolve().then((()=>v))}joinMeetingGroup(g,f){this.logger.info(`[JoinMeetingGroup][${g}] options ${safeJsonStringify(f)}`);const S=this._callOperationHandler.waitForOperation("JoinMeetingGroup",g),v={..."meetingGroupId"in f&&{meetingGroupId:f.meetingGroupId},..."meetingGroupLabel"in f&&{meetingGroupLabel:f.meetingGroupLabel},...f.groupPreferences&&{groupPreferences:f.groupPreferences}};return this.signalingSession.joinMeetingGroupAsync(g,v).catch((f=>{const S=getPIISafeObject(f);this.logger.info(`[${g}] [JoinMeetingGroup] error in joinMeetingGroup (synchronous error) : ${S}. joinMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("JoinMeetingGroup",{error:S},g)})),S}leaveMeetingGroup(g,f){this.logger.info(`[LeaveMeetingGroup][${g}] options ${safeJsonStringify(f)}`);const S=this._callOperationHandler.waitForOperation("LeaveMeetingGroup",g),v={meetingGroupId:f.meetingGroupId};return this.signalingSession.leaveMeetingGroupAsync(g,v).catch((f=>{const S=getPIISafeObject(f);this.logger.info(`[${g}] [LeaveMeetingGroup] error in leaveMeetingGroup (synchronous error) : ${S}. leaveMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("LeaveMeetingGroup",{error:S},g)})),S}sendMessages(g,f){var S,v;this.logger.info(`[SendMessages][${g}]`);const C={};for(const _ of f)if(0===_.scope){const f=this._callOperationHandler.createPendingOperation("SendMessages",_.operationId,g);C[_.operationId]={all:f},this.callTelemetry.recordOperation("SendMessages",g,_.operationId)}else if(1===_.scope)for(const f in _.to)if("participant"===_.to[f].level){const v=mapMriToResolveString(f,_.operationId),T=this._callOperationHandler.createPendingOperation("SendMessages",v,g);C[S=_.operationId]??(C[S]={}),C[_.operationId][f]=T,this.callTelemetry.recordOperation("SendMessages",g,v)}else if("endpoint"===_.to[f].level)for(const S in _.to[f].participantLegIdMap){const f=mapLegIdToResolveString(S,_.operationId),T=this._callOperationHandler.createPendingOperation("SendMessages",f,g);C[v=_.operationId]??(C[v]={}),C[_.operationId][S]=T,this.callTelemetry.recordOperation("SendMessages",g,f)}return this.signalingSession.sendProxiedMessageAsync(g,f).then((g=>{for(const f of g)f.then((g=>{this._callOperationHandler.maybeResolveOperation("SendMessages",g.transactionEnd,g.resolveString,g.causeId)})).catch((g=>{this._callOperationHandler.maybeRejectOperation("SendMessages",g.transactionEnd,g.resolveString,g.causeId)}));return C}))}async updateMonitorSession(g,f=generateCauseId()){this.logger.info(`updateMonitorSession: monitorActionType: ${g.monitorActionType}, monitorData: ${g.monitorData}`);const S=mapMonitorActionType(g.monitorActionType);if(void 0===S){const f={code:bi.CODE.CLIENT_ERROR_CODE,subCode:bi.SUB_CODE.INVALID_DATA_TYPE,phrase:`Invalid monitor action type ${g.monitorActionType}`};return Promise.reject(f)}const v={monitorActionType:S,monitorData:g.monitorData},C=this._callOperationHandler.waitForOperation("UpdateMonitorSession","",f);return this.signalingSession.updateMonitorSessionAsync(v,f).catch((g=>{const S=getPIISafeObject(g);this.logger.info(`[${f}] [UpdateMonitorSession] error in updateMonitorSession (synchronous error): ${JSON.stringify(S)}. updateMonitorSessionPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMonitorSession",{error:S},f)})),C}switchInterpreterGroup(g){return Promise.reject(new Error("Not implemented"))}setLiveInterpretationAttributes(g,f){return Promise.reject(new Error("Not implemented"))}async updateMeetingRoles(g,f,S=generateCauseId()){return 3===this.state&&this.signalingSession.hasOwnProperty("updateMeetingRolesAsync")?this.signalingSession.updateMeetingRolesAsync(g,f,S):Promise.reject({code:bi.CODE.CLIENT_ERROR_CODE,subCode:bi.SUB_CODE.ACTION_NOT_ALLOWED,phrase:"ActionNotAllowed"})}stopInternal(g){const f=this.logger.createFnLogger("stopInternal",g.causeId),S=g.terminatedReason||0;let v=g.rejectReason&&(g.rejectReason.code||g.rejectReason.subCode)?g.rejectReason:this.getRejectionInfoFromTerminatedReason(S);if(g.rejectReason&&(v||(v={}),v.clientReasonSubCode=g.rejectReason.clientReasonSubCode,v.clientReasonPhrase=g.rejectReason.clientReasonPhrase),f.info(`started, terminatedReason=${S}, rejectReason=${safeJsonStringify(v)}`),6===this.state)return f.logFailure("Trying to stop a call which is already Disconnecting"),this.disconnectingPromise;if(7===this.state)return f.logFailure("Trying to stop a call which is already Disconnected"),this.disconnectingPromise;this.setCallState(6,g.causeId,S);const C={causeId:g.causeId,forEveryone:g.forEveryone,scope:this.mapEndpointScope(g.scope),redirectOptions:g.redirectOptions&&convertRedirectOptions(g.redirectOptions)};return 1===g.scope&&(v.code=bi.CODE.SUCCESS,v.subCode=bi.SUB_CODE.ENDED_BY_REMOTE_ENDPOINT,v.phrase=Gi.EndedByRemoteEndpoint),this.disconnectingPromise=Promise.all([this.cleanUpMedia(g.causeId,v).then((()=>{this.callTelemetry.recordOperationSuccess("_MediaCleanUp")})).catch((S=>{throw f.logFailure(`cleanUpMedia failed with reason=${getPrintableObject(S)}`),this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:getPIISafeObject(S)},g.causeId),S})),this.signalingSession.endAsync(v,C).catch((g=>{throw f.logFailure(`endAsync failed with reason=${getPrintableObject(g)}`),g}))]).catch((S=>{throw f.logFailure(S),this.cleanUp(g.causeId,v),S})).then((()=>this.cleanUp(g.causeId,v))).catch((f=>{throw this.callTelemetry.updateOperationData("StopCall",{error:getPIISafeObject(f)},g.causeId),this.setCallState(7,g.causeId,S),f})),this.disconnectingPromise}async cleanUp(g,f){return this.logger.info(`[${g}][cleanup]start`),this.disposedPromise||(this.disposedPromise=this.cleanUpFinalize(g,f),this._getCallEndOperation().catch(noop).then((()=>{const f={code:bi.CODE.CLIENT_ERROR_CODE,subCode:bi.SUB_CODE.ABANDONED};this._callOperationHandler.rejectPendingOperations(61,g,f),this._participantOperationHandler.rejectPendingOperations(47,g,f)}))),this.disposedPromise}async cleanUpMedia(g,f){return this.mediaDisposedPromise||(this.callTelemetry.recordOperation("_MediaCleanUp",g),this.mediaDisposedPromise=(async()=>{this.callDeviceManager?.dispose(),this.callDeviceManager=null,this.turnOffLocalVideoPreview(g),this.localVideoContainer=null,this.disposeContentSharingSessions(),this.disposeSharingScreenHandle();const S=this.mediaSession;if(this.reportMediaStats=!!S,!S)return;this.unmixedAudioProvider.dispose(),this.dataChannel.dispose(),this.screenSharingControl.dispose(g),this.remoteUFDHandler.dispose(),this.mediaSession=null,this.streamManager.setMediaSession(null,g),this.participants?.forEach((f=>{f.setMediaSession(null,g)}));const v=S.terminate(g,f);this.isVideoOn=!1,this.setMediaStream(this.isVideoOn,!1,1),this.setMediaStream(!1,!1,2),this.setMediaStream(!1,!1,0),this.isScreenSharingOn=!1,this.screenSharingRenegotiationDeferred?.reject(f),this.screenSharingRenegotiationDeferred=null,this.mediaStateConfigurationHelper.removeModality(1),this.mediaStateConfigurationHelper.removeModality(0),this.mediaStateConfigurationHelper.removeModality(3),this.mediaStateConfigurationHelper.removeModality(2),this.batteryStatus?.dispose(),S?.getSessionConfig()?.config?.useOneDsLogger&&S.getSessionConfig().config.addTelemetryReportingCallback&&window.removeEventListener("beforeunload",this.beforeUnloadTelemetrySender);try{await v}finally{await this.collectCallStats(S),this.callStats.appendMediaControlPlaneInfo(JSON.stringify(S.getMediaControlPlaneInstance()?.getTelemetryReport()))}})()),this.mediaDisposedPromise}async cleanUpFinalize(g,f){try{await this.cleanUpMedia(g,f)}catch(f){this.logger.info(`[${g}][cleanUpMedia] failure: ${getPrintableObject(f)}`),this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:getPIISafeObject(f)},g)}this.callTelemetry.recordOperationSuccess("_MediaCleanUp");const S=this.reportCallEndStats(this.reportMediaStats);this.mediaSession?.getSessionConfig().config.waitReportStatsAtCallStop&&await S}async createContentSharingSession(g,f,S,v,C=generateCauseId()){if(this.signalingSession.signalingAgentConfig.checkAttendeeRoleInCreateContentSharing&&"attendee"===(this.advancedMeetingRole||this.meetingRole)){const g={terminatedReason:8,terminatedReasonCode:403,terminatedReasonSubCode:0,errorMessage:"Failed due to insufficient permissions"};return Promise.reject(g)}const _=new us(this.callTelemetry,this.logger,this.signalingSession,g,f,v,S);return this.contentSharingSessions.push(_),_.changed((()=>this.removeContentSessionIfEnded(_))),this.event("contentSharingChanged").raise(),Promise.resolve(_)}stopWithBeacon(g=generateCauseId()){if(6===this.state||7===this.state)return!0;this.mediaSession?.getSessionConfig()?.config?.enableCallStateChangesOnPageClose&&(this.callEndDiagnosticsInfo={callControllerCode:bi.CODE.SUCCESS,callControllerSubCode:bi.SUB_CODE.BEACON},this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo),this.setCallState(6,g,1));const f=this.signalingSession.endWithBeacon(g);return this.mediaSession?.getSessionConfig()?.config?.enableCallStateChangesOnPageClose&&this.setCallState(7,g,1),f}disposeContentSharingSessions(){this.contentSharingSessions.forEach((g=>{g.dispose(),this.removeContentSessionIfEnded(g)})),this.event("contentSharingChanged").raise()}isPreheatedOnly(){return!!(12===this.state||2===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall")||9===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))}removeContentSessionIfEnded(g){7!==g.contentSharingStatus&&8!==g.contentSharingStatus||(this.logger.info("stopping the content sharing session."),(0,Ki.remove)(this.contentSharingSessions,(f=>f.contentSharingGuid===g.contentSharingGuid)).length&&this.event("contentSharingChanged").raise())}getRejectionInfoFromTerminatedReason(g){switch(g){case 53:return{code:Fi.MediaError,subCode:xi.MediaWhiteListingIssue,phrase:Gi.MediaWhiteListingIssue};case 4:return{code:Fi.MediaError,subCode:this._wasAudioStreamConnected?xi.MediaDropAfterConnect:xi.MediaDropDuringConnect,phrase:this._wasAudioStreamConnected?Gi.MediaDropAfterConnect:Gi.MediaDropDuringConnect};case 47:return{code:Fi.MediaError,subCode:xi.MediaOfferProcessingError,phrase:Gi.MediaOfferProcessingError};case 38:return{code:Fi.MediaError,subCode:xi.MediaRenegotiationError,phrase:Gi.RetargetNotSupported};case 10:return{code:Fi.Reject,subCode:xi.Success,phrase:Gi.CallEndReasonLocalUserInitiated};case 25:return{code:Fi.UnknownError,subCode:xi.MediaUnknownError,phrase:Gi.MediaError};case 58:return{code:Fi.MediaError,subCode:xi.MediaPermissionError,phrase:Gi.MediaPermissionError};case 7:return{code:Fi.UnknownError,subCode:xi.Success,phrase:Gi.Unknown};case 0:case 1:return{code:Fi.Success,subCode:xi.Success,phrase:Gi.CallEndReasonLocalUserInitiated};case 75:return{code:Fi.CallRedirected,subCode:xi.CallRedirectedSuccess,phrase:Gi.CallEndReasonRedirected,resultCategories:["Success"]};case 77:return{code:Fi.Success,subCode:xi.Suspended,phrase:Gi.CallEndReasonSuspended}}return null}async acknowledge(g,f,S=generateCauseId()){const v=this.logger.createFnLogger("Acknowledge",S),C=Date.now();if(this.setInitialTelemetry("Acknowledge",{callStartTime:C},"",S),0!==this.state&&8!==this.state)throw new Error(`Trying to acknowledge a call that has already been acted on ${this.state}`);v.info(`isMultiParty=${g.isMultiParty}`),v.info(`fromMixer=${g.fromMixer}`),v.info(`participantId=${g.participantId}`),v.info(`callType=${g.callType}`),this.attachToCallAndGetOffer=new dt,this.setCallType(g.isMultiParty?2:1,S),this.setCallUsesMixer(!!g.fromMixer,S),this.setCallerMri(stripMriAliases(g.callerId)),this.setDisplayNameSource(g.displayNameSource),this.setTransferorMri(g.transferorId),this.transferorType=g.transferorType,this.transferorDisplayName=g.transferorDisplayName,this.incomingCallType=g.callType,this.consultativeCallId=g.consultativeCallId,this.callQueueInfo=g.callQueueInfo,this.setFromApplicationType(g.fromApplicationType,S),this.callStats.localStats.startCall();const _=createPhaseExecutor(v);try{if(_.executeSync("ProcessIncomingCallRequest",(()=>this.signalingSession.processIncomingCallRequest(g,f,S))),this.setParticipantId(this.participantId),_.executeSync("ResolvePotentialConflict",(()=>this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)))===this.signalingSession)return Promise.reject({code:7,success:!1});const mediaSetup=async()=>{_.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(S))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled());const g=this.signalingSession.getInitialMediaOfferFromIncomingCallPayload();this.callStats.setParticipantId(this.participantId),this.onBehalfOfMri=this.signalingSession.onBehalfOf,this.onBehalfOfUserDisplayName=this.signalingSession.onBehalfOfUserDisplayName,this.callQueueContext=this.signalingSession.callQueueContext,this.callQueueSupervisorContent=this.signalingSession.callQueueSupervisorContent,this.bannerContent=this.signalingSession.bannerContent,this.callPhoneLineType=this.signalingSession.callPhoneLineType;const f=await _.execute("WaitForMediaOffer",(()=>g?Promise.resolve(g):this.attachToCallAndGetOffer.promise));let C;try{C=await _.execute("ProcessOffer",(()=>this.mediaSession.processOfferAsync(f,S)))}catch(g){C=await this._handleOfferProcessingError(g,S,v)}await _.execute("ProcessOfferedModalities",(()=>this._processOfferedModalities(C,S)))},C=(()=>_.execute("SendAttach",(()=>this.signalingSession.sendAttachToCall(S))).then((()=>this.setCallState(1,S))))();return await Promise.all([C,mediaSetup()]).catch((async g=>{throw await C,g})),await _.execute("TrySendingProvisionalAnswer",(()=>this._trySendProvisionalMediaAnswer(S))),_.executeSync("OnAcknowledgeSuccess",(()=>this._onAcknowledgeSuccess(v,_.getTelemetryData(),S)))}catch(g){return this._onAcknowledgeError(g,S,v,_.getTelemetryData())}}_onMessageIdChanged(g,f){g&&this.messageId!==g&&this.setMessageId(g,f)}async accept(g,f=generateCauseId()){const S=this.logger.createFnLogger("Accept",f);if(S.info(`accept, answerMediaType: ${g.answerMediaType},\n                            withVideo: ${g.withVideo},\n                            muted: ${g.muted},\n                            getSendMediaModalities: ${JSON.stringify(g.sendMediaModalities)},\n                            clientEndpointCapabilities: ${g.clientEndpointCapabilities},\n                            muteFlags: ${g.muteFlags}`),1!==this.state)throw new Error("Only calls in Notified state can be accepted");this.setCallOptions({callStartOptions:g,callStartTime:Date.now()}),this.setSessionIceTransportPolicy(g?.mediaConfiguration);const v=this._callOperationHandler.createPendingOperation("_ConnectCall",void 0,f);this.callStats.localStats.audio.start();const C=createPhaseExecutor(S);this.mediaSession.createAudioElement(f);const _=g.muted||1==(1&g.muteFlags),T=2==(2&g.muteFlags);this.setMuted(_?2:this.isServerMuted?1:0,f),this.setSpeakerMuted(T,f),this.setCallState(2,f),this.connectCallPromise=this._callOperationHandler.waitForOperation("Accept");try{g.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient(),this.mediaStateConfigurationHelper.setCallAcceptOptions(g),this.mediaStateConfigurationHelper.isSending(1)&&await C.execute("StartVideoSafe",(()=>this.startVideoSafe(f))),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,f);const _=await C.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,f))),T=C.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(_))),I=await C.execute("evaluateEndpointStatesForAccept",(()=>this.evaluateEndpointStatesForAccept(2===this._muteState,g?.additionalEndpointProperties,f)));await C.execute("MuteUnmuteSpeakers",(()=>this.muteUnmuteSpeaker(this.isSpeakerMuted,f)));const b=C.execute("handleEndpointStatesForAccept",(()=>this.handleEndpointStatesForAccept(I,f)));S.info("Queued the handleEndpointStatesForAccept");const A=await C.execute("CreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,f)));await C.execute("Accept",(()=>this.signalingSession.acceptAsync(A,T,g.clientEndpointCapabilities,f))),await C.execute("WaitForConnect",(()=>v)),this.handleRemoteParticipantStateInOneToOneCall(f),await C.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(f))),await b,this.callTelemetry.updateOperationData("Accept",{phases:C.getTelemetryData()},f)}catch(g){let v=7,C={};throw this.callTelemetry.updateOperationData("Accept",this.getTelemetryFromPhaseExecution(g),f),g?.error&&(C={...g.error}),isOneOfPhaseErrors(Wi,g)&&(v=47),this.mediaSession?.getSessionConfig().config.stopCallOnAcceptFailure&&this.stopInternal({terminatedReason:v,causeId:f,rejectReason:C}),g.terminatedReason=v,S.logFailure(g),g}}async reject(g=generateCauseId(),f){const S=f?{clientReasonSubCode:f.clientSubCode,clientReasonPhrase:f.clientPhrase}:{};return 1!==this.state?Promise.reject(60):this.stopInternal({terminatedReason:10,causeId:g,rejectReason:S})}async join(g,f={},S=generateCauseId()){const v=Date.now();return this.setInitialTelemetry("JoinCall",{callStartOptions:f,callStartTime:v},g.conversationUrl,S),this.setCallerMri(stripMriAliases(g.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinCall"),this.joinOrStartCall({callStartOptions:getCallStartOptions(f),callStartTime:v},this.joinGivenConversation,S,g.conversationUrl)}async joinPreheatedCall(g,f){const S=this.logger.createFnLogger("JoinPreheatedCall",f),v=this.isServerMuted||1==(1&g.muteFlags),C=2==(2&g.muteFlags),_=createPhaseExecutor(S);this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinPreheatedCall");try{const T={endpointProperties:{preheatProperties:0}};this.setCallState(2,f),!this.isCallModeStreaming()&&v&&(T.state={isMuted:!0}),S.info(`captchaContentJson=${!!g.captchaContentJson} publishedStates=${!!g.publishedStates} muteFlags=${g.muteFlags}}`),await this.signalingSession.updateEndpointState(T,f,g.publishedStates,g.captchaContentJson),this.computeCallState(f),this.isCallModeStreaming()||(v||(await _.execute("UnmuteInput",(()=>this.mediaSession.unmuteInputAsync(f))),this.setMuted(0,f)),C||(await _.execute("UnmuteOutput",(()=>this.mediaSession.unmuteOutputAsync(f))),this.setSpeakerMuted(!1,f)))}catch(g){const v=7;let C;return S.logFailure(`error: ${v} ${getPrintableObject(g)}`),isTransactionEnd(g)?C=g:isPhaseError("UnmuteInput",g)?C={code:Fi.LocalError,subCode:xi.MediaUnmuteMicrophoneError,phrase:getPrintableObject(g),causeId:f}:isPhaseError("UnmuteOutput",g)&&(C={code:Fi.LocalError,subCode:xi.MediaUnmuteSpeakerError,phrase:getPrintableObject(g),causeId:f}),this.callTelemetry.updateOperationData("JoinPreheatedCall",{phases:_.getTelemetryData(),error:getPIISafeObject(g)},f),this.stopInternal({causeId:f,terminatedReason:v,rejectReason:C}),Promise.reject(C)}}async start(g={},f=generateCauseId()){const S=Date.now();return this.setCallerMri(rr+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCall",{callStartOptions:g,callStartTime:S},"",f),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCall"),this.joinOrStartCall({callStartOptions:getCallStartOptions(g),callStartTime:S},this.startOutgoingCall,f)}async startCallToVoicemail(g,f=generateCauseId()){const S=Date.now();return this.setCallerMri(rr+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCallToVoiceMail",{callVoicemailStartOptions:g,callStartTime:S},"",f),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallToVoiceMail"),this.joinOrStartCall({callVoicemailStartOptions:g,callStartTime:S},this.startVM,f)}async joinCallWithoutCallModality(g,f={},S=generateCauseId()){const v=Date.now();this.setCallerMri(g.groupCallInitiator),this.setCallType(2,S);const C={callStartOptions:getCallStartOptions(f),callStartTime:v};return this.setInitialTelemetry("Subscribe",C,g.conversationUrl,S),0!==this.state?(this.logger.info(`[${S}][joinCallWithoutCallModality]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(C),this.setCallState(8,S),this.signalingSession.subscribeToCall(g.conversationUrl,this.callId,f.clientEndpointCapabilities,{meetingRegistrationId:f.meetingRegistrationId,participantPin:f.participantPin,clientEndpointDebugContent:f.clientEndpointDebugContent,additionalEndpointProperties:f.additionalEndpointProperties},S).catch((g=>isTransactionEnd(g)?(this.logger.info(`[${S}][joinCallWithoutCallModality] ${getPrintableObject(g)}`),Promise.reject(g)):Promise.reject(convertReason(g)))),this._callOperationHandler.waitForOperation("Subscribe",void 0,S))}startWithMeetingData(g,f){const S=Date.now();return this.setCallerMri(rr+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartWithMeetingData",{callStartOptions:f,callStartTime:S},"",g),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartWithMeetingData"),this.joinOrStartCall({callStartOptions:getCallStartOptions(f),callStartTime:S,meetingPreferences:{shouldResurrect:f.shouldResurrect}},this.startOutgoingCall,g)}joinWithMeetingData(g,f,S){const v=Date.now();return this.setInitialTelemetry("JoinWithMeetingData",{callStartOptions:S,callStartTime:v},f.conversationUrl,g),this.setCallerMri(stripMriAliases(f.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinWithMeetingData"),this.joinOrStartCall({callStartOptions:getCallStartOptions(S),callStartTime:v,meetingPreferences:{shouldResurrect:S.shouldResurrect}},this.joinGivenConversation,g,f.conversationUrl)}subscribeWithMeetingData(g,f,S){const v=Date.now();this.setCallerMri(f.groupCallInitiator),this.setCallType(2,g);const C={callStartOptions:getCallStartOptions(S),callStartTime:v};return this.setInitialTelemetry("SubscribeWithMeetingData",C,f.conversationUrl,g),0!==this.state?(this.logger.info(`[${g}][subscribeWithMeetingData]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(C),this.setCallState(8,g),this.signalingSession.subscribeToCall(f.conversationUrl,this.callId,S.clientEndpointCapabilities,{meetingPreferences:{shouldResurrect:S.shouldResurrect},meetingData:this.meetingData,meetingRegistrationId:S.meetingRegistrationId,participantPin:S.participantPin,additionalEndpointProperties:S.additionalEndpointProperties},g).catch((f=>isTransactionEnd(f)?(this.logger.info(`[${g}][subscribeWithMeetingData] ${getPrintableObject(f)}`),Promise.reject(f)):Promise.reject(convertReason(f)))),this._callOperationHandler.waitForOperation("SubscribeWithMeetingData",void 0,g))}async startCallWithNudge(g,f={},S=generateCauseId()){this.setCallerMri(rr+this.currentUserSkypeIdentity.id),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallWithNudge");const v=Date.now();if(this.logger.info(`[${S}][startCallWithNudge]startCallWithNudge for participants: ${scrubMriOrOmitList(g)}`),this.participants.length)return Promise.reject(48);if(f.isCast&&f.isHuddleGroupCall)return this.logger.logFailure(`isCast: ${f.isCast} isHuddleGroupCall: ${f.isHuddleGroupCall}`),Promise.reject(new Error("isCast or isHuddleGroupCall can only be set exclusively."));const C={};return C.callStartOptions=getCallStartOptions(f),C.invitationType=an.INVITATION_TYPE.NUDGE,C.participantsToNudge=g,C.callStartTime=v,this.setInitialTelemetry("StartCallWithNudge",C,"",S),this.joinOrStartCall(C,this.startOutgoingCall,S)}async startAndUnpark(g,f,S={},v=generateCauseId()){this.setCallerMri(rr+this.currentUserSkypeIdentity.id);const C=this.logger.createFnLogger("StartCallAndUnpark",v),_=Date.now();this.setInitialTelemetry("StartCallAndUnpark",{callStartTime:_},"",v),C.info(`startAndUnpark for context: ${g}, pickupCode :${f}`),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallAndUnpark");const T={};switch(T.callStartOptions=getCallStartOptions(S),T.pickupCode=f,T.parkContext=fi.SERVER_HOLD,g){case 0:T.parkContext=fi.PARK;break;case 1:T.parkContext=fi.SHARED_LINE;break;case 5:T.parkContext=fi.CALL_PARK;break;case 2:T.parkContext=fi.SERVER_HOLD;break;default:throw new Error(`[startAndUnpark] unsupported ParkContext name: ${g}`)}return this.addParticipant(`4:${T.parkContext}`).catch((g=>C.logFailure("Failed to add participant to unparked call"))),this.joinOrStartCall(T,this.startOutgoingCall,v)}async admitParticipant(g,f=generateCauseId()){const S=generateAliasedMri(g),v=this.getParticipant(S),C=this._getParticipantLegId(v),_=C?{participantLegId:C}:{};if(v&&7!==v.state){const S={code:0,subCode:3552,phrase:"Participant is not in lobby state"};return this.callTelemetry.maybeRecordOperationSuccess("AdmitParticipant",S,g,f,_),Promise.reject(S)}return this.admitParticipantToCall(S,f,C)}admit(g,f){return this.signalingSession.admitAsync(f)}async callMeBack(g,f,S=generateCauseId()){const v=generateAliasedMri(`${rr}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri);return this.addCallMeBackParticipant(g,f||v,S)}async addParticipant(g,f={},S=generateCauseId()){return(await this.addParticipantsImpl([g],f,S,"addParticipant"))[0]}async addParticipants(g,f={},S=generateCauseId()){return this.addParticipantsImpl(g,f,S,"addParticipants")}async addParticipantsImpl(g,f={},S=generateCauseId(),v){if(this.logger.info(`[${S}][${v}] start`),this.isEmergency&&0===this.state&&(0!==this.participants.length||1!==g.length))return Promise.reject(new Error("Only 1 participant (the emergency operator) may be added to unstarted emergency calls"));if(f.participantInvitationData)try{JSON.stringify(f.participantInvitationData)}catch(g){throw this.logger.info(`[${S}][${v}] ${g}`),g}const C=[],_=[];if(g.forEach((g=>{const f=this.getOrCreateParticipant(g,S,!0);0===f.state||4===f.state?(_.push(f),C.push(this._participantOperationHandler.createPendingOperation("AddParticipant",f.id,S))):3===f.state?C.push(Promise.resolve(f)):this._participantOperationHandler.hasPendingOperationWithOperationId("AddParticipant",f.id)&&C.push(this._participantOperationHandler.waitForOperation("AddParticipant",f.id))})),0===_.length)return Promise.resolve(C);const T=!!f.disableUnmute,I=this.addParticipantsToCall(_,S,f.participantInvitationData,f.groupId,f.threadId,f.messageId,T,f.alternateId,f.customHeaderContext,f.callingLineIdentity);return(0,Ki.zip)(I,_).forEach((async([g,f])=>{try{await g;const v=this._getParticipantLegId(this.getParticipant(f.id)),C=v?{participantLegId:v}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},f.id,S,C),this._participantOperationHandler.maybeResolveOperation("AddParticipant",f,f.id,S)}catch(g){this._participantOperationHandler.maybeRejectOperation("AddParticipant",g,f.id,S)}})),this.raiseChanged(this._participantChangedEventSkipConfig),Promise.resolve(C)}async nudgeParticipants(g,f,S={},v=generateCauseId()){return 2!==this.state&&3!==this.state?Promise.reject(48):this.signalingSession.nudgeParticipantsAsync({participantsIds:f,causeId:v,invitationData:S.participantInvitationData,newGroupId:S.groupId,newThreadId:S.threadId,newMessageId:S.messageId})}mapRemoveEndpointScope(g){switch(g){case 0:return"specified";case 1:return"all";default:return"none"}}mapEndpointScope(g){return 1===g?"all":"none"}async removeParticipant(g,f=generateCauseId(),S,v){const C=this.logger.createFnLogger("removeParticipant",f);C.info("start");const _=this.mapRemoveEndpointScope(v);return this.signalingSession.removeParticipantAsync({id:g,endpointId:S},f,_).catch((S=>{C.logFailure(`Participant was not removed from call, error=${S}`);const v=this._handleParticipantOperationFailure("RemoveParticipant",S,f,g).reason;return Promise.reject(v||38)}))}async cancelNudge(g,f){throw new Error("Method not implemented.")}async searchParticipants(g,f){return this.signalingSession.searchParticipantsAsync(g.searchQueryOptions,f)}async getAllParticipants(g,f){return this.signalingSession.getAllParticipantsAsync(g.scope,f)}set dominantSpeakerInfo(g){this.internalDominantSpeakerInfo=g}get dominantSpeakerInfo(){return this.internalDominantSpeakerInfo?this.internalDominantSpeakerInfo:this.mediaSession?.getSessionConfig().config.emptyInitialDSH?{speakerList:[],timestamp:null,noCurrentDominantSpeaker:!1}:{speakerList:this.participants.filter((g=>3===g.state)).map((g=>g.id)),timestamp:null,noCurrentDominantSpeaker:!1}}set slowedDownActiveTalkerInfo(g){(0,Ki.isEqual)(this.internalSlowedDownActiveTalkerInfo?.speakerList,g.speakerList)||(this.internalSlowedDownActiveTalkerInfo=g,this.raiseChanged())}get slowedDownActiveTalkerInfo(){return this.internalSlowedDownActiveTalkerInfo}startVideoSafe(g){return this.startVideo(g).catch((f=>{this.logger.info(JSON.stringify(f),"startVideoSafe",g)}))}async joinOrStartCall(g,f,S,v){const C=this.logger.createFnLogger("joinOrStartCall",S);if(0!==this.state&&8!==this.state&&!g.isPromotingToRealtime){const g="Trying to start a call that has already been acted on";return C.logFailure(g),Promise.reject(60)}if(this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)===this.signalingSession)return Promise.reject(57);this.callStats.localStats.startCall();const _=8===this.state||1!==this.participants.length;C.info(`isMultiparty=${_}, reason: participants.length=${this.participants.length}`),this.setCallType(_?2:1,S),this.setCallUsesMixer(_,S),this._setMaxVbssChannels(g?.callStartOptions?.maxVbssChannels,S),this.setCallOptions(g);const T=g.callStartOptions||{};if(1==(1&T.preheatFlags))this.setMuted(2,S),this.setSpeakerMuted(!0,S),this.setCallState(11,S);else{const g=!!T&&(T.muted||1==(1&T.muteFlags)),f=T?.muteFlags?2==(2&T.muteFlags):this.isSpeakerMuted;this.setMuted(g?2:this.isServerMuted?1:0,S),this.setSpeakerMuted(f,S),this.setCallState(2,S)}const I=calculateJoinedFromForTelemetry(this.meetingData,this.threadId,this.messageId,this.groupId,!!v);this.callTelemetry.setJoinedFrom(I),this.signalingSession.setJoinedFrom(I),this.setHuddleGroupCall(!!g.callStartOptions?.isHuddleGroupCall);const b=this._callOperationHandler.createPendingOperation("_ConnectCall","",S);return b.catch(noop),await this.joinOrStartWithMedia(g,f,g.callStartTime,b,S,v),g.callStartOptions?.meetingRegistrationId&&this.callTelemetry.setHasMeetingRegistrationId(!0),g.callStartOptions?.participantPin&&this.callTelemetry.setHasParticipantPin(!0),b}setSessionIceTransportPolicy(g){const f=g?.connectionType;let S=qt.ICE_TRANSPORT_POLICY.all;switch(f){case"AllSupported":S=qt.ICE_TRANSPORT_POLICY.all;break;case"NoDirectConnection":S=qt.ICE_TRANSPORT_POLICY.relay}this.mediaSession?.getSessionConfig().setIceTransportPolicy?.(S)}async joinOrStartWithMedia(g,f,S,v,C,_){const T=this.logger.createFnLogger("joinOrStartWithMedia",C);this.callStats.localStats.audio.start();const I=g.callStartOptions,b=I&&1&I.preheatFlags;if(this._startCallPhase=createPhaseExecutor(T),g.callStartOptions?.sendMediaModalities&&(this.mediaStateConfigurationHelper=new Or(g.callStartOptions.sendMediaModalities)),this._preferredMpLocation){g.callStartOptions=g.callStartOptions||{};const f=g.callStartOptions.clientEndpointDebugContent?JSON.parse(g.callStartOptions.clientEndpointDebugContent):{};g.callStartOptions.clientEndpointDebugContent=JSON.stringify({preferredMpLocation:this._preferredMpLocation,...f})}try{I&&!b&&this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)&&this.mediaStateConfigurationHelper.isSending(2)&&(this.setCallUsesMixer(!0,C),await this.getScreenHandle().acquire()),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,C),this.callUsesMixer||this.mediaStateConfigurationHelper.disableModality(2),T.info(`skipSharingModality=${!this.callUsesMixer}`),this._startCallPhase.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(C,I?.mediaConfiguration))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.getSessionConfig().config.alwaysNegotiateDataChannel&&this.mediaStateConfigurationHelper.enableModality(3),this.setSessionIceTransportPolicy(g?.callStartOptions?.mediaConfiguration),this.mediaSession.createAudioElement(C),this.callUsesMixer||_||this.isOneToOnePSTNCall()||g.callVoicemailStartOptions||this.setIsSomeoneStreamingVideo(!0);const A=this._callOperationHandler.createPendingOperation("_WaitForAnswer","",C,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});A.catch(noop);let P=!1;g.isPromotingToRealtime?(this.isSpeakerMuted=!0,P=!0,await this._startCallPhase.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(C))),await this._startCallPhase.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(C)))):I&&(b?(P=!0,await this._startCallPhase.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(C))),await this._startCallPhase.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(C))),this.setMuted(2,C),this.setCallUsesMixer(!0,C)):this.mediaStateConfigurationHelper.isSending(1)&&await this._startCallPhase.execute("StartVideoSafe",(()=>this.startVideoSafe(C)))),I?.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient();const R=await this._startCallPhase.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,C)));if(!this.mediaSession?.createOfferAsync)throw{error:"NoMediaSession",phase:"CreateOffer"};const M=await this._startCallPhase.execute("CreateOffer",(()=>this.mediaSession.createOfferAsync(C))),w=this._startCallPhase.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(this.calculateModalityDirections({},C))));if(this.mediaStateConfigurationHelper.isSending(2)&&this.updateScreenSharingState(R,C),P||(await this._startCallPhase.execute("MuteUnmute",(()=>this.muteUnmute(2===this._muteState,C))),await this._startCallPhase.execute("MuteUnmuteSpeakers",(()=>this.muteUnmuteSpeaker(this.isSpeakerMuted,C)))),this._startCallPhase.executeSync("CallStart",(()=>f(C,g,M,w,S,_))),await this._startCallPhase.execute("WaitForConnect",(()=>v)),!this.isCallModeStreaming()||g.isPromotingToRealtime){const g=await this._startCallPhase.execute("WaitForAnswer",(()=>A));if(!this.mediaSession?.processAnswerAsync)throw{error:"NoMediaSession",phase:"ProcessAnswer"};await this._startCallPhase.execute("ProcessAnswer",(()=>this.mediaSession.processAnswerAsync(g,C,!1))),await this._startCallPhase.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(C)))}this.callTelemetry.updateOperationData("_ConnectCall",{phases:this._startCallPhase.getTelemetryData()},C),this._startCallPhase=void 0,2!==I?.screenshareDirection&&4!==I?.screenshareDirection||(this.allowScreenSharingControl()&&this.screenSharingControl.isInternalSharerControlEnabled()&&this.screenSharingControl.initControlForSharer(""),this.enableControlInjector())}catch(g){this.catchJoinOrStartCallError(g,C,T)}}catchJoinOrStartCallError(g,f,S){let v,C=0;throw S.logFailure(getPrintableObject(g)),g?.error&&(v={...g.error}),isPhaseError("MuteInput",g)?(C=7,v={code:Fi.LocalError,subCode:xi.MediaMuteMicrophoneError,phrase:getPrintableObject(g),causeId:f}):isPhaseError("MuteOutput",g)?(C=7,v={code:Fi.LocalError,subCode:xi.MediaMuteSpeakerError,phrase:getPrintableObject(g),causeId:f}):g?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer||isOneOfPhaseErrors(Wi,g)?C=47:g?.type===this.mediaAgent.constants.MEDIA_ERROR.permissionDeniedError?(C=58,v={code:Fi.MediaError,subCode:xi.MediaPermissionError,phrase:getPrintableObject(g),causeId:f}):isPhaseError("WaitForAnswer",g)||isPhaseError("WaitForConnect",g)?C=g.error:isOneOfPhaseErrors(qi,g)&&(C=7),this.callTelemetry.updateOperationData("_ConnectCall",this.getTelemetryFromPhaseExecution(g),f),this._startCallPhase=void 0,this.callSetupFailed=!0,Promise.all([this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",C,"",f),this._callOperationHandler.maybeRejectOperation("_ConnectCall",C,"",f)]).then((()=>{this.isPromotingToRealtime()||this.stopInternal({causeId:f,terminatedReason:C,rejectReason:v})})).catch(noop),C}addCallMeBackParticipant(g,f,S){const v=this._participantOperationHandler.waitForOperation("CallMeBack",g),C=this.logger.createFnLogger("CallMeBack",S),_={id:g,assertedId:f};return this.signalingSession.callMeBackAsync(_).then((()=>{C.logSuccess(`successfully executed call me back, participantId = ${scrubMriOrOmit(g)}`),this._participantOperationHandler.resolveOperation("CallMeBack",0,g)})).catch((v=>{C.logFailure(`Call me back failed, participantId = ${scrubMriOrOmit(g)}, error = ${v}`),this._handleParticipantOperationFailure("CallMeBack",v,S,f,!1);const _=this._processError(v);let T={};_&&(T={..._}),T.failureReason=_.reason?_.reason:11,this._participantOperationHandler.rejectOperation("CallMeBack",T,g)})),v}addParticipantsToCall(g,f,S,v,C,_,T,I,b,A){const P=this.logger.createFnLogger("addParticipantsToCall",f);g.forEach((g=>{g.setState(1,void 0,f)}));const R=g.map((g=>({id:g.mri})));P.info(`participantIds=${g.map((g=>scrubMriOrOmit(g.id)))}, disableUnmute=${T}`);const M={additionalData:S,groupId:v,threadId:C,messageId:_,disableUnmute:T,alternateId:I,customHeaderContext:b,callingLineIdentity:A};try{const g=this.signalingSession.addParticipantsAsync(R,M,f);return(0,Ki.zip)(g,R).map((async([g,S])=>{try{const v=await g;this.signalingNotifications.onParticipantJoined(v,f);const C=this._getParticipantLegId(this.getParticipant(S.id)),_=C?{participantLegId:C}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},v.id,f,_)}catch(g){const v=this._handleParticipantOperationFailure("AddParticipant",g,f,S.id).reason;throw this._removeParticipant(S,f,v),v}}))}catch(g){return P.logFailure(`Participants was not added to call, error=${g}`),(0,Ki.range)(R.length).map((()=>Promise.reject(1)))}}async mergeCallByAddParticipantWithReplaces(g,f,S,v,C,_,T,I){const b=this.logger.createFnLogger("mergeCallByAddParticipantWithReplaces",_),A=this.convertClientScenario(I),P={additionalData:g.additionalData,groupId:g.groupId,threadId:g.threadId,messageId:g.messageId,callIdToReplace:S.callId,replacementType:v,clientScenario:A},R=await this.signalingSession.addParticipantsAsync(f,P,_);for(let g=0;g<R.length;g++){const S=3===v?f[g].participantId:f[g].id;try{await R[g],b.logSuccess(` [participantInfos id =${scrubMriOrOmit(f[g].id)}]`);const v={debugContent:{replacementParticipantLegId:f[g].replacementParticipantId||void 0,clientScenario:A},participantLegId:f[g].participantId},T={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(C,T,S,_,v),this._callOperationHandler.maybeResolveOperation(C,T,S,_)}catch(v){b.logFailure(`Participant was not added to call, error=${getPIISafeObject(v)}`);const T=this._handleParticipantOperationFailure(C,v,_,S,!0,A).reason;this._removeParticipant(f[g],_,T);const I=v?v.endCode:T||0;this._callOperationHandler.maybeRejectOperation(C,I,S,_)}}return Promise.resolve(T)}admitParticipantToCall(g,f,S){const v=this.logger.createFnLogger("admitParticipantToCall",f),C={id:g};return v.info("start"),this.signalingSession.admitParticipantAsync(C,f).then((C=>{v.info(`successfully admitted participant to call, participantId = ${scrubMriOrOmit(g)}`);const _=S?{participantLegId:S}:{},T={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess("AdmitParticipant",T,g,f,_)})).catch((S=>{v.logFailure(`Participant was not admitted to call, error=${S}`);const C=this._handleParticipantOperationFailure("AdmitParticipant",S,f,g);return Promise.reject(C)}))}_processError(g){let f;const S={reason:f};if(g?.endCode){const v=getTerminationCode(g.endCode.code,g.endCode.subCode);f=_PluginlessCall2.getParticipantReasonFromTerminatedReason(v),S.reason=f,S.code=g.endCode.code,S.subCode=g.endCode.subCode,S.resultCategories=g.endCode.resultCategories,S.phrase=g.endCode.phrase}else S.phrase=`${g}`;return this.logger.info(`_processError error=${g} telemetryData=${JSON.stringify(S)}`),S}_handleParticipantOperationFailure(g,f,S,v,C=!0,_){this.callTelemetry.updateOperationData(g,{error:getPIISafeObject(f)},S,v);const T=this._processError(f),I=this.getParticipant(v);T.code&&I&&(I.callEndDiagnosticsInfo={callControllerCode:T.code,callControllerSubCode:T.subCode,phrase:T.phrase,resultCategories:T.resultCategories});try{if(C){const f={debugContent:{clientScenario:_},participantLegId:this._getParticipantLegId(I)||void 0};this.callTelemetry.recordOperationFailure(g,T,v,S,f)}}catch(g){this.logger.info(`_handleParticipantOperationFailure error during recordOperationFailure ${g}`)}return T}_getParticipantLegId(g){return(0,Ki.has)(g,"endpoints.endpointDetails")&&g.endpoints.endpointDetails.length&&g.endpoints.endpointDetails[0].participantId?g.endpoints.endpointDetails[0].participantId:null}isOneToOnePSTNCall(g=!1){const f=this.signalingSession.isIncomingCall?this.callerMri:this.participants.length>0?this.participants[0].id:"";return this.isOneToOneCall(g)&&(0,Ki.startsWith)(f,or)&&(!this.incomingCallType||!this.callUsesMixer)}isParkedCall(){return this.isOneToOnePSTNCall()&&!!this.callOptions?.parkContext}async updateMediaModalities(g={},f=generateCauseId(),S){let v;const C=this.logger.createFnLogger("updateMediaModalities",f);return C.info(`callUsesMixer=${this.callUsesMixer},isSomeoneSharing=${this.isSomeoneSharing},isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),C.info(`options=${safeJsonStringify(g)},requestHoldState=${this.requestedHoldState},requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}`),v=g.modalityOverride?g.modalityOverride:this.requestedHoldState&&!this.isMuteOnHold?this.getMediaModalitiesForHold(f):this.calculateModalityDirections(g?.offered,f),C.info(`modalities=${safeJsonStringify(v)}`),await this.mediaSession.configureModalitiesAsync(v,f,S),v}calculateModalityDirections(g={},f){const S=this.logger.createFnLogger("calculateModalityDirections",f);S.info(`callUsesMixer=${this.callUsesMixer}, isEscalationInProgress=${this.isEscalationInProgress}`);const v={audio:this.calculateAudioDirection(g.audio,S),video:this.calculateVideoDirection(g.video,S),sharing:this.calculateSharingDirection(g.sharing,S),data:this.calculateDataDirection(g.data,S)};return S.info(`done, modalities=${safeJsonStringify(v)}`),this.deleteExtraneousModalities(v,f),v}calculateAudioDirection(g,f){return f.info(`calculateAudioDirection, offer=${g}, requestedAudioState=${this.mediaStateConfigurationHelper.isSending(0)}`),this.receiveOnlyAudioOnCallStart?(f.info("calculateAudioDirection, direction=recvonly, receiveOnlyAudioOnCallStart=true"),"recvonly"):this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)||"inactive"===g?"inactive":this.mediaSession.getAllowedModalities().audio.some((g=>g===Hr.send||g===Hr.sendReceive))?"sendrecv":"sendonly"===g?"inactive":"recvonly"}calculateVideoDirection(g,f){const S=this.mediaStateConfigurationHelper.isSending(1);if(f.info(`calculateVideoDirection, offer=${g}, requestedVideoState=${S}, isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),this.mediaStateConfigurationHelper.isInactiveOrDisabled(0))return"inactive";let v=S,C=this.isSomeoneStreamingVideo||this.callUsesMixer||this.isEscalationInProgress;return g&&(v=v&&("sendrecv"===g||"sendonly"===g),C=C&&("sendrecv"===g||"recvonly"===g)),v?"sendrecv":C?"recvonly":"inactive"}calculateSharingDirection(g,f){return f.info(`calculateSharingDirection, offer=${g}, requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}, isSomeoneSharing=${this.isSomeoneSharing}`),"inactive"===g?"inactive":this.mediaStateConfigurationHelper.isSending(2)?"sendonly":this.isSomeoneSharing||this.callUsesMixer||this.isEscalationInProgress?"recvonly":void 0}calculateDataDirection(g,f){const S=this.mediaStateConfigurationHelper.isSending(3);if(f.info(`calculateDataDirection, offer=${g}, dataEnabled=${S}`),this.allowDataChannel())return S?"inactive"===g?"inactive":"sendrecv":void 0;f.info("calculateDataDirection, disabling data since ECS flag prohibits it")}getMediaModalitiesForHold(g){this.logger.info(`[${g}][getMediaModalitiesForHold]`);const f="inactive",S={audio:f,video:f,data:this.allowDataChannel()?f:void 0,sharing:f};return this.deleteExtraneousModalities(S,g),S}deleteExtraneousModalities(g,f){!hasSendDirectionality(g.video)&&this.mediaStateConfigurationHelper.isDisabled(1)&&(this.logger.info(`[${f}][deleteExtraneousModalities] skipping videoModality`),delete g.video),!hasSendDirectionality(g.sharing)&&this.mediaStateConfigurationHelper.isDisabled(2)&&(this.logger.info(`[${f}][deleteExtraneousModalities] skipping sharingModality`),delete g.sharing)}getSignalingMediaTypes(g){const isSendActive=g=>g===this.mediaAgent.constants.MEDIA_STATE.send||g===this.mediaAgent.constants.MEDIA_STATE.sendReceive,f=[];return g.audio&&g.audio!==this.mediaAgent.constants.MEDIA_STATE.inactive&&f.push("Audio"),isSendActive(g.video)&&f.push("Video"),g.sharing===this.mediaAgent.constants.MEDIA_STATE.send?f.push("ScreenSharer"):g.sharing===this.mediaAgent.constants.MEDIA_STATE.receive&&f.push("ScreenViewer"),f}enableControlInjector(){if(this.allowScreenSharingControl())if(this.getlocalScreenShareStream()){const g=this.mediaSession?.getLocalMediaTrackId("ScreenShare")??"";this.screenSharingControl.enableControlInjector(g)}else this.logger.warn("enableControlInjector: no local screenshare stream found")}createCallDeviceManager(){return new Xa(this.mediaAgent.getConfigProvider().config.allowVirtualDeviceInCall,this.mediaAgent.getDeviceManager(),this.logger.createChild("CallDeviceManager"),this.callStats,(g=>this.isMediaSending(g)))}initializeSignalingSession(g){if(this.signalingSession)return void this.logger.info("Session already exists!");const f=an.CALL_STATUS;if(this.localSignalingParticipant={id:generateAliasedMri(`${rr}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri),displayName:this.currentUserSkypeIdentity.displayName,endpointDetails:[],languageId:null,participantId:g,endpointId:null},this.accountConfiguration){if(this.localSignalingParticipant.applicationType=this.accountConfiguration.applicationType,this.callTelemetry.setApplicationType(this.accountConfiguration.applicationType),this.localSignalingParticipant.ring=this.accountConfiguration.ring,this.callTelemetry.setRing(this.accountConfiguration.ring),this.localSignalingParticipant.region=this.accountConfiguration.region,this.callTelemetry.setRegion(this.accountConfiguration.region),this.localSignalingParticipant.userHexCID=this.accountConfiguration.userHexCID,this.callTelemetry.setUserHexCID(this.accountConfiguration.userHexCID),this.localSignalingParticipant.partition=this.accountConfiguration.partition,this.callTelemetry.setPartition(this.accountConfiguration.partition),this.localSignalingParticipant.acsResourceId=this.accountConfiguration.acsResourceId,this.callTelemetry.setAcsResourceId(this.accountConfiguration.acsResourceId),this.callStats.setAcsResourceId(this.accountConfiguration.acsResourceId),this.accountConfiguration.serviceUrls){const g=this.accountConfiguration.serviceUrls.calling_conversationServiceUrl,f=this.accountConfiguration.serviceUrls.calling_uploadLogRequestUrl;this.signalingAgent.updateUrls(g,f,this.accountConfiguration.enforceUrls)}this.localSignalingParticipant.clientType=this.accountConfiguration.clientType,this.callTelemetry.setClientType(this.accountConfiguration.clientType)}this.callStats.localStats.setLocalUserId(this.localSignalingParticipant.id),this._callOperationHandler&&this._callOperationHandler.resetOperationChain(),this.signalingNotifications={onPromotionCompleted:(g,f,S)=>{this.logger.info(`[${S}][onPromotionCompleted] isFailed=${g} reason=${safeJsonStringify(f)} callMode=${this.callMode}`);const v=g?f:{code:0,subCode:0};if(this.callTelemetry.recordEvent("PromotionCompleted",{reason:v},S),g){const g=convertReason(f);this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",g,"",S),this._callOperationHandler.maybeRejectOperation("_CallStartOrJoinInitiated",g,"",S),this._callOperationHandler.maybeRejectOperation("_ConnectCall",g,"",S),this.promotionCompletedDeferred?.reject(g)}else this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,S),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,S);this.participants.forEach((g=>{g.applyCachedMediaStreams(S)}))},onCallStatusChanged:(g,S,v=generateCauseId())=>{const C=this.logger.createFnLogger("onCallStatusChanged",v);let _=`[status=${g}]`;if(S&&(_+=`[reason=${safeJsonStringify(S)}]`,void 0!==S.code&&(this.callEndDiagnosticsInfo={callControllerCode:S.code,callControllerSubCode:S.subCode,phrase:S.phrase,resultCategories:S.resultCategories},(S.overflowJoinInformation||S.registrationInformation)&&(this.callEndDiagnosticsInfo.additionalDiagnostics={overflowInformation:S.overflowJoinInformation,registrationInformation:S.registrationInformation}))),C.info(_),this.callTelemetry.recordEvent("_SignalingStateChanged",{status:g,reason:S},v),g===f.CONNECTING)this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,v);else if(g===f.RINGING)2===this.audioStreamState?(this.setCallState(9,v),this.participants.forEach((g=>g.setState(6,void 0,v)))):this.participants.forEach((g=>g.setState(2,void 0,v))),this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,v);else if(g===f.CONNECTED_FOR_ROSTER_ONLY)this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,v),this._callOperationHandler.maybeResolveOperation("SubscribeWithMeetingData",void 0,void 0,v);else if(g===f.CONNECTED){this._callIsSetupComplete=!0;const g=this.getLocalSignalingEndpointDetails();(g?.isLobby||g?.streamLobby)&&(this._callInLobby=!0,this.updateCapabilities(v,!0));const f=this.signalingSession.participantManager.localParticipant.isStaging;if(11===this.state)this.setCallState(12,v);else if(this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))C.info("wait for joinPreheatedCall to resolved");else if(this._callInLobby)C.info("[inLobby] Override Connected state from signaling agent"),this.setCallState(10,v);else if(f)this.setCallState(13,v);else{if(3===this.state&&!this._callOperationHandler.hasPendingOperation("_CallStartOrJoinInitiated")&&!this._callOperationHandler.hasPendingOperation("_ConnectCall"))return void C.info("Return: Don't re-send setup telemetry if call was already connected and operations are completed");this.setCallState(3,v),this.handleRemoteParticipantStateInOneToOneCall(v)}this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,v),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,v),this.reportTsCallingTelemetry(!0)}else if(g===f.LOCAL_TERMINATED||g===f.REMOTE_TERMINATED){let _=this.callSetupFailed?7:convertReason(S);if(8===this.state&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData"]))return this.signalingSession.resetState(),this._callOperationHandler.maybeRejectOperation("Subscribe",_,void 0,v),this._callOperationHandler.maybeRejectOperation("SubscribeWithMeetingData",_,void 0,v),void C.info("Subscribe failed, there is pending start/join operation, ignore call end message");if(1!==_&&S?.code===Fi.MediaError&&S?.subCode===xi.MediaPermissionError&&(_=58,C.info(`[terminated][reason=${safeJsonStringify(S)}]`)),(2===this.state||6===this.state||8===this.state)&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData","Subscribe","SubscribeWithMeetingData"])){const g={code:this.callEndDiagnosticsInfo.callControllerCode,subCode:this.callEndDiagnosticsInfo.callControllerSubCode,phrase:this.callEndDiagnosticsInfo.phrase,reason:_};this._callOperationHandler.maybeRejectOperations(["Accept","JoinCall","JoinWithMeetingData","JoinPreheatedCall","StartCall","StartCallAndUnpark","StartCallToVoiceMail","StartCallWithNudge","StartWithMeetingData","Subscribe","SubscribeWithMeetingData"],_,void 0,v,g)}this.signalingSession.acceptedElsewhereBy&&(this.acceptedElsewhereBy={id:this.signalingSession.acceptedElsewhereBy.id,displayName:this.signalingSession.acceptedElsewhereBy.displayName}),this.signalingSession.parkAdditionalContextJson&&(this.parkAdditionalContextJson=this.signalingSession.parkAdditionalContextJson),this.signalingSession.serverHoldLocation&&(this.serverHoldLocation=this.signalingSession.serverHoldLocation),this._callOperationHandler.hasPendingOperation("CallParkV2")&&S.pickupCode&&0===S.code&&this._callOperationHandler.resolveOperation("CallParkV2",""+S.pickupCode,void 0,v),1!==_&&this.mediaRelayWhiteListingIssue&&(_=53,C.info(`[terminated][reason=${safeJsonStringify(S)}]`)),this._callOperationHandler.maybeRejectOperation("CallParkV2",_,"",v),this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",_,"",v),this._callOperationHandler.maybeRejectOperation("_ConnectCall",_,"",v);const T=this.mediaSession?.getSessionConfig().config.setDisconnectAfterCleanUp;if(T?this.setTerminatedReason(_):this.setCallState(7,v,_),this.participants.forEach((g=>g.setState(4,void 0,v))),!this.disconnectingPromise){const _={...S,remoteTerminated:g===f.REMOTE_TERMINATED};this.disconnectingPromise=this.cleanUp(v,_).catch((g=>{C.logFailure(`Error when cleaning up the call, callId = ${this.callId}, error = ${g}`)}))}T&&this.disconnectingPromise.finally((()=>{7!==this.state&&this.setCallState(7,v,_)}))}},onOffer:(g,f=generateCauseId())=>{const S=this.logger.createFnLogger("onOffer",f);S.info(`${safeJsonStringify((0,Ki.omit)(scrubObjectFields(g),"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(g.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnOffer",this.prepareTelemetryForOfferAnswer(g),f),g.transferor?.details?.id&&this.setTransferorMri(g.transferor.details.id),g.transferor?.transferorType&&(this.transferorType=g.transferor.transferorType),g.transferor?.details?.displayName&&(this.transferorDisplayName=g.transferor.details.displayName),this.clientTransferContext=g.clientTransferContext,this.customHeaderContext=g.customHeaderContext,this.invitationData=g.invitationData,this.spamRiskLevel=g.riskLevel,this.spamStirAttestation=g.stirAttestation,g.mediaContent.isTwoPartyToMultiPartyEscalation&&this.setIsEscalationInProgress(!0,f),g.renegotiation?this.requestedHoldState&&this._pendingParkPromise?this.renegotiateIncoming(g.mediaContent,f):this._delayedElevationPending||this._delayedElevationQueued?(this.signalingSession.rejectRenegotiationAsync({},f),this.triggerDelayedReconnectIfNeeded(f,"onOffer")):this._callOperationHandler.executeChained((()=>this.renegotiateIncoming(g.mediaContent,f)),"_RenegotiateIncoming",f,f,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}):(S.info("resolving attach / offer promise"),this.attachToCallAndGetOffer.resolve(g.mediaContent))},onNewOffer:(g,f=generateCauseId())=>{const S=this.logger.createFnLogger("onNewOffer",f);this.newOfferRequestDeferred?(S.info("onNewOffer"),this.newOfferRequestDeferred.resolve(g.mediaContent)):S.info("callback received but new offer was not requested")},onAnswer:(g,f=generateCauseId())=>{const S=this.logger.createFnLogger("onAnswer",f);if(S.info(`${safeJsonStringify((0,Ki.omit)(g,"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(g.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnAnswer",this.prepareTelemetryForOfferAnswer(g),f),g.renegotiation)S.info("resolving previous renegotiation promise"),this.renegotiationAnswerDeferred.resolve(g.mediaContent);else if(S.info("resolving final answer promise"),g.provisional){const S=this.isOneToOnePSTNCall()&&(0,Ki.startsWith)(g.remoteParticipantId,or);this.mediaSession.processAnswerAsync(g.mediaContent,f,!0,S)}else this._callOperationHandler.maybeResolveOperation("_WaitForAnswer",g.mediaContent,void 0,f),this.handleRemoteParticipantStateInOneToOneCall(f);g.provisional||!g.mediaContent.fromMixer||this.callUsesMixer||this._callOperationHandler.executeChained((async()=>{this.setCallUsesMixer(!0,f),this.mediaStateConfigurationHelper.isDisabled(2)&&this.mediaStateConfigurationHelper.removeModality(2),await this.updateMediaModalities(void 0,f);const g=!(this.isSomeoneSharing||this.isScreenSharingOn||this.isVideoOn);return(this.isOneToOnePSTNCall()?this.mediaSession.getSessionConfig().config.callElevationDelayReconnectPSTN:this.mediaSession.getSessionConfig().config.callElevationDelayReconnect)&&g?(S.info("Delayed elevation: pending"),this._delayedElevationPending=!0,Promise.resolve()):this.mediaSession.reconnectAsync(f,!0)}),"_CallEscalatedToConference",f,f,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})},onMediaAcknowledgementSuccess:(g,f=generateCauseId())=>{this.logger.info(`isRenegotiation: ${g}`,"onMediaAcknowledgementSuccess",f),this._callOperationHandler.resolveOperation("_MediaAcknowledgment",void 0,void 0,f)},onMediaAcknowledgementFailure:(g,f,S=generateCauseId())=>{this.logger.createFnLogger("onMediaAcknowledgementFailure",S).logFailure(safeJsonStringify(f)),this._callOperationHandler.rejectOperation("_MediaAcknowledgment",f,S)},onMediaRenegotiationRejection:(g,f=generateCauseId())=>{this.logger.createFnLogger("onMediaRenegotiationRejection",f).logFailure(safeJsonStringify(g)),this.renegotiationAnswerDeferred.reject(g)},onRosterHandlingComplete:()=>{this.logger.info(`[onRosterHandlingComplete] ${this._publishedStatesModified}`),0!==this._publishedStatesModified&&(this.processPublishedStates(),this._publishedStatesModified=0)},onMeetingGroupDetailsUpdated:(g,f=generateCauseId())=>{this.meetingGroupDetails!==g&&(this.callTelemetry.recordEvent("_UpdateMeetingGroupDetails",g,f),this.logger.info(`[${f}][onMeetingGroupDetailsUpdated] update meetingGroupDetails from ${JSON.stringify(this.meetingGroupDetails)} to ${JSON.stringify(g)}`),this.meetingGroupDetails=g,this.raiseChanged())},onSelfParticipantUpdated:(g,f=generateCauseId())=>{this.logger.info(`[${f}][onSelfParticipantUpdated]`),this.updateLocalParticipant(g,f),this.raiseChanged()},onParticipantMriUpdated:(g,f,S=generateCauseId())=>{this.logger.info(`[${S}][onParticipantMriUpdated]`);const v=this.getParticipant(g);v&&(v.id=f,this.raiseChangedDeferred())},onParticipantUpdated:(g,f=generateCauseId())=>{this.logger.info(`[${f}][onParticipantUpdated]: ${scrubSignalingParticipant(g)}`);const S=this.getOrCreateParticipant(g.id,f,!0);S.displayName=g.displayName;const v=_PluginlessCall2.getStreamsFromEndpoints(g.endpointDetails,this.isMultiVBSSEnabled()),C=(0,Ki.some)(g.endpointDetails,(g=>g?.streamInformation));this.callUsesMixer||v.length>0||C?(this.updateParticipantStreams(S,g,v,f),this.updateCallParticipantFromSignalingParticipant(S,g,f)):S.setState(3,void 0,f),S.processParticipantDetails(g,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(g),this.calculateIsSomeoneStreaming(f),this.raiseChangedDeferred()},onParticipantRemoved:(g,f=generateCauseId(),S=!1)=>{if(this.logger.info(`[${f}][onParticipantRemoved]`),S){const S=this.getParticipant(g.id);this.callTelemetry.recordOperationSuccess("_ParticipantJoined",null,S?.id,f,{participantJoinedButReplaced:"Participant joined with original MRI and replaced with participant of RNL MRI"})}else this.callTelemetry.recordOperationSuccess("RemoveParticipant",null,g.id,f),this._participantOperationHandler.maybeRejectOperation("AddParticipant",1,g.id,f);this._removeParticipant(g,f),this.removePublishedStatesByParticipant(g.id),this.calculateIsSomeoneStreaming(f)},onParticipantJoined:(g,f=generateCauseId())=>{this.logger.info(`[${f}][onParticipantJoined]`);const S=!this.getParticipant(g.id),v=this.getOrCreateParticipant(g.id,f,!1);v.displayName=g.displayName,0===v.state&&v.setState(1,void 0,f);const C=_PluginlessCall2.filterVirtualEndpoints(g.endpointDetails),_=_PluginlessCall2.getStreamsFromEndpoints(C,this.isMultiVBSSEnabled()),T=(0,Ki.some)(g.endpointDetails,(g=>g?.streamInformation));this.callUsesMixer||_.length>0||T?(this.updateParticipantStreams(v,g,_,f),this.updateCallParticipantFromSignalingParticipant(v,g,f),this.calculateIsSomeoneStreaming(f)):(this.handleRemoteParticipantJoinedInOneToOneCall(g,f),this.handleRemoteParticipantStateInObservingCall(v,g,f),g.acceptedBy&&g.acceptedBy!==g.id&&(v.acceptedBy=g.acceptedBy)),this.callTelemetry.recordOperationSuccess("_ParticipantJoined",getEndpointInformationForTelemetry(g.endpointDetails),v.id,f),v.processParticipantDetails(g,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(g),S&&this.event("participantAdded").raise(v),this.raiseChangedDeferred()},onCallModeChanged:(g,f)=>{this.callTelemetry.recordEvent("_CallModeChanged",{newCallMode:g,oldCallMode:this._callMode},f),this.logger.info(`onCallModeChanged[${f}]: new=${g} old=${this._callMode} `),g&&this._callMode!==g&&(this._callMode=g,this.isCallModeStreaming()&&this.cleanUpDueToStreaming(f),1===this._callMode&&(this.participants.forEach((g=>{g.applyCachedMediaStreams(f)})),this.promotionCompletedDeferred?.resolve()),this.monitorCallStart(),this.updateCapabilities(f),this.raiseChanged())},getRemoteParticipantCollection:()=>this.participants.map((g=>g.toCafeParticipant())),onReTargetCompletedSuccess:g=>{const f=this.logger.createFnLogger("onReTargetCompletedSuccess",g);f.info(`started, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetSuccess",void 0,g),this.callStats.localStats.call.event(3);const S=this.isEscalationInProgress;this.screenSharingControl&&this.screenSharingControl.shutdownControlForViewer(),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.completeEscalationAsync(g).then((()=>(f.logSuccess("completeEscalationAsync"),this.callTelemetry.recordEvent("_WebOnEscalationSuccess",void 0,g),this.handleCallEscalation(S,g),this.updateMediaStatus(g)))).catch((S=>{f.logFailure(`completeEscalationAsync, error=${getPrintableObject(S)}`),this.setIsEscalationInProgress(!1,g),this.callTelemetry.recordEvent("_WebOnEscalationFailure",getPIISafeObject(S),g),this.stopInternal({causeId:g,terminatedReason:47})}))},onReTargetCompletedFailure:(g,f)=>{this.logger.createFnLogger("onReTargetCompletedFailure",f).logFailure(`reason=${getPrintableObject(g)}, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetFailure",getPIISafeObject(g),f),this.isEscalationInProgress&&(this.setIsEscalationInProgress(!1,f),this.setCallUsesMixer(!1,f),this.updateMediaStatus(f)),this.callStats.localStats.call.event(4),this.mediaSession.rejectEscalationAsync(g,f)},onChatModalitySetupFailed:g=>{this.logger.debug(`onChatModalitySetupFailed: ${g}`)},onConversationUpdated:(g,f)=>{this.logger.info(`onConversationUpdated[${f}]: ${JSON.stringify(scrubObjectFields(g,["organizerId","meetingData"]))}`),this.setConversationType(g.conversationType,f),this._onMessageIdChanged(g.teamsMessageId,f),this.setGroupId(g.groupId,f),this.setThreadId(g.threadId,f),this.setBackroomThreadId(g.backroomThreadId,f),this.setStreamThreadId(g.streamThreadId,f),this.setLobbyThreadId(g.lobbyThreadId,f),this.setCallType(g.isMultiParty?2:1,f),this._commandUrlPresence=g.commandUrlPresence,this.updateCapabilities(f),this.region=g.region,this.setMeetingData(g.meetingData),this.meetingInfo=g.meetingInfo,this.callLimits=g.callLimits,this.setComplianceRecordingContent(f,g.complianceRecordingContent),this.setHuddleGroupCall(g.isHuddleGroupCall),this.onConversationStartTimeChanged(g.conversationStartTime,f),this.raiseChanged()},onMeetingDetailsUpdated:g=>{this.meetingDetails=g,this.mediaSession&&!this.enableRealtimeTelemetry&&this.meetingDetails.meetingCapability?.enableRealtimeTelemetry&&(this.mediaSession.enableTeamsRealTimeTelemetry(),this.enableRealtimeTelemetry=!0),this.raiseChanged()},onMeetingStatesUpdated:g=>{(0,Ki.isEqual)(g,this.meetingStates)||(this.meetingStates=g,this.logger.info(`[onMeetingStatesUpdated] meetingStates updated to ${JSON.stringify(this.meetingStates)}`),this.raiseChanged())},onParticipantCountsUpdated:g=>{(0,Ki.isEqual)(g,this.participantCounts)||(this.participantCounts={...Si,...g},this.event("participantCountsUpdated").raise(this.participantCounts),this.mediaSession?.processNotification("ParticipantCountChanged",{count:g.totalParticipants}))},updateIsSharedLineAppearanceV2Activated:g=>{this.isSharedLineAppearanceV2Activated!==g&&(this.logger.info(`_updateIsSharedLineAppearanceV2Activated: new value is ${g}`),this.isSharedLineAppearanceV2Activated=g,this.event("sharedLineAppearanceV2ActivatedChanged").raise(this.isSharedLineAppearanceV2Activated))},onBroadcastMeetingUpdated:g=>{g&&(this.broadcastMeeting&&this.broadcastMeeting.metadataChanged(JSON.stringify(g)),this.broadcastMetadata=g,this.raiseChanged())},onBroadcastMeetingConnected:(g,f)=>{this.logger.info(`[${f}][onBroadcastMeetingConnected]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&(0===g.code?this._callOperationHandler.resolveOperation("AddBroadcastModality",g,f):this._callOperationHandler.rejectOperation("AddBroadcastModality",g,f))},onBroadcastMeetingEnded:(g,f)=>{this.logger.info(`[${f}][onBroadcastMeetingEnded]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&this._callOperationHandler.rejectOperation("AddBroadcastModality",g,f),this.signalingSession.endBroadcastMeeting(f)},onTransferRequested:(g,f)=>{const S=this.logger.createFnLogger("onTransferRequested",f);S.info("Transfer: onTransferRequested, target participant",scrubSignalingParticipant(g.target));let v="",C="",_=0;"voicemail"===g.target.endpointType&&(_=2);try{v=g.target.id,C=g.transferor.details.id,g&&g.parkType&&"none"!==g.parkType&&(_=1)}catch(g){return S.logFailure(g),this.callTelemetry.recordEvent("_OnTransferRequestedInvalid"),void this.signalingSession.signalTransferCompletedAsync({code:getCSAEndCode(7)})}const T=this.convertToTransferType(_,g.parkType),I={transferContext:{transferorMri:C,targetMri:v,transferType:_,context:{target:g.target,transferor:g.transferor,transferContext:g.transferContext,newCallModalities:g.newCallModalities,links:g.links,replacementDetails:g.replacementDetails,isConsultative:g.isConsultative,callAcceptanceCallback:()=>{S.logSuccess("Transfer: callAcceptanceCallback called"),this.signalingSession.signalTransferAcceptedAsync(T)}}},onCompleted:g=>{S.logSuccess("Transfer: onCompleted called"),this.signalingSession.signalTransferCompletedAsync({code:getCSAEndCode(g)})}};this.callTelemetry.recordEvent("_OnTransferRequested",{transferType:_}),this.event("transferRequested").raise(I)},onTransferredCallAcceptance:g=>{const f=this.logger.createFnLogger("onTransferredCallAcceptance",g);this._transferredCallAcceptanceCallback&&(f.info("[Transfer] Invoke call acceptance callback for original call"),this._transferredCallAcceptanceCallback())},onTransferAccepted:g=>{this.logger.info("Transfer: onTransferAccepted"),this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&this._setTransferState(2),this._callOperationHandler.hasPendingOperation("BlindTransfer")&&this._callOperationHandler.maybeResolveOperation("_CallTransferInProgress",void 0,void 0,g),this._callOperationHandler.hasPendingOperation("ParkCall")&&this._setParkState(2)},onTransferCompleted:(g,f)=>{const S=this.logger.createFnLogger("onTransferCompleted",f);S.info("Transfer: onTransferCompleted");const v=g.transferCompletion,C=convertReason(v);if(v&&(S.info(`Transfer: Call Transfer Code: ${v.code}`),0===v.code)){if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.resolveOperation("_CallTransferInProgress",void 0,void 0,f),this._setTransferState(3)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const g={code:0,subCode:0,phrase:"TransactionComplete"};this._callOperationHandler.resolveOperation("ConsultativeTransferWithPickupCode",g,void 0,f),this._setTransferState(3)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(g.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation&&(this.serverHoldLocation=g.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),void 0!==g.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("ParkCall",g.unparkContent.pickupCode,void 0,f),S.logSuccess(`pickupCode=${g.unparkContent.pickupCode}`),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",32,f),S.logFailure(`terminatedReason=${C}`),this._setParkState(4)))}else{if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.rejectOperation("_CallTransferInProgress",C,void 0,f),S.logFailure(`terminatedReason=${C}`),this.transferDiagnosticsInfo={callControllerCode:v.code,callControllerSubCode:v.subCode,phrase:v.phrase,resultCategories:v.resultCategories},this._setTransferState(4)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const g={code:v.code,subCode:v.subCode,resultCategories:v.resultCategories};this._callOperationHandler.rejectOperation("ConsultativeTransferWithPickupCode",g,void 0,f)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(this._callOperationHandler.rejectOperation("ParkCall",C,void 0,f),S.logFailure(`terminatedReason=${C}`),this.transferDiagnosticsInfo={callControllerCode:v.code,callControllerSubCode:v.subCode,phrase:v.phrase,resultCategories:v.resultCategories},this._setParkState(4))}},onParkCompleted:(g,f)=>{this.logger.createFnLogger("onParkCompleted",f).info(`transactionEnd ${getPrintableObject(g)}`),this._callOperationHandler.hasPendingOperation("CallParkV2")?0===g.code&&void 0!==g.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("CallParkV2",""+g.unparkContent?.pickupCode,void 0,f),this.callTelemetry.maybeRecordOperationSuccess("CallParkV2"),this.serverHoldLocation=g.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation,this.parkAdditionalContextJson=JSON.stringify(g.unparkContent.CallParkAdditionalContext)):this._callOperationHandler.rejectOperation("CallParkV2",g,f):this._callOperationHandler.hasPendingOperation("ParkCall")&&(0===g.code?(this._callOperationHandler.resolveOperation("ParkCall","",void 0,f),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",g,f),this._setParkState(4)))},onUnparkCompleted:(g,f)=>{this.logger.createFnLogger("onUnparkCompleted",f).info(`transactionEnd ${getPrintableObject(g)}`),this._callOperationHandler.hasPendingOperation("UnparkCall")&&(0===g.code?this._callOperationHandler.resolveOperation("UnparkCall",g,void 0,f):this._callOperationHandler.rejectOperation("UnparkCall",g,f))},onIncomingCallReplacement:(g,f)=>{const S=this.logger.createFnLogger("onIncomingCallReplacement",f);this.callTelemetry.recordEvent("_onIncomingCallReplacement",{},f),g.callNotification.callType="replaces",g.callNotification.consultativeCallId=this.callId,S.info(`consultativeCallId=${this.callId}`),g.body={gp:g,evt:Hi.INCOMING_SKYPE_NGC_CALL,nsp:void 0},this.event("replacementRequested").raise(g)},onContentSharingStopped:g=>{this.logger.debug("ScreenSharing: onContentSharingStopped");for(const f of this.contentSharingSessions)f.contentSharingGuid===g.correlationId&&(f.contentSharingStatus=7)},onContentSharingStarted:g=>{this.logger.debug("ScreenSharing: onContentSharingStarted");const f=new us(this.callTelemetry,this.logger.createChild("ContentSharingSession"),this.signalingSession,g.correlationId||generateGuid(),g.contentIdentifier,g.sessionState,g.subject,g.sessionId);f.contentSharingStatus=2,this.contentSharingSessions.push(f),f.changed((()=>this.removeContentSessionIfEnded(f))),this.event("contentSharingChanged").raise()},onContentSharingUpdated:g=>{this.logger.debug("ScreenSharing: onContentSharingUpdated");const f=(0,Ki.find)(this.contentSharingSessions,(f=>f.contentSharingGuid===g.correlationId));f?(g.presenter&&(f.presenterId=g.presenter),g.subject&&f.subject!==g.subject&&(f.subject=g.subject),g.sessionState&&f.contentSharingState!==g.sessionState&&(f.contentSharingState=g.sessionState),3===f.contentSharingStatus&&this.localSignalingParticipant.id!==g.presenter?f.contentSharingStatus=5:5===f.contentSharingStatus&&this.localSignalingParticipant.id===g.presenter&&(f.contentSharingStatus=3)):this.logger.warn("onContentSharingUpdated: session not found")},onWebRtcMediaNotification:(g,f)=>{this.mediaSession?.processNotification(g,f)},onCorrelationIdUpdated:(g,f)=>this.checkForCallIdUpdate(g,f),onUnmuteRequested:g=>{},onCallForwarded:g=>{g&&g.destinationType!==this.forwardingDestinationType&&(this.forwardingDestinationType=g.destinationType,this.raiseChanged())},onPSTNBalanceUpdate:g=>{},isOneToOnePstnCall:()=>this.isOneToOnePSTNCall(),onUpdateMeetingLiveStateCompleted:(g,f,S)=>{this.logger.info(`[onUpdateMeetingLiveStateCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"UpdateMeetingLiveState",S)},onUpdateMeetingStatesCompleted:(g,f,S)=>{this.logger.info(`[onUpdateMeetingStatesCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"UpdateMeetingStates",S)},onUpdateMeetingGroupsCompleted:(g,f,S)=>{this.logger.info(`[onUpdateMeetingGroupsCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"UpdateMeetingGroups",S)},onSetMeetingLayoutCompleted:(g,f,S)=>{this.logger.info(`[onSetMeetingLayoutCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"SetMeetingLayout",S)},onJoinMeetingGroupCompleted:(g,f,S)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"JoinMeetingGroup",S)},onLeaveMeetingGroupCompleted:(g,f,S)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"LeaveMeetingGroup",S)},onBreakoutDetailsUpdated:(g,f)=>{this.logger.info(`[onBreakoutDetailsUpdated] [${f}]`),this.breakoutDetails=g,this.raiseChanged()},onIncomingProxiedMessages:(g,f)=>{this.logger.info(`[onIncomingProxiedMessages] [${f}] payload ${getPrintableObject(g,!0)}`),this.event("incomingProxiedMessages").raise(g)},onUpdateParticipantsPropertiesCompleted:(g,f,S)=>{this.logger.createFnLogger("onUpdateParticipantsPropertiesCompleted",S).info(`promisesToResolve ${scrubMriOrOmit(safeJsonStringify(g))}`);for(const f of Object.keys(g))g[f].code===bi.CODE.SUCCESS?this._callOperationHandler.maybeResolveOperation("UpdateParticipantsProperties",g[f],f,S):this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",g[f],f,S)},onUpdateMonitorSessionCompleted:(g,f)=>{this.logger.info(`[onUpdateMonitorSessionCompleted] [${f}] transactionEnd ${getPrintableObject(g)}`),this.onOperationCompleteCommonHandler(g,f,"UpdateMonitorSession")},onNudgeToJoinRealtime:g=>{this.logger.info("[onNudgeToJoinRealtime]",g),this.callTelemetry.recordEvent("NudgeToJoinRealTime",g),this.canPromoteToRealTime(1)&&this.promoteToRealtime(1,g).then((()=>this.logger.info(`[onNudgeToJoinRealtime][${g}] completed`))).catch((f=>this.logger.info(`[onNudgeToJoinRealtime][${g}] failed to auto promote: ${getPrintableObject(f)}`)))},onConversationTypeUpdated:(g,f)=>{this.logger.info(`[onConversationTypeUpdated] [${f}] conversationType ${g}`),this.setConversationType(g,f)}};const S=Object.create(this.localSignalingParticipant);this.signalingSession=this.signalingAgent.getNewSignalingSession(S,this.signalingNotifications,this.callId,this._callCreationTime),this.signalingSession.participantManager.setEnableMuteAsync(this._enableMuteAsync),this.signalingSession.participantManager.setEnableUnmuteAsync(this._enableUnmuteAsync),this.accountConfiguration&&this.accountConfiguration.deviceType&&this.signalingSession.setDeviceType(this.accountConfiguration.deviceType),this.setCallId(this.callId||this.signalingSession.correlationId),this.signalingSession.participantManager&&this.signalingSession.participantManager.localParticipant&&(this.setDisplayName(this.signalingSession.participantManager.localParticipant.displayName),this.setEndpointId(this.signalingSession.participantManager.localParticipant.endpointId),this.setParticipantId(this.signalingSession.participantManager.localParticipant.participantId),this.callStats.setParticipantId(this.participantId))}updateParticipantStreams(g,f,S,v){const C=_PluginlessCall2.getNegotiationTagsFromEndpoints(f.endpointDetails);g.updateStreams(S,v,this.isCallModeStreaming(),C,this.isMultiVBSSEnabled());const _=this.getStreamInformationMap(f);this.logger.info(`[updateParticipantStreams]: streaming mode with new streamInfoMap: ${safeJsonStringify(_)}`);const T={callId:this.callId,participantId:this.participantId,endpointId:this.endpointId};this.meetingData&&(T.meetingId=this.meetingData.meetingCode);const I=this.telemetryLoggers?this.telemetryLoggers.tlePlayer:null;g.useUmsStream(_,this._liveStreamConfigProvider,T,this.threadId,I,v)}cleanUpDueToStreaming(g){this.logger.info(`cleanUpDueToStreaming[${g}]: cleaning streams and media and canceling cc operations`),this.cancelAllCallingOperationsDueToStreaming(g);const f={code:Fi.Success,subCode:xi.DowngradeToStreamingClient,phrase:Gi.DowngradeToStreamingClient};this.participants.forEach((f=>f.updateStreams([],g,this.isMultiVBSSEnabled()))),this.cleanUpMedia(g,f).then((()=>{this.callTelemetry.recordOperationSuccess("_MediaCleanUp")})).catch((f=>{this.callTelemetry.recordOperationFailure("_MediaCleanUp",{error:getPIISafeObject(f)},g)})).finally((()=>{this.mediaDisposedPromise=null})),this.finishCallHoldResume(f),this.renegotiationAnswerDeferred?.reject(f),this.newOfferRequestDeferred?.reject(f),this._parkState=0,this._transferState=0,this.isServerMuted||(this._muteState=0),this.isSpeakerMuted=!1,this.requestedHoldState=!1,this.isMuteOnHold=!1}cancelAllCallingOperationsDueToStreaming(g){this._callOperationHandler.maybeRejectPendingOperationsWithPredicate(74,g,((g,f)=>(0,Ki.some)(f?.preconditionTags,(g=>"NOT_SUPPORTED_IN_STREAMING_MODE"===g))))}onOperationCompleteCommonHandler(g,f,S,v){0===g.code?this._callOperationHandler.maybeResolveOperation(S,g,v,f):this._callOperationHandler.maybeRejectOperation(S,g,v,f)}convertToTransferType(g,f){let S="none";return 1===g&&f&&"none"!==f?"teamPark"===f?S="TransferTypeTeamPark":"sharedLinePark"===f?S="TransferTypeSharedLinePark":"serverHold"===f&&(S="TransferTypeServerHold"):0===g?S="TransferTypeStandard":2===g?S="TransferTypeVoicemail":this.logger.info(`Irrelevant combination of transferTye: ${g} and parkType: ${f}`),S}raiseChangedDeferred(g){(!this.raiseChangedDefer||this.raiseChangedDefer.isSkippable&&!g)&&(Vr.instance.runDeferredWithoutDedup((()=>{delete this.raiseChangedDefer,this.raiseChanged(g)}),"Call.raiseChanged"),this.raiseChangedDefer={isSkippable:!!g})}static getStreamsFromEndpoints(g,f){if(!g)return[];const S=_PluginlessCall2.filterVirtualEndpoints(g);return S.forEach((g=>{g.mediaStreams=f?g.mediaStreams:g.mediaStreams?.filter((g=>g.type!==$r.xsharing)),(0,Ki.forEach)(g.mediaStreams,(f=>{f.participantId=g.participantId,f.endpointId=g.endpointId}))})),(0,Ki.flatMap)(S,(g=>g&&g.mediaStreams||[]))}preconditions(g,f){this.logger.info(`check call mode currentMode is ${this.callMode} operationName is ${g}`),(0,Ki.some)(f,(g=>"NOT_SUPPORTED_IN_STREAMING_MODE"===g))&&this.isCallModeStreaming(!0)}mapCallSetupIntent(g){switch(g){case 0:return"None";case 1:return"AutoPromotion";case 2:return"PromotionWithAudio";case 3:return"PromotionWithVideo";default:return"Unknown"}}async promoteToRealtime(g,f){this.logger.info(`[${f}][promoteToRealtime] started with intent=${g}`);const S=this.getPromoteToRealtimeCallOptions(g,this.callOptions);this.callTelemetry.updateOperationData("_PromotionToRealtime",{intent:g},f),this.callTelemetry.recordEvent("StartPromotion",{intent:this.mapCallSetupIntent(g)},f);try{this.promotionCompletedDeferred=new dt,await Promise.all([this.joinOrStartCall(S,this.joinGivenConversation,f,void 0),this.promotionCompletedDeferred.promise])}catch(g){throw this.logger.logFailure(`[${f}][promoteToRealtime] failed with reason=${getPrintableObject(g)}`),this.cleanUpDueToStreaming(f),this.signalingSession.cleanUpDueToStreaming(f),g}}async promoteToRealtimeAndUnmute(g){return this.logger.info(`[${g}][promoteToRealtimeAndUnmute]`),this.isPromotingToRealtime()?(this.logger.info(`[${g}][promoteToRealtimeAndUnmute] already promoting to realtime.`),this._callOperationHandler.waitForOperation("_PromotionToRealtime").then((()=>this.muteUnmute(!1,g)))):this.canPromoteToRealTime(2)?(this.unmutePendingPromise=new dt,setTimeout((()=>{this.unmutePendingPromise?.reject("promoteToRealtime unmute timed out")}),1e3*this.signalingSession.signalingAgentConfig.csaTimeoutConfiguration.promotionUnmuteTimeoutSec),Promise.all([this.promoteToRealtime(2,g),this.unmutePendingPromise.promise]).then((()=>{})).finally((()=>this.unmutePendingPromise=null))):Promise.reject("manual promotion with audio is not allowed")}isPromotingToRealtime(){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")}getPromoteToRealtimeCallOptions(g,f){let S,v=1;1===g?S={value:!0,mediaTypes:["audio"]}:3===g?(S={value:!0,mediaTypes:["audio"]},v=4):2===g&&(S={value:!1});const C={...f.callStartOptions,sendMediaModalities:{mediaStates:[getMediaState(0,4),getMediaState(1,v)].filter((g=>null!=g))},preheatFlags:0};return{...f,callStartOptions:C,applyServerMute:S,isPromotingToRealtime:!0,callStartTime:Date.now()}}canPromoteToRealTime(g){const f=this.logger.createChild("[canPromoteToRealTime]");return f.info(`[promoteType:${g}]`),this.isCallModeStreaming()?this.isPromotingToRealtime()?(f.info("already promoting to realtime"),!1):1===g||2===g:(f.info("cant promote since call mode is not streaming"),!1)}isCallModeStreaming(g=!1){if(2===this.callMode){if(!g)return!0;throw this.logger.info("reject check callmode"),{code:499,subCode:3551,phrase:"TransactionNotAllowedForStreamMode"}}return!1}setCallOptions(g){this.receiveOnlyAudioOnCallStart=!!g.callStartOptions?.receiveOnlyAudioOnCallStart,this.callOptions=g,this.logger.info(`callOptions: ${safeJsonStringify(scrubCallOptions(g))}`)}getSelfClientEndpointCapabilities(){return this.callOptions?.callStartOptions?.clientEndpointCapabilities}getLocalSignalingEndpointDetails(){return(0,Ki.find)(this.localSignalingParticipant.endpointDetails,(g=>g?.endpointId===this._endpointId))}getStreamInformationMap(g){const f={};return g&&this.accountConfiguration?.clientSupportsUms&&(0,Ki.forEach)(g.endpointDetails,(g=>{g?.streamInformation&&g.participantId&&g.participantId!==this._participantId&&(f[g.participantId]=g.streamInformation)})),f}updateSATInfo(g=[]){const f=this.mediaSession?.getSessionConfig().config.slowedDownTalkerInfoAggregationTime;if(!f||f<0)return;const S=Date.now(),v=S-1e3*f;this.activeTalkersHistory=this.activeTalkersHistory.filter((({timestamp:g})=>g>v)).concat({speakers:g.map((g=>g.id)),timestamp:S});const C=Object.entries(this.activeTalkersHistory.reduce(((g,{speakers:f})=>{for(const S of f)g[S]??(g[S]=0),g[S]++;return g}),{})).sort((([,g],[,f])=>f-g)).map((([g])=>g));this.slowedDownActiveTalkerInfo={speakerList:C,timestamp:new Date(S)}}setPlatformCallConstraints(g){this.setCallConstraints(g).catch((g=>{this.logger.error(g)}))}setCallConstraints(g){return this.mediaSession?(this.logger.info(`Applying platform constraints to current call ${JSON.stringify(g)}`),this.mediaSession.setCallConstraints(g,generateCauseId())):(this.logger.info("Saving platform constraints until media session is created"),this.temporaryCallConstraints=g,new Promise(((g,f)=>{this.resolveTemporaryCallConstraints=g,this.rejectTemporaryCallConstraints=f})))}initializeMediaSession(g,f){if(this.mediaSession)return;const S=this.logger.createFnLogger("initializeMediaSession",g),v=((g,f)=>{const S={};return Object.keys(f).forEach((v=>{S[v]=(...S)=>f[v]&&g()&&f[v](...S)})),S})((()=>!this.isCallModeStreaming()||this.isPromotingToRealtime()),{onSessionErrorOccurred:(g,f=generateCauseId())=>{S.error(`[${f}][onSessionErrorOccurred]: ${safeJsonStringify(g)}`);const v=[this.mediaAgent.constants.MEDIA_ERROR.iceConnectionError,this.mediaAgent.constants.MEDIA_ERROR.internalError];(0,Ki.includes)(v,g.type)&&this.event("mediaConnectionFailed").raise(),this.callTelemetry.recordEvent("SessionError",{type:g.type},f)},onNegotiationRequired:(g=generateCauseId(),f)=>{this.executeNegotiation(g,"onNegotiationRequired",!0,f)},onContributingSourcesChanged:g=>{const f=this.mediaSession?.getSessionConfig().config.contributingSourcesLogInterval,v=f&&Date.now()>=this.lastContributingSourceReport+f,C=v?new Map(g.map((g=>[g,"<unknown>"]))):new Map,_=[];for(const f of this.participants){const S=g.some((g=>f.hasAudioSource(g))),T=S?1:0;f.updateVoiceLevel(T),S&&(_.push(f),v&&C.set(f.audio.id,scrubMriOrOmit(f.id)))}this.updateSATInfo(_),v&&(S.info(`[onContributingSourcesChanged], ${g.length?Array.from(C).join(";"):"none"}`),this.lastContributingSourceReport=Date.now())},onDominantSpeakerChanged:(g,f)=>{const v=generateCauseId(),C=[],_=[];g.forEach((g=>{const f=(0,Ki.find)(this.participants,(f=>f.hasAudioSource(g)));f?(C.push(f.id),_.push(scrubMriOrOmit(f.id))):_.push(this.streamManager.audio.id===g?"<self>":"<unknown>")})),S.info(`[${v}][onDominantSpeakerChanged], msidList = ${g} => speakerList = ${_}, timestamp = ${f}`),this.dominantSpeakerInfo={speakerList:C,timestamp:f,noCurrentDominantSpeaker:!1},this.event("dominantSpeakerChanged").raise(),this.raiseChanged(this._dominantSpeakerChangedEventSkipConfig)},onAudioStateChanged:(g,f)=>{const S=generateCauseId(),v=this.logger.createFnLogger("onAudioStateChanged",S);v.info(safeJsonStringify(g)),this.callStats.localStats.audio.streamStateChanged(g.stream,g.direction);const C=_PluginlessCall2.streamingStatetoMediaStreamState(g.stream);if(this.audioStreamState=C,!C)return;this.callTelemetry.recordEvent("AudioStateChanged",{state:g,reason:f},S),2===C&&2===this.state&&(this.setCallState(9,S),this.participants.forEach((g=>g.setState(6,void 0,S))));const _={mediaType:0,mediaDirection:_PluginlessCall2.streamingDirectionToMediaDirectionMapping(g.direction),mediaStreamState:C};if(this.event("mediaStreamStateChanged").raise(_),!this.isCallSetupTelemetrySent&&this.mediaSession?.getSessionConfig().config.sendCallStartupTelemetry&&this.sendCallSetupTelemetry(),0===_.mediaDirection&&(this.isAudioStreamConnected=(0,Ki.includes)([2,1],_.mediaStreamState)),(0,Ki.includes)([3,4],_.mediaStreamState)&&(v.logFailure(`audio stream state changed to ${g.stream} with reason ${f}`),!f||["timeout","connection-dropped","connectivity-check-failure","suspended"].indexOf(f)>=0)){this.event("mediaConnectionFailed").raise();const g="suspended"===f?77:this.mediaRelayWhiteListingIssue?53:4;this.mediaRelayWhiteListingIssue&&this.callTelemetry.recordEvent("_MediaWhiteListingIssueDetected"),this.stopInternal({causeId:S,terminatedReason:g})}},onQualityChanged:g=>{const f={type:_PluginlessCall2.convertQualityEventType(g.type),value:_PluginlessCall2.convertQualityLevel(g.value),isLocalSource:g.isLocalSource,mediaType:_PluginlessCall2.convertMediaType(g.mediaType)};this.muteUnmuteWorkaround(f),32===f.type&&(this.mediaRelayWhiteListingIssue=3===f.value,this.mediaRelayWhiteListingIssue&&this.event("mediaConnectionWhitelistingWarning").raise()),5===f.type&&3===f.value&&this.trouterService.checkConnection(!0),this.callTelemetry.recordEvent("AudioQualityChanged",f),this.remoteUFDHandler.raiseIfNeeded(g,this.participantCounts?.totalParticipants,(g=>{this.publishState(g,generateCauseId())})),this.event("callQualityChanged").raise(f)},onOptimalVideoReceiversCountChanged:g=>{S.debug(`onOptimalVideoReceiversCountChanged: ${g}`),this.optimalVideoCount!==g&&(this.optimalVideoCount=g,this.raiseChanged())},onDataChannelUpdated:g=>{const f=generateCauseId();S.debug(`[${f}] onDataChannelUpdated`),this.dataChannel.registerSessionDataChannel(g,f)},onUpdateMediaDescriptionsRequired:(g,f)=>{this.executeNegotiation(g,"onUpdateMediaDescriptionsRequired",!1,f)},onRealtimeTelemetryReport:()=>{this.reportTelemetryEvents([{eventName:vr.realtimeTelemetry,props:{user_object_id:{value:rr+this.currentUserSkypeIdentity.id,piiKind:10},display_name:{value:this.displayName,piiKind:1},call_context_id:{value:this.signalingSession.correlationId,piiKind:0},participant_id:{value:this.participantId,piiKind:0},media_leg_id:{value:this.mediaLegId,piiKind:0},DiagnosticLevel:{value:255,piiKind:0},eventpdclevel:{value:2,piiKind:0},eventpriority:{value:5,piiKind:0},call_technical_info:{value:JSON.stringify(this.mediaSession.getCallTechnicalInfo()),piiKind:0}}}],"realtimeMedia","mdsc")},onTransportConnected:()=>{this.allowDataChannel()||this.mediaStateConfigurationHelper.isSending(3)||this.isInitialSignalingDSHSubscriptionEnabled()||!this.callUsesMixer||this.updateSignalingDSHMessageSubscription(!0),this.unmixedAudioProvider.setSessionStreamsProvider(this.mediaSession.getUnmixedAudioProvider()),this.event("transportConnected").raise()},onTransportDisconnected:()=>{this.event("transportDisconnected").raise()},onTransportFailed:()=>{this.event("transportFailed").raise()},onUpdateSignalingDSHMessageSubscription:g=>this.updateSignalingDSHMessageSubscription(g)});this.callTelemetry.recordEvent("CreatingConference","",g),this.callDeviceManager||(S.info(`[${g}][initializeMediaSession] Creating new callDeviceManager`),this.callDeviceManager=this.createCallDeviceManager());const C={maxReinvitelessMediaForVBSSMultiparty:this.signalingSession.getMaxReinvitelessMediaForVBSSForWeb(),maxReinvitelessMediaForVideoMultiparty:this.signalingSession.getMaxReinvitelessMediaForVideoForWeb()};this.callTelemetry.recordEvent("_ReinvitelessConfig",{reinvitelessConfig:C},g);const _=this.mediaAgent?.getConfigProvider().config.identifyOneToOneCallWithoutParticipants;this.mediaSession=new Nr(this.mediaAgent.createSession(v,this.signalingSession,{isConference:this.callUsesMixer,isPstnCall:this.isOneToOnePSTNCall(_),isParkedCall:this.isParkedCall(),reinvitelessConfig:C},this.callDeviceManager,this.smallCallTelemetry,f),this.signalingSession),this.batteryStatus=new io(this.mediaSession.getDiagnostics(),this.mediaAgent.getConfigProvider()),this.batteryStatus.on("batteryStatusChanged",(()=>this.reportSmallCallEvent(this.smallCallTelemetry?.getSmallTelemetryOnBatteryLow()))),this.temporaryCallConstraints&&(S.info(`Applying saved call constraints to current call ${JSON.stringify(this.temporaryCallConstraints)}`),this.mediaSession.setCallConstraints(this.temporaryCallConstraints,generateCauseId()).then(this.resolveTemporaryCallConstraints).catch(this.rejectTemporaryCallConstraints).finally((()=>{this.temporaryCallConstraints=void 0,this.rejectTemporaryCallConstraints=void 0,this.resolveTemporaryCallConstraints=void 0}))),this.dataChannel.setConfigProviderView(this.mediaSession.getSessionConfig()),this.callTelemetry.recordEvent("CreatedConference","",g),this.streamManager.setMediaSession(this.mediaSession,g),this.participants.forEach((f=>{f.setMediaSession(this.mediaSession,g)}));const T=this.mediaSession.getSessionConfig()?.config;T?.useOneDsLogger&&T?.addTelemetryReportingCallback&&(this.beforeUnloadTelemetrySender=()=>{this.sendLastKnownStats()},window.addEventListener("beforeunload",this.beforeUnloadTelemetrySender)),this.screenSharingControl&&this.allowDataChannel()&&this.screenSharingControl.setupDataHandlers(),this.unmixedAudioProvider=new Qa}executeNegotiation(g,f,S,v){const C=this.logger.createFnLogger(f,g);if(this.isCallModeStreaming()||this.isEscalationInProgress)return void C.info(`ignored due to being in streaming=${this.isCallModeStreaming()},\n                isEscalationInProgress=${this.isEscalationInProgress}`);const _=generateCauseId();3===this.state||4===this.state||5===this.state||10===this.state||this.isPreheatedOnly()?(C.info(`started, state: ${this.state}, runNegotiation: ${S}`),S?(this.callTelemetry.recordEvent("NegotiationRequired","",g),this._callOperationHandler.executeChained((()=>this.renegotiateOutgoing(g,v)),"_RenegotiateOutgoing",_,g,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})):(this.callTelemetry.recordEvent("UpdateMediaDescriptions","",g),this._callOperationHandler.executeChained((()=>this.updateMediaDescriptions(g,v)),"_UpdateMediaDescriptions",void 0,g,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}))):C.info(`not started, state: ${this.state}`)}async muteUnmuteWorkaround(g){if(this.mediaSession?.getSessionConfig().config.enableMuteSpeakerUnmuteSpeakerWorkaround&&!this.isSpeakerMuted&&25===g.type&&3===g.value&&0===g.mediaType){this.logger.log("Performing muteSpeaker->unmuteSpeaker workaround");const g=generateCauseId();await this.muteSpeaker(g),await this.unmuteSpeaker(g)}}sendLastKnownStats(){if(this.tsCallingTelemetryReported)return;this.callEndDiagnosticsInfo={callControllerCode:bi.CODE.SUCCESS,callControllerSubCode:bi.SUB_CODE.BEACON},this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo);const g=this.callTelemetry.getShortEvent();g.Code=this.callEndDiagnosticsInfo.callControllerCode,g.SubCode=this.callEndDiagnosticsInfo.callControllerSubCode;let f="csa_conversation_callmodality";if(this.reportTelemetryEvents([{eventName:f,props:g}],"signaling","skypecosi_concore_web"),f=this._callIsSetupComplete?"in_call_session":"call_setup_session",this.reportTelemetryEvents([{eventName:f,props:this.callTelemetry.getEvent(!0)}],"signaling","skypecosi_concore_web_ts_calling"),this.mediaSession){const g=this.mediaSession.getLastKnownStats(!0);this.callStats.setMediaStats(g),this.reportSmallCallEvent(null,!0),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web")}this.reportVDITelemetryEvents()}reportSmallCallEvent(g,f){this.reportTelemetryEvents(this.callStats.buildShortCallEvent(g??this.smallCallTelemetry?.getEndCallSmallTelemetry(f)),"media","mdsc")}invertDirectionality(g){switch(g){case this.mediaAgent.constants.MEDIA_STATE.sendReceive:return Hr.sendReceive;case this.mediaAgent.constants.MEDIA_STATE.send:return Hr.receive;case this.mediaAgent.constants.MEDIA_STATE.receive:return Hr.send;default:return null}}completeNegotiationAsync(g){const f=this.logger.createFnLogger("completeNegotiationAsync",g),S=this.mediaSession.completeNegotiationAsync(g).then((S=>{f.info(`activeModalities=${S&&Object.keys(S.activeModalities)}`);const v=this.mediaSession.getSessionConfig().config.avoidFakeStreamsDuringEscalation&&this.isEscalationInProgress;if(!this.callUsesMixer&&!v){if(this.mediaStateConfigurationHelper.isSending(3)&&S.initiator){const f=S.offeredModalities.data===this.mediaAgent.constants.MEDIA_STATE.sendReceive,v=S.activeModalities.data===this.mediaAgent.constants.MEDIA_STATE.sendReceive;f&&!v&&(this.logger.info(`[${g}][completeNegotiationAsync] Disabling data modality as it was not wanted by remote`),this.mediaStateConfigurationHelper.removeModality(3))}const f=this.participants[0],v=f?.endpoints?.endpointDetails.length&&f.endpoints.endpointDetails[0].mediaStreams?.length;if(f&&!v){const prepareStreamData=(g,f,S)=>({participantId:so,endpointId:ro,type:g,direction:this.invertDirectionality(f),sourceId:S,serverMuted:!1}),v=[];v.push(prepareStreamData($r.audio,S.activeModalities.audio,ss)),S.activeModalities.video&&v.push(prepareStreamData($r.video,S.activeModalities.video,as)),S.activeModalities.sharing&&v.push(prepareStreamData($r.sharing,S.activeModalities.sharing,os)),f.updateStreams(v,g,this.isMultiVBSSEnabled()),!this.callIsHeld()&&this.calculateIsSomeoneStreaming(g)}}if(f.logSuccess(safeJsonStringify(S)),this.mediaAgent.getConfigProvider().config.syncMuteStateWithAudioDirection&&S?.activeModalities?.audio){const f=S.activeModalities.audio===this.mediaAgent.constants.MEDIA_STATE.receive||S.activeModalities.audio===this.mediaAgent.constants.MEDIA_STATE.inactive;this.setMuted(f?2:this.isServerMuted?1:0,g)}return S}));return S.catch((S=>{f.logFailure(S),this.callTelemetry.recordEvent("_CompleteNegotiationFailed",{e:S},g)})),S}async renegotiateOutgoing(g,f){this.renegotiationAnswerDeferred=new dt;const S=this.logger.createFnLogger("renegotiateOutgoing",g),v=this.inLocalHold()?this.getMediaModalitiesForHold(g):this.calculateModalityDirections({},g);if(this._delayedElevationPending&&!this._delayedElevationQueued){if(hasSendDirectionality(v.video)||hasSendDirectionality(v.sharing))return S.info("mediaModalities",v),void await this.triggerDelayedReconnectIfNeeded(g,"renegotiateOutgoing");S.info("Delayed elevation (renegotiateOutgoing): no outgoing video or sharing, skipping elevation for now")}S.info("start");const C=createPhaseExecutor(S);try{try{const S=await C.execute("MediaCreateOffer",(()=>this.mediaSession.createOfferAsync(g,f))),_=this.getSignalingMediaTypes(v);await C.execute("SignalingStartNegotiation",(()=>this.signalingSession.startRenegotiationAsync(S,_,g)));const T=await C.execute("SignalingRenegotiationAnswer",(()=>this.renegotiationAnswerDeferred.promise));await C.execute("MediaProcessAnswer",(()=>this.mediaSession.processAnswerAsync(T,g,!1)));const I=await C.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(g)));this.onNegotiationCompletion(I,!0,v,g,C.getTelemetryData())}catch(f){if(S.logFailure(f),!f.phase)throw this.callTelemetry.recordEvent("OutgoingNegotiationFailure",f,g),f;let C="unknown";const _=this.mediaAgent.constants.RENEGOTIATION_ERROR;if(C=_.local,"SignalingRenegotiationAnswer"===f.phase||"SignalingStartNegotiation"===f.phase){const g=415;C=f.error.code===Fi.GlareError?_.glare:f.error.code===g?_.media:_.signaling}else"MediaCreateOffer"===f.phase&&f.error.type===this.mediaAgent.constants.MEDIA_ERROR.noNetworkError&&(C=_.media);if(this.callTelemetry.recordEvent("OutgoingNegotiationFailure",this.getTelemetryFromPhaseExecution(f),g),f.error.message?.includes("The requested call does not exist"))throw new Error("Call drop due to remote replying with call not found");S.logFailure(C);const T={type:C,detail:f.error};await this.mediaSession.rejectNegotiationAsync(T,g),this.onNegotiationFailure(f.error,C,g,v)}}catch(f){S.logFailure(f),this.callTelemetry.recordEvent("NegotiationFatalError",getPIISafeObject(f),g),this.stopInternal({causeId:g,terminatedReason:47})}}async renegotiateIncoming(g,f){this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",null,f,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.mediaAcknowledgmentOperation.catch(noop);const S=this.logger.createFnLogger("renegotiateIncoming",f);if(S.info("start"),g.newOffer&&!this.mediaAgent.getCapabilities().retargeting)return S.logFailure("Retarget offer received, but pluginless has no support for retarget"),void this.stopInternal({causeId:f,terminatedReason:38});const v=createPhaseExecutor(S);try{const S=await v.execute("MediaProcessOffer",(()=>this.mediaSession.processOfferAsync(g,f)));this.handleOfferedModalities(S,f),2===this.getRenegotiationOfferType(S)&&await this.prepareModalitiesForResume(f);const C=await this.updateMediaModalities({offered:S},f);1===this.getRenegotiationOfferType(S)&&await this.prepareModalitiesForHold(f),this.updateMediaState(C,f),this.isRenegotiationHoldOrResume(C)&&this.updateScreenSharingState(C,f);const _=await v.execute("MediaCreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,f))),T=this.getSignalingMediaTypes(C);await v.execute("SignalingAcceptRenegotiation",(()=>this.signalingSession.acceptRenegotiationAsync(_,T,f))),await v.execute("SignalingMediaAcknowledgement",(()=>this.mediaAcknowledgmentOperation));const I=await v.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(f)));this.onNegotiationCompletion(I,!1,S,f,v.getTelemetryData())}catch(g){try{if(!g.phase||"CompleteNegotiation"===g.phase)throw this.callTelemetry.recordEvent("IncomingNegotiationFailure",g,f),g;const v=g;this.callTelemetry.recordEvent("IncomingNegotiationFailure",this.getTelemetryFromPhaseExecution(g),f);const C={type:this.mediaAgent.constants.RENEGOTIATION_ERROR.local,detail:g.error};if("SignalingAcceptRenegotiation"===v.phase||"SignalingMediaAcknowledgement"===v.phase)return S.logFailure("Error in renegotiateIncoming() -> rejecting media negotiation"),C.type=this.mediaAgent.constants.RENEGOTIATION_ERROR.signaling,this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",C,void 0,f),void await this.mediaSession.rejectNegotiationAsync(C,f);this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",C,void 0,f),await this.mediaSession.rejectNegotiationAsync(C,f),await this.signalingSession.rejectRenegotiationAsync(void 0,f)}catch(g){S.logFailure(g),this.callTelemetry.recordEvent("NegotiationFatalError",getPIISafeObject(g),f),this.stopInternal({causeId:f,terminatedReason:47})}}}async updateMediaDescriptions(g,f){const S=this.logger.createFnLogger("updateMediaDescriptions",g);S.info("start");try{const v=await this.mediaSession.startMediaDescriptionsUpdateAsync(g,f);S.info(`send updateMediaDesriptions, descriptions=${safeJsonStringify(v)}`),await this.signalingSession.updateMediaDescriptionsAsync(g,v);const C=await this.mediaSession.completeMediaDescriptionsUpdateAsync(g);if(this.mediaAgent.getConfigProvider().config.syncMuteStateWithAudioDirection&&C?.appliedModalities?.audio){const f=C.appliedModalities.audio===this.mediaAgent.constants.MEDIA_STATE.receive||C.appliedModalities.audio===this.mediaAgent.constants.MEDIA_STATE.inactive;this.setMuted(f?2:this.isServerMuted?1:0,g)}this.onUpdateMediaDescriptionsCompletion(C,g)}catch(f){S.logFailure(f),this.callTelemetry.recordEvent("UpdateMediaDescriptionsFailure",f,g);const v=await this.mediaSession.rejectMediaDescriptionsUpdateAsync(g,!0);this.onUpdateMediaDescriptionsFailure(f,v,g)}}handleCallEscalation(g,f){const S=this.logger.createFnLogger("handleCallEscalation",f);if(S.info(`current callType=${this.callType}, escalationInProgress=${g}, isEscalationInProgress=${this.isEscalationInProgress}`),g){const g=this.participants[0];g&&g.audio.participantId===so?g.updateStreams([{type:$r.audio,direction:"inactive",sourceId:null,serverMuted:!1},{type:$r.video,direction:"inactive",sourceId:null,serverMuted:!1},{type:$r.sharing,direction:"inactive",sourceId:null,serverMuted:!1}],f,this.isMultiVBSSEnabled()):S.info("no 1-1 participant found, stream update ignored"),this.setCallType(2,f),this.setCallUsesMixer(!0,f),this.setIsEscalationInProgress(!1,f),this.callTelemetry.recordEvent("_EscalationCompleted",void 0,f),this.raiseChanged()}}async reportTsCallingTelemetry(g){if(this.tsCallingTelemetryReported)return;await this.connectCallPromise.catch(noop);const f=g?"call_setup_session":"in_call_session";this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo),this.reportTelemetryEvents([{eventName:f,props:this.callTelemetry.getEvent(g)}],"signaling","skypecosi_concore_web_ts_calling"),g?this.callTelemetry.switchToInCallTelemetry():this.tsCallingTelemetryReported=!0}async sendMidCallTelemetry(g){this.mediaSession&&g?.length&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(!0)),this.appendInfoToCallStats(),this.reportTelemetryEvents(this.callStats.buildMidCallTelemetry(g),"media","mdsc_mid_call_telemetry"))}sendCallSetupTelemetry(){this.mediaSession&&(this.collectCallStats(this.mediaSession),this.reportCallSetupStats(),this.isCallSetupTelemetrySent=!0)}collectCallStats(g){const always=()=>this.collectMediaStatsDeferred.resolve();return g.getStatsAsync(!1).then((g=>this.callStats.setMediaStats(g))).then(always,always)}reportCallSetupStats(){this.collectMediaStatsDeferred.promise.then((()=>{this.reportTelemetryEvents(this.callStats.buildFromCallSetupStats(this.signalingSession.baseMessagingChannelUrl),"media","mdsc"),this.event("statsReported").raise(),this.collectMediaStatsDeferred=new dt}))}async reportCallEndStats(g){this.callTelemetry.setTerminationState(this.state),this.callTelemetry.setTerminationReason(this.terminatedReason),this.callStats.localStats.endCall(this.terminatedReason),g&&this.mediaAgent.getConfigProvider().config?.smallCallTelemetry?.enable&&this.reportSmallCallEvent(null),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web"),this.reportTsCallingTelemetry(!this._callIsSetupComplete),g&&(await this.collectMediaStatsDeferred.promise,this.callStats.appendTerminationInfo(this.terminatedReason,this.state),this.appendInfoToCallStats(),this.reportTelemetryEvents(this.callStats.buildFromMediaStats(),"media","mdsc")),this.reportVDITelemetryEvents(),this.event("statsReported").raise(),this.collectMediaStatsDeferred=new dt}async reportVDITelemetryEvents(){this.vdi3diagnostics&&this.reportTelemetryEvents([{eventName:"vdi_webrtc_session",props:await this.callStats.buildVDItelemetryReport(this.vdi3diagnostics)}],"media","mdsc")}reportTelemetryEvents(g,f,S){const v=this.telemetryLoggers?this.telemetryLoggers[f]:null;v?g.forEach((g=>v.sendEvent({eventName:`${S?`${S}_`:""}${g.eventName}`,props:g.props}))):this.logger.debug(`reportTelemetryEvents no logger for tenant ${f}`)}onLocalPreviewSizeChanged(g,f){this.logger.debug(`onLocalPreviewSizeChanged: ${g}x${f}`)}onLocalPreviewStateChanged(g){this.logger.debug(`onLocalPreviewStateChanged: ${g}`),this.callStats.localStats.video.streamStateChanged(g.stream)}async configureVideoModalitiesAsync(g,f,S){if(!this.mediaSession)return this.logger.warn("Tried to configure modalities after call end"),Promise.resolve();g&&this._delayedElevationPending&&!this._delayedElevationQueued&&await this.triggerDelayedReconnectIfNeeded(f,"configureVideoModalitiesAsync"),await this.updateMediaModalities(void 0,f,S),g||this.turnOffLocalVideoPreview(f),this.setVideoOn(g,f)}turnOffLocalVideoPreview(g){return this.localVideoRenderer&&(this.localVideoRenderer.dispose(),this.localVideoRenderer=null),this.disposeLocalVideoHandle(),Promise.resolve(void 0)}turnOnLocalVideoPreview(g){return this.mediaSession?.getSessionConfig().config.useDeviceHandleForLocalVideo?this.acquireLocalVideo(g):(this.localVideoContainer||(this.localVideoContainer=document.createElement("div")),this.turnOnLocalVideoPreviewUsingRenderer(g))}acquireLocalVideo(g){const f=this.logger.createFnLogger("_StartPreviewVideo",g);if(!this.mediaStateConfigurationHelper.isSending(1))return Promise.reject("could not start video preview, not configured to send");try{this.disposeLocalVideoHandle();const g=this.callDeviceManager.getDeviceManager(getAgentMediaType(1));return this.localVideoHandle=g.createDevicesHandle({video:!0},"pluginlessCall:acquireLocalVideo()"),this.localVideoHandle.on("onStreamStateChanged",(g=>this.onLocalPreviewStateChanged({stream:g}))),this.localVideoHandle.acquire()}catch(g){return f.logFailure(g),void this.disposeLocalVideoHandle()}}turnOnLocalVideoPreviewUsingRenderer(g){const f=this.logger.createFnLogger("_StartPreviewVideo",g),S=this.mediaStateConfigurationHelper.isSending(1);if(!S||!this.localVideoContainer)return Promise.reject(`could not start video preview: requestedVideoState=${S}, localVideoContainer=${this.localVideoContainer}`);this.turnOffLocalVideoPreview(g);const v=asap((()=>{this.localVideoRenderer=this.callDeviceManager.getDeviceManager(getAgentMediaType(1)).createPreviewRenderer(this.localVideoContainer,"Video"),this.localVideoRenderer.on("onVideoSizeChanged",((g,f)=>this.onLocalPreviewSizeChanged(g,f))),this.localVideoRenderer.on("onVideoStateChanged",(g=>this.onLocalPreviewStateChanged(g)))})).then((()=>this.localVideoRenderer.startVideoAsync(g)));return v.catch((g=>f.logFailure(g))),v}async startStopVideo(g,f,S){const v=this.logger.createFnLogger(g?"startVideo":"stopVideo",f);return v.info("start"),this.canToggleVideo?(g?(this.callStats.localStats.newSession(1),this.callStats.localStats.video.start()):this.callStats.localStats.video.stop(),g&&this.mediaStateConfigurationHelper.isDisabled(1)&&v.info("Video modality was skipped till now. Adding it now."),g?this.mediaStateConfigurationHelper.enableModality(1):this.mediaStateConfigurationHelper.removeModality(1),this.canToggleVideo=!1,this.videoTogglePromise=(async()=>{try{let v=!1;g&&(await this.turnOnLocalVideoPreview(f),v=!0),await this.configureVideoModalitiesAsync(v,f,S)}catch(g){throw v.logFailure(g),this.mediaStateConfigurationHelper.removeModality(1),await this.configureVideoModalitiesAsync(!1,f,S),g}finally{this.canToggleVideo=!0}})(),this.videoTogglePromise):g===this.mediaStateConfigurationHelper.isSending(1)?(await this.videoTogglePromise,void this.turnOnLocalVideoPreview(f)):(v.logFailure(`video switching is in progress ${g}]`),Promise.reject({reason:1}))}async startStopAudio(g,f){const S=this.logger.createFnLogger(g?"startAudio":"stopAudio",f);try{const g=await this.updateMediaModalities(void 0,f);this.updateMediaState(g,f)}catch(g){return S.logFailure(g),9}return 0}updateEndpointStateForMute(g,f){try{this.signalingSession.updateEndpointState({state:{isMuted:g}},f).catch((g=>{this.logger.logFailure(`updateEndpointStateForMute failure: ${g}`)}))}catch(g){this.logger.logFailure(`updateEndpointStateForMute failure: ${g}`)}}async handleServerMutedState(g){const f=this.logger.createFnLogger(`handleServerMutedState, isServerMuted=${!!this.isServerMuted}`,g);if(!this.isServerMuted){const S=3===this._muteState;if(1===this._muteState||S)try{f.info("is unmuting, as we are no longer server muted"),await this.handleMuteUnmuteOnMediaSession(!1,g),this.setMuted(0,g),this.unmutePendingPromise?.resolve(),S&&this.updateEndpointStateForMute(!1,g)}catch(g){throw f.logFailure(g),g}}if(this.isServerMuted&&0===this._muteState){f.info("is muting, as we are unmuted");try{await this.handleMuteUnmuteOnMediaSession(!0,g),this.setMuted(1,g)}catch(g){throw f.logFailure(g),g}}}async handleMuteUnmuteOnMediaSession(g,f){const S=this.logger.createFnLogger(`handleMuteUnmuteOnMediaSession, value=${!!g}`,f);if(this.mediaSession?.getAllowedModalities&&!this.isServerMuted){const v=this.isMuted||this.isServerMuted,C=this.mediaSession.getAllowedModalities().audio.some((g=>g===Hr.send||g===Hr.sendReceive));(v&&C||!v&&!C)&&(S.info(`updating audio modalities: Muted ${v} -> ${g}; audioAllowed = ${C}`),await this.updateMediaModalities(void 0,f))}return g?(S.info("mediaSession.muteInputAsync"),await(this.mediaSession?.muteInputAsync(f))):g||(S.info("mediaSession.unmuteInputAsync"),await(this.mediaSession?.unmuteInputAsync(f))),Promise.resolve()}canMuteOthers(){const g=this._enableUserMeetingRolesCheckForClientCapability&&this.meetingRoles?.some((g=>"attendee"===g))||"attendee"===(this.advancedMeetingRole||this.meetingRole),f=this._enableEndpointMeetingRoleCheckForClientCapability&&!!this.endpoints?.endpointDetails.find((g=>this._endpointId===g.endpointId))?.endpointMeetingRoles?.some((g=>"attendee"===g));return!g&&!f}updateCapabilities(g,f=!1){let S=!1,v=!1;callStateIsAnyOf(this.state,[11,12])||(this.isServerMuted&&!this._callInLobby?2&this._commandUrlPresence&&(S=!0):this.isMuted&&(S=!0),v=!!(1&this._commandUrlPresence)&&this.canMuteOthers()),this._capabilities.canUnmuteSelf===S&&this._capabilities.canMuteOthers===v||(this._capabilities.canUnmuteSelf=S,this._capabilities.canMuteOthers=v,this.logger.info(`[${g}][updateCapabilities] Computed self capabilities: ${JSON.stringify(this._capabilities)}`),f&&this.raiseChanged())}async evaluateEndpointStatesForAccept(g,f,S){const v=this.logger.createFnLogger(`evaluateEndpointStatesForAccept, isMuted=${!!g}`,S),C={};try{await this.handleMuteUnmuteOnMediaSession(g,S),Object.assign(C,{state:{isMuted:g}}),v.info("is updating endpointState for mute"),f&&(Object.assign(C,{endpointProperties:{additionalEndpointProperties:f}}),v.info("is updating endpointState for additionalEndpointProperties"))}catch(g){throw v.logFailure(g),getRejectTransactionEnd(g)}return C}async handleEndpointStatesForAccept(g,f){const S=this.logger.createFnLogger("handleEndpointStatesForAccept",f);try{await this.signalingSession.updateEndpointState(g,f)}catch(g){throw S.logFailure(g),getRejectTransactionEnd(g)}}async muteUnmute(g,f){const S=this.logger.createFnLogger(`muteUnmute, value=${!!g} isServerMuted=${this.isServerMuted} inLobby=${this._callInLobby}`,f);if(callStateIsAnyOf(this.state,[11,12]))return S.logFailure("Can not mute/unmute during preheat call"),Promise.reject(getRejectTransactionEnd("TransactionDisallowed"));const v=!g&&(!this.isServerMuted||this._callInLobby);try{if((g||v)&&await this.handleMuteUnmuteOnMediaSession(g,f),g)this.setMuted(2,f),S.info("is updating endpointState for mute"),this.updateEndpointStateForMute(!0,f);else{if(!v)return S.info("is unmuting on server"),2===this._muteState&&this.setMuted(3,f),this.isCallModeStreaming()?this.promoteToRealtimeAndUnmute(f):this.signalingSession.unmuteAsync(f).then((g=>{this.handleSelfUnmuteUpdatedInfo(g,f)}));S.info("is updating endpointState for unmute"),this.setMuted(0,f),this.updateEndpointStateForMute(!1,f)}}catch(g){throw S.logFailure(g),getRejectTransactionEnd(g)}}async muteUnmuteSpeaker(g,f){this.setSpeakerMuted(g,f),this.mediaSession&&(g?await this.mediaSession.muteOutputAsync(f):await this.mediaSession.unmuteOutputAsync(f))}getParticipant(g){return this.participants.filter((f=>f.isSameParticipantsMri(g)))[0]}getOrCreateParticipant(g,f,S){let v=this.getParticipant(g);return v||(v=new hs(g,this.mediaSession,this.logger,this.callStats.localStats,this.callTelemetry,f),v.changed((()=>this.onParticipantChanged(v))),this.participants.push(v),S&&this.event("participantAdded").raise(v),this.monitorCallStart(),v)}onParticipantChanged(g){this.event("participantUpdated").raise(g),this.raiseChangedDeferred(this._participantChangedEventSkipConfig)}setCallState(g,f,S=0){if(this.state===g)return;const v=this.logger.createFnLogger("setCallState",f);v.info(`currentState=${this.state}, newState=${g}, terminatedReason=${this.terminatedReason}`),(hr[this.state].indexOf(g)>=0||(v.logFailure("invalid state transition"),7===g))&&(this.callTelemetry.recordEvent("_SetCallState",{state:g,reason:S},f),this.state=g,this.callStats.localStats.call.callStateChanged(g),6===g&&this._startCallPhase&&(this.callTelemetry.updateOperationData("_ConnectCall",{phases:this._startCallPhase.getTelemetryData()},f),this._startCallPhase=void 0),7===g&&this.setTerminatedReason(S),3===g&&(this.callGotConnected=!0,this.callHeldAt=null),this.callIsHeld()&&!this.callHeldAt&&(this.callHeldAt=new Date),v.logSuccess(`changed to ${g}, terminatedReason: ${this.terminatedReason}, failureType=${this.failureType}`),this.screenSharingControl.callStateChanged(this.state),this.monitorCallStart(),this.event("callStateChanged").raise(),this.updateCapabilities(f),this.raiseChanged(),this.callTelemetry.recordEvent("_RaiseCallStateChangeEvent",{state:g,reason:S},f))}setTerminatedReason(g){if(this.terminatedReason=g,!(0,Ki.includes)(no,g)){const g=44===this.terminatedReason,f=55===this.terminatedReason,S=56===this.terminatedReason;this.setFailureType(!this.callGotConnected||!this._wasAudioStreamConnected||g||f||S?0:1)}}setMediaStream(g,f,S){if(g){if(!(0,Ki.find)(this.localMediaStreams,(g=>g.mediaType===S))){const g=new ao(f,S);this.logger.info(`setMediaStream ${JSON.stringify(g)}`),this.localMediaStreams.push(g)}}else this.logger.info(`setMediaStream removing ${S}`),(0,Ki.remove)(this.localMediaStreams,(g=>g.mediaType===S))}setVideoOn(g,f){this.logger.info(`[${f}]videoOn=${g}`),this.isVideoOn=g,this.setMediaStream(this.isVideoOn,!0,1),this.callTelemetry.recordEvent("_SetLocalVideo",{value:g},f),this.raiseChanged()}setAudioOn(g,f){this.logger.info(`[${f}]audioOn=${g}`),this.setMediaStream(g,!0,0),this.callTelemetry.recordEvent("_SetLocalAudio",{value:g},f)}setScreenSharingOn(g,f){this.logger.info(`[${f}]screenSharingOn=${g}`),this.isScreenSharingOn=g,this.setMediaStream(this.isScreenSharingOn,this.isScreenSharingOn,2),this.callTelemetry.recordEvent("_SetScreenSharing",{screenSharingOn:g},f),this.event("userActivityChanged").raise(),this.raiseChanged()}disposeSharingScreenHandle(){this.sharedScreenHandle&&(this.sharedScreenHandle.dispose(),this.sharedScreenHandle=null)}disposeLocalVideoHandle(){this.localVideoHandle?.dispose(),this.localVideoHandle=null}setMuted(g,f){this._muteState!==g&&(this._muteState=g,this.callTelemetry.recordEvent("_SetMuted",{isMuted:g},f),this.logger.info(`[${f}]participantMuteState:${g}, isMuted: ${this.isMuted}`),this.updateCapabilities(f),this.raiseChanged(),this.event("muteStateChanged").raise(this.isMuted,f))}setSpeakerMuted(g,f){this.logger.info(`[${f}]speakerMute=${g}]`),this.isSpeakerMuted=g,this.raiseChanged()}monitorCallStart(){3!==this.state||!this.participants.length&&2!==this.callMode||this.callStartedAt||(this.callStartedAt=new Date)}_removeParticipant(g,f,S=0){const v=this.logger.createFnLogger("removeParticipant",f);v.info(`mri=${scrubSignalingParticipant(g)}`);const C=(0,Ki.remove)(this.participants,(f=>f.isSameParticipantsMri(g.id)))[0];C?(C.setState(4,S,f),this.event("participantRemoved").raise(C)):v.logFailure(`unable to remove participant ${scrubMriOrOmit(g.id)}`),this.raiseChanged(this._participantChangedEventSkipConfig)}setIsSomeoneSharing(g,f){const S=this.isSomeoneSharing!==g&&!(g&&this.screenSharingRenegotiationDeferred&&this.callUsesMixer);S&&(this.isSomeoneSharing=g);let v=S;if(this.callUsesMixer&&this.mediaSession?.getSessionConfig().config.enableStopSharingWithIncomingOffer&&(v||(v=f)),!this.isMultiVBSSEnabled()&&v&&this.isSomeoneSharing&&this.isScreenSharingOn&&(this.stopScreenSharing(),this.logger.info("sharingStolen: Cleaning up local screenshare because remote screenshare is running"),this.event("sharingStolen").raise()),this.allowScreenSharingControl()&&this.screenSharingControl?.isInternalViewerControlEnabled()){const g=this.localSignalingParticipant.endpointDetails.find((g=>this._endpointId===g.endpointId)),f=this.participants.find((g=>g.streams[1].some((g=>g.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,f,g)}}handleOfferedModalities(g,f){const S=this.mediaAgent.constants.MEDIA_STATE,v=this.logger.createFnLogger("handleOfferedModalities",f);try{v.info(`offeredModalities=${safeJsonStringify(g)}`)}catch(g){v.logFailure(g)}g.hasOwnProperty("video")||this.mediaStateConfigurationHelper.isSending(1)?g.hasOwnProperty("video")&&!this.mediaStateConfigurationHelper.isSending(1)&&this.mediaStateConfigurationHelper.removeModality(1):this.mediaStateConfigurationHelper.disableModality(1),g.hasOwnProperty("sharing")||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.disableModality(2),g.sharing!==S.receive||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.removeModality(2),g.data===S.sendReceive&&this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this.isReivitelessEnabled()||(this.setIsSomeoneSharing(g.sharing===S.receive,!0),this.setIsSomeoneStreamingVideo(g.video===S.receive||g.video===S.sendReceive))}getRenegotiationOfferType(g){if(g)if(5===this.state){if("sendrecv"===g.audio)return 2}else if(this.modalitiesAreHold(g))return 1;return 0}isRenegotiationHoldOrResume(g){return 1===this.getRenegotiationOfferType(g)||2===this.getRenegotiationOfferType(g)}isReivitelessEnabled(){return(this.signalingSession.getMaxReinvitelessMediaForVideoForWeb()>0||this.signalingSession.getMaxReinvitelessMediaForVBSSForWeb()>0)&&this.callUsesMixer}isValidHoldResumeCallState(g){return[3,5,10,13].includes(g)}onNegotiationCompletion(g,f,S={},v,C){const _=this.logger.createFnLogger("onNegotiationCompletion",v);_.info(`byLocal=${f}, result=${safeJsonStringify(g)}`),this.callTelemetry.recordEvent("NegotiationCompletion",{phaseTelemetryBag:C,...this.prepareNegotiationResultForTelemtry(g)},v);const T=this.isOneToOneCall();if(T&&!this.callUsesMixer){const f=this.modalitiesAreHold(g.activeModalities)?5:3;this.participants[0].setState(f,void 0,v),_.info(`isOneToOneCall: participant[0] state set to ${f}`)}const I=this.modalitiesAreHold(g.configuredModalities),b=this.modalitiesAreHold(g.activeModalities);let A;const P=this.signalingSession.participantManager.localParticipant.isStaging;_.info(`isStaging= ${P}`),this.requestedHoldState?(I&&b||_.info(`Not expected modalities when processing local hold: ${I} ${b}`),4!==this.state&&_.info(`Not expected state when processing local hold: ${this.state}, switching back to LocalHold`)):f||this.callHoldResumeDeferred?!I&&b?A=5:I||b||this._callInLobby||this.isPreheatedOnly()||(A=P?13:3):4===this.state||this._callInLobby||this.isPreheatedOnly()||(A=T&&5===this.participants[0].state?5:P?13:3),A&&this.setCallState(A,v),this.callHoldResumeDeferred&&(_.info(`isHoldInProgress=${this.isHoldInProgress}, state=${this.state}, completed=${b}`),this.isHoldInProgress?b&&this.finishCallHoldResume():this.inLocalHold()||this.finishCallHoldResume(this.isValidHoldResumeCallState(A)?void 0:new Error(`Call state changed to ${A} instead of Connected, Lobby, Staging or RemoteHold`))),this.requestedHoldState||(this.setIsSomeoneSharing((0,Ki.some)(this.participants,(g=>(0,Ki.some)(g.streams[1],(g=>g.isAvailable))))),this.setIsSomeoneStreamingVideo((0,Ki.some)(this.participants,(g=>(0,Ki.some)(g.streams[0],(g=>g.isAvailable))))));const R=S&&S.sharing===this.mediaAgent.constants.MEDIA_STATE.send,M=g?.activeModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(this.resolveScreenSharingRenegotiation(v,R,M,g.isComplete),this.retryOutgoingRenegotiation.retry){const g=this.retryOutgoingRenegotiation.causeId;this._callOperationHandler.executeChained((()=>this.updateMediaModalities(void 0,g)),"_Renegotiate",g,g,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.retryOutgoingRenegotiation.retry=!1}}onUpdateMediaDescriptionsFailure(g,f,S){const v=f?.requestedModalities.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.screenSharingRenegotiationDeferred&&v&&(this.screenSharingRenegotiationDeferred.reject(g),this.screenSharingRenegotiationDeferred=null)}onUpdateMediaDescriptionsCompletion(g,f){this.logger.createFnLogger("onUpdateMediaDescriptionsCompletion",f).info(`result=${safeJsonStringify(g)}`),this.callTelemetry.recordEvent("UpdateMediaDescriptionsCompletion",g,f);const S=g?.requestedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send,v=g?.appliedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.resolveScreenSharingRenegotiation(f,S,v,!0)}resolveScreenSharingRenegotiation(g,f,S,v){const C=this.logger.createFnLogger("resolveScreenShareRenegotiation",g);if(C.info(`invoked with wasSharingOfferred: ${f}, isSharingActive: ${S}, isComplete: ${v}`),this.screenSharingRenegotiationDeferred)if(f&&S)C.info("resolving screenSharingRenegotiationDeferred"),this.screenSharingRenegotiationDeferred.resolve(),this.screenSharingRenegotiationDeferred=null;else if(this._enableResolveScreenSharingWhenNegotiationComplete&&v&&!this.retryOutgoingRenegotiation.retry&&this.canToggleScreenSharing){const g=new Error(`screenSharing error: wasSharingOfferred: ${f}, isSharingActive: ${S}`);C.info(`reject screenSharingRenegotiationDeferred ${g}`),this.screenSharingRenegotiationDeferred.reject(g),this.screenSharingRenegotiationDeferred=null}}async updateMediaStatus(g){if(this.calculateIsSomeoneStreaming(g),this.mediaSession){const f=await this.updateMediaModalities(void 0,g);this.callTelemetry.updateOperationData("_UpdateLocalMediaStatus",f,g)}}calculateIsSomeoneStreaming(g){let f=!1,S=!1;for(const g of this.participants)if(f||(f=(0,Ki.some)(g.streams[1],(g=>g.isAvailable))),S||(S=(0,Ki.some)(g.streams[0],(g=>g.isAvailable))),f&&S)break;this._delayedElevationPending&&(f||S)&&this.triggerDelayedReconnectIfNeeded(g,"roster update"),this.setIsSomeoneSharing(f),this.setIsSomeoneStreamingVideo(S)}async triggerDelayedReconnectIfNeeded(g,f=""){const onReconnectCompleted=()=>{this._delayedElevationPending=!1,this._delayedElevationQueued=!1,this.mediaSession?.getDiagnostics()?.registerElevation("completed")};this.logger.info(`Delayed elevation (${f}): pending=${this._delayedElevationPending} queued=${this._delayedElevationQueued}`),this._delayedElevationPending&&!this._delayedElevationQueued?(this._delayedElevationQueued=!0,this._callOperationHandler.maybeRejectOperations(["_RenegotiateIncoming","_RenegotiateOutgoing","_Renegotiate"]),this.mediaSession?.getDiagnostics()?.registerElevation("attempted"),await this.mediaSession.reconnectAsync(g,!0,onReconnectCompleted)):this.logger.info(`Delayed elevation: was not queued, pending=${this._delayedElevationPending} isQueued=${this._delayedElevationQueued}`)}onNegotiationFailure(g,f,S,v){const C=v&&v.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(f===this.mediaAgent.constants.RENEGOTIATION_ERROR.glare)return this.screenSharingRenegotiationDeferred&&C&&this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),void(this.retryOutgoingRenegotiation={retry:!0,causeId:S});this.finishCallHoldResume(g),this.screenSharingRenegotiationDeferred&&C&&(this.screenSharingRenegotiationDeferred.reject(g),this.screenSharingRenegotiationDeferred=null)}static getParticipantReasonFromTerminatedReason(g){switch(g){case 1:return 0;case 9:return 2;case 10:return 3;case 2:return 4;case 24:return 8;case 3:return 9;case 4:return 10;case 14:return 12;case 0:default:return 11;case 15:return 13;case 16:return 14;case 17:return 15;case 18:return 16;case 19:return 17;case 20:return 18;case 11:return 19;case 21:return 20;case 22:return 21;case 23:return 22;case 33:return 25;case 36:return 26;case 37:return 27;case 41:return 30;case 39:return 28;case 42:return 31;case 40:return 29;case 43:return 32;case 44:return 33;case 45:return 34;case 46:return 35;case 47:return 36;case 48:return 37;case 49:return 38;case 50:return 39;case 51:return 40;case 52:return 41;case 54:return 42;case 55:return 44;case 56:return 45;case 12:return 23;case 59:return 46;case 73:return 59;case 61:return 47;case 60:return 48;case 62:return 49;case 63:return 50;case 64:return 5;case 65:return 51;case 8:return 52}}isRemoteParticipantInStaging(g){if(!g.endpointDetails)return!1;for(const f of g.endpointDetails)if(!hasStagingGroup(f))return!1;return!0}updateCallParticipantFromSignalingParticipant(g,f,S){if((0,Ki.every)(f.endpointDetails,(g=>g?.isLobby||g?.streamLobby)))return void g.setState(7,void 0,S);const v=(0,Ki.some)(f.endpointDetails,(g=>g?.streamInformation)),C=f.endpointDetails&&(0,Ki.some)(f.endpointDetails,(g=>g.mappedTo)),_=_PluginlessCall2.filterVirtualEndpoints(f.endpointDetails),T=_&&_[0].mediaStreams,I=this.isRemoteParticipantInStaging(f);if(T&&T.length>0){const f=T.every((g=>"inactive"===g.direction));let v=f?5:I?8:3;1!==this.state||f||this.callUsesMixer||(v=2),this.logger.info(`[updateCallParticipantFromSignalingParticipant]: with mediaStreams is not empty, ParticipantState is set to ${v}`),g.setState(v,void 0,S)}else if(T||C||v){const f=I?8:3;this.logger.info(`[updateCallParticipantFromSignalingParticipant]: ParticipantState is set to ${f}, mediaStreams=${!!T}, hasMappedEndpoints=${C}, hasPlayerStreams=${v}`),g.setState(f,void 0,S)}}handleSelfServerMutedState(g){const f=_PluginlessCall2.filterVirtualEndpoints(this.localSignalingParticipant.endpointDetails),S=(0,Ki.find)(f,(g=>this._endpointId===g.endpointId)),v=S&&S.mediaStreams,C=v&&v.filter((g=>"audio"===g.type||"audio-teleconferencing"===g.type)),_=S&&(S.stream||S.streamLobby);if(_){const f=_.serverMuted??!1;S.serverMuteVersion=0,f!==this.isServerMuted&&(this.isServerMuted=f,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${f}`),this.event("serverMutedChanged").raise(f,g),this.updateCapabilities(g,!0),this.isServerMuted&&this.setMuted(1,g))}else if(C&&C.length>0){const f=C.some((g=>g.serverMuted));f!==this.isServerMuted&&(this.isServerMuted=f,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${f}`),this.event("serverMutedChanged").raise(f,g),this.updateCapabilities(g,!0),this.handleServerMutedState(g))}}checkIfIncomingServerMutedIsUpdated(g){const f=(0,Ki.find)(this.localSignalingParticipant.endpointDetails,(g=>g.participantId===this.localSignalingParticipant.participantId));if(void 0===f)return;const S=(0,Ki.find)(g.endpointDetails,(g=>g.participantId===this.localSignalingParticipant.participantId));handleServerMutedVersion(this.logger,f,S)}convertWiredPublishedState(g){if(!g)return;const f=getPluginlessStateTypeFromWire(g.stateType);return{content:g.content,stateType:f,typeRank:g.typeRank,stateId:g.stateId}}updatePublishedStateModified(g,f){g!==this.currentUserSkypeIdentity.id||f&&f!==this.participantId?this._publishedStatesModified=2|this._publishedStatesModified:this._publishedStatesModified=1|this._publishedStatesModified}updatePublishedStates(g){try{let f=[];(0,Ki.forEach)(g.publishedStates,(g=>{f.push(this.convertWiredPublishedState(g))})),(0,Ki.isEqual)(this._participantPublishedStatesMap[g.id],f)||(0!==f.length||void 0!==this._participantPublishedStatesMap[g.id]&&null!==this._participantPublishedStatesMap[g.id])&&(this._participantPublishedStatesMap[g.id]=f,this.updatePublishedStateModified(g.id));const S=[];(0,Ki.forEach)(g.endpointDetails,(v=>{S.push(v.participantId),f=[],(0,Ki.forEach)(v.publishedStates,(S=>{const C=this.convertWiredPublishedState(S);if(this._endpointPublishedStatesMap[g.id]||(this._endpointPublishedStatesMap[g.id]={},this._endpointPublishedStatesMap[g.id][v.participantId]=[]),"clientMediaUfd"===C.stateType)try{const g=JSON.parse(JSON.stringify(C.content));this.mediaSession.registerRemoteQualityStateChangedEvent(g,v.participantId)}catch(g){this.logger.error(`Error while parsing state.content for ClientMediaUFD: ${g}`)}f.push(C)})),this._endpointPublishedStatesMap[g.id]&&!(0,Ki.isEqual)(this._endpointPublishedStatesMap[g.id][v.participantId],f)&&(0!==f.length||null!==this._endpointPublishedStatesMap[g.id][v.participantId]&&void 0!==this._endpointPublishedStatesMap[g.id][v.participantId])&&(this._endpointPublishedStatesMap[g.id][v.participantId]=f,this.updatePublishedStateModified(g.id,v.participantId))})),this._endpointPublishedStatesMap[g.id]&&Object.keys(this._endpointPublishedStatesMap[g.id]).forEach((f=>{S.some((g=>g===f))||(delete this._endpointPublishedStatesMap[g.id][f],this.updatePublishedStateModified(g.id,f))}))}catch(g){this.logger.error(`updatePublishedStates ${JSON.stringify(g)}`)}this.logger.info(`updatePublishedStates ${getLoggableMriKeys(this._participantPublishedStatesMap)}`),this.logger.info(`updatePublishedStates ${getLoggableMriKeys(this._endpointPublishedStatesMap)}`)}removePublishedStatesByParticipant(g){this._endpointPublishedStatesMap[g]&&delete this._endpointPublishedStatesMap[g],this._participantPublishedStatesMap[g]&&delete this._participantPublishedStatesMap[g],this.updatePublishedStateModified(g)}findOrCreateTypeState(g){let f=this._publishedStates.typeStates.findIndex((f=>f.type===g));if(-1===f){const S={participantStates:[],type:g};this._publishedStates.typeStates.push(S),f=this._publishedStates.typeStates.length-1}return f}processPublishedStates(){this.logger.info(`processPublishedStates ${getLoggableMriKeys(this._participantPublishedStatesMap)}`),this.logger.info(`processPublishedStates ${getLoggableMriKeys(this._endpointPublishedStatesMap)}`);try{this._publishedStates||(this._publishedStates={typeStates:[]}),this._publishedStates.typeStates=[];for(const g of Object.keys(this._participantPublishedStatesMap)){const f=this._participantPublishedStatesMap[g];(0,Ki.forEach)(f,(f=>{const S=this.findOrCreateTypeState(f.stateType),v={id:g,publishedState:{content:f.content,stateId:f.stateId,typeRank:f.typeRank}};this._publishedStates.typeStates[S].participantStates.push(v)}))}for(const g of Object.keys(this._endpointPublishedStatesMap))for(const f of Object.keys(this._endpointPublishedStatesMap[g]))this._endpointPublishedStatesMap[g][f].forEach((S=>{const v=this.findOrCreateTypeState(S.stateType),C={id:f,publishedState:{content:S.content,stateId:S.stateId,typeRank:S.typeRank}},_={id:g,endpoints:[C]},T=this._publishedStates.typeStates[v].participantStates.filter((f=>f.id===g));T&&T.length>0?(T[0].endpoints||(T[0].endpoints=[]),T[0].endpoints.push(C)):this._publishedStates.typeStates[v].participantStates.push(_)}));this.event("publishedStatesChanged").raise(this._publishedStates),this.raiseChanged()}catch(g){this.logger.error(`processPublishedStates ${g}}`)}}updateLocalParticipant(g,f){const S=this.logger.createFnLogger("updateLocalParticipant",f);this.checkIfIncomingServerMutedIsUpdated(g),this.localSignalingParticipant.endpointDetails=g.endpointDetails,this.localSignalingParticipant.role=g.role,this.setMeetingRole(g.meetingRole),this.setAdvancedMeetingRole(g.advancedMeetingRole),this.setMeetingRoles(g.meetingRoles),this.setParticipantType(g.participantType),this.setDisplayName(g.displayName),this.setPropertyBag(g.propertyBag),this.setPropertyRosterVersion(g.version),this.setMaskedIdentityDetails(g.isIdentityMasked,g.maskedIdSeqNumber,g.maskedId),this.setOtpIdentity(g.otpIdentity),this.localSignalingParticipant.tenantId=g.tenantId,this.localSignalingParticipant.isLobby=g.isLobby,g.joinAsStreamingUser&&(this.localSignalingParticipant.joinAsStreamingUser=g.joinAsStreamingUser,this.setJoinAsStreamingUser(g.joinAsStreamingUser)),void 0!==g.enableCaptcha&&this.setEnableCaptcha(g.enableCaptcha),this.callTelemetry.setTenantId(g.tenantId),this.callStats.setTenantId(g.tenantId);const v=this.localSignalingParticipant.isLobby;g.endpointDetails&&this.updateLocalParticipantEndpoints(g.endpointDetails),this.updatePublishedStates(g),this.handleSelfServerMutedState(f);const C=this.getLocalSignalingEndpointDetails();this._callInLobby=v||!!C?.streamLobby,this.signalingSession.participantManager.localParticipant.isStaging=g.isStaging;const _=this.signalingSession.participantManager.localParticipant.isStaging;S.info(`callInLobby = ${v}, callSetupComplete = ${this._callIsSetupComplete}, callIsHeld = ${this.callIsHeld()}, isStaging = ${_}`),!this._callIsSetupComplete||this.callIsHeld()||callStateIsAnyOf(this.state,[11,12])||(v?this.setCallState(10,f):_&&callStateIsAnyOf(this.state,[3,13,10,9,2])?this.setCallState(13,f):this.setCallState(3,f));const T=_PluginlessCall2.getStreamsFromEndpoints(g.endpointDetails,this.isMultiVBSSEnabled());if(this.callTelemetry.recordEvent("_UpdateLocalParticipantStream",getStreamInformation(T),f),this.streamManager.updateStreams(T,f),this.updateCapabilities(f,!0),this.allowScreenSharingControl()&&this.screenSharingControl?.isInternalViewerControlEnabled()){const f=g.endpointDetails.find((g=>this._endpointId===g.endpointId)),S=this.participants.find((g=>g.streams[1].some((g=>g.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,S,f)}}modalitiesAreHold(g){return!(g.audio&&"inactive"!==g.audio||g.video&&"inactive"!==g.video||g.sharing&&"inactive"!==g.sharing)}toneToString(g){switch(g){case 0:return"0";case 1:return"1";case 2:return"2";case 3:return"3";case 4:return"4";case 5:return"5";case 6:return"6";case 7:return"7";case 8:return"8";case 9:return"9";case 10:return"*";case 11:return"#";default:return null}}static streamingStatetoMediaStreamState(g){switch(g){case"started":return 0;case"active":return 2;case"inactive":return 1;case"stopped":return 3;default:return 4}}static streamingDirectionToMediaDirectionMapping(g){switch(g){case"send":return 1;case"receive":return 0;default:return}}static convertMuteScope(g){switch(g){case 0:return"EveryoneElse";case 1:return"SpecifiedParticipants";default:return}}callIsHeld(){return 4===this.state||5===this.state}inLocalHold(){return this.isHoldInProgress||4===this.state}telemetryDataFromCallStartOptions(g){const f={};return g.muteFlags&&(f.muteMicrophone=!!(1&g.muteFlags),f.muteSpeaker=!!(2&g.muteFlags)),Object.keys(f).length?f:void 0}reconnect(){const g=generateCauseId();return this.mediaSession.reconnectAsync(g)}async provideCallQualityFeedback(g,f,S,v){}async showCQFInfo(g,f){throw new Error("Not implemented")}async isCqfRendered(g){}async provideCallQualityFeedbackEx(g,f,S,v,C,_){}testTriggerMediaRelayWhiteListingIssue(){this.logger.info("Simulating media relay whitelisting issue for test purposes");const g=this.mediaSession.mediaSession.callback,f={type:"NetworkRelaysNotReachable",value:"Bad",isLocalSource:!0,mediaType:"Audio"};g.onQualityChanged(f);const S={direction:"send",stream:"failed",content:"audio"};g.onAudioStateChanged(S)}async getMediaTelemetry(g=!1){return this.mediaSession&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(g)),this.appendInfoToCallStats()),this.callStats.buildMediaTelemetry()}getMediaSessionStats(){return this.mediaSession?.getMediaStatsReport()}async getMediaSessionStatsAsync(){return this.mediaSession?.getMediaStatsReport()}getDiagnosticsForE2E(){return this.mediaSession?.getDiagnostics().e2eDiagnostics}appendInfoToCallStats(){this.callStats.appendDataChannelInfo(this.dataChannel.getTelemetry()),this.callStats.appendSharingControlInfo(this.screenSharingControl?.isScreenSharingControlEnabled()),this.callStats.appendMediaControlPlaneInfo(JSON.stringify(this.mediaSession?.getMediaControlPlaneInstance()?.getTelemetryReport()))}getMediaLogs(){return this.mediaAgent.getMediaLogs()}testSetCallState(g){this.logger.info(`Overwriting call state for test purposes: ${this.state} -> ${g} `),this.state=g}testSetCallType(g){this.logger.info(`Overwriting call state for test purposes: ${this.callType} -> ${g} `),this.callType=g}addGroupModality(g,f=generateCauseId()){const S=this.logger.createFnLogger("AddGroupModality",f);if(!g.threadId&&!g.groupId)return Promise.reject(getRejectTransactionEnd("No threadId/groupId was provided."));if(6===this.state||7===this.state)return S.info(`Not adding modality because CallState is ${this.state} groupId=${scrubMriOrOmit(g.groupId)}, threadId = ${getLoggableThreadId(g.threadId)} messageId = ${g.messageId}`),Promise.reject(getRejectTransactionEnd("TransactionDisallowed"));let v;if(g.additionalData)try{v=JSON.stringify(g.additionalData)}catch(f){S.logFailure(`additionalData: ${g.additionalData} is not valid Json, error: ${f}`);const v={code:Fi.BadRequest,subCode:0,phrase:`additionalData is not valid Json, error: ${f}`};return Promise.reject(v)}if(S.info(`groupId=${scrubMriOrOmit(g.groupId)}, threadId = ${getLoggableThreadId(g.threadId)} messageId = ${g.messageId} additionalData = ${scrubMriOrOmit(v)}`),this._enableAddModalityGeneric){const v={groupContext:{id:g.groupId},groupChat:{threadId:g.threadId,messageId:g.messageId}};return this.signalingSession.addModalityAsync(v,f).catch((g=>(S.logFailure(getPrintableObject(g)),Promise.reject(g))))}{const C={groupId:g.groupId,threadId:g.threadId,messageId:g.messageId,additionalData:v};return this.signalingSession.addGroupModalityAsync(C,f).catch((g=>(S.logFailure(getPrintableObject(g)),Promise.reject(g))))}}addBroadcastModality(g,f){const S=this.logger.createFnLogger("AddBroadcastModality",f);return Promise.resolve().then((()=>{this.signalingSession.addBroadcastModalityAsync(g,f)})).catch((g=>(S.logFailure(getPrintableObject(g)),Promise.reject(getRejectTransactionEnd(g))))).then((()=>this._callOperationHandler.waitForOperation("AddBroadcastModality"))).catch((g=>{throw this.callTelemetry.updateOperationData("AddBroadcastModality",{error:getPIISafeObject(g)},f),S.logFailure(g),g}))}static convertQualityEventType(g){switch(g){case"NetworkSendQuality":return 1;case"NetworkRecvQuality":return 2;case"NetworkDelay":return 3;case"NetworkBandwidthLow":return 4;case"NetworkReconnect":return 5;case"NetworkPacketLoss":return 6;case"NetworkJitter":return 7;case"NetworkRateMatching":return 8;case"DeviceCaptureNotFunctioning":return 9;case"DeviceRenderNotFunctioning":return 10;case"DeviceRenderGlitches":return 11;case"DeviceLowSNR":return 12;case"DeviceLowSpeechLevel":return 13;case"DeviceClipping":return 14;case"DeviceEcho":return 15;case"DeviceNearEndToEchoRatio":return 16;case"DeviceHalfDuplexAec":return 17;case"DeviceMultipleEndpoints":return 18;case"DeviceHowling":return 19;case"DeviceRenderZeroVolume":return 20;case"DeviceRenderMute":return 21;case"NetworkSendCatastrophic":return 22;case"NetworkRecvCatastrophic":return 23;case"CpuInsufficient":return 24;case"DeviceCaptureMute":return 25;case"DeviceCaptureNotMuteButSilent":return 26;case"DeviceSpeakWhileMuted":return 27;case"VideoVbssRendered":return 28;case"NetworkEthernetInterfaceUsed":return 29;case"NetworkWlanInterfaceUsed":return 30;case"NetworkWwanInterfaceUsed":return 31;case"NetworkRelaysNotReachable":return 32;case"VideoCapturerDeviceStartFailed":return 33;case"VideoCapturerDeviceStartTimedOut":return 34;case"VideoCapturerDeviceStartFailureLackSystemRes":return 35;case"VideoCapturerDeviceStartFailureMFResConflict":return 36;case"NoNetwork":return 37;case"NetworkNotWorking":return 38;case"DeviceCaptureNotFunctioningDeviceInUse":return 39;case"DeviceRenderNotFunctioningDeviceInUse":return 40;case"VideoCaptureDeviceFreeze":return 45;case"ZeroCaptureDevicesEnumerated":return 43;case"ZeroRenderDevicesEnumerated":return 44;case"VideoCapturePermissionDenied":return 47;case"ScreenshareRecordingDisabled":return 55;case"AudioCapturePermissionDenied":return 46;case"VideoCaptureFreezeRecovered":return 48;case"DeviceRenderHowling":return 49;case"PresentationAudioLoopbackDeviceState":return 53;case"RemoteNetworkConnectivityIssue":return 52;case"AudioCaptureUltrasoundDetected":return 54;case"MusicModeNotAvailable":return 57;case"CameraLighting":return 61;case"AudioLoopbackDeviceReady":return 63;case"NoRequiredVideoCodecs":return 64;case"SpatialAudioMUCHUnavailable":return 65;case"AudioMixMUCHUnavailable":return 80;default:return}}static convertQualityLevel(g){switch(g){case"Unknown":return 0;case"Good":return 1;case"Poor":return 2;case"Bad":return 3;default:return}}static convertMediaType(g){switch(g){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2;case"Data":return 3;default:return}}getPluginlessPublishLevel(g){switch(g){case"user":return"user";case"endpoint":return"endpoint";default:throw"Invalid level type."}}setIsEmergency(g){this.logger.info(`Set isEmergency:${g}`),this.isEmergency=g,this.callTelemetry.setIsEmergency(g)}static filterVirtualEndpoints(g){return g&&(0,Ki.filter)(g,(g=>!g.mappedTo))}mapDataChannelSourceIdToParticipant(g){let f=null;return f=1===this.callType?this.participants[0]:(0,Ki.find)(this.participants,(f=>f.hasSourceId(3,g))),f?.id?this.logger.info(`ParticipantId: ${scrubMriOrOmit(f.id)} to SourceId: ${g}`):this.logger.warn(`No Participant found for SourceId: ${g}`),f}getDataChannelSourceId(){const g=(0,Ki.find)(this.endpoints.endpointDetails,(g=>null!==g&&g.participantId===this._participantId));if(!g)return this.logger.warn(`No participantLeg found for participantId: ${this._participantId}`),-1;if(!g.mediaStreams)return this.logger.warn(`ParticipantLeg ${this._participantId} does not have valid mediaStreams`),-1;const f=(0,Ki.find)(g.mediaStreams,(g=>3===mapMediaTypeStringToMediaType(g.type)));return f?f.sourceId:(this.logger.warn(`participantLeg ${this._participantId} has no data channel`),-1)}initializeLiveStreamConfigProvider(){const g="MDN_MIDDLELANE_TEAMS",f="liveStream",S=this.ecsProvider.getEcsConfig(g,f),v=this.ecsProvider.getEcsConfig("ConfigIDs",g);this._liveStreamConfigProvider=new rt(S,null,v,this.logger.createChild("LiveStreamConfigProvider"))}isMediaSending(g){return this.mediaStateConfigurationHelper.isSending(g)}async setAudioStreamConnectedAsync(g){this.isAudioStreamConnected=g}async setSpamRiskLevelAsync(g){this.spamRiskLevel=g}async setSpamStirAttestationAsync(g){this.spamStirAttestation=g}async setDominantSpeakerInfoAsync(g){this.dominantSpeakerInfo=g}async setSlowedDownActiveTalkerInfoAsync(g){this.slowedDownActiveTalkerInfo=g}};oo.instanceCount=0,oo.getNegotiationTagsFromEndpoints=g=>{if(!g)return;const f=new Map;return oo.filterVirtualEndpoints(g).forEach((g=>{f.set(g.endpointId,g.negotiationTag)})),f},__decorateClass([callOperation("Initialize",{type:"Sync",convertError:!0,idempotencyLevel:"NoOp"})],oo.prototype,"init",1),__decorateClass([callOperation("StartVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"startVideo",1),__decorateClass([callOperation("StopVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"stopVideo",1),__decorateClass([callOperation("DumpVideoSourceImages")],oo.prototype,"dumpVideoSourceImages",1),__decorateClass([__decorateParam(1,causeId)],oo.prototype,"hold",1),__decorateClass([callOperation("Hold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"holdWithRenegotiate",1),__decorateClass([callOperation("LocalHold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"localHold",1),__decorateClass([callOperation("Unhold",{waitFor:["Hold","LocalHold"],preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"unhold",1),__decorateClass([callOperation("UpdateEndpointMetadata"),__decorateParam(1,causeId)],oo.prototype,"updateEndpointMetadata",1),__decorateClass([callOperation("SendDtmfTone",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],oo.prototype,"sendDtmfTone",1),__decorateClass([callOperation("SetAudioUsage")],oo.prototype,"setAudioUsageMode",1),__decorateClass([callOperation("SetAudioMidcallConfig")],oo.prototype,"setAudioMidcallConfig",1),__decorateClass([callOperation("SetAudioMidcallConfigJon",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"setAudioMidcallConfigJson",1),__decorateClass([callOperation("SetParticipantSpatialAudioPositions",{waitFor:"_ElectronSlimcoreReady",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"setParticipantSpatialAudioPositions",1),__decorateClass([callOperation("BlindTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"callBlindTransfer",1),__decorateClass([callOperation("SafeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"callSafeTransfer",1),__decorateClass([callOperation("TransferToVoicemail",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"transferCallToVoicemail",1),__decorateClass([callOperation("ConsultativeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"callConsultativeTransfer",1),__decorateClass([callOperation("ConsultativeTransferWithPickupCode",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],oo.prototype,"consultativeTransferWithPickupCode",1),__decorateClass([callOperation("CallRedirect",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"callRedirect",1),__decorateClass([callOperation("ParkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"park",1),__decorateClass([callOperation("UnparkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"unpark",1),__decorateClass([callOperation("getTechnicalInformationJson",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],oo.prototype,"getTechnicalInformationJson",1),__decorateClass([callOperation("StartScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(3,causeId)],oo.prototype,"startScreenSharing",1),__decorateClass([callOperation("StopScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(2,causeId)],oo.prototype,"stopScreenSharing",1),__decorateClass([callOperation("StartDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"startDataChannel",1),__decorateClass([callOperation("StopDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"stopDataChannel",1),__decorateClass([callOperation("ShareSystemSounds",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"shareSystemSound",1),__decorateClass([callOperation("Mute",{waitFor:"JoinPreheatedCall",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]},!0),__decorateParam(0,causeId)],oo.prototype,"mute",1),__decorateClass([callOperation("Unmute",{waitFor:["JoinPreheatedCall"]},!0),__decorateParam(0,causeId)],oo.prototype,"unmute",1),__decorateClass([callOperation("MuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"muteSpeaker",1),__decorateClass([callOperation("UnmuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"unmuteSpeaker",1),__decorateClass([callOperation("GetSpeakerVolume",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId)],oo.prototype,"getSpeakerVolume",1),__decorateClass([callOperation("SetSpeakerVolume",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"setSpeakerVolume",1),__decorateClass([callOperation("MuteParticipants",void 0,!0),__decorateParam(2,causeId)],oo.prototype,"muteParticipants",1),__decorateClass([callOperation("StartAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"startAudio",1),__decorateClass([callOperation("StopAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"stopAudio",1),__decorateClass([callOperation("Assimilate"),__decorateParam(3,causeId)],oo.prototype,"assimilate",1),__decorateClass([__decorateParam(2,causeId)],oo.prototype,"merge",1),__decorateClass([callOperation("MergeParticipants"),__decorateParam(1,operationId),__decorateParam(3,causeId)],oo.prototype,"mergeParticipants",1),__decorateClass([callOperation("MergeWithPickupCode"),__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"mergeWithPickupCode",1),__decorateClass([callOperation("SetMaxVideoChannels")],oo.prototype,"setMaxVideoChannels",1),__decorateClass([callOperation("SetMaxVbssChannels")],oo.prototype,"setMaxVbssChannels",1),__decorateClass([callOperation("StopCall"),__decorateParam(1,causeId),__decorateParam(3,reason)],oo.prototype,"stop",1),__decorateClass([callOperation("PublishState"),__decorateParam(1,operationId)],oo.prototype,"publishState",1),__decorateClass([callOperation("PublishState"),__decorateParam(1,operationId)],oo.prototype,"publishStatesForEveryone",1),__decorateClass([callOperation("RemoveState"),__decorateParam(1,operationId)],oo.prototype,"removeState",1),__decorateClass([callOperation("RemoveState"),__decorateParam(1,operationId)],oo.prototype,"removeStatesForEveryone",1),__decorateClass([callOperation("UpdateMeetingSettings"),__decorateParam(1,operationId)],oo.prototype,"updateMeetingSettings",1),__decorateClass([callOperation("UpdateMeetingGroups"),__decorateParam(0,operationId)],oo.prototype,"updateMeetingGroups",1),__decorateClass([callOperation("UpdateMeetingLiveState"),__decorateParam(0,operationId)],oo.prototype,"updateMeetingLiveState",1),__decorateClass([callOperation("UpdateMeetingStates"),__decorateParam(1,operationId)],oo.prototype,"updateMeetingStates",1),__decorateClass([callOperation("UpdateParticipantInterpretationState"),__decorateParam(0,operationId)],oo.prototype,"updateParticipantInterpretationState",1),__decorateClass([callOperation("UpdateParticipantsProperties")],oo.prototype,"updateParticipantsProperties",1),__decorateClass([callOperation("JoinMeetingGroup"),__decorateParam(0,operationId)],oo.prototype,"joinMeetingGroup",1),__decorateClass([callOperation("LeaveMeetingGroup"),__decorateParam(0,operationId)],oo.prototype,"leaveMeetingGroup",1),__decorateClass([callOperation("SendMessages"),__decorateParam(0,operationId)],oo.prototype,"sendMessages",1),__decorateClass([callOperation("UpdateMonitorSession"),__decorateParam(1,causeId)],oo.prototype,"updateMonitorSession",1),__decorateClass([callOperation("SwitchInterpreterGroup")],oo.prototype,"switchInterpreterGroup",1),__decorateClass([callOperation("SetLiveInterpretationAttributes")],oo.prototype,"setLiveInterpretationAttributes",1),__decorateClass([callOperation("UpdateMeetingRole")],oo.prototype,"updateMeetingRoles",1),__decorateClass([callOperation("CreateContentSharingSession"),__decorateParam(4,causeId)],oo.prototype,"createContentSharingSession",1),__decorateClass([callOperation("StopCallWithBeacon",{type:"Sync"}),__decorateParam(0,causeId)],oo.prototype,"stopWithBeacon",1),__decorateClass([callOperation("Acknowledge",{type:"Chained",convertError:!0,idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(2,causeId)],oo.prototype,"acknowledge",1),__decorateClass([callOperation("Accept",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(1,causeId)],oo.prototype,"accept",1),__decorateClass([callOperation("Reject",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(0,causeId),__decorateParam(1,reason)],oo.prototype,"reject",1),__decorateClass([callOperation("JoinCall",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(1,callStartOptions),__decorateParam(2,causeId)],oo.prototype,"join",1),__decorateClass([callOperation("JoinPreheatedCall",{waitFor:"_CallStartOrJoinInitiated"})],oo.prototype,"joinPreheatedCall",1),__decorateClass([callOperation("StartCall",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(0,callStartOptions),__decorateParam(1,causeId)],oo.prototype,"start",1),__decorateClass([callOperation("StartCallToVoiceMail",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(1,causeId)],oo.prototype,"startCallToVoicemail",1),__decorateClass([callOperation("Subscribe",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(2,causeId)],oo.prototype,"joinCallWithoutCallModality",1),__decorateClass([callOperation("StartWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],oo.prototype,"startWithMeetingData",1),__decorateClass([callOperation("JoinWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],oo.prototype,"joinWithMeetingData",1),__decorateClass([callOperation("SubscribeWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],oo.prototype,"subscribeWithMeetingData",1),__decorateClass([callOperation("StartCallWithNudge",{type:"Chained",idempotencyLevel:"Error"}),__decorateParam(1,callStartOptions),__decorateParam(2,causeId)],oo.prototype,"startCallWithNudge",1),__decorateClass([callOperation("StartCallAndUnpark",{type:"Chained",idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),__decorateParam(2,callStartOptions),__decorateParam(3,causeId)],oo.prototype,"startAndUnpark",1),__decorateClass([participantOperation("AdmitParticipant"),__decorateParam(0,operationId),__decorateParam(1,causeId)],oo.prototype,"admitParticipant",1),__decorateClass([callOperation("Admit")],oo.prototype,"admit",1),__decorateClass([participantOperation("CallMeBack"),__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"callMeBack",1),__decorateClass([__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"addParticipant",1),__decorateClass([participantOperation("AddParticipants"),__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"addParticipants",1),__decorateClass([__decorateParam(0,operationId),__decorateParam(2,causeId)],oo.prototype,"addParticipantsImpl",1),__decorateClass([participantOperation("NudgeParticipants"),__decorateParam(0,operationId),__decorateParam(3,causeId)],oo.prototype,"nudgeParticipants",1),__decorateClass([participantOperation("RemoveParticipant"),__decorateParam(0,operationId),__decorateParam(1,causeId)],oo.prototype,"removeParticipant",1),__decorateClass([participantOperation("CancelNudge"),__decorateParam(0,operationId),__decorateParam(0,causeId)],oo.prototype,"cancelNudge",1),__decorateClass([callOperation("SearchParticipants"),__decorateParam(1,operationId),__decorateParam(1,causeId)],oo.prototype,"searchParticipants",1),__decorateClass([callOperation("GetAllParticipants"),__decorateParam(1,operationId),__decorateParam(1,causeId)],oo.prototype,"getAllParticipants",1),__decorateClass([callOperation("_PromotionToRealtime"),__decorateParam(1,causeId)],oo.prototype,"promoteToRealtime",1),__decorateClass([__decorateParam(0,causeId)],oo.prototype,"turnOffLocalVideoPreview",1),__decorateClass([callOperation("_StartPreviewVideo"),__decorateParam(0,causeId)],oo.prototype,"turnOnLocalVideoPreview",1),__decorateClass([__decorateParam(0,causeId)],oo.prototype,"acquireLocalVideo",1),__decorateClass([__decorateParam(0,causeId)],oo.prototype,"turnOnLocalVideoPreviewUsingRenderer",1),__decorateClass([callOperation("_UpdateLocalMediaStatus",{type:"Chained"}),__decorateParam(0,causeId)],oo.prototype,"updateMediaStatus",1),__decorateClass([__decorateParam(0,causeId)],oo.prototype,"calculateIsSomeoneStreaming",1),__decorateClass([callOperation("_Reconnect")],oo.prototype,"reconnect",1),__decorateClass([callOperation("AddGroupModality"),__decorateParam(1,causeId)],oo.prototype,"addGroupModality",1),__decorateClass([callOperation("AddBroadcastModality")],oo.prototype,"addBroadcastModality",1);var lo=oo;function decode(g){const f=new TextDecoder("utf-8"),S=atob(g),v=Uint8Array.from(S,(g=>g.charCodeAt(0)));return f.decode(v)}var co=__toESM2(ye()),ho=new RegExp("/callAgent/","i"),uo=class{constructor(g,f){this.signalingAgentProvider=g,this.callRegistry=f}handleMessage(g){if(!g.eventId){if(g.url.search(ho)>-1){const f=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(g);return"number"==typeof f?{isHandled:!0,resultCode:f}:{isHandled:!0,resultCode:f.resultCode,responseBody:f.responseBody,responseHeaders:f.responseHeaders}}return{isHandled:!1}}if(g.eventId in ji){this.callRegistry.logUploadNotification(g);const f=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(g);return"number"==typeof f?{isHandled:!0,resultCode:f}:{isHandled:!0,resultCode:f.resultCode,responseBody:f.responseBody,responseHeaders:f.responseHeaders}}return{isHandled:!1}}},go=class{constructor(g,f,S){this.callRegistry=g,this.recentInvitations=[],this.logger=f.createChild("IncomingCallMessageHandler"),this.ecsProvider=S}handleMessage(g){const f=this.handleIncomingCall(g);return f?{isHandled:f,resultCode:200}:{isHandled:f}}handleIncomingCall(g){const f=generateCauseId(),S=this.logger.createFnLogger("handleIncomingCall",f);if(this.isProxiableNotification(g))return this.callRegistry.proxyPushNotification(g),!0;if(!this.isIncomingCallMessage(g))return!1;let v;this.callRegistry.pushHandlingStarted(f);try{if(g?.body?.gp&&!isStringBase64(g.body.gp))S.info("unencoded payload, skipping decoding."),v=g.body.gp;else{const f=decodeNotificationPayload(g,S);v=JSON.parse(f)}v.body=g.body}catch(g){return this.callRegistry.pushHandlingEnded(f,{result:"Failed to parse incoming call notification payload",code:Fi.BadRequest,subCode:3080,participantId:"",callId:"",resultCategories:["UnexpectedServerError"]}),S.logFailure(`Error parsing notification payload: ${g}`),!1}const C=this.isCallTransferNotification(g)?this.buildTransferCallPayload(v):this.buildNGCCallPayload(v);if(!C)return this.callRegistry.pushHandlingEnded(f,{result:"Failed to get incoming call notification payload",code:Fi.BadRequest,subCode:3081,participantId:"",callId:"",resultCategories:["UnexpectedClientError"]}),!1;if(this.callRegistry.calls.some((g=>g.callId===C.convoCallId&&g.participantId===C.participantId)))return S.logFailure(`Duplicate call filtered because it was in the call registry, callId = ${C.convoCallId}, participantId = ${C.participantId}`),this.callRegistry.pushHandlingEnded(f,{result:"Failed due to duplicate call filtered because it was in the call registry",code:Fi.LocalError,subCode:3082,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["ExpectedError"]}),!1;const _=this.isCallReplacementNotification(g);if(S.log(`replacementCall=${_}`),!_&&this.recentInvitations.some((g=>g.convoCallId===C.convoCallId&&g.participantId===C.participantId)))return S.logFailure(`Duplicate call filtered because it was in the recent calls list, callId = ${C.convoCallId}, participantId = ${C.participantId}`),this.callRegistry.pushHandlingEnded(f,{result:"Failed due to duplicate call filtered because it was in the recent calls list",code:Fi.LocalError,subCode:3083,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["ExpectedError"]}),!1;5===this.recentInvitations.length&&this.recentInvitations.shift(),this.recentInvitations.push({convoCallId:C.convoCallId,participantId:C.participantId});let T=this.callRegistry.calls.find((g=>g.callId===C.convoCallId&&8===g.state));if(!T)if(C.groupId)try{T=this.callRegistry.createCallWithGroupId(C.groupId,C.convoCallId,C.participantId,f)}catch(g){this.callRegistry.pushHandlingEnded(f,{result:"Failed to create incoming call notification with groupId",code:Fi.BadRequest,subCode:3084,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["UnexpectedClientError"]})}else try{T=this.callRegistry.createCall(C.conversationId,C.convoCallId,C.participantId,void 0,f)}catch(g){this.callRegistry.pushHandlingEnded(f,{result:"Failed to create incoming call notification",code:Fi.BadRequest,subCode:3084,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["UnexpectedClientError"]})}return T.init({threadId:C.conversationId,messageId:C.messageId,mediaPeerType:2}),this.callRegistry.testEndpointMetadata?T.acknowledge(C,this.callRegistry.testEndpointMetadata,f).then((()=>this.callRegistry.pushHandlingEnded(f,{code:an.HTTP_STATUS_CODES.OK,subCode:Fi.Success,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["Success"]}))).catch((g=>this.callRegistry.pushHandlingEnded(f,{result:"Failed to acknowledge incoming call notification",code:Fi.LocalError,subCode:3085+g.code,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["UnexpectedClientError"]}))):T.acknowledge(C,void 0,f).then((()=>this.callRegistry.pushHandlingEnded(f,{code:an.HTTP_STATUS_CODES.OK,subCode:Fi.Success,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["Success"]}))).catch((g=>this.callRegistry.pushHandlingEnded(f,{result:"Failed to acknowledge incoming call notification",code:Fi.LocalError,subCode:3085+g.code,participantId:C?.participantId,callId:C?.convoCallId,resultCategories:["UnexpectedClientError"]}))),!0}isIncomingCallMessage(g){return Object.keys(Hi).some((f=>Hi[f]===g.eventId))?g.eventId!==Hi.INCOMING_TFL_TFW_CALL||this.ecsProvider?.getEcsConfig("SkypeCalling","enableTFWTFLOneToOneCall"):this.isCallTransferNotification(g)}isCallTransferNotification(g){return g.callNotification&&("transfer"===g.callNotification.callType||"replaces"===g.callNotification.callType)}isCallReplacementNotification(g){return g.callNotification&&"replaces"===g.callNotification.callType}isProxiableNotification(g){return Object.keys($i).some((f=>$i[f]===g.eventId))}buildTransferCallPayload(g){const f={body:g.body,callerId:g.callNotification.from.id,displayNameSource:parseDisplayNameSourceFromWire(g.callNotification.from.displayNameSource),groupId:null,conversationId:null,convoCallId:g.debugContent.callId,isMultiParty:g.conversationInvitation?.isMultiParty,fromMixer:g.callNotification.fromMixer,ngcCall:!0,participantId:g.callNotification.to.participantId,transferorId:g.callNotification.transferor&&g.callNotification.transferor.details&&g.callNotification.transferor.details.id,transferorType:g.callNotification.transferor&&g.callNotification.transferor.transferorType,transferorDisplayName:g.callNotification.transferor&&g.callNotification.transferor.details&&g.callNotification.transferor.details.displayName,callType:g.callNotification.callType,consultativeCallId:g.callNotification.consultativeCallId,messageId:null,callQueueInfo:g.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0};return this.logger.info("Incoming transfer paylod",getPIISafePayload(f,["callerId","transferorId"])),f}buildNGCCallPayload(g){if(!g.callNotification)return this.logger.error("Missing callNotification in parsed incoming NGC call payload"),null;const f={groupId:g.groupContext?.id,conversationId:g.groupChat?.threadId,messageId:g.groupChat?.messageId,callerId:g.callNotification.from.id,displayNameSource:parseDisplayNameSourceFromWire(g.callNotification.from.displayNameSource),isMultiParty:g.conversationInvitation.isMultiParty,fromMixer:g.callNotification.fromMixer,convoCallId:g.debugContent.callId,participantId:g.debugContent.participantId,ngcCall:!0,body:g.body,transferorId:g.callNotification.transferor&&g.callNotification.transferor.details&&g.callNotification.transferor.details.id,transferorType:g.callNotification.transferor&&g.callNotification.transferor.transferorType,transferorDisplayName:g.callNotification.transferor&&g.callNotification.transferor.details&&g.callNotification.transferor.details.displayName,callType:g.callNotification.callType,callQueueInfo:g.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0,fromApplicationType:g.callNotification.fromApplicationType};return this.logger.info("Incoming NGC paylod",getPIISafePayload(f,["callerId","transferorId"])),f}},po=class extends Ke{constructor(g,f,S,v,C,_=null,T,I,b){super(),this.trouterService=g,this.signalingAgentProvider=f,this.mediaAgent=S,this.callingLogger=v,this.telemetryLoggers=C,this.ecsProvider=_,this.skypeIdentity=T,this.oneDsTelemetryLoggers=I,this.vdi3diagnostics=b,this.calls=[],this.isDisposing=!1,this._disposedPromise=new dt,this.testEndpointMetadata=null,this._disconnectingPromiseDefers=new Map,this.skypeIdentity&&(this.identity=this.skypeIdentity.id),this.callSubscriptionsMap=new Map,this.logger=new Ge(this.callingLogger).createChild(`CallRegistry/${generateCauseId()}`),this.registryTelemetry=new Ti(this.logger,(new Date).getTime()),this._callOperationHandler||(this._callOperationHandler=new Li(this.logger,this.registryTelemetry,{},(g=>{this._publishTelemetry(g)})));const A=this.mediaAgent.getConfig().disconnectOnPageHide;this._windowUninitEvent=A?"pagehide":"beforeunload",this.signalingAgentProvider.getSignalingAgent().setTokenRequiredCallBack(this.onTokenRequired.bind(this)),this._createNewCallInDisconnectedState=this.ecsProvider.getEcsConfig("SkypeCalling","createNewCallInDisconnectedState"),this._invokeDeleteCallInDisconnectedState=this.ecsProvider.getEcsConfig("SkypeCalling","invokeDeleteCallInDisconnectedState")}init(g,f,S=generateCauseId()){return this.logger.createFnLogger("init",S).info("init"),this.login(g)}uninit(){return this.logout()}login(g,f=generateCauseId()){return this.logger.createFnLogger("login",f).info("login"),this.skypeIdentity=g,this.identity=this.skypeIdentity.id,this.initialize(f)}initialize(g=generateCauseId(),f){const S=this.logger.createFnLogger("initialize",g),v=f&&f.applicationType?f.applicationType:"null";S.info(`initialize with applicationType: ${v}`),this.accountConfiguration=f,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(f),this.incomingCallMessageHandler=new go(this,this.logger,this.ecsProvider),this.trouterService.registerMessageHandler(new uo(this.signalingAgentProvider,this)),this.trouterService.registerMessageHandler(this.incomingCallMessageHandler),S.info("Call registry init, endpointMetadata",this.testEndpointMetadata);try{this.windowUninitListener=()=>{this._disregardWindowUninitEvents||this.stopCallsWithBeacon()},window.addEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(g){S.logFailure(`Not adding beforeunload listener: ${g}`)}return Promise.resolve(void 0)}logout(g=generateCauseId()){const f=this.logger.createFnLogger("logout",g);f.info("logout");try{this.trouterService.clearMessageHandlers(),window.removeEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(g){f.info(`Not removing beforeunload listener: ${g}`)}return Promise.resolve(void 0)}_publishTelemetry(g){if(!this.telemetryLoggers?.signaling)return;this.registryTelemetry.setSkypeId(this.identity);try{const g=this.signalingAgentProvider.getSignalingAgent();this.registryTelemetry.setEndpointId(g.endpointId)}catch(g){this.logger.warn("Could not get end point ID from signaling agent for call registry telemetry.")}this.accountConfiguration&&(this.registryTelemetry.setAcsResourceId(this.accountConfiguration.acsResourceId),this.registryTelemetry.setApplicationType(this.accountConfiguration.applicationType),this.registryTelemetry.setPartition(this.accountConfiguration.partition),this.registryTelemetry.setRegion(this.accountConfiguration.region),this.registryTelemetry.setRing(this.accountConfiguration.ring),this.registryTelemetry.setTenantId(this.accountConfiguration.tenantId),this.registryTelemetry.setUserHexCID(this.accountConfiguration.userHexCID),this.registryTelemetry.setClientType(this.accountConfiguration.clientType));const f=mi.REGISTRY_WEB;this.telemetryLoggers.signaling.sendEvent({eventName:f,props:this.registryTelemetry.getEvent(null,g)})}async dispose(g=generateCauseId()){const f=this.logger.createFnLogger("dispose",g);if(f.info("dispose"),this.isDisposing)return f.warn("call registry is already in disposing stage!"),this._disposedPromise.promise;this.isDisposing=!0;const always=()=>{this.calls=[],this.event("disposed").raise(),super.dispose(),this._disposedPromise.resolve()},S=this.calls.map((g=>g.stop())),logout=()=>this.logout();return this.clearCallSubscription(),this.signalingAgentProvider.getSignalingAgent().resetAuthTokenManager(),Promise.all(S).then(logout,logout).then(always,always),this._disposedPromise.promise}get disposePromise(){return this._disposedPromise.promise}createCallAsync(g){const f=this.logger.createFnLogger("createCallAsync",g.causeId),S=`callId:${g.callId}, localParticipantId: ${scrubMriOrOmit(g.localParticipantId)},\n            causeId:${g.causeId}, type:${g.type}, `;switch(g.type){case"MeetingData":S.concat(`meetingUrl:${!!g.meetingData?.meetingUrl}, meetingCode:${!!g.meetingData?.meetingCode}`);break;case"GroupId":S.concat(`groupId:${scrubMriOrOmit(g.groupId)}`);break;case"ThreadId":S.concat(`threadId:${getLoggableThreadId(g.threadId)}, messageId:${g.messageId}`);break;default:throw new Error("Invalid type in passing parameter.")}f.info(S);const v=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers,C=this._getCurrentCall(g,f);if(C){if(6===C.state){const g=new dt;return this._disconnectingPromiseDefers.set(C.callId,g),g.promise}return Promise.resolve(C)}return Promise.resolve(this._createNewCall(g,v,f))}createCallWithMeetingData(g,f,S,v){const C=this.logger.createFnLogger("createCallWithMeetingData",v);if(C.info(`meetingData:${!!g}, callId:${f}, localParticipantId: ${scrubMriOrOmit(S)}`),!g)return C.info("meetingData cannot be null"),null;const _=this._generateCreateCallOptions(v,f,S,null,null,null,g),T=this._getCurrentCall(_,C);if(T)return T;const I=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(_,I,C)}createCall(g,f,S,v,C=generateCauseId()){return this._createCall(g,f,S,v,C)}createCallWithGroupId(g,f,S,v){return this._createCall("",f,S,void 0,v,g)}_createNewCall(g,f,S){let v=null,C=null,_=null,T=null;switch(g.type){case"MeetingData":T=g.meetingData;break;case"GroupId":v=g.groupId;break;case"ThreadId":C=g.threadId,_=g.messageId}const I=new lo(this.signalingAgentProvider.getSignalingAgent(),this.mediaAgent,new Ge(this.callingLogger),f,this.skypeIdentity,v,C,g.callId,g.localParticipantId,this.ecsProvider,this.trouterService,this.accountConfiguration,_,this.locationInfoContent,this.networkInfoContent,T,this.areaContent,this.vdi3diagnostics);I.on("callStateChanged",(async()=>{if(7===I.state&&this._createNewCallInDisconnectedState){const v=this._disconnectingPromiseDefers.get(I.callId);v&&(this._disconnectingPromiseDefers.delete(I.callId),v.resolve(this._createNewCall(g,f,S))),this._invokeDeleteCallInDisconnectedState&&setTimeout((()=>{this.deleteCall(I)}),0)}})),this.calls.push(I),this.event("callAdded").raise(I),this.raiseChanged(),S.info(`Created new call with id ${I.callId}`);const b=I.on("replacementRequested",(g=>{this.incomingCallMessageHandler.handleMessage(g)}));return this.addCallSubscriptionToMap(I,b),I}_getCurrentCall(g,f){let S=null;return"MeetingData"===g.type&&(S=this.getCallUsingMeetingData(g.meetingData,g.callId,g.localParticipantId,void 0,void 0,g.causeId),S)?(f.info("Call Registry has an entry for this call's meeting data"),S):(S=this.getCall(g.callId,g.localParticipantId,g.causeId),S?(f.info("Call Registry has an entry for this callId, participantId"),S):"ThreadId"===g.type&&(S=this.getCallUsingThreadIdMessageId(g.threadId,g.callId,g.messageId,g.causeId),S)?(f.info("Call Registry has an entry for this threadId, messageId"),S):"GroupId"===g.type&&(S=this.calls.find((f=>f.groupId===g.groupId)),S)?(f.info("Call Registry has an entry for this groupId"),S):S)}_generateCreateCallOptions(g,f,S,v,C,_,T){let I=null;return I=v?{type:"GroupId",callId:f,localParticipantId:S,causeId:g,groupId:v}:C?{type:"ThreadId",callId:f,localParticipantId:S,causeId:g,threadId:C,messageId:_}:{type:"MeetingData",callId:f,localParticipantId:S,causeId:g,meetingData:T},I}_createCall(g,f,S,v,C=generateCauseId(),_){const T=this.logger.createFnLogger("createCall",C);T.info(`threadId:${getLoggableThreadId(g)}, callId:${f}, localParticipantId: ${scrubMriOrOmit(S)}, messageId:${v}, groupId:${scrubMriOrOmit(_)}`);const I=this._generateCreateCallOptions(C,f,S,_,g,v,null),b=this._getCurrentCall(I,T);if(b)return b;const A=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(I,A,T)}getCall(g,f,S=generateCauseId()){const v=this.logger.createFnLogger(`getCall[callId=${g}][participantId=${scrubMriOrOmit(f)}]`,S);if(!g)return v.logFailure("callId is undefined"),null;const C=this.calls.find((f=>f.callId===g));return C&&v.info("Call Registry already has an entry for this call"),C}async deleteCallAsync(g){return asap((()=>this.deleteCall(g)))}deleteCall(g){const f=this.calls.indexOf(g);return-1!==f&&(this.callSubscriptionsMap.get(g).forEach((g=>{g.dispose()})),this.callSubscriptionsMap.delete(g),this.calls.splice(f,1),this.event("callRemoved").raise(g),this.raiseChanged(),!0)}async setConfiguration(g){this.accountConfiguration=g,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(g)}updateDisplayName(g){return this.skypeIdentity.displayName=g,this.calls.forEach((f=>{f.updateDisplayName(g)})),Promise.resolve()}fireIntent(g,f){return Promise.resolve()}getCallState(g,f){return Promise.reject("Not implemented")}getSetup(){}getEcsConfig(){return Promise.reject()}updateSkypeToken(g){this.logger.debug("CallRegistry.updateSkypeToken() called but not supported in the current set up.")}updateToken(g,f,S,v,C){this.logger.info(`[updateToken], causeId = ${v} tokenType = ${f.tokenType}, factorsJson = ${g}, tokenExpiredTime = ${C}`);try{return this.signalingAgentProvider.getSignalingAgent().updateToken(g,f,S,v,C),Promise.resolve(getSuccessTransactionEnd())}catch(f){return this.logger.info(`Failed to update token with ${g}, error is ${f}`),Promise.reject(getRejectTransactionEnd(`Failed to update token with ${g}, error is ${f}`))}}onTokenRequired(g){const{requestMetadataJson:f,factorsJson:S,tokenType:v,invalidToken:C}=g;this.logger.info(`[onTokenRequired], tokenType ${v}, factorsJson ${S}, requestMetadataJson ${JSON.stringify(f)}`),this.event("tokenRequired").raise(S,v,f,C)}pushHandlingStarted(g){this.logger.info(`handleIncomingCallStarted, causeId=${g}`),this.event("pushHandlingStarted").raise(g)}pushHandlingEnded(g,f){this.logger.info(`pushHandlingEnded, causeId=${g}`),this.event("pushHandlingEnded").raise(g,f)}debugInformation(g){const f=g?`CallInformation\n * CallId=${g.callId}`:void 0;return Promise.resolve(f)}setLocationInfo(g,f,S=generateCauseId()){if(this.logger.info(`setLocationInfo, ${S}, infoType:${g}, contentJson ${f?"is set":"is undefined"}`),f)try{JSON.parse(f)}catch(g){return Promise.reject(`invalid contentJson: ${g}`)}return this.locationInfoType=g,1===this.locationInfoType&&(this.locationInfoContent=f,this.logger.info(`locationInfoContent set to ${this.locationInfoContent}`)),2===this.locationInfoType&&(this.networkInfoContent=f,this.logger.info(`networkInfoContent set to ${this.networkInfoContent}`)),3===this.locationInfoType&&(this.areaContent=f,this.logger.info(`areaContent set to ${this.areaContent}`)),this.event("locationInfoSet").raise(g,f),Promise.resolve()}createDownloader(){return null}async getUnassembledLocalRecordingSessions(g=generateCauseId()){return Promise.reject("Not implemented")}submitBrbReport(g,f){return Promise.reject("Not implemented")}extendBrbFeedback(g,f){return Promise.reject("Not implemented")}proxyPushNotification(g){this.logger.info(`Proxying push notification with event ID ${g.eventId}`);try{const f={eventId:g.eventId,payload:decodeNotificationPayload(g,this.logger)};this.event("proxiedPushNotification").raise(f)}catch(g){this.logger.error(`Error proxying push notification: ${g}`)}}logUploadNotification(g){this.logger.info(`Log upload notification with event ID ${g.eventId}`);try{const f={eventId:g.eventId,payload:decodeNotificationPayload(g,this.logger)};this.event("logUploadNotification").raise(f)}catch(g){this.logger.error(`Error raising log upload notification: ${g}`)}}sendPush(g,f,S,v){const C={id:g},_=[];return f.forEach((g=>{_.push({id:g})})),this.signalingAgentProvider.getSignalingAgent().sendPushAsync(C,_,S,v)}enableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!1}disableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!0}async enableWindowUninitEventHandlerAsync(){this.enableWindowUninitEventHandler()}async disableWindowUninitEventHandlerAsync(){this.disableWindowUninitEventHandler()}getCallUsingThreadIdMessageId(g,f,S,v){this.logger.info(`[getCallUsingThreadIdMessageId][${v}] threadID: ${getLoggableThreadId(g)} callId: ${f} messageId: ${S}`);let C=null;return g&&(C=this.calls.find((v=>v.threadId===g&&(f&&v.callId===f||null!=S&&v.messageId===S))),C)?(this.logger.logFailure(`[getCallUsingThreadIdMessageId][${v}]Call Registry already has an entry for threadId: ${getLoggableThreadId(C.threadId)}, callId: ${C.callId}, messageId: ${C.messageId}`),C):C}getCallUsingMeetingData(g,f,S,v,C,_=generateCauseId()){const T=this.logger.createFnLogger("getCallUsingMeetingData",_);if(T.info(`[callId=${f}][participantId=${scrubMriOrOmit(S)}] meetingData: ${!!g} \n            threadId: ${getLoggableThreadId(v)} messageId: ${C}`),!f)return T.logFailure("callId is undefined"),null;let I;for(const S of this.calls){if(S.callId===f){I=S;break}if(compareMeetingData(S.meetingData,g,_,this.logger)){I=S;break}}return I}stopCallsWithBeacon(){for(const g of this.calls)g.stopWithBeacon()}addCallSubscriptionToMap(g,f){this.callSubscriptionsMap.set(g,(this.callSubscriptionsMap.get(g)||[]).concat(f))}clearCallSubscription(){this.callSubscriptionsMap.forEach((g=>{g.forEach((g=>{g.dispose()}))})),this.callSubscriptionsMap.clear()}};function decodeNotificationPayload(g,f){const S=f.createFnLogger("decodeNotificationPayload");let v="{}";if(g?.body?.gp)S.info("using notification.body.gp"),v=decode(g.body.gp);else if(g?.body?.cp){S.info("using notification.body.cp");const f=atob(g.body.cp);v=co.inflate(f,{to:"string"})}return v}__decorateClass([callOperation("Initialize",{enableInstantTelemetry:!0})],po.prototype,"initialize",1),__decorateClass([callOperation("Logout",{enableInstantTelemetry:!0})],po.prototype,"logout",1);var mo=M,fo=class{constructor(g){this.deviceManager=g}get childDeviceManagers(){return this.deviceManager.getRegisteredDevices()}createPreview(g,f,S,v){return this.executeOnVirtualDeviceManager((v=>S(g,f,v,"Video")),v)}getRawDeviceMediaStream(g,f,S){return this.executeOnVirtualDeviceManager((S=>S.getRawDeviceMediaStream(g,f)),S)}setDeviceEffectsAsync(g,f){return this.executeOnVirtualDeviceManager((g=>g.setVideoEffects(f)),g)}setRawMediaStream(g,f,S){this.executeOnVirtualDeviceManager((S=>S.setRawMediaStream(g,f)),S)}unsetRawMediaStream(g,f){this.executeOnVirtualDeviceManager((f=>f.unsetRawMediaStream(g)),f)}getVirtualDevice(g){return this.childDeviceManagers.find((f=>f.id===g))}executeOnVirtualDeviceManager(g,f){return this.getVirtualDevice(f).getDeviceManagers().map((f=>g(f)))}},So="default_output_device",vo=class _DeviceManagerAdapter extends Ke{constructor(g){super(),this._deviceManager=g,this.virtualDeviceAdapter=new fo(this._deviceManager),g.on("onDevicesChanged",(g=>{const f=this._deviceManager.getDeviceDescriptions(g),S=this._mapDevices(f);this._raiseDevicesChanged(S)})),g.on("onSelectedDevicesChanged",(g=>this._raiseDevicesChanged())),g.on("onPermissionStateChanged",(()=>this.event("onPermissionStateChanged").raise())),g.on("onVideoEffectsEvent",((g,f)=>this.event("videoEffectsEvent").raise(g,f))),g.on("onVideoEffectApplied",(()=>this.event("videoEffectApplied").raise())),g.on("onEffectsError",((g,f,S)=>this.event("onEffectsError").raise(getSkypeMediaType(g),f,S)))}get isAudioOutputSelectionSupported(){return this._deviceManager.isAudioOutputSelectionSupported}getPermissionState(g){return"camera"===g?this.getPermissionStateHelper(this._deviceManager.getPermissionState("camera")):"microphone"===g?this.getPermissionStateHelper(this._deviceManager.getPermissionState("microphone")):"unknown"}async getPermissionStateAsync(g){return this.getPermissionState(g)}askDevicePermission(g){return this._deviceManager.askDevicePermission?this._deviceManager.askDevicePermission(g):Promise.resolve({audio:!0,video:!0})}enumerateDevicesAsync(){return this._deviceManager.enumerateDevicesAsync().then((g=>this._mapDevices(g)))}getPreferredCamera(){throw new Error("Not implemented")}selectDevices(g){if(Object.keys(g).some((g=>this.isVirtualDevice(g))))throw new Error("Virtual Device selection on DM is not supported");const f=(0,mo.assign)({},this._deviceManager.getSelectedDevices(),g);this._deviceManager.selectDevices(f)}selectDevicesAsync(g){return asap((()=>this.selectDevices(g)))}getSelectedDevices(){return this._deviceManager.getSelectedDevices()}getSelectedDevicesAsync(){return asap((()=>this.getSelectedDevices()))}getDeviceNameAsync(g){return this._deviceManager.getDeviceNameAsync(g)}getSpeakerDeviceDomIdAsync(g,f){return this._deviceManager.getSpeakerDeviceDomIdAsync(g)}mapBrowserDevices(g,f){return Promise.reject(new Error("Not implemented"))}async setDeviceEffectsAsync(g,f){if(!this.isVirtualDevice(g))return this._deviceManager.setVideoEffects(f);Promise.all(this.virtualDeviceAdapter.setDeviceEffectsAsync(g,f))}getDeviceEffectsCapabilityAsync(g,f){return this._deviceManager.effectsManager.getEffectsCapability("Video")}setBackgroundImageAsync(g,f,S){return this._deviceManager.effectsManager.configure("Video",{imagePath:f,headers:S})}getImagePropertyAsync(g){return Promise.reject(new Error("Not implemented"))}getMicrophoneGeometryArrayInfoAsync(g){return Promise.reject(new Error("Not implemented"))}transformImageAsync(g,f,S,v){return Promise.reject(new Error("Not implemented"))}setAudioProcessingFlags(g){return this._deviceManager.setAudioProcessingFlags(g)}async sendMessageDeviceVideoEffectsAsync(g,f){return await this._deviceManager.sendMessageDeviceVideoEffectsAsync(g,f)}sendMessageDeviceVideoExtensibilityAsync(g,f){return Promise.reject(new Error("Not implemented"))}setVideoCaptureConfigAsync(g,f){return Promise.reject(new Error("Not implemented"))}captureVideoFrameWithoutEffectsAsync(g,f,S){return Promise.reject(new Error("Not implemented"))}enableSignLanguageDetectionAsync(g,f){return Promise.reject(new Error("Not implemented"))}downloadAiModel(g,f){return Promise.reject(new Error("Not implemented"))}getSpeakerVolume(){return Promise.reject(new Error("Not implemented"))}getSpeakerSystemVolume(){return Promise.reject(new Error("Not implemented"))}setSpeakerVolume(g){return Promise.reject(new Error("Not implemented"))}setSpeakerSystemVolume(g){return Promise.reject(new Error("Not implemented"))}unmuteMicrophone(){return Promise.reject(new Error("Not implemented"))}unmuteSpeaker(){return Promise.reject(new Error("Not implemented"))}getNrgLevelsForDeviceTuner(g){return Promise.reject(new Error("Not implemented"))}async getNrgLevelPollerForDeviceTuner(g){return await this._deviceManager.getNrgLevelPollerForDeviceTuner()}setAudioEffectsAsync(g,f){return this._deviceManager.setAudioEffects(f)}getAudioFeatureCapability(g){return this._deviceManager.effectsManager.getEffectsCapability("Audio")}getAudioFeatureProviderName(){return Promise.resolve(this._deviceManager.effectsManager.getAudioEffectsProviderName())}getMicrophoneVolume(){return Promise.reject(new Error("Not implemented"))}setMicrophoneVolume(g){return Promise.reject(new Error("Not implemented"))}setDeviceTelemetryData(g,f,S,v=0){return Promise.reject(new Error("Not implemented"))}getSourceFormats(g){return Promise.reject(new Error("Not implemented"))}enableShellSharing(){return Promise.reject(new Error("Not implemented"))}disableShellSharing(){return Promise.reject(new Error("Not implemeted"))}enableParticipantCameras(){return Promise.reject(new Error("Not implemeted"))}registerDerivedSource(g,f){return Promise.reject(new Error("Not implemeted"))}unregisterDerivedSource(g){return Promise.reject(new Error("Not implemeted"))}async createPreview(g,f,S){if("camera"===f.kind&&this.isVirtualDevice(f.device))return this.virtualDeviceAdapter.createPreview(g,S,this.getRenderer,f.device)[0];if("sharing"===f.kind)return this.createScreenSharingPreviewRenderer(g,S);if("camera"!==f.kind||!(0,mo.isUndefined)(f.device))throw new Error("Not yet supported");return this.createPreviewRenderer(g,S)}async createPreviewRenderer(g,f){return this.getRenderer(g,f,this._deviceManager,"Video")}async createScreenSharingPreviewRenderer(g,f){return this.getRenderer(g,f,this._deviceManager,"ScreenShare")}getRawDeviceMediaStream(g,f,S){const v=getAgentMediaType(g);return this.isVirtualDevice(S)?this.virtualDeviceAdapter.getRawDeviceMediaStream(v,f,S)[0]:this._deviceManager.getRawDeviceMediaStream(v,f)}setRawMediaStream(g,f,S){const v=getAgentMediaType(f);return this.isVirtualDevice(S)?this.virtualDeviceAdapter.setRawMediaStream(g,v,S):this._deviceManager.setRawMediaStream(g,v)}unsetRawMediaStream(g,f){const S=getAgentMediaType(g);return this.isVirtualDevice(f)?this.virtualDeviceAdapter.unsetRawMediaStream(S,f):this._deviceManager.unsetRawMediaStream(S)}createAudioRenderer(){return this._deviceManager.createAudioRenderer()}startAudioLoopbackDevice(g){return Promise.reject(new Error("Not implemented"))}async dispose(g){return this._deviceManager.dispose(g)}async registerCompositeVideoDevice(g,f,S){return this._deviceManager.registerVirtualDevice(g,f,S)}async unregisterCompositeVideoDevice(g){return this._deviceManager.unregisterVirtualDevice(g)}async createAudioPlayer(){return Promise.reject(new Error("Not implemented"))}_raiseDevicesChanged(g){(g?Promise.resolve(g):this.enumerateDevicesAsync()).then((g=>{this.raiseChanged(),this.event("devicesChanged").raise(g)}))}getPermissionStateHelper(g){switch(g){case"granted":return"granted";case"denied":return"denied";case"prompt":return"prompt";default:return"unknown"}}_mapDevices(g){return g?.map((g=>this._mapDeviceDesc(g)))}_mapDeviceDesc(g){const f=_DeviceManagerAdapter._mapDeviceType(g.kind);return 6===f?{id:g.id,label:g.label,kind:f,position:0,defaultVideoId:g.id,devicesIds:[]}:1===f?{id:g.id,browserId:g.browserId,label:g.label,kind:f,position:_DeviceManagerAdapter._mapCameraPosition(g.position)}:4===f?{id:null,browserId:null,label:g.label,kind:f,formFactor:g.formFactor,isPcInternalDevice:g.isPcInternalDevice,microphoneId:g.microphoneId,speakerId:g.speakerId}:{id:g.id,browserId:g.browserId===So?"default":g.browserId,label:g.label,kind:f,isSystemDefault:!!g.isSystemDefault}}static _mapDeviceType(g){switch(g){case"camera":return 1;case"microphone":return 2;case"speaker":return 3;case"compositeAudio":return 4;case"virtualDevice":return 6;default:throw new Error(`Invalid device type '${g}'`)}}static _mapCameraPosition(g){switch(g){case"front":return 1;case"back":return 2;case"external":return 3;default:return 0}}isVirtualDevice(g){return g&&this._deviceManager.getRegisteredDevices().some((f=>f.id===g))}async getRenderer(g,f,S,v){const C=new Kr(g,S,v);try{await C.startVideoAsync(),f&&(C.setScalingMode(f.scalingMode),C.setVideoMirroring(!f.ignoreMirroring))}catch(g){throw C.dispose(),g}return C}},Co=R,yo=R,Eo=class extends yo.AbstractLogAppender{constructor(g){super(new yo.StandardLogFormatter(yo.SLF_Flags.Component)),this._logger=g}log(g,f,S,v){if(!this._logger)return;const C=g.level<=yo.LogLevel.Debug4?this._logger.debug:g.level<=yo.LogLevel.Debug2?this._logger.log:g.level<=yo.LogLevel.Debug1?this._logger.info:g.level<=yo.LogLevel.Warning?this._logger.warn:this._logger.error;C&&C.apply(this._logger,[this.formatter().format(g,f,S,v)])}},_o=R,To=__toESM2(Ae()),Io=["CorrelationId","agent_environment_id","UserInfo_TenantId","participant_id","endpoint_id","mediaLegId","metrics_ConfigIds","ts_calling_version","uiVersion"],bo={video:[...Io,"Extensions_WebRTCStats_ssrc_video_recv_framesDecoded","Extensions_WebRTCStats_ssrc_video_recv_packetsReceived","Extensions_WebRTCStats_ssrc_video_recv_ssrc","Extensions_WebRTCStats_ssrc_video_recv_bytesReceived","Extensions_WebRTCStats_ssrc_video_recv_googFrameRateDecoded","Extensions_Video_SubscriptionEvents","Extensions_Video_recv_ResolutionDurations","Extensions_Video_recv_StreamsMax","Extensions_Video_recv_frameRateAvg","Extensions_Video_recv_DurationSeconds","Extensions_Video_recv_FreezeHistogram","Extensions_Video_recv_FreezeTimestamps","Extensions_WebRTCStats_ssrc_video_recv_keyFramesDecoded","Extensions_Video_recv_TotalFreezeDurationMs","Extensions_Video_recv_packetsLostRateMax","metrics_ReconnectAttempts","metrics_ReconnectConnectedCount","metrics_RetargetCompletedCount","metrics_UFDs","Payload"],sharing:[...Io,"Extensions_WebRTCStats_ssrc_sharing_recv_framesDecoded","Extensions_WebRTCStats_ssrc_sharing_recv_packetsReceived","Extensions_WebRTCStats_ssrc_sharing_recv_ssrc","Extensions_WebRTCStats_ssrc_sharing_recv_bytesReceived","Extensions_WebRTCStats_ssrc_sharing_recv_googFrameRateDecoded","Extensions_WebRTCStats_ssrc_sharing_recv_keyFramesDecoded","Extensions_Sharing_SubscriptionEvents","Extensions_Sharing_recv_ResolutionDurations","Extensions_Sharing_recv_StreamsMax","Extensions_Sharing_recv_frameRateAvg","Extensions_Sharing_recv_DurationSeconds","Extensions_Sharing_recv_FreezeHistogram","Extensions_Sharing_recv_FreezeTimestamps","Extensions_Sharing_recv_TotalFreezeDurationMs","Extensions_Sharing_recv_packetsLostRateMax","metrics_ReconnectAttempts","metrics_ReconnectConnectedCount","metrics_RetargetCompletedCount","metrics_UFDs","Payload"]},Ao=class extends Ke{constructor(){super(...arguments),this.stabilizationTimeInAvg=2e4}send(g){g&&setTimeout((()=>{this.event("sendMidCallTelemetry").raise(bo[g])}),this.stabilizationTimeInAvg)}},Po=class extends Ke{constructor(g,f){super(),this._telemetryService=g,this._ecsProvider=f,this._ecsProvider.on("OnECSChanged",(()=>_o.RootToolsManager.OnEcsChange()))}fetchEcsConfig(g,f){return To.Resolved().then((()=>this._ecsProvider.getEcsConfig(g,f)))}sendTelemetry(g,f){this._telemetryService.getGenericTelemetryLogger&&g?this._telemetryService.getGenericTelemetryLogger(g).sendEvent({eventName:"rt_log",props:f}):this._telemetryService.sendEvents([{eventName:"rt_log",props:f}])}sendMidCallTelemetry(g){Object.keys(bo).includes(g)&&this.event("onMidCallTelemetry").raise(g)}};function initLogger(g,f,S){if(!Co.RootToolsManager.isDelegateSet()){const v=new Po(g.telemetryService,f);if(Co.RootToolsManager.setDelegate(v),v.on("onMidCallTelemetry",(g=>S.send(g))),g.logger){const f=new Eo(g.logger);Co.LogFactory.instance().addAppender(f)}}g.logger=new Fe("JS.TsCalling.Pluginless",!0),g.mediaAgentFactoryConfig.logger=new Fe("JS.TsCalling.MediaAgentUnsafe",!1),g.mediaAgentFactoryConfig.safeLogger=new Fe("JS.TsCalling.MediaAgent",!0),g.signalingAgentConfig.logger=new Fe("JS.TsCalling.SignalingAgent",!0)}var Ro=M,Mo=class _NoopLogger{constructor(g){this._prefix=g,this._children=[],this._useConsoleLogger=!1,this.createChild=(g,f)=>{const S="function"==typeof g?"":g,v=new _NoopLogger((this._prefix||"")+S);return this._children.push(v),this._useConsoleLogger&&v.useConsoleLogger(),v},this.createFnLogger=(g,f,...S)=>{const v=`[${f}][${g}]`,C=new _NoopLogger((this._prefix||"")+v);return this._children.push(C),this._useConsoleLogger&&C.useConsoleLogger(),C}}logInfo(){}logFailure(){}logSuccess(){}log(...g){}debug(...g){}info(...g){}warn(...g){}error(...g){}useConsoleLogger(){this._useConsoleLogger=!0;const logWithConsole=(...g)=>{console.info(this._prefix||"",...g)};this.log=logWithConsole,this.debug=logWithConsole,this.info=logWithConsole,this.warn=logWithConsole,this.error=logWithConsole,(0,Ro.each)(this._children,(g=>g.useConsoleLogger()))}},wo=class{constructor(g){this.configProvider=g,this.window=Xs.window,this.updateCapabilityOverrides(),this.configProviderSub=g.on("configUpdated",(()=>this.updateCapabilityOverrides()))}get audio(){return this.getCapability("audio")}get video(){return this.getCapability("video")}get screensharing(){return this.getCapability("screensharing")}get retargeting(){return this.getCapability("retargeting")}dispose(){this.configProviderSub&&this.configProviderSub.dispose()}updateCapabilityOverrides(){let g;this.configProvider.config.capabilities&&(g=this.configProvider.config.capabilities),this.overrides=g||{}}hasMediaCapture(){return!!this.window.navigator.getUserMedia}getCapability(g){return void 0!==this.overrides[g]?!!this.overrides[g]:this.hasMediaCapture()&&this.hasWebRtc()}hasWebRtc(){return void 0!==this.window.RTCPeerConnection}},Oo=class _UFDManager2 extends Ht{constructor(g,f){super(g),this.logger=g,this.configProvider=f,this.eventStates=new Map,this.debounceMap=new Map,this.logger.safe.info("Initialized")}signalEvent(g,f,S="Audio",v=!0,C=generateCauseId(),_,T){const I={type:g,value:f,isLocalSource:v,mediaType:S,deviceManagerId:_,diagnosticData:T},b=this.getEventKey(I),A=this.eventStates.get(b);if(this.configProvider.config.localUFDDebounceTime&&A){clearTimeout(this.debounceMap.get(b));const g=setTimeout(this.raiseEvent.bind(this),this.configProvider.config.localUFDDebounceTime,I,C);this.debounceMap.set(b,g)}else this.raiseEvent(I,C)}raiseEvent(g,f){const S=this.getEventKey(g);this.shouldRaiseEvent(g)&&(this.eventStates.set(S,g),this.logger.safe.info(`[${f}] Raising UFD ${g.type} for ${g.mediaType}: ${g.value}`),this.event("onQualityChanged").raise(g))}signalDeviceEvent(g,f,S,v){const C=_UFDManager2.getQualityEventType(g,S,this.configProvider);C?this.signalEvent(C,f,S,void 0,generateCauseId(),v):this.logger.warn(`Unknown device quality event type: ${g}`)}raisePendingWhitelistingUFD(){this.lastWhitelistingUFD&&(this.logger.safe.debug(`Raising whitelisting UFD ${this.lastWhitelistingUFD.type}: ${this.lastWhitelistingUFD.value}`),this.event("onQualityChanged").raise(this.lastWhitelistingUFD),this.cancelPendingWhitelistingUFD())}cancelPendingWhitelistingUFD(){if(this.lastWhitelistingUFD){const g=this.getEventKey(this.lastWhitelistingUFD);this.eventStates.delete(g)}this.lastWhitelistingUFD=void 0}applyCurrentState(g){this.cancelPendingWhitelistingUFD();let f=0;for(const S of this.eventStates.values())"Good"!==S.value&&(g(S),f++);f>0&&this.logger.safe.info(`Applied ${f} UFDs`)}reset(){this.logger.safe.info("Resetting UFD states");for(const[g,f]of this.eventStates.entries())_UFDManager2.persistent.has(f.type)||this.eventStates.delete(g);this.lastWhitelistingUFD=void 0}getEventKey(g){return`${g.type}:${g.mediaType}`}shouldRaiseEvent(g){const f=this.getEventKey(g),S=this.eventStates.get(f);return S&&S.value===g.value?!(!this.configProvider.config.alwaysRaiseBadDeviceEvents||!_UFDManager2.deviceQualityEvents.has(g.type)||"Good"===g.value):!(!S&&"Good"===g.value||("NetworkRelaysNotReachable"===g.type?(this.lastWhitelistingUFD=g,1):"NetworkRecvQuality"===g.type&&!this.configProvider.config.webrtcStatNetworkDetectionEnabled))}static getQualityEventType(g,f,S){switch(g){case 0:return"Audio"===f?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartFailed";case 1:return"DeviceRenderNotFunctioning";case 2:return"Audio"===f?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartTimedOut";case 3:return"DeviceCaptureMute";case 4:switch(f){case"ScreenShare":return"ScreenshareRecordingDisabled";case"Audio":return S.config.enableSignalingAudioPermissionDeniedUFD?"AudioCapturePermissionDenied":"DeviceCaptureNotMuteButSilent";case"Video":return"VideoCapturePermissionDenied";default:return}default:return}}};Oo.persistent=new Set(["ZeroCaptureDevicesEnumerated","ZeroRenderDevicesEnumerated"]),Oo.deviceQualityEvents=new Set(["DeviceCaptureNotFunctioning","VideoCapturerDeviceStartFailed","VideoCapturerDeviceStartTimedOut","DeviceCaptureMute","ScreenshareRecordingDisabled","DeviceCaptureNotMuteButSilent","VideoCapturePermissionDenied"]);var Do=Oo,No=M,ko="function",Lo="object",Fo="undefined",xo="prototype",Uo=Object,Vo=Uo[xo];function _pureAssign2(g,f){return g||f}function _pureRef2(g,f){return g[f]}var Bo,Ho=void 0,$o=null,jo="",Go="function",qo="object",Wo="prototype",zo="__proto__",Ko="undefined",Jo="constructor",Yo="Symbol",Qo="_polyfill",Xo="length",Zo="name",el="call",tl="toString",il=_pureAssign2(Object),nl=_pureRef2(il,Wo),rl=_pureAssign2(String),sl=_pureRef2(rl,Wo),al=_pureAssign2(Math),ol=_pureAssign2(Array),ll=_pureRef2(ol,Wo),cl=_pureRef2(ll,"slice");function safe2(g,f){try{return{v:g.apply(this,f)}}catch(g){return{e:g}}}function safeGet2(g,f){var S=safe2(g);return S.e?f:S.v}function _createIs2(g){return function(f){return typeof f===g}}function _createObjIs2(g){var f="[object "+g+"]";return function(g){return!(!g||objToString2(g)!==f)}}function objToString2(g){return nl[tl].call(g)}function isUndefined4(g){return typeof g===Ko||g===Ko}function isNullOrUndefined2(g){return g===$o||isUndefined4(g)}function isStrictNullOrUndefined2(g){return g===$o||!isDefined22(g)}function isDefined22(g){return!!g||g!==Ho}function isPrimitive2(g){return g===$o||isPrimitiveType2(typeof g)}function isPrimitiveType2(g){return!Bo&&(Bo=["string","number","boolean",Ko,"symbol","bigint"]),g!==qo&&-1!==Bo.indexOf(g)}var dl=_createIs2("string"),hl=_createIs2(Go);function isObject3(g){return!(!g&&isNullOrUndefined2(g)||!g||typeof g!==qo)}var ul=_pureRef2(ol,"isArray"),gl=_createObjIs2("Date"),pl=_createIs2("number"),ml=_createIs2("boolean"),fl=_createObjIs2("Error");function isPromiseLike22(g){return!!(g&&g.then&&hl(g.then))}function isTruthy2(g){return!(!g||safeGet2((function(){return!(g&&0+g)}),!g))}var Sl=_pureRef2(il,"getOwnPropertyDescriptor");function objHasOwnProperty2(g,f){return!!g&&nl.hasOwnProperty[el](g,f)}var vl=_pureAssign2(_pureRef2(il,"hasOwn"),polyObjHasOwn2);function polyObjHasOwn2(g,f){return objHasOwnProperty2(g,f)||!!Sl(g,f)}function objForEachKey2(g,f,S){if(g&&isObject3(g))for(var v in g)if(vl(g,v)&&-1===f[el](S||g,v,g[v]))break}var Cl={e:"enumerable",c:"configurable",v:"value",w:"writable",g:"get",s:"set"};function _createProp2(g){var f={};if(f[Cl.c]=!0,f[Cl.e]=!0,g.l){f.get=function(){return g.l.v};var S=Sl(g.l,"v");S&&S.set&&(f.set=function(f){g.l.v=f})}return objForEachKey2(g,(function(g,S){f[Cl[g]]=isUndefined4(S)?f[Cl[g]]:S})),f}var yl=_pureRef2(il,"defineProperty"),El=_pureRef2(il,"defineProperties");function objDefine2(g,f,S){return yl(g,f,_createProp2(S))}function objDefineProps2(g,f){var S={};return objForEachKey2(f,(function(g,f){S[g]=_createProp2(f)})),El(g,S)}function _createKeyValueMap2(g,f,S,v,C){var _={};return objForEachKey2(g,(function(g,v){_assignMapValue2(_,g,f?v:g,C),_assignMapValue2(_,v,S?v:g,C)})),v?v(_):_}function _assignMapValue2(g,f,S,v){yl(g,f,{value:S,enumerable:!0,writable:!!v})}var _l=_pureAssign2(rl),Tl="[object Error]";function dumpObj2(g,f){var S=jo,v=nl[tl][el](g);v===Tl&&(g={stack:_l(g.stack),message:_l(g.message),name:_l(g.name)});try{S=(S=JSON.stringify(g,$o,f?"number"==typeof f?f:4:Ho))&&S.replace(/"(\w+)"\s*:\s{0,1}/g,"$1: ")||_l(g)}catch(g){S=" - "+dumpObj2(g,f)}return v+": "+S}function throwError2(g){throw new Error(g)}function throwTypeError2(g){throw new TypeError(g)}var Il=_pureRef2(il,"freeze");function _doNothing2(g){return g}function _getProto2(g){return g[zo]||$o}var bl=_pureRef2(il,"assign"),Al=_pureRef2(il,"keys");function objDeepFreeze2(g){return Il&&objForEachKey2(g,(function(g,f){(ul(f)||isObject3(f))&&objDeepFreeze2(f)})),Pl(g)}var Pl=_pureAssign2(Il,_doNothing2),Rl=_pureAssign2(_pureRef2(il,"getPrototypeOf"),_getProto2);function createEnum2(g){return _createKeyValueMap2(g,1,0,Pl)}function createEnumKeyMap2(g){return _createKeyValueMap2(g,0,0,Pl)}function createSimpleMap2(g){var f={};return objForEachKey2(g,(function(g,S){_assignMapValue2(f,g,S[1]),_assignMapValue2(f,S[0],S[1])})),Pl(f)}function createTypeMap2(g){return createSimpleMap2(g)}var Ml,wl=createEnumKeyMap2({asyncIterator:0,hasInstance:1,isConcatSpreadable:2,iterator:3,match:4,matchAll:5,replace:6,search:7,species:8,split:9,toPrimitive:10,toStringTag:11,unscopables:12}),Ol="__tsUtils$gblCfg";function _getGlobalValue2(){var g;return typeof globalThis!==Ko&&(g=globalThis),g||typeof self===Ko||(g=self),g||typeof window===Ko||(g=window),g||typeof C===Ko||(g=C),g}function _getGlobalConfig2(){if(!Ml){var g=safe2(_getGlobalValue2).v||{};Ml=g[Ol]=g[Ol]||{}}return Ml}var Dl=_unwrapFunctionWithPoly2;function _unwrapFunctionWithPoly2(g,f,S){var v=f&&f[g];return function(f){var C=f&&f[g]||v;if(C||S){var _=arguments;return(C||S).apply(f,C?cl[el](_,1):_)}throwTypeError2('"'+_l(g)+'" not defined for '+dumpObj2(f))}}function _unwrapProp2(g){return function(f){return f[g]}}var Nl=_pureRef2(al,"max"),kl=Dl("slice",sl),Ll=Dl("substring",sl),Fl=_unwrapFunctionWithPoly2("substr",sl,polyStrSubstr2);function polyStrSubstr2(g,f,S){return isNullOrUndefined2(g)&&throwTypeError2("Invalid "+dumpObj2(g)),S<0?jo:((f=f||0)<0&&(f=Nl(f+g[Xo],0)),isUndefined4(S)?kl(g,f):kl(g,f,f+S))}function strLeft2(g,f){return Ll(g,0,f)}var xl,Ul,Vl,Bl="_urid";function _globalSymbolRegistry2(){if(!xl){var g=_getGlobalConfig2();xl=g.gblSym=g.gblSym||{k:{},s:{}}}return xl}function polyNewSymbol2(g){var f={description:_l(g),toString:function(){return Yo+"("+g+")"}};return f[Qo]=!0,f}function polySymbolFor2(g){var f=_globalSymbolRegistry2();if(!vl(f.k,g)){var S=polyNewSymbol2(g),v=Al(f.s).length;S[Bl]=function(){return v+"_"+S[tl]()},f.k[g]=S,f.s[S[Bl]()]=_l(g)}return f.k[g]}function polyGetKnownSymbol2(g){var f;!Ul&&(Ul={});var S=wl[g];return S&&(f=Ul[S]=Ul[S]||polyNewSymbol2(Yo+"."+S)),f}function _initTestHooks2(){Vl=_getGlobalConfig2()}function getLazy2(g){var f={};return!Vl&&_initTestHooks2(),f.b=Vl.lzy,yl(f,"v",{configurable:!0,get:function(){var S=g();return Vl.lzy||yl(f,"v",{value:S}),f.b=Vl.lzy,S}}),f}function createCachedValue2(g){return yl({toJSON:function(){return g}},"v",{value:g})}var Hl,$l="window";function _getGlobalInstFn2(g,f){var S;return function(){return!Vl&&_initTestHooks2(),(!S||Vl.lzy)&&(S=createCachedValue2(safe2(g,f).v)),S.v}}function getGlobal2(g){return!Vl&&_initTestHooks2(),(!Hl||!1===g||Vl.lzy)&&(Hl=createCachedValue2(safe2(_getGlobalValue2).v||$o)),Hl.v}function getInst2(g,f){var S=Hl&&!1!==f?Hl.v:getGlobal2(f);return S&&S[g]?S[g]:g===$l?Gl():$o}function hasDocument2(){return!!jl()}var jl=_getGlobalInstFn2(getInst2,["document"]);function hasWindow2(){return!!Gl()}var Gl=_getGlobalInstFn2(getInst2,[$l]);function hasNavigator2(){return!!Kl()}var ql,Wl,zl,Kl=_getGlobalInstFn2(getInst2,["navigator"]),Jl=_getGlobalInstFn2((function(){return!!safe2((function(){return process&&(process.versions||{}).node})).v}));function _initSymbol2(){return ql=createCachedValue2(safe2(getInst2,[Yo]).v)}function _getSymbolKey2(g){var f=(Vl.lzy?0:ql)||_initSymbol2();return f.v?f.v[g]:Ho}function hasSymbol2(){return!!getSymbol2()}function getSymbol2(){return!Vl&&_initTestHooks2(),((Vl.lzy?0:ql)||_initSymbol2()).v}function getKnownSymbol2(g,f){var S=wl[g];!Vl&&_initTestHooks2();var v=(Vl.lzy?0:ql)||_initSymbol2();return v.v?v.v[S||g]:f?Ho:polyGetKnownSymbol2(g)}function newSymbol2(g,f){!Vl&&_initTestHooks2();var S=(Vl.lzy?0:ql)||_initSymbol2();return S.v?S.v(g):f?$o:polyNewSymbol2(g)}function symbolFor2(g){return!Vl&&_initTestHooks2(),((Wl=(Vl.lzy?0:Wl)||createCachedValue2(safe2(_getSymbolKey2,["for"]).v)).v||polySymbolFor2)(g)}function isIterator2(g){return!!g&&hl(g.next)}function isIterable2(g){return!isStrictNullOrUndefined2(g)&&hl(g[getKnownSymbol2(3)])}function iterForOf2(g,f,S){if(g&&(isIterator2(g)||(!zl&&(zl=createCachedValue2(getKnownSymbol2(3))),g=g[zl.v]?g[zl.v]():null),isIterator2(g))){var v=Ho,C=Ho;try{for(var _=0;!(C=g.next()).done&&-1!==f[el](S||g,C.value,_,g);)_++}catch(f){v={e:f},g.throw&&(C=$o,g.throw(v))}finally{try{C&&!C.done&&g.return&&g.return(C)}finally{if(v)throw v.e}}}}function fnApply2(g,f,S){return g.apply(f,S)}function arrAppend2(g,f){return!isUndefined4(f)&&g&&(ul(f)?fnApply2(g.push,g,f):isIterator2(f)||isIterable2(f)?iterForOf2(f,(function(f){g.push(f)})):g.push(f)),g}function arrForEach2(g,f,S){if(g)for(var v=g[Xo]>>>0,C=0;C<v&&(!(C in g)||-1!==f[el](S||g,g[C],C,g));C++);}var Yl=Dl("indexOf",ll);function arrSlice2(g,f,S){return(g&&g.slice||cl).apply(g,cl[el](arguments,1))}function polyArrIncludes2(g,f,S){return-1!==Yl(g,f,S)}var Ql,Xl=_unwrapFunctionWithPoly2("includes",ll,polyArrIncludes2),Zl=_pureAssign2(_pureRef2(il,"create"),polyObjCreate2);function polyObjCreate2(g){if(!g)return{};var f=typeof g;function tempFunc(){}return f!==qo&&f!==Go&&throwTypeError2("Prototype must be an Object or function: "+dumpObj2(g)),tempFunc[Wo]=g,new tempFunc}function objSetPrototypeOf2(g,f){return(il.setPrototypeOf||function(g,f){var S;!Ql&&(Ql=createCachedValue2(((S={})[zo]=[],S instanceof Array))),Ql.v?g[zo]=f:objForEachKey2(f,(function(f,S){return g[f]=S}))})(g,f)}function _createCustomError2(g,f,S){function __(){this[Jo]=f,safe2(objDefine2,[this,Zo,{v:g,c:!0,e:!1}])}return safe2(objDefine2,[f,Zo,{v:g,c:!0,e:!1}]),(f=objSetPrototypeOf2(f,S))[Wo]=S===$o?Zl(S):(__[Wo]=S[Wo],new __),f}function _setName2(g,f){f&&(g[Zo]=f)}function createCustomError2(g,f,S){var v=S||Error,C=v[Wo][Zo],_=Error.captureStackTrace;return _createCustomError2(g,(function(){var S=this,T=arguments;try{safe2(_setName2,[v,g]);var I=fnApply2(v,S,cl[el](T))||S;if(I!==S){var b=Rl(S);b!==Rl(I)&&objSetPrototypeOf2(I,b)}return _&&_(I,S[Jo]),f&&f(I,T),I}finally{safe2(_setName2,[v,C])}}),v)}function utcNow2(){return(Date.now||polyUtcNow2)()}function polyUtcNow2(){return(new Date).getTime()}function _createTrimFn2(g){return function _doTrim(f){return isNullOrUndefined2(f)&&throwTypeError2("strTrim called ["+dumpObj2(f)+"]"),f&&f.replace&&(f=f.replace(g,jo)),f}}var ec,tc,ic,nc=_unwrapFunctionWithPoly2("trim",sl,_createTrimFn2(/^\s+|(?=\s)\s+$/g));function isPlainObject2(g){if(!g||typeof g!==qo)return!1;ic||(ic=!hasWindow2()||Gl());var f=!1;if(g!==ic){tc||(ec=Function[Wo][tl],tc=ec[el](il));try{var S=Rl(g);(f=!S)||(objHasOwnProperty2(S,Jo)&&(S=S[Jo]),f=S&&typeof S===Go&&ec[el](S)===tc)}catch(g){}}return f}function _defaultDeepCopyHandler2(g){return g.value&&plainObjDeepCopyHandler2(g),!0}var rc=[arrayDeepCopyHandler2,plainObjDeepCopyHandler2,functionDeepCopyHandler2,dateDeepCopyHandler2];function _getSetVisited2(g,f,S,v){var C;return arrForEach2(g,(function(g){if(g.k===f)return C=g,-1})),C||(C={k:f,v:f},g.push(C),v(C)),C.v}function _deepCopy2(g,f,S,v){var C=S.handler,_=S.path?v?S.path.concat(v):S.path:[],T={handler:S.handler,src:S.src,path:_},I=typeof f,b=!1,A=!1;f&&I===qo?b=isPlainObject2(f):A=f===$o||isPrimitiveType2(I);var P={type:I,isPrim:A,isPlain:b,value:f,result:f,path:_,origin:S.src,copy:function(f,v){return _deepCopy2(g,f,v?T:S,v)},copyTo:function(f,S){return _copyProps2(g,f,S,T)}};return P.isPrim?C&&C[el](S,P)?P.result:f:_getSetVisited2(g,f,_,(function(g){objDefine2(P,"result",{g:function(){return g.v},s:function(f){g.v=f}});for(var f=0,v=C;!(v||(f<rc.length?rc[f++]:_defaultDeepCopyHandler2))[el](S,P);)v=$o}))}function _copyProps2(g,f,S,v){if(!isNullOrUndefined2(S))for(var C in S)f[C]=_deepCopy2(g,S[C],v,C);return f}function objCopyProps2(g,f,S){return _copyProps2([],g,f,{handler:S,src:f,path:[]})}function objDeepCopy2(g,f){return _deepCopy2([],g,{handler:f,src:g})}function arrayDeepCopyHandler2(g){var f=g.value;if(ul(f)){var S=g.result=[];return S.length=f.length,g.copyTo(S,f),!0}return!1}function dateDeepCopyHandler2(g){var f=g.value;return!!gl(f)&&(g.result=new Date(f.getTime()),!0)}function functionDeepCopyHandler2(g){return g.type===Go}function plainObjDeepCopyHandler2(g){var f=g.value;if(f&&g.isPlain){var S=g.result={};return g.copyTo(S,f),!0}return!1}function _doExtend2(g,f){return arrForEach2(f,(function(f){objCopyProps2(g,f)})),g}function deepExtend2(g,f,S,v,C,_,T){return _doExtend2(objDeepCopy2(g)||{},cl[el](arguments))}var sc=_unwrapProp2(Xo);function perfNow2(){return utcNow2()}var ac=_unwrapFunctionWithPoly2("endsWith",sl,polyStrEndsWith2);function polyStrEndsWith2(g,f,S){dl(g)||throwTypeError2("'"+dumpObj2(g)+"' is not a string");var v=dl(f)?f:_l(f),C=!isUndefined4(S)&&S<g[Xo]?S:g[Xo];return Ll(g,C-v[Xo],C)===v}var oc=Dl("indexOf",sl),lc=_unwrapFunctionWithPoly2("startsWith",sl,polyStrStartsWith2);function polyStrStartsWith2(g,f,S){dl(g)||throwTypeError2("'"+dumpObj2(g)+"' is not a string");var v=dl(f)?f:_l(f),C=S>0?S:0;return Ll(g,C,C+v[Xo])===v}var cc="ref",dc="unref",hc="hasRef",uc="enabled";function _createTimerHandler2(g,f,S){var v,C=!0,_=g?f($o):$o;function _unref(){return C=!1,_&&_[dc]&&_[dc](),v}function _cancel(){_&&S(_),_=$o}function _refresh(){return _=f(_),C||_unref(),v}function _setEnabled(g){!g&&_&&_cancel(),g&&!_&&_refresh()}return(v={cancel:_cancel,refresh:_refresh})[hc]=function(){return _&&_[hc]?_[hc]():C},v[cc]=function(){return C=!0,_&&_[cc]&&_[cc](),v},v[dc]=_unref,{h:v=yl(v,uc,{get:function(){return!!_},set:_setEnabled}),dn:function(){_=$o}}}function _createTimeoutWith2(g,f,S){var v=ul(f),C=v?f.length:0,_=(C>0?f[0]:v?Ho:f)||setTimeout,T=(C>1?f[1]:Ho)||clearTimeout,I=S[0];S[0]=function(){b.dn(),fnApply2(I,Ho,cl[el](arguments))};var b=_createTimerHandler2(g,(function(g){if(g){if(g.refresh)return g.refresh(),g;fnApply2(T,Ho,[g])}return fnApply2(_,Ho,S)}),(function(g){fnApply2(T,Ho,[g])}));return b.h}function scheduleTimeout2(g,f){return _createTimeoutWith2(!0,Ho,cl[el](arguments))}function scheduleTimeoutWith2(g,f,S){return _createTimeoutWith2(!0,g,cl[el](arguments,1))}function createTimeout2(g,f){return _createTimeoutWith2(!1,Ho,cl[el](arguments))}(getGlobal2()||{}).Symbol,(getGlobal2()||{}).Reflect;var gc,pc="hasOwnProperty",extendStaticsFn2=function(g,f){return(extendStaticsFn2=Uo.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f[pc](S)&&(g[S]=f[S])})(g,f)};function __extendsFn2(g,f){function __(){this.constructor=g}typeof f!==ko&&null!==f&&throwTypeError2("Class extends value "+String(f)+" is not a constructor or null"),extendStaticsFn2(g,f),g[xo]=null===f?Zl(f):(__[xo]=f[xo],new __)}function __spreadArrayFn2(g,f){for(var S=0,v=f.length,C=g.length;S<v;S++,C++)g[C]=f[S];return g}var mc="constructor",fc="prototype",Sc="function",vc="_dynInstFuncs",Cc="_isDynProxy",yc="_dynClass",Ec="_dynCls$",_c="_dynInstChk",Tc=_c,Ic="_dfOpts",bc="_unknown_",Ac="__proto__",Pc="_dyn"+Ac,Rc="__dynProto$Gbl",Mc="_dynInstProto",wc="useBaseInst",Oc="setInstFuncs",Dc=Object,Nc=Dc.getPrototypeOf,kc=Dc.getOwnPropertyNames,Lc=getGlobal2(),Fc=Lc[Rc]||(Lc[Rc]={o:(gc={},gc[Oc]=!0,gc[wc]=!0,gc),n:1e3});function _isObjectOrArrayPrototype2(g){return g&&(g===Dc[fc]||g===Array[fc])}function _isObjectArrayOrFunctionPrototype2(g){return _isObjectOrArrayPrototype2(g)||g===Function[fc]}function _getObjProto3(g){var f;if(g){if(Nc)return Nc(g);var S=g[Ac]||g[fc]||(g[mc]?g[mc][fc]:null);f=g[Pc]||S,objHasOwnProperty2(g,Pc)||(delete g[Mc],f=g[Pc]=g[Mc]||g[Pc],g[Mc]=S)}return f}function _forEachProp2(g,f){var S=[];if(kc)S=kc(g);else for(var v in g)"string"==typeof v&&objHasOwnProperty2(g,v)&&S.push(v);if(S&&S.length>0)for(var C=0;C<S.length;C++)f(S[C])}function _isDynamicCandidate2(g,f,S){return f!==mc&&typeof g[f]===Sc&&(S||objHasOwnProperty2(g,f))&&f!==Ac&&f!==fc}function _throwTypeError2(g){throwTypeError2("DynamicProto: "+g)}function _getInstanceFuncs2(g){var f=Zl(null);return _forEachProp2(g,(function(S){!f[S]&&_isDynamicCandidate2(g,S,!1)&&(f[S]=g[S])})),f}function _hasVisited2(g,f){for(var S=g.length-1;S>=0;S--)if(g[S]===f)return!0;return!1}function _getBaseFuncs2(g,f,S,v){function _instFuncProxy(g,f,S){var C=f[S];if(C[Cc]&&v){var _=g[vc]||{};!1!==_[Tc]&&(C=(_[f[yc]]||{})[S]||C)}return function(){return C.apply(g,arguments)}}var C=Zl(null);_forEachProp2(S,(function(g){C[g]=_instFuncProxy(f,S,g)}));for(var _=_getObjProto3(g),T=[];_&&!_isObjectArrayOrFunctionPrototype2(_)&&!_hasVisited2(T,_);)_forEachProp2(_,(function(g){!C[g]&&_isDynamicCandidate2(_,g,!Nc)&&(C[g]=_instFuncProxy(f,_,g))})),T.push(_),_=_getObjProto3(_);return C}function _getInstFunc2(g,f,S,v){var C=null;if(g&&objHasOwnProperty2(S,yc)){var _=g[vc]||Zl(null);if((C=(_[S[yc]]||Zl(null))[f])||_throwTypeError2("Missing ["+f+"] "+Sc),!C[_c]&&!1!==_[Tc]){for(var T=!objHasOwnProperty2(g,f),I=_getObjProto3(g),b=[];T&&I&&!_isObjectArrayOrFunctionPrototype2(I)&&!_hasVisited2(b,I);){var A=I[f];if(A){T=A===v;break}b.push(I),I=_getObjProto3(I)}try{T&&(g[f]=C),C[_c]=1}catch(g){_[Tc]=!1}}}return C}function _getProtoFunc2(g,f,S){var v=f[g];return v===S&&(v=_getObjProto3(f)[g]),typeof v!==Sc&&_throwTypeError2("["+g+"] is not a "+Sc),v}function _populatePrototype2(g,f,S,v,C){function _createDynamicPrototype(g,f){var dynProtoProxy=function(){return(_getInstFunc2(this,f,g,dynProtoProxy)||_getProtoFunc2(f,g,dynProtoProxy)).apply(this,arguments)};return dynProtoProxy[Cc]=1,dynProtoProxy}if(!_isObjectOrArrayPrototype2(g)){var _=S[vc]=S[vc]||Zl(null);if(!_isObjectOrArrayPrototype2(_)){var T=_[f]=_[f]||Zl(null);!1!==_[Tc]&&(_[Tc]=!!C),_isObjectOrArrayPrototype2(T)||_forEachProp2(S,(function(f){_isDynamicCandidate2(S,f,!1)&&S[f]!==v[f]&&(T[f]=S[f],delete S[f],(!objHasOwnProperty2(g,f)||g[f]&&!g[f][Cc])&&(g[f]=_createDynamicPrototype(g,f)))}))}}}function _checkPrototype2(g,f){if(Nc){for(var S=[],v=_getObjProto3(f);v&&!_isObjectArrayOrFunctionPrototype2(v)&&!_hasVisited2(S,v);){if(v===g)return!0;S.push(v),v=_getObjProto3(v)}return!1}return!0}function _getObjName2(g,f){return objHasOwnProperty2(g,fc)?g.name||f||bc:((g||{})[mc]||{}).name||f||bc}function dynamicProto2(g,f,S,v){objHasOwnProperty2(g,fc)||_throwTypeError2("theClass is an invalid class definition.");var C=g[fc];_checkPrototype2(C,f)||_throwTypeError2("["+_getObjName2(g)+"] not in hierarchy of ["+_getObjName2(f)+"]");var _=null;objHasOwnProperty2(C,yc)?_=C[yc]:(_=Ec+_getObjName2(g,"_")+"$"+Fc.n,Fc.n++,C[yc]=_);var T=dynamicProto2[Ic],I=!!T[wc];I&&v&&void 0!==v[wc]&&(I=!!v[wc]);var b=_getInstanceFuncs2(f);S(f,_getBaseFuncs2(C,f,b,I));var A=!!Nc&&!!T[Oc];A&&v&&(A=!!v[Oc]),_populatePrototype2(C,_,f,b,!1!==A)}dynamicProto2[Ic]=Fc.o;var xc,Uc=createEnum2,Vc=createTypeMap2,Bc=Uc({Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5}),Hc="toLowerCase",$c="blkVal",jc="length",Gc="rdOnly",qc="notify",Wc="warnToConsole",zc="throwInternal",Kc="setDf",Jc="watch",Yc="logger",Qc="apply",Xc="push",Zc="splice",ed="hdlr",td="cancel",id="initialize",nd="identifier",rd="removeNotificationListener",sd="addNotificationListener",ad="isInitialized",od="getNotifyMgr",ld="getPlugin",cd="pollInternalLogs",dd="name",hd="time",ud="processNext",gd="getProcessTelContext",pd="enabled",md="stopPollingInternalLogs",fd="unload",Sd="onComplete",vd="version",Cd="loggingLevelConsole",yd="createNew",Ed="teardown",_d="messageId",Td="message",Id="isAsync",bd="diagLog",Ad="_doTeardown",Pd="update",Rd="getNext",Md="setNextPlugin",wd="protocol",Od="userAgent",Dd="split",Nd="nodeType",kd="replace",Ld="logInternalMessage",Fd="type",xd="handler",Ud="status",Vd="getResponseHeader",Bd="getAllResponseHeaders",Hd="isChildEvt",$d="data",jd="getCtx",Gd="setCtx",qd="complete",Wd="urlString",zd="sendPOST",Kd="headers",Jd="timeout",Yd="setRequestHeader",Qd="traceId",Xd="spanId",Zd="traceFlags";function throwAggregationError2(g,f){xc||(xc=createCustomError2("AggregationError",(function(g,f){f[jc]>1&&(g.errors=f[1])})));var S=g||"One or more errors occurred.";throw arrForEach2(f,(function(g,f){S+="\n".concat(f," > ").concat(dumpObj2(g))})),new xc(S,f||[])}var eh="Promise",th="rejected";function doAwaitResponse2(g,f){return doAwait2(g,(function(g){return f?f({status:"fulfilled",rejected:!1,value:g}):g}),(function(g){return f?f({status:th,rejected:!0,reason:g}):g}))}function doAwait2(g,f,S,v){var C=g;try{if(isPromiseLike22(g))(f||S)&&(C=g.then(f,S));else try{f&&(C=f(g))}catch(g){if(!S)throw g;C=S(g)}}finally{v&&doFinally2(C,v)}return C}function doFinally2(g,f){var S=g;return f&&(isPromiseLike22(g)?S=g.finally?g.finally(f):g.then((function(g){return f(),g}),(function(g){throw f(),g})):f()),S}var ih,nh=["pending","resolving","resolved",th],rh="dispatchEvent";function _hasInitEventFn2(g){var f;return g&&g.createEvent&&(f=g.createEvent("Event")),!!f&&f.initEvent}function emitEvent2(g,f,S,v){var C=jl();!ih&&(ih=createCachedValue2(!!safe2(_hasInitEventFn2,[C]).v));var _=ih.v?C.createEvent("Event"):v?new Event(f):{};if(S&&S(_),ih.v&&_.initEvent(f,!1,!0),_&&g[rh])g[rh](_);else{var T=g["on"+f];if(T)T(_);else{var I=getInst2("console");I&&(I.error||I.log)(f,dumpObj2(_))}}}var sh,ah="unhandledRejection",oh=ah.toLowerCase(),lh=[],ch=0,dh=10;function dumpFnObj2(g){return hl(g)?g.toString():dumpObj2(g)}function _createPromise2(g,f,S){var v,C,_=arrSlice2(arguments,3),T=0,I=!1,b=[],A=ch++,P=!1,R=null;function _then(f,S){try{return lh.push(A),P=!0,R&&R.cancel(),R=null,g((function(g,C){b.push((function(){try{var _=2===T?f:S,I=isUndefined4(_)?v:hl(_)?_(v):_;isPromiseLike22(I)?I.then(g,C):_?g(I):3===T?C(I):g(I)}catch(g){C(g)}})),I&&_processQueue()}),_)}finally{lh.pop()}}function _catch(g){return _then(void 0,g)}function _finally(g){var f=g,S=g;return hl(g)&&(f=function(f){return g&&g(),f},S=function(f){throw g&&g(),f}),_then(f,S)}function _strState(){return nh[T]}function _processQueue(){if(b.length>0){var g=b.slice();b=[],P=!0,R&&R.cancel(),R=null,f(g)}}function _createSettleIfFn(g,f){return function(S){if(T===f){if(2===g&&isPromiseLike22(S))return T=1,void S.then(_createSettleIfFn(2,1),_createSettleIfFn(3,1));T=g,I=!0,v=S,_processQueue(),P||3!==g||R||(R=scheduleTimeout2(_notifyUnhandledRejection,dh))}}}function _notifyUnhandledRejection(){if(!P)if(P=!0,Jl())process.emit(ah,v,C);else{var g=Gl()||getGlobal2();!sh&&(sh=createCachedValue2(safe2(getInst2,[eh+"RejectionEvent"]).v)),emitEvent2(g,oh,(function(g){return objDefine2(g,"promise",{g:function(){return C}}),g.reason=v,g}),!!sh.v)}}function _toString(){return"IPromise "+_strState()+(I?" - "+dumpFnObj2(v):"")}return yl(C={then:_then,catch:_catch,finally:_finally},"state",{get:_strState}),hasSymbol2()&&(C[getKnownSymbol2(11)]="IPromise"),C.toString=_toString,function _initialize(){hl(S)||throwTypeError2(eh+": executor is not a function - "+dumpFnObj2(S));var g=_createSettleIfFn(3,0);try{S.call(C,_createSettleIfFn(2,0),g)}catch(f){g(f)}}(),C}function _createAllPromise2(g){return function(f){var S=arrSlice2(arguments,1);return g((function(g,S){try{var v=[],C=1;iterForOf2(f,(function(f,_){f&&(C++,doAwait2(f,(function(f){v[_]=f,0==--C&&g(v)}),S))})),0==--C&&g(v)}catch(g){S(g)}}),S)}}function _createResolvedPromise(g){return function(f){var S=arrSlice2(arguments,1);return isPromiseLike22(f)?f:g((function(g){g(f)}),S)}}function _createRejectedPromise(g){return function(f){var S=arrSlice2(arguments,1);return g((function(g,S){S(f)}),S)}}function syncItemProcessor2(g){arrForEach2(g,(function(g){try{g()}catch(g){}}))}function timeoutItemProcessor2(g){var f=pl(g)?g:0;return function(g){scheduleTimeout2((function(){syncItemProcessor2(g)}),f)}}function createAsyncPromise2(g,f){return _createPromise2(createAsyncPromise2,timeoutItemProcessor2(f),g,f)}var hh,uh,gh=_createAllPromise2(createAsyncPromise2),ph=_createResolvedPromise(createAsyncPromise2),mh=_createRejectedPromise(createAsyncPromise2);function createNativePromise2(g,f){!hh&&(hh=createCachedValue2(safe2(getInst2,[eh]).v||null));var S=hh.v;if(!S)return createAsyncPromise2(g);hl(g)||throwTypeError2(eh+": executor is not a function - "+dumpObj2(g));var v=0;function _strState(){return nh[v]}var C=new S((function(f,S){function _resolve(g){v=2,f(g)}function _reject(g){v=3,S(g)}g(_resolve,_reject)}));return yl(C,"state",{get:_strState}),C}function createPromise2(g,f){return!uh&&(uh=createCachedValue2(createNativePromise2)),uh.v.call(this,g,f)}var fh,Sh,vh=_createAllPromise2(createPromise2),Ch="reject",yh="Rejected",Eh=0,_h={};function _rejectDone(){}function _createError(g,f,S){!_h[g]&&(_h[g]=createCustomError2(g));var v=utcNow2();return new _h[g]("Task [".concat(f.id,"] ").concat(S||"","- ").concat(f.st?"Running":"Waiting",": ").concat(_calcTime(v,f.st||f.cr)))}function _calcTime(g,f){return(g-f||"0")+" ms"}function _abortStaleTasks(g,f){var S=utcNow2()-f;arrForEach2(g,(function(g){(g&&!g.rj&&g.st&&g.st<S||!g.st&&g.cr&&g.cr<S)&&g&&g[Ch](g.rj||_createError("Aborted",g,"Stale "))}))}function _removeTask(g,f){var S=Yl(g,f);-1!==S&&g.splice(S,1)}function _addDebugState(g,f,S){Sh=Sh||{toString:function(){return"[[SchedulerState]]"}},yl(g,fh=fh||{toString:function(){return"[[SchedulerName]]"}},{get:f}),yl(g,Sh,{get:S})}function createTaskScheduler(g,f){var S,v,C=[],_=[],T=6e5,I=T/10,b=0,A=(f?f+".":"")+Eh++;g=g||createPromise2;var _startBlockedTimer=function(){var g=sc(C)+sc(_)>0;T>0&&(v||(v=scheduleTimeout2((function(){_abortStaleTasks(C,T),_abortStaleTasks(_,T),v&&(v.enabled=sc(C)+sc(_)>0)}),I)).unref(),v&&(v.enabled=g))},_queueTask=function(f,v,C){var _,T=A+"."+b++;v&&(T+="-("+v+")");var I=((_={id:T,cr:utcNow2(),to:C})[Ch]=function(g){I.rj=g||_createError(yh,I),I[Ch]=_rejectDone},_);return I.p=S?_waitForPreviousTask(I,S,f):g(_runTask(I,f)),S=I,I.p},_runTask=function(g,f){return g.st=utcNow2(),C.push(g),_startBlockedTimer(),function(S,v){var _promiseReject=function(f){g.rj=g.rj||f||_createError(yh,g),g[Ch]=_rejectDone,_doCleanup(g),S=null,v&&v(f),v=null},C=g.id;if(g.rj)_promiseReject(g.rj);else{g[Ch]=_promiseReject;try{var _=f(C);g.to&&isPromiseLike22(_)&&(g.t=scheduleTimeout2((function(){_promiseReject(_createError("Timeout",g))}),g.to)),doAwait2(_,(function(f){_doCleanup(g);try{S&&S(f)}catch(g){v&&v(g)}v=null,S=null}),_promiseReject)}catch(g){_promiseReject(g)}}}},_waitForPreviousTask=function(f,S,v){return _.push(f),_startBlockedTimer(),g((function(g,C){doAwaitResponse2(S.p,(function(){_removeTask(_,f),_runTask(f,v)(g,C)}))}))},_doCleanup=function(g){_removeTask(C,g),g.t&&g.t.cancel(),g.t=null,S&&S===g&&(S=null,sc(C)+sc(_)===0&&(v&&v.cancel(),v=null))},P={idle:!0,queue:_queueTask,setStaleTimeout:function(g,f){v&&v.cancel(),v=null,T=g,I=f||g/10,_startBlockedTimer()}};return objDefine2(P,"idle",{g:function(){return sc(C)+sc(_)===0}}),_addDebugState(P,(function(){return A}),(function(){return{l:S,r:C,w:_}})),P}var Th=void 0,Ih="",bh="channels",Ah="core",Ph="createPerfMgr",Rh="disabled",Mh="extensionConfig",wh="extensions",Oh="processTelemetry",Dh="priority",Nh="eventsSent",kh="eventsDiscarded",Lh="eventsSendRequest",Fh="perfEvent",xh="offlineEventsStored",Uh="offlineBatchSent",Vh="offlineBatchDrop",Bh="getPerfMgr",Hh="domain",$h="path",jh="Not dynamic - ",Gh=/-([a-z])/g,qh=/([^\w\d_$])/g,Wh=/^(\d+[\w\d_$])/;function isNotNullOrUndefined2(g){return!isNullOrUndefined2(g)}function normalizeJsName2(g){var f=g;return f&&dl(f)&&(f=(f=(f=f[kd](Gh,(function(g,f){return f.toUpperCase()})))[kd](qh,"_"))[kd](Wh,(function(g,f){return"_"+f}))),f}function strContains2(g,f){return!(!g||!f)&&-1!==oc(g,f)}function toISOString2(g){return g&&g.toISOString()||""}function getExceptionName2(g){return fl(g)?g[dd]:Ih}function setValue2(g,f,S,v,C){var _=S;return g&&((_=g[f])===S||C&&!C(_)||v&&!v(S)||(_=S,g[f]=_)),_}function getSetValue2(g,f,S){var v;return g?!(v=g[f])&&isNullOrUndefined2(v)&&(v=isUndefined4(S)?{}:S,g[f]=v):v=isUndefined4(S)?{}:S,v}function _createProxyFunction2(g,f){var S=null,v=null;return hl(g)?S=g:v=g,function(){var g=arguments;if(S&&(v=S()),v)return v[f][Qc](v,g)}}function proxyFunctionAs2(g,f,S,v,C){g&&f&&S&&(!1!==C||isUndefined4(g[f]))&&(g[f]=_createProxyFunction2(S,v))}function proxyFunctions2(g,f,S,v){return g&&f&&isObject3(g)&&ul(S)&&arrForEach2(S,(function(S){dl(S)&&proxyFunctionAs2(g,S,f,S,v)})),g}function optimizeObject2(g){return g&&bl&&(g=Uo(bl({},g))),g}function objExtend2(g,f,S,v,C,_){var T=arguments,I=T[0]||{},b=T[jc],A=!1,P=1;for(b>0&&ml(I)&&(A=I,I=T[P]||{},P++),isObject3(I)||(I={});P<b;P++){var R=T[P],M=ul(R),w=isObject3(R);for(var O in R)if(M&&O in R||w&&vl(R,O)){var D=R[O],N=void 0;if(A&&D&&((N=ul(D))||isPlainObject2(D))){var k=I[O];N?ul(k)||(k=[]):isPlainObject2(k)||(k={}),D=objExtend2(A,k,D)}void 0!==D&&(I[O]=D)}}return I}function getResponseText2(g){try{return g.responseText}catch(g){}return null}function formatErrorMessageXdr2(g,f){return g?"XDomainRequest,Response:"+getResponseText2(g)||"":f}function formatErrorMessageXhr2(g,f){return g?"XMLHttpRequest,Status:"+g[Ud]+",Response:"+getResponseText2(g)||g.response||"":f}function prependTransports2(g,f){return f&&(pl(f)?g=[f].concat(g):ul(f)&&(g=f.concat(g))),g}var zh="Microsoft_ApplicationInsights_BypassAjaxInstrumentation",Kh="withCredentials",Jh="timeout";function openXhr3(g,f,S,v,C,_){function _wrapSetXhrProp(g,f,S){try{g[f]=S}catch(g){}}void 0===v&&(v=!1),void 0===C&&(C=!1);var T=new XMLHttpRequest;return v&&_wrapSetXhrProp(T,zh,v),S&&_wrapSetXhrProp(T,Kh,S),T.open(g,f,!C),S&&_wrapSetXhrProp(T,Kh,S),!C&&_&&_wrapSetXhrProp(T,Jh,_),T}function convertAllHeadersToMap2(g){var f={};return dl(g)&&arrForEach2(nc(g)[Dd](/[\r\n]+/),(function(g){if(g){var S=g.indexOf(": ");if(-1!==S){var v=nc(g.substring(0,S))[Hc](),C=nc(g.substring(S+1));f[v]=C}else f[nc(g)]=1}})),f}function _appendHeader2(g,f,S){if(!g[S]&&f&&f[Vd]){var v=f[Vd](S);v&&(g[S]=nc(v))}return g}var Yh="kill-duration",Qh="kill-duration-seconds",Xh="time-delta-millis";function _getAllResponseHeaders2(g,f){var S={};return g[Bd]?S=convertAllHeadersToMap2(g[Bd]()):f&&(S=_appendHeader2(S,g,Xh),S=_appendHeader2(S,g,Yh),S=_appendHeader2(S,g,Qh)),S}var Zh="location",eu="console",tu="JSON",iu="crypto",nu="msCrypto",ru="ReactNative",su="msie",au="trident/",ou="XMLHttpRequest",lu=null,cu=null,du=!1,hu=null,uu=null;function _hasProperty2(g,f){var S=!1;if(g){try{if(!(S=f in g)){var v=g[xo];v&&(S=f in v)}}catch(g){}if(!S)try{S=!isUndefined4((new g)[f])}catch(g){}}return S}function getLocation2(g){if(g&&du){var f=getInst2("__mockLocation");if(f)return f}return typeof location===Lo&&location?location:getInst2(Zh)}function getConsole2(){return typeof console!==Fo?console:getInst2(eu)}function hasJSON2(){return Boolean(typeof JSON===Lo&&JSON||null!==getInst2(tu))}function getJSON2(){return hasJSON2()?JSON||getInst2(tu):null}function getCrypto2(){return getInst2(iu)}function getMsCrypto2(){return getInst2(nu)}function isReactNative2(){var g=Kl();return!(!g||!g.product)&&g.product===ru}function isIE2(){var g=Kl();if(g&&(g[Od]!==cu||null===lu)){var f=((cu=g[Od])||Ih)[Hc]();lu=strContains2(f,su)||strContains2(f,au)}return lu}function isBeaconsSupported2(g){return null!==uu&&!1!==g||(uu=hasNavigator2()&&Boolean(Kl().sendBeacon)),uu}function isFetchSupported2(g){var f=!1;try{f=!!getInst2("fetch");var S=getInst2("Request");f&&g&&S&&(f=_hasProperty2(S,"keepalive"))}catch(g){}return f}function useXDomainRequest2(){return null===hu&&(hu=typeof XDomainRequest!==Fo)&&isXhrSupported2()&&(hu=hu&&!_hasProperty2(getInst2(ou),"withCredentials")),hu}function isXhrSupported2(){var g=!1;try{g=!!getInst2(ou)}catch(g){}return g}var gu=4294967296,pu=4294967295,mu=123456789,fu=987654321,Su=!1,vu=mu,Cu=fu;function _mwcSeed2(g){g<0&&(g>>>=0),vu=mu+g&pu,Cu=fu-g&pu,Su=!0}function _autoSeedMwc2(){try{var g=2147483647&utcNow2();_mwcSeed2((Math.random()*gu^g)+g)}catch(g){}}function random322(g){var f=0,S=getCrypto2()||getMsCrypto2();return S&&S.getRandomValues&&(f=S.getRandomValues(new Uint32Array(1))[0]&pu),0===f&&isIE2()&&(Su||_autoSeedMwc2(),f=mwcRandom322()&pu),0===f&&(f=Math.floor(gu*Math.random()|0)),g||(f>>>=0),f}function mwcRandom322(g){var f=((Cu=36969*(65535&Cu)+(Cu>>16)&pu)<<16)+(65535&(vu=18e3*(65535&vu)+(vu>>16)&pu))>>>0&pu|0;return g||(f>>>=0),f}function newId2(g){void 0===g&&(g=22);for(var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S=random322()>>>0,v=0,C=Ih;C[jc]<g;)v++,C+=f.charAt(63&S),S>>>=6,5===v&&(S=(random322()<<2&4294967295|3&S)>>>0,v=0);return C}var yu="3.2.1",Eu="."+newId2(6),_u=0;function _canAcceptData2(g){return 1===g[Nd]||9===g[Nd]||!+g[Nd]}function _getCache2(g,f){var S=f[g.id];if(!S){S={};try{_canAcceptData2(f)&&objDefine2(f,g.id,{e:!1,v:S})}catch(g){}}return S}function createUniqueNamespace2(g,f){return void 0===f&&(f=!1),normalizeJsName2(g+_u+++(f?"."+yu:Ih)+Eu)}function createElmNodeData2(g){var f={id:createUniqueNamespace2("_aiData-"+(g||Ih)+"."+yu),accept:function(g){return _canAcceptData2(g)},get:function(g,S,v,C){var _=g[f.id];return _?_[normalizeJsName2(S)]:(C&&((_=_getCache2(f,g))[normalizeJsName2(S)]=v),v)},kill:function(g,f){if(g&&g[f])try{delete g[f]}catch(g){}}};return f}function _isConfigDefaults2(g){return g&&isObject3(g)&&(g.isVal||g.fb||vl(g,"v")||vl(g,"mrg")||vl(g,"ref")||g.set)}function _getDefault2(g,f,S){var v,C=S.dfVal||isDefined22;if(f&&S.fb){var _=S.fb;ul(_)||(_=[_]);for(var T=0;T<_[jc];T++){var I=_[T],b=f[I];if(C(b)?v=b:g&&(C(b=g.cfg[I])&&(v=b),g.set(g.cfg,_l(I),b)),C(v))break}}return!C(v)&&C(S.v)&&(v=S.v),v}function _resolveDefaultValue2(g,f,S){var v,C=S;return S&&_isConfigDefaults2(S)&&(C=_getDefault2(g,f,S)),C&&(_isConfigDefaults2(C)&&(C=_resolveDefaultValue2(g,f,C)),ul(C)?(v=[])[jc]=C[jc]:isPlainObject2(C)&&(v={}),v&&(objForEachKey2(C,(function(S,C){C&&_isConfigDefaults2(C)&&(C=_resolveDefaultValue2(g,f,C)),v[S]=C})),C=v)),C}function _applyDefaultValue2(g,f,S,v){var C,_,T,I,b,A,P,R,M=v;_isConfigDefaults2(M)?(C=M.isVal,_=M.set,A=M[Gc],P=M[$c],I=M.mrg,!(b=M.ref)&&isUndefined4(b)&&(b=!!I),T=_getDefault2(g,f,M)):T=v,P&&g[$c](f,S);var w=!0,O=f[S];!O&&isNullOrUndefined2(O)||(R=O,w=!1,C&&R!==T&&!C(R)&&(R=T,w=!0),_&&(w=(R=_(R,T,f))===T)),w?R=T?_resolveDefaultValue2(g,f,T):T:(isPlainObject2(R)||ul(T))&&I&&T&&(isPlainObject2(T)||ul(T))&&objForEachKey2(T,(function(f,S){_applyDefaultValue2(g,R,f,S)})),g.set(f,S,R),b&&g.ref(f,S),A&&g[Gc](f,S)}var Tu=symbolFor2("[[ai_dynCfg_1]]"),Iu=symbolFor2("[[ai_blkDynCfg_1]]"),bu=symbolFor2("[[ai_frcDynCfg_1]]");function _cfgDeepCopy2(g){var f;return g&&(ul(g)?(f=[])[jc]=g[jc]:isPlainObject2(g)&&(f={}),f)?(objForEachKey2(g,(function(g,S){f[g]=_cfgDeepCopy2(S)})),f):g}function getDynamicConfigHandler2(g){if(g){var f=g[Tu]||g;if(f.cfg&&(f.cfg===g||f.cfg[Tu]===f))return f}return null}function blockDynamicConversion2(g){if(g&&(isPlainObject2(g)||ul(g)))try{g[Iu]=!0}catch(g){}return g}function _canMakeDynamic2(g,f,S){var v=!1;return S&&!g[f.blkVal]&&((v=S[bu])||S[Iu]||(v=isPlainObject2(S)||ul(S))),v}function throwInvalidAccess2(g){throwTypeError2("InvalidAccess:"+g)}var Au=["push","pop","shift","unshift","splice"],_throwDynamicError2=function(g,f,S,v){g&&g[zc](3,108,"".concat(S," [").concat(f,"] failed - ")+dumpObj2(v))};function _patchArray2(g,f,S){ul(f)&&arrForEach2(Au,(function(v){var C=f[v];f[v]=function(){for(var v=[],_=0;_<arguments.length;_++)v[_]=arguments[_];var T=C[Qc](this,v);return _makeDynamicObject2(g,f,S,"Patching"),T}}))}function _getOwnPropGetter2(g,f){var S=Sl(g,f);return S&&S.get}function _createDynamicProperty2(g,f,S,v){var C={n:S,h:[],trk:function(f){f&&f.fn&&(-1===Yl(C.h,f)&&C.h[Xc](f),g.trk(f,C))},clr:function(g){var f=Yl(C.h,g);-1!==f&&C.h[Zc](f,1)}},_=!0,T=!1;function _getProperty(){_&&(T=T||_canMakeDynamic2(_getProperty,g,v),v&&!v[Tu]&&T&&(v=_makeDynamicObject2(g,v,S,"Converting")),_=!1);var f=g.act;return f&&C.trk(f),v}function _setProperty(I){if(v!==I){_getProperty[g.ro]&&!g.upd&&throwInvalidAccess2("["+S+"] is read-only:"+dumpObj2(f)),_&&(T=T||_canMakeDynamic2(_getProperty,g,v),_=!1);var b=T&&_getProperty[g.rf];if(T)if(b){objForEachKey2(v,(function(g){v[g]=I?I[g]:Th}));try{objForEachKey2(I,(function(f,S){_setDynamicProperty2(g,v,f,S)})),I=v}catch(f){_throwDynamicError2((g.hdlr||{})[Yc],S,"Assigning",f),T=!1}}else v&&v[Tu]&&objForEachKey2(v,(function(f){var S=_getOwnPropGetter2(v,f);if(S){var C=S[g.prop];C&&C.chng()}}));if(I!==v){var A=I&&_canMakeDynamic2(_getProperty,g,I);!b&&A&&(I=_makeDynamicObject2(g,I,S,"Converting")),v=I,T=A}g.add(C)}}_getProperty[g.prop]={chng:function(){g.add(C)}},objDefine2(f,C.n,{g:_getProperty,s:_setProperty})}function _setDynamicProperty2(g,f,S,v){if(f){var C=_getOwnPropGetter2(f,S);C&&C[g.prop]?f[S]=v:_createDynamicProperty2(g,f,S,v)}return f}function _setDynamicPropertyState2(g,f,S,v){if(f){var C=_getOwnPropGetter2(f,S),_=C&&!!C[g.prop],T=v&&v[0],I=v&&v[1],b=v&&v[2];if(!_){if(b)try{blockDynamicConversion2(f)}catch(f){_throwDynamicError2((g.hdlr||{})[Yc],S,"Blocking",f)}try{_setDynamicProperty2(g,f,S,f[S]),C=_getOwnPropGetter2(f,S)}catch(f){_throwDynamicError2((g.hdlr||{})[Yc],S,"State",f)}}T&&(C[g.rf]=T),I&&(C[g.ro]=I),b&&(C[g.blkVal]=!0)}return f}function _makeDynamicObject2(g,f,S,v){try{objForEachKey2(f,(function(S,v){_setDynamicProperty2(g,f,S,v)})),f[Tu]||(yl(f,Tu,{get:function(){return g[ed]}}),_patchArray2(g,f,S))}catch(f){_throwDynamicError2((g.hdlr||{})[Yc],S,v,f)}return f}var Pu="[[ai_",Ru="]]";function _createState2(g){var f,S,v=newSymbol2(Pu+"get"+g.uid+Ru),C=newSymbol2(Pu+"ro"+g.uid+Ru),_=newSymbol2(Pu+"rf"+g.uid+Ru),T=newSymbol2(Pu+"blkVal"+g.uid+Ru),I=newSymbol2(Pu+"dtl"+g.uid+Ru),b=null,A=null;function _useHandler(f,v){var C=S.act;try{S.act=f,f&&f[I]&&(arrForEach2(f[I],(function(g){g.clr(f)})),f[I]=[]),v({cfg:g.cfg,set:g.set.bind(g),setDf:g[Kc].bind(g),ref:g.ref.bind(g),rdOnly:g[Gc].bind(g)})}catch(f){var _=g[Yc];throw _&&_[zc](1,107,dumpObj2(f)),f}finally{S.act=C||null}}function _notifyWatchers(){if(b){var g=b;b=null,A&&A[td](),A=null;var f=[];if(arrForEach2(g,(function(g){if(g&&(g[I]&&(arrForEach2(g[I],(function(f){f.clr(g)})),g[I]=null),g.fn))try{_useHandler(g,g.fn)}catch(g){f[Xc](g)}})),b)try{_notifyWatchers()}catch(g){f[Xc](g)}f[jc]>0&&throwAggregationError2("Watcher error(s): ",f)}}function _addWatcher(g){if(g&&g.h[jc]>0){b||(b=[]),A||(A=scheduleTimeout2((function(){A=null,_notifyWatchers()}),0));for(var f=0;f<g.h[jc];f++){var S=g.h[f];S&&-1===Yl(b,S)&&b[Xc](S)}}}function _trackHandler(g,f){if(g){var S=g[I]=g[I]||[];-1===Yl(S,f)&&S[Xc](f)}}return(f={prop:v,ro:C,rf:_})[$c]=T,f[ed]=g,f.add=_addWatcher,f[qc]=_notifyWatchers,f.use=_useHandler,f.trk=_trackHandler,S=f}function _createAndUseHandler2(g,f){var S={fn:f,rm:function(){S.fn=null,g=null,f=null}};return objDefine2(S,"toJSON",{v:function(){return"WatcherHandler"+(S.fn?"":"[X]")}}),g.use(S,f),S}function _createDynamicHandler2(g,f,S){var v,C=getDynamicConfigHandler2(f);if(C)return C;var _,T=createUniqueNamespace2("dyncfg",!0),I=f&&!1!==S?f:_cfgDeepCopy2(f);function _notifyWatchers(){_[qc]()}function _setValue(f,S,v){try{f=_setDynamicProperty2(_,f,S,v)}catch(f){_throwDynamicError2(g,S,"Setting value",f)}return f[S]}function _watch(g){return _createAndUseHandler2(_,g)}function _block(g,f){_.use(null,(function(S){var v=_.upd;try{isUndefined4(f)||(_.upd=f),g(S)}finally{_.upd=v}}))}function _ref(g,f){var S;return _setDynamicPropertyState2(_,g,f,(S={},S[0]=!0,S))[f]}function _rdOnly(g,f){var S;return _setDynamicPropertyState2(_,g,f,(S={},S[1]=!0,S))[f]}function _blkPropValue(g,f){var S;return _setDynamicPropertyState2(_,g,f,(S={},S[2]=!0,S))[f]}function _applyDefaults(g,f){return f&&objForEachKey2(f,(function(f,S){_applyDefaultValue2(b,g,f,S)})),g}var b=((v={uid:null,cfg:I})[Yc]=g,v[qc]=_notifyWatchers,v.set=_setValue,v[Kc]=_applyDefaults,v[Jc]=_watch,v.ref=_ref,v[Gc]=_rdOnly,v[$c]=_blkPropValue,v._block=_block,v);return objDefine2(b,"uid",{c:!1,e:!1,w:!1,v:T}),_makeDynamicObject2(_=_createState2(b),I,"config","Creating"),b}function _logInvalidAccess2(g,f){g?(g[Wc](f),g[zc](2,108,f)):throwInvalidAccess2(f)}function createDynamicConfig2(g,f,S,v){var C=_createDynamicHandler2(S,g||{},v);return f&&C[Kc](C.cfg,f),C}function onConfigChange2(g,f,S){var v=g[Tu]||g;return!v.cfg||v.cfg!==g&&v.cfg[Tu]!==v?(_logInvalidAccess2(S,jh+dumpObj2(g)),createDynamicConfig2(g,null,S)[Jc](f)):v[Jc](f)}function runTargetUnload2(g,f){if(g&&g[fd])return g[fd](f)}function doUnloadAll2(g,f,S){var v;return S||(v=createPromise2((function(g){S=g}))),g&&sc(g)>0?doAwaitResponse2(runTargetUnload2(g[0],f),(function(){doUnloadAll2(arrSlice2(g,1),f,S)})):S(),v}var Mu=500,wu="Microsoft_ApplicationInsights_BypassAjaxInstrumentation";function cfgDfMerge2(g){return{mrg:!0,v:g}}function cfgDfString2(g){return{isVal:dl,v:_l(g||Ih)}}var Ou,Du,Nu=[Nh,kh,Lh,Fh],ku=null;function _listenerProxyFunc2(g,f){return function(){var S=arguments,v=getDebugExt2(f);if(v){var C=v.listener;C&&C[g]&&C[g][Qc](C,S)}}}function _getExtensionNamespace2(){var g=getInst2("Microsoft");return g&&(ku=g.ApplicationInsights),ku}function getDebugExt2(g){var f=ku;return f||!0===g.disableDbgExt||(f=ku||_getExtensionNamespace2()),f?f.ChromeDbgExt:null}function getDebugListener2(g){if(!Ou){Ou={};for(var f=0;f<Nu[jc];f++)Ou[Nu[f]]=_listenerProxyFunc2(Nu[f],g)}return Ou}var Lu="warnToConsole",Fu="AI (Internal): ",xu="AI: ",Uu="AITR_",Vu={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},Bu=((Du={})[0]=null,Du[1]="errorToConsole",Du[2]=Lu,Du[3]="debugToConsole",Du);function _sanitizeDiagnosticText2(g){return g?'"'+g[kd](/\"/g,Ih)+'"':Ih}function _logToConsole2(g,f){var S=getConsole2();if(S){var v="log";S[g]&&(v=g),hl(S[v])&&S[v](f)}}var Hu=function(){function _InternalLogMessage3(g,f,S,v){void 0===S&&(S=!1);var C=this;C[_d]=g,C[Td]=(S?xu:Fu)+g;var _=Ih;hasJSON2()&&(_=getJSON2().stringify(v));var T=(f?" message:"+_sanitizeDiagnosticText2(f):Ih)+(v?" props:"+_sanitizeDiagnosticText2(_):Ih);C[Td]+=T}return _InternalLogMessage3.dataType="MessageData",_InternalLogMessage3}();function safeGetLogger2(g,f){return(g||{})[Yc]||new Gu(f)}var $u,ju,Gu=function(){function DiagnosticLogger3(g){this.identifier="DiagnosticLogger",this.queue=[];var f,S,v,C,_,T=0,I={};dynamicProto2(DiagnosticLogger3,this,(function(b){function _logInternalMessage3(g,f){if(!_areInternalMessagesThrottled()){var C=!0,_=Uu+f[_d];if(I[_]?C=!1:I[_]=!0,C&&(g<=S&&(b.queue[Xc](f),T++,_debugExtMsg(1===g?"error":"warn",f)),T===v)){var A="Internal events throttle limit per PageView reached for this app.",P=new Hu(23,A,!1);b.queue[Xc](P),1===g?b.errorToConsole(A):b[Wc](A)}}}function _setDefaultsFromConfig(g){return onConfigChange2(createDynamicConfig2(g,Vu,b).cfg,(function(g){var _=g.cfg;f=_[Cd],S=_.loggingLevelTelemetry,v=_.maxMessageLimit,C=_.enableDebug}))}function _areInternalMessagesThrottled(){return T>=v}function _debugExtMsg(f,S){var v=getDebugExt2(g||{});v&&v[bd]&&v[bd](f,S)}_=_setDefaultsFromConfig(g||{}),b.consoleLoggingLevel=function(){return f},b[zc]=function(g,S,v,_,T){void 0===T&&(T=!1);var A=new Hu(S,v,T,_);if(C)throw dumpObj2(A);var P=Bu[g]||Lu;if(isUndefined4(A[Td]))_debugExtMsg("throw"+(1===g?"Critical":"Warning"),A);else{if(T){var R=+A[_d];!I[R]&&f>=g&&(b[P](A[Td]),I[R]=!0)}else f>=g&&b[P](A[Td]);_logInternalMessage3(g,A)}},b.debugToConsole=function(g){_logToConsole2("debug",g),_debugExtMsg("warning",g)},b[Wc]=function(g){_logToConsole2("warn",g),_debugExtMsg("warning",g)},b.errorToConsole=function(g){_logToConsole2("error",g),_debugExtMsg("error",g)},b.resetInternalMessageCount=function(){T=0,I={}},b[Ld]=_logInternalMessage3,b[fd]=function(g){_&&_.rm(),_=null}}))}return DiagnosticLogger3.__ieDyn=1,DiagnosticLogger3}();function _getLogger2(g){return g||new Gu}function _throwInternal2(g,f,S,v,C,_){void 0===_&&(_=!1),_getLogger2(g)[zc](f,S,v,C,_)}function _warnToConsole2(g,f){_getLogger2(g)[Wc](f)}var qu,Wu="toGMTString",zu="toUTCString",Ku="cookie",Ju="expires",Yu="isCookieUseDisabled",Qu="disableCookiesUsage",Xu="_ckMgr",Zu=null,eg=null,tg=null,ig={},ng={},rg=(($u={cookieCfg:cfgDfMerge2((ju={},ju[Hh]={fb:"cookieDomain",dfVal:isNotNullOrUndefined2},ju.path={fb:"cookiePath",dfVal:isNotNullOrUndefined2},ju.enabled=Th,ju.ignoreCookies=Th,ju.blockedCookies=Th,ju)),cookieDomain:Th,cookiePath:Th})[Qu]=Th,$u);function _getDoc2(){!qu&&(qu=getLazy2((function(){return jl()})))}function _gblCookieMgr2(g,f){var S=createCookieMgr2[Xu]||ng[Xu];return S||(S=createCookieMgr2[Xu]=createCookieMgr2(g,f),ng[Xu]=S),S}function _isMgrEnabled2(g){return!g||g.isEnabled()}function _isIgnoredCookie2(g,f){return!!(f&&g&&ul(g.ignoreCookies))&&-1!==Yl(g.ignoreCookies,f)}function _isBlockedCookie2(g,f){return!!(f&&g&&ul(g.blockedCookies)&&-1!==Yl(g.blockedCookies,f))||_isIgnoredCookie2(g,f)}function _isCfgEnabled2(g,f){var S=f[pd];if(isNullOrUndefined2(S)){var v=void 0;isUndefined4(g[Yu])||(v=!g[Yu]),isUndefined4(g[Qu])||(v=!g[Qu]),S=v}return S}function safeGetCookieMgr2(g,f){var S;if(g)S=g.getCookieMgr();else if(f){var v=f.cookieCfg;S=v&&v[Xu]?v[Xu]:createCookieMgr2(f)}return S||(S=_gblCookieMgr2(f,(g||{})[Yc])),S}function createCookieMgr2(g,f){var S,v,C,_,T,I,b,A,P;g=createDynamicConfig2(g||ng,null,f).cfg,T=onConfigChange2(g,(function(f){f[Kc](f.cfg,rg),v=f.ref(f.cfg,"cookieCfg"),C=v[$h]||"/",_=v[Hh],I=!1!==_isCfgEnabled2(g,v),b=v.getCookie||_getCookieValue2,A=v.setCookie||_setCookieValue2,P=v.delCookie||_setCookieValue2}),f);var R=((S={isEnabled:function(){var S=!1!==_isCfgEnabled2(g,v)&&I&&areCookiesSupported2(f),C=ng[Xu];return S&&C&&R!==C&&(S=_isMgrEnabled2(C)),S},setEnabled:function(g){I=!1!==g,v[pd]=g},set:function(g,f,S,T,I){var b=!1;if(_isMgrEnabled2(R)&&!_isBlockedCookie2(v,g)){var P={},M=nc(f||Ih),w=oc(M,";");if(-1!==w&&(M=nc(strLeft2(f,w)),P=_extractParts2(Ll(f,w+1))),setValue2(P,Hh,T||_,isTruthy2,isUndefined4),!isNullOrUndefined2(S)){var O=isIE2();if(isUndefined4(P[Ju])){var D=utcNow2()+1e3*S;if(D>0){var N=new Date;N.setTime(D),setValue2(P,Ju,_formatDate2(N,O?Wu:zu)||_formatDate2(N,O?Wu:zu)||Ih,isTruthy2)}}O||setValue2(P,"max-age",Ih+S,null,isUndefined4)}var k=getLocation2();k&&"https:"===k[wd]&&(setValue2(P,"secure",null,null,isUndefined4),null===eg&&(eg=!uaDisallowsSameSiteNone2((Kl()||{})[Od])),eg&&setValue2(P,"SameSite","None",null,isUndefined4)),setValue2(P,$h,I||C,null,isUndefined4),A(g,_formatCookieValue2(M,P)),b=!0}return b},get:function(g){var f=Ih;return _isMgrEnabled2(R)&&!_isIgnoredCookie2(v,g)&&(f=b(g)),f},del:function(g,f){var S=!1;return _isMgrEnabled2(R)&&(S=R.purge(g,f)),S},purge:function(g,S){var v,C=!1;if(areCookiesSupported2(f)){var _=((v={})[$h]=S||"/",v[Ju]="Thu, 01 Jan 1970 00:00:01 GMT",v);isIE2()||(_["max-age"]="0"),P(g,_formatCookieValue2(Ih,_)),C=!0}return C}})[fd]=function(g){T&&T.rm(),T=null},S);return R[Xu]=R,R}function areCookiesSupported2(g){if(null===Zu){Zu=!1,!qu&&_getDoc2();try{var f=qu.v||{};Zu=void 0!==f[Ku]}catch(f){_throwInternal2(g,2,68,"Cannot access document.cookie - "+getExceptionName2(f),{exception:dumpObj2(f)})}}return Zu}function _extractParts2(g){var f={};return g&&g[jc]&&arrForEach2(nc(g)[Dd](";"),(function(g){if(g=nc(g||Ih)){var S=oc(g,"=");-1===S?f[g]=null:f[nc(strLeft2(g,S))]=nc(Ll(g,S+1))}})),f}function _formatDate2(g,f){return hl(g[f])?g[f]():null}function _formatCookieValue2(g,f){var S=g||Ih;return objForEachKey2(f,(function(g,f){S+="; "+g+(isNullOrUndefined2(f)?Ih:"="+f)})),S}function _getCookieValue2(g){var f=Ih;if(!qu&&_getDoc2(),qu.v){var S=qu.v[Ku]||Ih;tg!==S&&(ig=_extractParts2(S),tg=S),f=nc(ig[g]||Ih)}return f}function _setCookieValue2(g,f){!qu&&_getDoc2(),qu.v&&(qu.v[Ku]=g+"="+f)}function uaDisallowsSameSiteNone2(g){return!(!dl(g)||!strContains2(g,"CPU iPhone OS 12")&&!strContains2(g,"iPad; CPU OS 12")&&!(strContains2(g,"Macintosh; Intel Mac OS X 10_14")&&strContains2(g,"Version/")&&strContains2(g,"Safari"))&&(!strContains2(g,"Macintosh; Intel Mac OS X 10_14")||!ac(g,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))&&!strContains2(g,"Chrome/5")&&!strContains2(g,"Chrome/6")&&(!strContains2(g,"UnrealEngine")||strContains2(g,"Chrome"))&&!strContains2(g,"UCBrowser/12")&&!strContains2(g,"UCBrowser/11"))}var sg={perfEvtsSendAll:!1};function _runScheduledListeners2(g){g.h=null;var f=g.cb;g.cb=[],arrForEach2(f,(function(g){safe2(g.fn,[g.arg])}))}function _runListeners2(g,f,S,v){arrForEach2(g,(function(g){g&&g[f]&&(S?(S.cb[Xc]({fn:v,arg:g}),S.h=S.h||scheduleTimeout2(_runScheduledListeners2,0,S)):safe2(v,[g]))}))}var ag=function(){function NotificationManager3(g){var f,S;this.listeners=[];var v=[],C={h:null,cb:[]},_=createDynamicConfig2(g,sg);S=_[Jc]((function(g){f=!!g.cfg.perfEvtsSendAll})),dynamicProto2(NotificationManager3,this,(function(g){objDefine2(g,"listeners",{g:function(){return v}}),g[sd]=function(g){v[Xc](g)},g[rd]=function(g){for(var f=Yl(v,g);f>-1;)v[Zc](f,1),f=Yl(v,g)},g[Nh]=function(g){_runListeners2(v,Nh,C,(function(f){f[Nh](g)}))},g[kh]=function(g,f){_runListeners2(v,kh,C,(function(S){S[kh](g,f)}))},g[Lh]=function(g,f){_runListeners2(v,Lh,f?C:null,(function(S){S[Lh](g,f)}))},g[Fh]=function(g){g&&(!f&&g[Hd]()||_runListeners2(v,Fh,null,(function(f){g[Id]?scheduleTimeout2((function(){return f[Fh](g)}),0):f[Fh](g)})))},g[xh]=function(g){g&&g[jc]&&_runListeners2(v,xh,C,(function(f){f[xh](g)}))},g[Uh]=function(g){g&&g[$d]&&_runListeners2(v,Uh,C,(function(f){f[Uh](g)}))},g[Vh]=function(g,f){if(g>0){var S=f||0;_runListeners2(v,Vh,C,(function(f){f[Vh](g,S)}))}},g[fd]=function(g){var f,_finishUnload=function(){S&&S.rm(),S=null,v=[],C.h&&C.h[td](),C.h=null,C.cb=[]};if(_runListeners2(v,"unload",null,(function(S){var v=S[fd](g);v&&(f||(f=[]),f[Xc](v))})),f)return createPromise2((function(g){return doAwaitResponse2(vh(f),(function(){_finishUnload(),g()}))}));_finishUnload()}}))}return NotificationManager3.__ieDyn=1,NotificationManager3}(),og="ctx",lg="ParentContextKey",cg="ChildrenContextKey",dg=null,hg=function(){function PerfEvent3(g,f,S){var v,C=this;C.start=utcNow2(),C[dd]=g,C[Id]=S,C[Hd]=function(){return!1},hl(f)&&objDefine2(C,"payload",{g:function(){return!v&&hl(f)&&(v=f(),f=null),v}}),C[jd]=function(g){return g?g===PerfEvent3[lg]||g===PerfEvent3[cg]?C[g]:(C[og]||{})[g]:null},C[Gd]=function(g,f){g&&(g===PerfEvent3[lg]?(C[g]||(C[Hd]=function(){return!0}),C[g]=f):g===PerfEvent3[cg]?C[g]=f:(C[og]=C[og]||{})[g]=f)},C[qd]=function(){var g=0,f=C[jd](PerfEvent3[cg]);if(ul(f))for(var S=0;S<f[jc];S++){var v=f[S];v&&(g+=v[hd])}C[hd]=utcNow2()-C.start,C.exTime=C[hd]-g,C[qd]=function(){}}}return PerfEvent3.ParentContextKey="parent",PerfEvent3.ChildrenContextKey="childEvts",PerfEvent3}(),ug=function(){function PerfManager3(g){this.ctx={},dynamicProto2(PerfManager3,this,(function(f){f.create=function(g,f,S){return new hg(g,f,S)},f.fire=function(f){f&&(f[qd](),g&&hl(g[Fh])&&g[Fh](f))},f[Gd]=function(g,S){g&&((f[og]=f[og]||{})[g]=S)},f[jd]=function(g){return(f[og]||{})[g]}}))}return PerfManager3.__ieDyn=1,PerfManager3}(),gg="CoreUtils.doPerf";function doPerf2(g,f,S,v,C){if(g){var _=g;if(_[Bh]&&(_=_[Bh]()),_){var T=void 0,I=_[jd](gg);try{if(T=_.create(f(),v,C)){if(I&&T[Gd]&&(T[Gd](hg[lg],I),I[jd]&&I[Gd])){var b=I[jd](hg[cg]);b||(b=[],I[Gd](hg[cg],b)),b[Xc](T)}return _[Gd](gg,T),S(T)}}catch(g){T&&T[Gd]&&T[Gd]("exception",g)}finally{T&&_.fire(T),_[Gd](gg,I)}}}return S()}function getGblPerfMgr2(){return dg}function newGuid22(){var g=generateW3CId2();return Ll(g,0,8)+"-"+Ll(g,8,12)+"-"+Ll(g,12,16)+"-"+Ll(g,16,20)+"-"+Ll(g,20)}function generateW3CId2(){for(var g,f=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],S=Ih,v=0;v<4;v++)S+=f[15&(g=random322())]+f[g>>4&15]+f[g>>8&15]+f[g>>12&15]+f[g>>16&15]+f[g>>20&15]+f[g>>24&15]+f[g>>28&15];var C=f[8+(3&random322())|0];return Fl(S,0,8)+Fl(S,9,4)+"4"+Fl(S,13,3)+C+Fl(S,16,3)+Fl(S,19,12)}var pg="00000000000000000000000000000000",mg="0000000000000000";function _isValid2(g,f,S){return!(!g||g[jc]!==f||g===S||!g.match(/^[\da-f]*$/i))}function isValidTraceId2(g){return _isValid2(g,32,pg)}function isValidSpanId2(g){return _isValid2(g,16,mg)}var fg=createElmNodeData2("plugin");function _getPluginState2(g){return fg.get(g,"state",{},!0)}function initializePlugins2(g,f){for(var S,v=[],C=null,_=g[Rd]();_;){var T=_[ld]();if(T){C&&C[Md]&&T[Oh]&&C[Md](T);var I=!!(S=_getPluginState2(T))[ad];T[ad]&&(I=T[ad]()),I||v[Xc](T),C=T,_=_[Rd]()}}arrForEach2(v,(function(v){var C=g[Ah]();v[id](g.getCfg(),C,f,g[Rd]()),S=_getPluginState2(v),v[Ah]||S[Ah]||(S[Ah]=C),S[ad]=!0,delete S[Ed]}))}function sortPlugins2(g){return g.sort((function(g,f){var S=0;if(f){var v=f[Oh];g[Oh]?S=v?g[Dh]-f[Dh]:1:v&&(S=-1)}else S=g?1:-1;return S}))}function createDistributedTraceContext2(g){var f={};return{getName:function(){return f[dd]},setName:function(S){g&&g.setName(S),f[dd]=S},getTraceId:function(){return f[Qd]},setTraceId:function(S){g&&g.setTraceId(S),isValidTraceId2(S)&&(f[Qd]=S)},getSpanId:function(){return f[Xd]},setSpanId:function(S){g&&g.setSpanId(S),isValidSpanId2(S)&&(f[Xd]=S)},getTraceFlags:function(){return f[Zd]},setTraceFlags:function(S){g&&g.setTraceFlags(S),f[Zd]=S}}}var Sg,vg="TelemetryPluginChain",Cg="_hasRun",yg="_getTelCtx",Eg=0;function _getNextProxyStart2(g,f,S){for(;g;){if(g[ld]()===S)return g;g=g[Rd]()}return createTelemetryProxyChain2([S],f.config||{},f)}function _createInternalContext2(g,f,S,v){var C=null,_=[];f||(f=createDynamicConfig2({},null,S[Yc])),null!==v&&(C=v?_getNextProxyStart2(g,S,v):g);var T={_next:_moveNext,ctx:{core:function(){return S},diagLog:function(){return safeGetLogger2(S,f.cfg)},getCfg:function(){return f.cfg},getExtCfg:_resolveExtCfg,getConfig:_getConfig,hasNext:function(){return!!C},getNext:function(){return C},setNext:function(g){C=g},iterate:_iterateChain,onComplete:_addOnComplete}};function _addOnComplete(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];g&&_[Xc]({func:g,self:isUndefined4(f)?T.ctx:f,args:S})}function _moveNext(){var g=C;if(C=g?g[Rd]():null,!g){var f=_;f&&f[jc]>0&&(arrForEach2(f,(function(g){try{g.func.call(g.self,g.args)}catch(g){_throwInternal2(S[Yc],2,73,"Unexpected Exception during onComplete - "+dumpObj2(g))}})),_=[])}return g}function _getExtCfg(g,S){var v=null,C=f.cfg;if(C&&g){var _=C[Mh];!_&&S&&(_={}),C[Mh]=_,(_=f.ref(C,Mh))&&(!(v=_[g])&&S&&(v={}),_[g]=v,v=f.ref(_,g))}return v}function _resolveExtCfg(g,S){var v=_getExtCfg(g,!0);return S&&objForEachKey2(S,(function(g,S){if(isNullOrUndefined2(v[g])){var C=f.cfg[g];!C&&isNullOrUndefined2(C)||(v[g]=C)}_applyDefaultValue2(f,v,g,S)})),f[Kc](v,S)}function _getConfig(g,S,v){var C;void 0===v&&(v=!1);var _=_getExtCfg(g,!1),T=f.cfg;return!_||!_[S]&&isNullOrUndefined2(_[S])?!T[S]&&isNullOrUndefined2(T[S])||(C=T[S]):C=_[S],C||!isNullOrUndefined2(C)?C:v}function _iterateChain(g){for(var f;f=T._next();){var S=f[ld]();S&&g(S)}}return T}function createProcessTelemetryContext2(g,f,S,v){var C=createDynamicConfig2(f),_=_createInternalContext2(g,C,S,v),T=_.ctx;function _processNext(g){var f=_._next();return f&&f[Oh](g,T),!f}function _createNew(g,f){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain2(g,C.cfg,S,f)),createProcessTelemetryContext2(g||T[Rd](),C.cfg,S,f)}return T[ud]=_processNext,T[yd]=_createNew,T}function createProcessTelemetryUnloadContext2(g,f,S){var v=createDynamicConfig2(f.config),C=_createInternalContext2(g,v,f,S),_=C.ctx;function _processNext(g){var f=C._next();return f&&f[fd](_,g),!f}function _createNew(g,S){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain2(g,v.cfg,f,S)),createProcessTelemetryUnloadContext2(g||_[Rd](),f,S)}return _[ud]=_processNext,_[yd]=_createNew,_}function createProcessTelemetryUpdateContext2(g,f,S){var v=createDynamicConfig2(f.config),C=_createInternalContext2(g,v,f,S).ctx;function _processNext(g){return C.iterate((function(f){hl(f[Pd])&&f[Pd](C,g)}))}function _createNew(g,S){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain2(g,v.cfg,f,S)),createProcessTelemetryUpdateContext2(g||C[Rd](),f,S)}return C[ud]=_processNext,C[yd]=_createNew,C}function createTelemetryProxyChain2(g,f,S,v){var C=null,_=!v;if(ul(g)&&g[jc]>0){var T=null;arrForEach2(g,(function(g){if(_||v!==g||(_=!0),_&&g&&hl(g[Oh])){var I=createTelemetryPluginProxy2(g,f,S);C||(C=I),T&&T._setNext(I),T=I}}))}return v&&!C?createTelemetryProxyChain2([v],f,S):C}function createTelemetryPluginProxy2(g,f,S){var v,C=null,_=hl(g[Oh]),T=hl(g[Md]),I={getPlugin:function(){return g},getNext:function(){return C},processTelemetry:_processTelemetry,unload:_unloadPlugin,update:_updatePlugin,_id:v=g?g[nd]+"-"+g[Dh]+"-"+Eg++:"Unknown-0-"+Eg++,_setNext:function(g){C=g}};function _getTelCtx(){var v;return g&&hl(g[yg])&&(v=g[yg]()),v||(v=createProcessTelemetryContext2(I,f,S)),v}function _processChain(f,S,_,T,I){var b=!1,A=g?g[nd]:vg,P=f[Cg];return P||(P=f[Cg]={}),f.setNext(C),g&&doPerf2(f[Ah](),(function(){return A+":"+_}),(function(){P[v]=!0;try{var g=C?C._id:Ih;g&&(P[g]=!1),b=S(f)}catch(g){var T=!C||P[C._id];T&&(b=!0),C&&T||_throwInternal2(f[bd](),1,73,"Plugin ["+A+"] failed during "+_+" - "+dumpObj2(g)+", run flags: "+dumpObj2(P))}}),T,I),b}function _processTelemetry(f,S){function _callProcessTelemetry(S){if(!g||!_)return!1;var v=_getPluginState2(g);return!v[Ed]&&!v[Rh]&&(T&&g[Md](C),g[Oh](f,S),!0)}_processChain(S=S||_getTelCtx(),_callProcessTelemetry,"processTelemetry",(function(){return{item:f}}),!f.sync)||S[ud](f)}function _unloadPlugin(f,S){function _callTeardown(){var v=!1;if(g){var C=_getPluginState2(g),_=g[Ah]||C[Ah];!g||_&&_!==f.core()||C[Ed]||(C[Ah]=null,C[Ed]=!0,C[ad]=!1,g[Ed]&&!0===g[Ed](f,S)&&(v=!0))}return v}_processChain(f,_callTeardown,"unload",(function(){}),S[Id])||f[ud](S)}function _updatePlugin(f,S){function _callUpdate(){var v=!1;if(g){var C=_getPluginState2(g),_=g[Ah]||C[Ah];!g||_&&_!==f.core()||C[Ed]||g[Pd]&&!0===g[Pd](f,S)&&(v=!0)}return v}_processChain(f,_callUpdate,"update",(function(){}),!1)||f[ud](S)}return Pl(I)}function createUnloadHandlerContainer2(){var g=[];function _addHandler(f){f&&g[Xc](f)}function _runHandlers(f,S){arrForEach2(g,(function(g){try{g(f,S)}catch(g){_throwInternal2(f[bd](),2,73,"Unexpected error calling unload handler - "+dumpObj2(g))}})),g=[]}return{add:_addHandler,run:_runHandlers}}function createUnloadHookContainer2(){var g=[];function _doUnload(f){var S=g;g=[],arrForEach2(S,(function(g){try{(g.rm||g.remove).call(g)}catch(g){_throwInternal2(f,2,73,"Unloading:"+dumpObj2(g))}}))}function _addHook(f){f&&arrAppend2(g,f)}return{run:_doUnload,add:_addHook}}var _g="getPlugin",Tg=((Sg={})[Mh]={isVal:isNotNullOrUndefined2,v:{}},Sg),Ig=function(){function BaseTelemetryPlugin3(){var g,f,S,v,C,_=this;function _getTelCtx(g){void 0===g&&(g=null);var v=g;if(!v){var C=f||createProcessTelemetryContext2(null,{},_[Ah]);v=S&&S[_g]?C[yd](null,S[_g]):C[yd](null,S)}return v}function _setDefaults(g,v,C){createDynamicConfig2(g,Tg,safeGetLogger2(v)),!C&&v&&(C=v[gd]()[Rd]());var T=S;S&&S[_g]&&(T=S[_g]()),_[Ah]=v,f=createProcessTelemetryContext2(C,g,v,T)}function _initDefaults(){g=!1,_[Ah]=null,f=null,S=null,C=createUnloadHookContainer2(),v=createUnloadHandlerContainer2()}_initDefaults(),dynamicProto2(BaseTelemetryPlugin3,_,(function(f){f[id]=function(f,S,v,C){_setDefaults(f,S,C),g=!0},f[Ed]=function(g,_){var T,I=f[Ah];if(I&&(!g||I===g[Ah]())){var b,A=!1,P=g||createProcessTelemetryUnloadContext2(null,I,S&&S[_g]?S[_g]():S),R=_||((T={reason:0})[Id]=!1,T);return f[Ad]&&!0===f[Ad](P,R,_unloadCallback)?b=!0:_unloadCallback(),b}function _unloadCallback(){A||(A=!0,v.run(P,_),C.run(P[bd]()),!0===b&&P[ud](R),_initDefaults())}},f[Pd]=function(g,v){var C=f[Ah];if(C&&(!g||C===g[Ah]())){var _,T=!1,I=g||createProcessTelemetryUpdateContext2(null,C,S&&S[_g]?S[_g]():S),b=v||{reason:0};return f._doUpdate&&!0===f._doUpdate(I,b,_updateCallback)?_=!0:_updateCallback(),_}function _updateCallback(){T||(T=!0,_setDefaults(I.getCfg(),I.core(),I[Rd]()))}},proxyFunctionAs2(f,"_addUnloadCb",(function(){return v}),"add"),proxyFunctionAs2(f,"_addHook",(function(){return C}),"add"),objDefine2(f,"_unloadHooks",{g:function(){return C}})})),_[bd]=function(g){return _getTelCtx(g)[bd]()},_[ad]=function(){return g},_.setInitialized=function(f){g=f},_[Md]=function(g){S=g},_[ud]=function(g,f){f?f[ud](g):S&&hl(S[Oh])&&S[Oh](g,null)},_._getTelCtx=_getTelCtx}return BaseTelemetryPlugin3.__ieDyn=1,BaseTelemetryPlugin3}();function _addInitializer2(g,f,S){var v={id:f,fn:S};return arrAppend2(g,v),{remove:function(){arrForEach2(g,(function(f,S){if(f.id===v.id)return g[Zc](S,1),-1}))}}}function _runInitializers2(g,f,S){for(var v=!1,C=g[jc],_=0;_<C;++_){var T=g[_];if(T)try{if(!1===T.fn[Qc](null,[f])){v=!0;break}}catch(g){_throwInternal2(S,2,64,"Telemetry initializer failed: "+getExceptionName2(g),{exception:dumpObj2(g)},!0)}}return!v}var bg,Ag=function(g){function TelemetryInitializerPlugin22(){var f,S,v=g.call(this)||this;function _initDefaults(){f=0,S=[]}return v.identifier="TelemetryInitializerPlugin",v.priority=199,_initDefaults(),dynamicProto2(TelemetryInitializerPlugin22,v,(function(g,v){g.addTelemetryInitializer=function(g){return _addInitializer2(S,f++,g)},g[Oh]=function(f,v){_runInitializers2(S,f,v?v[bd]():g[bd]())&&g[ud](f,v)},g[Ad]=function(){_initDefaults()}})),v}return __extendsFn2(TelemetryInitializerPlugin22,g),TelemetryInitializerPlugin22.__ieDyn=1,TelemetryInitializerPlugin22}(Ig),Pg="Plugins must provide initialize method",Rg="_notificationManager",Mg="SDK is still unloading...",wg="SDK is not initialized",Og=objDeepFreeze2(((bg={cookieCfg:{}})[wh]={rdOnly:!0,ref:!0,v:[]},bg[bh]={rdOnly:!0,ref:!0,v:[]},bg[Mh]={ref:!0,v:{}},bg[Ph]=Th,bg.loggingLevelConsole=0,bg.diagnosticLogInterval=Th,bg));function _createPerfManager2(g,f){return new ug(f)}function _validateExtensions2(g,f,S){var v,C=[],_=[],T={};return arrForEach2(S,(function(S){(isNullOrUndefined2(S)||isNullOrUndefined2(S[id]))&&throwError2(Pg);var v=S[Dh],I=S[nd];S&&v&&(isNullOrUndefined2(T[v])?T[v]=I:_warnToConsole2(g,"Two extensions have same priority #"+v+" - "+T[v]+", "+I)),!v||v<f?C[Xc](S):_[Xc](S)})),(v={})[Ah]=C,v[bh]=_,v}function _isPluginPresent2(g,f){var S=!1;return arrForEach2(f,(function(f){if(f===g)return S=!0,-1})),S}function _deepMergeConfig2(g,f,S,v){S&&objForEachKey2(S,(function(S,C){v&&isPlainObject2(C)&&isPlainObject2(f[S])&&_deepMergeConfig2(g,f[S],C,v),v&&isPlainObject2(C)&&isPlainObject2(f[S])?_deepMergeConfig2(g,f[S],C,v):g.set(f,S,C)}))}function _findWatcher2(g,f){var S=null,v=-1;return arrForEach2(g,(function(g,C){if(g.w===f)return S=g,v=C,-1})),{i:v,l:S}}function _addDelayedCfgListener2(g,f){var S=_findWatcher2(g,f).l;return S||(S={w:f,rm:function(){var S=_findWatcher2(g,f);-1!==S.i&&g[Zc](S.i,1)}},g[Xc](S)),S}function _registerDelayedCfgListener2(g,f,S){arrForEach2(f,(function(f){var v=onConfigChange2(g,f.w,S);delete f.w,f.rm=function(){v.rm()}}))}function _initDebugListener2(g,f,S,v){return f.add(g[Jc]((function(g){var f=g.cfg.disableDbgExt;!0===f&&v&&(S[rd](v),v=null),S&&!v&&!0!==f&&(v=getDebugListener2(g.cfg),S[sd](v))}))),v}function _createUnloadHook2(g){return objDefine2({rm:function(){g.rm()}},"toJSON",{v:function(){return"aicore::onCfgChange<"+JSON.stringify(g)+">"}})}var Dg=function(){function AppInsightsCore4(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G;dynamicProto2(AppInsightsCore4,this,(function(q){function _startLogPoller(f){return $&&$[pd]||G||(f||S&&S.queue[jc]>0)&&(j||(j=!0,_addUnloadHook(g[Jc]((function(g){var f=g.cfg.diagnosticLogInterval;f&&f>0||(f=1e4);var S=!1;$&&(S=$[pd],$[td]()),($=createTimeout2(_flushInternalLogs,f)).unref(),$[pd]=S})))),$[pd]=!0),$}function _setPluginVersions(){var g={};B=[];var _addPluginVersions=function(f){f&&arrForEach2(f,(function(f){if(f[nd]&&f[vd]&&!g[f.identifier]){var S=f[nd]+"="+f[vd];B[Xc](S),g[f.identifier]=f}}))};_addPluginVersions(R),P&&arrForEach2(P,(function(g){_addPluginVersions(g)})),_addPluginVersions(A)}function _initDefaults(){f=!1,(g=createDynamicConfig2({},Og,q[Yc])).cfg[Cd]=1,objDefine2(q,"config",{g:function(){return g.cfg},s:function(g){q.updateCfg(g,!1)}}),objDefine2(q,"pluginVersionStringArr",{g:function(){return B||_setPluginVersions(),B}}),objDefine2(q,"pluginVersionString",{g:function(){return H||(B||_setPluginVersions(),H=B.join(";")),H||Ih}}),objDefine2(q,"logger",{g:function(){return S||(S=new Gu(g.cfg),g[Yc]=S),S},s:function(f){g[Yc]=f,S!==f&&(runTargetUnload2(S,!1),S=f)}}),q[Yc]=new Gu(g.cfg),V=[];var L=q.config[wh]||[];L.splice(0,L[jc]),arrAppend2(L,V),w=new Ag,v=[],runTargetUnload2(C,!1),C=null,_=null,T=null,runTargetUnload2(I,!1),I=null,b=null,A=[],P=null,R=null,M=!1,O=null,D=createUniqueNamespace2("AIBaseCore",!0),N=createUnloadHandlerContainer2(),F=null,x=null,k=createUnloadHookContainer2(),U=[],H=null,B=null,G=!1,$=null,j=!1}function _createTelCtx(){var f=createProcessTelemetryContext2(_getPluginChain(),g.cfg,q);return f[Sd](_startLogPoller),f}function _initPluginChain(g){var f=_validateExtensions2(q[Yc],Mu,A);b=null,H=null,B=null,R=sortPlugins2(arrAppend2(R=(P||[])[0]||[],f[bh]));var S=arrAppend2(sortPlugins2(f[Ah]),R);V=Pl(S);var v=q.config[wh]||[];v.splice(0,v[jc]),arrAppend2(v,V);var C=_createTelCtx();R&&R[jc]>0&&initializePlugins2(C[yd](R),S),initializePlugins2(C,S),g&&_doUpdate(g)}function _getPlugin(g){var f=null,S=null,v=[];return arrForEach2(V,(function(f){if(f[nd]===g&&f!==w)return S=f,-1;f.getChannel&&v[Xc](f)})),!S&&v[jc]>0&&arrForEach2(v,(function(f){if(!(S=f.getChannel(g)))return-1})),S&&(f={plugin:S,setEnabled:function(g){_getPluginState2(S)[Rh]=!g},isEnabled:function(){var g=_getPluginState2(S);return!g[Ed]&&!g[Rh]},remove:function(g,f){var v;void 0===g&&(g=!0);var C=[S],_=((v={reason:1})[Id]=g,v);_removePlugins(C,_,(function(g){g&&_initPluginChain({reason:32,removed:C}),f&&f(g)}))}}),f}function _getPluginChain(){if(!b){var f=(V||[]).slice();-1===Yl(f,w)&&f[Xc](w),b=createTelemetryProxyChain2(sortPlugins2(f),g.cfg,q)}return b}function _removePlugins(f,S,v){if(f&&f[jc]>0){var C=createProcessTelemetryUnloadContext2(createTelemetryProxyChain2(f,g.cfg,q),q);C[Sd]((function(){var g=!1,S=[];arrForEach2(A,(function(v,C){_isPluginPresent2(v,f)?g=!0:S[Xc](v)})),A=S,H=null,B=null;var C=[];P&&(arrForEach2(P,(function(S,v){var _=[];arrForEach2(S,(function(S){_isPluginPresent2(S,f)?g=!0:_[Xc](S)})),C[Xc](_)})),P=C),v&&v(g),_startLogPoller()})),C[ud](S)}else v(!1)}function _flushInternalLogs(){if(S&&S.queue){var g=S.queue.slice(0);S.queue[jc]=0,arrForEach2(g,(function(g){var f,S=((f={})[dd]=O||"InternalMessageId: "+g[_d],f.iKey=x,f[hd]=toISOString2(new Date),f.baseType=Hu.dataType,f.baseData={message:g[Td]},f);q.track(S)}))}}function _flushChannels(g,f,S,v){var C=1,_=!1,T=null;function doCallback(){C--,_&&0===C&&(T&&T[td](),T=null,f&&f(_),f=null)}return v=v||5e3,R&&R[jc]>0&&_createTelCtx()[yd](R).iterate((function(f){if(f.flush){C++;var _=!1;f.flush(g,(function(){_=!0,doCallback()}),S)||_||(g&&null==T?T=scheduleTimeout2((function(){T=null,doCallback()}),v):doCallback())}})),_=!0,doCallback(),!0}function _initPerfManager(){var f;_addUnloadHook(g[Jc]((function(g){if(g.cfg.enablePerfMgr){var S=g.cfg[Ph];f!==S&&(S||(S=_createPerfManager2),getSetValue2(g.cfg,Ph,S),f=S,T=null),_||T||!hl(S)||(T=S(q,q[od]()))}else T=null,f=null})))}function _doUpdate(g){var f=createProcessTelemetryUpdateContext2(_getPluginChain(),q);f[Sd](_startLogPoller),q._updateHook&&!0===q._updateHook(f,g)||f[ud](g)}function _logOrThrowError(g){var f=q[Yc];f?(_throwInternal2(f,2,73,g),_startLogPoller()):throwError2(g)}function _notifyInvalidEvent(g){var f=q[od]();f&&f[kh]([g],2)}function _addUnloadHook(g){k.add(g)}_initDefaults(),q._getDbgPlgTargets=function(){return[V]},q[ad]=function(){return f},q[id]=function(v,_,T,I){M&&throwError2(Mg),q[ad]()&&throwError2("Core cannot be initialized more than once"),v=(g=createDynamicConfig2(v,Og,T||q[Yc],!1)).cfg,_addUnloadHook(g[Jc]((function(g){x=g.cfg.instrumentationKey;var f=g.ref(g.cfg,Mh);objForEachKey2(f,(function(S){g.ref(f,S)})),isNullOrUndefined2(x)&&throwError2("Please provide instrumentation key")}))),L=_initDebugListener2(g,k,(C=I)&&q[od](),L),_initPerfManager(),q[Yc]=T;var b=v[wh];if((A=[])[Xc].apply(A,__spreadArrayFn2(__spreadArrayFn2([],_,!1),b)),P=v[bh],_initPluginChain(null),R&&0!==R[jc]||throwError2("No "+bh+" available"),P&&P[jc]>1){var w=q[ld]("TeeChannelController");w&&w.plugin||_throwInternal2(S,1,28,"TeeChannel required")}_registerDelayedCfgListener2(v,U,S),U=null,f=!0,q.releaseQueue(),q[cd]()},q.getChannels=function(){var g=[];return R&&arrForEach2(R,(function(f){g[Xc](f)})),Pl(g)},q.track=function(g){doPerf2(q[Bh](),(function(){return"AppInsightsCore:track"}),(function(){null===g&&(_notifyInvalidEvent(g),throwError2("Invalid telemetry item")),!g[dd]&&isNullOrUndefined2(g[dd])&&(_notifyInvalidEvent(g),throwError2("telemetry name required")),g.iKey=g.iKey||x,g[hd]=g[hd]||toISOString2(new Date),g.ver=g.ver||"4.0",!M&&q[ad]()?_createTelCtx()[ud](g):v[Xc](g)}),(function(){return{item:g}}),!g.sync)},q[gd]=_createTelCtx,q[od]=function(){return C||(C=new ag(g.cfg),q[Rg]=C),C},q[sd]=function(g){q.getNotifyMgr()[sd](g)},q[rd]=function(g){C&&C[rd](g)},q.getCookieMgr=function(){return I||(I=createCookieMgr2(g.cfg,q[Yc])),I},q.setCookieMgr=function(g){I!==g&&(runTargetUnload2(I,!1),I=g)},q[Bh]=function(){return _||T||getGblPerfMgr2()},q.setPerfMgr=function(g){_=g},q.eventCnt=function(){return v[jc]},q.releaseQueue=function(){if(f&&v[jc]>0){var g=v;v=[],arrForEach2(g,(function(g){_createTelCtx()[ud](g)}))}},q[cd]=function(g){return O=g||null,G=!1,$&&$[td](),_startLogPoller(!0)},q[md]=function(){G=!0,$&&$[td](),_flushInternalLogs()},proxyFunctions2(q,(function(){return w}),["addTelemetryInitializer"]),q[fd]=function(g,v,_){var T;void 0===g&&(g=!0),f||throwError2(wg),M&&throwError2(Mg);var b,A=((T={reason:50})[Id]=g,T.flushComplete=!1,T);g&&!v&&(b=createPromise2((function(g){v=g})));var P=createProcessTelemetryUnloadContext2(_getPluginChain(),q);function _doUnload(g){A.flushComplete=g,M=!0,N.run(P,A),q[md](),P[ud](A)}return P[Sd]((function(){k.run(q[Yc]),doUnloadAll2([I,C,S],g,(function(){_initDefaults(),v&&v(A)}))}),q),_flushInternalLogs(),_flushChannels(g,_doUnload,6,_),b},q[ld]=_getPlugin,q.addPlugin=function(g,f,S,v){if(!g)return v&&v(!1),void _logOrThrowError(Pg);var C=_getPlugin(g[nd]);if(C&&!f)return v&&v(!1),void _logOrThrowError("Plugin ["+g[nd]+"] is already loaded!");var _={reason:16};function _addPlugin(f){A[Xc](g),_.added=[g],_initPluginChain(_),v&&v(!0)}if(C){var T=[C.plugin];_removePlugins(T,{reason:2,isAsync:!!S},(function(g){g?(_.removed=T,_.reason|=32,_addPlugin()):v&&v(!1)}))}else _addPlugin()},q.updateCfg=function(f,S){var v;if(void 0===S&&(S=!0),q[ad]()){v={reason:1,cfg:g.cfg,oldCfg:deepExtend2({},g.cfg),newConfig:deepExtend2({},f),merge:S},f=v.newConfig;var C=g.cfg;f[wh]=C[wh],f[bh]=C[bh]}g._block((function(g){var v=g.cfg;_deepMergeConfig2(g,v,f,S),S||objForEachKey2(v,(function(S){vl(f,S)||g.set(v,S,Th)})),g[Kc](v,Og)}),!0),g[qc](),v&&_doUpdate(v)},q.evtNamespace=function(){return D},q.flush=_flushChannels,q.getTraceCtx=function(g){return F||(F=createDistributedTraceContext2()),F},q.setTraceCtx=function(g){F=g||null},q.addUnloadHook=_addUnloadHook,proxyFunctionAs2(q,"addUnloadCb",(function(){return N}),"add"),q.onCfgChange=function(S){return _createUnloadHook2(f?onConfigChange2(g.cfg,S,q[Yc]):_addDelayedCfgListener2(U,S))},q.getWParam=function(){return hasDocument2()||g.cfg.enableWParam?0:-1}}))}return AppInsightsCore4.__ieDyn=1,AppInsightsCore4}(),Ng="",kg="&NoResponseBody=true",Lg="POST",Fg=function(){function SenderPostManager3(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w=0;dynamicProto2(SenderPostManager3,this,(function(O,D){var N=!0;function _onSuccess(g,f){_doOnComplete(f,200,{},g)}function _onError(g,f){_throwInternal2(S,2,26,"Failed to send telemetry.",{message:g}),_doOnComplete(f,400,{})}function _onNoPayloadUrl(g){_onError("No endpoint url is provided for the batch",g)}function _getSenderInterface(g,f){for(var S,v=0,C=null,_=0;null==C&&_<g[jc];)v=g[_],I||1!==v?2!==v||!isFetchSupported2(f)||f&&P?3!==v||!isBeaconsSupported2()||(f?A:b)||(C=_beaconSender):C=_doFetchSender:useXDomainRequest2()?C=_xdrSender:isXhrSupported2()&&(C=_xhrSender),_++;return C?((S={_transport:v,_isSync:f})[zd]=C,S):null}function _doOnComplete(g,f,S,v){try{g&&g(f,S,v)}catch(g){}}function _doBeaconSend(g,f){var S=Kl(),C=g[Wd];if(!C)return _onNoPayloadUrl(f),!0;C=g[Wd]+(R?kg:Ng);var _=g[$d],T=v?_:new Blob([_],{type:"text/plain;charset=UTF-8"});return S.sendBeacon(C,T)}function _beaconSender(g,f,_){var I=g[$d];try{if(I)if(_doBeaconSend(g,f))_onSuccess(Ng,f);else{var b=C&&C.beaconOnRetry;b&&hl(b)?b(g,f,_doBeaconSend):(T&&T[zd](g,f,!0),_throwInternal2(S,2,40,". Failed to send telemetry with Beacon API, retried with normal sender."))}}catch(g){v&&_warnToConsole2(S,"Failed to send telemetry using sendBeacon API. Ex:"+dumpObj2(g)),_doOnComplete(f,v?0:400,{},Ng)}}function _xhrSender(f,S,_){var T,I,b,A=f[Kd]||{};!_&&g&&(T=createPromise2((function(g,f){I=g,b=f}))),v&&_&&f.disableXhrSync&&(_=!1);var P=f[Wd];if(!P)return _onNoPayloadUrl(S),void(I&&I(!1));var R=openXhr3(Lg,P,N,!0,_,f[Jd]);function _doOnReadyFunc(g){var _=C&&C.xhrOnComplete;if(_&&hl(_))_(g,S,f);else{var T=getResponseText2(g);_doOnComplete(S,g[Ud],_getAllResponseHeaders2(g,v),T)}}return v||R[Yd]("Content-type","application/json"),arrForEach2(Al(A),(function(g){R[Yd](g,A[g])})),R.onreadystatechange=function(){v||(_doOnReadyFunc(R),4===R.readyState&&I&&I(!0))},R.onload=function(){v&&_doOnReadyFunc(R)},R.onerror=function(g){_doOnComplete(S,v?R[Ud]:400,_getAllResponseHeaders2(R,v),v?Ng:formatErrorMessageXhr2(R)),b&&b(g)},R.ontimeout=function(){_doOnComplete(S,v?R[Ud]:500,_getAllResponseHeaders2(R,v),v?Ng:formatErrorMessageXhr2(R)),I&&I(!1)},R.send(f[$d]),T}function _doFetchSender(f,S,_){var T,I,b,A,P=f[Wd],O=f[$d],D=v?O:new Blob([O],{type:"application/json"}),k=new Headers,L=O[jc],F=!1,x=!1,U=f[Kd]||{},V=((T={method:Lg,body:D})[wu]=!0,T);f.headers&&Al(f.headers)[jc]>0&&(arrForEach2(Al(U),(function(g){k.append(g,U[g])})),V[Kd]=k),N&&v&&(V.credentials="include"),_&&(V.keepalive=!0,w+=L,v?2===f._sendReason&&(F=!0,R&&(P+=kg)):F=!0);var B=new Request(P,V);try{B[wu]=!0}catch(g){}if(!_&&g&&(I=createPromise2((function(g,f){b=g,A=f}))),!P)return _onNoPayloadUrl(S),void(b&&b(!1));function _handleError(g){_doOnComplete(S,v?0:400,{},v?Ng:g)}function _onFetchComplete(g,f,v){var _=g[Ud],T=C.fetchOnComplete;T&&hl(T)?T(g,S,v||Ng,f):_doOnComplete(S,_,{},v||Ng)}try{doAwaitResponse2(fetch(v?P:B,v?V:null),(function(g){if(_&&(w-=L,L=0),!x)if(x=!0,g.rejected)_handleError(g.reason&&g.reason[Td]),A&&A(g.reason);else{var S=g.value;try{v||S.ok?v&&!S.body?(_onFetchComplete(S,null,Ng),b&&b(!0)):doAwaitResponse2(S.text(),(function(g){_onFetchComplete(S,f,g.value),b&&b(!0)})):(_handleError(S.statusText),b&&b(!1))}catch(g){_handleError(dumpObj2(g)),A&&A(g)}}}))}catch(g){x||(_handleError(dumpObj2(g)),A&&A(g))}return F&&!x&&(x=!0,_doOnComplete(S,200,{}),b&&b(!0)),v&&!x&&f[Jd]>0&&M&&M.set((function(){x||(x=!0,_doOnComplete(S,500,{}),b&&b(!0))}),f[Jd]),I}function _xdrSender(g,f,_){var T=Gl(),I=new XDomainRequest,b=g[$d];I.onload=function(){var S=getResponseText2(I),v=C&&C.xdrOnComplete;v&&hl(v)?v(I,f,g):_doOnComplete(f,200,{},S)},I.onerror=function(){_doOnComplete(f,400,{},v?Ng:formatErrorMessageXdr2(I))},I.ontimeout=function(){_doOnComplete(f,500,{})},I.onprogress=function(){};var A=T&&T.location&&T.location[wd]||"",P=g[Wd];if(P){if(!v&&0!==P.lastIndexOf(A,0)){var R="Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.";return _throwInternal2(S,2,40,". "+R),void _onError(R,f)}var w=v?P:P[kd](/^(https?:)/,"");I.open(Lg,w),g[Jd]&&(I[Jd]=g[Jd]),I.send(b),v&&_?M&&M.set((function(){I.send(b)}),0):I.send(b)}else _onNoPayloadUrl(f)}function _initDefaults(){w=0,f=!1,g=!1,S=null,v=null,C=null,_=null,T=null,I=!1,b=!1,A=!1,P=!1,R=!1,M=null}_initDefaults(),O[id]=function(g,v){S=v,f&&_throwInternal2(S,1,28,"Sender is already initialized"),O.SetConfig(g),f=!0},O._getDbgPlgTargets=function(){return[f,v,_,g]},O.SetConfig=function(f){try{if(C=f.senderOnCompleteCallBack||{},_=!!f.disableCredentials,v=!!f.isOneDs,g=!!f.enableSendPromise,I=!!f.disableXhr,b=!!f.disableBeacon,A=!!f.disableBeaconSync,M=f.timeWrapper,R=!!f.addNoResponse,P=!!f.disableFetchKeepAlive,T={sendPOST:_xhrSender},v||(N=!1),_){var S=getLocation2();S&&S.protocol&&"file:"===S.protocol[Hc]()&&(N=!1)}return!0}catch(g){}return!1},O.getSyncFetchPayload=function(){return w},O.getSenderInst=function(g,f){return g&&g[jc]?_getSenderInterface(g,f):null},O.getFallbackInst=function(){return T},O[Ad]=function(g,f){_initDefaults()}}))}return SenderPostManager3.__ieDyn=1,SenderPostManager3}(),xg="on",Ug="attachEvent",Vg="addEventListener",Bg="detachEvent",Hg="removeEventListener",$g="events",jg="visibilitychange",Gg="pagehide",qg="pageshow",Wg="unload",zg="beforeunload",Kg=createUniqueNamespace2("aiEvtPageHide"),Jg=createUniqueNamespace2("aiEvtPageShow"),Yg=/\.[\.]+/g,Qg=/[\.]+$/,Xg=1,Zg=createElmNodeData2("events"),ep=/^([^.]*)(?:\.(.+)|)/;function _normalizeNamespace2(g){return g&&g[kd]?g[kd](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g,Ih):g}function _getEvtNamespace2(g,f){var S;if(f){var v=Ih;ul(f)?(v=Ih,arrForEach2(f,(function(g){(g=_normalizeNamespace2(g))&&("."!==g[0]&&(g="."+g),v+=g)}))):v=_normalizeNamespace2(f),v&&("."!==v[0]&&(v="."+v),g=(g||Ih)+v)}var C=ep.exec(g||Ih)||[];return(S={})[Fd]=C[1],S.ns=(C[2]||Ih).replace(Yg,".").replace(Qg,Ih)[Dd](".").sort().join("."),S}function _getRegisteredEvents2(g,f,S){void 0===S&&(S=!0);var v=Zg.get(g,$g,{},S),C=v[f];return C||(C=v[f]=[]),C}function _doDetach2(g,f,S,v){g&&f&&f[Fd]&&(g[Hg]?g[Hg](f[Fd],S,v):g[Bg]&&g[Bg](xg+f[Fd],S))}function _doAttach2(g,f,S,v){var C=!1;return g&&f&&f[Fd]&&S&&(g[Vg]?(g[Vg](f[Fd],S,v),C=!0):g[Ug]&&(g[Ug](xg+f[Fd],S),C=!0)),C}function _doUnregister2(g,f,S,v){for(var C=f[jc];C--;){var _=f[C];_&&(S.ns&&S.ns!==_.evtName.ns||v&&!v(_)||(_doDetach2(g,_.evtName,_[xd],_.capture),f[Zc](C,1)))}}function _unregisterEvents2(g,f,S){if(f[Fd])_doUnregister2(g,_getRegisteredEvents2(g,f[Fd]),f,S);else{var v=Zg.get(g,$g,{});objForEachKey2(v,(function(v,C){_doUnregister2(g,C,f,S)})),0===Al(v)[jc]&&Zg.kill(g,$g)}}function mergeEvtNamespace2(g,f){return f?_getEvtNamespace2("xx",ul(f)?[g].concat(f):[g,f]).ns[Dd]("."):g}function eventOn2(g,f,S,v,C){var _;void 0===C&&(C=!1);var T=!1;if(g)try{var I=_getEvtNamespace2(f,v);if((T=_doAttach2(g,I,S,C))&&Zg.accept(g)){var b=((_={guid:Xg++,evtName:I})[xd]=S,_.capture=C,_);_getRegisteredEvents2(g,I.type)[Xc](b)}}catch(g){}return T}function eventOff2(g,f,S,v,C){if(void 0===C&&(C=!1),g)try{var _=_getEvtNamespace2(f,v),T=!1;_unregisterEvents2(g,_,(function(g){return!((!_.ns||S)&&g[xd]!==S||(T=!0,0))})),T||_doDetach2(g,_,S,C)}catch(g){}}function addEventHandler2(g,f,S){var v=!1,C=Gl();C&&(v=eventOn2(C,g,f,S),v=eventOn2(C.body,g,f,S)||v);var _=jl();return _&&(v=eventOn2(_,g,f,S)||v),v}function removeEventHandler2(g,f,S){var v=Gl();v&&(eventOff2(v,g,f,S),eventOff2(v.body,g,f,S));var C=jl();C&&eventOff2(C,g,f,S)}function _addEventListeners2(g,f,S,v){var C=!1;return f&&g&&g[jc]>0&&arrForEach2(g,(function(g){g&&(S&&-1!==Yl(S,g)||(C=addEventHandler2(g,f,v)||C))})),C}function addEventListeners2(g,f,S,v){var C=!1;return f&&g&&ul(g)&&!(C=_addEventListeners2(g,f,S,v))&&S&&S[jc]>0&&(C=_addEventListeners2(g,f,null,v)),C}function removeEventListeners2(g,f,S){g&&ul(g)&&arrForEach2(g,(function(g){g&&removeEventHandler2(g,f,S)}))}function addPageUnloadEventListener2(g,f,S){return addEventListeners2([zg,Wg,Gg],g,f,S)}function removePageUnloadEventListener2(g,f){removeEventListeners2([zg,Wg,Gg],g,f)}function addPageHideEventListener2(g,f,S){function _handlePageVisibility(f){var S=jl();g&&S&&"hidden"===S.visibilityState&&g(f)}var v=mergeEvtNamespace2(Kg,S),C=_addEventListeners2([Gg],g,f,v);return f&&-1!==Yl(f,jg)||(C=_addEventListeners2([jg],_handlePageVisibility,f,v)||C),!C&&f&&(C=addPageHideEventListener2(g,null,S)),C}function removePageHideEventListener2(g,f){var S=mergeEvtNamespace2(Kg,f);removeEventListeners2([Gg],g,S),removeEventListeners2([jg],null,S)}function addPageShowEventListener2(g,f,S){function _handlePageVisibility(f){var S=jl();g&&S&&"visible"===S.visibilityState&&g(f)}var v=mergeEvtNamespace2(Jg,S),C=_addEventListeners2([qg],g,f,v);return!(C=_addEventListeners2([jg],_handlePageVisibility,f,v)||C)&&f&&(C=addPageShowEventListener2(g,null,S)),C}function removePageShowEventListener2(g,f){var S=mergeEvtNamespace2(Jg,f);removeEventListeners2([qg],g,S),removeEventListeners2([jg],null,S)}var tp,ip="",np="https://browser.events.data.microsoft.com/OneCollector/1.0/",rp="version",sp="properties",ap="initialize",op="logger",lp="indexOf",cp="timings",dp="pollInternalLogs",hp="value",up="kind",gp="length",pp="processTelemetryStart",mp="1DS-Web-JS-4.2.1",fp=Vo.hasOwnProperty,Sp=((tp={})[0]=0,tp[2]=6,tp[1]=1,tp[3]=7,tp[4098]=6,tp[4097]=1,tp[4099]=7,tp);function isValueAssigned2(g){return!(g===ip||isNullOrUndefined2(g))}function getTenantId2(g){if(g){var f=oc(g,"-");if(f>-1)return strLeft2(g,f)}return ip}function isLatency2(g){return!!(g&&pl(g)&&g>=1&&g<=4)}function sanitizeProperty2(g,f,S){if(!f&&!isValueAssigned2(f)||"string"!=typeof g)return null;var v=typeof f;if("string"===v||"number"===v||"boolean"===v||ul(f))f={value:f};else if("object"!==v||fp.call(f,"value")){if(isNullOrUndefined2(f[hp])||f[hp]===ip||!dl(f[hp])&&!pl(f[hp])&&!ml(f[hp])&&!ul(f[hp]))return null}else f={value:S?JSON.stringify(f):f};if(ul(f[hp])&&!isArrayValid2(f[hp]))return null;if(!isNullOrUndefined2(f[up])){if(ul(f[hp])||!isValueKind2(f[up]))return null;f[hp]=f[hp].toString()}return f}function getCommonSchemaMetaData2(g,f,S){var v=-1;if(!isUndefined4(g))if(f>0&&(32===f?v=8192:f<=13&&(v=f<<5)),isDataType2(S))-1===v&&(v=0),v|=S;else{var C=Sp[getFieldValueType2(g)]||-1;-1!==v&&-1!==C?v|=C:6===C&&(v=C)}return v}function getCookieValue2(g,f,S){var v;return void 0===S&&(S=!0),g&&(v=g.get(f),S&&v&&decodeURIComponent&&(v=decodeURIComponent(v))),v||ip}function createGuid2(g){void 0===g&&(g="D");var f=newGuid22();return"B"===g?f="{"+f+"}":"P"===g?f="("+f+")":"N"===g&&(f=f.replace(/-/g,ip)),f}function extend2(g,f,S,v,C){var _={},T=!1,I=0,b=arguments[gp],A=arguments;for(ml(A[0])&&(T=A[0],I++);I<b;I++)objForEachKey2(A[I],(function(g,f){T&&f&&isObject3(f)?ul(f)?(_[g]=_[g]||[],arrForEach2(f,(function(f,S){_[g][S]=f&&isObject3(f)?extend2(!0,_[g][S],f):f}))):_[g]=extend2(!0,_[g],f):_[g]=f}));return _}var vp=perfNow2;function isValueKind2(g){return 0===g||g>0&&g<=13||32===g}function isDataType2(g){return g>=0&&g<=9}function isArrayValid2(g){return g[gp]>0}function setProcessTelemetryTimings2(g,f){var S=g;S[cp]=S[cp]||{},S[cp][pp]=S[cp][pp]||{},S[cp][pp][f]=vp()}function getFieldValueType2(g){var f=0;if(null!=g){var S=typeof g;"string"===S?f=1:"number"===S?f=2:"boolean"===S?f=3:S===Lo&&(f=4,ul(g)?(f=4096,g[gp]>0&&(f|=getFieldValueType2(g[0]))):fp.call(g,"value")&&(f=8192|getFieldValueType2(g[hp])))}return f}function isChromium2(){return!!getInst2("chrome")}function isGreaterThanZero2(g){return g>0}var Cp=objDeepFreeze2({endpointUrl:np,propertyStorageOverride:{isVal:_chkPropOverride2}});function _chkPropOverride2(g){return!g||g.getProperty&&g.setProperty||throwError2("Invalid property storage override passed."),!0}var yp=function(g){function AppInsightsCore4(){var f=g.call(this)||this;return dynamicProto2(AppInsightsCore4,f,(function(g,f){g[ap]=function(S,v,C,_){doPerf2(g,(function(){return"AppInsightsCore.initialize"}),(function(){try{f[ap](createDynamicConfig2(S,Cp,C||g[op],!1).cfg,v,C,_)}catch(f){var T=g[op],I=dumpObj2(f);-1!==I[lp]("channels")&&(I+="\n - Channels must be provided through config.channels only!"),_throwInternal2(T,1,514,"SDK Initialization Failed - no telemetry will be sent: "+I)}}),(function(){return{config:S,extensions:v,logger:C,notificationManager:_}}))},g.track=function(S){doPerf2(g,(function(){return"AppInsightsCore.track"}),(function(){var v=S;if(v){v[cp]=v[cp]||{},v[cp].trackStart=vp(),isLatency2(v.latency)||(v.latency=1);var C=v.ext=v.ext||{};C.sdk=C.sdk||{},C.sdk.ver=mp;var _=v.baseData=v.baseData||{};_[sp]=_[sp]||{};var T=_[sp];T[rp]=T[rp]||g.pluginVersionString||ip}f.track(v)}),(function(){return{item:S}}),!S.sync)},g[dp]=function(g){return f[dp](g||"InternalLog")}})),f}return __extendsFn2(AppInsightsCore4,g),AppInsightsCore4.__ieDyn=1,AppInsightsCore4}(Dg),Ep=Uc({Normal:1,CostDeferred:2,RealTime:3,Immediate:4}),_p=Uc({Normal:1,Critical:2}),Tp="REAL_TIME",Ip="NEAR_REAL_TIME",bp="BEST_EFFORT",Ap="",Pp="drop",Rp="send",Mp="requeue",wp="rspFail",Op="oth",Dp="no-cache, no-store",Np="application/x-json-stream",kp="cache-control",Lp="content-type",Fp="kill-tokens",xp="kill-duration",Up="time-delta-millis",Vp="client-version",Bp="client-id",Hp="time-delta-to-apply-millis",$p="upload-time",jp="apikey",Gp="AuthMsaDeviceTicket",qp="WebAuthToken",Wp="AuthXToken",zp="NoResponseBody",Kp="msfpc",Jp="trace",Yp="user",Qp="allowRequestSending",Xp="firstRequestSent",Zp="shouldAddClockSkewHeaders",em="getClockSkewHeaderValue",tm="setClockSkew",im="length",nm="concat",rm="iKey",sm="count",am="events",om="push",lm="split",cm="splice",dm="toLowerCase",hm="hdrs",um="useHdrs",gm="initialize",pm="setTimeoutOverride",mm="clearTimeoutOverride",fm="payloadPreprocessor",Sm="overrideEndpointUrl",vm="avoidOptions",Cm="disableEventTimings",ym="stringifyObjects",Em="enableCompoundKey",_m="disableXhrSync",Tm="disableFetchKeepAlive",Im="addNoResponse",bm="excludeCsMetaData",Am="useSendBeacon",Pm="alwaysUseXhrOverride",Rm="unloadTransports",Mm="serializeOfflineEvt",wm="getOfflineRequestDetails",Om="createPayload",Dm="createOneDSPayload",Nm="payloadBlob",km="headers",Lm="_thePayload",Fm="urlString",xm="batches",Um="sendType",Vm="addHeader",Bm="canSendRequest",Hm="sendQueuedRequests",$m="isCompletelyIdle",jm="setUnloading",Gm="isTenantKilled",qm="sendSynchronousBatch",Wm="_transport",zm="getWParam",Km="isBeacon",Jm="timings",Ym="isTeardown",Qm="isSync",Xm="data",Zm="timeout",ef="_sendReason",tf="setKillSwitchTenants",nf="_backOffTransmission",rf="identifier",sf="disableOptimizeObj",af="ignoreMc1Ms0CookieProcessing",of="eventsLimitInMem",lf="autoFlushEventsLimit",cf="disableAutoBatchFlushLimit",df="overrideInstrumentationKey",hf="disableTelemetry",uf="baseData",gf="sendAttempt",pf="latency",mf="sync";function _getEventMsfpc2(g){var f=(g.ext||{}).intweb;return f&&isValueAssigned2(f[Kp])?f[Kp]:null}function _getMsfpc3(g){for(var f=null,S=0;null===f&&S<g[im];S++)f=_getEventMsfpc2(g[S]);return f}var ff=function(){function EventBatch22(g,f){var S=f?[][nm](f):[],v=this,C=_getMsfpc3(S);v[rm]=function(){return g},v.Msfpc=function(){return C||Ap},v[sm]=function(){return S[im]},v[am]=function(){return S},v.addEvent=function(g){return!!g&&(S[om](g),C||(C=_getEventMsfpc2(g)),!0)},v[lm]=function(f,v){var _;if(f<S[im]){var T=S[im]-f;isNullOrUndefined2(v)||(T=v<T?v:T),_=S[cm](f,T),C=_getMsfpc3(S)}return new EventBatch22(g,_)}}return EventBatch22.create=function(g,f){return new EventBatch22(g,f)},EventBatch22}(),Sf=function(){function ClockSkewManager22(){var g=!0,f=!0,S=!0,v="use-collector-delta",C=!1;dynamicProto2(ClockSkewManager22,this,(function(_){_[Qp]=function(){return g},_[Xp]=function(){S&&(S=!1,C||(g=!1))},_[Zp]=function(){return f},_[em]=function(){return v},_[tm]=function(S){C||(S?(v=S,f=!0,C=!0):f=!1,g=!0)}}))}return ClockSkewManager22.__ieDyn=1,ClockSkewManager22}(),vf=1e3,Cf=function(){function KillSwitch22(){var g={};function _normalizeTenants(g){var f=[];return g&&arrForEach2(g,(function(g){f[om](nc(g))})),f}dynamicProto2(KillSwitch22,this,(function(f){f[tf]=function(f,S){if(f&&S)try{var v=_normalizeTenants(f[lm](","));if("this-request-only"===S)return v;for(var C=parseInt(S,10)*vf,_=0;_<v[im];++_)g[v[_]]=utcNow2()+C}catch(g){return[]}return[]},f[Gm]=function(f){var S=g,v=nc(f);return void 0!==S[v]&&S[v]>utcNow2()||(delete S[v],!1)}}))}return KillSwitch22.__ieDyn=1,KillSwitch22}(),yf=.8,Ef=1.2,_f=3e3,Tf=6e5;function retryPolicyShouldRetryForStatus2(g){return!(g>=300&&g<500&&429!=g||501==g||505==g)}function retryPolicyGetMillisToBackoffForRetry2(g){var f=0,S=_f*yf,v=_f*Ef,C=Math.floor(Math.random()*(v-S))+S;return f=Math.pow(2,g)*C,Math.min(f,Tf)}var If,bf=20,Af=3984588,Pf=65e3,Rf=2e6,Mf=Math.min(Rf,Pf),wf="metadata",Of="f",Df=/\./,Nf=function(){function Serializer22(g,f,S,v,C,_){var T="data",I="baseData",b="ext",A=!!v,P=!0,R=f,M={},w=!!_,O=C||getCommonSchemaMetaData2;dynamicProto2(Serializer22,this,(function(f){function _isReservedField(g,f){var S=M[g];return void 0===S&&(g.length>=7&&(S=lc(g,"ext.metadata")||lc(g,"ext.web")),M[g]=S),S}function _processPathKeys(g,f,v,C,_,T,I){objForEachKey2(g,(function(g,b){var P=null;if(b||isValueAssigned2(b)){var M=v,w=g,O=_,D=f;if(A&&!C&&Df.test(g)){var N=g.split("."),k=N.length;if(k>1){O&&(O=O.slice());for(var L=0;L<k-1;L++){var F=N[L];D=D[F]=D[F]||{},M+="."+F,O&&O.push(F)}w=N[k-1]}}if(P=C&&_isReservedField(M)||!R||!R.handleField(M,w)?sanitizeProperty2(w,b,S):R.value(M,w,b,S)){var x=P.value;if(D[w]=x,T&&T(O,w,P),I&&"object"==typeof x&&!ul(x)){var U=O;U&&(U=U.slice()).push(w),_processPathKeys(b,x,M+"."+w,C,U,T,I)}}}}))}f.createPayload=function(g,f,S,v,C,_){return{apiKeys:[],payloadBlob:Ap,overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:g,isTeardown:f,isSync:S,isBeacon:v,sendType:_,sendReason:C}},f.appendPayload=function(S,v,C){var _=S&&v&&!S.overflow;return _&&doPerf2(g,(function(){return"Serializer:appendPayload"}),(function(){for(var g=v.events(),_=S.payloadBlob,T=S.numEvents,I=!1,b=[],A=[],P=S.isBeacon,R=P?Pf:Af,M=P?Mf:Rf,w=0,O=0;w<g.length;){var D=g[w];if(D){if(T>=C){S.overflow=v.split(w);break}var N=f.getEventBlob(D);if(N&&N.length<=M){var k=N.length;if(_.length+k>R){S.overflow=v.split(w);break}_&&(_+="\n"),_+=N,++O>bf&&(Fl(_,0,1),O=0),I=!0,T++}else N?b.push(D):A.push(D),g.splice(w,1),w--}w++}if(b.length>0&&S.sizeExceed.push(ff.create(v.iKey(),b)),A.length>0&&S.failedEvts.push(ff.create(v.iKey(),A)),I){S.batches.push(v),S.payloadBlob=_,S.numEvents=T;var L=v.iKey();-1===Yl(S.apiKeys,L)&&S.apiKeys.push(L)}}),(function(){return{payload:S,theBatch:{iKey:v.iKey(),evts:v.events()},max:C}})),_},f.getEventBlob=function(f){try{return doPerf2(g,(function(){return"Serializer.getEventBlob"}),(function(){var g={};g.name=f.name,g.time=f.time,g.ver=f.ver,g.iKey="o:"+getTenantId2(f.iKey);var S,v={};w||(S=function(g,f,S){_addJSONPropertyMetaData2(O,v,g,f,S)});var C=f[b];C&&(g[b]=v,objForEachKey2(C,(function(g,f){_processPathKeys(f,v[g]={},"ext."+g,!0,null,null,!0)})));var _=g[T]={};_.baseType=f.baseType;var A=_[I]={};return _processPathKeys(f.baseData,A,I,!1,[I],S,P),_processPathKeys(f.data,_,T,!1,[],S,P),JSON.stringify(g)}),(function(){return{item:f}}))}catch(g){return null}}}))}return Serializer22.__ieDyn=1,Serializer22}();function _addJSONPropertyMetaData2(g,f,S,v,C){if(C&&f){var _=g(C.value,C.kind,C.propertyType);if(_>-1){var T=f[wf];T||(T=f[wf]={f:{}});var I=T[Of];if(I||(I=T[Of]={}),S)for(var b=0;b<S.length;b++){var A=S[b];I[A]||(I[A]={f:{}});var P=I[A][Of];P||(P=I[A][Of]={}),I=P}I=I[v]={},ul(C.value)?I.a={t:_}:I.t=_}}}function createTimeoutWrapper2(g,f){return{set:function(S,v){for(var C=[],_=2;_<arguments.length;_++)C[_-2]=arguments[_];return scheduleTimeoutWith2([g,f],S,v,C)}}}var kf="sendAttempt",Lf="&"+zp+"=true",Ff="?cors=true&"+Lp[dm]()+"="+Np,xf=((If={})[1]=Mp,If[100]=Mp,If[200]="sent",If[8004]=Pp,If[8003]=Pp,If),Uf={},Vf={};function _addCollectorHeaderQsMapping2(g,f,S){Uf[g]=f,!1!==S&&(Vf[f]=g)}function _hasHeader2(g,f){var S=!1;if(g&&f){var v=Al(g);if(v&&v[im]>0)for(var C=f[dm](),_=0;_<v[im];_++){var T=v[_];if(T&&objHasOwnProperty2(f,T)&&T[dm]()===C){S=!0;break}}}return S}function _addRequestDetails2(g,f,S,v){f&&S&&S[im]>0&&(v&&Uf[f]?(g[hm][Uf[f]]=S,g[um]=!0):g.url+="&"+f+"="+S)}function _addQueryStringParameter2(g,f,S){for(var v=0;v<g[im];v++)if(g[v].name===f)return void(g[v].value=S);g[om]({name:f,value:S})}function _removeQueryStringParameter2(g,f){for(var S=0;S<g[im];S++)if(g[S].name===f)return void g[cm](S,1)}_addCollectorHeaderQsMapping2(Gp,Gp,!1),_addCollectorHeaderQsMapping2(Vp,Vp),_addCollectorHeaderQsMapping2(Bp,"Client-Id"),_addCollectorHeaderQsMapping2(jp,jp),_addCollectorHeaderQsMapping2(Hp,Hp),_addCollectorHeaderQsMapping2($p,$p),_addCollectorHeaderQsMapping2(Wp,Wp);var Bf=function(){function HttpManager22(g,f,S,v){var C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q,W,z,K,J,Y,Q,X=!1;dynamicProto2(HttpManager22,this,(function(Z){_initDefaults();var ee=!0;function _getSenderInterface(g,f){try{return Q&&Q.getSenderInst(g,f)}catch(g){}return null}function _getSendPostMgrConfig(){try{return{enableSendPromise:!1,isOneDs:!0,disableCredentials:!ee,disableXhr:!1,disableBeacon:!X,disableBeaconSync:!X,disableFetchKeepAlive:H,timeWrapper:J,addNoResponse:j,senderOnCompleteCallBack:{xdrOnComplete:_xdrOncomplete,fetchOnComplete:_fetchOnComplete,xhrOnComplete:_xhrOnComplete,beaconOnRetry:_onBeaconRetry}}}catch(g){}return null}function _xdrOncomplete(g,f,S){var v=getResponseText2(g);_doOnComplete(f,200,{},v),_handleCollectorResponse(v)}function _initDefaults(){var g;C=null,_=new Cf,T=!1,I=new Sf,X=!1,b=0,A=null,P=null,R=null,M=null,w=!0,O=[],D={},N=[],k=null,L=!1,F=null,x=!1,U=!1,V=g,B=g,H=g,$=g,j=g,G=[],q=g,W=g,z=[],K=!1,J=createTimeoutWrapper2(),Y=!1,Q=null}function _fetchOnComplete(g,f,S,v){var handleResponse=function(g,S,v){_doOnComplete(f,g,S,v),_handleCollectorResponse(v)},C={},_=g[km];_&&_.forEach((function(g,f){C[f]=g})),handleResponse(g.status,C,S||Ap)}function _xhrOnComplete(g,f,S){var v=getResponseText2(g);_doOnComplete(f,g.status,_getAllResponseHeaders2(g,!0),v),_handleCollectorResponse(v)}function _doOnComplete(g,f,S,v){try{g(f,S,v)}catch(g){_throwInternal2(P,2,518,dumpObj2(g))}}function _onBeaconRetry(g,f,S){var v=200,C=g[Lm],_=g[Fm]+(j?Lf:Ap);try{var T=Kl();if(C){var I=!!M.getPlugin("LocalStorage"),b=[],A=[];arrForEach2(C[xm],(function(g){if(b&&g&&g[sm]()>0)for(var f=g[am](),S=0;S<f[im];S++){if(!T.sendBeacon(_,k.getEventBlob(f[S]))){b[om](g[lm](S));break}A[om](g[S])}else b[om](g[lm](0))})),A[im]>0&&(C.sentEvts=A),I||_sendBatchesNotification(b,8003,C[Um],!0)}else v=0}catch(g){_warnToConsole2(P,"Failed to send telemetry using sendBeacon API. Ex:"+dumpObj2(g)),v=0}finally{_doOnComplete(f,v,{},Ap)}}function _isBeaconPayload(g){return 2===g||3===g}function _adjustSendType(g){return x&&_isBeaconPayload(g)&&(g=2),g}function _hasIdleConnection(){return!T&&b<f}function _clearQueue(){var g=N;return N=[],g}function _canSendPayload(g,f,S){var v=!1;return g&&g[im]>0&&!T&&R[f]&&k&&(v=0!==f||_hasIdleConnection()&&(S>0||I[Qp]())),v}function _createDebugBatches(g){var f={};return g&&arrForEach2(g,(function(g,S){f[S]={iKey:g[rm](),evts:g[am]()}})),f}function _sendBatches(f,S,v,C,I){if(f&&0!==f[im])if(T)_sendBatchesNotification(f,1,C);else{C=_adjustSendType(C);try{var b=f,A=0!==C;doPerf2(M,(function(){return"HttpManager:_sendBatches"}),(function(T){T&&(f=f.slice(0));for(var b=[],P=null,M=vp(),w=R[C]||(A?R[1]:R[0]),O=w&&w[Wm],D=$&&(x||_isBeaconPayload(C)||3===O||w._isSync&&2===O);_canSendPayload(f,C,S);){var L=f.shift();L&&L[sm]()>0&&(_.isTenantKilled(L[rm]())?b[om](L):(P=P||k[Om](S,v,A,D,I,C),k.appendPayload(P,L,g)?null!==P.overflow&&(f=[P.overflow][nm](f),P.overflow=null,_doPayloadSend(P,M,vp(),I),M=vp(),P=null):(_doPayloadSend(P,M,vp(),I),M=vp(),f=[L][nm](f),P=null)))}P&&_doPayloadSend(P,M,vp(),I),f[im]>0&&(N=f[nm](N)),_sendBatchesNotification(b,8004,C)}),(function(){return{batches:_createDebugBatches(b),retryCount:S,isTeardown:v,isSynchronous:A,sendReason:I,useSendBeacon:_isBeaconPayload(C),sendType:C}}),!A)}catch(g){_throwInternal2(P,2,48,"Unexpected Exception sending batch: "+dumpObj2(g))}}}function _buildRequestDetails(g,f){var S={url:C,hdrs:{},useHdrs:!1};f?(S[hm]=extend2(S[hm],D),S.useHdrs=Al(S.hdrs)[im]>0):objForEachKey2(D,(function(g,f){Vf[g]?_addRequestDetails2(S,Vf[g],f,!1):(S[hm][g]=f,S[um]=!0)})),_addRequestDetails2(S,Bp,"NO_AUTH",f),_addRequestDetails2(S,Vp,mp,f);var v=Ap;arrForEach2(g.apiKeys,(function(g){v[im]>0&&(v+=","),v+=g})),_addRequestDetails2(S,jp,v,f),_addRequestDetails2(S,$p,utcNow2().toString(),f);var _=_getMsfpc32(g);if(isValueAssigned2(_)&&(S.url+="&ext.intweb.msfpc="+_),I[Zp]()&&_addRequestDetails2(S,Hp,I[em](),f),M[zm]){var T=M[zm]();T>=0&&(S.url+="&w="+T)}for(var b=0;b<O[im];b++)S.url+="&"+O[b].name+"="+O[b].value;return S}function _setTimingValue(g,f,S){g[f]=g[f]||{},g[f][A.identifier]=S}function _doPayloadSend(g,f,S,v){if(g&&g.payloadBlob&&g.payloadBlob[im]>0){var C=!!q,_=R[g.sendType];!_isBeaconPayload(g[Um])&&g[Km]&&2===g.sendReason&&(_=R[2]||R[3]||_);var T=U;(g.isBeacon||3===_[Wm])&&(T=!1);var A=_buildRequestDetails(g,T);T=T||A[um];var O=vp();doPerf2(M,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var R=0;R<g.batches[im];R++)for(var D=g[xm][R][am](),N=0;N<D[im];N++){var k=D[N];if(L){var F=k[Jm]=k[Jm]||{};_setTimingValue(F,"sendEventStart",O),_setTimingValue(F,"serializationStart",f),_setTimingValue(F,"serializationCompleted",S)}k[kf]>0?k[kf]++:k[kf]=1}_sendBatchesNotification(g[xm],1e3+(v||0),g[Um],!0);var x={data:g[Nm],urlString:A.url,headers:A[hm],_thePayload:g,_sendReason:v,timeout:V,disableXhrSync:B,disableFetchKeepAlive:H};T&&(_hasHeader2(x[km],kp)||(x[km][kp]=Dp),_hasHeader2(x[km],Lp)||(x[km][Lp]=Np));var U=null;_&&(U=function(f){I[Xp]();var onComplete=function(f,S){_retryRequestIfNeeded(f,S,g,v)},S=g[Ym]||g[Qm];try{_.sendPOST(f,onComplete,S),W&&W(x,f,S,g[Km])}catch(g){_warnToConsole2(P,"Unexpected exception sending payload. Ex:"+dumpObj2(g)),_doOnComplete(onComplete,0,{})}}),doPerf2(M,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(U)if(0===g[Um]&&b++,C&&!g.isBeacon&&3!==_[Wm]){var f={data:x[Xm],urlString:x[Fm],headers:extend2({},x[km]),timeout:x[Zm],disableXhrSync:x[_m],disableFetchKeepAlive:x[Tm]},S=!1;doPerf2(M,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{q(f,(function(g){S=!0,w||g[Lm]||(g[Lm]=g[Lm]||x[Lm],g[ef]=g[ef]||x[ef]),U(g)}),g.isSync||g[Ym])}catch(g){S||U(x)}}))}else U(x)}))}),(function(){return{thePayload:g,serializationStart:f,serializationCompleted:S,sendReason:v}}),g[Qm])}g.sizeExceed&&g.sizeExceed[im]>0&&_sendBatchesNotification(g.sizeExceed,8003,g[Um]),g.failedEvts&&g.failedEvts[im]>0&&_sendBatchesNotification(g.failedEvts,8002,g[Um])}function _addEventCompletedTimings(g,f){L&&arrForEach2(g,(function(g){_setTimingValue(g[Jm]=g[Jm]||{},"sendEventCompleted",f)}))}function _retryRequestIfNeeded(g,f,v,C){var T=9e3,A=null,P=!1,R=!1;try{var M=!0;if(typeof g!==Fo){if(f){I[tm](f[Up]);var w=f[xp]||f["kill-duration-seconds"];arrForEach2(_[tf](f[Fp],w),(function(g){arrForEach2(v[xm],(function(f){if(f[rm]()===g){A=A||[];var S=f[lm](0);v.numEvents-=S[sm](),A[om](S)}}))}))}if(200==g||204==g)return void(T=200);(!retryPolicyShouldRetryForStatus2(g)||v.numEvents<=0)&&(M=!1),T=9e3+g%1e3}if(M){T=100;var O=v.retryCnt;0===v[Um]&&(O<S?(P=!0,_doAction((function(){0===v[Um]&&b--,_sendBatches(v[xm],O+1,v[Ym],x?2:v[Um],5)}),x,retryPolicyGetMillisToBackoffForRetry2(O))):(R=!0,x&&(T=8001)))}}finally{P||(I[tm](),_handleRequestFinished(v,T,C,R)),_sendBatchesNotification(A,8004,v[Um])}}function _handleRequestFinished(g,f,S,v){try{v&&A[nf]();var C=g[xm];200===f&&(C=g.sentEvts||g[xm],v||g[Qm]||A._clearBackOff(),_addCompleteTimings(C)),_sendBatchesNotification(C,f,g[Um],!0)}finally{0===g[Um]&&(b--,5!==S&&Z.sendQueuedRequests(g[Um],S))}}function _addCompleteTimings(g){if(L){var f=vp();arrForEach2(g,(function(g){g&&g[sm]()>0&&_addEventCompletedTimings(g[am](),f)}))}}function _doAction(g,f,S){f?g():J.set(g,S)}function _getMsfpc32(g){for(var f=0;f<g.batches[im];f++){var S=g[xm][f].Msfpc();if(S)return encodeURIComponent(S)}return Ap}function _handleCollectorResponse(g){var f=z;try{for(var S=0;S<f[im];S++)try{f[S](g)}catch(g){_throwInternal2(P,1,519,"Response handler failed: "+g)}if(g){var v=JSON.parse(g);isValueAssigned2(v.webResult)&&isValueAssigned2(v.webResult[Kp])&&F.set("MSFPC",v.webResult[Kp],31536e3)}}catch(g){}}function _sendBatchesNotification(g,f,S,C){if(g&&g[im]>0&&v){var _=v[_getNotificationAction(f)];if(_){var T=0!==S;doPerf2(M,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){_doAction((function(){try{_.call(v,g,f,T,S)}catch(g){_throwInternal2(P,1,74,"send request notification failed: "+g)}}),C||T,0)}),(function(){return{batches:_createDebugBatches(g),reason:f,isSync:T,sendSync:C,sendType:S}}),!T)}}}function _getNotificationAction(g){var f=xf[g];return isValueAssigned2(f)||(f=Op,g>=9e3&&g<=9999?f=wp:g>=8e3&&g<=8999?f=Pp:g>=1e3&&g<=1999&&(f=Rp)),f}Z[gm]=function(g,f,S){K||(M=f,F=f.getCookieMgr(),P=(A=S).diagLog(),arrAppend2(G,onConfigChange2(g,(function(g){var v,_=g.cfg,T=g.cfg.extensionConfig[S.identifier];J=createTimeoutWrapper2(T[pm],T[mm]),isValueAssigned2(_.anonCookieName)?_addQueryStringParameter2(O,"anoncknm",_.anonCookieName):_removeQueryStringParameter2(O,"anoncknm"),q=T[fm],W=T.payloadListener;var I=T.httpXHROverride,b=T[Sm]?T[Sm]:_.endpointUrl;C=b+Ff,U=!!isUndefined4(T[vm])||!T[vm],L=!T[Cm];var A=T.valueSanitizer,D=T[ym],N=!!_[Em];isUndefined4(T[Em])||(N=!!T[Em]),V=T.xhrTimeout,B=!!T[_m],H=!!T[Tm],j=!1!==T[Im],Y=!!T[bm],f.getPlugin("LocalStorage")&&(H=!0),X=!isReactNative2(),k=new Nf(M,A,D,N,getCommonSchemaMetaData2,Y),isNullOrUndefined2(T[Am])||(X=!!T[Am]);var F=_getSendPostMgrConfig();Q?Q.SetConfig(F):(Q=new Fg)[gm](F,P);var x=I,G=T[Pm]?I:null,z=T[Pm]?I:null,K=[3,2];if(!I){w=!1;var Z=[];isReactNative2()?(Z=[2,1],K=[2,1,3]):Z=[1,2,3],(I=_getSenderInterface(Z=prependTransports2(Z,T.transports),!1))||_warnToConsole2(P,"No available transport to send events"),x=_getSenderInterface(Z,!0)}G||(G=_getSenderInterface(K=prependTransports2(K,T[Rm]),!0)),$=!w&&(X&&isBeaconsSupported2()||!H&&isFetchSupported2(!0)),(v={})[0]=I,v[1]=x||_getSenderInterface([1,2,3],!0),v[2]=G||x||_getSenderInterface([1],!0),v[3]=z||_getSenderInterface([2,3],!0)||x||_getSenderInterface([1],!0),R=v}))),K=!0)},Z.addResponseHandler=function(g){return z[om](g),{rm:function(){var f=z.indexOf(g);f>=0&&z[cm](f,1)}}},Z[Mm]=function(g){try{if(k)return k.getEventBlob(g)}catch(g){}return Ap},Z[wm]=function(){try{return _buildRequestDetails(k&&k[Om](0,!1,!1,!1,1,0),U)}catch(g){}return null},Z[Dm]=function(f,S){try{var v=[];arrForEach2(f,(function(g){S&&(g=optimizeObject2(g));var f=ff.create(g[rm],[g]);v[om](f)}));for(var C=null;v[im]>0&&k;){var _=v.shift();_&&_[sm]()>0&&(C=C||k[Om](0,!1,!1,!1,1,0),k.appendPayload(C,_,g))}var T=_buildRequestDetails(C,U),I={data:C[Nm],urlString:T.url,headers:T[hm],timeout:V,disableXhrSync:B,disableFetchKeepAlive:H};return U&&(_hasHeader2(I[km],kp)||(I[km][kp]=Dp),_hasHeader2(I[km],Lp)||(I[km][Lp]=Np)),I}catch(g){}return null},Z._getDbgPlgTargets=function(){return[R[0],_,k,R]},Z[Vm]=function(g,f){D[g]=f},Z.removeHeader=function(g){delete D[g]},Z[Bm]=function(){return _hasIdleConnection()&&I[Qp]()},Z[Hm]=function(g,f){isUndefined4(g)&&(g=0),x&&(g=_adjustSendType(g),f=2),_canSendPayload(N,g,0)&&_sendBatches(_clearQueue(),0,!1,g,f||0)},Z[$m]=function(){return!T&&0===b&&0===N[im]},Z[jm]=function(g){x=g},Z.addBatch=function(g){if(g&&g[sm]()>0){if(_.isTenantKilled(g[rm]()))return!1;N[om](g)}return!0},Z.teardown=function(){N[im]>0&&_sendBatches(_clearQueue(),0,!0,2,2),arrForEach2(G,(function(g){g&&g.rm&&g.rm()})),G=[]},Z.pause=function(){T=!0},Z.resume=function(){T=!1,Z[Hm](0,4)},Z[qm]=function(g,f,S){g&&g[sm]()>0&&(isNullOrUndefined2(f)&&(f=1),x&&(f=_adjustSendType(f),S=2),_sendBatches([g],0,!1,f,S||0))}}))}return HttpManager22.__ieDyn=1,HttpManager22}(),Hf=.25,$f=500,jf=20,Gf=6,qf=2,Wf=4,zf=2,Kf=1,Jf=1e4,Yf="eventsDiscarded",Qf="",Xf=void 0,Zf=objDeepFreeze2({eventsLimitInMem:{isVal:isGreaterThanZero2,v:Jf},immediateEventLimit:{isVal:isGreaterThanZero2,v:500},autoFlushEventsLimit:{isVal:isGreaterThanZero2,v:0},disableAutoBatchFlushLimit:!1,httpXHROverride:{isVal:isOverrideFn2,v:Xf},overrideInstrumentationKey:Xf,overrideEndpointUrl:Xf,disableTelemetry:!1,ignoreMc1Ms0CookieProcessing:!1,setTimeoutOverride:Xf,clearTimeoutOverride:Xf,payloadPreprocessor:Xf,payloadListener:Xf,disableEventTimings:Xf,valueSanitizer:Xf,stringifyObjects:Xf,enableCompoundKey:Xf,disableOptimizeObj:!1,transports:Xf,unloadTransports:Xf,useSendBeacon:Xf,disableFetchKeepAlive:Xf,avoidOptions:!1,xhrTimeout:Xf,disableXhrSync:Xf,alwaysUseXhrOverride:!1,maxEventRetryAttempts:{isVal:pl,v:Gf},maxUnloadEventRetryAttempts:{isVal:pl,v:qf},addNoResponse:Xf,excludeCsMetaData:Xf});function isOverrideFn2(g){return g&&g.sendPOST}var eS,tS=function(g){function PostChannel22(){var f,S=g.call(this)||this;S.identifier="PostChannel",S.priority=1011,S.version="4.2.1";var v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q=!1,W=[],z=!1,K=0,J=0,Y={},Q=Tp;return dynamicProto2(PostChannel22,S,(function(g,S){function _removeUnloadHandlers(){removePageUnloadEventListener2(null,x),removePageHideEventListener2(null,x),removePageShowEventListener2(null,x)}function _hookWParam(g){var f=g[zm];g[zm]=function(){var S=0;return V&&(S|=2),S|f.call(g)}}function _batch(g){var f=Qf;return g&&g[im]&&arrForEach2(g,(function(g){f&&(f+="\n"),f+=g})),f}function _serialize(g){var f=Qf;try{_cleanEvent(g),f=P[Mm](g)}catch(g){}return f}function _handleUnloadEvents(g){"beforeunload"!==(g||Gl().event).type&&(k=!0,P[jm](k)),_releaseAllQueues(2,2)}function _handleShowEvents(g){k=!1,P[jm](k)}function _cleanEvent(g){g.ext&&g.ext[Jp]&&delete g.ext[Jp],g.ext&&g.ext[Yp]&&g.ext[Yp].id&&delete g.ext[Yp].id,N&&(g.ext=optimizeObject2(g.ext),g[uf]&&(g[uf]=optimizeObject2(g[uf])),g[Xm]&&(g[Xm]=optimizeObject2(g[Xm])))}function _addEventToQueues(g,f){if(g[gf]||(g[gf]=0),g[pf]||(g[pf]=1),_cleanEvent(g),g[mf])if(b||z)g[pf]=3,g[mf]=!1;else if(P)return N&&(g=optimizeObject2(g)),void P[qm](ff.create(g[rm],[g]),!0===g[mf]?1:g[mf],3);var S=g[pf],v=J,T=_;4===S&&(v=K,T=C);var I=!1;if(v<T)I=!_addEventToProperQueue(g,f);else{var A=1,R=jf;4===S&&(A=4,R=1),I=!0,_dropEventWithLatencyOrLess(g[rm],g[pf],A,R)&&(I=!_addEventToProperQueue(g,f))}I&&_notifyEvents(Yf,[g],Bc.QueueFull)}function _sendEventsForLatencyAndAbove(g,f,S){var v=_queueBatches(g,f,S);return P[Hm](f,S),v}function _hasEvents(){return J>0}function _scheduleTimer(){if(O>=0&&_queueBatches(O,0,D)&&P[Hm](0,D),K>0&&!I&&!z){var g=Y[Q][2];g>=0&&(I=_createTimer((function(){I=null,_sendEventsForLatencyAndAbove(4,0,1),_scheduleTimer()}),g))}var f=Y[Q][1];!T&&!v&&f>=0&&!z&&(_hasEvents()?T=_createTimer((function(){T=null,_sendEventsForLatencyAndAbove(0===A?3:1,0,1),A++,A%=2,_scheduleTimer()}),f):A=0)}function _initDefaults(){f=null,q=!1,W=[],v=null,z=!1,K=0,C=500,J=0,_=Jf,Y={},Q=Tp,T=null,I=null,b=0,A=0,R={},M=0,$=!1,w=0,O=-1,D=null,N=!0,k=!1,L=Gf,F=qf,x=null,j=null,G=!1,U=createTimeoutWrapper2(),P=new Bf($f,zf,Kf,{requeue:_requeueEvents,send:_sendingEvent,sent:_eventsSentEvent,drop:_eventsDropped,rspFail:_eventsResponseFail,oth:_otherEvent}),_initializeProfiles(),_clearQueues(),_setAutoLimits()}function _createTimer(g,f){0===f&&b&&(f=1);var S=1e3;return b&&(S=retryPolicyGetMillisToBackoffForRetry2(b-1)),U.set(g,f*S)}function _clearScheduledTimer(){return null!==T&&(T.cancel(),T=null,A=0,!0)}function _releaseAllQueues(g,f){_clearScheduledTimer(),v&&(v.cancel(),v=null),z||_sendEventsForLatencyAndAbove(1,g,f)}function _clearQueues(){R[4]={batches:[],iKeyMap:{}},R[3]={batches:[],iKeyMap:{}},R[2]={batches:[],iKeyMap:{}},R[1]={batches:[],iKeyMap:{}}}function _getEventBatch(g,f,S){var v=R[f];v||(v=R[f=1]);var C=v.iKeyMap[g];return!C&&S&&(C=ff.create(g),v.batches[om](C),v.iKeyMap[g]=C),C}function _performAutoFlush(f,S){P[Bm]()&&!b&&(M>0&&J>M&&(S=!0),S&&null==v&&g.flush(f,(function(){}),20))}function _addEventToProperQueue(g,f){N&&(g=optimizeObject2(g));var S=g[pf],v=_getEventBatch(g[rm],S,!0);return!!v.addEvent(g)&&(4!==S?(J++,f&&0===g[gf]&&_performAutoFlush(!g.sync,w>0&&v[sm]()>=w)):K++,!0)}function _dropEventWithLatencyOrLess(g,f,S,v){for(;S<=f;){var C=_getEventBatch(g,f,!0);if(C&&C[sm]()>0){var _=C[lm](0,v),T=_[sm]();if(T>0)return 4===S?K-=T:J-=T,_notifyBatchEvents(Yf,[_],Bc.QueueFull),!0}S++}return _resetQueueCounts(),!1}function _resetQueueCounts(){for(var g=0,f=0,_loop_1=function(S){var v=R[S];v&&v[xm]&&arrForEach2(v[xm],(function(v){4===S?g+=v[sm]():f+=v[sm]()}))},S=1;S<=4;S++)_loop_1(S);J=f,K=g}function _queueBatches(f,S,v){var C=!1,_=0===S;return!_||P[Bm]()?doPerf2(g.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var g=[],S=4;S>=f;){var v=R[S];v&&v.batches&&v.batches[im]>0&&(arrForEach2(v[xm],(function(f){P.addBatch(f)?C=C||f&&f[sm]()>0:g=g[nm](f[am]()),4===S?K-=f[sm]():J-=f[sm]()})),v[xm]=[],v.iKeyMap={}),S--}g[im]>0&&_notifyEvents(Yf,g,Bc.KillSwitch),C&&O>=f&&(O=-1,D=0)}),(function(){return{latency:f,sendType:S,sendReason:v}}),!_):(O=O>=0?Math.min(O,f):f,D=Math.max(D,v)),C}function _flushImpl(g,f){_sendEventsForLatencyAndAbove(1,0,f),_resetQueueCounts(),_waitForIdleManager((function(){g&&g(),W[im]>0?v=_createTimer((function(){v=null,_flushImpl(W.shift(),f)}),0):(v=null,_scheduleTimer())}))}function _waitForIdleManager(g){P[$m]()?g():v=_createTimer((function(){v=null,_waitForIdleManager(g)}),Hf)}function _resetTransmitProfiles(){_clearScheduledTimer(),_initializeProfiles(),Q=Tp,_scheduleTimer()}function _initializeProfiles(){(Y={})[Tp]=[2,1,0],Y[Ip]=[6,3,0],Y[bp]=[18,9,0]}function _requeueEvents(f,S){var v=[],C=L;k&&(C=F),arrForEach2(f,(function(f){f&&f[sm]()>0&&arrForEach2(f[am](),(function(f){f&&(f[mf]&&(f[pf]=4,f[mf]=!1),f[gf]<C?(setProcessTelemetryTimings2(f,g[rf]),_addEventToQueues(f,!1)):v[om](f))}))})),v[im]>0&&_notifyEvents(Yf,v,Bc.NonRetryableStatus),k&&_releaseAllQueues(2,2)}function _callNotification(f,S){var v=H||{},C=v[f];if(C)try{C.apply(v,S)}catch(S){_throwInternal2(g.diagLog(),1,74,f+" notification failed: "+S)}}function _notifyEvents(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];f&&f[im]>0&&_callNotification(g,[f][nm](S))}function _notifyBatchEvents(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];f&&f[im]>0&&arrForEach2(f,(function(f){f&&f[sm]()>0&&_callNotification(g,[f.events()][nm](S))}))}function _sendingEvent(g,f,S){g&&g[im]>0&&_callNotification("eventsSendRequest",[f>=1e3&&f<=1999?f-1e3:0,!0!==S])}function _eventsSentEvent(g,f){_notifyBatchEvents("eventsSent",g,f),_scheduleTimer()}function _eventsDropped(g,f){_notifyBatchEvents(Yf,g,f>=8e3&&f<=8999?f-8e3:Bc.Unknown)}function _eventsResponseFail(g){_notifyBatchEvents(Yf,g,Bc.NonRetryableStatus),_scheduleTimer()}function _otherEvent(g,f){_notifyBatchEvents(Yf,g,Bc.Unknown),_scheduleTimer()}function _setAutoLimits(){w=B?0:Math.max($f*(zf+1),_/6)}_initDefaults(),g._getDbgPlgTargets=function(){return[P,f]},g[gm]=function(v,T,I){doPerf2(T,(function(){return"PostChannel:initialize"}),(function(){S[gm](v,T,I),H=T.getNotifyMgr();try{x=mergeEvtNamespace2(createUniqueNamespace2(g[rf]),T.evtNamespace&&T.evtNamespace()),g._addHook(onConfigChange2(v,(function(S){var v=S.cfg,I=createProcessTelemetryContext2(null,v,T);f=I.getExtCfg(g[rf],Zf),U=createTimeoutWrapper2(f[pm],f[mm]),N=!f[sf]&&isChromium2(),V=f[af],_hookWParam(T),_=f[of],C=f.immediateEventLimit,M=f[lf],L=f.maxEventRetryAttempts,F=f.maxUnloadEventRetryAttempts,B=f[cf],_setAutoLimits(),j=f[df],G=!!f[hf],$&&_removeUnloadHandlers();var b=v.disablePageUnloadEvents||[];$=addPageUnloadEventListener2(_handleUnloadEvents,b,x),$=addPageHideEventListener2(_handleUnloadEvents,b,x)||$,$=addPageShowEventListener2(_handleShowEvents,v.disablePageShowEvents,x)||$}))),P[gm](v,g.core,g)}catch(f){throw g.setInitialized(!1),f}}),(function(){return{theConfig:v,core:T,extensions:I}}))},g.processTelemetry=function(f,S){setProcessTelemetryTimings2(f,g[rf]),S=S||g._getTelCtx(S);var v=f;G||q||(j&&(v[rm]=j),_addEventToQueues(v,!0),k?_releaseAllQueues(2,2):_scheduleTimer()),g.processNext(v,S)},g.getOfflineSupport=function(){try{var g=P&&P[wm]();if(P)return{getUrl:function(){return g?g.url:null},serialize:_serialize,batch:_batch,shouldProcess:function(g){return!G},createPayload:function(g){return null},createOneDSPayload:function(g){if(P[Dm])return P[Dm](g,N)}}}catch(g){}return null},g._doTeardown=function(g,f){_releaseAllQueues(2,2),q=!0,P.teardown(),_removeUnloadHandlers(),_initDefaults()},g.setEventQueueLimits=function(g,S){f[of]=_=isGreaterThanZero2(g)?g:Jf,f[lf]=M=isGreaterThanZero2(S)?S:0,_setAutoLimits();var v=J>g;if(!v&&w>0)for(var C=1;!v&&C<=3;C++){var T=R[C];T&&T[xm]&&arrForEach2(T[xm],(function(g){g&&g[sm]()>=w&&(v=!0)}))}_performAutoFlush(!0,v)},g.pause=function(){_clearScheduledTimer(),z=!0,P.pause()},g.resume=function(){z=!1,P.resume(),_scheduleTimer()},g._loadTransmitProfiles=function(g){_resetTransmitProfiles(),objForEachKey2(g,(function(g,f){var S=f[im];if(S>=2){var v=S>2?f[2]:0;if(f[cm](0,S-2),f[1]<0&&(f[0]=-1),f[1]>0&&f[0]>0){var C=f[0]/f[1];f[0]=Math.ceil(C)*f[1]}v>=0&&f[1]>=0&&v>f[1]&&(v=f[1]),f[om](v),Y[g]=f}}))},g.flush=function(g,f,S){var C;if(void 0===g&&(g=!0),!z)if(S=S||1,g)f||(C=createPromise2((function(g){f=g}))),null==v?(_clearScheduledTimer(),_queueBatches(1,0,S),v=_createTimer((function(){v=null,_flushImpl(f,S)}),0)):W[om](f);else{var _=_clearScheduledTimer();_sendEventsForLatencyAndAbove(1,1,S),f&&f(),_&&_scheduleTimer()}return C},g.setMsaAuthTicket=function(g){P[Vm](Gp,g)},g.setAuthPluginHeader=function(g){P[Vm](qp,g)},g.removeAuthPluginHeader=function(){P.removeHeader(qp)},g.hasEvents=_hasEvents,g._setTransmitProfile=function(g){Q!==g&&void 0!==Y[g]&&(_clearScheduledTimer(),Q=g,_scheduleTimer())},proxyFunctions2(g,(function(){return P}),["addResponseHandler"]),g[nf]=function(){b<Wf&&(b++,_clearScheduledTimer(),_scheduleTimer())},g._clearBackOff=function(){b&&(b=0,_clearScheduledTimer(),_scheduleTimer())}})),S}return __extendsFn2(PostChannel22,g),PostChannel22.__ieDyn=1,PostChannel22}(Ig),iS="locale",nS="ver",rS="browser",sS="browserVer",aS="popSample",oS="eventFlags",lS="name",cS="serviceName",dS=Vc({UserExt:[0,"user"],DeviceExt:[1,"device"],TraceExt:[2,"trace"],WebExt:[3,"web"],AppExt:[4,"app"],OSExt:[5,"os"],SdkExt:[6,"sdk"],IntWebExt:[7,"intweb"],UtcExt:[8,"utc"],LocExt:[9,"loc"],CloudExt:[10,"cloud"],DtExt:[11,"dt"]}),hS=Vc({id:[0,"id"],ver:[1,nS],appName:[2,lS],locale:[3,iS],expId:[4,"expId"],env:[5,"env"]}),uS=Vc({domain:[0,"domain"],browser:[1,rS],browserVer:[2,sS],screenRes:[3,"screenRes"],userConsent:[4,"userConsent"],consentDetails:[5,"consentDetails"]}),gS=Vc({locale:[0,iS],localId:[1,"localId"],id:[2,"id"]}),pS=Vc({osName:[0,lS],ver:[1,nS]}),mS=Vc({ver:[0,nS],seq:[1,"seq"],installId:[2,"installId"],epoch:[3,"epoch"]}),fS=Vc({msfpc:[0,"msfpc"],anid:[1,"anid"],serviceName:[2,cS]}),SS=Vc({popSample:[0,aS],eventFlags:[1,oS]}),vS=Vc({tz:[0,"tz"]}),CS=Vc({sessionId:[0,"sesId"]}),yS=Vc({localId:[0,"localId"],deviceClass:[1,"deviceClass"],make:[2,"make"],model:[3,"model"]}),ES=Vc({role:[0,"role"],roleInstance:[1,"roleInstance"],roleVer:[2,"roleVer"]}),_S=Vc({traceId:[0,"traceID"],traceName:[1,lS],parentId:[2,"parentID"]}),TS=Vc({traceId:[0,"traceId"],spanId:[1,"spanId"],traceFlags:[2,"traceFlags"]});function canUseLocalStorage2(){return void 0===eS&&(eS=!!_getVerifiedStorageObject2(0)),eS}function _getLocalStorageObject2(){return canUseLocalStorage2()?_getVerifiedStorageObject2(0):null}function _getVerifiedStorageObject2(g){var f,S,v=null;try{var C=getGlobal2();if(!C)return null;S=new Date,(v=0===g?C.localStorage:C.sessionStorage)&&hl(v.setItem)&&(v.setItem(S,S),f=v.getItem(S)!==S,v.removeItem(S),f&&(v=null))}catch(g){v=null}return v}function setStorage2(g,f,S){var v=_getLocalStorageObject2();if(null!==v)try{return v.setItem(f,S),!0}catch(f){eS=!1,_throwInternal2(g,1,504,"Browser failed write to local storage. "+f)}return!1}function getStorage2(g,f){var S=_getLocalStorageObject2();if(null!==S)try{return S.getItem(f)}catch(f){eS=!1,_throwInternal2(g,1,503,"Browser failed read of local storage. "+f)}return null}function _getId2(){return this.getId()}function _setId2(g){this.setId(g)}var IS=function(){function Session3(){dynamicProto2(Session3,this,(function(g){g.setId=function(f){g.customId=f},g.getId=function(){return dl(g.customId)?g.customId:g.automaticId}}))}return Session3._staticInit=void objDefine2(Session3.prototype,"id",{g:_getId2,s:_setId2}),Session3}(),bS="ai_session",AS=function(){function SessionManager22(g,f,S){var v,C,_,T=safeGetLogger2(g),I=safeGetCookieMgr2(g);dynamicProto2(SessionManager22,this,(function(g){var b=onConfigChange2(f,(function(){_=f,g.config=_}));function _initializeAutomaticSession(){var f=I.get(C());if(f&&hl(f.split))_initializeAutomaticSessionWithData(f);else{var S=getStorage2(T,C());S&&_initializeAutomaticSessionWithData(S)}g.automaticSession.getId()||_renew()}function _initializeAutomaticSessionWithData(f){var S=g.automaticSession,v=f.split("|");v.length>0&&S.setId(v[0]);try{if(v.length>1){var C=+v[1];S.acquisitionDate=+new Date(C),S.acquisitionDate=S.acquisitionDate>0?S.acquisitionDate:0}if(v.length>2){var _=+v[2];S.renewalDate=+new Date(_),S.renewalDate=S.renewalDate>0?S.renewalDate:0}}catch(g){_throwInternal2(T,1,510,"Error parsing ai_session cookie, session will be reset: "+g)}0===S.renewalDate&&_throwInternal2(T,2,517,"AI session renewal date is 0, session will be reset.")}function _renew(){var f=g.automaticSession,S=(new Date).getTime(),v=g.config.sessionAsGuid;!isUndefined4(v)&&v?ml(v)?f.setId(createGuid2()):f.setId(createGuid2(v)):f.setId(newId2(_.idLength||22)),f.acquisitionDate=S,f.renewalDate=S,_setCookie(f.getId(),f.acquisitionDate,f.renewalDate),canUseLocalStorage2()||_throwInternal2(T,2,505,"Browser does not support local storage. Session durations will be inaccurate.")}function _setCookie(f,S,_){var T=S+g.config.sessionExpirationMs,b=_+g.config.sessionRenewalMs,A=new Date,P=[f,S,_];T<b?A.setTime(T):A.setTime(b);var R=g.config.cookieDomain||null;I.set(C(),P.join("|")+";expires="+A.toUTCString(),null,R),v=(new Date).getTime()}function _setStorage(g,f,S){setStorage2(T,C(),[g,f,S].join("|"))}S&&S.add(b),C=function(){return g.config.namePrefix?bS+g.config.namePrefix:bS},g.automaticSession=new IS,g.update=function(){g.automaticSession.getId()||_initializeAutomaticSession();var f=g.automaticSession,S=g.config,C=(new Date).getTime(),_=C-f.acquisitionDate>S.sessionExpirationMs,T=C-f.renewalDate>S.sessionRenewalMs;_||T?_renew():(!v||C-v>SessionManager22.cookieUpdateInterval)&&(f.renewalDate=C,_setCookie(f.getId(),f.acquisitionDate,f.renewalDate))},g.backup=function(){var f=g.automaticSession;_setStorage(f.getId(),f.acquisitionDate,f.renewalDate)}}))}return SessionManager22.cookieUpdateInterval=6e4,SessionManager22}(),PS=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function _validateAppExpId2(g,f){void 0===f&&(f=PS);var S=null;if(g)for(var v=g.split(","),C=0;C<v.length;C++)_isValidAppFlightId2(v[C],f)&&(S?S+=","+v[C]:S=v[C]);return S}function _isValidAppFlightId2(g,f){if(void 0===f&&(f=PS),!g||g.length<4)return!1;for(var S=!1,v=256,C=g.substring(0,3).toString().toUpperCase(),_=0;_<f.length;_++)if(f[_]+":"===C&&g.length<=v){S=!0;break}return S}function _getExpId2(){return this.getExpId()}var RS=function(){function Application22(g,f,S){var v,C=null,_=PS.slice(0),T="Treatments",I=null;dynamicProto2(Application22,this,(function(b){if(_populateDefaults(g),hasDocument2()){var A=jl().documentElement;A&&(b.locale=A.lang)}function _getMetaDataFromDOM(g){var f,S={},v=jl();if(v){f=v&&v.querySelectorAll("meta");for(var C=0;C<f.length;C++){var _=f[C];_.name&&0===_.name.toLowerCase().indexOf(g)&&(S[_.name.replace(g,"")]=_.content)}}return S}function _setAppExpId(g){g!==C&&(C=_validateAppExpId2(g,_))}function _readExpIdFromCookie(){return _setAppExpId(getCookieValue2(v,T)),C}function _readExpIdFromCoreData(g){return _setAppExpId(g),C}function _populateDefaults(g){var C=onConfigChange2(g,(function(){v=f&&f.getCookieMgr(),I=g||{},b.env=I.env||_getMetaDataFromDOM("awa-").env}));S&&S.add(C)}b.getExpId=function(){return I.expId?_readExpIdFromCoreData(I.expId):_readExpIdFromCookie()}}))}return Application22.validateAppExpId=_validateAppExpId2,Application22._staticInit=void objDefine2(Application22.prototype,"expId",{g:_getExpId2}),Application22}(),MS=function(){function Cloud22(){}return Cloud22}(),wS=function(){function Device3(){}return Device3}();function _getMsfpc22(){return this.getMsfpc()}function _getAnid2(){return this.getAnid()}var OS=function(){function IntWeb22(g,f,S){var v;dynamicProto2(IntWeb22,this,(function(C){function _populateDefaults(g){var _=onConfigChange2(g,(function(){v=f&&f.getCookieMgr();var S=g||{};S.serviceName&&(C.serviceName=S.serviceName)}));S&&S.add(_)}_populateDefaults(g),C.getMsfpc=function(){return getCookieValue2(v,"MSFPC")},C.getAnid=function(){return getCookieValue2(v,"ANON").slice(0,34)}}))}var g;return IntWeb22._staticInit=(objDefine2(g=IntWeb22.prototype,"msfpc",{g:_getMsfpc22}),void objDefine2(g,"anid",{g:_getAnid2})),IntWeb22}(),DS=function(){function Loc22(){var g=(new Date).getTimezoneOffset(),f=g%60,S=(g-f)/60,v="+";S>0&&(v="-"),S=Math.abs(S),f=Math.abs(f),this.tz=v+(S<10?"0"+S:S.toString())+":"+(f<10?"0"+f:f.toString())}return Loc22}(),NS={WIN:/(windows|win32)/i,WINRT:/ arm;/i,WINPHONE:/windows\sphone\s\d+\.\d+/i,OSX:/(macintosh|mac os x)/i,IOS:/(ipad|iphone|ipod)(?=.*like mac os x)/i,LINUX:/(linux|joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)/i,ANDROID:/android/i,CROS:/CrOS/i},kS={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},LS="([\\d,.]+)",FS="([\\d,_,.]+)",xS="Unknown",US=[{r:NS.WINPHONE,os:"Windows Phone"},{r:NS.WINRT,os:"Windows RT"},{r:NS.WIN,os:"Windows"},{r:NS.IOS,os:"iOS"},{r:NS.ANDROID,os:"Android"},{r:NS.LINUX,os:"Linux"},{r:NS.CROS,os:"Chrome OS"},{s:"x11",os:"Unix"},{s:"blackberry",os:"BlackBerry"},{s:"symbian",os:"Symbian"},{s:"nokia",os:"Nokia"},{r:NS.OSX,os:"Mac OS X"}];function _getOsName2(g){for(var f=0;f<US.length;f++){var S=US[f];if(S.r&&g.match(S.r))return S.os;if(S.s&&-1!==g.indexOf(S.s))return S.os}return xS}function _getOsVersion2(g,f){return"Windows"===f?_getGenericOsVersion2(g,"Windows NT"):"Android"===f?_getGenericOsVersion2(g,f):"Mac OS X"===f?_getMacOsxVersion2(g):"iOS"===f?_getIosVersion2(g):xS}function _getGenericOsVersion2(g,f){var S=g.match(new RegExp(f+" "+LS));return S?kS[S[1]]?kS[S[1]]:S[1]:xS}function _getMacOsxVersion2(g){var f=g.match(new RegExp("Mac OS X "+FS));if(f){var S=f[1].replace(/_/g,".");if(S){var v=_getDelimiter2(S);return v?S.split(v)[0]:S}}return xS}function _getIosVersion2(g){var f=g.match(new RegExp("OS "+FS));if(f){var S=f[1].replace(/_/g,".");if(S){var v=_getDelimiter2(S);return v?S.split(v)[0]:S}}return xS}function _getDelimiter2(g){return g.indexOf(".")>-1?".":g.indexOf("_")>-1?"_":null}var VS=function(){function OperatingSystem22(g,f){var S=this,v=null,C=null,_=null,T=null,_setSysName=function(g){_=g},_setSysVer=function(g){T=g},_getSysName=function(){return _||v},_getSysVer=function(){return T||C},I=onConfigChange2(g,(function(){if((g||{}).populateOperatingSystemInfo){var f=Kl()||{},S=g.userAgent||f.userAgent||"",_=(g.userAgentData||{}).platform||(f.userAgentData||{}).platform;if(S){var T=_getOsName2(S.toLowerCase());v=T,C=_getOsVersion2(S,T)}v&&v!==xS||!dl(_)||(v=_)}}));f&&f.add(I),objDefine2(S,"name",{s:_setSysName,g:_getSysName}),objDefine2(S,"ver",{s:_setSysVer,g:_getSysVer})}return OperatingSystem22}(),BS="MicrosoftApplicationsTelemetryDeviceId";function _saveData2(g,f,S,v){f?f.setProperty(S,v):g.set(S,v,31536e3)}function _getData2(g,f,S){return f?f.getProperty(S)||"":getCookieValue2(g,S)}var HS=function(){function Sdk22(g,f,S){var v,C=0;dynamicProto2(Sdk22,this,(function(_){_.seq=C,_.epoch=random322(!1).toString(),_.getSequenceId=function(){return++C};var T=onConfigChange2(g,(function(g){v=f&&f.getCookieMgr();var S=g.cfg.propertyStorageOverride;if(v.isEnabled()||S){var C=_getData2(v,S,BS);C||(C=newGuid22()),_saveData2(v,S,BS,C),_.installId=C}else v.purge(BS)}));S&&S.add(T)}))}return Sdk22.__ieDyn=1,Sdk22}(),$S=function(){function Trace22(g,f,S,v,C){var _=this;_.traceId=f||generateW3CId2();var T=onConfigChange2(g,(function(){var f=g;if(f.enableDistributedTracing&&!S&&(S=generateW3CId2().substring(0,16)),_.parentId=_.parentId||S,f.enableApplicationInsightsTrace&&!v){var C=getLocation2();C&&C.pathname&&(v=C.pathname)}_.name=_.name||v}));C&&C.add(T)}return Trace22}(),jS="setLocalId";function _getLocalId2(){return this.getLocalId()}function _setLocalId2(g){this[jS](g)}var GS=function(){function User22(g,f,S,v){var C,_,T;dynamicProto2(User22,this,(function(I){if(_populateDefaults(f),"undefined"!=typeof navigator){var b=navigator;I.locale=b.userLanguage||b.language}function _populateMuidFromCookie(){if(!C.hashIdentifiers&&!C.dropIdentifiers){var g=getCookieValue2(T,"MUID");g&&(_="t:"+g)}return _}function _populateDefaults(f){var b=onConfigChange2(f,(function(){if(T=S&&S.getCookieMgr(),C=f,_=null,T&&T.isEnabled()&&(_populateMuidFromCookie(),C.enableApplicationInsightsUser)){var v=getCookieValue2(T,User22.userCookieName);if(v){var b=v.split(User22.cookieSeparator);b.length>0&&(I.id=b[0])}if(!I.id){I.id=newId2(g&&!isUndefined4(g.idLength)?g.idLength:22);var A=toISOString2(new Date);I.accountAcquisitionDate=A;var P=[I.id,A],R=C.cookieDomain?C.cookieDomain:void 0;T.set(User22.userCookieName,P.join(User22.cookieSeparator),31536e3,R)}}}));v&&v.add(b)}I.getLocalId=function(){return _||_populateMuidFromCookie()},I[jS]=function(g){_=g}}))}return User22.cookieSeparator="|",User22.userCookieName="ai_user",User22._staticInit=void objDefine2(User22.prototype,"localId",{g:_getLocalId2,s:_setLocalId2}),User22}(),qS=1048576,WS=2097152,zS=4194304,KS=function(){function Utc22(g,f){var S=this;S.popSample=100;var v=onConfigChange2(g,(function(){S.eventFlags=0,g.hashIdentifiers&&(S.eventFlags=S.eventFlags|qS),g.dropIdentifiers&&(S.eventFlags=S.eventFlags|WS),g.scrubIpOnly&&(S.eventFlags=S.eventFlags|zS)}));f&&f.add(v)}return Utc22}(),JS=["Required","Analytics","SocialMedia","Advertising"],YS="([\\d,.]+)",QS="Unknown",XS="Edg/",ZS=[{ua:"OPR/",b:"Opera"},{ua:"PhantomJS",b:"PhantomJS"},{ua:"Edge",b:"Edge"},{ua:XS,b:"Edge"},{ua:"Electron",b:"Electron"},{ua:"Chrome",b:"Chrome"},{ua:"Trident",b:"MSIE"},{ua:"MSIE ",b:"MSIE"},{ua:"Firefox",b:"Firefox"},{ua:"Safari",b:"Safari"},{ua:"SkypeShell",b:"SkypeShell"}],ev=[{br:"Microsoft Edge",b:"Edge"},{br:"Google Chrome",b:"Chrome"},{br:"Opera",b:"Opera"}];function _userAgentContainsString2(g,f){return f.indexOf(g)>-1}function _getBrandVersion2(g,f){for(var S=0;S<f.length;S++)if(g==f[S].brand)return f[S].version;return null}function _getBrowserName2(g){if(g)for(var f=0;f<ZS.length;f++)if(_userAgentContainsString2(ZS[f].ua,g))return ZS[f].b;return QS}function _getBrowserVersion2(g,f){return"MSIE"===f?_getIeVersion2(g):_getOtherVersion2(f,g)}function _getIeVersion2(g){var f=g.match(new RegExp("MSIE "+YS));if(f)return f[1];var S=g.match(new RegExp("rv:"+YS));return S?S[1]:void 0}function _getOtherVersion2(g,f){"Safari"===g?g="Version":"Edge"===g&&_userAgentContainsString2(XS,f)&&(g="Edg");var S=f.match(new RegExp(g+"/"+YS));return S||"Opera"===g&&(S=f.match(new RegExp("OPR/"+YS)))?S[1]:QS}function _getScreenResolution2(){var g={h:0,w:0},f=Gl();return f&&f.screen&&(g.h=screen.height,g.w=screen.width),g}function _getUserConsent2(){return this.getUserConsent()}var tv=function(){function Web22(g,f,S){var v=safeGetCookieMgr2(f),C=g||{},_=null,T=null,I=null,b=null,A=null,P=null,R=null;dynamicProto2(Web22,this,(function(f){_populateDefaults(g);var M=getLocation2();if(M){var w=M.hostname;w&&(f.domain="file:"===M.protocol?"local":w)}var O=_getScreenResolution2();function _parseUserAgent(g,f){if(ul(f))try{for(var S=0;S<ev.length;S++){var v=_getBrandVersion2(ev[S].br,f);if(v)return A=ev[S].b,void(P=v)}}catch(g){}if(g){var C=_getBrowserName2(g);A=C,P=_getBrowserVersion2(g,C)}}function _setBrowser(g){I=g}function _setBrowserVer(g){b=g}function _getBrowser(){return I||A}function _getBrowserVer(){return b||P}f.screenRes=O.w+"X"+O.h,f.getUserConsent=function(){return C.userConsented||!!getCookieValue2(v,C.userConsentCookieName||"MSCC")},f.getUserConsentDetails=function(){var g=null;try{var f=C.callback;if(f&&f.userConsentDetails){var S=f.userConsentDetails();if(S){g=C.disableConsentDetailsSanitize?S:{};for(var v=0;v<JS.length;v++){var _=JS[v];g[_]=S[_]||!1}}}return null!==R&&((g=g||{}).GPC_DataSharingOptIn=!!R),g?JSON.stringify(g):null}catch(g){}};var _getGpcDataSharing=function(){return R},_setGpcDataSharing=function(g){R=ml(g)?g:null,C.gpcDataSharingOptIn=R};function _populateDefaults(g){var f=onConfigChange2(g,(function(){if((C=g).populateBrowserInfo){var f=C.userAgent,S=(C.userAgentData||{}).brands;if(f!==_||S!==T){if(!f||!S||0===S.length){var v=Kl();v&&(f=f||v.userAgent||"",S=S||(v.userAgentData||{}).brands)}_parseUserAgent(f,S),_=f,T=S}}R=ml(C.gpcDataSharingOptIn)?C.gpcDataSharingOptIn:null}));S&&S.add(f)}objDefineProps2(f,{userConsent:{g:f.getUserConsent},browser:{s:_setBrowser,g:_getBrowser},browserVer:{s:_setBrowserVer,g:_getBrowserVer},gpcDataSharingOptIn:{g:_getGpcDataSharing,s:_setGpcDataSharing}})}))}return Web22._staticInit=void objDefine2(Web22.prototype,"userConsent",{g:_getUserConsent2}),Web22}();function _applyExtValues2(g,f,S,v,C){var _=f.ext[dS[g]];if(_)try{objForEachKey2(v,(function(g,f){if(dl(f)||pl(f)||ml(f)){var v=_[S[g]];!C&&(v||dl(v)||pl(v)||ml(v))&&(f=v),_[S[g]]=f}}))}catch(g){}return _}var iv,nv=function(){function TelemetryContext4(g,f,S,v){dynamicProto2(TelemetryContext4,this,(function(C){C.app=new RS(f,S,v),C.cloud=new MS,C.user=new GS(g,f,S,v),C.os=new VS(f,v),C.web=new tv(f,S,v);var _=new HS(g,S,v),T=new OS(f,S,v),I=new KS(f,v);C.loc=new DS,C.device=new wS;var b=new AS(S,f,v);C.session=new IS;var A=void 0,P=createDistributedTraceContextFromTraceCtx2(new $S(f,A,A,A,v),_getTraceCtx()),R=!(f||{}).eventContainExtFields;function _getSessionId(){var g=C.session;if(g&&dl(g.customId))return g.customId;b.update();var f=b.automaticSession;if(f){var S=f.getId();S&&dl(S)&&(g.automaticId=S)}return g.automaticId}function _getTraceCtx(){var g=P;return S&&S.getTraceCtx&&(g=S.getTraceCtx(!1)||P),g}C.getTraceCtx=function(){return P},C.getSessionId=_getSessionId,C.applyApplicationContext=function(g){var f,S=C.app;_applyExtValues2(4,g,hS,((f={})[0]=S.id,f[1]=S.ver,f[2]=S.name,f[3]=S.locale,f[4]=S.getExpId(),f[5]=S.env,f),R)},C.applyUserContext=function(g){var f,S=C.user;_applyExtValues2(0,g,gS,((f={})[1]=S.getLocalId(),f[0]=S.locale,f[2]=S.id,f),R)},C.applyWebContext=function(g){var f,S=C.web;_applyExtValues2(3,g,uS,((f={})[0]=S.domain,f[1]=S.browser,f[2]=S.browserVer,f[3]=S.screenRes,f[5]=S.getUserConsentDetails(),f[4]=S.getUserConsent(),f),R)},C.applyOsContext=function(g){var f,S=C.os;_applyExtValues2(5,g,pS,((f={})[0]=S.name,f[1]=S.ver,f),R)},C.applySdkContext=function(g){var f;_applyExtValues2(6,g,mS,((f={})[2]=_.installId,f[1]=_.getSequenceId(),f[3]=_.epoch,f),R)},C.applyIntWebContext=function(g){var f;_applyExtValues2(7,g,fS,((f={})[0]=T.getMsfpc(),f[1]=T.getAnid(),f[2]=T.serviceName,f),R)},C.applyUtcContext=function(g){var f,S=((f={})[0]=I.popSample,f);I.eventFlags>0&&(S[1]=I.eventFlags),_applyExtValues2(8,g,SS,S,R)},C.applyLocContext=function(g){var f;_applyExtValues2(9,g,vS,((f={})[0]=C.loc.tz,f),R)},C.applySessionContext=function(g){var f;_applyExtValues2(4,g,CS,((f={})[0]=_getSessionId(),f),R)},C.applyDeviceContext=function(g){var f,S=C.device;_applyExtValues2(1,g,yS,((f={})[0]=S.localId,f[2]=S.make,f[3]=S.model,f[1]=S.deviceClass,f),R)},C.applyCloudContext=function(g){var f,S=C.cloud;_applyExtValues2(10,g,ES,((f={})[0]=S.role,f[1]=S.roleInstance,f[2]=S.roleVer,f),R)},C.applyAITraceContext=function(g){var S;if(f.enableApplicationInsightsTrace){var v=_getTraceCtx();v&&_applyExtValues2(2,g,_S,((S={})[0]=v.getTraceId(),S[1]=v.getName(),S[2]=v.getSpanId(),S),!1)}},C.applyDistributedTraceContext=function(g){var f,S=_getTraceCtx();if(S){var v=((f={})[0]=S.getTraceId(),f[1]=S.getSpanId(),f),C=S.getTraceFlags();isNullOrUndefined2(C)||(v[2]=C),_applyExtValues2(11,g,TS,v,!1)}}}))}return TelemetryContext4.__ieDyn=1,TelemetryContext4}();function createDistributedTraceContextFromTraceCtx2(g,f){var S=g||{};return{getName:function(){return S.name},setName:function(g){f&&f.setName(g),S.name=g},getTraceId:function(){return S.traceId},setTraceId:function(g){f&&f.setTraceId(g),isValidTraceId2(g)&&(S.traceId=g)},getSpanId:function(){return S.parentId},setSpanId:function(g){f&&f.setSpanId(g),isValidSpanId2(g)&&(S.parentId=g)},getTraceFlags:function(){return S.traceFlags},setTraceFlags:function(g){f&&f.setTraceFlags(g),S.traceFlags=g}}}var rv=[dS[4],dS[0],dS[3],dS[5],dS[6],dS[7],dS[8],dS[9],dS[1],dS[2],dS[11],dS[10]],sv=objDeepFreeze2({populateBrowserInfo:!1,populateOperatingSystemInfo:!1,userAgent:cfgDfString2(),userAgentData:cfgDfMerge2({brands:iv,mobile:iv,platform:iv}),userConsentCookieName:cfgDfString2(),userConsented:!1,serviceName:cfgDfString2(),env:cfgDfString2(),expId:cfgDfString2(),sessionRenewalMs:18e5,sessionExpirationMs:864e5,sessionAsGuid:null,cookieDomain:cfgDfString2(),namePrefix:cfgDfString2(),enableApplicationInsightsTrace:!1,enableApplicationInsightsUser:!1,hashIdentifiers:!1,dropIdentifiers:!1,scrubIpOnly:!1,callback:cfgDfMerge2({userConsentDetails:null}),gpcDataSharingOptIn:iv,idLength:22,enableDistributedTracing:!1,eventContainExtFields:!1}),av=function(g){function PropertiesPlugin22(){var f,S,v,C=g.call(this)||this;return C.identifier="SystemPropertiesCollector",C.priority=3,C.version="4.2.1",dynamicProto2(PropertiesPlugin22,C,(function(g,C){function _initDefaults(){f=null,S={}}function _populateDefaults(S){var C=g.identifier,_=g.core;g._addHook(onConfigChange2(S,(function(){var g=createProcessTelemetryContext2(null,S,_);v=g.getExtCfg(C,sv)}))),f=new nv(S,v,_,g._unloadHooks),_&&_.setTraceCtx&&_.setTraceCtx(f.getTraceCtx())}function _addPropertiesIfAbsent(g,f){g&&objForEachKey2(g,(function(g,S){f[g]||(f[g]=S)}))}_initDefaults(),g.initialize=function(g,f,S){C.initialize(g,f,S),_populateDefaults(g)},g.processTelemetry=function(C,_){setProcessTelemetryTimings2(C,g.identifier),_=g._getTelCtx(_);var T=C.ext=C.ext?C.ext:{};C.data=C.data?C.data:{},arrForEach2(rv,(function(g){T[g]=T[g]||{}})),f&&(f.applyUtcContext(C),f.applyApplicationContext(C),f.applyUserContext(C),f.applyWebContext(C),f.applyOsContext(C),f.applySdkContext(C),f.applyIntWebContext(C),f.applyLocContext(C),f.applySessionContext(C),f.applyDeviceContext(C),v.enableApplicationInsightsTrace&&f.applyAITraceContext(C),v.enableDistributedTracing&&f.applyDistributedTraceContext(C),f.applyCloudContext(C)),arrForEach2(Al(T),(function(g){0===Al(T[g]).length&&delete T[g]})),_addPropertiesIfAbsent(S,C.data),g.processNext(C,_)},g.getPropertiesContext=function(){return f},g.setProperty=function(g,f){S[g]=f},g._doTeardown=function(g,S){var v=(g||{}).core();if(v&&v.getTraceCtx&&f){var C=v.getTraceCtx(!1);C&&C===f.getTraceCtx()&&v.setTraceCtx(null)}_initDefaults()},g._getDbgPlgTargets=function(){return[v]}})),C}return __extendsFn2(PropertiesPlugin22,g),PropertiesPlugin22.__ieDyn=1,PropertiesPlugin22}(Ig),ov=function(){function BaseContext22(g){this._setOverride=function(f,S){g.setOverride(f,S)},this._getOverride=function(f){return g.getOverride(f)}}return BaseContext22}(),lv=function(g){function ApplicationContext22(f,S,v){var C=g.call(this,f)||this,_=C;_.setId=function(g){_._setOverride(hS.id,g)},_.getId=function(){return _._getOverride(hS.id)},_.setVer=function(g){_._setOverride(hS.ver,g)},_.getVer=function(){return _._getOverride(hS.ver)},_.setName=function(g){_._setOverride(hS.appName,g)},_.getName=function(){return _._getOverride(hS.appName)},_.setLocale=function(g){_._setOverride(hS.locale,g)},_.getLocale=function(){return _._getOverride(hS.locale)},_.setEnv=function(g){_._setOverride(hS.env,g)},_.getEnv=function(){return _._getOverride(hS.env)},_.setExpId=function(g){_._setOverride(hS.expId,RS.validateAppExpId(g))},_.getExpId=function(){return _._getOverride(hS.expId)};var T=onConfigChange2(S,(function(){S&&(isUndefined4(S.env)||_.setEnv(S.env),isNullOrUndefined2(S.expId)||_.setExpId(S.expId))}));return v&&v.add(T),C}return __extendsFn2(ApplicationContext22,g),ApplicationContext22}(ov),cv=function(g){function CloudContext22(f){var S=g.call(this,f)||this,v=S;return v.setRole=function(g){v._setOverride(ES.role,g)},v.getRole=function(){return v._getOverride(ES.role)},v.setRoleInstance=function(g){v._setOverride(ES.roleInstance,g)},v.getRoleInstance=function(){return v._getOverride(ES.roleInstance)},v.setRoleVer=function(g){v._setOverride(ES.roleVer,g)},v.getRoleVer=function(){return v._getOverride(ES.roleVer)},S}return __extendsFn2(CloudContext22,g),CloudContext22}(ov),dv=function(g){function DataContext22(f){var S=g.call(this,f)||this,v=S;return v.setProperty=function(g,f){v._setOverride(g,f)},v.getProperty=function(g){return v._getOverride(g)},S}return __extendsFn2(DataContext22,g),DataContext22}(ov),hv=function(g){function DeviceContext22(f){var S=g.call(this,f)||this,v=S;return v.setLocalId=function(g){v._setOverride(yS.localId,g)},v.getLocalId=function(){return v._getOverride(yS.localId)},v.setDeviceClass=function(g){v._setOverride(yS.deviceClass,g)},v.getDeviceClass=function(){return v._getOverride(yS.deviceClass)},v.setMake=function(g){v._setOverride(yS.make,g)},v.getMake=function(){return v._getOverride(yS.make)},v.setModel=function(g){v._setOverride(yS.model,g)},v.getModel=function(){return v._getOverride(yS.model)},S}return __extendsFn2(DeviceContext22,g),DeviceContext22}(ov),uv=function(g){function LocContext22(f){var S=g.call(this,f)||this,v=S;return v.setTz=function(g){v._setOverride(vS.tz,g)},v.getTz=function(){return v._getOverride(vS.tz)},S}return __extendsFn2(LocContext22,g),LocContext22}(ov),gv=function(g){function OperatingSystemContext22(f,S,v){var C=g.call(this,f)||this,_=C,T=null;_.setOsName=function(g){_._setOverride(pS.osName,g)},_.getOsName=function(){return _._getOverride(pS.osName)},_.setVer=function(g){_._setOverride(pS.ver,g)},_.getVer=function(){return _._getOverride(pS.ver)};var I=onConfigChange2(S,(function(){!T&&S.userAgent&&S.populateOperatingSystemInfo&&(T=new VS(S,v)),T&&(_.setOsName(T.name),_.setVer(T.ver))}));return v&&v.add(I),C}return __extendsFn2(OperatingSystemContext22,g),OperatingSystemContext22}(ov);function _getEventRoot2(g,f){if(g)for(var S=0;S<f.length;S++){var v=f[S];isNullOrUndefined2(g[v])&&(g[v]={}),g=g[v]}return g}function _setOverride2(g,f,S){if(g&&f){var v=f.split("."),C=v[v.length-1];v.length>1&&(g=_getEventRoot2(g,v.slice(0,-1))),isNullOrUndefined2(S)?isUndefined4(g[C])||delete g[C]:g[C]=S}}var pv,mv,fv=function(){function OverrideContainer22(g){var f=this,S=[];f.setOverride=function(g,f){g&&S.push({key:g,value:f})},f.hasOverride=function(g){var f=!1;return arrForEach2(S,(function(S){S.key===g&&(f=!0)})),f},f.getOverride=function(g){var f;return arrForEach2(S,(function(S){S.key===g&&(f=S.value)})),f},f.applyOverrides=function(f,v){if(S.length>0)try{var C=_getEventRoot2(f,g);arrForEach2(S,(function(g){_setOverride2(C,g.key,g.value)}))}catch(g){}}}return OverrideContainer22}(),Sv=function(g){function UserContext22(f){var S=g.call(this,f)||this,v=S;return v.setLocalId=function(g){v._setOverride(gS.localId,g)},v.getLocalId=function(){return v._getOverride(gS.localId)},v.setLocale=function(g){v._setOverride(gS.locale,g)},v.getLocale=function(){return v._getOverride(gS.locale)},v.setId=function(g){v._setOverride(gS.id,g)},v.getId=function(){return v._getOverride(gS.id)},S}return __extendsFn2(UserContext22,g),UserContext22}(ov),vv=function(g){function WebContext22(f,S,v){var C=g.call(this,f)||this,_=C;_.setDomain=function(g){_._setOverride(uS.domain,g)},_.getDomain=function(){return _._getOverride(uS.domain)},_.setBrowser=function(g){_._setOverride(uS.browser,g)},_.getBrowser=function(){return _._getOverride(uS.browser)},_.setBrowserVer=function(g){_._setOverride(uS.browserVer,g)},_.getBrowserVer=function(){return _._getOverride(uS.browserVer)},_.setScreenRes=function(g){_._setOverride(uS.screenRes,g)},_.getScreenRes=function(){return _._getOverride(uS.screenRes)},_.setUserConsent=function(g){_._setOverride(uS.userConsent,g)},_.getUserContext=function(){return _._getOverride(uS.userConsent)};var T=onConfigChange2(S,(function(){S&&(isUndefined4(S.userConsented)||_.setUserConsent(S.userConsented))}));return v&&v.add(T),C}return __extendsFn2(WebContext22,g),WebContext22}(ov),Cv="ext",yv="data",Ev=function(){function OverrideContext22(g,f,S,v){var C=this,_={};function _getContainer(g){for(var f="",S=0;S<g.length;S++)f&&(f+="_"),f+=g[S];return isUndefined4(_[f])&&(_[f]=new fv(g)),f?_[f]:null}C.data=new dv(_getContainer([yv])),C.app=new lv(_getContainer([Cv,dS.AppExt]),f,v),C.user=new Sv(_getContainer([Cv,dS.UserExt])),C.os=new gv(_getContainer([Cv,dS.OSExt]),f,v),C.web=new vv(_getContainer([Cv,dS.WebExt]),f,v),C.device=new hv(_getContainer([Cv,dS.DeviceExt])),C.loc=new uv(_getContainer([Cv,dS.LocExt])),C.cloud=new cv(_getContainer([Cv,dS.CloudExt])),C.applyOverrides=function(g,f){var S=Al(_);S&&S.length>0&&arrForEach2(S,(function(S){_[S].applyOverrides(g,f)}))}}return OverrideContext22}(),_v=void 0,Tv=objDeepFreeze2({env:_v,expId:_v,populateOperatingSystemInfo:!1,userAgent:_v,userAgentData:cfgDfMerge2({brands:_v,mobile:_v,platform:_v}),userConsented:_v}),Iv="OverridePropertiesPlugin",bv=function(g){function OverridePropertiesPlugin22(){var f=g.call(this)||this;f.identifier=Iv,f.priority=4,f.version="4.2.1";var S=null;return dynamicProto2(OverridePropertiesPlugin22,f,(function(g,v){g.initialize=function(f,S,C){v.initialize(f,S,C),g._baseInit(f,S,C)},g.processTelemetry=function(S,v){setProcessTelemetryTimings2(S,f.identifier),v=g._getTelCtx(v);var C=g.getOverrideContext();C&&C.applyOverrides(S,v),g.processNext(S,v)},g._baseInit=function(v,C,_){S=new Ev(v,f._getTelCtx().getExtCfg(f.identifier,Tv),C,g._unloadHooks)},g.setProperty=function(g,f){S&&S.data.setProperty(g,f)},g.getOverrideContext=function(){return S}})),f}return __extendsFn2(OverridePropertiesPlugin22,g),OverridePropertiesPlugin22.__ieDyn=1,OverridePropertiesPlugin22}(Ig),Av="_dropInst",Pv=["channelConfiguration","propertyStorageOverride"];function _fixupExtensionConfig2(g){if(g&&ul(g.extensionConfig)){var f=g.extensionConfig,S={};objForEachKey2(f,(function(g,f){hl(f)||lc(g,"Symbol(")||(S[g]=f)})),g.extensionConfig=S}return g}function _copyObjProperties2(g,f){if(f)for(var S=Al(f),v=0;v<S.length;v++){var C=S[v];vl(g,C)||lc(C,"Symbol(")||(g[C]=f[C])}}function _proxyReadonlyProperty2(g,f,S){var v;return objDefine2(g,f,{g:function(){return isPrimitive2(S)?S:(ul(S)?(ul(v)||(v=[]),v.length=S.length):isObject3(v)||(v={}),objForEachKey2(S,(function(g,f){lc(g,"Symbol(")||_proxyReadonlyProperty2(v,g,f)})),v)}})}function _isChannel2(g){return g.pause&&g.teardown&&g.flush}function _getEndpointUrl2(g,f){var S=null;if(f){f.endpointUrl&&(S=f.endpointUrl);var v=(f.extensionConfig||{})[g]||{};v.overrideEndpointUrl&&(S=v.overrideEndpointUrl)}return S}var Rv=objDeepFreeze2({cookieCfg:{},channelConfiguration:cfgDfMerge2({}),propertyConfiguration:cfgDfMerge2({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:cfgDfMerge2({}),createPerfMgr:mv,loggingLevelConsole:0}),Mv=objDeepFreeze2({propertyConfiguration:cfgDfMerge2({}),cookieCfg:cfgDfMerge2({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:cfgDfMerge2((pv={},pv[Iv]=cfgDfMerge2({}),pv)),createPerfMgr:mv,loggingLevelConsole:0}),wv=function(g){function ChildNotificationManager22(f,S){var v=g.call(this)||this;return dynamicProto2(ChildNotificationManager22,v,(function(g,v){function _getEvents(g){var S=[];return g&&arrForEach2(g,(function(g){g.iKey===f&&S.push(g)})),S}function _hasListeners(f){if(g[f]&&g.listeners)for(var S=0;S<g.listeners.length;S++){var v=g.listeners[S];if(v&&v[f])return!0}return!1}var C={eventsSent:function(f){if(_hasListeners("eventsSent")){var S=_getEvents(f);S.length>0&&g.eventsSent(S)}},eventsDiscarded:function(f,S){if(_hasListeners("eventsDiscarded")){var v=_getEvents(f);v.length>0&&g.eventsDiscarded(v,S)}},eventsSendRequest:function(f,S){_hasListeners("eventsSendRequest")&&g.eventsSendRequest(f,S)},perfEvent:function(f){_hasListeners("perfEvent")&&g.perfEvent(f)}};S.addNotificationListener(C)})),v}return __extendsFn2(ChildNotificationManager22,g),ChildNotificationManager22.__ieDyn=1,ChildNotificationManager22}(ag),Ov=function(){function ApplicationInsightsManager22(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w,O=null,D=null;dynamicProto2(ApplicationInsightsManager22,this,(function(N){function _initDefaults(){g=createDynamicConfig2({},Rv,null),f=[],S=null,v=null,C=[],_=[],T={},I=null,b=null,A=null,R=null,M=null,w=!1,g.cfg.loggingLevelConsole=1,P=new Gu(g.cfg),objDefine2(N,"sharedConfig",{g:function(){return w&&_initializeSharedInstance(),g.cfg}})}function _registerPlugin(f,S){var v;if(void 0===S&&(S=null),f){(_isChannel2(f)?_:C).push(f);var T=f.identifier,I=g.cfg.extensionConfig;g.setDf(I,((v={})[T]={ref:!0,v:S||{}},v))}return f}function _initializeSharedChannels(){var f=g.cfg,S=f.channels,v=new tS,C=v.identifier,_=!1;b=null,A=null,arrForEach2(S,(function(g){_||arrForEach2(g,(function(g){if(!hl(g)&&(_registerPlugin(g),g.identifier===C))return b=g,_=!0,-1}))})),_||(b=_registerPlugin(v,f.channelConfiguration),S.length>0?arrAppend2(S[0],b):f.channels.push([b]))}function _initializeSharedExtensions(S){var v=g.cfg;f=[],I=_registerPlugin(new av,v.propertyConfiguration),f.push(I),v.extensions&&arrForEach2(v.extensions,(function(g){hl(g)||_registerPlugin(g)})),S&&arrForEach2(S,(function(g){g&&!hl(g)&&f.push(_registerPlugin(g))}))}function _initializeSharedInstance(){S||(w||_throwInternal2(N.diagLog(),2,520,"The Shared Manager is not yet created, the returned shared instance will be overwritten"),g.cfg.instrumentationKey=g.cfg.instrumentationKey||"_not_defined_",v=new ag,(S=new Dv(N,N.diagLog(),v)).initialize(g.cfg,f),S.isInitialized()&&(objDefineProps2((g=getDynamicConfigHandler2(S.config)).cfg,{channelConfiguration:{g:function(){return g.cfg.extensionConfig[b.identifier]}},propertyConfiguration:{g:function(){return g.cfg.extensionConfig[I.identifier]}}}),b&&(A=_getEndpointUrl2(b.identifier,g.cfg))),O&&S.setCookieMgr(O))}function _createInstanceConfig(f,S){var v=[],C=g.cfg,_={};if(objForEachKey2(C.extensionConfig,(function(g,f){g===b.identifier||g===I.identifier||lc(g,"Symbol(")||(g!==Iv?_proxyReadonlyProperty2(_,g,f):(_[g]={},_copyObjProperties2(_[g],f)))})),S){S.extensions&&S.extensions.length>0&&(v=arrAppend2(v,S.extensions));var T=S.extensionConfig;T&&(vl(T,b.identifier)&&Al(T).length>0&&_throwInternal2(N.diagLog(),2,511,"Instances cannot override the shared Post channel configuration, the shared will be used!"),_copyObjProperties2(_,T))}var A={instrumentationKey:f,channels:_createMergedChannels(S),extensions:v,extensionConfig:_};return _copyObjProperties2(A,S),A}function _createMergedChannels(f){var S=g.cfg,v=[[]];return S.channels&&arrForEach2(S.channels,(function(g,f){hl(g)||(v[f]=v[f]||[],v[f]=v[f].concat(g))})),f&&f.channels&&arrForEach2(f.channels,(function(g,f){hl(g)||(v[f]=v[f]||[],v[f]=v[f].concat(g))})),v}function _createMergedExtensions(g){var S=[];return f&&f.length>0&&(S=S.concat(f)),g&&g.length>0&&(S=S.concat(g)),S}function _unloadInstance(g,f,S,v){var C=T[g];C&&(C.inst&&C.inst.isInitialized()?C.inst.unload(f,(function(f){S&&S(g,f)}),v):S&&S(g,{reason:50,isAsync:f,flushComplete:!1}))}_initDefaults(),N.diagLog=function(){return P||(P=new Gu(g.cfg)),P},N.getCookieMgr=function(){return _initializeSharedInstance(),O||S.getCookieMgr()},N.setCookieMgr=function(g){O=g,S&&S.setCookieMgr(g)},N.getPerfMgr=function(){return M||g&&g.cfg.enablePerfMgr&&(M=D||new ug(N.getNotifyMgr())),M},N.setPerfMgr=function(g){D=g,M=g},N.create=function(f,v){w?_throwInternal2(N.diagLog(),2,514,"Shared Manager has already been initialized."):(g=createDynamicConfig2(_fixupExtensionConfig2(f?objExtend2({},f):{}),Rv,null),S=null,_initializeSharedChannels(),_initializeSharedExtensions(v),w=!0)},N.getInst=function(g){return(T[g]||{}).inst},N.newInst=function(f,C,_){var I=N.getInst(f);if(I)return _throwInternal2(N.diagLog(),2,514,"Instance already exists for ["+f+"]"),I;if(_initializeSharedInstance(),S.isInitialized()){var P=_createInstanceConfig(f,C);if(b){var R=_getEndpointUrl2(b.identifier,P);A&&R&&A!==R&&_throwInternal2(N.diagLog(),2,511,"The endpointUrl mismatch, shared Url ["+A+"] is different from configured ["+R+"] shared will be used!")}var M=new wv(f,v);if(I=new Dv(N,N.diagLog(),M),T[f]={iKey:f,inst:I,notifyMgr:M},I.setPerfMgr(N.getPerfMgr()),I.initialize(P,_createMergedExtensions(_)),I.isInitialized()){var w=I.config;objDefineProps2(w,{propertyConfiguration:{g:function(){return w.extensionConfig[Iv]}}});try{delete w.endpointUrl,delete w.channelConfiguration,delete w.propertyStorageOverride}catch(g){_throwInternal2(N.diagLog(),2,108,"Failed to remove unused defaults!")}objForEachKey2(g.cfg,(function(g,f){vl(w,g)||lc(g,"Symbol(")||Xl(Pv,g)||_proxyReadonlyProperty2(w,g,f)}))}else _throwInternal2(N.diagLog(),2,520,"Failed to initialize new instance!"),I=null,delete T[f]}return I},N.getSharedPlugin=function(g){_initializeSharedInstance();var f=null,v=S.getPlugin(g);return v&&(f=v.plugin),f},N.getPropertyManager=function(){return _initializeSharedInstance(),I},N.getPostChannel=function(){return _initializeSharedInstance(),b},N.getNotifyMgr=function(){return R||(R=new ag),R},N.unload=function(g,f,v){var C,_=Al(T),I=_.length+1,b={reason:50,isAsync:g,flushComplete:!1};function _doUnload(g,S){0==--I&&(_initDefaults(),f&&f(S))}return g&&!f&&(C=createPromise2((function(g){f=g}))),S&&(arrForEach2(_,(function(f){_unloadInstance(f,g,(function(g,f){_doUnload(g,f)}),v)})),S.isInitialized()&&(S.unload(g,(function(g){_doUnload(null,b=g)}),v),S=null)),_doUnload(null,b),C},N.addUnloadHook=function(g){_initializeSharedInstance(),S.addUnloadHook(g)},N.addSharedPlugin=function(g,f,v,C){return _initializeSharedInstance(),S.addPlugin(g,f,v,C)},N.updateCfg=function(g,f){return _initializeSharedInstance(),S.updateCfg(g,f)},N.evtNamespace=function(){return _initializeSharedInstance(),S.evtNamespace()},N.addUnloadCb=function(g){_initializeSharedInstance(),S.addUnloadCb(g)},N.onCfgChange=function(g){return _initializeSharedInstance(),S.onCfgChange(g)},N[Av]=function(g){g&&T.iKey&&delete T[g]}}))}return ApplicationInsightsManager22.__ieDyn=1,ApplicationInsightsManager22}(),Dv=function(g){function ApplicationInsights32(f,S,v){var C,_=g.call(this)||this,T=f;return dynamicProto2(ApplicationInsights32,_,(function(g,f){g.getSharedPropertyManager=function(){return T.getPropertyManager()},g.getSharedPostChannel=function(){return T.getPostChannel()},g.getOverridePropertyManager=function(){return C},g.initialize=function(_,T){doPerf2(g,(function(){return"ApplicationInsights:initialize"}),(function(){var I=[C=new bv];T&&(I=I.concat(T));var b=_.propertyConfiguration||{};if(_.propertyConfiguration)try{delete _.propertyConfiguration}catch(g){_.propertyConfiguration={}}_.extensionConfig=_.extensionConfig||{},_.extensionConfig[C.identifier]=b,_=createDynamicConfig2(_,Mv,S||g.logger,!1).cfg;try{f.initialize(_,I,S,v)}catch(f){_throwInternal2(g.logger,1,514,"Failed to initialize SDK."+dumpObj2(f))}}),(function(){return{config:_,extensions:T}}))},g.unload=function(S,v,C){return T[Av]&&T[Av]((g.config||{}).instrumentationKey),f.unload(S,v,C)}})),_}return __extendsFn2(ApplicationInsights32,g),ApplicationInsights32.__ieDyn=1,ApplicationInsights32}(yp),Nv=class{constructor(g){this.key=g.config.bwSeedOptions.localStorageKey||"bwSeed";const f=localStorage.getItem(this.key);parseInt(f)||localStorage.setItem(this.key,g.config.bwSeedOptions.constValue.toString())}getSeed(){const g=localStorage.getItem(this.key),f=parseInt(g);return isNaN(f)?void 0:f}saveSeed(g){localStorage.setItem(this.key,g.toString())}static localStorageAvailable(){try{const g=window.localStorage,f="someKey",S="someValue";return g.setItem(f,S),g.removeItem(f),!0}catch(g){return!1}}},kv=class _BandwidthMemoryStorage{constructor(g){_BandwidthMemoryStorage.value??(_BandwidthMemoryStorage.value=g.config.bwSeedOptions.constValue)}getSeed(){return _BandwidthMemoryStorage.value}saveSeed(g){_BandwidthMemoryStorage.value=g}},Lv=class{constructor(g){this.value=g}addValue(g){}getAggregated(){return this.value}},Fv=class{addValue(g){this.value=g}getAggregated(){return this.value}},xv=class{constructor(g){this.size=g,this.items=[]}clear(){this.items=[]}},Uv=class extends xv{get isFull(){return this.items.length>=this.size}add(g){return this.isFull&&this.items.shift(),this.items.push(g),!0}},Vv=class extends xv{add(g){return!(this.items.length>=this.size||(this.items.push(g),0))}},Bv=class{constructor(g){this.values=new Uv(g)}addValue(g){this.values.add(g)}getAggregated(){return Math.floor(average(this.values.items))}},Hv=class{constructor(){this.total=0,this.duration=0,this.max=0,this.minNonZero=Number.MAX_SAFE_INTEGER}get avg(){return 0!==this.duration?this.total/this.duration:0}get maxSample(){return this.max}get minNonZeroSample(){return this.minNonZero}captureSample(g){(g||0===g)&&(this.total+=g,this.duration++,this.max=Math.max(g,this.max),0!==g&&(this.minNonZero=Math.min(g,this.minNonZero)))}},$v=class{constructor(){this.sampleCounts={}}get min(){const g=Object.keys(this.sampleCounts).map(Number).filter((g=>g>0));return g.length>0?Math.min(...g):0}get max(){const g=Object.keys(this.sampleCounts).map(Number);return g.length>0?Math.max(...g):0}get mode(){const g=Object.keys(this.sampleCounts).map(Number);return g.length>0?g.reduce(((g,f)=>this.sampleCounts[f]>this.sampleCounts[g]?f:g),g[0]):0}captureSample(g){var f;if(void 0!==g){const S=`${g}`;(f=this.sampleCounts)[S]??(f[S]=0),this.sampleCounts[S]++}}},jv=class{get delta(){if(void 0!==this.cur&&void 0!==this.last)return this.cur-this.last}captureSample(g,f){void 0!==g&&(void 0!==this.cur&&(this.last=this.cur),this.cur=g)}},Gv=class{constructor(g=0){this.precision=g}get delta(){if(void 0!==this.currentSample&&void 0!==this.prevSample){let g=1;return void 0!==this.currentTimestamp&&void 0!==this.prevTimestamp&&(g=(this.currentTimestamp-this.prevTimestamp)/1e3),g&&round((this.currentSample-this.prevSample)/g,this.precision)}}captureSample(g,f){if(this.currentTimestamp!==f){if(void 0===g)return this.prevSample=void 0,this.currentSample=void 0,this.prevTimestamp=void 0,void(this.currentTimestamp=void 0);void 0!==this.currentSample&&(this.prevSample=this.currentSample),this.prevTimestamp=this.currentTimestamp,this.currentTimestamp=f,this.currentSample=g}}},qv=class{constructor(){this.startTime=Date.now()}get elapsed(){return round((Date.now()-this.startTime)/1e3,0)}},Wv=class{constructor(g){this.numOfHistogramSamples=g,this.eventCount=0,this.totalActiveDuration=0,this.countBuckets={seconds1to3:0,seconds3to5:0,seconds5to8:0,seconds8to15:0,seconds15to60:0,seconds60toMax:0},this.timestampBuckets={seconds1to3:[],seconds3to5:[],seconds5to8:[],seconds8to15:[],seconds15to60:[],seconds60toMax:[]},this.averager=new Hv}get active(){return!!this.current}get ongoingDuration(){return this.current?.elapsed||0}get avgDuration(){return this.averager.avg}get longestDuration(){return this.averager.maxSample}get numEvents(){return this.eventCount}get totalDuration(){return this.current?this.totalActiveDuration+this.current.elapsed:this.totalActiveDuration}get timestamps(){return deepClone(this.timestampBuckets)}get counts(){return deepClone(this.countBuckets)}set active(g){if(!this.current&&g)this.current=new qv;else if(this.current&&!g){const g=this.current.elapsed;this.averager.captureSample(g),this.totalActiveDuration+=g;for(const f of Object.keys(qt.HISTOGRAM_BATCH))if(g<=qt.HISTOGRAM_BATCH[f]){this.countBuckets[f]++,arrayLimitedPush22(this.timestampBuckets[f],this.current.startTime,this.numOfHistogramSamples);break}this.eventCount++,this.current=void 0}}},zv=class{constructor(){this.sampleChangeCount=0,this.sampleDurations={}}get durations(){return deepClone(this.sampleDurations)}get sortedDurations(){return Object.keys(this.sampleDurations).sort(((g,f)=>this.sampleDurations[f]-this.sampleDurations[g]))}get durationRatios(){const g={};let f=0;for(const g in this.sampleDurations)f+=this.sampleDurations[g];for(const S in this.sampleDurations)g[S]=round(this.sampleDurations[S]/f*100);return g}get changeCount(){return this.sampleChangeCount}captureSample(g){this.sampleDurations[g]||(this.sampleDurations[g]=0),this.sampleDurations[g]++,g!==this.lastSample&&(this.sampleChangeCount++,this.lastSample=g)}},Kv=class{constructor(g,f){this.validTimeBetweenFramesArrival=g,this.invalidFPSAboveMax=f,this.lastSampleTimestamp=-1,this.fpsHarmonicSumWeigtsTs=0,this.fpsHarmonicWeigtedSumsFramePerDelayTs=0}captureSample(g){const f=Date.now();if(g>0&&this.lastSampleTimestamp>0){const S=f-this.lastSampleTimestamp;if(this.lastSampleTimestamp=f,S<0||S>this.validTimeBetweenFramesArrival||g>this.invalidFPSAboveMax)return;const v=S/g;this.fpsHarmonicSumWeigtsTs+=S,this.fpsHarmonicWeigtedSumsFramePerDelayTs+=S*v}(this.lastSampleTimestamp<0||0===g)&&(this.lastSampleTimestamp=f)}get harmonicMean(){return this.fpsHarmonicWeigtedSumsFramePerDelayTs>0?1e3*this.fpsHarmonicSumWeigtsTs/this.fpsHarmonicWeigtedSumsFramePerDelayTs:0}},Jv=class{constructor(g){this.samplesNum=g,this.samples=[],this.sortedSamples=[],this.lastReport={avg:-1,max:-1,median:-1,p90:-1,volatilityPercent:-1}}isReportComplete(){return this.samples.length===this.samplesNum}getReport(){return this.lastReport}captureSample(g){void 0===g||g<0||(arrayLimitedPush22(this.samples,g,this.samplesNum),this.sortedSamples=deepClone(this.samples).sort(((g,f)=>g-f)),this.lastReport={avg:this.getAvg(),median:this.calculatePercentile(50),p90:this.calculatePercentile(90),max:this.calculatePercentile(100),volatilityPercent:this.getVolatility()})}getAvg(){return average(this.samples)}getVolatility(){const g=this.getAvg();if(0===g)return 0;let f=0;return this.samples.forEach((S=>{f+=Math.abs(S-g)})),round(f/this.samples.length*100/g,2)}calculatePercentile(g){if(g<0||g>100)throw new Error("Percentile must be between 0 and 100");const f=g/100*(this.sortedSamples.length-1),S=Math.floor(f),v=Math.ceil(f),C=f-S;return v>=this.sortedSamples.length?this.sortedSamples[S]:this.sortedSamples[S]*(1-C)+this.sortedSamples[v]*C}},Yv=class{constructor(){this.duration=0,this.reportAggr={avg:0,max:0,median:0,p90:0,volatilityPercent:0}}captureSample(g){!g||g.avg<0||(this.reportAggr={avg:this.reportAggr.avg+g.avg,max:Math.max(this.reportAggr.max,g.max),median:this.reportAggr.median+g.median,p90:this.reportAggr.p90+g.p90,volatilityPercent:this.reportAggr.volatilityPercent+g.volatilityPercent},this.duration++)}getReport(){if(0!==this.duration)return{avg:this.reportAggr.avg/this.duration,max:this.reportAggr.max,median:this.reportAggr.median/this.duration,p90:this.reportAggr.p90/this.duration,volatilityPercent:this.reportAggr.volatilityPercent/this.duration}}},Qv=class{constructor(g,f=0){this.overshootType=g,this.allowedOvershoot=f,this.past=[],this.totalOvershootDuration=0,this.lastAllowed=0}get isOvershooting(){return!!this.current}get events(){return this.current?[...this.past,this.current]:this.past}get totalDuration(){return this.totalOvershootDuration}captureSample(g,f){const S=round(g-f);S>this.allowedOvershoot&&(0===this.lastAllowed||f===this.lastAllowed||!this.current&&f>this.lastAllowed)?(this.totalOvershootDuration++,this.current?(this.current.min=Math.min(this.current.min,S),this.current.max=Math.max(this.current.max,S)):this.current={timestamp:Date.now(),min:S,max:S,type:this.overshootType}):this.current&&(this.current.duration=Date.now()-this.current.timestamp,this.past.push(this.current),this.current=void 0),this.lastAllowed=f}},Xv=class{constructor(g=!1){this.disableNormalization=g,this.prevLost=0,this.prevReceived=0,this.minPackets=100}calculate(g,f){if(void 0===g||void 0===f)return;const S=g-this.prevReceived,v=f-this.prevLost;if(S+v<this.minPackets)return;this.prevReceived=g,this.prevLost=f;const C=v*(this.disableNormalization?1:this.minPackets)/(v+S);return C>(this.disableNormalization?1:this.minPackets)?0:C}},Zv=class{constructor(){this.capturedSamples=[]}captureSample(g){g&&this.capturedSamples.push(g)}calculateStd(){if(!this.capturedSamples.length)return;const g=this.capturedSamples.reduce(((g,f)=>g+f),0)/this.capturedSamples.length,f=this.capturedSamples.map((f=>(f-g)**2)),S=f.reduce(((g,f)=>g+f),0)/f.length;return round(Math.sqrt(S),2)}getFirst(){return this.capturedSamples[0]}getLast(){if(this.capturedSamples.length)return this.capturedSamples[this.capturedSamples.length-1]}calculatePercentile(g){if(!this.capturedSamples.length)return;const f=this.capturedSamples.sort(((g,f)=>g-f)),S=(f.length-1)*g,v=Math.floor(S),C=S-v;return void 0!==f[v+1]?f[v]+C*(f[v+1]-f[v]):f[v]}};function isPowerEfficient(g){if(!g)return;const f=["libvpx","ffmpeg"];let S=!0;for(const v of f)if(g.toLowerCase().includes(v)){S=!1;break}return S}var eC=class{constructor(g){this.samplesCount=g,this.capturedSamples=[]}captureSample(g){void 0!==g&&arrayLimitedPush22(this.capturedSamples,g,this.samplesCount)}getRate(){if(!this.capturedSamples.length)return;const g=this.samplesCount/this.capturedSamples.length;return this.capturedSamples.reduce(((g,f)=>g+f))*g/this.samplesCount}},tC=class{constructor(g=5){this.limit=g,this.curWidth=0,this.curHeight=0,this.resolutionSwitches=[]}captureSample(g,f){g===this.curWidth&&f===this.curHeight||(arrayLimitedPush22(this.resolutionSwitches,`${g}x${f}`,this.limit),this.curWidth=g,this.curHeight=f)}get switches(){if(this.resolutionSwitches.length)return this.resolutionSwitches}};function calcMacroblockRate(g,f,S){return g&&f?Math.ceil(g/qt.MACROBLOCK_SIZE)*Math.ceil(f/qt.MACROBLOCK_SIZE)*S:0}var iC=class{constructor(){this.macroblockRateAveragerReceived=new Hv,this.macroblockRateAveragerDecoded=new Hv,this.maxDecoderLoss=0,this.decoderLoss=0}captureSample(g,f){this.macroblockRateAveragerReceived.captureSample(g),this.macroblockRateAveragerDecoded.captureSample(f);let S=this.maxDecoderLoss;g&&(S=(g-f)/g*100),this.decoderLoss=S,this.maxDecoderLoss=Math.max(S,this.maxDecoderLoss)}getReport(){return{macroblockRateReceivedMax:this.macroblockRateAveragerReceived.maxSample,macroblockRateReceivedAvg:this.macroblockRateAveragerReceived.avg,macroblockRateDecodedMax:this.macroblockRateAveragerDecoded.maxSample,macroblockRateDecodedAvg:this.macroblockRateAveragerDecoded.avg,macroblockRateMaxDecoderLossPercent:Math.floor(this.maxDecoderLoss),macroblockRateDecoderLossPercent:Math.floor(this.decoderLoss)}}},nC=class{constructor(){this.codecReport={}}captureSample(g,f){var S,v;const C=g.split("/").pop();return void 0===this.activeMsi||this.activeMsi!==f?(this.activeMsi=f,this.previousCodec=C,void((S=this.codecReport)[f]??(S[f]={[C]:1,codecSwitchCounter:0}))):this.previousCodec!==C?((v=this.codecReport[f])[C]??(v[C]=0),this.codecReport[f][C]++,this.codecReport[f].codecSwitchCounter++,void(this.previousCodec=C)):void this.codecReport[f][C]++}get report(){return this.codecReport}},rC=class{constructor(g=5){this.limit=g,this.curPowerEfficientCodecState=!1,this.powerEfficientCodecEvents=[],this.powerEfficientCodecEventOnCount=0,this.powerEfficientCodecEventOffCount=0}captureSample(g,f){if(g!==this.curPowerEfficientCodecState){const S={timestamp:Date.now(),powerEfficient:g,frameHeight:f};arrayLimitedPush22(this.powerEfficientCodecEvents,S,this.limit),this.curPowerEfficientCodecState=g,g?this.powerEfficientCodecEventOnCount++:this.powerEfficientCodecEventOffCount++}}get events(){if(this.powerEfficientCodecEvents.length)return this.powerEfficientCodecEvents}get eventOnCount(){return this.powerEfficientCodecEventOnCount}get eventOffCount(){return this.powerEfficientCodecEventOffCount}get curPowerEfficientEncoderState(){return this.curPowerEfficientCodecState}},sC=class{constructor(){this.bandwidthAverager=new Hv}addValue(g){this.bandwidthAverager.captureSample(g)}getAggregated(){return Math.floor(this.bandwidthAverager.avg)}},aC=-1,oC=class{constructor(g){this.configProvider=g,this.aggregator=this.getAggregator(),this.storage=this.getStorage(),this.cappingValue=this.configProvider.config.bwSeedOptions.cappingValue,this.minValue=this.configProvider.config.bwSeedOptions.minValue??aC}getSeed(){const g=this.storage.getSeed()??aC;return this.cappingValue>0?Math.min(Math.max(g,this.minValue),this.cappingValue):Math.max(g,this.minValue)}saveSeed(g){this.aggregator.addValue(g);const f=this.aggregator.getAggregated();this.storage.saveSeed(f)}getAggregator(){switch(this.configProvider.config.bwSeedOptions.aggregation){case"avg":return this.configProvider.config.bwSeedOptions.aggregateLastN>0?new Bv(this.configProvider.config.bwSeedOptions.aggregateLastN):new sC;case"last":return new Fv;default:return new Lv(this.configProvider.config.bwSeedOptions.constValue)}}getStorage(){return this.configProvider.config.bwSeedOptions.useLocalStorage&&Nv.localStorageAvailable()?new Nv(this.configProvider):new kv(this.configProvider)}},lC=M;function adjustResolutionToAspectRatio(g,f){const S=g.width/g.height,v=(0,lC.clone)(g);return S>f?v.width=Math.floor(g.height*f):S<f&&(v.height=Math.floor(g.width/f)),v}var cC=class _ConstraintsObject{constructor(g,f,S=!0,v=!1,C){this.audio=g,this.video=f,this.withTimeout=S,this.withEffect=v,this.withOverridenStream=C}clone(){const g=deepClone(this.video),f=deepClone(this.audio);return new _ConstraintsObject(f,g,this.withTimeout,this.withEffect,this.withOverridenStream)}},dC=class{constructor(g){this.logger=g}dispose(){}updateVideoConstraints(g,f,S){const v=this.calculateConstraints(f,S);this.logger.safe.info(`Calculated constraints: ${JSON.stringify(v)} from capabilities: ${JSON.stringify(f)}`);const C=v.resolution,_=v.fps,T=C&&(!isInRange(C.width,g.video.minWidth,g.video.maxWidth)||!isInRange(C.height,g.video.minHeight,g.video.maxHeight)),I=g.video.fps!==_;if(!T&&!I)return g;const b=g.clone();return T&&this.setResolution(b,C),I&&(b.video.fps=_),b}updateResolution(g,f){const S=g.clone();return this.setResolution(S,f),S}setResolution(g,f){g.video.maxWidth=f.width,g.video.minWidth=f.width,g.video.maxHeight=f.height,g.video.minHeight=f.height}getKey(g){return g.video?isEmpty(g.video)?"video":g.video.deviceId&&g.video.minWidth&&g.video.minHeight?`${g.video.deviceId}x${g.video.minWidth}x${g.video.minHeight}`:g.video.minWidth&&g.video.minHeight?`${g.video.minWidth}x${g.video.minHeight}`:g.video.deviceId?`${g.video.deviceId}`:(this.logger.safe.error(`Cannot create key for constraints: ${scrubConstraints(g)}`),""):"audio"}convertConstraints(g,f={}){if(!g)return null;const S=deepClone(f);return g?.deviceId&&(S.deviceId=g.deviceId),S}},hC=class{constructor(){this.MAX_SHARING_WIDTH=1920,this.MAX_SHARING_HEIGHT=1080}getResolutionTable(g,f){const S=this.constraintToMaxResolution(g,f);return this.generateResolutionTable(S)}constraintToMaxResolution(g,f){const S=this.getPortraitOrLandscapeMaxResolution(g),v=adjustResolutionToAspectRatio({width:g.width,height:g.height},f),C=S.width/v.width,_=S.height/v.height,T=Math.min(C,_);return this.resizeResolution(v,T)}resizeResolution(g,f){return{width:Math.round(g.width*f),height:Math.round(g.height*f)}}getPortraitOrLandscapeMaxResolution(g){return g.width>g.height?{width:this.MAX_SHARING_WIDTH,height:this.MAX_SHARING_HEIGHT}:{width:this.MAX_SHARING_HEIGHT,height:this.MAX_SHARING_WIDTH}}ceilToMackroblockSize(g){const f=g.width,S=g.height;return{width:Math.ceil(f/qt.MACROBLOCK_SIZE)*qt.MACROBLOCK_SIZE,height:Math.ceil(S/qt.MACROBLOCK_SIZE)*qt.MACROBLOCK_SIZE}}generateResolutionTable(g){return[1,2/3,1/3,1/6].map((f=>this.resizeResolution(g,f))).map((g=>this.ceilToMackroblockSize(g)))}},uC=class{constructor(g){this.logger=g,this.FPS_TABLE=[15,7.5,3.75,1.875],this.resolutionTableCalculator=new hC,this.initialAspectRatio=null}calculateConstraints(g,f){this.initialAspectRatio||(this.initialAspectRatio=f.width/f.height);const S=this.resolutionTableCalculator.getResolutionTable(f,this.initialAspectRatio);let v={resolution:S[S.length-1],fps:this.FPS_TABLE[this.FPS_TABLE.length-1]};return S.some((f=>{const S=this.getFs(f);return this.FPS_TABLE.some((C=>{const _=this.getMbps(S,C);return S<=g.maxFs&&C<=g.maxFps&&_<=g.maxMbps&&(v={resolution:f,fps:C},!0)}))}))?this.logger.safe.info(`Calculated resolution: ${JSON.stringify(v)}`):this.logger.safe.error(`None of available resolutions are suitable: ${JSON.stringify(S)}. Fallback to: ${JSON.stringify(v)}`),v}getMbps(g,f){return g*f}getFs(g){return Math.ceil(g.width/qt.MACROBLOCK_SIZE)*Math.ceil(g.height/qt.MACROBLOCK_SIZE)}},gC=class{constructor(g,f){this.logger=g,this.maxCapabilities=f}ensureValidity(g){this.throwIfMissing(g);const f=this.calculateMissing(g);return this.maxCapabilities&&this.applyMaxCapabilities(f),this.logger.safe.info(`Validating capabilities ${JSON.stringify(f)}`),f}throwIfMissing(g){if(!g.maxFs&&!g.maxMbps&&!g.maxFps||g.maxFs&&!g.maxMbps&&!g.maxFps||!g.maxFs&&g.maxMbps&&!g.maxFps||!g.maxFs&&!g.maxMbps&&g.maxFps)throw new Error(`Missing video capabilities ${JSON.stringify(g)}`)}calculateMissing(g){const f=shallowClone(g);return!g.maxFs&&g.maxMbps&&g.maxFps&&(f.maxFs=g.maxMbps/g.maxFps),g.maxFs&&!g.maxMbps&&g.maxFps&&(f.maxMbps=g.maxFs*g.maxFps),g.maxFs&&g.maxMbps&&!g.maxFps&&(f.maxFps=g.maxMbps/g.maxFs),f}applyMaxCapabilities(g){this.maxCapabilities.maxFs&&(g.maxFs=Math.min(g.maxFs,this.maxCapabilities.maxFs)),this.maxCapabilities.maxMbps&&(g.maxMbps=Math.min(g.maxMbps,this.maxCapabilities.maxMbps)),this.maxCapabilities.maxFps&&(g.maxFps=Math.min(g.maxFps,this.maxCapabilities.maxFps))}},pC=8160,mC=15,fC=class extends dC{constructor(g,f){super(g),this.initialConstraints={maxWidth:1920,minWidth:1920,maxHeight:1080,minHeight:1080,fps:15},this.maxCapabilities={maxFs:pC,maxFps:mC},this.validator=new gC(this.logger.createChild("CV"),this.maxCapabilities),this.constraintsCalculator=new uC(this.logger.createChild("CC")),f.config.resizeModeForSharing&&(this.initialConstraints.resizeMode=f.config.resizeModeForSharing)}createConstraintsObject(g){if(!g.sharing)throw new Error(`Sharing constraints are not presented: ${JSON.stringify(g)}`);const f=this.convertConstraints(g.sharing,this.initialConstraints),S=g.audio?g.audio:null;return S?.deviceId===qt.SYSTEM_AUDIO_SOURCE_ID&&delete S.deviceId,new cC(S,f,!1,!1,g.withOverridenStream)}generatePolicies(g){return[g]}calculateConstraints(g,f){this.logger.safe.info(`Stream resolution is ${JSON.stringify(f)}`);const S=this.validator.ensureValidity(g);return this.constraintsCalculator.calculateConstraints(S,f)}},SC=class extends fC{constructor(g,f,S){super(g,S);const v=f.screen.width/f.screen.height;v<1&&([this.initialConstraints.maxWidth,this.initialConstraints.maxHeight]=[this.initialConstraints.maxHeight,this.initialConstraints.maxWidth],[this.initialConstraints.minWidth,this.initialConstraints.minHeight]=[this.initialConstraints.minHeight,this.initialConstraints.minWidth]);let C=adjustResolutionToAspectRatio({width:this.initialConstraints.maxWidth,height:this.initialConstraints.maxHeight},v);[this.initialConstraints.maxWidth,this.initialConstraints.maxHeight]=[C.width,C.height],C=adjustResolutionToAspectRatio({width:this.initialConstraints.minWidth,height:this.initialConstraints.minHeight},v),[this.initialConstraints.minWidth,this.initialConstraints.minHeight]=[C.width,C.height]}},vC=class extends dC{constructor(g,f){super(f),this.configProvider=g}get currentMaxFS(){return this.streamConstraintsMaxFS??this.configProvider.config.webrtcCameraOpenFs}createConstraintsObject(g){const f={};void 0!==g.audioProcessingFlags&&(et.isEngine("Chromium","ChromiumAVD")?(f.autoGainControl=!!(1&g.audioProcessingFlags),f.echoCancellation=!!(2&g.audioProcessingFlags),f.noiseSuppression=!!(4&g.audioProcessingFlags),this.configProvider.config.useGoogPrefixAudioConstraints&&(f.googAutoGainControl=!!(1&g.audioProcessingFlags),f.googAutoGainControl2=!!(1&g.audioProcessingFlags),f.googEchoCancellation=!!(2&g.audioProcessingFlags),f.googHighpassFilter=!!(4&g.audioProcessingFlags),f.googNoiseSuppression=!!(4&g.audioProcessingFlags),f.googTypingNoiseDetection=!!(4&g.audioProcessingFlags))):et.isEngine("Safari","Firefox")?(f.autoGainControl=!!(1&g.audioProcessingFlags),f.echoCancellation=!!(2&g.audioProcessingFlags),f.noiseSuppression=!!(4&g.audioProcessingFlags)):this.logger.warn(`Unsupported browser engine for audio processing flags ${et.getBrowserInfo().engine}`));const S=this.convertConstraints(g.audio,f);this.streamConstraintsMaxFS=g.videoMaxFS;const v=this.convertConstraints(g.video,this.initialVideoConstraints(this.currentMaxFS));return new cC(S,v,g.withTimeout,g.withEffect,g.withOverridenStream)}calculateConstraints(g){const f=Math.min(g.maxFs,this.currentMaxFS);return{resolution:ei.Send.getResolutionByFs(f),fps:g.maxFps}}initialVideoConstraints(g){const f=ei.Send.getResolutionByFs(g);return{maxWidth:f.width,minWidth:f.width,maxHeight:f.height,minHeight:f.height,fps:this.configProvider.config.maxCameraOpenFps}}},CC=class{static getProvider(g,f,S){if("ScreenShare"===g){const g=S.createChild("SharingCP");return et.isBrowser("Safari")?new SC(g,Xs.window,f):new fC(g,f)}return new vC(f,S.createChild("VideoCP"))}},yC=class{constructor(g,f,S){this.error=g,this.constraints=f,this.configProvider=S,this.permissionDeniedBySystemErrorMsg=["Permission denied by system","The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission."]}getMediaError(){let g;switch(this.error.name){case"SourceUnavailableError":case"TrackStartError":case"NotReadableError":case"AbortError":g={type:qt.MEDIA_ERROR.sourceUnavailableError,detail:`media device is already used by another process: ${stringifyObject2(this.error)}`};break;case"ConstraintNotSatisfiedError":case"OverconstrainedError":g={type:qt.MEDIA_ERROR.constraintNotSatisfiedError,detail:`could not obtain constrained media stream: ${stringifyObject2(this.error)}`};break;case"DevicesNotFoundError":case"NotFoundError":g=this.configProvider.config.permissionDeniedUFDWorkaround?{type:qt.MEDIA_ERROR.permissionDeniedBySystemError,detail:`no system permissions: ${stringifyObject2(this.error)}`}:{type:qt.MEDIA_ERROR.devicesNotFoundError,detail:`specified device not found: ${stringifyObject2(this.error)}`};break;case"NotAllowedError":g=this.permissionDeniedBySystemErrorMsg.some((g=>g===this.error.message))?{type:qt.MEDIA_ERROR.permissionDeniedBySystemError,detail:`no system permissions: ${stringifyObject2(this.error)}`}:{type:qt.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${stringifyObject2(this.error)}`};break;case"PermissionDeniedError":case"PermissionDismissedError":g={type:qt.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${stringifyObject2(this.error)}`};break;case qt.MEDIA_ERROR.extensionNotFoundError:g={type:qt.MEDIA_ERROR.extensionNotFoundError,detail:`extension is not found: ${stringifyObject2(this.error)}`};break;case qt.MEDIA_ERROR.chromeRuntimeNotDefinedError:g={type:qt.MEDIA_ERROR.chromeRuntimeNotDefinedError,detail:`chrome runtime is not defined: ${stringifyObject2(this.error)}`};break;case qt.MEDIA_ERROR.sharingCancelledError:g=this.getSharingCancelledError(this.error);break;case qt.MEDIA_ERROR.mediaStreamRequestTimedOut:g={type:qt.MEDIA_ERROR.mediaStreamRequestTimedOut,detail:"Media Stream request timed out."};break;default:g=this.error.message===qt.MEDIA_ERROR.sharingCancelledError?this.getSharingCancelledError(this.error):{type:qt.MEDIA_ERROR.mediaStreamRequestError,detail:`media stream request error: ${stringifyObject2(this.error)}`}}return g.isAudio=!!this.constraints.audio,g.detail+=` constraints: ${stringifyObject2(scrubConstraints(this.constraints))}`,g.message=g.detail,g}getSharingCancelledError(g){return{type:qt.MEDIA_ERROR.sharingCancelledError,detail:`screen sharing cancelled: ${stringifyObject2(g)}`}}},EC=class{constructor(g,f){this.logger=g,this.configProvider=f}static isSupported(){return!0}getStream(g){const f=this.constraintsAdapter.toGumConstraints(g);return this.logger.safe.info(`Constraints to be applied: ${JSON.stringify(scrubConstraints(f))}`),new Promise(((g,S)=>{Xs.window.navigator.getUserMedia(f,g,S)})).catch((f=>{throw new yC(f,g,this.configProvider).getMediaError()}))}applyConstraints(g,f){if(!g?.getVideoTracks()?.[0])return Promise.reject("No video tracks found");const S=g.getVideoTracks()[0];return this.applyConstraintsForTrack(S,f)}applyConstraintsForTrack(g,f){const S=this.constraintsAdapter.toTrackConstraints(f);return g.applyConstraints?(this.logger.safe.info(`Apply constraints: ${JSON.stringify(S)} on ${JSON.stringify(g.id)}`),g.applyConstraints(S).catch((g=>{throw new yC(g,f,this.configProvider).getMediaError()}))):Promise.reject("track.applyConstraints() is not supported")}},_C=class{constructor(g){this.configProvider=g}toGumConstraints(g){const f={};return g.audio&&(f.audio=deepClone(g.audio),f.audio.deviceId&&delete f.audio.deviceId,g.audio.deviceId&&g.audio.deviceId!==qt.MEDIA_DEVICE.defaultId&&(f.audio.deviceId=g.audio.deviceId)),g.video&&(f.video={mandatory:{}},g.video.deviceId&&(f.video.mandatory.sourceId=g.video.deviceId),g.video.minWidth&&(f.video.mandatory.minWidth=g.video.minWidth),g.video.maxWidth&&(f.video.mandatory.maxWidth=g.video.maxWidth),g.video.minHeight&&(f.video.mandatory.minHeight=g.video.minHeight),g.video.maxHeight&&(f.video.mandatory.maxHeight=g.video.maxHeight),g.video.fps&&(f.video.mandatory.maxFrameRate=g.video.fps,this.configProvider.config.setMinFpsForWebkit&&(f.video.mandatory.minFrameRate=this.configProvider.config.minCameraOpenFps,f.video.mandatory.idealFrameRate=g.video.fps)),isEmpty(f.video.mandatory)&&delete f.video.mandatory),f}toTrackConstraints(g){const f={};return g.video&&(g.video.minWidth&&(f.width=g.video.minWidth),g.video.minHeight&&(f.height=g.video.minHeight),g.video.fps&&(f.frameRate=g.video.fps)),f}},TC=class{constructor(g){this.configProvider=g}toGumConstraints(g){const f={};if(g.audio&&(f.audio=deepClone(g.audio),f.audio.deviceId&&delete f.audio.deviceId,g.audio.deviceId&&g.audio.deviceId!==qt.MEDIA_DEVICE.defaultId&&(f.audio.deviceId={exact:g.audio.deviceId})),g.video){f.video={width:{},height:{},frameRate:{}},g.video.deviceId&&(f.video.deviceId={exact:g.video.deviceId}),g.video.minWidth&&(f.video.width.min=g.video.minWidth),g.video.maxWidth&&(f.video.width.max=g.video.maxWidth),g.video.minHeight&&(f.video.height.min=g.video.minHeight),g.video.maxHeight&&(f.video.height.max=g.video.maxHeight),g.video.fps&&(f.video.frameRate.max=g.video.fps,f.video.frameRate.min=this.configProvider.config.minCameraOpenFps,f.video.frameRate.ideal=g.video.fps);for(const g in f.video)isEmpty(f.video[g])&&delete f.video[g]}return f}toTrackConstraints(g){const f={};return g.video&&(g.video.minWidth&&(f.width=g.video.minWidth),g.video.minHeight&&(f.height=g.video.minHeight),g.video.fps&&(f.frameRate=g.video.fps)),f}},IC=class{toGumConstraints(g){if(!g?.video)throw new Error(`constraints cannot be applied: ${g}`);const f={video:{}},S=g.video.deviceId&&g.video.deviceId!==qt.DISPLAY_SOURCE_ID;return g.video.resizeMode&&(f.video.resizeMode=g.video.resizeMode),S&&(f.video.deviceId={exact:g.video.deviceId}),g.video.maxWidth&&(f.video.width={max:g.video.maxWidth},S&&(f.video.width.ideal=g.video.maxWidth)),g.video.maxHeight&&(f.video.height={max:g.video.maxHeight},S&&(f.video.height.ideal=g.video.maxHeight)),g.video.fps&&(f.video.frameRate=g.video.fps),g.audio&&(f.audio=!g.audio.deviceId||{deviceId:{exact:g.audio.deviceId}}),f}toTrackConstraints(g){const f=navigator.mediaDevices.getSupportedConstraints();if(!f)throw new Error("Constraints are not supported by browser");const S={};return f.width&&g.video.minWidth&&(S.width=g.video.minWidth),f.height&&g.video.minHeight&&(S.height=g.video.minHeight),f.frameRate&&g.video.fps&&(S.frameRate=g.video.fps),S.resizeMode=g.video.resizeMode,S}},bC=class extends EC{constructor(g,f){if(super(f.createChild("WebRTCProvider"),g),this.timeoutId=null,void 0!==navigator.webkitGetUserMedia&&void 0!==webkitRTCPeerConnection&&isVdiPlatform()){if(!this.configProvider.config.overrideGumFromWebkit||!Ys)return void(this.constraintsAdapter=new _C(g));this.logger.safe.info("Overriding getUserMedia from webkit"),overrideGumSourceFromWebkit()}this.constraintsAdapter=new TC(g)}getStream(g){if(!g.withTimeout||!this.configProvider.config.gumRequestTimeout)return super.getStream(g);const f=this.startGumRequestTimer(g),S=super.getStream(g).then((f=>{if(!this.timeoutId)throw this.stopStreamAfterTimeout(f,g),this.getMediaStreamTimeoutError(g);return this.stopGumRequestTimer(),f}));return Promise.race([f,S]).catch((g=>{throw this.stopGumRequestTimer(),g}))}getMediaStreamTimeoutError(g){const f={name:qt.MEDIA_ERROR.mediaStreamRequestTimedOut,message:`Media stream request timed out. Constraints: ${stringifyObject2(scrubConstraints(g))}`};return new yC(f,g,this.configProvider).getMediaError()}startGumRequestTimer(g){return new Promise(((f,S)=>{this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,S(this.getMediaStreamTimeoutError(g))}),this.configProvider.config.gumRequestTimeout)}))}stopGumRequestTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}stopStreamAfterTimeout(g,f){this.logger.safe.info(`Stopping media stream acquired after timeout: ${JSON.stringify(g.id)} with constraints: ${JSON.stringify(f)}`);try{g.getTracks().forEach((g=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(g.id)}`),g.stop()})),this.logger.safe.info(`Media stream stopped: ${g.id}`)}catch(g){this.logger.safe.warn(`Failed to stop media stream: ${stringifyObject2(g)}`)}}},AC=class extends EC{constructor(g,f){super(g.createChild("WebRTCDispProvider"),f),this.constraintsAdapter=new IC}static isSupported(){return!!window.navigator.mediaDevices.getDisplayMedia}getStream(g){const f=this.constraintsAdapter.toGumConstraints(g);return this.logger.safe.info(`Constraints to be used: ${JSON.stringify(f)}`),Promise.resolve().then((()=>g.video?.deviceId&&g.video?.deviceId!==qt.DISPLAY_SOURCE_ID?Xs.window.navigator.mediaDevices.getUserMedia(f):Xs.window.navigator.mediaDevices.getDisplayMedia(f))).catch((f=>{throw new yC(f,g,this.configProvider).getMediaError()}))}},PC=class{constructor(g){this.detail=g}getStream(g){throw this.getError(g)}applyConstraints(g,f){throw this.getError(f)}applyConstraintsForTrack(g,f){throw this.getError(f)}getError(g){return{type:qt.MEDIA_ERROR.unsupportedStream,detail:this.detail,message:this.detail,isAudio:!!g.audio}}},RC=class{static getStreamProvider(g,f,S){return"ScreenShare"===g?AC.isSupported()?new AC(S,f):(S.error("GUM stream provider cannot be created for display stream"),new PC("Sharing not supported")):new bC(f,S)}},MC=[30,15,7.5,3.75,1.875];function getResolutionForStream(g){return g?.getVideoTracks?.()[0]?getResolutionForTrack(g.getVideoTracks()[0]):null}function getResolutionForTrack(g){const f=g?.getSettings?.();return f?{width:f.width,height:f.height}:null}function getFrameRateForStream(g){return g?.getVideoTracks?.()[0]?getFrameRateForTrack(g.getVideoTracks()[0]):0}function getFrameRateForTrack(g){const f=g?.getSettings?.();return f?getClosestValue(MC,f.frameRate,!0):0}var wC=class extends Ht{constructor(g,f,S,v,C,_,T){super(T),this.id=g,this.masterStream=f,this.currentConstraints=S,this.constraintsProvider=v,this.streamProvider=C,this.configProvider=_,this._isDisposed=!1,this.masterStreamSubscriptions=[],this.mixerSubscriptions=[],this.parentId=f.id,this.logger=T.createChild(`C:${this.parentId}:${this.id}`),this.subscribeOnMasterStreamEvents()}get rawTrack(){return this.mediaTrack}get rawStream(){return this.rawMediaStream||(this.rawMediaStream=new MediaStream([this.mediaTrack]),this.configProvider.config.reassignMediaStreamAudioTrackAfterCreation&&this.rawMediaStream.getAudioTracks().length>0&&(this.rawMediaStream.removeTrack(this.rawMediaStream.getAudioTracks()[0]),this.rawMediaStream.addTrack(this.mediaTrack))),this.rawMediaStream}get deviceId(){return this.masterStream.deviceId}get mediaType(){return this.masterStream.mediaType}get originalMediaStream(){return this.masterStream.getOriginalMediaStream()}getCurrentConstraints(){return this.currentConstraints}dispose(g){this._isDisposed||(this._isDisposed=!0,this.logger.safe.info(`dispose: ${g}`),this.logger=this.logger.createChild("DISPOSED"),this.event("onStreamClientDisposing").raise(this),this.mediaTrack&&(this.unsubscribeFromMediaTrackEvents(),this.mediaTrack=null),this.masterStream&&(this.unsubscribeFromMasterStreamEvents(),this.masterStream.disposeClient(this),this.masterStream=null),this.unsubscribeFromMixerTrackEvents(),super.dispose(),this.event("onStreamClientDisposed").raise(this))}async applyCapabilities(g){if(!this.mediaTrack)return!1;const f=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,g,this.getResolution());if(!f||!this.configProvider.config.recoverOnStreamUnmute&&this.currentConstraints===f)return!1;this.configProvider.config.waitForVideoEffectsBeforeApplyingConstraints&&this.masterStream.mediaStreamReady&&await this.masterStream.mediaStreamReady();const applyConstraints=async g=>{try{return await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,f),this.currentConstraints=f,!0}catch(f){if(g)throw this.logger.safe.error(`Apply constraints error: ${JSON.stringify(f)}`),f;return this.logger.safe.warn(`Apply constraints failed and will be re-tried, error ${JSON.stringify(f)}`),!1}},S=this.currentConstraints.withEffect&&this.configProvider.config.effectsApplyConstraintsRetryMs;return!await applyConstraints(!S)&&S&&(await delay(this.configProvider.config.effectsApplyConstraintsRetryMs),await applyConstraints(!0)),!0}start(){return this.masterStream.start()}clone(g){return this.masterStream||this.logger.safe.error(`clone: master stream is null, reason: ${g}`),this.masterStream.getClient(`streamclient: ${g}`)}setMuted(g,f){this.isMuted=g,this.applyState(f)}setHold(g,f){this.isHold=g,this.applyState(f)}isSameStream(g){return this.parentId===g.parentId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},f=getResolutionForTrack(this.mediaTrack),S=f?.width?f:g,v=`Track resolution is ${S.width}x${S.height}.`;return f?.width?this.logger.safe.info(v):this.logger.safe.error(`${v}. Resolution not found, assuming default resolution.'`),S}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g=getFrameRateForTrack(this.mediaTrack);return 0===g?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${g}`),g}update(g){g?this.mediaTrack?this.logger.safe.error(`Media track is already created: ${this.mediaTrack.id}`):(this.mediaTrack=this.getTrackByMediaType(g,this.mediaType),this.updateTrackConstraints(),this.subscribeOnMediaTrackEvents(this.mediaTrack),this.hasMasterAudio=g&&g.getAudioTracks().length>0,this.hasMasterVideo=g&&g.getVideoTracks().length>0,this.hasMasterAudio&&this.hasMasterVideo&&(this.rawMediaStream=g),this.logger.safe.info(`Updated: ${printMediaStream(g)}`)):this.logger.safe.error("No master media stream, skipping update")}resetEffectsOutputConstraints(g){this.masterStream.resetEffectsOutputConstraints(g)}async updateTrackConstraints(){if("ScreenShare"!==this.mediaType)return;const g=this.masterStream.getResolution();if(g){const f=this.currentConstraints.clone();f.video.maxWidth=g.width,f.video.minWidth=g.width,f.video.maxHeight=g.height,f.video.minHeight=g.height;try{await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,f),this.currentConstraints=f}catch(g){this.logger.safe.error(`Apply constraints error: ${JSON.stringify(g)}`)}}}getTrackByMediaType(g,f){return"Audio"===f?g.getAudioTracks()[0]:g.getVideoTracks()[0]}applyState(g){void 0!==this.mediaTrack?.enabled&&(this.mediaTrack.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`[${g}] Track ${JSON.stringify(this.mediaTrack.id)} enabled state set to => ${this.mediaTrack.enabled}`))}subscribeOnMediaTrackEvents(g){g.onended=f=>{this.logger.safe.info(`Track ${g.id} ended: ${JSON.stringify(f)}`),this.event("onStreamClientEnded").raise(this,f)},g.onmute=()=>{this.logger.safe.info(`Track ${g.id} muted`),this.event("onStreamClientMuted").raise(this,!0)},g.onunmute=()=>{this.logger.safe.info(`Track ${g.id} unmuted`),this.event("onStreamClientMuted").raise(this,!1)}}unsubscribeFromMediaTrackEvents(){this.mediaTrack.onended=null,this.mediaTrack.onmute=null,this.mediaTrack.onunmute=null}unsubscribeFromMixerTrackEvents(){this.mixerSubscriptions.forEach((g=>g.dispose())),this.mixerSubscriptions=[]}subscribeOnMasterStreamEvents(){this.masterStreamSubscriptions.push(this.masterStream.on("onStreamStarted",((g,f)=>this.event("onStreamClientStarted").raise(this,f))),this.masterStream.on("onStreamError",((g,f)=>this.event("onStreamClientError").raise(this,f))),this.masterStream.on("onStreamTrackMuted",((g,f)=>this.event("onStreamClientMuted").raise(this,f))),this.masterStream.on("onStreamDisposing",(g=>this.dispose())),this.masterStream.on("onStreamQualityChanged",((g,f,S,v)=>this.event("onStreamQualityChanged").raise(this,f,S,v))),this.masterStream.on("onStreamTrackEnded",((g,f)=>this.event("onStreamClientEnded").raise(this,f))))}unsubscribeFromMasterStreamEvents(){this.masterStreamSubscriptions.forEach((g=>g.dispose())),this.masterStreamSubscriptions=[]}hasAudio(){return this.hasMasterAudio}hasVideo(){return this.hasMasterVideo}isActive(){return this.mediaTrack?.enabled&&!this.mediaTrack?.muted&&"live"===this.mediaTrack?.readyState}onVideoStreamQualityChanged(g,f,S){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(g)}@${f}, reason=${S}`),this.masterStream.onVideoStreamQualityChanged(g,f,S)}isDisposed(){return this._isDisposed}},OC=class extends Ht{constructor(g,f,S,v,C,_){super(_),this.stream=g,this.constraints=f,this.constraintsProvider=S,this.gumStreamProvider=v,this.configProvider=C,this.logger=_,this.clients=[],this.streams=[],this.clientId=0,this.mediaStreamSubscription=this.stream.on("onStreamAcquired",(()=>this.onStreamAcquired()))}getClient(){const g=new wC(this.clientId++,this.stream,this.constraints,this.constraintsProvider,this.gumStreamProvider,this.configProvider,this.logger);return this.addClient(g),g}disposeClient(g){this.removeClient(g),this.clients.length||this.event("onAllClientsDisposed").raise()}dispose(){this.mediaStreamSubscription.dispose(),this.clients.length&&this.logger.safe.error(`Not all clients are disposed! ${JSON.stringify(this.clients.map((g=>g.id)))}`),this.streams.forEach((g=>this.disposeStream(g))),super.dispose()}getOrCreateStream(){const g=this.streams.length?this.streams[this.streams.length-1]:this.stream.rawStream;if(!g)return null;const f=g.clone();return this.logger.safe.info(`Cloned: ${printMediaStream(g)} -> ${printMediaStream(f)}`),this.resetStream(f),this.streams.push(f),f}addClient(g){this.updateClient(g),this.clients.push(g)}updateClient(g){const f=this.getOrCreateStream();f&&g.update(f)}removeClient(g){const f=this.clients.indexOf(g);this.clients.splice(f,1)}addStream(){this.clients.forEach((g=>this.updateClient(g)))}disposeStream(g){g.getTracks().forEach((g=>{this.logger.safe.info(`Stopping track: ${JSON.stringify(g.id)}`),g.stop()}))}onStreamAcquired(){this.addStream()}resetStream(g){g.getTracks().forEach((g=>{this.logger.safe.info(`Resetting state for track: ${g.id}`),g.enabled=!0}))}},DC=class{constructor(){}getPolicies(g){if(g.audio&&!g.video&&this.hasAudioProcessingConstraints(g))return[g,new cC({deviceId:g.audio.deviceId},null)];if(!g.video)return[g];const f=this.getSuitableResolutions(g).map((f=>this.getConstraintsForResolution(g,f))),S=g.audio,v={deviceId:g.video.deviceId},C=new cC(S,v,g.withTimeout);return f.push(C),f}getSuitableResolutions(g){return ei.Send.getResolutions().filter((f=>f.width<=g.video.maxWidth&&f.height<=g.video.maxHeight)).reverse()}getConstraintsForResolution(g,f){const S=g.clone();return S.video.minWidth=f.width,S.video.minHeight=f.height,S}hasAudioProcessingConstraints(g){const f=g&&g.audio;return f&&(void 0!==f.echoCancellation||void 0!==f.autoGainControl||void 0!==f.noiseSuppression)}},NC=class{static getStrategy(g,f,S,v,C,_){return _?new xC(S,v):"Video"===g?new FC(f,S,v,C):new LC(f,S,v)}},kC=class{constructor(g,f,S){this.gumStreamProvider=g,this.serialQueue=f,this.logger=S}getStream(g){return this.logger.safe.info(`Requesting stream with constraints: ${JSON.stringify(scrubConstraints(g))}`),this.serialQueue.add((()=>this.request(g)))}},LC=class extends kC{constructor(g,f,S){super(g,f,S.createChild("SimpleStrat"))}request(g){return this.gumStreamProvider.getStream(g)}},FC=class extends kC{constructor(g,f,S,v){super(g,f,S.createChild("MultStrat")),this.policyGenerator=new DC}request(g){const f=this.policyGenerator.getPolicies(g);return this.makeRequests(f)}makeRequests(g){const f=g[0];return this.logger.safe.info(`Requesting media stream with policy: ${JSON.stringify(f)}`),this.makeRequestWithPolicy(f).catch((f=>{const S=g.slice(1);if(S.length&&qt.MEDIA_ERROR.constraintNotSatisfiedError===f.type)return this.logger.safe.warn("Could not obtain constrained media stream, will attempt weaker policy"),this.makeRequests(S);throw f}))}makeRequestWithPolicy(g){return this.gumStreamProvider.getStream(g)}},xC=class extends kC{constructor(g,f){super(null,g,f.createChild("WithOveriddenStreamStart"))}request(g){return new Promise(((f,S)=>f(g.withOverridenStream)))}},UC=class _SimulcastMediaStream2 extends Ht{constructor(g,f,S,v,C){super(v),this.serialQueue=f,this.configProvider=S,this.effectManager=C,this.gumRequestTime=0,this.effectsSubs=[],this.id=_SimulcastMediaStream2.streamId++,this.logger=v.createChild(`MediaStream:${this.id}`),this.mediaType=this.getMediaType(g),this.initialize(g)}get rawStream(){return this.mediaStream}get deviceId(){return this.originalMediaStream?this.originalMediaStream.getTracks()?.[0]?.getSettings?.()?.deviceId:null}start(){return this.mediaStreamStartPromise||(this.mediaStreamStartPromise=this.startStream(this.currentConstraints)),this.mediaStreamStartPromise}dispose(g){this.event("onStreamDisposing").raise(this),this.stopMediaStream(g).catch((g=>{this.event("onStreamError").raise(this,g)})).finally((()=>{this.constraintsProvider=null,this.serialQueue=null,this.configProvider=null,this.logger=this.logger.createChild("DISPOSED"),this.clientGenerationStrategy.dispose(),this.event("onStreamDisposed").raise(this),super.dispose()}))}disposeClient(g){this.clientGenerationStrategy.disposeClient(g)}getClient(g){return this.logger.safe.debug(`getClient: ${g}`),this.clientGenerationStrategy.getClient()}getOriginalMediaStream(){return this.originalMediaStream}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},f=getResolutionForStream(this.mediaStream),S=f??g,v=`Stream resolution is ${S.width}x${S.height}.`;return f?this.logger.safe.info(v):this.logger.safe.error(`${v}. Resolution not found, assuming default resolution.'`),S}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g=getFrameRateForStream(this.mediaStream);return 0===g?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${g}`),g}getMediaType(g){if(g.sharing)return"ScreenShare";if(g.video)return"Video";if(g.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(g)}`)}resetEffectsOutputConstraints(g){const f=getResolutionForStream(this.originalMediaStream);this.effectManager.resetOutputConstraints("Video",{width:Math.min(g.width,f.width||Number.MAX_SAFE_INTEGER),height:Math.min(g.height,f.height||Number.MAX_SAFE_INTEGER)})}initialize(g){this.constraintsProvider=CC.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(g),this.gumStreamProvider=RC.getStreamProvider(this.mediaType,this.configProvider,this.logger),this.mediaStreamRequestStrategy=NC.getStrategy(this.mediaType,this.gumStreamProvider,this.serialQueue,this.logger,this.configProvider,!!this.currentConstraints.withOverridenStream),this.clientGenerationStrategy=new OC(this,this.currentConstraints,this.constraintsProvider,this.gumStreamProvider,this.configProvider,this.logger),this.clientGenerationStrategy.on("onAllClientsDisposed",(()=>this.onAllClientsDisposed()))}onAllClientsDisposed(){this.logger.safe.info("All clients are disposed, disposing master stream"),this.dispose()}async startStream(g){try{await this.getOrCreateMediaStream(g),this.event("onStreamStarted").raise(this,this.currentConstraints)}catch(g){throw this.event("onStreamError").raise(this,g),g}}mediaStreamReady(){return this.effectsApplied?this.effectsApplied.promise:Promise.resolve()}async getOrCreateMediaStream(g){if(this.mediaStream)return Promise.resolve();const f=this.getRequestStartTimestamp(),S=await this.mediaStreamRequestStrategy.getStream(g);return this.gumRequestTime=this.getRequestDuration(f),this.handleMediaStreamRequestSuccess(S,g)}async handleMediaStreamRequestSuccess(g,f){this.logger.safe.info(`Media stream acquired: ${printMediaStream(g)} with constraints: ${JSON.stringify(scrubConstraints(f))}`),this.originalMediaStream=g,this.subscribeToTrackEvents(this.originalMediaStream),this.currentConstraints=f,this.mediaStream=await this.applyEffects(g),this.applyState(this.mediaStream),this.event("onStreamAcquired").raise(this,this.gumRequestTime,"Audio"!==this.mediaType&&this.getResolution()||void 0)}async applyEffects(g){switch(this.mediaType){case"Video":return this.getVideoEffectStream(g);case"Audio":return this.startNoiseSuppression(g);case"ScreenShare":return this.delayScreenShare(g)}return g}async delayScreenShare(g){return this.configProvider.config.useDelayedScreenShareStream?this.effectManager.startEffect("ScreenShare",g):g}async startNoiseSuppression(g){return this.configProvider.config.applyAudioEffectOnDemand&&!this.currentConstraints.withEffect?g:(this.logger.safe.info(`ECS keys for wasmvqe are: ${JSON.stringify(this.configProvider.config.wasmvqe)}`),this.logger.safe.info(`ECS keys for wasmdns are: ${JSON.stringify(this.configProvider.config.wasmdns)}`),await this.effectManager.startEffect("Audio",g))}async getVideoEffectStream(g){if(!this.currentConstraints.withEffect||this.currentConstraints.withOverridenStream&&this.configProvider.config.useRawMediaApiForVideoEffects)return g;this.effectsSubs.push(this.effectManager.on("onVideoStreamQualityChanged",((g,f,S)=>this.onVideoStreamQualityChanged(g,f,S)))),this.configProvider.config.waitForVideoEffectsBeforeApplyingConstraints&&(this.effectsApplied=new dt,this.effectsSubs.push(this.effectManager.on("onVideoEffectApplied",(()=>{this.logger.safe.info("Resolving effects applied promise"),this.effectsApplied.resolve()}))));const f=await this.effectManager.startEffect("Video",g);return this.logger.safe.info(`Media stream switched: ${printMediaStream(g)} -> ${printMediaStream(f)}`),f}subscribeToTrackEvents(g){const f=g?this.getTrackByMediaType(g,this.mediaType):null;f&&(f.onended=g=>{this.logger.safe.info(`Track ${f.id} ended: ${JSON.stringify(g)}`),this.event("onStreamTrackEnded").raise(this,g)},f.onmute=()=>{this.logger.safe.info(`Track ${f.id} muted`),this.event("onStreamTrackMuted").raise(this,!0)},f.onunmute=()=>{this.logger.safe.info(`Track ${f.id} unmute`),this.event("onStreamTrackMuted").raise(this,!1)})}unsubscribeFromTrackEvents(g){const f=g?this.getTrackByMediaType(g,this.mediaType):null;f&&(f.onended=null,f.onmute=null,f.onunmute=null)}getTrackByMediaType(g,f){return"Audio"===f?g.getAudioTracks()[0]:g.getVideoTracks()[0]}removeVideoEffectStream(){this.effectsSubs.forEach((g=>g?.dispose())),this.effectsSubs=[],this.effectManager.stopEffect("Video",this.mediaStream)}applyState(g){g.getAudioTracks()?.forEach((g=>this.applyAudioState(g)));const f=g.getVideoTracks()[0];this.applyVideoState(f)}applyAudioState(g){g&&(this.hasNonDefaultAudioProcessingConstraints()||"ScreenShare"===this.mediaType?this.applyContentHint(g,"music"):this.configProvider.config.defaultAudioContentHint&&this.applyContentHint(g,this.configProvider.config.defaultAudioContentHint),g.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(g.id)}`))}applyVideoState(g){g&&("ScreenShare"===this.mediaType&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(g,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(g.id)}`))}applyContentHint(g,f){this.logger.safe.info(`Apply content hint: ${f}`),g.contentHint=f}hasNonDefaultAudioProcessingConstraints(){const g=this.currentConstraints.audio;if(g){const f=this.configProvider.config.defaultAudioProcessingFlags;let S;return void 0===g.echoCancellation&&void 0===g.autoGainControl&&void 0===g.noiseSuppression||(S=0,void 0!==g.echoCancellation&&(S+=g.echoCancellation?2:0),void 0!==g.autoGainControl&&(S+=g.autoGainControl?1:0),void 0!==g.noiseSuppression&&(S+=g.noiseSuppression?4:0)),S!==f}return!1}getRequestStartTimestamp(){return Date.now()}getRequestDuration(g){return 0===g?0:Date.now()-g}stopMediaStream(g){return this.mediaStreamStartPromise?(this.logger.safe.info(`Queueing media stream stop: ${g}`),this.serialQueue.add((()=>this.stopMediaStreamInternal()))):Promise.resolve()}stopOneMediaStream(g){try{g.getTracks().forEach((g=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(g.id)}`),g.stop()})),this.logger.safe.info(`Media stream stopped: ${g.id}`)}catch(g){this.logger.safe.warn(`Failed to stop media stream: ${stringifyObject2(g)}`)}}stopMediaStreamInternal(){"Video"===this.mediaType&&this.configProvider.config.enableVideoEffects&&this.removeVideoEffectStream(),this.mediaStream&&(this.stopOneMediaStream(this.mediaStream),this.mediaStream=null),this.originalMediaStream&&(this.stopOneMediaStream(this.originalMediaStream),this.unsubscribeFromTrackEvents(this.originalMediaStream),this.originalMediaStream=null)}onVideoStreamQualityChanged(g,f,S){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(g)}@${f}, reason=${S}`),this.event("onStreamQualityChanged").raise(this,g,f,S)}};UC.streamId=0;var VC=UC,BC=class{static getStrategy(g){switch(g.config.diagnostics.performanceMonitoring.monitoringStrategy){case"decodeTime":default:return new HC(g);case"renderedFps":return new $C(g);case"rendererVolatility":return new jC(g)}}},HC=class{constructor(g){this.configProvider=g,this.decodeThresholds=this.configProvider.config.diagnostics.performanceMonitoring.decodeThresholds,this.defaultThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultThrehold,this.badPerfCount=new Map}checkQuality(g){let f=!1,S=!1;const v=ei.Recv.getResolutionRecord(Math.min(g.frameHeight,g.frameWidth)).height,C=this.decodeThresholds[v]||this.defaultThreshold,_=g.decodeTimeTracker.getReport();return _.median>C.maxDecodeTime&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)||1),f=!0),_.median<C.maxDecodeTime&&this.badPerfCount.get(g.msi)&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)-1),S=!0),f?0:S?2:1}},$C=class{constructor(g){this.configProvider=g,this.fpsDiffThresholds=this.configProvider.config.diagnostics.performanceMonitoring.fpsDiffThresholds,this.defaultFpsDiffThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultFpsDiffThreshold,this.badPerfCount=new Map}checkQuality(g){let f=!1,S=!1;const v=ei.Recv.getResolutionRecord(Math.min(g.frameHeight,g.frameWidth)).height,C=this.fpsDiffThresholds[v]||this.defaultFpsDiffThreshold,_=g.incomingFps.getReport(),T=g.rendererFps.getReport(),I=_.median-T.median;return I>=C.fpsDiff&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)||1),f=!0),I<C.fpsDiff&&this.badPerfCount.get(g.msi)&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)-1),S=!0),f?0:S?2:1}},jC=class{constructor(g){this.configProvider=g,this.volatilityThresholds=this.configProvider.config.diagnostics.performanceMonitoring.volatilityThresholds,this.defaultVolatilityThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultVolatilityThreshold,this.badPerfCount=new Map}checkQuality(g){let f=!1,S=!1;const v=ei.Recv.getResolutionRecord(Math.min(g.frameHeight,g.frameWidth)).height,C=this.volatilityThresholds[v]||this.defaultVolatilityThreshold,_=g.rendererFps.getReport(),T=g.incomingFps.getReport(),I=Math.abs(_.volatilityPercent-T.volatilityPercent);return C&&I>=C&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)||1),f=!0),I<C&&this.badPerfCount.get(g.msi)&&(this.badPerfCount.set(g.msi,this.badPerfCount.get(g.msi)-1),S=!0),f?0:S?2:1}},GC=class{constructor(g,f){this.streamClient=g,this.logger=f,this.rawBaseClient=new Yr((()=>this.getStream()),(()=>this.activeRawInputMediaStreamClient?.dispose()),f)}client(){return this.rawBaseClient}disposeActiveMediaStreamClient(){this.logger.info("Disposing active media stream client"),this.activeRawInputMediaStreamClient?.dispose("Disposed by RawDeviceStreamManager"),this.activeRawInputMediaStreamClient=null}async getStream(){return this.activeRawInputMediaStreamClient?.originalMediaStream?.active?(this.logger.info("Returning stream from active mediaStreamClient"),this.activeRawInputMediaStreamClient.originalMediaStream):(this.activeRawInputMediaStreamClient=await this.streamClient(),await this.activeRawInputMediaStreamClient.start(),this.activeRawInputMediaStreamClient.originalMediaStream)}},qC=class{constructor(g,f){this.logger=g,this.raiseTelemetryEvent=f,this.handlerMap=new Map([["Audio",new Map],["Video",new Map],["ScreenShare",new Map]])}dispose(g){this.logger.info(`disposing IRawStream ${g}`),this.handlerMap.get(g).forEach((g=>g.client().dispose()))}disposeAll(){this.logger.info("Dispose All clients"),this.handlerMap.forEach((g=>g.forEach((g=>g.client().dispose()))))}notifyChange(g){this.handlerMap.get(g).forEach((g=>{g.disposeActiveMediaStreamClient(),g.client().notifyStreamChange()}))}createIRawStreamClient(g,f){this.logger.info(`Create new IRawStream client for ${f}`);const S=new GC(g,this.logger);return this.handlerAdded(S,f),S.client()}handlerAdded(g,f){const S=g.client();this.setClientSubscription(S,f),this.handlerMap.get(f).set(S.clientId,g)}deleteRawStreamManagerById(g,f){this.logger.info(`Deleting from map: ${f}`),this.handlerMap.get(f).delete(g)}setClientSubscription(g,f){this.logger.info(`Setting subscription on IRawStream client for ${f}`),g.on("clientDisposed",(S=>{this.deleteRawStreamManagerById(g.clientId,f),this.raiseTelemetryEvent("IRawStream_client_disposed",{mediaType:f,clientId:S})})),g.on("rawStreamRequested",(g=>{this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:f,clientId:g})})),g.on("notifiedOnStreamChanged",(g=>this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:f,clientId:g})))}},WC=class extends Ht{constructor(g,f,S){super(g),this.logger=g,this.configProvider=f,this.audioRendererDiagnostics=S,this.window=Xs.window,this.isMuted=!1,this.isPlayingAllowed=!1,this.hadPlaybackError=!1,this.id=uniqueId(),this.onAudioError=g=>{const f=g&&g.target||this.audio;if(this.hadPlaybackError=!0,f?.error){const g=f.error.code,S=`error with rendering audio code: ${g}, message: ${f.error.message}`;this.event("onAudioPlaybackError").raise(g,qt.MEDIA_ERROR.audioPlaybackError,S),this.logger.safe.error(S)}else this.logger.safe.error("error with audio rendering")},this.onAudioPaused=async()=>{if(this.configProvider.config.audioRendererRestartOnPause&&this.canPlay&&!this.isMuted){const g=generateCauseId();this.logger.safe.info(`[${g}] audio playback is paused by OS, resuming it`),await this.startStream(g)}},this.onAudioPlayed=()=>{this.audioRendererDiagnostics?.registerSuccessfullReopen(this.deviceId),this.logger.safe.info("Audio element started playing")}}get canPlay(){return this.stream&&this.isPlayingAllowed}get muted(){return this.isMuted}async setMuted(g,f){return this.isMuted=g,g?this.stopStream(f):this.startStream(f)}async getSpeakerVolume(g){const f=this.audio?.volume??0;return this.logger.safe.info(`[${g}] get speaker volume: ${f}`),f}async setSpeakerVolume(g,f){this.assureAudioElement(f),this.audio.volume=g,this.logger.safe.info(`[${f}] set speaker volume: ${g}`)}getStream(){return this.stream}getDeviceId(){return this.deviceId}async play(g){if(this.stream=g,this.isPlayingAllowed=!0,!this.isMuted)return this.startStream()}stop(){this.stopStream(),this.isPlayingAllowed=!1}async setOutputDevice(g,f=generateCauseId()){if(this.audio)if(this.configProvider.config.disableAudioOutputSelection)this.logger.safe.warn(`[${f}] audio-output selection is disabled, disableAudioOutputSelection: true`);else if(this.audio.setSinkId){if(g&&g!==this.currentSinkId){this.logger.safe.info(`[${f}] setting audio output device ID to ${scrubMriOrOmit(g)}`),this.deviceId=g;try{this.configProvider.config.audioSetSinkIdWorkaround&&this.stream&&!this.stream.active?(this.audio.srcObject=null,await this.audio.setSinkId(g),this.audio.srcObject=this.stream):await this.audio.setSinkId(g),this.currentSinkId=g}catch(g){this.logger.safe.warn(`[${f}] setSinkId operation was aborted with error ${stringifyObject2(g)}`)}this.configProvider.config.audioRendererRestartOnDeviceError&&this.hadPlaybackError&&!this.isMuted&&(this.audioRendererDiagnostics?.registerReopenRequest(g),this.logger.safe.info(`[${f}] audio playback error happened, restarting audio stream on new device`),await this.startStream(f),this.hadPlaybackError=!1)}}else this.logger.safe.warn(`[${f}] setting output device is not supported`);else this.deviceId=g}dispose(){this.logger.safe.info("dispose"),super.dispose(),this.audio&&(this.stop(),this.stream=void 0,this.audio.removeEventListener("error",this.onAudioError),this.audio.removeEventListener("pause",this.onAudioPaused),this.audio.removeEventListener("play",this.onAudioPlayed),this.window.document.body.removeChild(this.audio),this.event("onAudioElementRemoved").raise(this.audio),this.currentSinkId=void 0,this.audio=void 0),this.detachGainNode()}async startStream(g=generateCauseId()){if(this.canPlay)try{await this.assureAudioElement(g),this.logger.safe.info(`[${g}] attaching stream to renderer: ${this.stream?.id}`),this.configProvider.config.speakerGainLevel&&this.reattachToGainNode(this.stream,this.configProvider.config.speakerGainLevel),this.audio.srcObject=this.stream,await this.audio.play(),this.event("onAudioStateChanged").raise(this.stream,this.id)}catch(f){this.logger.safe.warn(`[${g}] play operation was aborted with error ${stringifyObject2(f)}`)}}async assureAudioElement(g=generateCauseId()){if(!this.audio)return this.logger.safe.info(`[${g}] creating audio element`),this.audio=this.window.document.createElement("audio"),this.audio.addEventListener("error",this.onAudioError),this.audio.addEventListener("pause",this.onAudioPaused),this.audio.addEventListener("play",this.onAudioPlayed),this.window.document.body.appendChild(this.audio),this.audio.autoplay=!0,this.event("onAudioElementAdded").raise(this.audio),this.setOutputDevice(this.deviceId,g)}stopStream(g=generateCauseId()){this.audio&&this.canPlay&&(this.detachGainNode(),this.configProvider.config.audioRendererUsePauseOnDetach?(this.logger.safe.info(`[${g}] Pausing with stream: ${this.stream?.id}`),this.audio.pause()):(this.logger.safe.info(`[${g}] Detaching from stream: ${this.stream?.id}`),this.audio.srcObject=null),this.event("onAudioStateChanged").raise(null,this.id))}attachToGainNode(g,f){this.audioContext=new Xs.window.AudioContext,this.sourceNode=this.audioContext.createMediaStreamSource(g),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=f,this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination)}detachGainNode(){this.sourceNode?.disconnect(),this.sourceNode=void 0,this.gainNode?.disconnect(),this.gainNode=void 0,this.audioContext?.close(),this.audioContext=void 0}reattachToGainNode(g,f){this.detachGainNode(),this.attachToGainNode(g,f)}},zC=class{constructor(g){this.logger=g,this.queue=Promise.resolve()}add(g,f=generateCauseId()){let S;S=g instanceof dt?()=>g.promise:g;const v=this.queue.then(S);return this.queue=v.catch((g=>{if(this.queue){let S="";g instanceof TypeError&&(S=g.stack),this.logger.safe.error(`[${f}] Error from promiseQueue! ${stringifyObject2(g)} ${S}`)}})),v}dispose(){this.queue=null}},KC=M,JC=(g=>(g[g.NONE=0]="NONE",g[g.VIDEO=1]="VIDEO",g[g.AUDIO=2]="AUDIO",g))(JC||{});function getRecvOverlayStats(g,f,S){const{ssrc:v,keyFramesDecoded:C,nackCount:_,firCount:T,pliCount:I,decoderImplementation:b,packetsLost:A}=g.inboundRTP,{frameRateReceived:P,frameRateDecoded:R,bitrate:M,decodeTime:w,isFrozen:O}=g.extensions??{},{sourceId:D,msid:N,streamSize:k,rendererSize:L}=S,F=g.renderer?.modality===qt.MODALITY.sharing,{audioLevel:x}=f.inboundRTP,{mimeType:U}=f.codec??{},{healedRatio:V,lossRate:B}=f.extensions??{};return{streamSize:{overlayTab:1,format:"{0}x{1}",values:[k?.width,k?.height],undefinedFallback:0},rendererSize:{overlayTab:1,format:"{0}x{1}",values:[L?.width,L?.height],undefinedFallback:0},ssrc:{overlayTab:1,values:[v]},msid:{overlayTab:1,text:"sourceId/msid",format:"{0}/{1}",values:[D(),N()]},fps:{overlayTab:1,text:"FPS(r/d)",format:"{0}/{1}",values:[P,R],highlightUndefined:!0,lowerThreshold:1,upperThreshold:45,allowedDeviationThreshold:.2,suppressHighlighting:F},bitrate:{overlayTab:1,format:"{0} kbps",values:[toKbps(M)],lowerThreshold:24,suppressHighlighting:F},decodeTime:{overlayTab:1,format:"{0} ms",values:[w],upperThreshold:15,highlightUndefined:!0,suppressHighlighting:F},keyFramesDecoded:{overlayTab:1,text:"KFs",values:[C]},nacksFirsPlisSent:{overlayTab:1,text:"N/F/P",format:"{0}/{1}/{2}",values:[_,T,I],undefinedFallback:0,highlightChange:!0},packetsLost:{overlayTab:1,text:"lost",values:[A],undefinedFallback:0,highlightChange:!0},codecImplementationName:{overlayTab:1,text:"decoder",values:[b],highlightUndefined:!0},isFrozen:{overlayTab:1,values:[O?"YES":"NO"],fixedValueThreshold:"NO"},audioCodec:{overlayTab:2,values:[U?.split("/").pop()]},audioLevel:{overlayTab:2,values:[round(x,4)]},healedRatio:{overlayTab:2,values:[round(V,4)],upperThreshold:.2},lossRate:{overlayTab:2,values:[round(B,4)],upperThreshold:.1}}}function getSendOverlayStats(g,f){const{rid:S,ssrc:v,frameWidth:C,frameHeight:_,framesPerSecond:T,keyFramesEncoded:I,nackCount:b,firCount:A,pliCount:P,encoderImplementation:R,qualityLimitationReason:M}=g.outboundRTP,{cameraOpenResolution:w,bitrate:O,encodeTime:D,frameRateEncoded:N,frameRateSent:k,qp:L}=g.extensions??{},{mimeType:F}=f.codec??{},{lossRate:x}=f.extensions??{},{audioLevel:U}=f.mediaSource??{};return{rid:{overlayTab:1,values:[S],hideUndefined:!0},cameraSize:{overlayTab:1,format:"{0}x{1}",values:[w?.width,w?.height]},inputSize:{overlayTab:1,format:"{0}x{1}",values:[g.mediaSource?.width,g.mediaSource?.height]},sentSize:{overlayTab:1,format:"{0}x{1}",values:[C,_]},ssrc:{overlayTab:1,values:[v]},fps:{overlayTab:1,text:"FPS(i/e/s)",format:"{0}/{1}/{2}",values:[T,N,k],lowerThreshold:7,upperThreshold:45,allowedDeviationThreshold:.2},bitrate:{overlayTab:1,format:"{0} kbps",values:[toKbps(O)],lowerThreshold:24},encodeTime:{overlayTab:1,format:"{0} ms",values:[D],upperThreshold:15},keyFramesEncoded:{overlayTab:1,text:"KFs",values:[I]},qp:{overlayTab:1,values:[L]},nacksFirsPlisRecv:{overlayTab:1,text:"N/F/P",format:"{0}/{1}/{2}",values:[b,A,P],undefinedFallback:0,highlightChange:!0},codecImplementationName:{overlayTab:1,text:"encoder",values:[R],highlightUndefined:!0},qualityLimitationReason:{overlayTab:1,text:"limited",values:[M],fixedValueThreshold:"none"},bwe:{overlayTab:1,format:"{0} kbps",values:[toKbps(g.transport?.selectedCandidatePair?.availableOutgoingBitrate)],lowerThreshold:100},audioCodec:{overlayTab:2,values:[F?.split("/").pop()]},audioLevel:{overlayTab:2,values:[round(U,4)]},lossRate:{overlayTab:2,values:[round(x,4)]}}}function toKbps(g){return g&&Math.floor((g||0)/1e3)}var YC=class{constructor(g){this.container=g,this.formatRegexPattern=new RegExp(/{(\d+)}/g),this.elements={},this.previousSamples={},this.overlayTab=1,this.createTableCell=(g,f,S)=>{this.elements[g]=document.createElement("td"),this.elements[g].title=g,this.addElementStyle(g,S),this.elements[f].appendChild(this.elements[g])},this.topElement=g.ownerDocument.createElement("div"),this.topElement.classList.add("vdi-occlusion"),this.topElement.style.position="absolute",this.topElement.style.top="0px",this.topElement.style.left="0px",this.topElement.style.zIndex="100",this.topElement.style.transform="inherit",this.topElement.style.backgroundColor="rgba(0, 0, 0, 0.25)",this.topElement.style.pointerEvents="all",this.topElement.style.minWidth="15px",this.topElement.style.minHeight="15px",this.topElement.style.cursor="pointer",this.topElement.onclick=()=>{this.overlayTab=getNextTab(this.overlayTab)},this.container.appendChild(this.topElement),this.table=document.createElement("table"),this.table.style.borderCollapse="collapse",this.table.style.fontSize="smaller",this.topElement.appendChild(this.table)}dispose(){this.topElement.removeChild(this.table),this.container.removeChild(this.topElement),this.table=null,this.topElement=null,this.container=null}createTableColumn(g,f){for(const S of Object.keys(g)){const v=g[S];v.overlayTab===this.overlayTab&&(v.hideUndefined&&v.values.every((g=>!g))||this.createTableRow(S,v,f))}}createTableRow(g,f,S){this.elements[g]||(this.elements[g]=document.createElement("tr"),this.table.appendChild(this.elements[g]));const v=`${g}-title`,C=`${g}-${S}`,_=this.formatValue(f),T=this.previousSamples[C]!==_;this.previousSamples[C]=_;const I=isOutlier(f)||!(!f.highlightChange||!T);this.elements[v]||(this.createTableCell(v,g,!1),this.elements[v].innerText=f.text?f.text:g),this.createTableCell(C,g,!f.suppressHighlighting&&I),this.elements[C].innerText=_}clearTable(){for(;this.table.hasChildNodes();)this.table.removeChild(this.table.lastChild);this.elements={}}getOverlayTab(){return this.overlayTab}addElementStyle(g,f){this.elements[g].style.color=f?"#F72F35":"#FBF719",this.elements[g].style.fontSize="smaller",this.elements[g].style.lineHeight="1",this.elements[g].style.padding="0px 1px 0px 1px",this.elements[g].style.maxWidth="60px",this.elements[g].style.overflow="hidden",this.elements[g].style.whiteSpace="nowrap",this.elements[g].style.textOverflow="ellipsis"}formatValue(g){const{values:f,format:S,undefinedFallback:v="N/A"}=g;return S?S.replace(this.formatRegexPattern,((g,S)=>f?.[S]?.toString()??v.toString())):f?.[0]?.toString()??v.toString()}},QC=class{constructor(g,f,S){this.container=f,this.renderer=S,this.subs=[],g&&!this.overlay&&(this.overlay=new YC(this.container),this.rendererStats={msid:()=>this.renderer.getLocalMsi(),sourceId:()=>this.renderer.getMsi()},this.subs.push(this.renderer.on("onVideoSizeChanged",((g,f)=>this.rendererStats.streamSize={width:g,height:f}))),this.subs.push(this.renderer.on("onRendererSizeChanged",((g,f)=>this.rendererStats.rendererSize={width:Math.ceil(f.width),height:Math.ceil(f.height)}))))}setStats(g,f){this.overlay&&(this.overlay.clearTable(),this.overlay.createTableColumn(getRecvOverlayStats(g,f,this.rendererStats),g.inboundRTP.id))}dispose(){this.subs.forEach((g=>g.dispose())),this.subs=[],this.overlay?.dispose(),this.overlay=null,this.container=null,this.renderer=null}},XC=class{constructor(g,f){this.container=f,g&&!this.overlay&&(this.overlay=new YC(this.container))}setStats(g,f){if(!this.overlay)return;if(this.overlay.clearTable(),2===this.overlay.getOverlayTab())return void this.overlay.createTableColumn(getSendOverlayStats(g,f),g.outboundRTP.id);const S=[g,...g.altLayouts??[]];for(const g of S)this.overlay.createTableColumn(getSendOverlayStats(g,f),g.outboundRTP.id)}dispose(){this.overlay?.dispose(),this.overlay=null,this.container=null}};function getNextTab(g){const f=Object.keys(JC).filter((g=>isNaN(Number(g)))),S=(g+1)%f.length;return JC[f[S]]}function isOutlier(g){const{values:f,lowerThreshold:S,upperThreshold:v,highlightUndefined:C,fixedValueThreshold:_,allowedDeviationThreshold:T}=g;for(const g of f){if(void 0===g&&null===g&&C)return!0;if(_&&_!==g)return!0;if(null==g||!(0,KC.isNumber)(g))return!1;if(S&&Number(g)<=S)return!0;if(v&&Number(g)>=v)return!0;if(T){const S=(0,KC.mean)(f),v=S*T;if(Math.abs(Number(g)-S)>v)return!0}}return!1}function getObjectFitValue(g){switch(g){case"crop":return"cover";case"stretch":return"fill";default:return"contain"}}var ZC=class _VideoRendererBase2 extends Ht{constructor(g,f,S){const v=f.createChild(""+_VideoRendererBase2.rendererId++);super(v),this.container=g,this.configProvider=S,this.video=this.container.ownerDocument.createElement("video"),this.lastNotifiedVideoWidth=0,this.lastNotifiedVideoHeight=0,this.isVideoAttached=!1,this.onVideoDataUpdated=()=>{let g=this.video.videoWidth,f=this.video.videoHeight;(g<32||f<32)&&(g=f=0),this.lastNotifiedVideoWidth===g&&this.lastNotifiedVideoHeight===f||(this.lastNotifiedVideoWidth=g,this.lastNotifiedVideoHeight=f,this.event("onVideoSizeChanged").raise(g,f)),this.playVideo()},this.onVideoError=()=>{this.logger.safe.info(`onVideoError: error with video rendering: ${JSON.stringify(this.video.error)||"no video"}`),this.event("onVideoRendererStateChanged").raise({timestamp:Date.now(),state:"onError",payload:JSON.stringify(this.video.error)||"no video"})},this.onVideoPaused=()=>{this.logger.safe.info("onVideoPaused: video playback is paused"),this.event("onVideoRendererStateChanged").raise({timestamp:Date.now(),state:"onVideoPaused"}),this.playVideo()},this.onVideoPlayed=()=>{this.logger.safe.info("onVideoPlayed"),this.event("onVideoRendererStateChanged").raise({timestamp:Date.now(),state:"onVideoPlayed"})},this.onContextMenu=g=>{g.preventDefault()},this.logger=v,this.video.style.width="100%",this.video.style.height="100%",this.video.setAttribute("playsinline","true"),this.video.disablePictureInPicture=!0,this.video.autoplay=!0,this.video.muted=!0,this.attachEventListeners(),this.logger.safe.info("created")}getVideoElement(){return this.video}dispose(){super.dispose(),this.isVideoAttached&&(this.container.removeChild(this.video),this.isVideoAttached=!1),this.detachEventListeners(),this.attachMediaStream(null),this.video=null,this.stream=null,this.canvas=null,this.context=null}attachMediaStream(g){this.stream!==g&&(this.stream&&(this.video.srcObject=null),g&&(this.video.hidden=0===g.getVideoTracks().length,this.video.srcObject=g,this.isVideoAttached||(this.container.appendChild(this.video),this.isVideoAttached=!0)),this.stream=g)}setScalingMode(g){this.video.style.objectFit=getObjectFitValue(g)}getMediaStream(){return this.stream}getTrackId(){return this.stream?.getTracks()[0]?.id??void 0}async captureFrame(){const g=this.stream;if(!g)throw this.logger.safe.error("Mediastream not found"),new Error("Mediastream not found");const f=g.getVideoTracks?.()?.[0]?.getSettings(),S=f?.width,v=f?.height;if(!S||!v)throw this.logger.safe.error("Failed to get video track width/height"),new Error("Failed to get video track width/height");const C=this.getImageData(S,v);return{getSize:()=>({width:S,height:v}),isMirrored:()=>!1,getImageData:()=>C}}playVideo(){this.video?.paused&&this.video.play().catch((g=>{this.logger.safe.error(`Play video error: ${g}`)}))}getImageData(g,f){if(this.canvas??(this.canvas=this.container.ownerDocument.createElement("canvas")),this.context??(this.context=this.canvas.getContext("2d")),!this.context)throw this.logger.safe.error("Failed to get canvas 2d context"),new Error("Failed to get canvas 2d context");return this.canvas.width=g,this.canvas.height=f,this.context.drawImage(this.video,0,0,g,f),this.context.getImageData(0,0,g,f)}attachEventListeners(){this.video.addEventListener("loadedmetadata",this.onVideoDataUpdated),this.video.addEventListener("timeupdate",this.onVideoDataUpdated),this.video.addEventListener("error",this.onVideoError),this.video.addEventListener("pause",this.onVideoPaused),this.video.addEventListener("contextmenu",this.onContextMenu),this.video.addEventListener("play",this.onVideoPlayed)}detachEventListeners(){this.video.removeEventListener("loadedmetadata",this.onVideoDataUpdated),this.video.removeEventListener("timeupdate",this.onVideoDataUpdated),this.video.removeEventListener("error",this.onVideoError),this.video.removeEventListener("pause",this.onVideoPaused),this.video.removeEventListener("contextmenu",this.onContextMenu),this.video.removeEventListener("play",this.onVideoPlayed)}};ZC.rendererId=0;var ey=ZC,ty=class extends ey{constructor(g,f,S,v,C){super(g,S.createChild("local"),v),this.mediaStreamProvider=f,this.mediaType=C,this.isDisposed=!1,this.serialQueue=new zC(this.logger.createChild("rendererQueue")),this.logger.safe.info("ctor"),this.overlayStats=new XC(this.configProvider.config.showStatsInCall,g)}dispose(){this.logger.safe.info("dispose"),this.isDisposed=!0,this.event("onRendererDisposed").raise(this),super.dispose(),this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),this.overlayStats.dispose()}setVideoMirroring(g){this.configProvider.config.localPreviewMirroringSupported&&(this.getVideoElement().style.transform=g?"scaleX(-1)":void 0)}startVideoAsync(g=generateCauseId()){return this.logger.safe.info(`[${g}] starting local video`),this.event("onRendererStarted").raise(this),this.serialQueue.add((()=>this.restartVideo()),g)}updateStreamAsync(g=generateCauseId()){return this.logger.safe.info(`[${g}] updating local video`),this.serialQueue.add((()=>this.restartVideo()),g)}onDiagnosticUpdated(g){g.video?.send?.length&&g.audio?.send?.length&&this.overlayStats.setStats(g.video.send[0],g.audio.send[0])}async restartVideo(){try{let g;if("Video"===this.mediaType)g=await this.mediaStreamProvider.getVideoStream(!1,"localVideoRenderer");else{if("ScreenShare"!==this.mediaType)throw new Error("Not yet supported");g=await this.mediaStreamProvider.getDisplayStream("localSSRenderer")}if(await g.start(),this.isDisposed)throw g.dispose(),new Error("local video renderer is disposed");this.attachStream(g)}catch(g){throw this.mediaStreamProvider.raiseTelemetryEvent("video_preview_error",{mediaType:this.mediaType,error:stringifyObject2(g)}),g}}attachStream(g){if(this.mediaStream!==g)if(this.mediaStream?.parentId!==g?.parentId){this.logger.safe.info(`attach media stream ${g?.id}`);try{this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),g&&super.attachMediaStream(g.rawStream),this.mediaStream=g}catch(f){throw g&&g.dispose(),f}}else g.dispose()}},iy=class extends Ht{constructor(g,f,S){super(S),this.mediaStream=g,this.logger=S,this.mediaStreamSubscriptions=[],this.isHold=!1,this.isMuted=this.mediaStream.getMuted(),this._isDisposed=!1,this.originalId=g.id,this.subscribeOnMediaStreamEvents(),this.update(f),this.logger.safe.info("ctor"),this.mediaType=this.mediaStream.mediaType}get id(){return this.originalId}get parentId(){return this.originalId}get rawStream(){return this.gumStream}get rawTrack(){return this.getTrackByMediaType(this.rawStream,this.mediaType)}get deviceId(){return this.mediaStream.deviceId}update(g){g&&(this.gumStream=g,this.enableDisableTracks())}dispose(){this._isDisposed?this.logger.safe.info("already disposed"):(this._isDisposed=!0,this.logger.safe.info("dispose"),this.logger=this.logger.createChild("DISPOSED"),this.event("onStreamClientDisposing").raise(this),this.mediaStream&&(this.mediaStream.disposeClient(this),this.unsubscribeFromMediaStreamEvents(),this.mediaStream=null),this.event("onStreamClientDisposed").raise(this))}clone(){const g=this.mediaStream.getClient();return this.isMuted&&g.setMuted(!0),this.isHold&&g.setHold(!0),g}applyCapabilities(g){return this.mediaStream.applyCapabilities(g)}setMuted(g,f=generateCauseId()){this.isMuted=g||this.mediaStream.getMuted(),this.logger.safe.info(`[${f}] setMuted => ${this.isMuted}`),this.enableDisableTracks()}setHold(g){this.isHold=g,this.enableDisableTracks()}start(){return this.mediaStream.start()}hasAudio(){return this.mediaStream.hasAudio()}hasVideo(){return this.mediaStream.hasVideo()}hasDisplay(){return this.mediaStream.hasDisplay()}isSameStream(g){return this.parentId===g.parentId}getResolution(){return this.mediaStream.getResolution()}getFrameRate(){return this.mediaStream.getFrameRate()}isActive(){return!0}isDisposed(){return this._isDisposed}subscribeOnMediaStreamEvents(){this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamStarted",((g,f)=>{this.event("onStreamClientStarted").raise(this,f)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamError",((g,f)=>{this.event("onStreamClientError").raise(this,f)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackMuted",((g,f)=>{this.event("onStreamClientMuted").raise(this,f)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackEnded",((g,f)=>{this.event("onStreamClientEnded").raise(this,f)})))}unsubscribeFromMediaStreamEvents(){this.mediaStreamSubscriptions.forEach((g=>g.dispose())),this.mediaStreamSubscriptions=[]}enableDisableTracks(){this.gumStream?this.gumStream.getTracks().forEach((g=>{void 0!==g.enabled&&(g.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`Track ${JSON.stringify(g.id)} enabled state set to => ${g.enabled}`))})):this.logger.safe.warn("gumStream stream doesn't exist")}getTrackByMediaType(g,f){return"Audio"===f?g.getAudioTracks()[0]:g.getVideoTracks()[0]}},ny=class _MediaStreamInternal2 extends Ht{constructor(g,f,S,v){super(S),this.streamConstraints=g,this.serialQueue=f,this.configProvider=v,this.clientId=0,this.clients=[],this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.isMuted=!1,this.isHold=!1,this.gumStartTime=0,this.streamId=_MediaStreamInternal2.streamGeneration++,this.logger=S.createChild(`MediaStream:${this.streamId}`),this.mediaType=this.getMediaType(this.streamConstraints),this.constraintsProvider=CC.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(g)}get id(){return this.streamId}get rawStream(){return this.currentGumStream}get deviceId(){return this.rawStream?.getTracks()?.[0]?.getSettings?.()?.deviceId??null}applyCapabilities(g){if(this.currentGumStream){const f=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,g,this.getResolution());if(!f)return Promise.resolve(!1);if(this.currentConstraints!==f){this.currentConstraints=f;const g=this.currentConstraints;return this.hasDisplay()?this.applyConstraints(this.currentConstraints).then((()=>deepEqual(this.currentConstraints,g))).catch((g=>(this.logger.safe.error(`Apply constraints error: ${stringifyObject2(g)}`),!1))):this.applyConstraintsInternal().then((()=>deepEqual(this.currentConstraints,g)))}}return Promise.resolve(!1)}getClient(){let g;this.currentGumStream?(g=this.getClone(),this.clientGumStreams.push({[this.constraintsProvider.getKey(this.currentConstraints)]:g})):this.clientGumStreams.push({});const f=new iy(this,g,this.logger.createChild("Client:"+this.clientId++));return this.clients.push(f),f}getClone(){return this.hasDisplay()?this.currentGumStream:this.currentGumStream.clone()}setMuted(g){this.isMuted=g,this.clients.forEach((f=>{f.setMuted(g)})),this.enableDisableTracks()}getMuted(){return this.isMuted}setHold(g){this.isHold=g,this.clients.forEach((f=>{f.setHold(g)})),this.enableDisableTracks()}start(){return this.mediaStreamStartPromise||(this.mediaStreamStartPromise=this.startStream(this.currentConstraints)),this.mediaStreamStartPromise}dispose(){for(let g=this.clients.length-1;g>=0;g--)this.clients[g].dispose()}disposeClient(g){const f=this.clients.indexOf(g);f>=0&&(this.clients.splice(f,1),this.streamsDump.push(this.clientGumStreams[f]),this.clientGumStreams.splice(f,1),0===this.clients.length)&&this.disposeStream()}async disposeStream(){this.event("onStreamDisposing").raise(this);try{await this.stopGumStream(),this.event("onStreamDisposed").raise(this)}catch(g){this.event("onStreamError").raise(this,g)}this.constraintsProvider=null,this.serialQueue=null,this.configProvider=null,this.logger=this.logger.createChild("DISPOSED"),super.dispose()}hasAudio(){return!!this.currentGumStream&&0!==this.currentGumStream.getAudioTracks().length}hasVideo(){return!!this.currentGumStream&&0!==this.currentGumStream.getVideoTracks().length&&this.currentConstraints.video&&this.currentConstraints.video.deviceId!==qt.DISPLAY_SOURCE_ID}hasDisplay(){return!!this.currentGumStream&&0!==this.currentGumStream.getVideoTracks().length&&this.currentConstraints.video&&this.currentConstraints.video.deviceId===qt.DISPLAY_SOURCE_ID}getVideoDeviceId(){return this.currentConstraints.video.deviceId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},f=getResolutionForStream(this.currentGumStream),S=f??g,v=`Stream resolution is ${S.width}x${S.height}.`;return f?this.logger.safe.info(v):this.logger.safe.error(`${v}. Resolution not found, assuming default resolution.'`),S}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((g=>g===this.mediaType)))return null;const g=getFrameRateForStream(this.currentGumStream);return 0===g?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${g}`),g}async startStream(g){let f;f=g.video?this.applyConstraintsInternal():this.updateGumStreamInternal(g);try{await f,this.event("onStreamStarted").raise(this,g)}catch(g){throw this.event("onStreamError").raise(this,g),g}}getMediaType(g){if(g.sharing)return"ScreenShare";if(g.video)return"Video";if(g.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(g)}`)}updateClients(g){const f=this.constraintsProvider.getKey(g);this.clients.forEach(((g,S)=>{this.clientGumStreams[S][f]||(this.clientGumStreams[S][f]=this.getClone()),g.update(this.clientGumStreams[S][f])}))}applyConstraints(g){const f=this.getGumStreamProvider();return Promise.all(this.clients.map((S=>f.applyConstraints(S.rawStream,g)))).then((()=>{}))}applyConstraintsInternal(){return new Promise(((g,f)=>{this.logger.safe.info(`applying stream constraints: ${JSON.stringify(scrubConstraints(this.currentConstraints))}`);const S=new dt;this.clients.forEach((g=>{g.onApplyConstraints&&g.onApplyConstraints(S.promise)}));const v=this.serialQueue.add((()=>{const g=(new DC).getPolicies(this.currentConstraints);return this.mediaStreamStartPromise=this.updateGumStreamInternal(g[0]),g.slice(1).forEach((g=>{this.mediaStreamStartPromise=this.mediaStreamStartPromise.catch((f=>{if(qt.MEDIA_ERROR.constraintNotSatisfiedError===f.type)return this.logger.safe.warn("could not obtain constrained media stream, will attempt weaker policy"),this.updateGumStreamInternal(g);throw f.constraints=g,f}))})),this.mediaStreamStartPromise})).then((()=>{S.resolve()})).catch((g=>{throw this.logger.safe.error(`failed to apply constraints: ${JSON.stringify(scrubConstraints(g.constraints))} error: ${stringifyObject2(g)}`),S.reject(g),g}));g(v)}))}enableDisableTracks(){this.currentGumStream&&this.currentGumStream.getTracks().forEach((g=>{void 0!==g.enabled&&(g.enabled=!("audio"===g.kind&&this.isMuted||this.isHold),this.logger.safe.info(`control media stream track kind: ${g.kind} enabled: ${g.enabled} muted: ${g.muted}`))}))}getGumStreamProvider(){return RC.getStreamProvider(this.mediaType,this.configProvider,this.logger.createChild("MSProvider"))}async updateGumStreamInternal(g){this.logger.safe.info(`querying user media for stream: ${JSON.stringify(g)}`),this.logger.safe.info("Getting GUM stream");const f=await this.getGumStream(g);this.logger.safe.info("Updating gum stream audio tracks"),this.updateGumStreamAudioTracks(f),this.currentGumStream=f,this.logger.safe.info("Updating stream constraints"),this.updateConstraints(g,f),this.logger.safe.info("Caching GUM stream"),this.cacheGumStream(this.currentConstraints,f),this.updateClients(this.currentConstraints),this.updateGumStreamVideoTracks(f),this.enableDisableTracks(),this.logger.safe.info("media stream updated");const S=this.stopRequestCalculation();this.event("onStreamAcquired").raise(this,S,(this.hasVideo()||this.hasDisplay())&&this.getResolution()||void 0)}async getGumStream(g){const f=this.gumStreams[this.constraintsProvider.getKey(g)];if(f)return f;const S=this.getGumStreamProvider();return this.startRequestCalculation(),S.getStream(g)}updateGumStreamAudioTracks(g){g.getAudioTracks().forEach((g=>{g.onended=g=>{this.logger.safe.info(`Audio stream track ended: ${JSON.stringify(g.error?.name||g)}`),this.event("onStreamTrackEnded").raise(this,g)},g.onmute=()=>{this.logger.safe.info("Audio stream track muted"),this.event("onStreamTrackMuted").raise(this,!0)},g.onunmute=()=>{this.logger.safe.info("Audio stream track unmuted"),this.event("onStreamTrackMuted").raise(this,!1)},g.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(g.id)}`)}))}updateGumStreamVideoTracks(g){const[f]=g.getVideoTracks();f&&(f.onmute=g=>{this.logger.safe.error(`Video stream track muted: ${JSON.stringify(scrubConstraints(this.currentConstraints))}; ${JSON.stringify(g)}`)},f.onended=g=>{this.logger.safe.info(`Video stream track ended: ${JSON.stringify(scrubConstraints(this.currentConstraints))}; ${JSON.stringify(g?.error.name||g)}`),this.event("onStreamTrackEnded").raise(this,g)},this.hasDisplay()&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(f,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(f.id)}`))}cacheGumStream(g,f){const S=this.constraintsProvider.getKey(g);this.gumStreams[S]!==f&&(this.gumStreams[S]&&(this.logger.safe.info(`Stream cache hit for ${S}, stopping old stream`),this.stopOneGumStream(this.gumStreams[S])),this.gumStreams[S]=f)}updateConstraints(g,f){this.currentConstraints=g.video?this.constraintsProvider.updateResolution(g,this.getResolution()):g,this.logger.safe.info(`Stream constraints updated: ${JSON.stringify(this.currentConstraints)}`)}applyContentHint(g,f){["","text","detail","motion"].indexOf(f)<0?this.logger.safe.error(`Cannot apply content hint: ${f}`):(this.logger.safe.info(`Apply content hint: ${f}`),g.contentHint=f)}startRequestCalculation(){this.gumStartTime=Date.now()}stopRequestCalculation(){if(0===this.gumStartTime)return 0;const g=Date.now()-this.gumStartTime;return this.gumStartTime=0,g}stopGumStream(){return this.mediaStreamStartPromise?(this.logger.safe.info("queueing media stream stop"),this.serialQueue.add((()=>{this.stopGumStreamInternal()}))):Promise.resolve()}stopOneGumStream(g){try{g.getTracks().forEach((g=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(g.id)}`),g.onended=null,g.onmute=null,g.stop()})),this.logger.safe.info("media stream stopped")}catch(g){this.logger.safe.warn(`failed to stop media stream: ${stringifyObject2(g)}`)}}stopGumStreamInternal(){this.currentGumStream&&([...this.clientGumStreams,...this.streamsDump,this.gumStreams].forEach((g=>{forOwn(g,(g=>{this.stopOneGumStream(g)}))})),this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.currentGumStream=null)}};ny.streamGeneration=0;var ry=ny,sy=class _MediaStreamManager extends Ht{constructor(g,f,S){super(g),this.logger=g,this.configProvider=f,this.effectsManager=S,this.cachedStreamsSubs=new Map,this.cachedStreamsMap=new Map,this.mediaStreamSerialQueue=new zC(this.logger),this.couldUseWebrtc_1_0=!1}getMediaStream(g,f){this.logger.safe.info(`retrieving media stream: ${JSON.stringify(scrubConstraints(g))}`),this.cachedStreamsMap.size||(this.couldUseWebrtc_1_0=canUseWebrtc1_0(this.configProvider.config.checkSupportForWebrtc_1_0));let S=this.getSuitableStream(g);S||(this.logger.safe.info(`cached stream is not found. Creating a new one with constraints: ${stringifyObject2(scrubConstraints(g))}`),S=this.createCachedStream(g)),this.logger.safe.info(`starting cached stream id=${S.id}`,f);const v=S.getClient(f);return v.start().catch((g=>{this.logger.safe.error(`could not start media stream: ${S.id}, total streams: ${this.cachedStreamsMap.size}, error: ${stringifyObject2(g)}`),this.removeStream(S)})),v}dispose(){this.cachedStreamsSubs&&(this.cachedStreamsSubs.forEach((g=>{g.forEach((g=>{g.dispose()}))})),this.cachedStreamsSubs=null),this.cachedStreamsMap&&(this.cachedStreamsMap.forEach((g=>g.dispose("MSM dispose"))),this.cachedStreamsMap=null),this.mediaStreamSerialQueue&&(this.mediaStreamSerialQueue.dispose(),this.mediaStreamSerialQueue=null),super.dispose()}getCachedStreams(){return this.cachedStreamsMap}getActiveConstraints(){const g={audio:!1,video:!1,sharing:!1};return this.cachedStreamsMap.forEach(((f,S)=>{S.audio&&(g.audio=!0),S.video&&(g.video=!0),S.sharing&&(g.sharing=!0)})),g}onDevicesChanged(g){this.configProvider.config.enablePermissionsWorkaround&&_MediaStreamManager.isDeviceListEmpty(g)?this.logger.safe.info("Device list is empty, permission workaround enabled"):this.cachedStreamsMap.forEach(((f,S)=>{if(!S.sharing){const f=this.isDeviceOutdated(S.audio,g),v=this.isDeviceOutdated(S.video,g);(f||v)&&this.cachedStreamsMap.delete(S)}}))}getSuitableStream(g){let f;return this.cachedStreamsMap.forEach(((S,v)=>{this.isSuitable(this.addDeviceIdIfNecessary(S,v),g)&&(f=v)})),f&&this.cachedStreamsMap.get(f)}addDeviceIdIfNecessary(g,f){if(!g.deviceId)return f;const S=this.cloneStreamConstraints(f);return f.audio&&void 0===f.audio.deviceId&&(S.audio.deviceId=g.deviceId),f.video&&void 0===f.video.deviceId&&(S.video.deviceId=g.deviceId),f.sharing&&(S.sharing.deviceId=qt.DISPLAY_SOURCE_ID),S}cloneStreamConstraints(g){return{...deepClone(g),withOverridenStream:g.withOverridenStream}}createCachedStream(g){const f=this.createStream(g);return this.event("onStreamCreated").raise(f.id,f.mediaType),this.subscribeOnStreamEvents(f),this.logger.safe.info(`created media stream, id: ${f.id} total: ${this.cachedStreamsMap.size}`),this.cachedStreamsMap.set(g,f),f}disposeCurrentDeviceStream(g){for(const[f,S]of this.cachedStreamsMap.entries())g.sharing||f.sharing||(_MediaStreamManager.deviceChanged(g.audio,f.audio)||_MediaStreamManager.deviceChanged(g.video,f.video))&&S.dispose("MSM dispose oneStreamPerDeviceType")}createStream(g){return this.configProvider.config.oneStreamPerDeviceType&&this.couldUseWebrtc_1_0&&this.disposeCurrentDeviceStream(g),this.configProvider.config.webrtcSimulcastSessionEnabled&&oa.hasApplyConstraints()&&this.couldUseWebrtc_1_0?new VC(g,this.mediaStreamSerialQueue,this.configProvider,this.logger,this.effectsManager):new ry(g,this.mediaStreamSerialQueue,this.logger,this.configProvider)}subscribeOnStreamEvents(g){const f=[];f.push(g.on("onStreamAcquired",((g,f,S)=>this.onStreamAcquired(g,f,S)))),f.push(g.on("onStreamDisposing",(g=>this.onStreamDisposing(g)))),this.cachedStreamsSubs.set(g,f)}unsubscribeFromStreamEvents(g){this.cachedStreamsSubs.get(g).forEach((g=>g.dispose())),this.cachedStreamsSubs.delete(g)}removeStream(g){this.logger.safe.info(`release media stream generation: ${g.id} cached: ${this.cachedStreamsMap.size}`),this.cachedStreamsSubs.has(g)?(this.unsubscribeFromStreamEvents(g),this.cachedStreamsMap.delete(this.getConstraintsForStream(g)),this.getStreamsCountByType("Audio")||this.effectsManager.stopEffect("Audio"),this.cachedStreamsMap.size||this.event("onAllStreamsRemoved").raise()):this.logger.safe.warn(`skipping unknown stream ${g.id}`)}getConstraintsForStream(g){let f;return this.cachedStreamsMap.forEach(((S,v)=>{g===S&&(f=v)})),f}isSuitable(g,f){const S=!(!g.withOverridenStream||!f.withOverridenStream),v=S||f.sharing||this.isAcceptable(g.audio,f.audio)&&g.audioProcessingFlags===f.audioProcessingFlags,C=S||this.isAcceptable(g.video,f.video),_=this.configProvider.config.requireUserActionForAudioSharing&&f.sharing&&!!g.audio!=!!f.audio,T=this.isAcceptable(g.sharing,f.sharing),I=T&&this.isAcceptable(g.audio,f.audio),b=_?I:T,A=g.withEffect===f.withEffect,P=g.withOverridenStream?.id===f.withOverridenStream?.id;return!f.force&&v&&C&&b&&A&&P}isAcceptable(g,f){return!g&&!f||g&&f&&g.deviceId===f.deviceId}isDeviceOutdated(g,f){return g?.deviceId&&!f.some((f=>f.deviceId===g.deviceId))}onStreamDisposing(g){this.logger.safe.info(`onStreamDisposing event ${g.id}`),this.event("onStreamDisposing").raise(g.id,g.mediaType),this.removeStream(g)}onStreamAcquired(g,f,S){const v="Audio"===g.mediaType?void 0:!!g.rawStream.getAudioTracks()[0],C="ScreenShare"===g.mediaType?this.getSharingSource(g):void 0,_="Audio"===g.mediaType||v?g.rawStream?.getAudioTracks?.()[0]?.getSettings?.()?.sampleRate:void 0;this.event("onStreamAcquired").raise({id:g.id,mediaType:g.mediaType,timestamp:f,resolution:S,withAudio:v,source:C,sampleRate:_})}getSharingSource(g){const f=g.rawStream.getVideoTracks()[0],S=f.getConstraints();if(S?.deviceId)return"camera";const v=f.getSettings();return v?.displaySurface??"unknown"}static deviceChanged(g,f){return!(!g||!f)&&g.deviceId!==f.deviceId}static isDeviceListEmpty(g){return g.every((g=>""===g.label))}getStreamsCountByType(g){let f=0;return this.cachedStreamsMap.forEach((S=>{f+=S.mediaType===g?1:0})),f}},ay=class{constructor(g){this.configProvider=g,this.data={deviceList:[],deviceSelectionChangeCount:0,deviceSelectionChangeCountFromInterface:0,permissionStates:{microphone:"unknown",camera:"unknown"},devicesCount:{microphone:0,camera:0,speaker:0,compositeAudio:0,audioIngestDevice:0,virtualDevice:0},devicesChangeCount:0,devicesPollChangeCount:0,deviceTelemetryEvents:[],videoEffectsEvents:[],audioEffectsEvents:[],workerEvents:[],audioSourceNumOfReopenRequests:0,audioSourceNumOfSuccessfulReopens:0,audioRenderDeviceErrorFlags:[],audioCaptureDeviceErrorFlags:[]},Object.defineProperty(this.data,"rawUsedDevices",{get:()=>this.rawUsedDevices,configurable:!1,enumerable:!1})}set permissionStates(g){this.data.permissionStates=g}setSelectedDevices(g,f){const S={microphone:scrubDeviceLabelPii(g.microphone?.label,this.configProvider.config.devices.piiSafeWords),camera:scrubDeviceLabelPii(g.camera?.label,this.configProvider.config.devices.piiSafeWords),speaker:scrubDeviceLabelPii(g.speaker?.label,this.configProvider.config.devices.piiSafeWords)};this.rawUsedDevices={microphone:g.microphone?.label,camera:g.camera?.label,speaker:g.speaker?.label},this.data.usedDevices&&(this.data.deviceSelectionChangeCount++,f&&this.data.deviceSelectionChangeCountFromInterface++),this.data.usedDevices=S}setDeviceList(g,f,S){this.data.deviceList=g.map((g=>({label:scrubDeviceLabelPii(g.label,this.configProvider.config.devices.piiSafeWords),kind:g.type}))),S&&(this.data.deviceDebugStrings=deepClone(S)),this.data.devicesCount.microphone=g.filter((g=>"microphone"===g.type)).length,this.data.devicesCount.camera=g.filter((g=>"camera"===g.type)).length,this.data.devicesCount.speaker=g.filter((g=>"speaker"===g.type)).length,this.data.devicesCount.compositeAudio=g.filter((g=>"compositeAudio"===g.type)).length,this.data.devicesChangeCount++,f&&this.data.devicesPollChangeCount++}registerDeviceTelemetryEvent(g){if("stream_acquired"===g.eventType){const f=g.payload;"Video"===f.mediaType&&(this.data.latestCameraOpenResolution=f.resolution)}"Audio"===g.payload.mediaType&&("stream_acquired"===g.eventType&&(this.data.audioSourceNumOfReopenRequests++,this.data.audioSourceNumOfSuccessfulReopens++),"stream_error"===g.eventType&&this.data.audioSourceNumOfReopenRequests++),arrayLimitedPush2(this.data.deviceTelemetryEvents,g,this.configProvider.config.diagnostics.collectionLimits.numDeviceEvents)}logAudioDeviceError(g,f){switch(g){case"reconnect_on_audio_playback_error":{const g=this.getAudioPlaybackErrorCode(f.error);this.registerAudioRenderError(g);break}case"enumeration_failed":this.registerAudioRenderError(1),this.registerAudioCaptureError(1);break;case"permissions_state_changed":"denied"===f.microphone&&this.registerAudioCaptureError(0x800000000000);break;case"stream_ended_error":this.registerAudioCaptureError(4194304)}}getAudioPlaybackErrorCode(g){switch(g){case 3:return 4194304;case 4:return 128;default:return 0x8000000000000000}}registerVideoEffectsEvent(g){arrayLimitedPush2(this.data.videoEffectsEvents,g,this.configProvider.config.diagnostics.collectionLimits.numVideoEffectsEvents)}registerAudioEffectsEvent(g){arrayLimitedPush2(this.data.audioEffectsEvents,g,this.configProvider.config.diagnostics.collectionLimits.numAudioEffectsEvents)}registerWorkerEvent(g){arrayLimitedPush2(this.data.workerEvents,g,this.configProvider.config.diagnostics.collectionLimits.numWorkerEvents)}registerAudioCaptureError(g){const f={timestamp:Date.now(),audioDeviceErrorFlag:g};arrayLimitedPush2(this.data.audioCaptureDeviceErrorFlags,f,this.configProvider.config.diagnostics.collectionLimits.numAudioCaptureErrors)}registerAudioRenderError(g){const f={timestamp:Date.now(),audioDeviceErrorFlag:g};arrayLimitedPush2(this.data.audioRenderDeviceErrorFlags,f,this.configProvider.config.diagnostics.collectionLimits.numAudioRenderErrors)}getObjectRef(){return this.data}},oy=class{constructor(g,f,S,v,C){this.deviceId=g,this.label=f,this.kind=S,this.groupId=v,this.capabilities=C,this.type=this.getType(this.kind),this.guid=`${this.type}:${this.deviceId}`,this.isSystemDefault=this.deviceId===qt.MEDIA_DEVICE.defaultId}toDeviceDesc(){return{id:this.guid,browserId:this.deviceId,label:this.label,kind:this.type}}getType(g){switch(g){case qt.MEDIA_DEVICE_KIND.audioInput:return qt.MEDIA_DEVICE.microphone;case qt.MEDIA_DEVICE_KIND.audioOutput:return qt.MEDIA_DEVICE.speaker;case qt.MEDIA_DEVICE_KIND.videoInput:return qt.MEDIA_DEVICE.camera;case qt.MEDIA_DEVICE_KIND.compositeAudio:return qt.MEDIA_DEVICE.compositeAudio;case qt.MEDIA_DEVICE_KIND.virtualDevice:return qt.MEDIA_DEVICE.virtualDevice;default:throw new Error(`Device kind to recognized: ${g}`)}}},ly=class extends oy{constructor(g,f,S,v){super(g,f,S,v)}},cy=class extends oy{constructor(g,f,S,v,C){super(g,f,S,v,C)}toDeviceDesc(){const g=super.toDeviceDesc();return g.isSystemDefault=this.isSystemDefault,g}},dy=class extends oy{constructor(g,f,S,v,C){if(super(g,f,S,v,C),this.position="unknown",C&&C.facingMode&&1===C.facingMode.length)switch(C.facingMode[0]){case"user":this.position="front";break;case"environment":this.position="back"}}toDeviceDesc(){const g=super.toDeviceDesc();return g.position=this.position,g}},hy=class extends oy{constructor(g,f,S,v,C,_){super(null,S,v,""),this.micDevice=g,this.speakerDevice=f,this.formFactor=C,this.isPcInternalDevice=_,this.guid=null,this.isSystemDefault=!1}get micDeviceId(){return this.micDevice.guid}get speakerDeviceId(){return this.speakerDevice.guid}toDeviceDesc(){const g=super.toDeviceDesc();return g.microphoneId=this.micDeviceId,g.speakerId=this.speakerDeviceId,g.formFactor=this.formFactor,g.isPcInternalDevice=this.isPcInternalDevice,g}};function createDevice(g){const f=g.getCapabilities&&g.getCapabilities();switch(f&&(delete f.groupId,delete f.deviceId),g.kind){case qt.MEDIA_DEVICE_KIND.audioInput:case qt.MEDIA_DEVICE_KIND.audioOutput:return new cy(g.deviceId,g.label,g.kind,g.groupId,f);case qt.MEDIA_DEVICE_KIND.videoInput:return new dy(g.deviceId,g.label,g.kind,g.groupId,f);default:throw new Error(`Device kind is not recognized: ${g.kind}`)}}function createCompositeAudioDevice(g,f,S){return new hy(g,f,S,"compositeAudio",0,!1)}function createDefaultDevice(g){const f={deviceId:qt.MEDIA_DEVICE.defaultId,label:qt.MEDIA_DEVICE.defaultDeviceLabel,kind:getKind(g),groupId:"",toJSON:()=>JSON.stringify(f)};return createDevice(f)}function getKind(g){switch(g){case qt.MEDIA_DEVICE.microphone:return qt.MEDIA_DEVICE_KIND.audioInput;case qt.MEDIA_DEVICE.speaker:return qt.MEDIA_DEVICE_KIND.audioOutput;case qt.MEDIA_DEVICE.camera:return qt.MEDIA_DEVICE_KIND.videoInput;default:throw new Error(`Device type to recognized: ${g}`)}}function compilePrimitiveDeviceList(g,f,S,v,C={str:""}){C.str+=`|input(${f.length})`;let _=[];const T=[v.config.devices.blacklist[g],v.defaultConfig.devices.blacklist[g]];for(const g of T)try{const S=new RegExp(g,"i");_=f.filter((f=>g&&f.label.match(S)?(C.str+=`|-blacklisted(${f.label})`,!1):f.deviceId!==qt.MEDIA_DEVICE.communicationsId||(C.str+="|-communications",!1)));break}catch(S){C.str+=`|filterError('${g}', ${stringifyObject2(S)})`,_=f}if(_.length){const f=deductDefaultDevice(S,_,C);if(f&&(f.isSystemDefault=!0,C.str+=`|default(${scrubMriOrOmit(f.guid)})`),f&&f.deviceId!==qt.MEDIA_DEVICE.defaultId&&_.length>1&&(_=_.filter((g=>g.deviceId!==qt.MEDIA_DEVICE.defaultId||(C.str+="|-defaultId",!1)))),g===qt.MEDIA_DEVICE.camera||f||(C.str+="|+syntheticDefault",_.unshift(createDefaultDevice(g))),S.forEach((g=>{const f=_.find((f=>f.guid===g.guid));f&&!f.label&&g.label&&(C.str+=`|migrateLabel(${scrubMriOrOmit(f.guid)})`,f.label=g.label)})),g===qt.MEDIA_DEVICE.speaker){const g=_.filter((g=>""===g.label));g.length>1&&g.length===_.length&&(_=f?[f]:[_[0]],C.str+=`|-filteredEmptyLabels(${g.length})`)}}return _}function deductDefaultDevice(g,f,S){if(1===f.length)return S.str+="|default:only",f[0];const v=f.find((g=>g.isSystemDefault&&g.deviceId===qt.MEDIA_DEVICE.defaultId));if(!v)return S.str+="|default:noSynthetic",f.find((g=>g.isSystemDefault))||f[0];{const C=f.filter((g=>g!==v));if(1===C.length)return S.str+="|default:firstNonDefault",C[0];if(""!==v.groupId){const g=C.filter((g=>g.groupId===v.groupId));if(1===g.length)return S.str+=`|default:groupId(${scrubMriOrOmit(g[0].guid)})`,g[0]}const _=C.map((g=>g.label)),T=getMaxSubstring(v.label,_),I=C.find((g=>g.label===T));if(I)return S.str+=`|default:label(${scrubMriOrOmit(I.guid)})`,I;const b=g.find((g=>g.isSystemDefault));if(b){const g=C.find((g=>g.deviceId===b.deviceId));if(g)return S.str+=`|default:previousList(${scrubMriOrOmit(g.guid)})`,g}}return S.str+="|default:anyOrNull",f.find((g=>g.isSystemDefault))||null}function compileAudioDeviceList(g,f,S=.5,v={str:""}){const C=[];if(g.length&&f.length){const _=getGroupedPairs(g.filter((g=>""!==g.groupId)),f.filter((g=>""!==g.groupId)),v);_.length&&(C.push(..._.map((g=>createCompositeAudioDevice(g.microphone,g.speaker,createCompositeDeviceLabel(g.microphone.label,g.speaker.label))))),v.str+=`|directMatched(${C.length})`);const T=C.length;C.push(...composeAudioDevicesFromLabels(g.filter((g=>!C.some((f=>f.micDeviceId===g.guid)))),f.filter((g=>!C.some((f=>f.speakerDeviceId===g.guid)))),S,v)),v.str+=`|otherMatched(${C.length-T})`}return C}function getGroupedPairs(g,f,S={str:""}){const v=new Set;for(const S of[...g,...f])v.add(S.groupId);const C=[];for(const _ of v.values()){let v=g.filter((g=>g.groupId===_)),T=f.filter((g=>g.groupId===_));if(v&&T)if(1===v.length&&1===T.length)C.push({microphone:v[0],speaker:T[0]}),S.str+=`|pairSimple(${scrubMriOrOmit(v[0].guid)}, ${scrubMriOrOmit(T[0].guid)})`;else if(v.length>1||T.length>1){let g=getMostSimilarPair(v,T);for(;g;)S.str+=`|pairComplex(${scrubMriOrOmit(g.microphone.guid)}, ${scrubMriOrOmit(g.speaker.guid)})`,C.push(g),v=v.filter((f=>f!==g.microphone)),T=T.filter((f=>f!==g.speaker)),g=getMostSimilarPair(v,T)}}return C}function getMostSimilarPair(g,f){let S=999,v=null;if(g.length>0&&f.length>0)for(const C of g)for(const g of f){const f=levenshteinDistance(C.label,g.label);f<S&&(S=f,v={microphone:C,speaker:g})}return v}function composeAudioDevicesFromLabels(g,f,S,v){const C=[];return g.length&&f.length?(g.forEach((g=>{const _=f.filter((f=>f.groupId===g.groupId));if(!_.length)return void(v.str+=`|lbl_nocand(${scrubMriOrOmit(g.guid)})`);let T=getLongestCommonContiguousSubstring(g.label,_[0].label).length;const I=_.sort(((f,S)=>{const v=getLongestCommonContiguousSubstring(g.label,f.label),C=getLongestCommonContiguousSubstring(g.label,S.label);return v.length>T&&(T=v.length),C.length>T&&(T=C.length),C.length-v.length}));if(I.length){const f=T/g.label.length;f>S&&(C.push(createCompositeAudioDevice(g,I[0],createCompositeDeviceLabel(g.label,I[0].label))),v.str+=`|lbl_matched(${scrubMriOrOmit(g.guid)} & ${scrubMriOrOmit(I[0].guid)}, ${Math.round(1e4*f)/100}%)`)}})),C):C}function createCompositeDeviceLabel(g,f){if(g===f)return g;let S=getLongestCommonContiguousSubstring(g,f);S=S.trim().replace(/^\((.+)\)$/,"$1");let v="",C="",_=0;const T=[countBraces(g),countBraces(f)];if(0===T[0]||0===T[1])return S;for(let g=0;g<S.length;g++)if("("===S[g])_++,C+=S[g];else if(")"===S[g]){if(!(_>0))break;_--,C+=S[g],v+=C,C=""}else _>0?C+=S[g]:v+=S[g];const I=countBraces(v);return I!==T[0]&&I!==T[1]||(v=v.replace(/\w+\s?\((.+)\)/,"$1"),v=createCompositeDeviceLabel(S,v)),v.trim()}function countBraces(g){const f=["(",")"];let S=0;for(let v=0;v<g.length;v++)f.some((f=>g[v]===f))&&S++;return S}var uy={microphone:"",camera:"",speaker:"",compositeAudio:"",audioIngestDevice:"",virtualDevice:""},gy=class extends Ht{constructor(g,f){super(f),this.configProvider=g,this.logger=f,this.debugInfo=uy,this.lists=new Map,this.lists.set(qt.MEDIA_DEVICE.microphone,[]),this.lists.set(qt.MEDIA_DEVICE.camera,[]),this.configProvider.userAgentConfig.isAudioOutputSelectionSupported&&(this.lists.set(qt.MEDIA_DEVICE.speaker,[]),this.lists.set(qt.MEDIA_DEVICE.compositeAudio,[])),g.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>this.onConfigUpdated())),this.logger.safe.info("Initialized")}get devices(){const g=[];return this.lists.forEach((f=>g.push(...f))),g}getDevicesByType(g){return this.lists.get(g)??[]}updateDevices(g,f=!1){if(deepEqual(this.latestRawList,g))return;this.latestRawList=g;const S=this.devices;this.debugInfo.microphone="microphone",this.debugInfo.camera="camera",this.debugInfo.speaker="speaker",this.debugInfo.compositeAudio="compositeAudio",this.updatePrimitiveDeviceList(qt.MEDIA_DEVICE.microphone,g.filter((g=>g.type===qt.MEDIA_DEVICE.microphone))),this.updatePrimitiveDeviceList(qt.MEDIA_DEVICE.camera,g.filter((g=>g.type===qt.MEDIA_DEVICE.camera))),this.lists.get(qt.MEDIA_DEVICE.speaker)&&(this.updatePrimitiveDeviceList(qt.MEDIA_DEVICE.speaker,g.filter((g=>g.type===qt.MEDIA_DEVICE.speaker))),this.lists.get(qt.MEDIA_DEVICE.compositeAudio)&&this.updateCompositeAudioDeviceList(this.lists.get(qt.MEDIA_DEVICE.microphone),this.lists.get(qt.MEDIA_DEVICE.speaker)));const v=this.lists.get(qt.MEDIA_DEVICE.compositeAudio)||[];this.lists.set(qt.MEDIA_DEVICE.microphone,this.orderDeviceList(this.lists.get(qt.MEDIA_DEVICE.microphone),v)),this.lists.get(qt.MEDIA_DEVICE.speaker)&&this.lists.set(qt.MEDIA_DEVICE.speaker,this.orderDeviceList(this.lists.get(qt.MEDIA_DEVICE.speaker),v));const C=this.lists.get(qt.MEDIA_DEVICE.microphone);this.setTopItemToDefault(C);const _=this.lists.get(qt.MEDIA_DEVICE.speaker);this.setTopItemToDefault(_),deepEqual(S,this.devices)||(this.logger.safe.info("Device lists updated and changed"),this.logger.safe.info(this.debugInfo.microphone),this.logger.safe.info(this.debugInfo.camera),this.logger.safe.info(this.debugInfo.speaker),this.logger.safe.info(this.debugInfo.compositeAudio),this.event("onDevicesChanged").raise(this.devices,f))}updateVirtualDeviceList(g){const f=this.lists.get(qt.MEDIA_DEVICE.virtualDevice),S=g.map((g=>new ly(g.id,g.label,"virtualDevice","")));deepEqual(f,S)?this.logger.safe.info("Device lists did not change."):(this.lists.set(qt.MEDIA_DEVICE.virtualDevice,S),this.event("onDevicesChanged").raise(this.devices,!1))}updateActiveMicrophone(g){if(!g||g.deviceId===qt.MEDIA_DEVICE.defaultId)return;const f=this.lists.get(qt.MEDIA_DEVICE.microphone),S=f.findIndex((g=>g.isSystemDefault));-1!==S&&f[S]!==g?(this.logger.safe.info("Removing synthetic default microphone"),g.isSystemDefault=!0,f.splice(S,1),this.lists.set(qt.MEDIA_DEVICE.microphone,f),this.event("onDevicesChanged").raise(this.devices,!1)):g.isSystemDefault=!0}updatePrimitiveDeviceList(g,f){const S={str:this.debugInfo[g]};this.lists.set(g,compilePrimitiveDeviceList(g,f,this.lists.get(g)||[],this.configProvider,S)),this.debugInfo[g]=S.str}updateCompositeAudioDeviceList(g,f){const S={str:this.debugInfo.compositeAudio};this.lists.set(qt.MEDIA_DEVICE.compositeAudio,compileAudioDeviceList(g,f,this.configProvider.config.devices.compositeLabelMatchingThreshold,S)),this.debugInfo.compositeAudio=S.str}orderDeviceList(g,f){return g.sort(((g,S)=>this.getDevicePriority(S,this.getCompositeAudioDeviceCounterpart(S,f))-this.getDevicePriority(g,this.getCompositeAudioDeviceCounterpart(g,f))))}getCompositeAudioDeviceCounterpart(g,f){const S=f.find((f=>f.micDeviceId===g.guid||f.speakerDeviceId===g.guid));return S?S[g.type===qt.MEDIA_DEVICE.speaker?"micDevice":"speakerDevice"]:null}getDevicePriority(g,f){let S=0;return this.configProvider.config.devices.overrideDefault&&f&&(!g.isSystemDefault&&f.isSystemDefault?(this.debugInfo[g.type]+=`|overrideDefault(${scrubMriOrOmit(g.guid)})`,S+=10):g.isSystemDefault&&!f.isSystemDefault&&"microphone"===g.type&&(S+=15)),g.isSystemDefault&&(S+=5),f&&(S+=1,f.isSystemDefault&&(S+=2)),S}setTopItemToDefault(g){g?.length&&(g.forEach((g=>g.isSystemDefault=!1)),g[0].isSystemDefault=!0)}onConfigUpdated(){let g=!1;this.configProvider.userAgentConfig.isAudioOutputSelectionSupported?this.lists.has(qt.MEDIA_DEVICE.speaker)||(this.lists.set(qt.MEDIA_DEVICE.speaker,[]),this.lists.set(qt.MEDIA_DEVICE.compositeAudio,[]),g=!0):(this.lists.has(qt.MEDIA_DEVICE.speaker)&&(this.lists.delete(qt.MEDIA_DEVICE.speaker),g=!0),this.lists.has(qt.MEDIA_DEVICE.compositeAudio)&&(this.lists.delete(qt.MEDIA_DEVICE.compositeAudio),g=!0)),g&&(this.logger.safe.info("Updating device list due to config update"),this.updateDevices(this.latestRawList||[]))}},py=class _DeviceEnumerator2 extends Ht{constructor(g,f){super(f),this.pollingInterval=0,_DeviceEnumerator2.enumeratorUsers.add(this),_DeviceEnumerator2.initialize(this,g,f)}startDevicePolling(g){this.pollingInterval=g?_DeviceEnumerator2.configProvider.config.devices.pollingIntervalIdle:_DeviceEnumerator2.configProvider.config.devices.pollingIntervalActive,_DeviceEnumerator2.updatePollingTask()}stopDevicePolling(g){this.pollingInterval=g?0:_DeviceEnumerator2.configProvider.config.devices.pollingIntervalIdle,_DeviceEnumerator2.updatePollingTask()}dispose(){super.dispose(),this.stopDevicePolling(!0),_DeviceEnumerator2.enumeratorUsers.delete(this),0===_DeviceEnumerator2.enumeratorUsers.size&&(_DeviceEnumerator2.logger.safe.info("disposing"),_DeviceEnumerator2.initializeCalled=!1,_DeviceEnumerator2.isDeviceListAvailable=new dt,_DeviceEnumerator2.list=void 0,_DeviceEnumerator2.window.navigator.mediaDevices.ondevicechange=void 0)}static get isPolling(){return 0!==_DeviceEnumerator2.currentPollingInterval}static initialize(g,f,S){_DeviceEnumerator2.initializeCalled||(_DeviceEnumerator2.initializeCalled=!0,_DeviceEnumerator2.window=Xs.window,_DeviceEnumerator2.configProvider=f,_DeviceEnumerator2.logger=S,_DeviceEnumerator2.list=new gy(f,S.createChild("DeviceList")),f.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>_DeviceEnumerator2.enumerateDevices())),f.on("configUpdated",(()=>{void 0!==f.config.devices.pollingIntervalIdle&&null!==_DeviceEnumerator2.pollingTimer&&g.startDevicePolling(!0)})),f.config.devices.pollingIntervalIdle&&f.config.devices.idlePollingOnStart&&g.startDevicePolling(!0),_DeviceEnumerator2.window.navigator.mediaDevices&&(_DeviceEnumerator2.window.navigator.mediaDevices.ondevicechange=()=>{S.safe.info("enumerating due to ondevicechange callback"),_DeviceEnumerator2.enumerateDevices().catch((g=>{S.safe.error(`unable to enumerate ondevicechange: ${stringifyObject2(g)}`)}))}),_DeviceEnumerator2.enumerateDevices())}static async enumerateDevices(g=!1){if(!_DeviceEnumerator2.window.navigator?.mediaDevices?.enumerateDevices){const g=new Error("device enumeration unsupported");throw _DeviceEnumerator2.isDeviceListAvailable.isPending&&_DeviceEnumerator2.isDeviceListAvailable.reject(g),g}if(_DeviceEnumerator2.enumerateDevicesPromise&&!g)return _DeviceEnumerator2.logger.safe.info("enumeration request postponed"),_DeviceEnumerator2.hasPendingUpdate=!0,void(_DeviceEnumerator2.isDeviceListAvailable.isPending&&et.isEngine("Firefox")&&_DeviceEnumerator2.isDeviceListAvailable.resolve());try{if(!_DeviceEnumerator2.enumerateDevicesPromise)if(_DeviceEnumerator2.configProvider.config.devices.enumerateDevicesTimeout){const g=deferWithTimeout2(_DeviceEnumerator2.configProvider.config.devices.enumerateDevicesTimeout);_DeviceEnumerator2.enumerateDevicesPromise=g.promise,_DeviceEnumerator2.window.navigator.mediaDevices.enumerateDevices().then(g.resolve,g.reject)}else _DeviceEnumerator2.enumerateDevicesPromise=_DeviceEnumerator2.window.navigator.mediaDevices.enumerateDevices();const f=await _DeviceEnumerator2.enumerateDevicesPromise;_DeviceEnumerator2.list.updateDevices(f.map((g=>createDevice(g))),g),_DeviceEnumerator2.isDeviceListAvailable.isPending&&_DeviceEnumerator2.isDeviceListAvailable.resolve()}catch(g){const f=stringifyObject2(g);throw _DeviceEnumerator2.logger.safe.warn(`error with enumerating devices: ${f}`),_DeviceEnumerator2.raiseFailedEnumeration(f),_DeviceEnumerator2.isDeviceListAvailable.isPending&&_DeviceEnumerator2.isDeviceListAvailable.reject(g),g}finally{_DeviceEnumerator2.enumerateDevicesPromise=void 0,_DeviceEnumerator2.hasPendingUpdate&&(_DeviceEnumerator2.hasPendingUpdate=!1,_DeviceEnumerator2.logger.safe.info("running postponed enumeration"),_DeviceEnumerator2.enumerateDevices())}}static updatePollingTask(){let g=Number.MAX_SAFE_INTEGER;for(const f of _DeviceEnumerator2.enumeratorUsers.values())f.pollingInterval<g&&(g=f.pollingInterval);if(g===Number.MAX_SAFE_INTEGER&&(g=0),(_DeviceEnumerator2.pollingTimer||_DeviceEnumerator2.currentPollingInterval!==g)&&_DeviceEnumerator2.pollingTimer&&(_DeviceEnumerator2.window.clearTimeout(_DeviceEnumerator2.pollingTimer),_DeviceEnumerator2.pollingTimer=void 0),_DeviceEnumerator2.currentPollingInterval=g,0===g)return;const pollingTask=async()=>{if(_DeviceEnumerator2.currentPollingInterval)try{await _DeviceEnumerator2.enumerateDevices(!0),_DeviceEnumerator2.pollingTimer=_DeviceEnumerator2.window.setTimeout(pollingTask,_DeviceEnumerator2.currentPollingInterval)}catch(g){throw _DeviceEnumerator2.pollingTimer=null,g}};_DeviceEnumerator2.logger.safe.info(`starting device polling with interval ${g}ms`),_DeviceEnumerator2.pollingTimer=1,pollingTask()}static raiseFailedEnumeration(g){for(const f of _DeviceEnumerator2.enumeratorUsers.values())f.event("onDeviceEnumerationfailed").raise(g)}};py.isDeviceListAvailable=new dt,py.initializeCalled=!1,py.currentPollingInterval=0,py.hasPendingUpdate=!1,py.enumeratorUsers=new Set;var my=py,fy=class extends Ht{constructor(g,f,S){super(S),this.deviceList=g,this.configProvider=f,this.logger=S,this.userSelectedDevices={microphone:null,camera:null,speaker:null},this.currentlySelectedDevices={microphone:null,camera:null,speaker:null,audioIngestDevice:null},this.deviceList.on("onDevicesChanged",(g=>this.onDevicesChanged(g))),g.devices.length>0&&this.onDevicesChanged(g.devices),this.logger.safe.info("Initialized")}get selectedDevices(){return deepClone(this.currentlySelectedDevices)}selectDevices(g){let f=!1;if(forOwn(g,((g,S)=>{const v=this.getDeviceToSelect(S,this.deviceList.getDevicesByType("audioIngestDevice"===S?"microphone":S),g);"camera"===S&&(this.userSelectedDevices[S]=v?.guid||this.userSelectedDevices[S]),v?.guid!==this.currentlySelectedDevices[S]?.guid&&(this.userSelectedDevices[S]=v?.guid||this.userSelectedDevices[S],f=!0),this.currentlySelectedDevices[S]=v})),f){const g=values(this.currentlySelectedDevices).map((g=>JSON.stringify(scrubDevices(g,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed from public interface: ${g}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!0)}}getDeviceToSelect(g,f,S){let v;const C=this.userSelectedDevices[g];return S?v=f.find((g=>g.guid===S)):C&&(v=f.find((g=>g.guid===C))),"audioIngestDevice"===g?v:v||f[0]}onDevicesChanged(g){let f=!1;if(Object.keys(this.currentlySelectedDevices).forEach((S=>{const v="audioIngestDevice"===S?"microphone":S,C=g.filter((g=>g.type===v));if(C.length>0){const g=this.getDeviceToSelect(S,C);g?.guid!==this.currentlySelectedDevices[S]?.guid&&(this.currentlySelectedDevices[S]=g,f=!0)}else this.currentlySelectedDevices[S]&&(this.currentlySelectedDevices[S]=null,f=!0)})),f){const g=values(this.currentlySelectedDevices).map((g=>JSON.stringify(scrubDevices(g,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed due to device list change: ${g}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!1)}}},Sy=class extends Ht{constructor(g,f){super(g),this.logger=g,this.mediaStream=f,this.subs=[],this.subscribeOnMediaStreamEvents(f)}acquire(){return this.mediaStream?this.mediaStream.start().then((()=>this.logger.safe.info("Stream acquired"))).catch((g=>{throw this.logger.safe.warn(`Failed to acquire the stream: ${stringifyObject2(g)}`),g})):Promise.reject("Disposed")}dispose(){this.logger.safe.info("Disposing stream"),this.unsubscribeFromMediaStreamEvents(),this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),super.dispose()}subscribeOnMediaStreamEvents(g){this.subs=[g.on("onStreamClientStarted",(()=>this.event("onStreamStateChanged").raise("active"))),g.on("onStreamClientMuted",((g,f)=>this.event("onStreamStateChanged").raise(f?"inactive":"active"))),g.on("onStreamClientEnded",(()=>this.event("onStreamStateChanged").raise("stopped"))),g.on("onStreamClientError",((g,f)=>{const S=f.type===qt.MEDIA_ERROR.permissionDeniedError||f.type===qt.MEDIA_ERROR.sharingCancelledError;this.event("onStreamStateChanged").raise(S?"cancelled":"failed")}))]}unsubscribeFromMediaStreamEvents(){this.subs.forEach((g=>g.dispose())),this.subs=[]}},vy=[qt.MEDIA_STATE.inactive,qt.MEDIA_STATE.receive,qt.MEDIA_STATE.send,qt.MEDIA_STATE.sendReceive],Cy=[qt.MEDIA_STATE.inactive,qt.MEDIA_STATE.receive],yy=class extends Ht{constructor(g,f,S){super(S),this.configProvider=g,this.deviceManager=f,this.logger=S,this.currentState={microphone:"unknown",camera:"unknown"},this.lastGum={audio:!1,video:!1},this.registeredTrackers=new Set,this.accessIssuePermissionOther={audio:!1,video:!1},this.window=Xs.window,this.permittedModalities={audio:vy,video:vy,sharing:vy},this.initialize()}async initialize(){!oa.hasPermissionsApi()||"unknown"!==this.currentState.microphone&&"unknown"!==this.currentState.camera?"unknown"!==this.currentState.microphone&&"unknown"!==this.currentState.camera||this.logger.safe.warn(`Permissions API is not supported in this browser. Microphone: ${this.currentState.microphone}, camera: ${this.currentState.camera}`):(this.logger.safe.info("Initializing"),await this.registerPermissionTracker("microphone"),await this.registerPermissionTracker("camera"))}getPermissionState(g){return this.currentState[g]||"unknown"}isPermissionKnown(g){const f=this.getPermissionState(g);return"unknown"!==f&&"prompt"!==f}get browserPermittedModalities(){return this.permittedModalities}get knownPermissionStates(){return deepClone(this.currentState)}update(g,f){const S=deepClone(f);g.audio||delete S.audio,g.video||delete S.video;const v=deepClone(this.permittedModalities);forOwn(S,((g,f)=>{this.permittedModalities[f]=g?vy:Cy})),deepEqual(v,this.permittedModalities)||this.event("onDevicesPermissionChanged").raise()}async askDevicePermission(g){const f=g?deepClone(g):{audio:!0,video:this.deviceManager.hasCamera()};if(this.accessIssuePermissionOther={audio:!1,video:!1},this.configProvider.config.permissions.rememberNegative&&(f.audio=f.audio&&this.permittedModalities.audio===vy,f.video=f.video&&this.permittedModalities.video===vy),f.sharing)throw new Error("askDevicePermission does not support sharing constraints.");const S={audio:!1,video:!1};this.lastGum={audio:!1,video:!1};const resolve=async(S,v,C)=>{const _={audio:!!S.audio,video:!!S.video,sharing:!0};return!(this.configProvider.config.permissions.adpRequestAVLast&&f.audio&&f.video)||this.lastGum.audio&&this.lastGum.video||(this.logger.safe.info("Prompting for audio and video to ensure omnibar state"),await this.askDevicePermissionPrompt({audio:!0,video:!0},!1)),this.update(f,_),this.deviceManager.raiseTelemetryEvent("ask_device_permission",{constraints:g,resultConstraints:S,error:C,reason:v}),_};await this.initialize();const v=this.getPermissionState("microphone"),C=this.getPermissionState("camera");if(this.logger.safe.info(`Permission state { audio: ${v}, video: ${C} }`),this.configProvider.config.permissions.useNegativeInAdp&&(!f.audio||"denied"===v)&&(!f.video||"denied"===C))return resolve(S,"navigator_permissions_denied");if(this.configProvider.config.permissions.usePositiveInAdp&&(!f.audio||f.audio&&"granted"===v)&&(!f.video||f.video&&"granted"===C))return resolve(f,"navigator_permissions_granted");try{return resolve(this.getConstrainsWithPermissionError(await this.askDevicePermissionPrompt(f,this.configProvider.config.permissions.adpFallback)),"stream_acquisition")}catch(g){return resolve(S,"stream_acquisition",g)}}async askDevicePermissionPrompt(g,f=!0){const S={audio:!1,video:!1};try{const f=this.deviceManager.getMediaStream(g);return f&&(this.lastGum=deepClone(g),await f.start(),S.audio=f.hasAudio(),S.video=f.hasVideo(),this.disposeLater(f)),S}catch(v){if(g.audio&&g.video&&f){try{S.video=this.configProvider.config.permissions.adpFallbackVideo&&(await this.askDevicePermissionPrompt({video:!0})).video}catch(g){g.type!==qt.MEDIA_ERROR.permissionDeniedError&&g.type!==qt.MEDIA_ERROR.permissionDeniedBySystemError&&(this.accessIssuePermissionOther.video=!0)}try{S.audio=this.configProvider.config.permissions.adpFallbackAudio&&(await this.askDevicePermissionPrompt({audio:!0})).audio}catch(g){g.type!==qt.MEDIA_ERROR.permissionDeniedError&&g.type!==qt.MEDIA_ERROR.permissionDeniedBySystemError&&(this.accessIssuePermissionOther.audio=!0)}}else if(f)throw v;return S}}getConstrainsWithPermissionError(g){return this.configProvider.config.permissions.disableOnPermissionDeniedOnly?{audio:this.accessIssuePermissionOther.audio||g.audio,video:this.accessIssuePermissionOther.video||g.video}:g}disposeLater(g){setTimeout((()=>{g.dispose()}),this.configProvider.config.mediaStreamHoldInterval)}async registerPermissionTracker(g){if(!this.registeredTrackers.has(g))try{const f=await this.window.navigator.permissions.query({name:g});this.handlePermissionStateChanged(g,f.state),f.onchange=()=>this.handlePermissionStateChanged(g,f.state),this.registeredTrackers.add(g)}catch(f){this.logger.safe.error(`Error querying permissions for ${g}: ${stringifyObject2(f)}`)}}handlePermissionStateChanged(g,f){if(this.logger.safe.info(`Permission state for ${g} changed ${this.currentState[g]} -> ${f}`),this.configProvider.config.permissions.enumerateDevicesAfterChange){this.logger.safe.info(`enumerateDevicesAfterChange: ${JSON.stringify(this.configProvider.config.permissions)}`),my.logger.safe.info("enumerating due to permission change");try{my.enumerateDevices()}catch(g){my.logger.safe.error(`unable to enumerate on permission change: ${stringifyObject2(g)}`)}}this.currentState[g]=f,this.deviceManager.raiseTelemetryEvent("permissions_state_changed",this.knownPermissionStates),this.deviceManager.handlePermissionStateChange()}},Ey=class extends Ke{constructor(g,f=uniqueId()){super(),this.dms=g,this.label=f,this.id=uniqueId(),this.receivedEvents=new Map,this.subscribeToDeviceManagers(g)}getDeviceManagers(){return this.dms}dispose(){super.dispose(),this.dms?.forEach((g=>g.dispose())),this.dms=null}subscribeToDeviceManagers(g){g.forEach(((g,f)=>{g.on("onVideoEffectsEvent",((...f)=>this.eventHandler("onVideoEffectsEvent",g,(()=>this.event("onVideoEffectsEvent").raise(...f))))),g.on("onVideoEffectApplied",((...f)=>this.eventHandler("onVideoEffectApplied",g,(()=>this.event("onVideoEffectApplied").raise(...f))))),g.on("onDeviceTelemetryEvent",(g=>this.event("onDeviceTelemetryEvent").raise({deviceId:`${this.id}/${f}`,...g}))),g.on("onVideoEffectsTelemetryEvent",(g=>this.event("onVideoEffectsTelemetryEvent").raise({deviceId:`${this.id}/${f}`,...g}))),g.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise(`${this.id}/${f}`))),g.on("onStreamUpdateRequested",((...g)=>this.event("onStreamUpdateRequested").raise(...g)))}))}eventHandler(g,f,S){let v=this.receivedEvents.get(g);if(v??(v=new Set),v.add(f),this.dms.every((g=>v.has(g))))return S(),void v.clear();this.receivedEvents.set(g,v)}},sequentialize=()=>(g,f,S)=>{const v=S.value;return S.value=function(...g){return this.serialQueue.add(v.bind(this,...g))},S},_y=class{constructor(g,f,S){this.configProvider=g,this.statistics=f,this.logger=S}isWasmEffectSupported(){return this.configProvider.config.webcv.useWasmEffects?!!window.MediaStreamTrackProcessor||(this.logger.info("wasmEffects disabled, insertable streams are not supported"),!1):(this.logger.info("wasmEffects disabled by feature flag"),!1)}isWebgl2EffectSupported(){return this.isCurrentRendererSupported()&&this.isWebGL2Supported()}isCurrentRendererSupported(){const g=this.configProvider.config.webcv.webGLUnsupportedRenderers;let f=!1;const S=oa.unmaskedGlRenderer;return S&&!g.some((g=>g===S))?f=!0:(this.statistics.setError("RendererIsNotSupported",`Blacklisted from ${JSON.stringify(g)}`),this.logger.info(`Unsupported renderer: ${stringifyObject2(S)}`)),f}isWebGL2Supported(){try{const g=document.createElement("canvas").getContext("webgl2");if(!g)return this.statistics.setError("WebGL2IsNotSupported"),this.logger.info("WebGL2 context is not supported"),!1;const f=g.getSupportedExtensions(),S=this.configProvider.config.webcv.webGLRequiredExtensions.filter((g=>!f.includes(g)));if(S.length>0)return this.statistics.setError("WebGL2RequiredExtensionsNotSupported","Required WebGL2 extensions not supported."),this.logger.info(`Unsupported WebGL2 extensions: ${stringifyObject2(S)}`),!1}catch(g){return this.statistics.setError("WebGL2IsNotSupported",`Error: ${stringifyObject2(g)}`),this.logger.error(`isWebGL2Supported: ${stringifyObject2(g)}`),!1}return!0}},Ty=class{constructor(g){this.error=new Vv(g)}startLoadTimer(){this.loadStartTimestamp=Date.now()}stopLoadTimer(){this.loadDuration=Date.now()-this.loadStartTimestamp}clearErrors(){this.error.clear()}setError(g,f){this.error.add({type:g,message:f})}getReport(){return{loadDuration:this.loadDuration,error:this.error.items}}},Iy=class extends Ht{constructor(g,f,S,v){super(S),this.webcvProvider=g,this.configProvider=f,this.logger=S,this.wasmLoader=v,this.serialQueue=new zC(this.logger),this.videoEffectToWebCVEffectMapping={0:lr.VideoEffectType.Off,1:lr.VideoEffectType.BackgroundBlur,16:lr.VideoEffectType.BackgroundReplacement,512:lr.VideoEffectType.PresenterMode,256:lr.VideoEffectType.None,2048:lr.VideoEffectType.None,262144:lr.VideoEffectType.None},this.currentEffect=0,this.effectProviderSubs=[],this.statistics=new Ty(this.configProvider.config.effectsTelemetryBufferSize),this.processorType=lr.ProcessorType.Webgl2,this.queryMessageProcessor=new by(this.configProvider,this.logger)}get isEffectEnabled(){return 0!==this.currentEffect||0!==this.queryMessageProcessor.payload.effectType}async init(){if(!this.effectProvider)try{this.effectProvider=await this.initializeVideoEffectProvider()}catch(g){throw Error(g)}}async dispose(){this.logger.safe.debug("Dispose"),this.effectProvider&&(this.effectProviderSubs.forEach((g=>g.dispose())),this.effectProviderSubs=null,await this.effectProvider.disposeAsync()),super.dispose()}async configure(g){if(this.logger.safe.debug(`Set config: ${JSON.stringify(g)}`),this.effectConfig={backgroundImageUrl:g.imagePath,headers:g.headers},this.effectProvider)return this.effectProvider.configureEffect(this.effectConfig);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async setEffectAsync(g){if(this.currentEffect===g)return void this.logger.safe.debug(`Effect ${this.currentEffect} is already set`);this.effectProvider||(this.logger.safe.debug("Initializing effect provider"),await this.init()),this.logger.safe.debug(`Set effect: ${g}`);const f=this.getWebCVEffect(g);if(!f)throw new Error(`Effect with type ${g} is not supported`);if(this.shouldCollectStats(g)&&this.notifyAboutLastSessionStats("EffectChanged"),this.currentEffect=g,this.effectProvider)try{await this.effectProvider.setEffectAsync(f)}catch(g){throw await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to apply ${f}, error:${stringifyObject2(g)}`),g}else this.logger.safe.debug("WebCV is not initialized. Do nothing")}async processingVideoEffectMessage(g){let f={code:0,response:{effects:[]},type:"EnableEffects"};try{await this.init()}catch(g){return this.logger.error(`Failed to initialize WebCV, error:${stringifyObject2(g)}`),this.notifyError("FailedToInitialize",`Initialization failed, error:${stringifyObject2(g)}`),f}const S=this.currentEffect;this.logger.info(`Processing video effect request type: ${JSON.stringify(g.type)}`),f=await this.queryMessageProcessor.processVideoEffectMessage(g),this.queryMessageProcessor.reconfigure&&(await this.configure({imagePath:this.queryMessageProcessor.payload.imageConfig.backgroundImageUrl,headers:this.queryMessageProcessor.payload.imageConfig.headers}),this.queryMessageProcessor.reconfigure=!1);try{this.shouldCollectStats(S)&&this.notifyAboutLastSessionStats("EffectChanged"),await this.effectProvider.setEffectAsync(this.getWebCVEffect(this.queryMessageProcessor.payload.effectType),this.queryMessageProcessor.payload)}catch{this.logger.error("Failed to apply video effect")}return f}async setSourceAsync(g){if(this.logger.safe.debug(`Set source: ${g?g.id:"no stream"}`),!this.effectProvider)return this.logger.safe.debug("WebCV is not initialized. Do nothing"),g;let f=g;try{f=await this.effectProvider.setSourceAsync(g)}catch(g){await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to set source, error:${stringifyObject2(g)}`)}return f}async removeSourceAsync(g){if(this.logger.safe.debug(`Remove source: ${g?g.id:"no stream"}`),this.effectProvider)return this.effectProvider.removeSourceAsync(g);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async getEffectsCapability(){let g=0;const f=await this.getCapability();this.logger.safe.debug(`Get capabilty with return: ${JSON.stringify(f)}`);for(const S of f)g|=S;return g}getStats(g){if(!this.effectProvider)return;const f=this.effectProvider.getStats(),S=this.statistics.getReport();return f||S.error.length?{timestamp:Date.now(),statsReason:g,...this.createTelemetryEvent(f,S)}:void 0}getVersion(){return this.effectProvider?.getVersion?.()??"Unknown"}async resetOutputConstraints(g,f=lr.EffectQualityChangeReason.ExternalParam){const S={...this.configProvider.config.webcv.qualityConfig};return S.outputResolution=g.height,this.effectProvider?.configureStreamProcessor(S,lr.EffectQualityChangeReason.ExternalParam)}createTelemetryEvent(g,f){return{payload:{version:this.getVersion(),...f,...g,isWasmEnabled:this.processorType===lr.ProcessorType.Wasm}}}notifyError(g,f){this.statistics.setError(g,f),this.notifyAboutLastSessionStats("EffectError")}notifyAboutLastSessionStats(g){const f=this.getStats(g);f&&this.event("onVideoEffectTelemetryEvent").raise(f)}async initializeVideoEffectProvider(){if(!this.webcvProvider)return this.logger.safe.debug("WebCV provider is not set"),null;this.statistics.startLoadTimer();const g=await this.webcvProvider.getVideoEffectProvider();if(this.statistics.stopLoadTimer(),!g)return this.statistics.setError("FailedToInitialize"),this.logger.safe.warn("WebCV is not initialized"),null;this.logger.safe.debug(`WebCV v${g.getVersion?.()} is initialized`);const f=await this.webcvProvider.getModelConfig();return await g.configureModel(f),this.configProvider.config.webcv.loadWorkerCallback=this.wasmLoader.getWorkerFunction("wasmcv"),this.configProvider.config.webcv.loadTimerWorkerCallback=this.wasmLoader.getWorkerFunction("timer"),await g.configure({...this.configProvider.config.webcv,processorType:this.processorType}),this.effectConfig&&await g.configureEffect(this.effectConfig),this.effectProviderSubs=[g.on("onEffectApplied",(()=>this.event("onMediaStreamUpdateRequested").raise("Video"))),g.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats("EffectStopped"))),g.on("onVideoEffectQualityChanged",(g=>this.event("onVideoEffectQualityChanged").raise(g))),g.on("onVideoStreamQualityChanged",(g=>this.event("onVideoStreamQualityChanged").raise(g.resolution,g.fps,g.reason))),g.on("onCapabilitiesChanged",(()=>this.event("onVideoEffectCapabilitiesChanged").raise())),g.on("onFirstFrameProcessed",(()=>this.onFirstFrameProcessed())),g.on("onErrorNotified",(g=>this.notifyError("WebcvProcessorError",g))),g.on("videoFreezeDetected",(g=>this.event("videoFreezeDetected").raise(g)))],g}async getCapability(){if(!this.configProvider.config.enableVideoEffects)return this.logger.debug("Video effects disabled"),[0];if(!this.webcvProvider)return this.logger.debug("WebCVProvider is not configured"),[0];const g=new _y(this.configProvider,this.statistics,this.logger.createChild("CapabilityChecker"));let f=[0];return g.isWasmEffectSupported()?(f=[0,1,16,262144,512,2048],this.processorType=lr.ProcessorType.Wasm):g.isWebgl2EffectSupported()&&(f=[0,1,16],this.processorType=lr.ProcessorType.Webgl2),f}getWebCVEffect(g){return this.videoEffectToWebCVEffectMapping[g]||lr.VideoEffectType.None}onFirstFrameProcessed(){this.event("onVideoEffectApplied").raise(),this.logger.safe.debug("onVideoEffectApplied event raised")}async handleFailedProcessing(){this.currentEffect=0;try{await this.effectProvider.setEffectAsync(lr.VideoEffectType.Off)}catch(g){this.notifyError("WebcvProcessorError",`Failed to handle error state, error:${stringifyObject2(g)}`)}}shouldCollectStats(g){return 0!==this.currentEffect&&0!==g&&this.currentEffect!==g}};__decorateClass([sequentialize()],Iy.prototype,"init",1),__decorateClass([sequentialize()],Iy.prototype,"dispose",1),__decorateClass([sequentialize()],Iy.prototype,"configure",1),__decorateClass([sequentialize()],Iy.prototype,"setSourceAsync",1),__decorateClass([sequentialize()],Iy.prototype,"removeSourceAsync",1),__decorateClass([sequentialize()],Iy.prototype,"getEffectsCapability",1);var by=class{constructor(g,f){this.configProvider=g,this.logger=f,this.currentEffects=0,this.currentEffectPayload={effectType:0},this.shouldReconfigure=!1}get payload(){return this.currentEffectPayload.effectType=this.currentEffects,this.currentEffectPayload}get reconfigure(){return this.shouldReconfigure}set reconfigure(g){this.shouldReconfigure=g}async processVideoEffectMessage(g){switch(g.type){case"EnableEffects":return await this.processEnableEffectsMessage(g);case"DisableEffects":return await this.processDisableEffectsMessage(g);case"QueryEffects":return await this.processQueryEffectsMessage(g);default:return this.logger.error(`Unsupported video effect message type: ${g.type}`),null}}async processEnableEffectsMessage(g){const f={code:0,response:{effects:[]},type:"EnableEffects"};for(let S=0;S<g.request.effects.length;S++){const v=g.request.effects[S];switch(v.type){case"BackgroundModification":if("Blur"===v.options.variant){this.currentEffects|=1;const g={type:"BackgroundModification",options:{variant:"Blur"}};f.response.effects.push(g),this.currentEffects&=-262673}else if("Replacement"===v.options.variant){this.currentEffects|=16;const g={type:"BackgroundModification",options:{variant:"Replacement",location:v.options.location}};this.shouldReconfigure=!0,this.currentEffectPayload.imageConfig={backgroundImageUrl:v.options.location,headers:v.options?.headers},f.response.effects.push(g),this.currentEffects&=-262658}else if("WeatherPerson"===v.options.variant){if(!this.configProvider.config.webcv.useWasmEffects){this.logger.error("WeatherPerson effect is not supported on non wasm effect provider");break}this.currentEffects|=512;const g={type:"BackgroundModification",options:{variant:"WeatherPerson"}};f.response.effects.push(g),this.currentEffects&=-262162}else if("Bokeh"===v.options.variant){if(!this.configProvider.config.webcv.useWasmEffects){this.logger.error("Bokeh effect is not supported on non wasm effect provider");break}this.currentEffects|=262144;const g={type:"BackgroundModification",options:{variant:"Bokeh"}};f.response.effects.push(g),this.currentEffects&=-530}break;case"TouchUp":this.logger.error("TouchUp effect is not supported on non wasm effect provider");break;case"AutoAdjust":if(!this.configProvider.config.webcv.useWasmEffects){this.logger.error("AutoAdjust effect is not supported on non wasm effect provider");break}this.currentEffects|=2048,f.response.effects.push({type:"AutoAdjust"})}}return f}async processQueryEffectsMessage(g){const f={code:0,response:{effects:[]},type:"QueryEffects"};if(1&this.currentEffects){const g={type:"BackgroundModification",options:{variant:"Blur"},state:"On"};f.response.effects.push(g)}else{const g={type:"BackgroundModification",options:{variant:"Blur"},state:"Off"};f.response.effects.push(g)}if(262144&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const g={type:"BackgroundModification",options:{variant:"Bokeh"},state:"On"};f.response.effects.push(g)}else if(this.configProvider.config.webcv.useWasmEffects){const g={type:"BackgroundModification",options:{variant:"Bokeh"},state:"Off"};f.response.effects.push(g)}else{const g={type:"BackgroundModification",options:{variant:"Bokeh"},state:"Unavailable"};f.response.effects.push(g)}if(16&this.currentEffects){const g={variant:"Replacement",location:""};this.currentEffectPayload?.imageConfig&&(g.location=this.currentEffectPayload?.imageConfig.backgroundImageUrl);const S={type:"BackgroundModification",options:g,state:"On"};f.response.effects.push(S)}else{const g={type:"BackgroundModification",options:{variant:"Replacement",location:""},state:"Off"};f.response.effects.push(g)}if(512&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const g={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"On"};f.response.effects.push(g)}else if(this.configProvider.config.webcv.useWasmEffects){const g={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"Off"};f.response.effects.push(g)}else{const g={type:"BackgroundModification",options:{variant:"WeatherPerson"},state:"Unavailable"};f.response.effects.push(g)}if(256&this.currentEffects){const g={type:"TouchUp",state:"Unavailable",options:{strength:0}};f.response.effects.push(g)}if(2048&this.currentEffects&&this.configProvider.config.webcv.useWasmEffects){const g={type:"AutoAdjust",state:"On"};f.response.effects.push(g)}else if(this.configProvider.config.webcv.useWasmEffects){const g={type:"AutoAdjust",state:"Off"};f.response.effects.push(g)}else{const g={type:"AutoAdjust",state:"Unavailable"};f.response.effects.push(g)}return f}async processDisableEffectsMessage(g){const f={code:0,response:{effects:[]},type:"DisableEffects"},S=g,v={effects:[]};for(let g=0;g<S.request.effects.length;g++){const f=S.request.effects[g];switch(f.type){case"BackgroundModification":if("Blur"===f.options.variant){const g={type:"BackgroundModification",options:{variant:"Blur"}};v.effects.push(g),this.currentEffects&=-2}if("Bokeh"===f.options.variant){const g={type:"BackgroundModification",options:{variant:"Bokeh"}};v.effects.push(g),this.currentEffects&=-262145}if("Replacement"===f.options.variant){const g={variant:"Replacement",location:""};void 0!==this.payload?.imageConfig&&(g.location=this.payload?.imageConfig.backgroundImageUrl);const f={type:"BackgroundModification",options:g};v.effects.push(f),this.currentEffects&=-17}if("WeatherPerson"===f.options.variant){const g={type:"BackgroundModification",options:{variant:"WeatherPerson"}};v.effects.push(g),this.currentEffects&=-513}break;case"TouchUp":this.logger.error("TouchUp effect is not supported now"),v.effects.push({type:"TouchUp",options:{strength:0}}),this.currentEffects&=-257,this.currentEffectPayload.softfocusStrength=0;break;case"AutoAdjust":v.effects.push({type:"AutoAdjust"}),this.currentEffects&=-2049}}return f.response=v,f}},Ay=class extends Ht{constructor(g,f,S,v,C,_){super(C),this.wasmdnsProvider=g,this.wasmaecProvider=f,this.wasmVqeProvider=S,this.configProvider=v,this.logger=C,this.wasmLoader=_,this.serialQueue=new zC(this.logger),this.stopped=!0,this.hasError=!1,this.statistics=new Ty(this.configProvider.config.effectsTelemetryBufferSize),this.currentEffect=cr.AudioEffectType.Off,this.currentEffectCapability=0,this.audioEffectToWasmAudioEffectType={0:cr.AudioEffectType.Off,1:cr.AudioEffectType.NoiseSuppressionClassic,2:cr.AudioEffectType.NoiseSuppressionDeep,4:cr.AudioEffectType.EchoCancellationClassic,8:cr.AudioEffectType.VoiceQualityEnhancementClassic,16:cr.AudioEffectType.VoiceQualityEnhancementDeep},this.noiseSuppressionModeToWasmDnsEffectMapping={Off:cr.AudioEffectType.Off,High:cr.AudioEffectType.NoiseSuppressionDeep,Low:cr.AudioEffectType.NoiseSuppressionClassic}}get isEffectEnabled(){return this.currentEffect!==cr.AudioEffectType.Off}shouldFallbackToNativeProcessing(){return!(!this.configProvider.config.enableAudioProcessingFallback||(this.configProvider.config.wasmvqe.enableVqe||this.configProvider.config.wasmdns.enableNoiseSuppression?this.hasError?(this.logger.safe.info("shouldFallbackToNativeProcessing: error was encountred initializing the package"),0):this.configProvider.config.wasmvqe.enableVqe&&!this.wasmVqeProvider?(this.logger.safe.info("shouldFallbackToNativeProcessing: VQE provider is enabled but not loaded"),0):!this.configProvider.config.wasmdns.enableNoiseSuppression||this.wasmdnsProvider&&this.wasmaecProvider||(this.logger.safe.info("shouldFallbackToNativeProcessing: DNS/AEC provider is enabled but not loaded"),0):(this.logger.safe.info("shouldFallbackToNativeProcessing: custom processing is not enabled"),0)))}nsModeToVqeMode(g,f){switch(g){case"High":return f?cr.VqeMode.DeepVQE:cr.VqeMode.DeepNS;case"Low":return f?cr.VqeMode.SkypeVQE:cr.VqeMode.SkypeNS;default:return f?cr.VqeMode.SkypeAEC:cr.VqeMode.Off}}vqeModeToNsMode(g){switch(g){case cr.VqeMode.DeepVQE:case cr.VqeMode.DeepNS:return"High";case cr.VqeMode.SkypeVQE:case cr.VqeMode.SkypeNS:return"Low";case cr.VqeMode.SkypeAEC:case cr.VqeMode.Off:default:return"Off"}}vqeModeToAudioEffectType(g){switch(g){case cr.VqeMode.DeepVQE:return 16;case cr.VqeMode.DeepNS:return 2;case cr.VqeMode.SkypeVQE:return 8;case cr.VqeMode.SkypeNS:return 1;case cr.VqeMode.SkypeAEC:return 4;case cr.VqeMode.Off:default:return 0}}audioEffectTypeToVqeMode(g){switch(g){case 16:return cr.VqeMode.DeepVQE;case 2:return cr.VqeMode.DeepNS;case 8:return cr.VqeMode.SkypeVQE;case 1:return cr.VqeMode.SkypeNS;case 4:return cr.VqeMode.SkypeAEC;default:return cr.VqeMode.Off}}async initializeProvider(){if(this.configProvider.config.wasmvqe.enableVqe&&!this.vqeProvider)return this.logger.safe.debug("Initializing VQE provider ..."),void(this.vqeProvider=await this.initializeAudioEffectProvider(cr.AudioEffectType.VoiceQualityEnhancementDeep));this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.dnsProvider&&(this.logger.safe.debug("Initializing DNS provider ..."),this.dnsProvider=await this.initializeAudioEffectProvider(cr.AudioEffectType.NoiseSuppressionDeep)),this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.aecProvider&&(this.logger.safe.debug("Initializing AEC provider ..."),this.aecProvider=await this.initializeAudioEffectProvider(cr.AudioEffectType.EchoCancellationClassic))}async configureEffect(g){this.statistics.clearErrors();let f=g;if(!f){let g=this.configProvider.mediaConfig.noiseSuppressionMode;this.logger.safe.info(`Configuring the audio effect manager for Noise Suppression mode: ${g}`),"Auto"===g&&(g=this.configProvider.config.wasmvqe.enableVqe?this.vqeModeToNsMode(this.configProvider.config.wasmvqe.defaultVqeMode):this.configProvider.config.wasmdns.noiseSuppressionMode,this.logger.safe.info(`Overriding 'Auto' with ${g}`)),f={...this.configProvider.config.wasmdns,...this.configProvider.config.wasmvqe},f.noiseSuppressionMode=g}if(await this.getEffectsCapability(),this.configProvider.config.wasmvqe.enableVqe)try{if(!this.vqeProvider)return void this.logger.safe.error("VQE provider is not initialized");this.userNoiseSuppressionMode&&(f.defaultVqeMode=this.userNoiseSuppressionMode),f.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmVqeWorklet,f.loadWasmWorkerCallback=this.wasmLoader?.audioWorklet?.getWasmVqeWorker,this.logger.safe.debug("Configuring VQE audio effects ..."),await this.vqeProvider.configureEffect(f),this.logger.safe.debug(`The audio effects were configured as follows: ${stringifyObject2(f)}, and current capability is ${this.currentEffectCapability}.`)}catch(g){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${g}), while trying to use this configuration: ${stringifyObject2(f)},\n                    under the following capability: ${this.currentEffectCapability}.`),this.requestStreamUpdate(!1,!0)}else if(this.configProvider.config.wasmdns.enableNoiseSuppression){f.noiseSuppressionMode||(this.logger.safe.debug("configureEffect was called without a noiseSuppressionMode. Using noiseSuppressionMode from config provider ..."),f.noiseSuppressionMode=this.configProvider.mediaConfig.noiseSuppressionMode),this.currentEffect=this.noiseSuppressionModeToWasmDnsEffectMapping[f.noiseSuppressionMode],this.logger.safe.debug(`currentEffect is ${this.currentEffect}`);try{if(!this.dnsProvider||!this.aecProvider)return void this.logger.safe.debug("DNS & AEC providers not initialized");this.logger.safe.debug("Configuring DNS/AEC audio effects ..."),f.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmDnsWorklet,await this.dnsProvider.configureEffect(f),f.loadAudioWorkletCallback=this.wasmLoader?.audioWorklet?.getWasmAecWorklet,await this.aecProvider.configureEffect(f),this.logger.safe.debug(`The audio effects were configured as follows: ${stringifyObject2(f)}, and current capability is ${this.currentEffectCapability}.`)}catch(g){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${g}), while trying to use this configuration: ${stringifyObject2(f)},\n                    under the following capability: ${this.currentEffectCapability}.`),this.requestStreamUpdate(!1,!0)}}}async setSourceAsync(g){if(this.logger.safe.debug(`Set source: ${g?g.id:"no stream"}, currentEffect = ${this.currentEffect}`),this.stopped||(this.stop(),this.stopped=!1),this.shouldFallbackToNativeProcessing())return this.logger.safe.info("No custom audio effect is used. Fallback to native audio processing"),g;if(await this.initializeProvider(),await this.configureEffect(),!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const f=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setSourceAsync: audio effect provider not initialized (${f}).`),this.logger.safe.warn(`Unable to configure audio effects: audio effect provider not initialized (${f}).`),g}if(!this.configProvider.config.wasmvqe.enableVqe&&!this.configProvider.config.wasmdns.enableNoiseSuppression)return g;if(this.effectProviderSubs=[this.vqeProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onErrorNotified",((g,f)=>this.notifyError("WasmVqeProcessorError",g,f))),this.dnsProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onErrorNotified",(g=>this.notifyError("WasmDnsProcessorError",g))),this.aecProvider?.on("onErrorNotified",(g=>this.notifyError("WasmAecProcessorError",g)))],this.configProvider.config.wasmvqe.enableVqe)try{const f=await this.vqeProvider.setSourceAsync(g);return this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId)),f}catch(f){return this.notifyError("WasmVqeProcessorError",`setSourceAsync: Failed to asynchronously set source for VQE (${f})`),g}let f=g;try{f=await this.aecProvider.setSourceAsync(g),this.aecRefStream&&(this.logger.safe.debug(`Setting the reference stream to: ${this.aecRefStream.id}`),this.setAecRefStream(this.aecRefStream,this.rendererId))}catch(g){this.notifyError("WasmAecProcessorError",`setSourceAsync: Failed to asynchronously set source for AEC (${g})`)}try{return await this.dnsProvider.setSourceAsync(f)}catch(g){this.notifyError("WasmDnsProcessorError",`setSourceAsync: Failed to asynchronously set source for DNS (${g})`)}return f}setAecRefStream(g,f){try{if(!g&&this.rendererId!==f)return void this.logger.safe.debug(`Ref stream can't be set to null by renderer ${f}`);if(this.logger.safe.debug(`Setting the reference stream to: ${g?g.id:"Null"} requested by renderer ${f}`),this.aecRefStream=g,this.rendererId=f,!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const g=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setAecRefStream: audio effect provider not initialized (${g}).`),void this.logger.safe.warn(`Unable to setAecRefStream for audio effects: audio effect provider not initialized (${g}).`)}this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider.setRefStream(g):this.configProvider.config.wasmdns.enableNoiseSuppression&&this.aecProvider.setRefStream(g)}catch(g){this.notifyError("WasmVqeProcessorError",`setRefStream: Failed to set reference stream for echo cancellation (${g})`)}}async setEffectAsync(g){const f=this.audioEffectToWasmAudioEffectType[g];if(this.currentEffect===f)return;const S=this.currentEffect===cr.AudioEffectType.Off||f===cr.AudioEffectType.Off;if(this.currentEffect=f,this.userNoiseSuppressionMode=this.audioEffectTypeToVqeMode(g),await this.initializeProvider(),await this.configureEffect(),!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const g=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";throw this.notifyError("FailedToInitialize",`setEffectAsync: audio effect provider not initialized (${g}).`),Error("FailedToInitialize")}try{this.configProvider.config.wasmvqe.enableVqe?await this.vqeProvider.setEffectAsync(f):this.configProvider.config.wasmdns.enableNoiseSuppression&&(await this.dnsProvider.setEffectAsync(f),await this.aecProvider.setEffectAsync(f)),this.configProvider.config.applyAudioEffectOnDemand&&this.configProvider.config.wasmvqe.enableVqe&&S&&this.requestStreamUpdate(!0),this.logger.safe.debug(`The audio effect was set to '${f}'`)}catch(g){throw this.notifyError("WasmVqeProcessorError",`setEffectAsync: Failed to apply '${f}' audio effect, error: ${stringifyObject2(g)}`),g}}stop(){try{this.aecRefStream=null,this.dnsProvider?.dispose(),this.dnsProvider=null,this.aecProvider?.dispose(),this.aecProvider=null,this.vqeProvider?.dispose(),this.vqeProvider=null,this.effectProviderSubs?.forEach((g=>g?.dispose())),this.effectProviderSubs=null,this.stopped=!0,this.logger.safe.debug("The audio effects provider was stopped.")}catch(g){this.logger.safe.error(`Failed to stop the audio effects provider (${g})`)}}dispose(){try{this.hasError=!1,this.stop(),super.dispose(),this.logger.safe.debug("The audio effects provider was disposed.")}catch(g){this.logger.safe.error(`dispose: Failed to dispose the audio effects provider (${g})`)}}async getEffectsCapability(){return this.currentEffectCapability=0,this.configProvider.config.wasmvqe.enableVqe?(this.currentEffectCapability|=1,this.currentEffectCapability|=2,this.configProvider.config.wasmvqe.enableAec&&(this.currentEffectCapability|=4,this.currentEffectCapability|=8,this.currentEffectCapability|=16)):this.configProvider.config.wasmdns.enableNoiseSuppression&&(this.currentEffectCapability|=1,this.currentEffectCapability|=2,this.currentEffectCapability|=4),this.currentEffectCapability}getVersion(){return`WasmDns ${this.dnsProvider?.getVersion()??"Unknown"} / WasmAec ${this.aecProvider?.getVersion()??"Unknown"} / WasmVqe ${this.vqeProvider?.getVersion()??"Unknown"}`}getStats(){const g=this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider?.getStats():this.dnsProvider?.getStats();return g?(g.userNoiseSuppressionMethod=this.userNoiseSuppressionMode,{timestamp:Date.now(),...this.createTelemetryEvent(g)}):null}async initializeAudioEffectProvider(g){if(!this.wasmVqeProvider&&g===cr.AudioEffectType.VoiceQualityEnhancementDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmVqe package not available."),this.logger.safe.warn("WasmVqe package not available."),null;if(!this.wasmdnsProvider&&g===cr.AudioEffectType.NoiseSuppressionDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmDns package not available."),this.logger.safe.warn("WasmDns package not available."),null;if(!this.wasmaecProvider&&g===cr.AudioEffectType.EchoCancellationClassic)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmAec package not available."),this.logger.safe.warn("WasmAec package not available."),null;let f;this.statistics.startLoadTimer();try{this.configProvider.config.wasmvqe.enableVqe&&g===cr.AudioEffectType.VoiceQualityEnhancementDeep&&(f=await this.wasmVqeProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&g===cr.AudioEffectType.NoiseSuppressionDeep&&(f=await this.wasmdnsProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&g===cr.AudioEffectType.EchoCancellationClassic&&(f=await this.wasmaecProvider.getAudioEffectProvider())}catch(g){this.logger.safe.warn(`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${g})`),this.statistics.setError("FailedToInitialize",`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${g})`)}return this.statistics.stopLoadTimer(),f?(g===cr.AudioEffectType.VoiceQualityEnhancementDeep&&this.logger.safe.debug(`WasmVqe v${f.getVersion?.()} initialized!`),g===cr.AudioEffectType.NoiseSuppressionDeep&&this.logger.safe.debug(`WasmDns v${f.getVersion?.()} initialized!`),g===cr.AudioEffectType.EchoCancellationClassic&&this.logger.safe.debug(`WasmAec v${f.getVersion?.()} initialized!`),f):(this.logger.safe.warn("Unitialized Wasm audio effect provider."),null)}createTelemetryEvent(g){return{payload:{audioEffectsCapability:this.currentEffectCapability,version:this.getVersion(),...this.statistics.getReport(),...g}}}notifyError(g,f,S=!1){this.logger.error(`Audio effect error: ${g}, message: ${f}`),this.statistics.setError(g,f),this.notifyAboutLastSessionStats(),S&&this.requestStreamUpdate(!1,!0),this.event("onEffectsError").raise("Audio",g,f)}notifyAboutLastSessionStats(){const g=this.getStats();g&&this.event("onAudioEffectTelemetryEvent").raise(g)}requestStreamUpdate(g=!1,f=!1){(g||this.configProvider.config.enableAudioProcessingFallback&&!this.hasError)&&(this.hasError=f,this.event("onMediaStreamUpdateRequested").raise("Audio"))}};__decorateClass([sequentialize()],Ay.prototype,"setSourceAsync",1),__decorateClass([sequentialize()],Ay.prototype,"setAecRefStream",1),__decorateClass([sequentialize()],Ay.prototype,"setEffectAsync",1),__decorateClass([sequentialize()],Ay.prototype,"stop",1),__decorateClass([sequentialize()],Ay.prototype,"dispose",1);var Py=class{constructor(g){this.logger=g}async setSourceAsync(g){let f=document.createElement("video");return f.srcObject=g,this.logger.info(`Stream settings before play: ${JSON.stringify(this.getSettings(g))}`),await f.play(),this.logger.info(`Stream settings after play: ${JSON.stringify(this.getSettings(g))}`),f.pause(),f.srcObject=null,f.remove(),f=null,g}getSettings(g){return g.getVideoTracks()?.[0]?.getSettings()}},Ry=class extends Ht{constructor(g,f){super(),this.configProvider=g,this.logger=f}isEffectEnabled(g){switch(g){case"Video":return this.videoEffectManager?.isEffectEnabled;case"Audio":return this.audioEffectManager?.isEffectEnabled;default:return!1}}shouldFallbackToNativeProcessing(g){return"Audio"===g&&this.audioEffectManager?.shouldFallbackToNativeProcessing()}addEffectManager(g,f){switch(g){case"Audio":this.addAudioEffectManagerAndSubscribe(f);break;case"Video":this.addVideoEffectManagerAndSubscribe(f);break;case"ScreenShare":this.delayedScreenShareEffectManager=new Py(this.logger.createChild("DelayedScreenShareEffectManager"))}}async startEffect(g,f){switch(g){case"Audio":return this.audioEffectManager.setSourceAsync(f);case"Video":return this.videoEffectManager.setSourceAsync(f);case"ScreenShare":return this.delayedScreenShareEffectManager.setSourceAsync(f);default:return f}}async setEffectType(g,f){switch(g){case"Audio":return this.audioEffectManager?.setEffectAsync(f);case"Video":return this.videoEffectManager?.setEffectAsync(f)}}async processingVideoEffectMessage(g){return this.videoEffectManager.processingVideoEffectMessage(g)}stopEffect(g,f){switch(g){case"Audio":this.logger.safe.info("stopping audio effect"),this.audioEffectManager?.stop();break;case"Video":this.logger.safe.info("stopping video effect"),this.videoEffectManager?.removeSourceAsync(f)}}resetOutputConstraints(g,f,S){"Video"===g&&this.videoEffectManager?.resetOutputConstraints(f,S)}getStats(g,f){switch(g){case"Audio":return this.audioEffectManager?.getStats();case"Video":return this.videoEffectManager?.getStats(f);default:return}}async configure(g,f){if("Video"===g)return this.videoEffectManager?.configure(f)}async getEffectsCapability(g){switch(g){case"Audio":return this.audioEffectManager?.getEffectsCapability();case"Video":return this.videoEffectManager?.getEffectsCapability();default:return 0}}setAecRefStream(g,f){return this.audioEffectManager.setAecRefStream(g,f)}vqeModeToAudioEffectType(g){return this.audioEffectManager.vqeModeToAudioEffectType(g)}nsModeToVqeMode(g,f){return this.audioEffectManager.nsModeToVqeMode(g,f)}getAudioEffectsProviderName(){let g="None";return this.configProvider.config.wasmvqe.enableVqe?g="DeepVqe":this.configProvider.config.wasmdns.enableNoiseSuppression&&(g="DNS"),g}dispose(){super.dispose(),this.audioEffectManager?.dispose(),this.audioEffectManager=null,this.videoEffectManager?.dispose(),this.videoEffectManager=null}addAudioEffectManagerAndSubscribe(g){this.audioEffectManager||(this.audioEffectManager=new Ay(g.wasmdnsProvider,g.wasmaecProvider,g.wasmVqeProvider,this.configProvider,this.logger.createChild("AudioEffectManager"),g.wasmLoader),this.audioEffectManager.on("onAudioEffectTelemetryEvent",(g=>{this.event("onAudioEffectTelemetryEvent").raise(g)})),this.audioEffectManager.on("onMediaStreamUpdateRequested",(g=>{this.event("onMediaStreamUpdateRequested").raise(g)})),this.audioEffectManager.on("onEffectsError",((g,f,S)=>{this.event("onEffectsError").raise(g,f,S)})))}addVideoEffectManagerAndSubscribe(g){this.videoEffectManager||(this.videoEffectManager=new Iy(g.webcvProvider,this.configProvider,this.logger.createChild("VideoEffectManager"),g.wasmLoader),this.videoEffectManager.on("onMediaStreamUpdateRequested",(g=>{this.event("onMediaStreamUpdateRequested").raise(g)})),this.videoEffectManager.on("onVideoEffectQualityChanged",(g=>{this.event("onVideoEffectQualityChanged").raise(g)})),this.videoEffectManager.on("onVideoStreamQualityChanged",((g,f,S)=>{this.event("onVideoStreamQualityChanged").raise(g,f,S)})),this.videoEffectManager.on("onVideoEffectCapabilitiesChanged",(()=>{this.event("onVideoEffectCapabilitiesChanged").raise()})),this.videoEffectManager.on("onVideoEffectTelemetryEvent",(g=>{this.event("onVideoEffectTelemetryEvent").raise(g)})),this.videoEffectManager.on("onVideoEffectApplied",(()=>{this.event("onVideoEffectApplied").raise()})),this.videoEffectManager.on("videoFreezeDetected",(g=>{this.event("videoFreezeDetected").raise(g)})))}},My=class{constructor(g){this.audioContext=new Xs.window.AudioContext,g?(this.sourceNode=this.audioContext.createMediaStreamSource(g),this.analyzerNode=this.createAnalyserNode(this.sourceNode),this.freqs=new Uint8Array(this.analyzerNode.frequencyBinCount),this.ffreqs=new Float32Array(this.analyzerNode.frequencyBinCount)):(this.freqs=new Uint8Array(0),this.ffreqs=new Float32Array(0))}dispose(){this.sourceNode.disconnect(),this.audioContext.close(),this.audioContext=null,this.sourceNode=null,this.analyzerNode=null,this.freqs=null}getData(g){return 1===g?this.analyzerNode?.getByteFrequencyData(this.freqs):0===g&&this.analyzerNode?.getByteTimeDomainData(this.freqs),this.freqs}getDataFloat(g){return 1===g?this.analyzerNode?.getFloatFrequencyData(this.ffreqs):0===g&&this.analyzerNode?.getFloatTimeDomainData(this.ffreqs),this.ffreqs}getInputLevel(){return this.analyzerNode?.getByteFrequencyData(this.freqs),getAverage(this.freqs)}getInputLevelNormalized(g=65535,f=255){return Math.floor(this.getInputLevel()*g/f)}createAnalyserNode(g){const f=this.audioContext.createAnalyser();return f.fftSize=1024,f.smoothingTimeConstant=.1,g.connect(f),f}},wy=class _AudioStreamAnalyzerWrapper{constructor(g,f,S){this.logger=g,this.audioStreamAnalyzer=f,this.rawStream=S}getInputLevel(){return this.audioStreamAnalyzer.getDataFloat(0).reduce(((g,f)=>Math.max(Math.abs(f),g)),0)}getInputLevelNormalized(g,f){throw new Error("Method not implemented.")}dispose(g){this.logger.safe.info(`[${g}] AudioStreamAnalyzerWrapper disposed`),this.audioStreamAnalyzer.dispose(),this.rawStream?.dispose()}static async init(g,f){try{const S=g.getRawDeviceMediaStream("Audio"),v=await S.getMediaStream(),C=new My(v),_=new _AudioStreamAnalyzerWrapper(f,C,S);return _.rawStream.changed((async()=>{const g=await S.getMediaStream();_.audioStreamAnalyzer.dispose(),_.audioStreamAnalyzer=new My(g)})),f.safe.info("AudioStreamAnalyzerWrapper created"),_}catch(g){f.safe.warn(`failed to acquire audio stream for mic level: ${g}`);const S=new My;return new _AudioStreamAnalyzerWrapper(f,S)}}},Oy=class _DeviceManager extends Ht{constructor(g,f,S,v,C,_,T,I,b,A){super(g),this.logger=g,this.configProvider=f,this.diagnostics=S,this.domOverrides=v,this.ufdManager=C,this.id=uniqueId(),this.virtualDeviceRecord=new Map,this.deviceEnumerator=new my(this.configProvider,this.logger.createChild("DeviceEnumerator")),this.deviceSelection=new fy(my.list,this.configProvider,this.logger.createChild("DeviceSelection")),this.permissionManager=new yy(this.configProvider,{getMediaStream:g=>this.getMediaStream({...g,withEffect:!1,withTimeout:!0,force:!1,audioProcessingFlags:g.audio&&!g.video?this.getAudioProcessingFlags():void 0},"permissionManager"),hasCamera:()=>this.hasDeviceType("camera"),raiseTelemetryEvent:(g,f)=>this.raiseTelemetryEvent(g,f),getActiveConstraints:()=>this.mediaStreamManager.getActiveConstraints(),handlePermissionStateChange:()=>this.handlePermissionStateChange()},this.logger.createChild("PermissionManager")),this.activeRenderers=[],this.selectedDevices={camera:null,microphone:null,speaker:null,audioIngestDevice:null},this.pendingDevices=null,this.deviceManagerSubscriptions=[],this.streamManagerSubscriptions=[],this.streamSubscriptions=new Map,this.rendererSubscriptions=new Map,this.rawDeviceStreamManager=new qC(this.logger.createChild("RawDeviceStream"),this.raiseTelemetryEvent.bind(this)),this.customDeviceMediaStreamMap=new Map,this.clientAudioRenderers=new Map,this.audioSharingRequested=!1,this.virtualDeviceSubs=new Map,this.effectsManagerInternal=new Ry(this.configProvider,this.logger.createChild("EffectsManager")),this.effectsManagerInternal.addEffectManager("Audio",{wasmdnsProvider:T,wasmaecProvider:I,wasmVqeProvider:b,wasmLoader:A}),this.effectsManagerInternal.addEffectManager("Video",{webcvProvider:_,wasmLoader:A}),this.effectsManagerInternal.addEffectManager("ScreenShare",null),this.mediaStreamManager=new sy(this.logger.createChild("MediaStreamManager"),this.configProvider,this.effectsManager),this.deviceManagerSubscriptions=[this.permissionManager.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise())),my.list.on("onDevicesChanged",((g,f)=>this.onDevicesChanged(g,f))),this.deviceSelection.on("onSelectedDevicesChanged",((g,f)=>this.onSelectedDevicesChanged(g,f))),this.effectsManager.on("onAudioEffectTelemetryEvent",(g=>{this.diagnostics.registerAudioEffectsEvent(deepClone(g)),this.event("onAudioEffectsTelemetryEvent").raise(g)})),this.effectsManager.on("onMediaStreamUpdateRequested",(g=>this.onMediaStreamUpdateRequested(g,!0))),this.effectsManager.on("onVideoEffectQualityChanged",(g=>this.onVideoEffectsQualityEventHandler(g))),this.effectsManager.on("onVideoEffectTelemetryEvent",(g=>{this.diagnostics.registerVideoEffectsEvent(deepClone(g)),this.event("onVideoEffectsTelemetryEvent").raise(g)})),this.effectsManager.on("onVideoEffectApplied",(()=>{this.raiseTelemetryEvent("video_effect_applied",{}),this.event("onVideoEffectApplied").raise()})),this.effectsManager.on("onEffectsError",((g,f,S)=>this.event("onEffectsError").raise(g,f,S)))],this.subscribeOnStreamManagerEvents(),this.subscribeOnDeviceEnumeratorEvents(),this.deviceList.length&&this.onSelectedDevicesChanged(this.deviceSelection.selectedDevices,!1),this.createChildDeviceManager=g=>new _DeviceManager(g,f,new ay(f),v,C,_,T,I,b,A)}get deviceList(){return my.list.devices}get isDeviceListAvailable(){return my.isDeviceListAvailable}get isAudioOutputSelectionSupported(){return this.configProvider.userAgentConfig.isAudioOutputSelectionSupported}get effectsManager(){return this.effectsManagerInternal}createPreviewRenderer(g,f){const S=new ty(g,this,this.logger.createChild("videorenderer"),this.configProvider,f);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(S.getVideoElement()),this.subscribeOnRendererEvents(S),S}async askDevicePermission(g){await this.isDeviceListAvailable.promise;const f=await this.permissionManager.askDevicePermission(g);if(this.configProvider.config.devices.enumerateDevicesAfterADP)try{await my.enumerateDevices()}catch(g){this.logger.safe.warn(`Post-ADP device enumeration failed: ${stringifyObject2(g)}`)}return f}getPermissionState(g){return this.permissionManager.getPermissionState(g)}handlePermissionStateChange(){this.diagnostics&&(this.diagnostics.permissionStates=this.permissionManager.knownPermissionStates),this.event("onPermissionStateChanged").raise()}onMediaStreamUpdateRequested(g,f=!1){if("Video"===g&&(this.updateRenderersAsync(),this.effectsManager.isEffectEnabled("Video")))return this.logger.safe.info("onStreamUpdateRequested will be called after the first frame is proccessed of the video effect stream"),void this.effectsManager.once("onVideoEffectApplied",(()=>this.event("onStreamUpdateRequested").raise(g)));this.event("onStreamUpdateRequested").raise(g,f)}createAudioRenderer(){const g=new WC(this.logger.createChild("CustomAudioRenderer"),this.configProvider),f=g.id;this.clientAudioRenderers.set(f,g);const S=g.play.bind(g),v=g.stop.bind(g);return this.raiseTelemetryEvent("custom_audio_renderer_created",this.getSelectedDevices()),{play:S,stop:v,dispose:()=>{this.clientAudioRenderers.get(f)?.dispose(),this.clientAudioRenderers.delete(f)},setMuted:(f,S=generateCauseId())=>g.setMuted(f,S),isMuted:()=>g.muted}}setAudioSharingRequested(g){this.audioSharingRequested=g}createDevicesHandle(g,f,S){const v=g.sharing?"ScreenShare":g.video?"Video":"Audio";return new Sy(this.logger.createChild("DevicesHandle"),this.getMediaStream({...g,...S&&{deviceId:S},withTimeout:!1,withEffect:!1,audioProcessingFlags:this.audioProcessingFlags,force:!1,withOverridenStream:this.customDeviceMediaStreamMap.get(v)?.active&&this.customDeviceMediaStreamMap.get(v)},f))}shareSystemSound(g){this.configProvider.config.postponeAudioMixerForAudioSharing&&(this.audioSharingRequested=g,this.event("onAudioSharingToggled").raise(g))}getAllowedModalities(){const g=shallowClone(this.permissionManager.browserPermittedModalities);return this.hasDeviceType("microphone")||(g.audio=[qt.MEDIA_STATE.inactive,qt.MEDIA_STATE.receive]),this.hasDeviceType("camera")||(g.video=[qt.MEDIA_STATE.inactive,qt.MEDIA_STATE.receive]),g}getRawDeviceMediaStream(g,f){if("ScreenShare"!==g&&!this.hasDeviceType(this.getDeviceType(g)))throw new Error("NoInputDevice");this.audioSharingRequested=f;const S=this.getStreamHandlerByType(g);if(!S)return this.logger.safe.debug(`method not found for ${g}`),null;const v=this.rawDeviceStreamManager.createIRawStreamClient(S,g);return this.raiseTelemetryEvent("IRawStream_client_created",g),v}setRawMediaStream(g,f){if(!g)throw this.logger.error(`Could not set ${g} as to ${f}`),new Error("InvalidStream");this.customDeviceMediaStreamMap.set(f,g),this.onMediaStreamUpdateRequested(f),this.raiseTelemetryEvent("set_raw_outgoing_media_stream",f)}unsetRawMediaStream(g){this.customDeviceMediaStreamMap.get(g)?(this.customDeviceMediaStreamMap.delete(g),this.onMediaStreamUpdateRequested(g),this.raiseTelemetryEvent("unset_raw_outgoing_media_stream",g)):this.logger.safe.debug("no custom stream")}async setVideoEffects(g){return this.effectsManager.setEffectType("Video",g)}async sendMessageDeviceVideoEffectsAsync(g,f){return this.effectsManager.processingVideoEffectMessage(f)}async setAudioEffects(g){return this.effectsManager.setEffectType("Audio",g)}async getAudioStream(g,f,S=!1){const v=this.configProvider.config.devices.enumerateBeforeGettingStream;return v&&("always"!==v&&my.isPolling||await my.enumerateDevices()),this.getMediaStream({audio:!0,withTimeout:this.permissionManager.isPermissionKnown("microphone"),withEffect:!S&&this.effectsManager.isEffectEnabled("Audio"),audioProcessingFlags:this.getAudioProcessingFlags(),force:g,withOverridenStream:!S&&this.customDeviceMediaStreamMap.get("Audio")?.active&&this.customDeviceMediaStreamMap.get("Audio")},f)}async getVideoStream(g,f,S=!1,v){const C=this.configProvider.config.devices.enumerateBeforeGettingStream;return C&&("always"!==C&&my.isPolling||await my.enumerateDevices()),this.getMediaStream({video:!0,withTimeout:this.permissionManager.isPermissionKnown("camera"),withEffect:!S&&this.configProvider.config.enableVideoEffects&&this.effectsManager.isEffectEnabled("Video"),force:g,withOverridenStream:!S&&this.customDeviceMediaStreamMap.get("Video")?.active&&this.customDeviceMediaStreamMap.get("Video"),videoMaxFS:v},f)}getDisplayStream(g,f=!1){const S=!(!this.configProvider.config.enableAudioSharing||!this.audioSharingRequested);return this.getMediaStream({audio:S,sharing:!0,withTimeout:!1,withEffect:!1,audioProcessingFlags:S?0:void 0,force:!1,withOverridenStream:!f&&this.customDeviceMediaStreamMap.get("ScreenShare")?.active&&this.customDeviceMediaStreamMap.get("ScreenShare")},g)}async enumerateDevicesAsync(){return await this.isDeviceListAvailable.promise,this.getDeviceDescriptions(this.deviceList)}async getDeviceNameAsync(g){await this.isDeviceListAvailable.promise;const f=this.deviceList.find((f=>f.guid===g));return f?.label??""}async getSpeakerDeviceDomIdAsync(g){await this.isDeviceListAvailable.promise;const f=this.deviceList.find((f=>f.guid===g));return f?.deviceId??""}selectDevices(g){return this.pendingDevices?(this.logger.safe.info(`Overriding device selection until enumeration is complete with ${JSON.stringify(scrubSelectedDevices(this.pendingDevices))}`),void(this.pendingDevices=g)):this.isDeviceListAvailable.isPending?(this.logger.safe.info("Postponing device selection until enumeration is complete"),this.pendingDevices=g,void this.isDeviceListAvailable.promise.then((()=>{this.logger.safe.info("Performing postponed device selection");const g=this.pendingDevices;this.pendingDevices=null,this.selectDevices(g)}))):void this.deviceSelection.selectDevices(g)}getSelectedDevices(){return this.toSelectedDevices(this.deviceSelection.selectedDevices)}setAudioProcessingFlags(g){g!==this.audioProcessingFlags&&(this.logger.debug(`Setting audio processing flags: ${this.audioProcessingFlags} -> ${g}`),this.audioProcessingFlags=g,this.event("onStreamUpdateRequested").raise("Audio"))}getOutputDeviceId(){return this.selectedDevices.speaker?.deviceId}getDeviceDescriptions(g){return(g||this.deviceList).map((g=>g.toDeviceDesc()))}getDevicesCount(){return this.deviceList.reduce(((g,f)=>(g[f.type]++,g)),{camera:0,speaker:0,microphone:0,compositeAudio:0,virtualDevice:0,audioIngestDevice:0})}async getKnownPermissionStates(){return await this.permissionManager.initialize(),this.permissionManager.knownPermissionStates}getLocalVideoRenderers(){return this.activeRenderers}dispose(){this.deviceManagerSubscriptions?.forEach((g=>g.dispose())),this.deviceManagerSubscriptions=null,this.virtualDeviceSubs?.forEach((g=>g.forEach((g=>g.dispose())))),this.virtualDeviceSubs?.clear(),this.virtualDeviceSubs=null,this.virtualDeviceRecord?.forEach((g=>g.dispose())),this.virtualDeviceRecord=null,this.unsubscribeFromStreamManagerEvents(),this.deviceEnumerator.dispose(),this.mediaStreamManager.dispose(),this.activeVideoEffectSub?.dispose(),this.activeVideoStreamForEffect?.dispose(),this.disposeRawStreamAccess(),this.disposeClientAudioRenderer(),this.effectsManager.dispose(),super.dispose()}async registerVirtualDevice(g,f){const S=g.length?g.map((({id:g},f)=>{const S=this.createChildDeviceManager(this.logger.createChild(`VirtualDevice-${f}`));return S.selectDevices({camera:g}),S})):[this.createChildDeviceManager(this.logger.createChild("VirtualDevice"))],v=new Ey(S,f),C=v.id,_=[v.on("onVideoEffectApplied",((...g)=>this.event("onVideoEffectApplied").raise(...g))),v.on("onVideoEffectsEvent",((...g)=>this.event("onVideoEffectsEvent").raise(...g))),v.on("onDeviceTelemetryEvent",((...g)=>this.event("onDeviceTelemetryEvent").raise(...g))),v.on("onVideoEffectsTelemetryEvent",((...g)=>this.event("onVideoEffectsTelemetryEvent").raise(...g))),v.on("onDevicesPermissionChanged",((...g)=>this.event("onDevicesPermissionChanged").raise(...g))),v.on("onStreamUpdateRequested",((...g)=>this.event("onStreamUpdateRequested").raise(...g)))];return this.virtualDeviceSubs.set(C,_),this.virtualDeviceRecord.set(C,v),my.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.raiseTelemetryEvent("register_virtual_device",{deviceCount:S.length,id:C}),this.event("onVirtualDevicesChanged").raise(),C}async unregisterVirtualDevice(g){this.virtualDeviceRecord.has(g)?(this.virtualDeviceSubs.get(g).forEach((g=>g.dispose())),this.virtualDeviceSubs.delete(g),this.virtualDeviceRecord.get(g).dispose(),this.virtualDeviceRecord.delete(g),my.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.event("onVirtualDevicesChanged").raise(),this.raiseTelemetryEvent("unregister_virtual_device",{id:g})):this.logger.error(`No virtual device found with id ${g}`)}getRegisteredDevices(){return Array.from(this.virtualDeviceRecord.values())}async getNrgLevelPollerForDeviceTuner(){return await wy.init(this,this.logger)}getAudioProcessingFlags(){if(!this.effectsManager.shouldFallbackToNativeProcessing("Audio"))return this.audioProcessingFlags??this.configProvider.config.defaultAudioProcessingFlags}disposeClientAudioRenderer(){this.clientAudioRenderers.size&&(this.clientAudioRenderers.forEach((g=>{g.dispose()})),this.clientAudioRenderers.clear(),this.raiseTelemetryEvent("custom_audio_renderer_disposed",this.getSelectedDevices()))}disposeRawStreamAccess(){this.rawDeviceStreamManager.disposeAll(),this.rawDeviceStreamManager=null}toSelectedDevices(g){return Object.entries(g).reduce(((g,[f,S])=>(S&&(g[f]=S.guid),g)),{})}getStreamConstraints(g){const f={deviceId:g?.deviceId||void 0};return this.configProvider.config.audioSampleRate&&(f.sampleRate=this.configProvider.config.audioSampleRate),f}hasDeviceType(g){return values(this.deviceList).some((f=>f.type===g))}getConstraints(g){if(!g.audio&&!g.video&&!g.sharing)throw new Error("requesting nothing");if(this.logger.safe.info(`retrieving media stream: ${JSON.stringify(g)}`),g.sharing){let f;const S=this.selectedDevices.audioIngestDevice;return f=S&&g.deviceId?{deviceId:S.deviceId}:g.audio&&!g.deviceId?{deviceId:qt.SYSTEM_AUDIO_SOURCE_ID}:void 0,{audio:f,sharing:{deviceId:g.deviceId||qt.DISPLAY_SOURCE_ID},withTimeout:g.withTimeout,withEffect:!1,audioProcessingFlags:g.audioProcessingFlags,force:!1,withOverridenStream:g.withOverridenStream}}const f=this.selectedDevices.microphone,S=this.selectedDevices.camera,v=g.audio&&f,C=g.video&&S;if(!v&&!C)throw{type:qt.MEDIA_ERROR.noDeviceSelected,detail:`audio requested ${g.audio}, video requested: ${g.video} Devices: ${JSON.stringify(this.deviceList.map((g=>JSON.stringify(scrubDevices(g,this.configProvider.config.devices.piiSafeWords)))))}`};const _=this.getStreamConstraints(f),T=this.getStreamConstraints(S);let I=g.audioProcessingFlags;return void 0!==I&&g.audio&&!g.video&&f?.capabilities&&(f.capabilities.echoCancellation&&!f.capabilities.echoCancellation.includes(!!(2&I))&&(I^=2),f.capabilities.autoGainControl&&!f.capabilities.autoGainControl.includes(!!(1&I))&&(I^=1),f.capabilities.noiseSuppression&&!f.capabilities.noiseSuppression.includes(!!(4&I))&&(I^=4)),I!==g.audioProcessingFlags&&this.logger.safe.warn(`Unable to fulfill processing flags ${g.audioProcessingFlags}, using ${I} instead`),{audio:g.audio?_:void 0,video:g.video?T:void 0,withTimeout:g.withTimeout,withEffect:g.withEffect,audioProcessingFlags:I,force:g.force,withOverridenStream:g.withOverridenStream,videoMaxFS:g.videoMaxFS}}getMediaStream(g,f){const S=this.getConstraints(g),v=this.mediaStreamManager.getMediaStream(S,f);return this.subscribeOnStreamEvents(v),v.start().then((()=>{const f=v.hasAudio(),S=v.hasVideo();f&&this.signalDeviceGood("Audio",v.rawTrack.muted),S&&this.signalDeviceGood(v.mediaType,v.rawTrack.muted),this.permissionManager.update(g,g)})).catch((f=>this.handleUserMediaError(g,f))),v}signalDeviceGood(g,f){this.ufdManager.signalDeviceEvent(0,"Good",g,this.id),this.ufdManager.signalDeviceEvent(2,"Good",g,this.id),this.ufdManager.signalDeviceEvent(4,"Good",g,this.id),f||"Audio"!==g&&!this.configProvider.config.raiseVideoMuteUfd||this.ufdManager.signalDeviceEvent(3,"Good",g,this.id)}handleUserMediaError(g,f){const S=this.getMediaType(g),v=g.audio&&g.video,signalUFD=(g,f)=>{!v&&this.ufdManager.signalDeviceEvent(g,f,S,this.id)},logAudioError=g=>{!v&&"Audio"===S&&this.diagnostics.registerAudioRenderError(g)};switch(f.type){case qt.MEDIA_ERROR.permissionDeniedError:"ScreenShare"!==S&&(signalUFD(4,"Bad"),logAudioError(0x800000000000),this.configProvider.config.permissions.persistOnDeniedError&&this.refreshPermissions(g));break;case qt.MEDIA_ERROR.permissionDeniedBySystemError:signalUFD(4,"Bad"),logAudioError(0x800000000000);break;case qt.MEDIA_ERROR.sourceUnavailableError:signalUFD(0,"Bad"),logAudioError(512);break;case qt.MEDIA_ERROR.mediaStreamRequestTimedOut:signalUFD(2,"Bad"),logAudioError(35184372088832);break;default:this.logger.safe.error(`getMediaStream() error: ${stringifyObject2(f)}`),signalUFD(0,"Bad"),logAudioError(4194304)}}refreshPermissions(g){const f=g.audio&&!g.video,S=!g.audio&&g.video;f?this.permissionManager.update({audio:!0},{audio:!1}):S&&this.permissionManager.update({video:!0},{video:!1})}getMediaType(g){if(g.sharing)return"ScreenShare";if(g.video)return"Video";if(g.audio)return"Audio";throw new Error(`mediaType is not defined for this constraint ${JSON.stringify(g)}`)}subscribeOnStreamEvents(g){const f=[];f.push(g.on("onStreamClientStarted",((g,f)=>this.onStreamStarted(g,f)))),f.push(g.on("onStreamClientDisposing",(g=>this.onStreamDisposing(g)))),f.push(g.on("onStreamClientEnded",((g,f)=>this.onStreamEnded(g,f)))),f.push(g.on("onStreamClientMuted",((g,f)=>this.onStreamMuted(g,f)))),f.push(g.on("onStreamClientError",((g,f)=>this.onStreamError(g,f)))),this.configProvider.config.useRawMediaApiForVideoEffects&&f.push(g.on("onStreamClientDisposed",(g=>this.removeVideoEffectStream(g)))),this.streamSubscriptions.set(g,f)}async removeVideoEffectStream(g){if(g.getCurrentConstraints().withEffect){this.logger.safe.info(`this.activeVideoEffectSub: ${this.activeVideoEffectSub} to be disposed`),this.activeVideoEffectSub?.dispose();const g=await(this.activeVideoStreamForEffect?.getMediaStream());this.effectsManager.stopEffect("Video",g)}}unsubscribeFromStreamEvents(g){this.streamSubscriptions.has(g)&&(this.streamSubscriptions.get(g).forEach((g=>g.dispose())),this.streamSubscriptions.delete(g))}subscribeOnRendererEvents(g){const f=[];f.push(g.on("onRendererDisposed",(g=>this.onRendererDisposed(g)))),f.push(g.on("onRendererStarted",(g=>this.onRendererStarted(g)))),this.rendererSubscriptions.set(g,f)}unsubscribeFromRendererEvents(g){this.rendererSubscriptions.has(g)&&(this.rendererSubscriptions.get(g).forEach((g=>g.dispose())),this.rendererSubscriptions.delete(g))}subscribeOnStreamManagerEvents(){this.streamManagerSubscriptions=[],this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onAllStreamsRemoved",(()=>this.onAllStreamsRemoved()))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamAcquired",(g=>this.onStreamAcquired(g)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamCreated",((g,f)=>this.onStreamCreated(g,f)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamDisposing",((g,f)=>this.onMasterStreamDisposing(g,f))))}subscribeOnDeviceEnumeratorEvents(){this.deviceEnumerator.on("onDeviceEnumerationfailed",(g=>this.raiseTelemetryEvent("enumeration_failed",{error:g})))}unsubscribeFromStreamManagerEvents(){this.streamManagerSubscriptions.forEach((g=>g.dispose()))}async updateRenderersAsync(){try{await Promise.all(this.activeRenderers.map((g=>g.updateStreamAsync()))),this.logger.safe.info("Renderers updates finished")}catch(g){this.logger.safe.error(`Error updating renderers: ${stringifyObject2(g)}`)}}onSelectedDevicesChanged(g,f){const S=this.selectedDevices;if(this.selectedDevices=g,this.diagnostics.setSelectedDevices(g,f),!("camera"in S^"camera"in this.selectedDevices||"microphone"in S^"microphone"in this.selectedDevices)){const g=this.toSelectedDevices(this.selectedDevices),f=this.toSelectedDevices(S);this.event("onSelectedDevicesChanged").raise(g,f),g.microphone!==f.microphone&&this.rawDeviceStreamManager.notifyChange("Audio"),g.camera!==f.camera&&this.rawDeviceStreamManager.notifyChange("Video"),this.clientAudioRenderers.forEach((g=>{g.setOutputDevice(this.getOutputDeviceId())}))}const v=this.configProvider.config.devices.piiSafeWords;this.raiseTelemetryEvent("selected_devices_changed",{microphone:this.selectedDevices.microphone&&scrubDeviceLabelPii(this.selectedDevices.microphone.label,v),camera:this.selectedDevices.camera&&scrubDeviceLabelPii(this.selectedDevices.camera.label,v),speaker:this.selectedDevices.speaker&&scrubDeviceLabelPii(this.selectedDevices.speaker.label,v),fromInterface:f}),this.updateRenderersAsync()}onDevicesChanged(g,f){this.event("onDevicesChanged").raise(g,f),this.mediaStreamManager.onDevicesChanged(g),this.diagnostics.setDeviceList(g,f,this.getDeviceListDebugInfo());const S=this.getDevicesCount(),v=S.microphone>0,C=S.speaker>0;this.ufdManager.signalEvent("ZeroCaptureDevicesEnumerated",v?"Good":"Bad"),v||this.diagnostics.registerAudioCaptureError(1),this.isAudioOutputSelectionSupported&&(this.ufdManager.signalEvent("ZeroRenderDevicesEnumerated",C?"Good":"Bad"),C||this.diagnostics.registerAudioRenderError(1));const _=new Map;let T=1;this.raiseTelemetryEvent("devices_changed",{devices:g.map((g=>{const f=_.get(g.groupId)||T++;return _.set(g.groupId,f),{label:scrubDeviceLabelPii(g.label,this.configProvider.config.devices.piiSafeWords),isSystemDefault:g.isSystemDefault,kind:g.kind,type:g.type,capabilities:g.capabilities,groupId:`${f}`}})),debug:this.getDeviceListDebugInfo()})}getDeviceListDebugInfo(){return my.list.debugInfo}raiseTelemetryEvent(g,f){this.logger.safe.info(`Device event: ${g}: ${JSON.stringify(this.scrubPayload(g,f))}`);const S={eventType:g,timestamp:Date.now(),payload:f};this.diagnostics.registerDeviceTelemetryEvent(deepClone(S)),this.diagnostics.logAudioDeviceError(g,f),this.event("onDeviceTelemetryEvent").raise(S)}scrubPayload(g,f){return"devices_changed"===g?{devices:values(f.devices).map((g=>scrubDevices(g,this.configProvider.config.devices.piiSafeWords))),debug:f.debug}:f}async onStreamStarted(g,f){if(this.permissionManager.browserPermittedModalities.audio.some((g=>g===qt.MEDIA_STATE.send))||this.permissionManager.browserPermittedModalities.video.some((g=>g===qt.MEDIA_STATE.send)))try{await my.enumerateDevices()}catch(g){this.logger.safe.warn(`onStreamStarted device enumeration failed: ${stringifyObject2(g)}`)}if(g.rawTrack){switch(g.mediaType){case"Audio":this.deviceEnumerator.startDevicePolling(),this.updateActiveMicrophone(g,f);break;case"Video":this.deviceEnumerator.startDevicePolling()}this.configProvider.config.useRawMediaApiForVideoEffects&&g.getCurrentConstraints().withEffect&&(this.activeVideoEffectSub=this.effectsManager.on("onVideoStreamQualityChanged",((f,S,v)=>g.onVideoStreamQualityChanged(f,S,v))))}else this.logger.safe.warn(`stream:${g.id} is already disposed`)}updateActiveMicrophone(g,f){if(g.deviceId){const S=this.deviceList.find((f=>f.deviceId===g.deviceId));if(!S&&"default"!==g.deviceId)return void this.logger.safe.error("Active device not found",`Device id from track: '${scrubMriOrOmit(g.deviceId)}', known devices: [${this.deviceList.map((g=>JSON.stringify(scrubDevices(g,this.configProvider.config.devices.piiSafeWords))))}]}`,JSON.stringify(scrubConstraints(f)));S&&"default"!==g.deviceId&&f.audio&&f.audio.deviceId===qt.MEDIA_DEVICE.defaultId&&my.list.updateActiveMicrophone(S)}}onStreamDisposing(g){this.unsubscribeFromStreamEvents(g)}onStreamMuted(g,f){("Audio"===g.mediaType||this.configProvider.config.raiseVideoMuteUfd)&&this.ufdManager.signalDeviceEvent(3,f?"Bad":"Good",g.mediaType,this.id),"Audio"===g.mediaType&&this.event("onAudioStreamMuted").raise(f),this.raiseTelemetryEvent(f?"stream_muted":"stream_unmuted",g.mediaType)}onStreamEnded(g,f){f.error?(this.raiseTelemetryEvent("stream_ended_error",{mediaType:g.mediaType,error:{type:f.error.name,detail:f.error.message}}),"SourceUnavailableError"===f.error.name&&this.ufdManager.signalDeviceEvent(0,"Bad","Audio",this.id)):("Audio"!==g.mediaType&&"Video"!==g.mediaType||this.ufdManager.signalDeviceEvent(0,"Bad",g.mediaType,this.id),this.raiseTelemetryEvent("stream_ended",g.mediaType))}onStreamError(g,f){this.raiseTelemetryEvent("stream_error",{mediaType:g.mediaType,error:f})}onAllStreamsRemoved(){this.deviceEnumerator.stopDevicePolling(),this.audioSharingRequested=!1}onStreamAcquired({id:g,mediaType:f,timestamp:S,resolution:v,withAudio:C,source:_,sampleRate:T}){0!==S&&this.raiseTelemetryEvent("stream_acquired",{id:g,mediaType:f,timestamp:S,resolution:v,withAudio:C,source:_,sampleRate:T})}onStreamCreated(g,f){this.raiseTelemetryEvent("stream_created",{id:g,mediaType:f})}onMasterStreamDisposing(g,f){this.raiseTelemetryEvent("stream_disposed",{id:g,mediaType:f})}onRendererDisposed(g){remove2(this.activeRenderers,(f=>f===g)),this.domOverrides.onMediaElementRemoved?.(g.getVideoElement()),this.unsubscribeFromRendererEvents(g)}onRendererStarted(g){this.activeRenderers.push(g),this.event("onLocalRendererStarted").raise(g)}onVideoEffectsQualityEventHandler(g){const f=this.deviceSelection.selectedDevices.camera;if(f?.deviceId){const S={type:"onVideoEffectQualityChanged",payload:{message:g.message,effectType:g.effectType}};this.event("onVideoEffectsEvent").raise(f.deviceId,S)}}getDeviceType(g){if("Video"===g)return"camera";if("Audio"===g)return"microphone";throw new Error(`DeviceType for mediaType: ${g} doesn't exist`)}getStreamHandlerByType(g){return"Video"===g?()=>this.getVideoStream(!1,"rawStream",!0):"Audio"===g?()=>this.getAudioStream(!1,"rawStream",!0):"ScreenShare"===g?()=>Promise.resolve(this.getDisplayStream("rawStream",!0)):null}};function getPlatformConfig(){return et.isEngine("ChromiumAVD")?new ky:et.isEngine("Safari")?new Ly:et.isEngine("Firefox")?new Fy:isVdiPlatform()?new xy:et.isEngine("Chromium")?new Uy:new Dy}var Dy=class{getInitialSettings(){return{resizeModeForSharing:"none",enableAudioProcessingFallback:!0,allowVirtualDeviceInCall:!1,activeSpeaker:{timeToPromote:1e4},dtmf:{toneDuration:200,toneGap:100},mediaStreamHoldInterval:5e3,webrtcContributingSourcesPollingStartDelay:1e3,webrtcContributingSourcesPollingInterval:1e3,webrtcContributingSourcesPollingEmptySources:0,webrtcIceGatheringTimeoutMs:2e4,webrtcAllowedMediaContentType:qt.ALLOWED_CONTENT_TYPES.SDP_NGC,webrtcMediaContentType:qt.CONTENT_TYPE.SDP,useNGC1webrtcContentType:!1,webrtcScreensharingCapabilityMaxFS:8160,webrtcScreensharingCapabilityMaxFPS:1500,webrtcStatHwSilentDetectionDuration:5,webrtcStatHwSilentDetectionLevel:14,webrtcStatPollInterval:1e3,webrtcStatStoredRecordsNumber:60,webrtcStatNetworkDetectionDuration:10,webrtcHealedRatioWindowSize:5,webrtcHealedRatioExtendedWindowSize:20,webrtcStatNetworkDetectionHysteresis:.01,webrtcStatNetworkDetectionBadLevel:.17,webrtcStatNetworkDetectionGoodLevel:.15,webrtcMinAudioSamplesRecvForNetworkRecvQuality:48e4,webrtcVideoCapabilityCheckIntervalMin:2e4,webrtcVideoCapabilityCheckIntervalMinMultiparty:5e3,webrtcVideoCapabilityCheckIntervalMax:3e4,webrtcVideoCapabilityCheckIntervalMaxMultiparty:5500,webrtcScreensharingCapabilityCheckIntervalMin:0,webrtcScreensharingCapabilityCheckIntervalMax:0,webrtcVideoCapabilityMaxFS:3600,webrtcVideoCapabilityMaxFPS:3e3,webrtcMultiPartyRecvVideoMaxFS:3600,webrtcRecvVideoMaxFS:8160,webrtcCameraOpenFs:3600,minCameraOpenFps:15,maxCameraOpenFps:30,maxCameraFsViaCallConstraints:-1,webrtcMultipartyMaxScalingFs:3600,webrtcMaxScalingFs:8160,webrtcVideoScaling:!1,webrtcVideoScalingMultiparty:!0,enableOptimalVideoCount:!1,ovcBandwidthPerVideoReceiver:2e5,ovcSlidingWindowPercentile:.3,ovcSlidingWindowSamples:20,nonEstimatedDefaultVideoReceiversCount:4,ovcMaxCount:4,ovcMaxCountXL:4,ovcMaxCountMultiStream:16,ovcXLParticipantsCount:100,ovcIgnoreFirstSamples:10,ovcAvailableConcurrencyForBiggerGrid:4,ovcMemoryForBiggerGrid:2,ovcRampUpCooldown:15e3,ovcRampDownCooldown:1e4,webrtcStatNetworkDetectionEnabled:!0,webrtcUseNewStatsApi:!0,useAudioAnalyzer:!0,webrtcVideoSubscriptionDisposeTimeout:2e3,webrtcCompareContentTypeInOffer:!0,iceServerTransport:"udp,tcp,tls",iceHostCandidateOnly:!0,iceUdpAddressType:"ip",iceTcpAddressType:"ip",renegotiationAttempts:3,reconnectTimeLimit:9e4,initialReconnectTimeLimit:0,maxReconnectDelayTime:5,waitForRelayOnReconnect:!0,relayWaitSaneTimeoutMs:25e3,reconnectOnDisconnect:!1,reconnectWithNoRelays:!1,reconnectWithProbes:!1,reconnectWaitTimeAfterProbe:1e3,reconnectOnPcClose:!0,reconnectWakeupTimeLimit:18e4,webrtcSpeakingWhileMutedDetectionWindow:3,webrtcSpeakingWhileMutedBadDuration:3,webrtcSpeakingWhileMutedDetectionLevel:4e3,webrtcNegotiateDisabledDataModality:!1,recoverableMediaErrors:[qt.MEDIA_ERROR.iceConnectionError,qt.MEDIA_ERROR.noNetworkError,qt.MEDIA_ERROR.srtpError,qt.MEDIA_ERROR.incompatibleOffer,qt.MEDIA_ERROR.internalError].join(","),forceReconnectErrors:[qt.MEDIA_ERROR.audioPlaybackError].join(","),sendCallStartupTelemetry:!0,webrtcMultiPartyRecvVideoSignaling:!0,webrtcVideoDelayThreshold:10,webrtcEndOfCallFreezeThreshold:3,webrtcSubscriptionEventLimit:300,webrtcHandleRollback:!0,webrtcHandleRemoteRollback:!0,losingConnectivityTimeoutMs:-1,iceCandidateFilterMDns:!0,webrtcInjectTransportCCAudio:!1,webrtcInjectTransportCCAudioMultiparty:!0,webrtcRejectedFeatures:"byPass",webrtcRequiredFeatures:"nonByPass",webrtcSimulcastSessionEnabled:!1,webrtcSimulcastStreamsCountForVideo:1,webrtcSimulcastStreamsCountForSharing:1,webrtcFmtParamListSupported:!0,webrtcNegotiatedSsrcRangeForVideo:0,webrtcNegotiatedSsrcRangeForSharing:0,webrtcNegotiatedSsrcRangeForVideoOneToOne:0,webrtcNegotiatedSsrcRangeForSharingOneToOne:0,webrtcAllowRestoreKeyframe:!1,webrtcEnabledCustomBwEstimationForVideo:!1,webrtcDisabledSenderBitrate:1e3,maxStoredPreferredResolutionCount:4,maxStoredQualityLimitationReasonEvents:30,maxStoredUFDCount:50,simulcastTelemetryLayoutsPerSession:5,simulcastTelemetryNumModalitySessions:3,simulcastTelemetryNumFMTP:10,maxSendVideoCapabilities:{enableForVideo:!1,enableForSharing:!1,useMaximumWidthHeight:!1,sendMaxMbps:!1,sendMaxFs:!1},maxReportedOvershootingEvents:20,broadcastMode:{townHallScenarioNames:["premiumtownhall","basetownhall"]},performanceFallbackMaxFsFor1080pSend:3600,sendVideoCapabilityManager:{priorityOrder:["Performance","BroadcastMode","HardwareEncoder","Software1080P"],allowOptIn:["HardwareEncoder"]},video1080p:{software:{}},permissions:{usePositiveInAdp:!1,useNegativeInAdp:!1,adpFallback:!0,adpFallbackAudio:!0,adpFallbackVideo:!0,adpRequestAVLast:!0,rememberNegative:!1,persistOnDeniedError:!0,disableOnPermissionDeniedOnly:!0,enumerateDevicesAfterChange:!0},devices:{blacklist:{microphone:"stereo mix \\(",camera:"(^ir camera|avstream media device)",speaker:"stereo mix \\("},overrideDefault:!1,compositeLabelMatchingThreshold:.5,piiSafeWords:["airpod","bluetooth","hands-free","stereo","wireless","citrix hdx","remote audio","vmware","built-in","integrated","internal","teams","high definition","facetime","macbook","smartaudio","front","rear","back","iphone","ipad","display","displayport","dp","hdmi","amd","nvidia","intel","analog","digital","dock","line( in| out)?","s/pdif","external","thunderbolt\\d*","usb","panoramic","desktop","capture","cable","cam","virtual","manycam","snap camera","obs","vb-audio","vaio","effect","sink","source","default","test"],pollingIntervalActive:3e3,enumerateDevicesTimeout:25e3,enumerateDevicesAfterADP:!1,setSinkImmediately:!0,enumerateBeforeGettingStream:"always"},useGoogPrefixAudioConstraints:!0,multiviewResolutionLimits:{1:720,2:720,3:540,4:360,more:360},maxSpotlightResolution:1080,excludeUnsizedRenderersFromMultiviewResolutionLimits:!1,multiviewResolutionLimitUpdateThrottleDelay:300,useMultiviewLimitsOnInitialRequest:!0,useApplyChannelParametersForSourceRequests:!0,maxVideoFreezeTimestampsInBucket:5,webrtcSendBandwidthIgnoredUpdateLimit:6,webrtcSendBandwidthThreshold:.1,checkSupportForWebrtc_1_0:!1,webrtcLastAppliedVideoCapabilitiesCount:5,webrtcLastAppliedVideoCapabilitiesSequenceCount:5,gumRequestTimeout:2e4,overrideGumFromWebkit:!1,setMinFpsForWebkit:!1,videoCaptureFreezeTimeout:5e3,webrtcCloseAfterIceFailure:!0,audioBandwidthInKbps:90,maxBandwidthInKbps:7e3,maxBandwidthInKbpsFallback:7e3,videoBandwidthAllocation:.3,enableQosSupport:!1,forceUnbundledTransport:!1,allowedAudioCodecs:[],allowedVideoCodecs:[],allowedVideoCodecsMultiparty:[{clockRate:9e4,mimeType:"video/H264"},{clockRate:9e4,mimeType:"video/rtx"}],filterCodecsInSdp:!1,filterCodecsInSdpMultiparty:!0,filterCodecsInSdpV2:!1,reduceRtcpFbInSdp:[],reduceRtcpFbInSdpMultiparty:["goog-remb","transport-cc","ccm/fir","nack","nack/pli"],subscribeToSsrcForVideo:!1,audioRendererUsePauseOnDetach:!0,audioRendererRestartOnPause:!1,audioRendererRestartOnDeviceError:!0,disableAudioOutputSelection:!1,preferSdesSrtp:!1,preferSdesSrtpPstn:!1,useLocalStorageForOneDs:!0,oneDSDisabledPageUnloadEvents:[],oneDSLocalStorage:{sendStaleEvents:!1,accessThresholdInMs:6e5},oneDSNotificationManager:{blockNotificationsOnPageUnload:!1,blockEventsDiscardedNotifications:!1},useOneDsLogger:!1,addTelemetryReportingCallback:!0,eventsLimitInMem:200,eventLatency:Ep.Normal,eventLatencyRealTime:Ep.RealTime,enableCompoundKey:!1,telemetryTenants:{signaling:"53fdaa090eb946b5a1d6cbdeb4f2ef66-bcbf6380-2590-41cc-ae60-9e467cd51835-7413",gtcAudit:"53fdaa090eb946b5a1d6cbdeb4f2ef66-bcbf6380-2590-41cc-ae60-9e467cd51835-7413",media:"1cae5691997646c98b01d15beddae7a3-ce16e198-bc32-420f-ac64-42bb916111af-6865",realtimeMedia:"5aea257f81424f5d8574e57a50974ead-d3a768ce-590c-4595-ab85-3dd046114290-6701",tlePlayer:"2efdf03d07594586a5977c404e185186-71b046c4-f48f-4ba7-96d3-2a74b54e1d46-7326"},transmitProfileName:"REAL_TIME",transmitProfileTimings:[],waitReportStatsAtCallStop:!1,oneStreamPerDeviceType:!1,enableWebRtcInternalsLogs:!1,enableMultiViewStats:!0,webrtcBWJumpLowerLimit:1e5,webrtcBWJumpUpperLimit:3e5,uplinkBWStabilizationSlidingWindowSize:10,uplinkBWStabilizationMaxDeviation:.1,uplinkBWStabilizationMinBandwidth:1e5,downlinkBWStabilizationSlidingWindowSize:10,downlinkBWStabilizationMaxDeviation:.1,downlinkBWStabilizationMinBandwidth:1e5,maxKeyFrameTimestampsInBucket:5,enableAudioSharing:!1,audioSharingContextOptions:{sampleRate:48e3},enableStopSharingWithIncomingOffer:!0,enableDevtoolsAPI:!1,enableDataChannel:!1,enableDataChannelMultiparty:!0,enableDataChannelPstn:!1,alwaysNegotiateDataChannel:!0,webrtcDataChannel:{enableFragmentation:!1,fragmentationSize:0,enableSendScheduler:!1,rateLimiterCheckInterval:250,discardOnSendFailure:!1,bufferedAmountLowThreshold:65535,bufferedAmountHighThreshold:262144,maxBitrate:0,maxPacketRate:0,maxQueueSize:524288,dataIds:[]},acceptDisabledDataModality:!0,rejectUnbundledDataModality:!0,sctpPort:5e3,removeRtcpRsizeFromLocalSdp:!1,enableGiveControl:!1,maxStoredDataChannelValues:15,mediaControlPlaneConfig:{enableBweNotifications:!0,enableDominantSpeakerHistory:!0,enableSourceRequests:!0,enableSendBandwidthNotificationsEnabled:!1,sourceRequestsMessagesTimeout:1e4,storedSRRecordsCount:60,verboseTelemetry:!1,sendBeforeAck:!1,handshakeTimeout:1e4,setResendingMechanism:!1},localPreviewMirroringSupported:!1,enableVideoEffects:!0,waitForVideoEffectsBeforeApplyingConstraints:!1,useRawMediaApiForVideoEffects:!1,forceKeyFrameV2ScaleFactor:1.1,effectsTelemetryBufferSize:20,useDelayedScreenShareStream:!1,applyAudioEffectOnDemand:!1,wasmdns:{pTime:10,goodPerfThreshold:8,poorPerfThreshold:10,badPerfThreshold:12,perfWindowLength:10,enableNoiseSuppression:!1,noiseSuppressionMode:"Off",backgroundMode:!1},wasmvqe:{enableAec:!1,enableVqe:!1,backgroundMode:!1,performanceThresholdMs:8,performanceWindowDurationSecs:10,defaultVqeMode:cr.VqeMode.Off,callType:cr.CallType.Conference,audioUsageMode:cr.AudioUsageMode.Default,performanceProfile:cr.AecPerfProfile.Normal},webcv:{qualityConfig:{outputFps:{min:15,max:30},outputResolution:720,preserveResolution:!0,degradationLadder:[{resolution:{width:1920,height:1080},fps:{min:15,max:30}},{resolution:{width:1280,height:720},fps:{min:15,max:30}},{resolution:{width:960,height:540},fps:{min:15,max:30}},{resolution:{width:640,height:360},fps:{min:13,max:30}},{resolution:{width:416,height:234},fps:{min:10,max:20}},{resolution:{width:320,height:180},fps:{min:10,max:20}}],initialLadderResolution:720,improvementFpsThresholdPercent:20,statsIntervalSec:5,enableMaskPropagation:!1,maskPropagationFramesInterval:30},powerPreference:lr.PowerPreference.HighPerformance,useInsertableStreams:!1,webGLUnsupportedRenderers:["Google SwiftShader"],webGLRequiredExtensions:["EXT_color_buffer_float","WEBGL_debug_renderer_info","OES_texture_float_linear"],usePreheat:!1,useSharedArrayBuffer:!0,useWasmEffects:!1,processorType:lr.ProcessorType.Webgl2},insertFakeCandidateIfNeeded:!0,useSdpCapabilitiesLegacySession:!0,useSdpCapabilities:!0,enableH264SpsPpsIdrKeyframe:!0,disableMsSdp:!1,disableSdes:!1,disableIceReinvite:!1,iceDisconnectedTimeoutMs:3e4,enableLocalVideoConstraints:!0,webrtcAudioChannelSignalingFeedback:"app recv:dsh",webrtcVideoChannelSignalingFeedback:"app send:src recv:src,vc",webrtcResolutionManagerCooldownTimeout:15e3,webrtcResolutionManagerRetryDelay:5e3,webrtcNativeCpuOveruseDisabled:!1,webrtcDisplayStreamContentHint:"text",h264SendProfileOverride:"42C02A",learnCodecSendCapabilitiesFromSenderApi:!1,addFmtpToInitialSubscription:!0,h264SubscribeProfile:"64001f",notRenderingTimeInterval:{video:3,sharing:10},notRenderingLowBitrateThreshold:6,notRenderingLowFramerateThreshold:3,isBytesRecvUsedInIsRenderingCalculation:!0,useConnectionState:!0,transportStateFailedFix:!1,useDtlsTrasportConnectionCheck:!1,enableNetworkRecvQualityUFD:!0,enableNetworkSendQualityUFD:!0,enableSignalingAudioPermissionDeniedUFD:!1,webrtcJitterLowThreshold:.2,webrtcJitterHighThreshold:.35,webrtcJitterSticknessTime:5e3,webrtcLossRateLowThreshold:.2,webrtcLossRateHighThreshold:.3,webrtcLossRateSticknessTime:5e3,webrtcMinPacketsSentForNetworkSendQuality:200,webrtcLossRateWindowSize:3,webrtcJitterWindowSize:3,networkSendQualityDiagnostics:!1,networkRecvQualityDiagnostics:!1,webrtcJitterExtendedWindowSize:6,webrtcLossRateExtendedWindowSize:6,freezeMinDuration:128,freezeIntervalFrequency:1e3,disableNormalizationToCalculatePacketLossRate:!1,healedRatioPrecision:8,jitterPrecision:3,requestNewStreamOnUnmute:!0,raiseVideoMuteUfd:!1,useMediaQualityController:!1,useMediaQualityControllerForceKeyFrame:!1,bandwidthAllocatorV2:{sharingLadder:[8e4,5e5,8e5,1e6,12e5,25e5,3e6],videoLadders:[{maxFS:240,ladder:[4e4,7e4,1e5,15e4,25e4,3e5,35e4]}],defaultVideoMaxFS:240},layoutControlTimeout:1e4,extmapAllowMixed:!1,enableVla:!1,allowRemoteVla:!1,enableNonAdvVla:!1,specCompliantSimulcast:{},specCompliantSimulcastMultiparty:{video:{enableLocally:!1,allowEnableRemotely:!1,layerScaleFactors:[1],minFsForSimulcast:[920],useApplyConstraints:!1},sharing:{enableLocally:!1,allowEnableRemotely:!1,layerScaleFactors:[1]},allowOverride:!1,constraintsDisableVla:!0,collectResolutionInfo:!0,maxBrControlEnabled:!1,allowedBweOvershootRatio:1,allowResLimit:!1,disableTilde:!1},enforceOpusFmtpMultiparty:{usedtx:1},videoIsRenderingCheck:!1,fixSdpForPartialIceRestart:!1,mapSsrcToTrackForStats:!1,enableVideoOrientationExtension:!1,speakerGainLevel:0,ignoreClosedDtlsTransportState:!1,disconnectOnPageHide:!1,renderThroughCanvas:!1,isRenderingBasedOnRawStatistics:!1,enableDevicePixelRatio:!0,useSetParametersToApplyCapabilities:!1,useSetParametersToApplySSCapabilities:!1,enablePlatformCallConstraints:!1,enablePlatformCallConstraintsPerCall:!1,enableDynamicCallConstraints:!0,numCallConstraintsEvents:6,setParametersMaxBitrateUndefined:!1,onAddTrackRemoveOtherTracks:!0,avoidFakeStreamsDuringEscalation:!0,navConnectionPollingInterval:1e3,navConnectionNumSamplesToCollect:60,acceptProvisionalAnswer:!1,acceptProvisionalAnswerPstn:!0,acceptProvisionalAnswerFromPstnOnly:!0,createProvisionalAnswer:{enabled:!1,enabledPstn:!1,forceRecvonly:!1,streamsBeforeSetFullRD:!1,setProperAnswerType:!1,connectTransport:!0,audioState:"active",dtlsRole:"",dtlsRolePstn:""},webrtcPranswerCheckAudioEnergy:!1,webrtcPranswerMediaPollingTimeout:500,webrtcPranswerWaitFinalAnswer:!1,webrtcPranswerAudioThreshold:0,webrtcPranswerWaitIntervalBeforePolling:500,webrtcPranswerStopPollingAfterError:!1,disableIncomingDtlsRoleOverride:!1,disableOutgoingDtlsRoleOverride:!1,statsAllowAnyVideoSendTrack:!1,pictureInPicture:{enablePictureInPicture:!1,aspectRatioHorizontal:16,aspectRatioVertical:9,maxActiveStreams:1,minStreamGridCellWidth:160,dominantStreamChangeDebounce:3e3,statisticsBufferSize:20,multiStreamWorkerURL:""},showStatsInCall:!1,useSetStreamsForSender:!0,addPrefixForMsidInSdp:!1,enableMuteSpeakerUnmuteSpeakerWorkaround:!1,alwaysRaiseBadDeviceEvents:!1,removeRecvStreamOnEnded:!0,requiredVideoCodecs:["h264"],primaryVideoCodecs:["h264","vp8","vp9"],removeUnsupportedVideoModality:!1,enableActiveSpeakerBasedDSH:!0,enableInitialSignalingDSHSubscription:!0,enableSignalingDSHFallback:!1,emptyInitialDSH:!0,bwPercentiles:[5,50,95],enableTimerTracker:!0,diagnostics:{sideBySide:!0,useForTelemetry:!1,collectWhileNotConnected:!1,traceLogging:!1,collectionLimits:{numOfHistogramSamples:100,numDeviceEvents:200,numVideoEffectsEvents:100,numAudioEffectsEvents:100,numOvershootEvents:100,numIsRenderingEvents:100,numStatsReports:600,numStatsErrors:100,numSubscriptionEvents:100,numPerformanceEvents:50,numUFDs:100,numNativeSessions:3,numSessions:3,numNetworkEvents:50,numReconnects:50,numReconnectRecords:20,numCapabilitiesRequested:60,numCapabilitiesApplied:60,numAudioCaptureErrors:100,numAudioRenderErrors:100,numResolutionSwitches:10,numSamplesForE2E:4,numWorkerEvents:50,numTransportStateEvents:100,numElevation:5,numVideoStatsAfterSubscription:30,numVideoSubscriptionStats:30,numPowerEfficientEncoderEvents:60},telemetryLimits:{numOfHistogramSamples:50,numDeviceEvents:40,numVideoEffectsEvents:20,numAudioEffectsEvents:30,numWorkerEvents:25,numOvershootEvents:20,numIsRenderingEvents:4,numPreferredResolutions:3,numSubscriptionEvents:100,numPerformanceEvents:30,numUFDs:50,numAggregatedSamples:60,numStatsErrors:20,numCapabilitiesRequested:5,numCapabilitiesApplied:3,numNetworkEvents:20,numReconnects:10,numRendererStateChangedEvents:10,numAuthTokenErrors:20,numPowerEfficientEncoderEvents:20},teamsRealtimeTelemetry:{pollingInterval:15},performanceMonitoring:{usePerfConstrainedOvc:!1,useCpuSample:!1,useComputePressure:!1,fluctuationSamplesNum:5,enableRemoteVideoCalculator:!1,enableLowerResolution:!1,monitoringStrategy:"decodeTime",decodeThresholds:{1080:{fps:30,maxDecodeTime:20},720:{fps:30,maxDecodeTime:15},540:{fps:30,maxDecodeTime:11},360:{fps:30,maxDecodeTime:9},234:{fps:15,maxDecodeTime:10},180:{fps:15,maxDecodeTime:10}},defaultThrehold:{fps:30,maxDecodeTime:60},fpsDiffThresholds:{1080:{fps:30,fpsDiff:4},720:{fps:30,fpsDiff:4},540:{fps:30,fpsDiff:4},360:{fps:30,fpsDiff:4},234:{fps:15,fpsDiff:2},180:{fps:15,fpsDiff:2}},defaultFpsDiffThreshold:{fps:30,fpsDiff:10},volatilityThresholds:{1080:10,720:10,540:10,360:10,234:5,180:5},defaultVolatilityThreshold:10,remoteVideoTrackInterval:10,telemetryResolutionRequestSpanMs:5e3,cpuMetricCollector:3},features:{takeFreezeTelemetryFromGathererV2:!0,useLastSampleDeltaPerSecondConverter:!1,useNewerStatisticsMetrics:!1,useNewNetworkUFD:!1,useNewSendBandwidthCalculation:!0,useNewStatsForLocalVideoStreamWatcher:!0,useFallbackToNewExtensions:!0,logContributingSourcesError:!0,useTwoSampleVBSSFreezeDetection:!1,useNewSimulcastTelemetryExtension:!1}},requireUserActionForAudioSharing:!1,postponeAudioMixerForAudioSharing:!1,reassignMediaStreamAudioTrackAfterCreation:!1,deactiveAudioSender:!1,webrtcForceSdesForS1:!1,webrctRemoveVideoModalitiesForPstn:!1,removeSendersOnConfigureModalities:!0,negotiationParallelStreamAcquisitionCreateOffer:!1,negotiationParallelStreamAcquisitionCreateAnswer:!1,streamAvailabilityConsiderModalities:!0,setBWSeed:!0,bwSeedOptions:{mids:["*"],aggregation:"last",aggregateLastN:null,constValue:6e5,minValue:-1,cappingValue:15e5,useLocalStorage:!0,localStorageKey:"bwSeed"},stopCallOnAcceptFailure:!0,allowMediaBypass:!0,enablePermissionsWorkaround:!1,disposeSendersSync:!1,disposeStreamsSync:!1,maxVideoStatsAfterSubscription:30,ecsConfigTimeout:2e4,contributingSourcesLogInterval:1e4,useNewTokenApi:!1,audioRendererFailedReconnectTimes:0,audioRendererFailedRetryCodes:[3],effectsApplyConstraintsRetryMs:1e3,isSpotlightEnabled:!0,addAudioStreamBeforeConnection:!1,redReceiveEnabled:!1,mediaEventDictionary:qt.MEDIA_EVENT_FIELDS,smallCallTelemetry:{enable:!1,mediaUFDEventDictionary:{}},applySenderParamsBeforeStart:!0,applyMaxCapabilitiesToSenderParamsDirectly:!1,reuseLastSetParameters:!0,hevcCodecs:["hev1.1.6.L120.90","hev1.1.4.L93.B0","hev1.1.6.L93.B0"],useInactiveAudioTrack:!1,enableRollbackHandler:!1,callElevationDelayReconnect:!1,callElevationDelayReconnectPSTN:!1,enableCachingFMTP:!0,enableCachingFMTPAwait:!1,enableCachingFMTPDelay:0,setDisconnectAfterCleanUp:!1,sendResolutionTableOverride:qt.RES_TABLE.SEND,recvResolutionTableOverride:qt.RES_TABLE.RECV,maxSendVideoCapabilitiesMultiparty:{enableForVideo:!0,enableForSharing:!1,useMaximumWidthHeight:!0,sendMaxMbps:!1,sendMaxFs:!1},participantStreamInitialSubscriptions:!0,holdRetryActivationDelay:-1,holdSkipActivation:!0,recoverOnStreamUnmute:!1,isAv1Allowed:!1,audioSharingMemoryLeakFix:!0,h264SdpProfileMultiparty:"64001f",rejectIncompatibleOriginator:!0,coeffOfValidTimeDelayBetweenFramesArrival:2,invalidFPSAboveMax:40,useWakeLockApi:!0,noRequiredCodecsWorkaround:!1,vdiDisconnectedTracking:{enabled:!0,clientPhrases:["failure"]},multiStreamSupported:!1,nonMultiStreamChannels:9,useTokenMigrationHeader:!1,clientSupportsAadToken:!1,clientSupportsCaeToken:!1,clientSupportsSkypeToken:!0,supportMissingTokenTypesInResponse:!0,useSkypeTokenWhenNoAuthenticateHeader:!1,useKeyFrameApi:!1,enablePlayVideoOnStreamUnmuteWorkaround:!1,useDeviceHandleForLocalVideo:!0,enableCallStateChangesOnPageClose:!0,remoteUFD:{enabled:!1,maxParticipantNumber:20,debounceTime:1e3,list:{}},fixOpusComfortNoise:!1,streamModalitiesExcludeData:!0,muteDuringRemotePranswer:!0,syncMuteStateWithAudioDirection:!1,permissionDeniedUFDWorkaround:!1,audioSetSinkIdWorkaround:!1,identifyOneToOneCallWithoutParticipants:!1,emptyIceCandidateMarksGatheredAnswerer:!1,disableSendersTroughSetParametersVideo:!1,disableSendersTroughSetParametersAudio:!1,maxNumberOfPinnedVideos:1,localUFDDebounceTime:0,audioSampleRate:0,lowBatteryThreshold:10}}getEnforcedSettings(){return{}}},Ny=class extends Dy{getInitialSettings(){const g=super.getInitialSettings();return g.oneStreamPerDeviceType=!0,g.removeUnsupportedVideoModality=!0,g.webrtcPranswerWaitForMediaPollingInterval=100,g.diagnostics.features.useLastSampleDeltaPerSecondConverter=!0,et.isFormFactor("Mobile")&&(g.webrtcCameraOpenFs=920,g.webrtcVideoCapabilityMaxFS=920),g}},ky=class extends Dy{getEnforcedSettings(){return{useAudioAnalyzer:!1,enableAudioSharing:!1}}},Ly=class extends Ny{getEnforcedSettings(){const g={webrtcSimulcastSessionEnabled:!0,webrtcAllowRestoreKeyframe:!0,permissions:{usePositiveInAdp:!1,useNegativeInAdp:!1,adpFallback:!0,adpFallbackAudio:!0,adpFallbackVideo:!1,adpRequestAVLast:!1,rememberNegative:!1},devices:{pollingIntervalIdle:1e4},audioRendererRestartOnPause:!0,subscribeToSsrcForVideo:!0,noRequiredCodecsWorkaround:!0,degradationPreference:"maintain-framerate"};return et.isVersionGreaterOrEqual("15.0")||(g.statsAllowAnyVideoSendTrack=!0),et.isVersionGreaterOrEqual("16.0")&&et.isFormFactor("Mobile")&&(g.enablePermissionsWorkaround=!0),et.isVersionGreaterOrEqual("17.0")&&et.isFormFactor("Mobile")&&(g.recoverOnStreamUnmute=!0,g.enablePlayVideoOnStreamUnmuteWorkaround=!0),g}},Fy=class extends Ny{getEnforcedSettings(){return{webrtcSimulcastSessionEnabled:!0,webrtcAllowRestoreKeyframe:!0,useDtlsTrasportConnectionCheck:!0,videoIsRenderingCheck:!1,fixSdpForPartialIceRestart:!0,mapSsrcToTrackForStats:!0,ignoreClosedDtlsTransportState1on1:!0,subscribeToSsrcForVideo1on1:!0,devices:{enumerateDevicesTimeout:0,pollingIntervalIdle:1e4,idlePollingOnStart:!0},webrtcInjectTransportCCAudioMultiparty:!1,videoCaptureFreezeTimeout:0,filterCodecsInSdp:!0,useSetParametersToApplyCapabilities:!0,removeRecvStreamOnEnded:!0,webrtcDisabledSenderBitrate:0,disableAudioOutputSelection:!0,permissionDeniedUFDWorkaround:!0}}},xy=class extends Dy{getEnforcedSettings(){const g={checkSupportForWebrtc_1_0:!1,requireUserActionForAudioSharing:!0,webrtcSimulcastSessionEnabled:!0,webrtcAllowRestoreKeyframe:!0,useAudioAnalyzer:!1,enablePlatformCallConstraints:!0,specCompliantSimulcastMultiparty:{video:{layerScaleFactors:[1,2],enableLocally:!0,allowEnableRemotely:!0},maxBrControlEnabled:!0,allowResLimit:!0,allowOverride:!0,disableTilde:!1},extmapAllowMixedMultiparty:!0,enableVlaMultiparty:!0,allowRemoteVlaMultiparty:!0,enableNonAdvVlaMultiparty:!0,useMediaQualityControllerMultiparty:!0,useSdpCapabilities:!1,enableRollbackHandler:!0,allowedAudioCodecs:[{channels:2,clockRate:48e3,mimeType:"audio/opus"},{channels:1,clockRate:8e3,mimeType:"audio/G722"},{channels:1,clockRate:8e3,mimeType:"audio/PCMU"},{channels:1,clockRate:8e3,mimeType:"audio/PCMA"},{channels:1,clockRate:8e3,mimeType:"audio/CN"},{channels:1,clockRate:8e3,mimeType:"audio/telephone-event"}]};return"43"===getVdiPlatform()&&(g.postponeAudioMixerForAudioSharing=!0,g.enableAudioSharing=!0,g.filterCodecsInSdp=!0,g.webrtcPranswerWaitForMediaPollingInterval=250,g.specCompliantSimulcastMultiparty.video.useApplyConstraints=!1,g.localPreviewMirroringSupported=!0,g.webrtcContributingSourcesPollingStartDelay=3e3),"44"===getVdiPlatform()&&(g.postponeAudioMixerForAudioSharing=!0,g.enableAudioSharing=!0,g.disposeSendersSync=!0,g.disposeStreamsSync=!0,g.filterCodecsInSdp=!0,g.useInactiveAudioTrack=!0,g.specCompliantSimulcastMultiparty.video.useApplyConstraints=!0,g.specCompliantSimulcastMultiparty.video.minFsForSimulcast=[920],g.webrtcPranswerWaitForMediaPollingInterval=250,g.webrtcContributingSourcesPollingStartDelay=5e3),"45"===getVdiPlatform()&&(g.setParametersMaxBitrateUndefined=!0,g.specCompliantSimulcastMultiparty.video.useApplyConstraints=!0,g.specCompliantSimulcastMultiparty.video.minFsForSimulcast=[920]),g}},Uy=class extends Ny{getEnforcedSettings(){const g={};return et.isVersionGreaterOrEqual("74.0")&&(g.webrtcSimulcastSessionEnabled=!0,g.webrtcAllowRestoreKeyframe=!0,g.enableAudioSharing=!0),et.isVersionGreaterOrEqual("122.0")&&(g.useKeyFrameApi=!0),et.isFormFactor("RoomAudioProcessing")&&(g.defaultAudioProcessingFlags=0,g.wasmvqe={enableAec:!1,enableVqe:!1,backgroundMode:!1},g.wasmdns={enableNoiseSuppression:!1,backgroundMode:!1}),(et.isBrowser("CiscoOS")||et.isBrowser("ZoomRoom"))&&(g.waitReportStatsAtCallStop=!0,g.setDisconnectAfterCleanUp=!0),et.isFormFactor("Mobile")&&(g.enableAudioSharing=!1,g.audioRendererFailedReconnectTimes=3,g.devices={pollingIntervalIdle:1e4}),et.isBrowser("SamsungTV")&&(g.useSetParametersToApplyCapabilities=!0),et.isVersionGreaterOrEqual("98.0")&&et.isFormFactor("Desktop")&&(g.specCompliantSimulcastMultiparty={video:{layerScaleFactors:[1,2],enableLocally:!0,allowEnableRemotely:!0,useApplyConstraints:!0,minFsForSimulcast:[920]},maxBrControlEnabled:!0,allowResLimit:!0,disableTilde:!1},g.extmapAllowMixedMultiparty=!0,g.enableVlaMultiparty=!0,g.allowRemoteVlaMultiparty=!0,g.enableNonAdvVlaMultiparty=!0,g.useMediaQualityControllerMultiparty=!0),et.isVersionGreaterOrEqual("100.0")&&(g.redReceiveEnabledMultiparty=!0),g.webcv={useWasmEffects:!0,processorType:lr.ProcessorType.Wasm},g}},Vy=class{constructor(g){this.settings=g,this.isTransportUnbundled=!1,this.webrtcRejectedFeatures="",this.webrtcRequiredFeatures="",this.spatialAudioEnabled=!1,this._maxBandwidthInKbps=0,this._noiseSuppressionMode="Auto",this._enableMediaBypass=!1,this.audioContext={enabledLocally:!1,disabledRemotely:!1,enabledForSend:!1,initFailed:!1,initSendFailed:!1,codec:"None",lastUsedCodec:"None"}}setMediaConfiguration(g,f){this.maxBandwidthInKbps=Math.floor((g.maxBandwidthInBps||0)/1e3),this.isTransportUnbundled=this.settings.forceUnbundledTransport||this.settings.enableQosSupport&&(g.enableMediaQoS||!!g.mediaPortRanges),this._mediaPortRanges=g.mediaPortRanges,this.simulcastSessionEnabled=this.settings.webrtcSimulcastSessionEnabled&&canUseWebrtc1_0(this.settings.checkSupportForWebrtc_1_0),this._noiseSuppressionMode=g.noiseSuppressionMode||"Auto",this._enableMediaBypass=this.settings.allowMediaBypass&&g.enableMediaBypass,this.webrtcRejectedFeatures=this._enableMediaBypass?"":this.settings.webrtcRejectedFeatures,this.webrtcRequiredFeatures=this._enableMediaBypass?"":this.settings.webrtcRequiredFeatures,this.spatialAudioEnabled=f?f.spatialAudioEnabled:g.enableSpatialAudio}get mediaBypassEnabled(){return this._enableMediaBypass}get noiseSuppressionMode(){return this._noiseSuppressionMode}get maxBandwidthInKbps(){return this._maxBandwidthInKbps}set maxBandwidthInKbps(g){this._maxBandwidthInKbps=g,this.settings.maxBandwidthInKbps&&(this._maxBandwidthInKbps=Math.min(this.settings.maxBandwidthInKbps,this._maxBandwidthInKbps||Number.MAX_SAFE_INTEGER))}get audioPortRange(){if(this.isTransportUnbundled&&this._mediaPortRanges&&this._mediaPortRanges.audioMin&&this._mediaPortRanges.audioMax)return{min:this._mediaPortRanges.audioMin,max:this._mediaPortRanges.audioMax}}get videoPortRange(){if(this.isTransportUnbundled&&this._mediaPortRanges&&this._mediaPortRanges.videoMin&&this._mediaPortRanges.videoMax)return{min:this._mediaPortRanges.videoMin,max:this._mediaPortRanges.videoMax}}get audioCodecContext(){return this.settings.useInsertableStreams?.audioWasmCodec?.enable?this.audioContext:void 0}},By=class extends Ht{constructor(g,f,S={}){super(g),this.logger=g,this.platformCallConstraintsProvider=f,this.platformConfig=getPlatformConfig(),this.sessionCount=0,this._consoleOverrides={},this.uaConfig=new oa(this),this.mediaConfiguration={},this.configReceivedDefer=new dt,this.logger.info(`initializing configProvider ${this.constructor.name} from BrowserInfo: ${et.toString()}`),this.initialSettings=(0,No.mergeWith)({},(0,No.cloneDeep)(this.platformConfig.getInitialSettings()),(0,No.cloneDeep)(S),this.platformConfig.getEnforcedSettings(),arrayMergeCustomizer2),this.settings=this.initialSettings,this.settingsWithoutOverrides=this.initialSettings,this.stackSettings=(0,No.cloneDeep)(S),this.mediaSettings=new Vy(this.settings),this.platformCallConstraintsProvider.changed((()=>{this.updateSettings();const g=this.platformCallConstraintsProvider.constraints,f=this.logger.createChild("SettingsToCallConstraintsConverter"),S=convertSettingsToCallConstraints(f,this.settings,g);this.platformCallConstraintsProvider.addCallConstraintsTelemetryEvent(S,"applied")})),this.configReceivedTimeout=window.setTimeout((()=>{this.configReceivedTimeout=void 0,this.configReceivedDefer.resolve()}),this.settings.ecsConfigTimeout),this.logger.safe.info("Initialized")}getCallConstraints(){return this.platformCallConstraintsProvider.constraints}setCallConstraints(g){return this.platformCallConstraintsProvider.setConstraints(g),g}getCallConstraintsTelemetry(){return this.logger.error("Not supported globally, returning empty array"),[]}addCallConstraintsTelemetryEvent(g,f){this.logger.error("Not supported globally")}overrideMaxSessionBandwidth(g){return this.logger.error("Not supported globally"),!1}getIceTransportPolicy(){return this.logger.warn(`Not supported globally, returning default ${qt.ICE_TRANSPORT_POLICY.all}`),qt.ICE_TRANSPORT_POLICY.all}setIceTransportPolicy(g){this.logger.error("Not supported globally")}getConfigReceivedOrTimeout(){return this.configReceivedDefer.promise}getConfigView(g,f){const S=g?"Multiparty":"1on1",v=Object.entries((0,No.cloneDeep)(this.settings)).reduce(((g,[f,v])=>(g[f]=v,f.endsWith(S)&&(g[f.replace(S,"")]=v),g)),{}),C=new Vy(v);return C.setMediaConfiguration(this.mediaConfiguration,f?.mediaConfig),new ma(this.logger.createChild("ConfigProviderView"),v,C,this.userAgentConfig,this.countryCode,this.platformCallConstraintsProvider,f?.getCallConstraints())}updateConfig(g,f,S,v){this.etag=f||this.etag,this.configIds=S||this.configIds,this.country=v||this.country,this.event("newConfigReceived").raise(g,f,S),this.settingsWithoutOverrides=(0,No.mergeWith)({},this.settingsWithoutOverrides,g,arrayMergeCustomizer2),this.updateSettings(),this.configReceivedTimeout&&(window.clearTimeout(this.configReceivedTimeout),this.configReceivedTimeout=void 0),this.configReceivedDefer.resolve()}updateSessionCount(g){this.sessionCount=g,0===g&&this.pendingSettings&&(this.logSettings("Applying pending configuration",this.pendingSettings),this.updateSettings(this.pendingSettings),this.pendingSettings=null),g>0&&this.configReceivedTimeout&&this.configReceivedDefer.resolve()}get config(){return this.settings}get stackConfig(){return this.stackSettings}get consoleOverrides(){return this._consoleOverrides}get defaultConfig(){return this.initialSettings}get userAgentConfig(){return this.uaConfig}get countryCode(){return this.country}setMediaConfiguration(g){this.mediaConfiguration=g,this.mediaSettings.setMediaConfiguration(g)}get mediaConfig(){return this.mediaSettings}get ETag(){return this.etag}get ecsConfigIds(){return this.configIds}setConsoleOverrides(g){this._consoleOverrides=(0,No.mergeWith)({},this._consoleOverrides,g,arrayMergeCustomizer2),this.updateSettings()}setConsoleOverride(g,f){this._consoleOverrides[g]=f,this.updateSettings()}clearConsoleOverride(g){delete this._consoleOverrides[g],this.updateSettings()}clearAllConsoleOverrides(){this._consoleOverrides={},this.updateSettings()}updateSettings(g=this.settingsWithoutOverrides){if(this.sessionCount>0)return this.pendingSettings=g,void this.logSettings("pendingSettings updated",g);this.settings=this.mergeSettings(g),this.event("configUpdated").raise(),this.logSettings("Settings updated",this.settings)}logSettings(g,f){const S=Object.entries(f).reduce(((g,[f,S])=>(S!==this.initialSettings[f]&&(g[f]=S),g)),{});this.logger.safe.info(`${g}: ${JSON.stringify(S)}`)}mergeSettings(g){if(!g.enablePlatformCallConstraints&&!this._consoleOverrides.enablePlatformCallConstraints)return this.mergeSettingsWithConsoleOverrides(g);let f=g;const{setConsoleOverridesBeforeCallConstraints:S}=this._consoleOverrides;return S&&(f=this.mergeSettingsWithConsoleOverrides(f)),f=this.mergeSettingsWithPlatformConstraints(f),S||(f=this.mergeSettingsWithConsoleOverrides(f)),f}mergeSettingsWithConsoleOverrides(g){return this.logger.safe.info(`Merging settings with console overrides: ${stringifyObject2(this._consoleOverrides)}`),(0,No.mergeWith)({},g,this._consoleOverrides,arrayMergeCustomizer2)}mergeSettingsWithPlatformConstraints(g){const f=this.platformCallConstraintsProvider.getSettings(g);return this.logger.safe.info(`Merging settings with platform call constraints: ${stringifyObject2(f)}`),(0,No.assign)({},g,f,arrayMergeCustomizer2)}},Hy=class{constructor(){this.data={clientDSH:void 0,signalingDSH:void 0,serverDSH:void 0,activeStrategy:void 0,lastMsgOrigin:void 0,changedCountContributingSources:0,changedCountDSH:0}}contributingSourcesChanged(){this.data.changedCountContributingSources++}setCurrentActiveStrategy(g){this.data.activeStrategy=g}resetState(){return this.data.lastMsgOrigin=void 0,this}recordHistoryEvent(g,f){var S,v;this.data.changedCountDSH++,(S=this.data)[v=f+"DSH"]??(S[v]={count:0,duplicateCount:0}),this.data.lastMsgOrigin=f;const C=this.data[f+"DSH"];C.count++,C.firstMsgTime??(C.firstMsgTime=Date.now()),deepEqual(this.data.lastHistory,g)&&C.duplicateCount++,this.data.lastHistory=g,this.data.lastMsgDate=Date.now()}getObjectRef(){return this.data}},$y=class{constructor(g,f,S,v,C,_,T,I){this.mediaStream=g,this.receiver=f,this.modality=S,this.sourceStreamId=v,this.controller=C,this.videoCapabilities=_,this.getMaxAllowedVideoFS=T,this.substreamIndex=I,this.msi=-1,this.operations=Promise.resolve()}dispose(){this.receiver=null,this.mediaStream=null}getId(){return this.mediaStream.id}getModality(){return this.modality}getMsi(){return this.msi}getMediaStream(){return this.mediaStream}getReceiver(){return this.receiver}getSourceStreamId(){return this.sourceStreamId}getSubstreamIndex(){return this.substreamIndex}requestSource(g){this.msi=g;const f=this.operations.then((()=>{let f;return this.videoCapabilities&&(this.videoCapabilities.resetToInitial(),this.getMaxAllowedVideoFS&&this.videoCapabilities.setMaxFS(Math.min(this.getMaxAllowedVideoFS(),this.videoCapabilities.getMaxFS())),f=this.videoCapabilities.buildFmtp(),this.videoCapabilities.resetToInitial()),this.controller.requestSource(this.mediaStream.id,g,f)}));return this.operations=f.catch((()=>{})),f}},jy=class{constructor(g){this.subscription=g}get subscribedStream(){return this.subscription.stream?.getMediaStream()}get msi(){return this.checkDisposed(),this.subscription.msi}get modality(){return this.checkDisposed(),this.subscription.modality}get localMsi(){return this.checkDisposed(),this.subscription.localMsi}setOnMediaStreamChangedHandler(g){this.checkDisposed(),this.mediaStreamChanged=g,this.subscription.isStreamReady&&this.notifyMediaStreamChanged()}setOnErrorHandler(g){this.checkDisposed(),this.error=g}dispose(){this.subscription&&(this.subscription.dispose(generateCauseId(),this),this.subscription=null)}unsubscribe(){this.subscription&&(this.subscription.unsubscribe(),this.subscription=null)}notifyMediaStreamChanged(){if(this.mediaStreamChanged){const g=this.subscription.stream,f=this.subscription.isStreamReady;this.mediaStreamChanged(g&&f?g.getMediaStream():null)}}notifyError(g){this.error&&this.error(g)}checkDisposed(){if(!this.subscription)throw new Error("subscription disposed")}},Gy=class extends Ht{constructor(g,f,S){super(),this.modality=g,this.msi=f,this.disposeDelay=S,this.clients=[],this.streamReady=!1}createClient(){const g=new jy(this);return this.clients.push(g),g}get isStreamReady(){return this.streamReady}get localMsi(){return this.subStream?.getSourceStreamId()}get isInactive(){return!this.clients.length}get stream(){return this.subStream}set stream(g){try{if(g===this.subStream)return;this.subStream&&(this.unsubscribe(!1),this.notifyStreamChanged()),this.subStream=g,g&&(this.streamReady=!1,g.requestSource(this.msi).then((()=>{this.streamReady=!0,this.notifyStreamChanged()})).catch((g=>{this.notifyError(g)})))}catch(g){this.event("onFailed").raise(this,g)}}notifyError(g){this.clients.forEach((f=>{f.notifyError(g)})),this.event("onFailed").raise(this,g)}dispose(g,f){f?(remove2(this.clients,(g=>g===f)),this.isInactive&&(this.disposeTimeout=window.setTimeout((()=>{this.disposeTimeout=null,this.unsubscribeIfInactive()}),this.disposeDelay))):(this.clients=[],this.unsubscribe())}unsubscribeIfInactive(){this.isInactive&&(this.disposeTimeout&&clearTimeout(this.disposeTimeout),this.unsubscribe())}unsubscribe(g=!0){this.subStream&&(this.subStream.requestSource(-1).catch((()=>{})),this.streamReady=!1,this.subStream=null),g&&this.event("onDisposed").raise(this)}notifyStreamChanged(){this.clients.forEach((g=>g.notifyMediaStreamChanged())),this.event("onStreamChanged").raise()}},qy=class extends Ht{constructor(g,f,S,v){super(g),this.configProvider=f,this.diagnostics=v,this.videoSubscriptions=[],this.isMcpSrAvailable=!1,this.subscriptionEvents=new Map,this.setLogger(g),this.diagnostics??(this.diagnostics=new Wy(this.configProvider,(()=>{}))),this.setStreamProvider(S),this.logger.safe.info("created")}getSubscriptionsCount(){return this.videoSubscriptions.filter((g=>g.isStreamReady)).length}setStreamProvider(g){this.streamProvider=g,this.streamProvider.setOnStreamsChangedHandler((()=>this.streamsChanged()))}setLogger(g){this.logger=g}subscribeVideo(g,f=-2){let S=this.videoSubscriptions.find((S=>S.msi===f&&S.modality===g)),v=this.getAvailableStream(g);if(S)!S.stream&&v?this.assignStream(S,v):this.logger.safe.info(`subscription #${f} for modality ${g} already exists, stream assigned: ${!!S.stream}`);else{const C=Date.now();this.disposeInactiveSubscriptionIfNeeded(g),v=this.getAvailableStream(g);const _=v?.getSourceStreamId();this.logger.safe.info(`creating new subscription #${f} for modality ${g}`),this.event("onSubscriptionChanged").raise(1,g,f,_,null),this.diagnostics.addSubscribe(g,f,_),S=new Gy(g,f,this.configProvider.config.webrtcVideoSubscriptionDisposeTimeout);const T=[];T.push(S.on("onDisposed",(g=>this.onSubscriptionDisposed(g)))),T.push(S.on("onStreamChanged",(()=>{const v=S.stream?.getId(),_=S.localMsi;if(this.updateTrackIds(),S.isStreamReady){const S=Date.now();this.event("onSubscriptionChanged").raise(2,g,f,_,S-C,v),this.diagnostics.addSubscribed(g,f,_,S-C)}}))),T.push(S.on("onFailed",((g,f)=>this.onSubscriptionFailed(g,f)))),this.subscriptionEvents.set(S,T),this.videoSubscriptions.push(S),v?this.assignStream(S,v):this.logger.safe.info(`waiting for available stream for subscription #${f}`)}return S.createClient()}dispose(){const g=generateCauseId();this.videoSubscriptions.concat().forEach((f=>f.dispose(g))),this.streamProvider.setOnStreamsChangedHandler(null),super.dispose(),this.logger.safe.info("disposed")}reriseSubscribeEvents(){this.logger.safe.info(`rerising subscription events: ${this.videoSubscriptions.length}`);const g=[];this.videoSubscriptions.forEach((f=>{const S=f.modality,v=f.msi,C=f.localMsi;this.event("onSubscriptionChanged").raise(1,S,v,C),this.diagnostics.addSubscribe(S,v,C),g.push(...this.getSubscriptionVideoTrackIds(f))})),this.diagnostics.subscribedTrackIds=g}setDiagnostics(g){this.diagnostics=g??new Wy(this.configProvider,(g=>{this.logger.safe.warn(`Unhandled stats error from inactive subscription manager: ${g}`)}))}streamChangedByMsi(g){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`);const f=this.videoSubscriptions.find((f=>f.msi===g));f?this.assignSubscriptionToStream(f):this.logger.safe.error(`Subscription for msi ${g} not found`)}mcpSourceRequestsAvailable(){this.isMcpSrAvailable=!0}streamsChanged(){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`),this.videoSubscriptions.forEach((g=>{this.assignSubscriptionToStream(g)}))}assignSubscriptionToStream(g){const f=!g.stream||this.isStreamRemoved(g.stream);if(this.logger.safe.info(`Subscription for ${g.modality} #${g.msi} needs new stream: ${f}`),!f)return;const S=this.getAvailableStream(g.modality);S?this.assignStream(g,S):this.resignStream(g)}getAvailableStream(g){let f=this.streamProvider.getStreams();return"video"===g&&!this.isMcpSrAvailable&&this.configProvider.config.multiStreamSupported&&(f=f.filter((g=>void 0===g.getSubstreamIndex()))),f.find((f=>g===f.getModality()&&-1===f.getMsi()))}isStreamRemoved(g){return!this.streamProvider.getStreams().some((f=>f===g))}assignStream(g,f){this.logger.safe.info(`assigning stream #${f.getId()} to subscription #${g.msi}`),g.stream=f}resignStream(g){if(g.stream)this.logger.safe.info(`removing stream from subscription #${g.msi}`),g.stream=null;else{const f=this.streamProvider.getStreams().filter((f=>g.modality===f.getModality()&&-1!==f.getMsi())).length;this.logger.safe.warn(`no stream available for ${g.modality} #${g.msi}, ${g.modality} used stream count: ${f}`)}}disposeInactiveSubscriptionIfNeeded(g){this.getAvailableStream(g)||this.videoSubscriptions.find((f=>f.modality===g&&f.isInactive))?.unsubscribeIfInactive()}onSubscriptionDisposed(g){const f=generateCauseId(),S=g.modality,v=g.msi,C=g.localMsi;this.event("onSubscriptionChanged").raise(3,S,v,C),this.diagnostics.addUnsubscribe(S,v,C),this.logger.safe.info(`disposing subscription for ${S} #${v}`),remove2(this.videoSubscriptions,(f=>f===g)),this.streamsChanged(),this.updateTrackIds(),this.subscriptionEvents.has(g)&&(this.subscriptionEvents.get(g).forEach((g=>g.dispose(f))),this.subscriptionEvents.delete(g))}updateTrackIds(){const g=[],f=[];this.videoSubscriptions.forEach((S=>{if(!S.isStreamReady)return;const v=S.stream?.getId().split("-")[1];f.push(v),g.push(...this.getSubscriptionVideoTrackIds(S))})),this.event("onTrackIdsChanged").raise(g),this.diagnostics.subscribedTrackIds=g,this.configProvider.config.subscribeToSsrcForVideo&&this.event("onTrackSsrcChanged").raise(f)}getSubscriptionVideoTrackIds(g){return g?.stream?.getMediaStream()?.getVideoTracks().map((g=>g.id))??[]}onSubscriptionFailed(g,f){this.event("onSubscriptionFailed").raise(-1,g.modality,g.msi,g.localMsi,f),this.diagnostics.addFailed(g.modality,g.msi,g.localMsi,stringifyObject2(f))}},Wy=class{constructor(g,f){this.configProvider=g,this.addStatsError=f,this.data={video:{events:[],counters:{attempted:0,subscribed:0,unsubscribed:0,failed:0}},sharing:{events:[],counters:{attempted:0,subscribed:0,unsubscribed:0,failed:0}},subscribedTrackIds:[]}}set subscribedTrackIds(g){this.data.subscribedTrackIds=g}addSubscribe(g,f,S){const v=this.getModalityData(g);if(v){const g={evt:1,msi:f,localMsi:S,ts:Date.now()};arrayLimitedPush22(v.events,g,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),v.counters.attempted++}}addSubscribed(g,f,S,v){const C=this.getModalityData(g);if(C){const g={evt:2,msi:f,localMsi:S,ts:Date.now(),duration:v};arrayLimitedPush22(C.events,g,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),C.counters.subscribed++}}addUnsubscribe(g,f,S){const v=this.getModalityData(g);if(v){const g={evt:3,msi:f,localMsi:S,ts:Date.now()};arrayLimitedPush22(v.events,g,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),v.counters.unsubscribed++}}addFailed(g,f,S,v){const C=this.getModalityData(g);if(C){const g={evt:-1,msi:f,localMsi:S,ts:Date.now(),error:v};arrayLimitedPush22(C.events,g,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),C.counters.failed++}}getObjectRef(){return this.data}getModalityData(g){switch(g){case qt.MEDIA_TYPE.video:return this.data.video;case qt.MEDIA_TYPE.sharing:return this.data.sharing;default:return void this.addStatsError(`Unsupported modality ${g}`)}}},zy=class{constructor(g,f){this.configProvider=g,this.addStatsError=f,this.data={videoMaxCapabilitiesEvents:[],videoMaxCapabilitiesErrors:[],sharingMaxCapabilitiesEvents:[],sharingMaxCapabilitiesErrors:[],currentVideoSsrcRequestedCapabilities:{},currentVideoSsrcAppliedCapabilities:{},currentSharingSsrcRequestedCapabilities:{},currentSharingSsrcAppliedCapabilities:{},numVideoControlMessages:0,numOutOfOrderVideoControlMessages:0,numWebcamFreezeIntervals:0,numProcessedStreamFreezeIntervals:0}}onMaxCapabilitiesRequested(g){const f={causeId:g.causeId,events:[{eventType:"req",timestamp:Date.now(),capabilities:g.capabilities,isSimulcast:g.isSimulcastEnabled}]};try{if(g.modality===qt.MODALITY.video){arrayLimitedPush22(this.data.videoMaxCapabilitiesEvents,f,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested),this.data.currentVideoSsrcRequestedCapabilities={};for(const f of g.capabilities)this.data.currentVideoSsrcRequestedCapabilities[`${f.ssrc??0}`]=f}else if(g.modality===qt.MODALITY.sharing){arrayLimitedPush22(this.data.sharingMaxCapabilitiesEvents,f,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested),this.data.currentSharingSsrcRequestedCapabilities={};for(const f of g.capabilities)this.data.currentSharingSsrcRequestedCapabilities[`${f.ssrc??0}`]=f}}catch(g){this.addStatsError?.("onMaxCapabilitiesRequested",stringifyObject2(g))}}onMaxCapabilitiesApplied(g){try{const f=this.getEventForCause(g.modality,g.causeId),S={eventType:"app",timestamp:Date.now(),capabilities:g.capabilities,error:`${g.error}`||"none"};if(f&&(arrayLimitedPush22(f.events,S,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1),g.error&&(g.modality===qt.MODALITY.video?arrayLimitedPush22(this.data.videoMaxCapabilitiesErrors,f,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1):g.modality===qt.MODALITY.sharing&&arrayLimitedPush22(this.data.sharingMaxCapabilitiesErrors,f,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1))),g.modality===qt.MODALITY.video){this.data.currentVideoSsrcAppliedCapabilities={};for(const f of g.capabilities)this.data.currentVideoSsrcAppliedCapabilities[`${f.ssrc??0}`]=f}else if(g.modality===qt.MODALITY.sharing){this.data.currentSharingSsrcAppliedCapabilities={};for(const f of g.capabilities)this.data.currentSharingSsrcAppliedCapabilities[`${f.ssrc??0}`]=f}}catch(g){this.addStatsError?.("onMaxCapabilitiesApplied",stringifyObject2(g))}}addVideoControlMessage(g=!1){this.data.numVideoControlMessages++,g&&this.data.numOutOfOrderVideoControlMessages++}getObjectRef(){return this.data}registerWebcamFreeze(){this.data.numWebcamFreezeIntervals++}registerProcessedStreamFreeze(){this.data.numProcessedStreamFreezeIntervals++}getEventForCause(g,f){return(g===qt.MODALITY.video?this.data.videoMaxCapabilitiesEvents:this.data.sharingMaxCapabilitiesEvents).find((g=>g.causeId===f))}},Ky=class{constructor(g){this.configProvider=g,this.data={renderers:[],firstTimeToFirstFrameVideo:-1,firstTimeToFirstFrameSharing:-1,timeToFirstFrameSinceSubscriptionStartVideo:-1,timeToFirstFrameSinceSubscriptionStartSharing:-1,isRenderingEvents:{video:[],sharing:[]},preferredResolution:{video:void 0,sharing:void 0}}}setTimeToFirstFrame(g,f){-1!==g&&(f===qt.MODALITY.video&&-1===this.data.firstTimeToFirstFrameVideo?this.data.firstTimeToFirstFrameVideo=g:f===qt.MODALITY.sharing&&-1===this.data.firstTimeToFirstFrameSharing&&(this.data.firstTimeToFirstFrameSharing=g))}setTimeToFirstFrameSinceSubscriptionStart(g,f){-1!==g&&(f===qt.MODALITY.video&&-1===this.data.timeToFirstFrameSinceSubscriptionStartVideo?this.data.timeToFirstFrameSinceSubscriptionStartVideo=g:f===qt.MODALITY.sharing&&-1===this.data.timeToFirstFrameSinceSubscriptionStartSharing&&(this.data.timeToFirstFrameSinceSubscriptionStartSharing=g))}setIsRendering(g,f){this.data.isRenderingEvents[f]&&arrayLimitedPush22(this.data.isRenderingEvents[f],{isRendering:g,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents)}setPreferredResolution(g,f){(g.width||g.height)&&(this.data.preferredResolution[f]=g)}newRendererDiagnostics(){const g=new Jy(this,this.configProvider),f=g.on("onDisposed",(()=>{this.removeDeadRenderers(),f.dispose()}));return this.data.renderers.push(g.getObjectRef()),g}getObjectRef(){return this.data}removeDeadRenderers(){this.data.renderers=this.data.renderers.filter((g=>g.alive))}},Jy=class extends Ht{constructor(g,f){super(),this.managerDiagnostics=g,this.configProvider=f,this.isAlive=!0,this.data={alive:!0,totalFreezeDuration:0,isRendering:!1,timeToFirstFrame:-1,timeToFirstFrameSinceSubscriptionStart:-1,rendererStates:[]},delete this.data.alive,Object.defineProperty(this.data,"alive",{get:()=>this.isAlive,enumerable:!1,configurable:!1})}set trackId(g){this.data.trackId=g}set rendererSize(g){this.data.rendererSize=g,g.toString=()=>`${g.width}x${g.height}`,this.managerDiagnostics.setPreferredResolution(g,this.data.modality)}set msi(g){this.data.msi=g}set modality(g){this.data.modality=g}set isRendering(g){this.data.isRendering=g,this.managerDiagnostics.setIsRendering(g,this.data.modality)}set timeToFirstFrame(g){this.data.timeToFirstFrame=g,this.managerDiagnostics.setTimeToFirstFrame(g,this.data.modality)}set timeToFirstFrameSinceSubscriptionStart(g){this.data.timeToFirstFrameSinceSubscriptionStart=g,this.managerDiagnostics.setTimeToFirstFrameSinceSubscriptionStart(g,this.data.modality)}addFreezeDuration(g){this.data.totalFreezeDuration+=g}addStateChange(g){arrayLimitedPush22(this.data.rendererStates,g,this.configProvider.config.diagnostics.telemetryLimits.numRendererStateChangedEvents)}dispose(){this.isAlive=!1,this.event("onDisposed").raise()}getObjectRef(){return this.data}},Yy=M,Qy=__toESM2(we()),Xy=M;function fmtParamsToString(g){let f="";return forOwn(g,((g,S)=>{f+=(f?";":"")+S,void 0!==g&&(f+=`=${g}`)})),f}var Zy=class{constructor(g){this.parameters={},g&&g.split(";").forEach((g=>{const f=g.split("=");this.parameters[f[0]]=f[1]}))}setIfMissing(g,f){this.contains(g)||(this.parameters[g]=f)}removeIfPresent(g){this.contains(g)&&delete this.parameters[g]}get(g){return this.parameters[g]}names(){return Object.keys(this.parameters)}contains(g){return this.parameters.hasOwnProperty(g)}toString(){return fmtParamsToString(this.parameters)}};function updatePayload(g,f,S){if(!g.rtp)return;const v=g.rtp.filter((g=>g.payload===f))[0];v&&forOneCodec(g,{codec:v.codec,rate:v.rate,payload:v.payload,encoding:v.encoding},(g=>(g.rtp.payload=S,g)))}function findAvailablePayload(g){const f=new Set;for(const S of g.media)for(const g of S.rtp??[])f.add(g.payload);const S=[96,127];for(let g=S[0];g<=S[1];g++)if(!f.has(g))return g;const v=[35,64];for(let g=v[0];g<=v[1];g++)if(!f.has(g))return g;return-1}function findAllAvailablePayloads(g,f){const S=new Set,v=[];for(const f of g.media)for(const g of f.rtp??[])S.add(g.payload);for(let g=f[0];g<=f[1];g++)S.has(g)||v.push(g);return v}function forOneCodec(g,f,S,v){forCodec(g,f,!0,v,S)}function forAllCodecs(g,f,S,v){forCodec(g,f,!1,v,S)}function forCodec(g,f,S,v=!0,C){if(g.rtp){for(let _=0;_<g.rtp.length;_++){const T=g.rtp[_],I=T.payload;if(f.codec.toLowerCase()!==T.codec.toLowerCase()||f.rate!==T.rate||f.encoding!==T.encoding||f.payload&&f.payload!==T.payload)continue;const b={rtp:T};g.fmtp||(g.fmtp=[]);const A=g.fmtp.find((g=>T.payload===g.payload));b.fmtp=A,g.rtcpFb||(g.rtcpFb=[]),b.rtcpFb=g.rtcpFb.filter((g=>g.payload===T.payload));const P=b.rtcpFb.length>0;if(null===C(b))g.payloads=g.payloads.toString().split(" ").filter((g=>T.payload!==+g)).join(" "),g.fmtp=g.fmtp.filter((g=>T.payload!==g.payload)),g.rtcpFb=g.rtcpFb.filter((g=>T.payload!==g.payload)),g.rtp[_]=null;else{if(b.rtp.payload!==I){const f=b.rtp.payload;g.payloads=g.payloads.toString().split(" ").map((g=>+g===I?f:+g)).join(" "),b.fmtp&&(b.fmtp.payload=f),b.rtcpFb&&b.rtcpFb.forEach((g=>g.payload=f)),v&&g.fmtp.filter((g=>g.config&&g.config.indexOf(`apt=${I}`)>-1)).forEach((g=>g.config=g.config.replace(`apt=${I}`,`apt=${f}`)))}!A&&b.fmtp&&g.fmtp.push(b.fmtp),!P&&b.rtcpFb&&b.rtcpFb.forEach((f=>g.rtcpFb.push(f)))}if(S)break}g.rtp=g.rtp.filter((g=>!!g))}}function removeCodec(g,f){if(!g.rtp)return;let S=-1;if(g.rtp.forEach((function(g,v){f.codec.toLowerCase()!==g.codec.toLowerCase()||f.rate!==g.rate||f.encoding!==g.encoding||f.payload&&f.payload!==g.payload||(S=v)})),S>=0&&g.rtp.length>1){const f=g.rtp[S].payload;g.rtp.splice(S,1),g.payloads=g.payloads.split(" ").filter((g=>f!==+g)).join(" "),g.fmtp=g.fmtp?.filter((g=>f!==g.payload))}}function addCodec(g,f){g.rtp.unshift({payload:f.payload,codec:f.codec,rate:f.rate,encoding:f.encoding}),g.payloads=`${f.payload} ${g.payloads}`}function isCodecsMatch2(g,f,S){if(!(0,Xy.isUndefined)(g.rate)&&g.rate!==f.rate)return!1;if(!(0,Xy.isUndefined)(g.codec)&&g.codec.toLowerCase()!==f.codec.toLowerCase())return!1;if(!(0,Xy.isUndefined)(g.encoding)){if(!(0,Xy.isUndefined)(f.encoding)&&g.encoding!==f.encoding)return!1;if((0,Xy.isUndefined)(f.encoding)&&1!==g.encoding)return!1}if(!(0,Xy.isUndefined)(g.fmtpLine)){const v=S?.find((S=>S.payload===f.payload&&-1!==S.config.toLowerCase().indexOf(g.fmtpLine.toLowerCase())));return!!v}return!0}function isPayloadMatch(g,f){return f===g||"*"===f}function filterCodecs(g,f,S,v){if(!g.rtp?.length)return;let C=g.rtp.filter((S=>f.some((f=>isCodecsMatch2(f,S,g.fmtp)))));g.type===qt.MEDIA_TYPE.video&&(C=C.filter((f=>{const S=g.fmtp?.find((g=>g.payload===f.payload&&g.config.startsWith("apt=")));if(S){const g=+S.config.split(";")[0].split("=")[1];return C.some((f=>f.payload===g))}return!0}))),C.length?(g.rtp=C,S&&(g.rtp=(0,Xy.flatten)(f.map((f=>g.rtp.filter((S=>isCodecsMatch2(f,S,g.fmtp))))))),g.payloads=g.rtp.map((g=>g.payload)).join(" "),g.fmtp=g.fmtp?.filter((f=>g.rtp.some((g=>isPayloadMatch(g.payload,f.payload))))),g.rtcpFb=g.rtcpFb?.filter((f=>g.rtp.some((g=>isPayloadMatch(g.payload,f.payload)))))):v&&v.warn("Empty rtp list after filtering")}function getModalityForMedia(g){if(g.label)switch(g.label){case qt.MEDIA_LABEL.audio:return"Audio";case qt.MEDIA_LABEL.video:return"Video";case qt.MEDIA_LABEL.sharing:return"ScreenShare";case qt.MEDIA_LABEL.data:return"Data"}else switch(g.type){case qt.MEDIA_TYPE.audio:return"Audio";case qt.MEDIA_TYPE.video:return"Video";case qt.MEDIA_TYPE.data:case qt.MEDIA_TYPE.dataChannel:return"Data"}return null}function getModality(g){if(g.label)switch(g.label){case qt.MEDIA_LABEL.audio:return qt.MODALITY.audio;case qt.MEDIA_LABEL.video:return qt.MODALITY.video;case qt.MEDIA_LABEL.sharing:return qt.MODALITY.sharing;case qt.MEDIA_LABEL.data:return qt.MODALITY.data}else switch(g.type){case qt.MEDIA_TYPE.audio:return qt.MODALITY.audio;case qt.MEDIA_TYPE.video:return qt.MODALITY.video;case qt.MEDIA_TYPE.data:case qt.MEDIA_TYPE.dataChannel:return qt.MODALITY.data}return null}function getLabelForModality(g){switch(g){case qt.MODALITY.audio:return qt.MEDIA_LABEL.audio;case qt.MODALITY.video:return qt.MEDIA_LABEL.video;case qt.MODALITY.sharing:return qt.MEDIA_LABEL.sharing;case qt.MODALITY.data:return qt.MEDIA_LABEL.data;default:return null}}function getModalities(g){return g.media.reduce(((g,f)=>{if(0!==f.port){const S=getModality(f);if(!(S in g)){const v=f.direction?f.direction.toLowerCase():qt.MEDIA_STATE.sendReceive;g[S]=v}}return g}),{})}function getTypeFromModality(g){switch(g){case qt.MODALITY.audio:return qt.MEDIA_TYPE.audio;case qt.MODALITY.video:case qt.MODALITY.sharing:return qt.MEDIA_TYPE.video;case qt.MODALITY.data:return qt.MEDIA_TYPE.data;default:return null}}function getBundle(g){const f=g.groups?.find((g=>"BUNDLE"===g.type));if(f){const S=f.mids?.toString().split(" ")[0];return g.media.find((g=>{const f="number"==typeof g.mid?g.mid.toString():g.mid;return S===f}))||null}return null}function isMediaDisabled(g){return 0===g.port}function getRecvCapabilitiesForMedia(g){let f;return g&&forOneCodec(g,{codec:"h264",rate:9e4},(g=>{g.fmtp?.config&&(f=parseVideoCapabilitiesFromFmtpConfig(g.fmtp.config))})),f}function getNextAvailableMid(g){const f=g.media.map((g=>parseFloat(g.mid||"0")));for(let g=1;g<=Math.max(...f)+1;g++)if(!f.includes(g))return g.toString();return"-1"}function parseVideoCapabilitiesFromFmtpConfig(g){const f=new Zy(g);return{maxFs:+f.get(qt.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+f.get(qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+f.get(qt.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+f.get(qt.VIDEO_CAPABILITIES.MAX_BR_PATH)}}function getMultiStreamCountFromSdp(g){const f=/a=x-multi-stream:(\d+)/,S=g.match(f);if(S)return parseInt(S[1])}var eE=M;function CandidateTransform(){const g=[{jsep:"active",msSdp:"tcp-act"},{jsep:"passive",msSdp:"tcp-pass"},{jsep:"so",msSdp:"tcp-so"}];function transformBundle(g,f){if(g.port&&!g.candidates.length){const S=getBundle(f);S&&(g.port=S.port,g.connection=S.connection)}}function transformCandidate(g,f){delete g.generation,delete g["network-id"],delete g["network-cost"],g.transport.match(/tcp/i)&&transformTcpCandidate(g,f)}function transformTcpCandidate(f,S){g.some((function(g){if(S){if(g.msSdp===f.transport.toLowerCase())return f.transport="tcp",f.tcptype=g.jsep,!0}else if(f.tcptype&&g.jsep===f.tcptype.toLowerCase())return f.transport=g.msSdp,delete f.tcptype,!0;return!1}))}function isDefault(g,f,S){const v=f.connection||S.connection,isSame=function(g,f,S){return g.port===S&&g.ip===f};return!!v&&(1===g.component?isSame(g,v.ip,f.port):!!f.rtcp&&isSame(g,f.rtcp.ip||v.ip,f.rtcp.port))}this.fromMsSdp=function(g){g.candidates=g.candidates||[],g.xCandidatesIpv6&&(g.xCandidatesIpv6.forEach((function(f){g.candidates.push(f)})),delete g.xCandidatesIpv6),g.candidates.forEach((function(g){transformCandidate(g,!0)}))},this.toMsSdp=function(g,f){g.candidates=g.candidates||[],g.candidates.sort((function(S,v){return S.foundation!==v.foundation?S.foundation-v.foundation:S.component!==v.component?S.component-v.component:+isDefault(v,g,f)-+isDefault(S,g,f)})),g.candidates=g.candidates.filter((function(f,S){transformCandidate(f,!1);const v=g.candidates[S-1];return!v||v.component!==f.component||v.foundation!==f.foundation})),transformBundle(g,f)}}var tE={build:()=>new CandidateTransform},iE=class{toMsSdp(g,f){"offer"===f?g.rtcp&&(g.rtcp={port:g.port}):delete g.rtcp}},nE={build:()=>new iE},rE={STREAM_ID:{audio:"mainAudio",video:"mainVideo",sharing:"applicationsharingVideo"},STREAM_ID_DELIMITER:"-"},sE=[{label:qt.MEDIA_LABEL.audio,id:rE.STREAM_ID.audio},{label:qt.MEDIA_LABEL.video,id:rE.STREAM_ID.video},{label:qt.MEDIA_LABEL.sharing,id:rE.STREAM_ID.sharing}].reduce(((g,f)=>(g[f.label]=f.id,g)),{}),aE=uniqueId(),oE=class{constructor(g){this.configuration=g}fromMsSdp(g){if(0===g.port)return;const f="-";if(!this.isRecvOnly(g)||this.configuration.unifiedPlanEnabled){if(g.msid){g.ssrcs&&1===g.ssrcs.length&&(this.addStream(g,g.ssrcs[0].id,g.ssrcs[0].value,g.msid),g.ssrcs.shift());const S=g.msid.split(" ");(this.configuration.addPrefixForMsid||S[0]===f)&&(g.msid=this.getMsidValue(S[0],S[1]||S[0],g.label))}if(g.ssrcs)this.updateMsids(g.ssrcs,((S,v)=>this.configuration.addPrefixForMsid||S===f?this.getMsidValue(S,v,g.label):`${S} ${v}`));else{const f=this.getFlowSsrcs(g);f.length>0?f.forEach((S=>{this.addStream(g,S,aE,this.getMsidValue(f[0],f[0],g.label))})):g.xSsrcRange&&this.addStream(g,g.xSsrcRange.ssrcMin,aE,this.getMsidValue(g.xSsrcRange.ssrcMin,g.xSsrcRange.ssrcMin,g.label))}}delete g.xSsrcRange}toMsSdp(g,f){if(0===g.port)return;let S;g.ssrcs?.[0]&&(S=g.ssrcs[0].id),void 0!==S&&(g.xMultiStream||(g.xSsrcRange={ssrcMin:S,ssrcMax:S+f}))}getFlowSsrcs(g){if(g.ssrcGroups&&g.type===qt.MEDIA_TYPE.video){let f;if(g.ssrcGroups.some((g=>"FID"===g.semantics&&(f=g,!0))),f)return f.ssrcs.split(" ").map((g=>+g))}return[]}addStream(g,f,S,v){g.ssrcs=g.ssrcs||[],g.ssrcs.push({attribute:"cname",id:f,value:S}),g.ssrcs.push({attribute:"msid",id:f,value:v})}updateMsids(g,f){g.filter((g=>"msid"===g.attribute)).forEach((g=>{const S=g.value.split(" ");g.value=f(S[0],S[1]||S[0])}))}getMsidValue(g,f,S){const v=this.getMsidPrefix(S);return v+g+" "+v+f}getMsidPrefix(g){return sE[g]?sE[g]+rE.STREAM_ID_DELIMITER:""}isRecvOnly(g){return"recvonly"===g.direction}},lE={audio:"main-audio",video:"main-video"},cE=class{constructor(g,f){this.context=g,this.mediaManager=f,this.logger=this.context.logger,this.candidateTransform=tE.build(),this.streamTransform=new oE(this.context.configuration),this.rtcpTransform=nE.build()}toMsSdp(g,f){return g.msidSemantic={semantic:"WMS",token:"*"},g.media.forEach(((S,v)=>{if(S.protocol=qt.PROFILES.rtpSavp,S.label=S.label||this.getLabel(S.type),isMediaDisabled(S)){for(const g in S)S.hasOwnProperty(g)&&["type","port","protocol","payloads"].indexOf(g)<0&&delete S[g];S.payloads="34"}const C=this.getSsrcRangeForIndex(S.direction,v);this.streamTransform.toMsSdp(S,C),S.crypto&&S.crypto.forEach((function(g){g.config+="|2^31"})),0!==S.port&&g.fingerprint&&(S.fingerprint=g.fingerprint),this.candidateTransform.toMsSdp(S,g),this.rtcpTransform.toMsSdp(S,f),S.invalid&&(this.logger.unsafe.error(`Unknown SDP attributes! ${JSON.stringify(S.invalid)}`),delete S.invalid),this.transformExtensions(S,!1),0!==S.port&&(S.type===qt.MEDIA_TYPE.audio&&this.context.configProvider.config.webrtcAudioChannelSignalingFeedback?S.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcAudioChannelSignalingFeedback}:S.type===qt.MEDIA_TYPE.video&&this.context.configProvider.config.webrtcVideoChannelSignalingFeedback&&(S.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcVideoChannelSignalingFeedback}))})),delete g.fingerprint,g}fromMsSdp(g,f){for(let S=g.media.length-1;S>=0;--S){const v=g.media[S];if((v.ssrcs?.[0]||v.xSsrcRange)&&(g.msidSemantic={semantic:"WMS",token:"*"}),isMediaDisabled(v))v.direction||(v.direction="inactive");else{if(this.streamTransform.fromMsSdp(v),delete v.cryptoscale,v.fingerprint&&(!this.isOffer(f)||this.context.configProvider.config.disableIncomingDtlsRoleOverride&&v.setup||(v.setup="actpass")),v.crypto)for(let g=v.crypto.length-1;g>=0;--g){const f=v.crypto[g];f.config.match(/.*\|\d+:\d+/)?v.crypto.splice(g,1):f.config=f.config.replace(/(.*)\|2\^\d+/,"$1")}v.remoteCandidates&&(delete v.candidates,delete v.xCandidatesIpv6,delete v.remoteCandidates),this.candidateTransform.fromMsSdp(v),v.rtcpFbXMessage&&delete v.rtcpFbXMessage,v.invalid&&this.logger.unsafe.info(`Unknown SDP attributes! ${JSON.stringify(v.invalid)}`),this.transformExtensions(v,!0)}}return g}transformExtensions(g,f){const S=[{name:qt.ABS_SEND_TIME.EXT_URI,encoded:qt.ABS_SEND_TIME.MSSDP_ENCODED_URI},{name:qt.TRANSPORT_CC.EXT_URI,encoded:qt.TRANSPORT_CC.MSSDP_ENCODED_URI}];g.ext&&g.ext.forEach((function(g){S.some((function(S){const v=f?S.encoded:S.name,C=f?S.name:S.encoded;return v===g.uri&&(g.uri=C,!0)}))}))}isOffer(g){return"offer"===g}getLabel(g){return lE.hasOwnProperty(g)&&lE[g]||"undefined"}getSsrcRangeForIndex(g,f){const S=this.mediaManager.getMediaEntities()[f],v=S?.getSimulcastContext();return hasSendDirectionality(g)&&v?v.getSsrcRange():0}},dE=4294967040,hE=class{constructor(){this.ssrc=Math.floor(Math.random()*(dE-1))+1}nextAudioStreamSsrc(){return this.nextSsrc(0)}nextVideoStreamSsrc(){return this.nextSsrc(99)}nextSsrc(g){let f=this.ssrc;do{f=this.ssrc,this.ssrc=(this.ssrc+g+1)%dE,0===this.ssrc&&(this.ssrc=1)}while(f+g>dE);return{min:f,max:f+g}}},uE=M,gE=class{constructor(g,f,S){this.mediaEntity=g,this.logger=f,this.configProvider=S,this.activeRids=[],this.isLocalDescSet=!1,this.enabledLocally=!1,this.enabledRemotely=!1;const v=modalityToMediaType(this.mediaEntity.getModality());this.config=getSimulcastConfigForMediaType(v,this.configProvider),this.config?this.logger.safe.debug(`Adding simulcast info to ${g.getModality()} with mid: ${g.getMid()}, config: ${JSON.stringify(this.config)}`):this.logger.safe.debug(`Simulcast is disabled for ${g.getModality()}`)}get ridList(){return this.config?(0,uE.times)(this.config.layerScaleFactors.length,(g=>g+1)):[]}localDescriptionIsApplied(){this.isLocalDescSet=!0}enableInLocalDesc(){this.enabledLocally=!0}shouldBeEnabledInLocalDesc(){return!!this.config&&(this.config.enableLocally||this.enabledRemotely)}enableInRemoteDesc(){this.enabledRemotely=!0}shouldBeEnabledInRemoteDesc(){return!!this.config&&(this.enabledLocally||this.config.allowEnableRemotely&&this.isMidRidHeaderExtPresented()&&!this.isLocalDescSet)}shouldUseSimulcast(){return this.shouldBeEnabledInLocalDesc()}getSsrcRange(){return this.shouldUseSimulcast()?99:0}isMidRidHeaderExtPresented(){const g=this.mediaEntity.getRtpHeaderExtensions();return g?.some((g=>"mid"===g.headerType||"rid"===g.headerType||"rrid"===g.headerType))}};function getSimulcastConfigForMediaType(g,f){return"Video"===g?f.config.specCompliantSimulcast?.video:"ScreenShare"===g?f.config.specCompliantSimulcast?.sharing:null}var pE=M,mE=[2812,4218,8437,16875,33750,67500,108e3,135e3,198e3,244800,27e4,352500,52e4],fE=class{constructor(g,f,S,v){this.initialMaxFS=g,this.initialMaxFPS=f,this.isAv1Allowed=S,this.h264SubscribeProfile=v,this.maxFS=g,this.maxFPS=f}setMaxFS(g,f){return!(this.maxFS===g||(this.maxFS=g,!f)||(f(this),0))}getMaxFS(){return this.maxFS}getMaxFPS(){return this.maxFPS}getMaxMBPS(){return this.calculateMbps(this.maxFS,this.maxFPS)}calculateMbps(g,f){return getClosestValue(mE,g*f/100,!0)}resetToInitial(){this.maxFS=this.initialMaxFS,this.maxFPS=this.initialMaxFPS}fmtpParams(){return{"max-fs":this.getMaxFS(),"max-mbps":this.getMaxMBPS(),"max-fps":this.getMaxFPS()}}buildFmtp(){const g=[];let f=this.fmtpParams();return this.h264SubscribeProfile&&(f["profile-level-id"]=this.h264SubscribeProfile),g.push(f),this.isAv1Allowed&&(f=this.fmtpParams(),f.codec="AV1",g.push(f)),g}},SE=class _MediaEntity{constructor(g,f){this.entity=g,this.configProvider=f,this.supportedSendProfiles={}}toString(){return`MediaEntity: ${this.entity.modality} \nmid: ${this.entity.mid} localRecvCaps: ${JSON.stringify(this.localRecvCapabilities?.buildFmtp())}  remoteRecvCaps: ${JSON.stringify(this.remoteRecvCapabilities)}  localSsrc: ${this.getLocalSsrc()} remoteSsrc: ${this.getRemoteSsrc()} localTrackId: ${this.getLocalTrackId()} remoteStreamId: ${this.getRemoteStreamId()} remoteTrackId: ${this.getRemoteTrackId()} xSourceStreamId: ${this.getXSourceStreamId()} subStreamIndex: ${this.getSubstreamIndex()} extensions: ${JSON.stringify(this.entity.extensions)} rtpExt: ${JSON.stringify(this.entity.rtpExt)}         `}static getVideoCababilities(g,f,S){if(g!==qt.MEDIA_TYPE.video)return null;let v,C;f===qt.MODALITY.sharing?(v=S.config.webrtcScreensharingCapabilityMaxFS,C=S.config.webrtcScreensharingCapabilityMaxFPS):(v=S.config.webrtcVideoCapabilityMaxFS,C=S.config.webrtcVideoCapabilityMaxFPS,S.config.useMultiviewLimitsOnInitialRequest&&S.config.multiviewResolutionLimits[1]&&(v=ei.Send.getMaxFsForHeight(S.config.multiviewResolutionLimits[1])));const _=S.config.isAv1Allowed&&f===qt.MODALITY.sharing;return new fE(v,C,_,S.config.h264SubscribeProfile)}static create(g,f,S){const v=getTypeFromModality(f),C=new _MediaEntity({modality:f,mid:S,mtype:v,extensions:{}},g);return C.localRecvCapabilities=_MediaEntity.getVideoCababilities(v,f,g),C}clone(){const g=new _MediaEntity((0,pE.cloneDeep)(this.entity),this.configProvider);return g.setSimulcastContext(this.simulcastContext),g.localRecvCapabilities=this.localRecvCapabilities,g.remoteRecvCapabilities=this.remoteRecvCapabilities,g.supportedSendProfiles=this.supportedSendProfiles,g}getModality(){return this.entity.modality}getType(){return this.entity.mtype}getMid(){return this.entity.mid}disable(){this.entity.mid=null}update(g,f){this.entity.modality!==g&&(this.localRecvCapabilities=_MediaEntity.getVideoCababilities(this.entity.mtype,g,this.configProvider)),this.entity.modality=g,this.entity.mid=f,this.isEnabled()&&this.setExtension("rollback",!1)}isDisabled(){return!this.entity.mid}isEnabled(){return!!this.entity.mid}getLocalRecvCapabilities(){return this.localRecvCapabilities}getRemoteRecvCapabilities(){return{sourceId:this.getXSourceStreamId(),capabilities:this.remoteRecvCapabilities?[this.remoteRecvCapabilities]:[]}}setRemoteRecvCapabilities(g){this.remoteRecvCapabilities=g}getRemoteStreamId(){return this.entity.remoteStreamId}setRemoteStreamId(g){this.entity.remoteStreamId=g}setRemoteSsrc(g){this.entity.remoteSsrc=g}getRemoteSsrc(){return this.entity.remoteSsrc}setLocalSsrc(g){this.entity.localSsrc=g}getLocalSsrc(){return this.entity.localSsrc}getRemoteTrackId(){return this.entity.remoteTrackId}setRemoteTrackId(g){this.entity.remoteTrackId=g}getXSourceStreamId(){return this.entity.xSourceStreamId}setXSourceStreamId(g){this.entity.xSourceStreamId=g}setLocalTrackId(g){this.entity.localTrackId=g}getLocalTrackId(){return this.entity.localTrackId}setSubStreamIndex(g){this.entity.subStreamIndex=g}getSubstreamIndex(){return this.entity.subStreamIndex}getExtension(g){return this.entity.extensions[g]}setExtension(g,f){this.entity.extensions[g]=f}getRtpHeaderExtensions(){return this.entity.rtpExt}setRtpHeaderExtensions(g){this.entity.rtpExt=g}setSimulcastContext(g){this.simulcastContext=g}getSimulcastContext(){return this.simulcastContext}addSupportedSendProfile(g,f){void 0===this.supportedSendProfiles[g]&&(this.supportedSendProfiles[g]=new Set),this.supportedSendProfiles[g].add(f)}isSendProfileSupported(g,f){const S=this.supportedSendProfiles[g];if(void 0!==S){const g=f.slice(0,2);for(const f of S)if(f.startsWith(g))return!0}return!1}serialize(){return deepClone(this.entity)}},vE={toffset:"toffset","abs-send-time":"abs-send-time","video-orientation":"video-orientation","draft-holmer-rmcat-transport-wide-cc-extensions-01":"transport-cc","video-content-type":"video-content-type","video-timing":"video-timing","color-space":"color-space","video-layers-allocation00":"vla","video-layers-allocation00-non-advertised":"non-adv-vla",mid:"mid","rtp-stream-id":"rid","repaired-rtp-stream-id":"rrid","fast_bandwidth_feedback#version_3":"fast_bandwidth_feedback#version_3","frame-counters-gvc":"frame-counters-gvc"},CE=class{constructor(g){this.context=g,this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.ssrcGenerator=new hE,this.rollbackHandlers=[],this.logger=g.logger.createChild("MM2"),this.configProvider=g.configProvider}fromOffer(g,f,S=!1){this.logger.safe.debug(`fromOffer, modalities: ${JSON.stringify(f)} disableOnly: ${S}`),this.updateMediaEntitiesFromModel(g,S),this.updateSharingEntity(!!f.sharing),g.media.forEach((g=>{this.logger.safe.debug(`Media entity for mid: ${g.mid}, ${this.getMediaEntityByMid(g.mid)}`);const f=this.getMediaEntityByMid(g.mid);f&&this.saveLocalSsrc(f,g)}))}fromRemote(g,f){const S=0===this.mediaEntities.length;this.updateMediaEntitiesFromModel(g,!1,f),g.media.forEach(((g,f)=>{const S=this.getMediaEntityByMid(g.mid);S&&(this.saveRemoteMsid(S,g),this.saveRemoteSsrc(S,g),this.saveRtpHeaderExtensions(S,g),S.setXSourceStreamId(g.xSourceStreamId||this.generateSourceStreamId(f)),S.setRemoteRecvCapabilities(getRecvCapabilitiesForMedia(g)),S.setSubStreamIndex(g.subStreamIndex)),this.logger.safe.debug(`Media entity for mid: ${g.mid}, ${S}`)})),S&&this.updateReinvitelessState(g)}isEmpty(){return 0===this.mediaEntities.length}createMediaEntity(g,f){const S=SE.create(this.configProvider,g,f);return this.logger.safe.debug(`Creating media entity for modality: ${g}, mid: ${f}`),this.context.useSimulcast&&!this.mediaEntities.find((f=>f.getModality()===g))&&this.setSimulcastContext(S),S.setExtension("reinviteless",!1),this.mediaEntities.push(S),S}getMediaEntities(){return this.mediaEntities}getMediaEntity(g){return this.mediaEntities[g]}getMediaEntityByMid(g){return this.mediaEntities.find((f=>f.getMid()===g))}getMediaEntitiesByModality(g){return this.mediaEntities.filter((f=>f.getModality()===g))}getMediaEntitiesByMediaType(g){const f=modalityToMediaType(g);return this.getMediaEntitiesByModality(f)}getMediaEntityByRemoteStreamId(g){return this.mediaEntities.find((f=>f.getRemoteStreamId()===g))}getMediaEntityByLocalTrackId(g){return this.mediaEntities.find((f=>f.getLocalTrackId()===g))}getMediaEntityByXSourceStreamId(g){return this.mediaEntities.find((f=>f.getXSourceStreamId()===g))}reset(){this.mediaEntities=[],this.rollbackHandlers=[]}syncModalities(g,f,S=!1){this.logger.safe.debug(`syncModalities, modalities: ${JSON.stringify(f)}, disableOnly: ${S},`),this.fromOffer(g,f,S)}setLocalTracksInfo(g){this.mediaTracks=g}getLocalTracksInfo(){return this.mediaTracks}backup(){this.logger.safe.debug("backup"),this.mediaEntitiesBackup=[],this.mediaEntities.forEach((g=>{this.mediaEntitiesBackup.push(g.clone())}))}commit(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((g=>{g.setExtension("unnegotiatedModality",!1)}))}rollback(){this.logger.safe.debug(`rollback, if backup exists: ${!!this.mediaEntitiesBackup.length}`),this.mediaEntitiesBackup.length&&(this.rollbackHandlers.forEach((g=>g(this.mediaEntities,this.mediaEntitiesBackup))),this.mediaEntities.forEach(((g,f)=>{this.mediaEntitiesBackup[f]?this.mediaEntities[f]=this.mediaEntitiesBackup[f]:(g.disable(),g.setExtension("rollback",!0))})))}updateMediaEntitiesWithLocalTracks(){this.mediaTracks?(this.mediaEntities.forEach((g=>g.setLocalTrackId(null))),this.mediaTracks.forEach((g=>{const f=this.getMediaEntitiesByModality(g.modality)[0];f?(this.logger.safe.debug(`Setting local track id ${g.trackId} for modality ${g.modality}`),f.setLocalTrackId(g.trackId)):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(g.modality)}`)}))):this.logger.safe.debug("No mediaTracks, not updating local tracks for media entities")}updateMediaEntitiesWithActivityState(g,f){this.logger.safe.debug(`Updating activity indexes for ${g} to ${JSON.stringify(f)}`);const S=mediaTypeToModality(g),v=this.getMediaEntitiesByModality(S)[0];if(!v)return void this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(S)}`);const C=v.getSimulcastContext();C&&(C.activeRids=f)}setRollbackUpdateHandler(g){this.rollbackHandlers.push(g)}saveRtpHeaderExtensions(g,f){if(g.isDisabled())return void g.setRtpHeaderExtensions(void 0);const S=f.ext?.map((g=>this.getHeaderExtension(g)));this.logger.safe.debug(`RTP header ext for mid=${f.mid}, modality=${g.getModality()}: ${JSON.stringify(S)}`),g.setRtpHeaderExtensions(S)}getHeaderExtension(g){let f="unknown";for(const[S,v]of Object.entries(vE))if(g.uri.endsWith(S)){f=v;break}return{headerType:f,value:g.value}}saveRemoteMsid(g,f){if(isMediaDisabled(f))g.setRemoteStreamId(null);else if(f.msid)g.setRemoteStreamId(f.msid.split(" ")[0]);else if(f.ssrcs){const S=f.ssrcs.find((g=>"msid"===g.attribute));S?g.setRemoteStreamId(S.value.split(" ")[0]):this.logger.safe.warn(`No ssrc msid for media of type ${f.type} with mid ${f.mid}`)}}saveRemoteSsrc(g,f){if(f.ssrcs?.length){const S=f.ssrcs[0];g.setRemoteSsrc(+S.id)}}saveLocalSsrc(g,f){const S=f.ssrcs?.[0]?.id;if(!hasSendDirectionality(f.direction))return this.logger.safe.debug(`set local SSRC to ${S}`),void g.setLocalSsrc(+S);this.logger.safe.debug("has no send direction");const v=S||g.getLocalSsrc()||this.ssrcGenerator.nextVideoStreamSsrc().min;g.setLocalSsrc(+v)}updateMediaEntitiesFromModel(g,f,S){g.media.forEach(((g,v)=>{if(this.mediaEntities[v])if(isMediaDisabled(g))this.logger.safe.debug(`Disabling media entity for mid: ${g.mid}`),this.mediaEntities[v].disable();else{const f=g.mid||this.mediaEntities[v].getMid(),S=this.mediaEntities[v].getModality();this.logger.safe.debug(`Updating media entity for mid: ${f}, modality: ${S}`),this.mediaEntities[v].update(S,f),this.logger.safe.debug(`updated entity: ${this.mediaEntities[v]}`)}else f||this.createMediaEntity(getModality(g),g.mid||v.toString());this.mediaEntities[v]&&S&&!(this.mediaEntities[v].getModality()in S)&&(this.logger.safe.debug(`Disabling media entity for mid: ${g.mid} as it is not found in modalities ${JSON.stringify(S)}`),this.mediaEntities[v].disable())}))}updateSharingEntity(g){if(g&&!this.getMediaEntitiesByModality(qt.MODALITY.sharing).length){const g=this.getMediaEntitiesByModality(qt.MODALITY.video).pop();g.update(qt.MODALITY.sharing,g.getMid())}}setSimulcastContext(g){if(!g||g.getSimulcastContext())return;const f=new gE(g,this.logger.createChild(`SimContext:${g.getModality()}`),this.configProvider);g.setSimulcastContext(f)}generateSourceStreamId(g){return g+10}updateReinvitelessState(g){const f={[qt.MODALITY.audio]:0,[qt.MODALITY.video]:0,[qt.MODALITY.sharing]:0};for(const S of g.media){const g=getModality(S);void 0!==f[g]&&f[g]++;const v=this.getMediaEntityByMid(S.mid);if(v){const C=this.context.reinviteltessContext?.maxStreamsForModality[g]>=f?.[g]&&(!S.direction||"sendrecv"===S.direction);v.setExtension("reinviteless",C)}}}},yE=class{constructor(g){this.modifierList=g}modify(g){for(const f of this.modifierList)f.modify(g)}},EE=class{constructor(g,f,S,v){this.context=g,this.mediaManager=f,this.modalities=S,this.cname=v}build(g){switch(g.sdpSource){case 0:return new yE([new g_(this.context.configProvider),new qE(this.context.configProvider),new b_(this.mediaManager,this.context.configProvider),new I_(this.mediaManager),new t_(this.context.configProvider),new QE(this.context.configProvider),new u_(this.context.configProvider,this.mediaManager,g.sdpType,!1,this.context.getLogger().createChild("OverrideH264SendProfile")),new KE(this.mediaManager,this.context.configProvider,g.sdpType),new zE(this.mediaManager,this.context.configProvider,this.context.config.isConference,!1),new L_(this.context.configProvider,g.sdpType),new l_(this.context.configProvider)]);case 2:return new yE([new PE(this.mediaManager,this.modalities),new WE,new RE(this.mediaManager,!0),new S_(this.context.configProvider,this.mediaManager),new LE(this.modalities,this.mediaManager),new r_,new e_,new i_,new n_(this.context.configProvider),new ZE(this.context.configProvider),new h_(this.context.configProvider),new u_(this.context.configProvider,this.mediaManager,g.sdpType,!0,this.context.getLogger().createChild("OverrideH264SendProfile")),new xE,new IE(this.context),new E_(this.mediaManager,this.context.configProvider),new GE(this.context.configProvider),new w_,new M_(this.context.configProvider),new A_(this.context.configProvider),new BE(this.mediaManager,this.modalities,this.context.configProvider),new kE(this.context),new O_(this.context.configProvider),new DE(this.context.configProvider),new KE(this.mediaManager,this.context.configProvider,g.sdpType),new JE(this.mediaManager,this.context.configProvider,g.sdpType),new zE(this.mediaManager,this.context.configProvider,this.context.config.isConference,!0),new a_(this.context.configProvider,this.context.getLogger()),new VE,new N_(this.context.configProvider),new l_(this.context.configProvider),new F_(g,this.context),new C_(this.context.configProvider),new m_(this.context.configProvider)]);case 1:return new yE([new wE(this.context,this.modalities.data),new RE(this.mediaManager,!1),new HE(this.context.configProvider),new PE(this.mediaManager,this.modalities),new UE(this.mediaManager),new e_,new XE(this.context.configProvider),new bE(this.mediaManager,"offer"===g.sdpType,this.context.configProvider),new T_(this.mediaManager,this.context.getLogger()),new R_(this.context.configProvider,this.mediaManager),new FE(this.context.config.isConference,this.cname),new $E(this.mediaManager),new jE,new p_(this.context.configProvider),new NE(this.context.configProvider),new D_(this.context.configProvider),new k_(this.context.configProvider),new JE(this.mediaManager,this.context.configProvider,g.sdpType),new d_(this.mediaManager,this.context.configProvider,g.sdpType),new m_(this.context.configProvider)])}}},_E=class{constructor(g,f,S){this.context=g,this.mediaManager=f,this.sessionType=S,this.msSdpT=new cE(this.context,this.mediaManager)}modify(g){this.msSdpT.toMsSdp(g,this.sessionType)}},TE=class{constructor(g,f,S){this.context=g,this.mediaManager=f,this.sessionType=S,this.msSdpT=new cE(this.context,this.mediaManager)}modify(g){this.msSdpT.fromMsSdp(g,this.sessionType)}},IE=class{constructor(g){this.context=g}modify(g){const f=preferSdesSrtp(this.context.configProvider,this.context.config.isPstnCall),S=getSrtpInfo(g),v=g.media.find((g=>!!g.crypto));g.media.forEach((g=>{g.type!==qt.MEDIA_TYPE.dataChannel&&(!f&&g.fingerprint&&g.crypto&&delete g.crypto,g.protocol=!S.dtls||S.sdes&&f?qt.PROFILES.rtpSavpf:qt.PROFILES.udpTlsRtpSavpf,isMediaDisabled(g)&&g.protocol===qt.PROFILES.rtpSavpf&&v&&(g.crypto=v.crypto))}))}},bE=class{constructor(g,f,S){this.mediaManager=g,this.isOffer=f,this.configProvider=S}modify(g){g.media.forEach(((g,f)=>{const S=g.setup,v=this.mediaManager.getMediaEntities()[f],C=v.getExtension("setup");S&&v.isEnabled()&&("actpass"!==S?v.setExtension("setup",S):this.isOffer&&void 0!==C&&"actpass"!==C&&!this.configProvider.config.disableOutgoingDtlsRoleOverride&&(g.setup=C))}))}},AE=class{modify(g){g.media.forEach((g=>{g.direction===qt.MEDIA_STATE.sendReceive&&(g.direction=qt.MEDIA_STATE.receive),g.direction===qt.MEDIA_STATE.send&&(g.direction=qt.MEDIA_STATE.inactive)}))}},PE=class{constructor(g,f){this.mediaManager=g,this.modalities=f}modify(g){let f=0;g.media.forEach(((g,S)=>{const v=parseInt(g.mid,10);!isNaN(v)&&v>=f&&(f=v+1)})),g.media.forEach(((S,v)=>{const C=this.mediaManager.getMediaEntities()[v];if(isMediaDisabled(S)||C.isDisabled()||!(C.getModality()in this.modalities)){const _=C.getExtension("midApplied")?void 0:S.mid||""+f++;0===v?S.direction=qt.MEDIA_STATE.inactive:g.media[v]=disabledMedia(S.type,void 0,S.protocol,_)}}))}},RE=class{constructor(g,f){this.mediaManager=g,this.remote=f}modify(g){const f=this.mediaManager.getMediaEntities();for(let S=0;S<f.length;S++){const v=f[S],C=g.media[S];if(v.getExtension("rollback"))if(C&&!this.remote)g.media[S]=null;else if(!C&&this.remote){const f=v.getType()===qt.MEDIA_TYPE.data?qt.MEDIA_TYPE.dataChannel:v.getType(),S=f===qt.MEDIA_TYPE.dataChannel?qt.PROFILES.udpDtlsSctp:qt.PROFILES.udpTlsRtpSavpf;g.media.push(disabledMedia(f,void 0,S,void 0))}}g.media=g.media.filter((g=>g))}},ME=class{constructor(g){this.mediaManager=g}modify(g){this.mediaManager.getMediaEntities().forEach(((f,S)=>{const v=g.media[S];f.getModality()!==qt.MODALITY.data||v&&v.type===qt.MEDIA_TYPE.dataChannel||g.media.splice(S,0,disabledMedia(qt.MEDIA_TYPE.data,qt.MEDIA_LABEL.data,qt.PROFILES.rtpSavp,void 0))}))}},wE=class{constructor(g,f){this.context=g,this.direction=f}modify(g){g.media.forEach((g=>{g.type===qt.MEDIA_TYPE.dataChannel&&(g.type=qt.MEDIA_TYPE.data,g.payloads=qt.PAYLOAD_TYPE.X_DATA)})),allowDataChannel(this.context)&&getEnabledMedia(g,qt.MEDIA_TYPE.data).forEach((f=>{f.rtp=f.rtp||[],f.fmtp=f.fmtp||[],f.rtp.push({codec:"x-data",payload:127,rate:9e4}),f.rtp.push({codec:"rtx",payload:126,rate:9e4}),f.fmtp.push({payload:126,config:"apt=127"});const S=this.getNonOverlappingSsrc(g);f.xSsrcRange={ssrcMin:S,ssrcMax:S},f.rtcpMux="rtcp-mux",f.xDataProtocol="sctp",f.direction=this.direction}))}getNonOverlappingSsrc(g){let f,S=!0;do{f=Math.floor(4294967293*Math.random())+2,getEnabledMedia(g).forEach((g=>{g?.ssrcs?.[0]?.id===f&&(S=!1)}))}while(!S);return f}},OE=class{constructor(g){this.configProvider=g,this.uri="urn:3gpp:video-orientation",this.value=13}modify(g){if(this.configProvider.config.enableVideoOrientationExtension)for(const f of getEnabledMedia(g,qt.MEDIA_TYPE.video))this.modifyMedia(f)}},DE=class extends OE{modifyMedia(g){g.ext??(g.ext=[]),g.ext.some((g=>g.uri===this.uri))||g.ext.push({value:this.getAvailableValue(g.ext),uri:this.uri})}getAvailableValue(g){const f=g.map((g=>g.value));return f.includes(this.value)?Math.max(...f)+1:this.value}},NE=class extends OE{modifyMedia(g){g.ext=g.ext?.filter((g=>g.uri!==this.uri))}},kE=class{constructor(g){this.context=g}modify(g){const f=g.groups?.find((g=>"BUNDLE"===g.type));for(let S=g.media.length-1;S>=0;S--){const v=g.media[S];if(v.type===qt.MEDIA_TYPE.data){const C=this.context.configProvider.config.rejectUnbundledDataModality&&!this.context.configProvider.mediaConfig.isTransportUnbundled&&!f?.mids?.toString().includes(v.mid),_=allowDataChannel(this.context);_||this.context.configProvider.config.acceptDisabledDataModality?(v.port=_&&!C?v.port:0,v.payloads=qt.PAYLOAD_TYPE.DATA_CHANNEL,v.type=qt.MEDIA_TYPE.dataChannel,v.protocol=qt.PROFILES.udpDtlsSctp,v.sctpPort??(v.sctpPort=this.context.configProvider.config.sctpPort),delete v.xDataProtocol,delete v.rtp,delete v.fmtp,delete v.rtcp,delete v.rtcpMux,delete v.ext,delete v.ssrcs,delete v.ssrcGroups,delete v.xSsrcRange):g.media.splice(S,1)}}}},LE=class{constructor(g,f){this.modalities=g,this.mediaManager=f}modify(g){getEnabledMedia(g).forEach((g=>{const f=getModality(g),S=this.mediaManager.getMediaEntityByMid(g.mid);!(this.modalities[f]!==qt.MEDIA_STATE.send||S.getExtension("reinviteless")||g.direction&&g.direction.toLowerCase()===qt.MEDIA_STATE.receive)&&(g.direction=qt.MEDIA_STATE.receive)}))}},FE=class{constructor(g,f){this.isMultiparty=g,this.cname=f}modify(g){this.isMultiparty&&getEnabledMedia(g).forEach((g=>{const f=g.direction;f!==qt.MEDIA_STATE.receive&&f!==qt.MEDIA_STATE.inactive||(g.ssrcs?.[0]?g.ssrcs=[{id:g.ssrcs[0].id,attribute:"cname",value:this.cname}]:g.type===qt.MEDIA_TYPE.audio?g.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:g.type===qt.MEDIA_TYPE.video&&(g.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}))}},xE=class{modify(g){const f=new Set;getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{g.ssrcs&&g.ssrcs.length>1&&f.add(+g.ssrcs[0].id)}));const S=getEnabledMedia(g,qt.MEDIA_TYPE.video).find((g=>g.direction===qt.MEDIA_STATE.sendReceive||g.direction===qt.MEDIA_STATE.send));getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{const v=g.direction;if((v===qt.MEDIA_STATE.receive||v===qt.MEDIA_STATE.inactive)&&g.ssrcs&&1===g.ssrcs.length){const v=g.ssrcs[0].id;(1===v||S&&S.ssrcs[0].id===v||!S&&f.has(v))&&(delete g.ssrcs,delete g.ssrcGroups)}}))}},UE=class{constructor(g){this.mediaManager=g}modify(g){g.media.forEach(((g,f)=>{const S=this.mediaManager.getMediaEntities()[f];g.label=getLabelForModality(S.getModality())}))}},VE=class{modify(g){g.media.forEach((g=>{delete g.label}))}},BE=class{constructor(g,f,S){this.mediaManager=g,this.modalities=f,this.configProvider=S}modify(g){let f=this.configProvider.mediaConfig.maxBandwidthInKbps;const S=g.bandwidth?.find((g=>"CT"===g.type));S&&(!f||f>+S.limit)&&(f=+S.limit);const v=this.configProvider.config.audioBandwidthInKbps||0,C=Math.max(f-v,0),_=this.configProvider.config.videoBandwidthAllocation&&hasSendDirectionality(this.modalities.video)&&hasSendDirectionality(this.modalities.sharing);getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{if(delete g.bandwidth,C){let f=C;if(_){const S=this.mediaManager.getMediaEntityByMid(g.mid).getModality()===qt.MODALITY.video?this.configProvider.config.videoBandwidthAllocation:1-this.configProvider.config.videoBandwidthAllocation;f=Math.round(C*S)}g.bandwidth=[{limit:f,type:"AS"}]}}))}},HE=class{constructor(g){this.configProvider=g}modify(g){const f=this.configProvider.mediaConfig.maxBandwidthInKbps;f&&(g.bandwidth=[{limit:f,type:"CT"}])}},$E=class{constructor(g){this.mediaManager=g}modify(g){g.media.forEach(((g,f)=>{const S=this.mediaManager.getMediaEntities()[f],v=S.getExtension("iceUfrag");S.setExtension("iceRestart",!!g.iceUfrag&&!!v&&v!==g.iceUfrag),S.setExtension("iceUfrag",g.iceUfrag)}))}},jE=class{modify(g){const f=new Set(["urn:ietf:params:rtp-hdrext:csrc-audio-level","http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"]);getEnabledMedia(g).forEach((g=>{g.ext&&(g.ext=g.ext.filter((g=>!f.has(g.uri))))}))}},GE=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.extmapAllowMixed&&(g.extmapAllowMixed="extmap-allow-mixed")}},qE=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.extmapAllowMixed||delete g.extmapAllowMixed}},WE=class{modify(g){getEnabledMedia(g).forEach((g=>{delete g.signalingFbXMessage}))}},zE=class{constructor(g,f,S,v){this.mediaManager=g,this.configProvider=f,this.isConference=S,this.remote=v}modify(g){if(this.configProvider.config.isAv1Allowed&&this.isConference){const f=findAllAvailablePayloads(g,[96,127]);this.mediaManager.getMediaEntities().forEach(((S,v)=>{let C=0;const _=g.media[v];if(S.getModality()!==qt.MODALITY.audio){if(!this.remote){const g=changeCodecPayload(_,{codec:"AV1",rate:9e4},f,!0,C);C=f.length-1,g.forEach((g=>{changeCodecPayload(_,{codec:"rtx",rate:9e4,payload:g+1},f,!1,C),C--}))}this.remote&&this.configProvider.config.av1LevelIndex&&forAllCodecs(_,{codec:"AV1",rate:9e4},(g=>{const replaceLevelIdx=(g,f)=>g.replace(/level-idx=\d+((\.\d+)+)?/g,`level-idx=${f}`);g.fmtp.config=replaceLevelIdx(g.fmtp.config,this.configProvider.config.av1LevelIndex)}))}}))}}},KE=class{constructor(g,f,S){this.mediaManager=g,this.configProvider=f,this.sdpType=S,this.baseModifier=new YE(this.mediaManager,this.configProvider,this.sdpType,!1)}modify(g){this.configProvider.config.filterCodecsInSdpV2||this.baseModifier.modify(g)}},JE=class{constructor(g,f,S){this.mediaManager=g,this.configProvider=f,this.sdpType=S,this.baseModifier=new YE(this.mediaManager,this.configProvider,this.sdpType,!0)}modify(g){this.configProvider.config.filterCodecsInSdpV2&&this.baseModifier.modify(g)}},YE=class{constructor(g,f,S,v=!1){this.mediaManager=g,this.configProvider=f,this.sdpType=S,this.alwaysReorder=v}modify(g){this.configProvider.config.filterCodecsInSdp&&"offer"===this.sdpType&&this.mediaManager.getMediaEntities().forEach(((f,S)=>{const v=g.media[S];if(!v)return;const C=getAllowedCodecs(this.configProvider,v.type);C.length&&filterCodecs(v,convertToCodecInfo(C),!!f.getExtension("unnegotiatedModality")||this.alwaysReorder,null)}))}},QE=class{constructor(g){this.configProvider=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(!f)return;const S=this.configProvider.mediaConfig.audioCodecContext;if(!S?.enabledLocally)return this.removeSubstitutionCodec(f,"SatinFB"),void this.removeSubstitutionCodec(f,"MUCHv2");S.codec!==S.lastUsedCodec&&"None"!==S.lastUsedCodec&&this.removeSubstitutionCodec(f,S.lastUsedCodec),S.enabledLocally&&!S.disabledRemotely&&this.addSubstitutionCodecIfNeeded(f,S.codec,g)}addSubstitutionCodecIfNeeded(g,f,S){if(this.isSubstitutionCodecAdded(g,f))return;const v=findAvailablePayload(S);if(-1===v)return;const C=getCustomCodecParams(f,"SUBSTITUTION");changePayloadType(S,C.payload,v),addCodec(g,C)}removeSubstitutionCodec(g,f){removeCodec(g,getCustomCodecParams(f,"SUBSTITUTION"))}isSubstitutionCodecAdded(g,f){let S=!1;return forOneCodec(g,getCustomCodecParams(f,"SUBSTITUTION"),(()=>{S=!0})),S}},XE=class{constructor(g){this.configProvider=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(!f)return;const S=this.configProvider.mediaConfig.audioCodecContext;if(!S?.enabledLocally||S.disabledRemotely)return this.removeSubstitutionCodec(f,"SatinFB"),void this.removeSubstitutionCodec(f,"MUCHv2");const v=getCustomCodecParams(S.codec,"SUBSTITUTION"),C=getCustomCodecParams(S.codec,"CODEC");forOneCodec(f,v,(g=>{g.rtp.codec=C.codec,g.rtp.rate=C.rate,g.rtp.encoding=C.encoding,"SatinFB"===S.codec&&(g.fmtp={payload:C.payload,config:"decoderversion=1"})}))}removeSubstitutionCodec(g,f){removeCodec(g,getCustomCodecParams(f,"SUBSTITUTION"))}},ZE=class{constructor(g){this.configProvider=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(!f)return;const S=this.configProvider.mediaConfig.audioCodecContext;if(!S?.enabledLocally)return this.removeCodec(f,"SatinFB"),void this.removeCodec(f,"MUCHv2");const v=getCustomCodecParams(S.codec,"CODEC"),C=getCustomCodecParams(S.codec,"SUBSTITUTION");let _=!1;forOneCodec(f,v,(g=>{S.enabledForSend&&(g.rtp.codec=C.codec,g.rtp.rate=C.rate,g.rtp.encoding=C.encoding,g.fmtp={payload:v.payload,config:"ptime=20"}),_=!0})),S.disabledRemotely=!_}removeCodec(g,f){removeCodec(g,getCustomCodecParams(f,"CODEC")),removeCodec(g,getCustomCodecParams(f,"SUBSTITUTION"))}},e_=class{modify(g){removeCodec(g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),{codec:"CN",rate:16e3})}},t_=class{constructor(g){this.configProvider=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),S=this.configProvider.mediaConfig.audioCodecContext;if(this.configProvider.config.fixOpusComfortNoise){if(!f||S&&(!S.enabledLocally||S.disabledRemotely))return}else if(!f||!S?.enabledLocally||S.disabledRemotely)return;let v=!1;const C={codec:"CN",rate:48e3};if(forOneCodec(f,C,(()=>{v=!0})),v)return;const _=findAvailablePayload(g);-1!==_&&(this.configProvider.config.fixOpusComfortNoise?C.payload=_:(changePayloadType(g,qt.PAYLOAD_TYPE.MSRTC_CNFB,_),C.payload=qt.PAYLOAD_TYPE.MSRTC_CNFB),addCodec(f,C))}},i_=class{modify(g){removeCodec(g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),{codec:"g722",rate:8e3,encoding:2})}},n_=class{constructor(g){this.configProvider=g}modify(g){const f=this.configProvider.config.enforceOpusFmtp;f&&forOneCodec(g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),{codec:"opus",rate:48e3,encoding:2},(g=>{g.fmtp||(g.fmtp={payload:g.rtp.payload});const S=new Zy(g.fmtp.config);Object.keys(f).forEach((g=>{S.removeIfPresent(g),S.setIfMissing(g,`${f[g]}`)})),g.fmtp.config=S.toString()}))}},r_=class{modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(f&&isMediaDisabled(f)){const S=g.media.find((g=>!!g.iceUfrag));S&&(f.port=9,f.direction="inactive",f.iceUfrag=S.iceUfrag,f.icePwd=S.icePwd,f.rtcpMux="rtcp-mux",S.crypto&&(f.crypto=S.crypto),S.fingerprint&&(f.fingerprint=S.fingerprint,f.setup=S.setup),f.rtp=[{payload:0,codec:"PCMU",rate:8e3}],f.payloads="0")}}},s_=class{constructor(g){this.otherPartyCodecs=g}modify(g){const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),S=["cn","telephone-event"],v=f.rtp.filter((g=>-1!==this.otherPartyCodecs.indexOf(g.codec.toLowerCase())&&-1===S.indexOf(g.codec.toLowerCase())));if(0===v.length)throw new Error("there is no matching primary audio codec");f.rtp.filter((g=>g!==v[0]&&-1===S.indexOf(g.codec.toLowerCase()))).forEach((g=>{removeCodec(f,g)}))}},a_=class{constructor(g,f){this.configProvider=g,this.logger=f}modify(g){this.configProvider.config.webrtcInjectTransportCCAudio&&getEnabledMedia(g,qt.MEDIA_TYPE.audio).forEach((g=>{const f=g.ext?.find((g=>g.uri===qt.TRANSPORT_CC.EXT_URI));if(!f)return void this.logger.safe.info("transport-cc ext not present in sdp, skipping injecting transport-cc attribute for audio");const S=g.rtp?.find((g=>"opus"===g.codec.toLowerCase()));if(!S)return void this.logger.safe.info("opus codec not found, skipping injecting transport-cc attribute for audio");const v=S.payload,C=g.rtcpFb?.find((g=>g.type===qt.TRANSPORT_CC.ATTRIBUTE&&g.payload===v));C?this.logger.safe.info("opus codec already has transport-cc attribute"):(g.rtcpFb=g.rtcpFb||[],g.rtcpFb.push({payload:v,type:qt.TRANSPORT_CC.ATTRIBUTE}),this.logger.safe.info("injected transport-cc attribute"))}))}},o_=class{constructor(g,f){this.mediaManager=g,this.configProvider=f}modify(g){g.media.forEach(((g,f)=>{if(isMediaDisabled(g)||g.type!==qt.MEDIA_TYPE.video)return;const S=this.mediaManager.getMediaEntities()[f];forOneCodec(g,{codec:"h264",rate:9e4},(g=>{const f=S.getLocalRecvCapabilities();if(!f)return;g.fmtp||(g.fmtp={payload:g.rtp.payload});const v=new Zy(g.fmtp.config);this.configProvider.config.h264SdpProfile?(v.removeIfPresent("profile-level-id"),v.setIfMissing("profile-level-id",this.configProvider.config.h264SdpProfile)):v.setIfMissing("profile-level-id","42C02A"),v.setIfMissing("max-fs",f.getMaxFS().toString()),v.setIfMissing("max-mbps",f.getMaxMBPS().toString()),v.setIfMissing("max-fps",f.getMaxFPS().toString()),g.fmtp.config=v.toString()}))}))}},l_=class{constructor(g){this.configProvider=g}modify(g){if(!this.configProvider.config.removeRtcpRsizeFromLocalSdp)return;const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));f?.rtcpRsize&&delete f.rtcpRsize}},c_=class{constructor(g){this.configProvider=g}modify(g){if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<this.configProvider.config.nonMultiStreamChannels)return;let f=0;for(let S=0;S<g.media.length;S++)if("Video"===getModalityForMedia(g.media[S])){if(g.media[S].xMultiStream)break;f++}const S=g.media.findIndex((g=>g.xMultiStream)),v=g.media[S];if(!v)return;const C=v.xMultiStream.startSsrc,_=v.xMultiStream.ssrcGroupRange,T=v.xMultiStream.ssrcRange;delete v.xMultiStream;const I=this.configProvider.config.numVideoChannelsGvc-f-1;v.subStreamIndex=I;const b=[];for(let f=0;f<I;f++){const I=(0,eE.cloneDeep)(v);I.mid=getNextAvailableMid(g),I.xSourceStreamId=v.xSourceStreamId,I.subStreamIndex=f,b.push(I.mid);const A=C+f*T;I.ssrcGroups=[{ssrcs:`${A} ${A+_}`,semantics:"FID"}],I.xSsrcRange={ssrcMin:A,ssrcMax:A+T-1},g.media.splice(S+f,0,I)}const A=C+I*T;v.ssrcGroups=[{ssrcs:`${A} ${A+_}`,semantics:"FID"}],v.xSsrcRange={ssrcMin:A,ssrcMax:A+T-1};const P=g.groups.find((g=>g.mids.includes(v.mid)));P.mids=`${P.mids} ${b.join(" ")}`}},d_=class{constructor(g,f,S){this.mediaManager=g,this.configProvider=f,this.type=S}modify(g){const f=1;if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<=this.configProvider.config.nonMultiStreamChannels+f)return;const S=this.mediaManager.getMediaEntitiesByModality(qt.MODALITY.video);let v=-1,C=-1;if(S.forEach(((f,S)=>{const _=g.media.findIndex((g=>g.mid===f.getMid()));S===this.configProvider.config.nonMultiStreamChannels-1&&(C=_),v=_})),-1===v||-1===C)return;const _=g.media[v];g.media.splice(C+1,v-C-1);const T=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;_.xMultiStream={numberOfStreams:T,startSsrc:1,ssrcRange:1,ssrcGroupRange:1},"answer"===this.type&&(_.xMultiStream.numberOfStreams=Math.min(T,this.configProvider.mediaConfig.multiStreamChannelsOffered),_.ssrcGroups&&delete _.ssrcGroups,_.xSsrcRange&&delete _.xSsrcRange)}},h_=class{constructor(g){this.configProvider=g}modify(g){getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{forOneCodec(g,{codec:"h264",rate:9e4},(g=>{if(g.fmtp){const f=new Zy,S=new Zy(g.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((g=>{if(S.contains(g)){let v=S.get(g);"profile-level-id"===g&&(v=this.configProvider.config.h264SendProfileOverride||v),f.setIfMissing(g,v)}})),g.fmtp.config=f.toString()}}))}))}},u_=class{constructor(g,f,S,v,C){this.configProvider=g,this.mediaManager=f,this.sdpType=S,this.remote=v,this.log=C}process(g,f,S){getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{getModalityForMedia(g)===f&&forOneCodec(g,{codec:"h264",rate:9e4},(f=>{if(f.fmtp){const v=new Zy(f.fmtp.config),C=new Zy;let _=!1;for(const f of v.names()){let T=v.get(f);if("profile-level-id"===f){const f=this.mediaManager.getMediaEntities().filter((f=>f.getModality()===getModality(g))).filter((g=>g.isEnabled())),v=S(f,T);typeof v==typeof T&&v!==T&&(T=v,_=!0)}C.setIfMissing(f,T)}_&&(f.fmtp.config=C.toString())}}))}))}modify(g){const f=this.configProvider.config.preferredH264SendProfileFallback,S=this.configProvider.config.preferredH264SharingSendProfile,v=this.configProvider.config.preferredH264VideoSendProfile;if(this.remote){const override=g=>(S,v)=>S.some((f=>f.isSendProfileSupported("H264",g)))?(this.log.safe.info(`Overriding H264 send profile: ${v} => ${g}`),g):(this.log.safe.info(`Applying fallback H264 profile: ${v} => ${f}`),f);v&&this.process(g,"Video",override(v)),S&&this.process(g,"ScreenShare",override(S))}else"answer"===this.sdpType&&(v||S)&&this.configProvider.config.enableFallbackH264SendProfileForLocalAnswer&&this.process(g,"Video",((g,C)=>C===v||C===S?(this.log.safe.info(`Restoring fallback profile in local answer: ${C} => ${f}`),f):C))}},g_=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{forAllCodecs(g,{codec:"h264",rate:9e4},(g=>{if(g.fmtp){const f=new Zy(g.fmtp.config);f.setIfMissing("sps-pps-idr-in-keyframe","1"),g.fmtp.config=f.toString()}}))}))}},p_=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&getEnabledMedia(g,qt.MEDIA_TYPE.video).forEach((g=>{forAllCodecs(g,{codec:"h264",rate:9e4},(g=>{if(g.fmtp){const f=new Zy(g.fmtp.config);f.removeIfPresent("sps-pps-idr-in-keyframe"),g.fmtp.config=f.toString()}}))}))}},m_=class{constructor(g){this.configProvider=g}modify(g){const f=(g.groups||[]).findIndex((g=>"BUNDLE"===g.type)),S=g.groups?g.groups[f]:void 0;S&&(this.configProvider.mediaConfig.isTransportUnbundled?(S.mids=this.createBundleFromMedia(getEnabledMedia(g,qt.MEDIA_TYPE.video)),S.mids||g.groups.splice(f,1)):S.mids=this.createBundleFromMedia(getEnabledMedia(g)))}createBundleFromMedia(g){return g.map((g=>g.mid?.toString())).filter((g=>g)).join(" ")}},f_=class{modify(g){g.media.forEach((g=>{isMediaDisabled(g)&&g.bundleOnly&&(g.port=9,delete g.invalid)}))}},S_=class{constructor(g,f){this.configProvider=g,this.mediaManager=f}modify(g){if(!this.configProvider.mediaConfig.isTransportUnbundled&&!g.groups?.find((g=>"BUNDLE"===g.type))){let f=!1;if(g.media.forEach(((g,S)=>{const v=this.mediaManager.getMediaEntities()[S];!f&&v.isEnabled()?(g.mid=v.getMid(),f=!0):(v.disable(),g.port=0)})),f){g.groups||(g.groups=[]);const f={type:"BUNDLE"};g.groups.push(f)}}}},v_=class{constructor(g,f){this.configProvider=g,this.logger=f}modify(g){g.media.forEach((g=>{const f=!!g.candidates;if(g.candidates&&(g.candidates=g.candidates.filter((g=>{let f=!0,S=!0,v=!0;return this.configProvider.config.iceCandidateType&&(f=!!g.type.match(new RegExp(this.configProvider.config.iceCandidateType,"i"))),this.configProvider.config.iceCandidateTransport&&(S=!!g.transport.match(new RegExp(this.configProvider.config.iceCandidateTransport,"i"))),this.configProvider.config.iceCandidateFilterMDns&&(v=!this.isMdns(g.ip),v||this.logger.safe.info(`Filtering out mDNS candidate ${scrubMriOrOmit(g.ip)}:${scrubMriOrOmit(g.port)}`)),f&&S&&v}))),f&&g.connection&&this.configProvider.config.iceCandidateFilterMDns&&(g.candidates&&0!==g.candidates.length||(g.candidates=[getDummyCandidate(g.port)]),this.isMdns(g.connection.ip)||!this.hasMatchingCandidate(g))){const f=this.getDefaultCandidate(g);g.connection.ip=f.ip,g.port=f.port}}))}hasMatchingCandidate(g){const f=g.connection;return f&&!!g.candidates.find(this.createIpAndPortMatcher(f.ip,g.port))}getDefaultCandidate(g){return g.candidates.slice().sort(((g,f)=>g.type===f.type?0:"host"===g.type||"relay"===f.type?1:"relay"===g.type||"host"===f.type?-1:0))[0]}isMdns(g){return g.indexOf(".local")>-1||g.indexOf(".encrypted")>-1}createIpAndPortMatcher(g,f){return S=>S.ip===g&&S.port===f}},C_=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.useOneRelayCandidateForRemoteSDP&&g.media.forEach((g=>{if(g.candidates){const f=g.candidates.filter((g=>!!g.type.match(new RegExp("relay","i"))));f.length>0&&(g.candidates=f.slice(0,1))}}))}},y_=class{modify(g){const f=getEnabledMedia(g)[0];f&&(f.candidates=[getDummyCandidate()])}},E_=class{constructor(g,f){this.mediaManager=g,this.configProvider=f}modify(g){g.media.forEach(((g,f)=>{this.fromMsSdp(g,f)}))}fromMsSdp(g,f){if(isMediaDisabled(g)||g.rids&&g.simulcast)return;const S=this.mediaManager.getMediaEntities()[f],v=S?.getSimulcastContext();v?.shouldBeEnabledInRemoteDesc()&&(v.enableInRemoteDesc(),g.simulcast={dir1:"recv",list1:this.configProvider.config.specCompliantSimulcast?.disableTilde?v.ridList.map((g=>`${g}`)).join(";"):v.ridList.map((g=>`${v.activeRids.includes(g)?"":"~"}${g}`)).join(";")},g.rids=v.ridList.map((g=>({id:g,direction:"recv"}))))}},T_=class{constructor(g,f){this.mediaManager=g,this.logger=f}modify(g){g.media.forEach(((g,f)=>{this.toMsSdp(g,f)}))}toMsSdp(g,f){const S=this.mediaManager.getMediaEntities()[f],v=S?.getSimulcastContext();v&&(v.localDescriptionIsApplied(),v.shouldBeEnabledInLocalDesc()&&(v.enableInLocalDesc(),this.removeSimulcastEnvelope(g),this.addStreamSsrc(g,S.getLocalSsrc())))}removeSimulcastEnvelope(g){g.rids&&delete g.rids,g.simulcast&&delete g.simulcast}addStreamSsrc(g,f){if(!f)return;if(g.ssrcs)return void this.logger.safe.debug(`Media mid: ${g.mid} already contains ssrc: ${JSON.stringify(g.ssrcs)}`);const S=f;this.setSsrc(g,S)}setSsrc(g,f){g.ssrcs=[{id:f,attribute:"fake_attribute",value:"fake_value"}]}},I_=class{constructor(g){this.mediaManager=g}modify(g){g.media.forEach(((g,f)=>{const S=this.mediaManager.getMediaEntities()[f],v=S?.getLocalTrackId();(!g.msid&&S?.getSimulcastContext()?.shouldUseSimulcast()&&v||S?.getExtension("reinviteless"))&&(g.msid=`- ${v??f}`)}))}},b_=class{constructor(g,f){this.mediaManager=g,this.configProvider=f}modify(g){const f=this.mediaManager.getMediaEntities(),S=(0,eE.flatMap)(f,(g=>g.getRtpHeaderExtensions())),v=S.find((g=>"vla"===g?.headerType))?.value,C=S.find((g=>"non-adv-vla"===g?.headerType))?.value,_=v??C??(0,eE.flatMap)(g.media,(g=>g.ext||[])).find((g=>g.uri===qt.VLA.EXT_URI))?.value,T=getFreeValueForExt(g,this.configProvider.config.extmapAllowMixed,qt.VLA.DEFAULT_VALUE);g.media.forEach(((g,S)=>{const v=getModalityForMedia(g);if(!this.configProvider.config.enableVla||"Video"!==v&&"ScreenShare"!==v)return;if(g.ext?.find((g=>g.uri===qt.VLA.EXT_URI)))return;const C=f[S]?.getRtpHeaderExtensions(),I=C?C.find((g=>"vla"===g.headerType))?.value??C.find((g=>"non-adv-vla"===g.headerType))?.value:_??T;I&&(g.ext=g.ext||[],g.ext.push({value:I,uri:qt.VLA.EXT_URI}))}))}},A_=class{constructor(g){this.configProvider=g}modify(g){g.media.forEach((g=>{const f=getModalityForMedia(g);if(this.configProvider.config.allowRemoteVla&&("Video"===f||"ScreenShare"===f))return;const S=g.ext?.findIndex((g=>g.uri===qt.VLA.EXT_URI));S>-1&&g.ext.splice(S,1)}))}},P_=class{constructor(g){this.configProvider=g}modify(g,f,S){g.media.forEach((g=>{const v=getModalityForMedia(g);if(!this.configProvider.config.enableNonAdvVla||"Video"!==v&&"ScreenShare"!==v||g.ext?.find((g=>g.uri===S)))return;const C=g.ext?.find((g=>g.uri===f));C&&(C.uri=S)}))}},R_=class extends P_{constructor(g,f){super(g),this.mediaManager=f}modify(g){const f=this.mediaManager.getMediaEntities();(0,eE.flatMap)(f,(g=>g.getRtpHeaderExtensions())).some((g=>"vla"===g?.headerType))||super.modify(g,qt.VLA.EXT_URI,qt.VLA.EXT_URI_NON_ADV)}},M_=class extends P_{constructor(g){super(g)}modify(g){super.modify(g,qt.VLA.EXT_URI_NON_ADV,qt.VLA.EXT_URI)}},w_=class{modify(g){g.media.forEach((g=>{g.ext?.forEach((g=>g.uri=this.normalizeSlashesInUri(g.uri)))}))}normalizeSlashesInUri(g){return g.replace(/\\/g,"/")}},O_=class{constructor(g){this.configProvider=g}modify(g){if(this.configProvider.config.fixSdpForPartialIceRestart){const[{iceUfrag:f,icePwd:S}={}]=g.media;void 0!==f&&void 0!==S&&g.media.forEach((g=>{g.iceUfrag=f,g.icePwd=S}))}}},D_=class{constructor(g){this.configProvider=g}modify(g){if(this.configProvider.config.reduceRtcpFbInSdp?.length)for(const f of getEnabledMedia(g,qt.MEDIA_TYPE.video))f.rtcpFb=f.rtcpFb&&this.getFbList(f.rtcpFb)}getFbList(g){const f=[],S=[];for(const v of g){const g=v.subtype?`${v.type}/${v.subtype}`:`${v.type}`;f.includes(g)||(this.configProvider.config.reduceRtcpFbInSdp.includes(g)?(f.push(g),S.push({...v,payload:"*"})):S.push(v))}return S}},N_=class{constructor(g){this.configProvider=g}modify(g){if(!this.configProvider.config.redReceiveEnabled)return;const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio));let S=0;forOneCodec(f,{codec:"opus",rate:48e3,encoding:2},(g=>{S=g.rtp.payload}));const v={codec:"RED",rate:8e3};forOneCodec(f,v,(g=>{g.rtp.rate=48e3,g.rtp.encoding=2,S&&(g.fmtp={payload:g.rtp.payload,config:`${S}/${S}`})})),removeCodec(f,v)}},k_=class{constructor(g){this.configProvider=g}modify(g){this.configProvider.config.redReceiveEnabled&&forOneCodec(g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),{codec:"red",rate:48e3,encoding:2},(g=>{g.rtp.codec="RED",g.rtp.rate=8e3,delete g.rtp.encoding}))}},L_=class{constructor(g,f){this.configProvider=g,this.sdpType=f}modify(g){if(!this.configProvider.config.redReceiveEnabled||"offer"!==this.sdpType)return;const f=g.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),S={codec:"red",rate:48e3,encoding:2};let v=0;if(forOneCodec(f,S,(g=>{v=g.rtp.payload})),v===qt.PAYLOAD_TYPE.MSRTC_RED)return;const C=findAvailablePayload(g);-1!==C&&(changePayloadType(g,qt.PAYLOAD_TYPE.MSRTC_RED,C),forOneCodec(f,S,(g=>{g.rtp.payload=qt.PAYLOAD_TYPE.MSRTC_RED})))}},F_=class{constructor(g,f){this.modification=g,this.context=f,this.logger=f.getLogger().createChild("IncomingDtlsRoleModifier")}modify(g){if("answer"!==this.modification.sdpType)if("offer"===this.modification.sdpType&&2===this.modification.sdpSource){if(this.modification.isOrWasProvisional){const f=this.context.config.isPstnCall?this.context.configProvider.config.createProvisionalAnswer.dtlsRolePstn:this.context.configProvider.config.createProvisionalAnswer.dtlsRole;if(!f)return;this.logger.debug(`Configured DTLS role override: ${f}`),g.media.forEach(((g,S)=>{const v=g.setup;"inactive"!==g.direction&&(v&&"actpass"!==v?this.logger.warn(`Remote DTLS role is ${v}, cannot change`):(g.setup=f,this.logger.debug(`Remote DTLS role changed from ${v} to ${g.setup} for mid=${g.mid}`)))}))}}else this.logger.error(`Tried to apply invalid change to DTLS role: ${this.modification.sdpType} ${this.modification.sdpSource}`)}};function disabledMedia(g,f,S,v){const C={type:g,port:0,label:f,payloads:g===qt.MEDIA_TYPE.dataChannel||g===qt.MEDIA_TYPE.data?qt.PAYLOAD_TYPE.DATA_CHANNEL:"36",protocol:S,connection:{ip:"10.10.10.10",version:4}};return v&&(C.mid=v),C}function getEnabledMedia(g,f=null){return g.media.filter((g=>!(isMediaDisabled(g)||f&&g.type!==f)))}function getDummyCandidate(g=1234){return{component:1,ip:"10.10.10.10",foundation:"1755259772",priority:2122197247,port:9!==g?g:1234,transport:"UDP",type:"host"}}function getFreeValueForExt(g,f,S,v=!1){const C=(0,eE.flatMap)(g.media,(g=>g.ext||[])).map((g=>g.value));if(0===C.length)return S;const _=2,T=14;if(v&&!C.includes(S))return S;let I;for(let g=_;g<=T;g++)if(!C.includes(g)){I=g;break}return!I&&f&&(I=Math.max(...C)+1),I}function getCustomCodecParams(g,f){if(!Ra[g]?.[f])throw`unsupported codec ${g} or type ${f}`;const S=Ra[g][f];return{codec:S.NAME,rate:S.RATE,encoding:S.ENCODING,payload:Ra[g].PT}}function changePayloadType(g,f,S){for(const v of g.media)updatePayload(v,f,S)}function changeCodecPayload(g,f,S,v,C){const _=new Set;return forAllCodecs(g,f,(g=>{g.rtp.payload<96&&(_.add(g.rtp.payload),g.rtp.payload=S[C]??g.rtp.payload,C++)}),v),_}var x_=class _SessionDescription{constructor(g,f,S,v){this.context=g,this.sessionType=f,this.sdp=S,this.remote=v,this.mediaManager=this.context.mediaManager,this.sdpTransform=this.context.sdpTransform,this.logger=this.context.logger.createChild("SessionDescr"),this.sdpModel=Qy.parse(this.sdp),v&&new c_(this.context.configProvider).modify(this.sdpModel),this.sdpModel.media.forEach((g=>{(0,Yy.isUndefined)(g.mid)||(g.mid=g.mid.toString())})),this.remote&&!this.context.configProvider.config.disableMsSdp&&new TE(g,this.mediaManager,f).modify(this.sdpModel)}getSdp(){return Qy.write(this.sdpModel)}clone(){return new _SessionDescription(this.context,this.sessionType,this.sdp,this.remote)}getModalities(){return this.modalities||getModalities(this.sdpModel)}updateModalities(g){this.logger.debug("updateModalities",g),this.modalities=g}getSrtpInfo(){return getSrtpInfo(this.sdpModel)}getVideoCodecs(){const g={};return this.sdpModel.media.forEach((f=>{"video"===f.type&&f.rtp.map((g=>g.codec.toLowerCase())).forEach((f=>g[f]=!0))})),Object.keys(g)}usePrimaryAudioCodecOnly(g){new s_(g).modify(this.sdpModel)}isCodecSwitchSupported(){return!this.sdpModel.media.some((g=>g.type===qt.MEDIA_TYPE.audio&&g.xMediaSettings&&this.containsMediaSetting(g.xMediaSettings,"codecswitchunsupported")))}toLocal(){return this.sdpModel=this.sdpTransform.toLocal(this.sdpModel,this.mediaManager,this.sessionType),this.getSdp()}toOffer(){return this.toOfferAnswer()}toAnswer(){return this.toOfferAnswer()}toOfferAnswer(){const g="offer"===this.sessionType;return new v_(this.context.configProvider,this.logger).modify(this.sdpModel),(new f_).modify(this.sdpModel),g&&this.mediaManager.isEmpty()&&this.mediaManager.fromOffer(this.sdpModel,this.modalities),this.mediaManager.syncModalities(this.sdpModel,this.modalities,!g),this.sdpModel=g?this.sdpTransform.toOffer(this.sdpModel,this.mediaManager,this.modalities):this.sdpTransform.toAnswer(this.sdpModel,this.mediaManager,this.modalities),this.context.configProvider.config.disableMsSdp||new _E(this.context,this.mediaManager,this.sessionType).modify(this.sdpModel),new o_(this.mediaManager,this.context.configProvider).modify(this.sdpModel),this.modalities=getModalities(this.sdpModel),this.getSdp()}setModalities(g){this.modalities=g,this.mediaManager.fromRemote(this.sdpModel,this.modalities)}toRemote(g=!1){return this.sdpModel=this.sdpTransform.toRemote(this.sdpModel,this.mediaManager,this.modalities,this.sessionType,g),this.getSdp()}getVideoRecvCapabilities(){return getRecvCapabilitiesForMedia(this.getMediaByLabel(qt.MEDIA_LABEL.video))}getSharingRecvCapabilities(){return getRecvCapabilitiesForMedia(this.getMediaByLabel(qt.MEDIA_LABEL.sharing))}getMediaByType(g){return this.sdpModel.media.find((f=>f.type===g))}isUnbundled(){const g=this.sdpModel.groups?.find((g=>"BUNDLE"===g.type)),f=this.sdpModel.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),S=this.sdpModel.media.find((g=>g.type===qt.MEDIA_TYPE.video));return g?!g.mids.toString().split(" ").find((g=>g===f.mid)):!!S}couldBeUnbundled(){return!this.sdpModel.groups?.find((g=>"BUNDLE"===g.type))||this.hasUnbundledIceCandidates()}containsMediaSetting(g,f){return g.some((g=>-1!==g.settings.indexOf(f)))}getMediaByLabel(g){return this.sdpModel.media.find((f=>f.label===g))}hasIceCandidatesForMediaType(g,f=""){const S=this.sdpModel.media?this.sdpModel.media.filter((f=>f.type===g&&!!f.candidates&&0!==f.candidates.length)):[];return f?S.some((g=>!!g.candidates&&g.candidates.some((g=>g.type===f)))):!!S.length}hasIceCandidates(){return this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.audio)||this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.video)}hasRelayIceCandidates(){return this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.audio,"relay")||this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.video,"relay")}hasUnbundledIceCandidates(){const g=this.sdpModel.media.filter((g=>g.type===qt.MEDIA_TYPE.video&&0!==g.port));return this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.audio)&&(!g.length||this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.video))}hasUnbundledRelayIceCandidates(){const g=this.sdpModel.media.filter((g=>g.type===qt.MEDIA_TYPE.video&&0!==g.port));return this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.audio,"relay")&&(!g.length||this.hasIceCandidatesForMediaType(qt.MEDIA_TYPE.video,"relay"))}isIceRestart(){return this.mediaManager.getMediaEntities().some((g=>g.getExtension("iceRestart")))}isMSRTC(){return!!this.sdpModel.xMediaBw}insertFakeCandidateIfNeeded(){return!this.hasIceCandidates()&&((new y_).modify(this.sdpModel),!0)}forceRecvonly(){(new AE).modify(this.sdpModel)}getBweType(){const g=this.sdpModel.media.find((g=>0!==g.port&&g.type===qt.MEDIA_TYPE.video));if(!g)return"Unknown";const f=g.ext?.find((g=>g.uri===qt.TRANSPORT_CC.EXT_URI||g.uri===qt.TRANSPORT_CC.MSSDP_ENCODED_URI));return f?"SSBWE":"REMB"}fixDataModality(){new ME(this.mediaManager).modify(this.sdpModel)}getPayloadsForMedia(g){const f=this.sdpModel.media.find((f=>f.type===g&&0!==f.port));return f?.rtp??[]}},U_=class{constructor(g){this.context=g}createLocalOffer(g){return new x_(this.context,"offer",g)}createRemoteOffer(g){return new x_(this.context,"offer",g,!0)}createLocalAnswer(g){return new x_(this.context,"answer",g)}createRemoteAnswer(g){return new x_(this.context,"answer",g,!0)}},V_=class{static build(g){return new U_(g=g||{})}};function getSrtpReport(g){let f="";return g.dtls&&(f+="dtls"),g.sdes&&(f+="sdes"),f}var B_=class{constructor(){this.info={OfferedSrtp:"none",NegotiatedSrtp:"none",IceConnectionState:"none",IceConnectionStatePrevious:"none",SignalingState:"none",SignalingStatePrevious:"none",RelayCandidate:"none",IceTransportPolicy:"none",IceServers:"none",FakeIceCandidate:!1,BweType:"none",SdpSemantics:"none",BundlePolicy:"none",IPAddress:"none",ReflexiveLocalIP:"none",NumberOfInterfaces:0,EncodedStreamWorker:!1,AudioCodecEvents:"none"}}setCandidateDetails(g){"host"===g.type&&"udp"===g.protocol?this.setIPAddressInfo(g.ip):"srflx"===g.type&&this.setReflexiveLocalIP(g.ip)}setOfferedModalities(g){this.offeredModalities=g,this.activeModalities=g}setNegotiatedModalities(g){this.negotiatedModalities=g,this.activeModalities=g}setNegotiatedSrtpInfo(g){this.info.NegotiatedSrtp=getSrtpReport(g)}setOfferedSrtpInfo(g){this.info.OfferedSrtp=getSrtpReport(g)}setIceConnectionState(g){this.info.IceConnectionStatePrevious=this.info.IceConnectionState,this.info.IceConnectionState=g}setSignalingConnectionState(g){this.info.SignalingStatePrevious=this.info.SignalingState,this.info.SignalingState=g}setRelayCandidateInfo(g){this.info.RelayCandidate=JSON.stringify(g)}fillExtensionInfo(g){assign(g,this.info)}setIceTransportPolicy(g){this.info.IceTransportPolicy=g}setIceServers(g){const f=g.map((g=>{const f={...g};return f.username&&(f.username="true"),f.credential&&(f.credential="true"),f}));this.info.IceServers=JSON.stringify(f)}setFakeIceCandidate(g){this.info.FakeIceCandidate=g}setBweType(g){"Unknown"!==g&&(this.info.BweType=g)}setSdpSemantics(g){this.info.SdpSemantics=g}setBundlePolicy(g){this.info.BundlePolicy=g}setEncodedStreamWorkerLoaded(g){this.info.EncodedStreamWorker=g}setAudioCodecEvents(g){this.info.AudioCodecEvents=JSON.stringify(g)}setIPAddressInfo(g){this.info.NumberOfInterfaces+=1,"none"===this.info.IPAddress&&(this.info.IPAddress=g)}setReflexiveLocalIP(g){"none"===this.info.ReflexiveLocalIP&&(this.info.ReflexiveLocalIP=g)}},H_=class{constructor(){this.presentationAPIUserDuration=0,this.presentationAudioDuration=0,this.isActiveScreenSharing=!1}handleInputLevel(g,f){this.isActiveScreenSharing&&("ScreenShare"===g&&f>0&&(this.presentationAPIUserDuration+=qt.TIME_INTERVAL.SEC_1),"Audio"===g&&f>0&&(this.presentationAudioDuration+=qt.TIME_INTERVAL.SEC_1))}updateScreenSharingStream(g,f){"ScreenShare"===f&&(this.isActiveScreenSharing=!!g)}getPresentationAudioDuration(){return this.presentationAudioDuration}getPresentationAudioAPIUserDuration(){return this.presentationAPIUserDuration}},$_=class _TimerTracker{constructor(g){this.name=g,this.sharedState={mark:new Map,measure:[]}}mark(g,f){const S=Jt();this.sharedState.mark.set(g,{name:g,ts:S,startTime:round(Yt+S),details:f})}measure(g,f){const S=this.sharedState.mark.get(f.start),v=this.sharedState.mark.get(f.end);if(S&&v){const C={...f,parentName:this.name===g?"":this.name};this.sharedState.measure.push({name:g,details:C,duration:round(v.ts-S.ts),startTime:S.startTime})}}markAndMeasure(g,f,S,v){!1===this.sharedState.mark.has(f)&&this.mark(f,S);const C=this.sharedState.mark.get(g),_=this.sharedState.mark.get(f);if(C&&_){const g={...v,parentName:this.name===f?"":this.name};this.sharedState.measure.push({name:f,details:g,duration:round(_.ts-C.ts),startTime:C.startTime})}}clone(g){const f=new _TimerTracker(`${this.name}|${g}`);return f.setSharedState(this.sharedState),f}setSharedState(g){this.sharedState=g}getReport(){return this.sharedState.measure.map((g=>({name:g.name,duration:g.duration,ts:g.startTime,parentName:g.details.parentName})))}},j_=class _NoopTracker{mark(){}measure(){}markAndMeasure(){}clone(){return new _NoopTracker}getReport(){return[]}},G_=class{constructor(g){this.enableTimerTracker=g,this.timerTrackers={},this.timerTrackerOptions={}}getTimerTracker(g,f){if(!this.enableTimerTracker)return new j_;const S=new $_(g);if(this.timerTrackers[g]){const f=this.timerTrackerOptions[g];if(f?.first)return new j_;f?.last&&(this.timerTrackers[g]=[S]),f?.all&&this.timerTrackers[g].push(S)}else this.timerTrackers[g]=[S],this.timerTrackerOptions[g]=f;return S}getReport(){if(this.enableTimerTracker)return Object.keys(this.timerTrackers).reduce(((g,f)=>{const S=this.timerTrackerOptions[f];return(S.first||S.last)&&(g[f]=[this.timerTrackers[f][0]?.getReport()]),S.all&&(g[f]=Object.values(this.timerTrackers[f]).map((g=>g?.getReport()))),g}),{})}},q_=class{constructor(g,f){this.configProvider=g,this.sessionInfo=f,this.data={fakeCandidate:!1,bweType:"Unknown",offeredSrtp:"unknown",negotiatedSrtp:"unknown",callSetupTimeReport:{}},this.timerTrackerManager=new G_(this.configProvider.config.enableTimerTracker),addGetterFields(this.data,{callSetupTimeReport:()=>this.timerTrackerManager.getReport()})}getTimerTracker(g,f){return this.timerTrackerManager.getTimerTracker(g,f)}set offeredModalities(g){this.data.offeredModalities=g,this.data.activeModalities=g,this.sessionInfo.setOfferedModalities(g)}set negotiatedModalities(g){this.data.negotiatedModalities=g,this.data.activeModalities=g,this.sessionInfo.setNegotiatedModalities(g)}set fakeCandidate(g){var f;(f=this.data).fakeCandidate||(f.fakeCandidate=g),this.sessionInfo.setFakeIceCandidate(g)}set bweType(g){this.data.bweType=g,this.sessionInfo.setBweType(g)}set negotiatedSrtp(g){this.data.negotiatedSrtp=getSrtpReport2(g),this.sessionInfo.setNegotiatedSrtpInfo(g)}set offeredSrtp(g){this.data.offeredSrtp=getSrtpReport2(g),this.sessionInfo.setOfferedSrtpInfo(g)}set meetingScenario(g){this.data.meetingScenario=g}set isTownHall(g){this.data.isTownHall=g}getObjectRef(){return this.data}};function getSrtpReport2(g){let f="";return g.dtls&&(f+="dtls"),g.sdes&&(f+="sdes"),f}var W_=class{constructor(g){this.data=g,this.reopenRequestDeviceIds=new Set}registerReopenRequest(g){this.reopenRequestDeviceIds.has(g)||(this.data.sinkNumOfReopenRequests++,this.reopenRequestDeviceIds.add(g))}registerSuccessfullReopen(g){this.reopenRequestDeviceIds.has(g)&&(this.data.sinkNumOfSuccessfulReopens++,this.reopenRequestDeviceIds.delete(g))}getObjectRef(){return this.data}},z_=class{constructor(g){this.configProvider=g,this.data={signalingState:"none",signalingStatePrevious:"none",iceConnectionState:"none",iceConnectionStatePrevious:"none",numCallbacksScheduled:0,numCallbacksExecuted:0,numCallbacksExecutedImmediately:0,scheduledCallbacks:[],events:[],timers:{}},this.scheduledCallbacks=new Map,this.stateTrackers={},addGetterFields(this.data,{scheduledCallbacks:()=>this.scheduledCallbacks.values(),timers:()=>{const g={};for(const f of Object.keys(this.stateTrackers))g[f]=this.stateTrackers[f].durations;return g}})}dispose(){for(const g of Object.values(this.stateTrackers))g.dispose()}set hasConnectionState(g){this.data.hasConnectionState=g}set transportState(g){this.data.transportStatePrevious=this.data.transportState,this.data.transportState=g,this.addStateEvent("transport",this.data.transportStatePrevious,this.data.transportState)}set signalingState(g){this.data.signalingStatePrevious=this.data.signalingState,this.data.signalingState=g,this.addStateEvent("signaling",this.data.signalingStatePrevious,this.data.signalingState)}set iceConnectionState(g){this.data.iceConnectionStatePrevious=this.data.iceConnectionState,this.data.iceConnectionState=g,this.addStateEvent("ice",this.data.iceConnectionStatePrevious,this.data.iceConnectionState)}set connectionState(g){this.data.connectionStatePrevious=this.data.connectionState,this.data.connectionState=g,this.addStateEvent("connection",this.data.connectionStatePrevious,this.data.connectionState)}set dtlsTransportState(g){this.data.dtlsTtransportStatePrevious=this.data.dtlsTransportState,this.data.dtlsTransportState=g,this.addStateEvent("dtlsTransport",this.data.dtlsTtransportStatePrevious,this.data.dtlsTransportState)}set provisional(g){this.addStateEvent("provisional",`${this.data.isProvisional}`,`${g}`),this.data.isProvisional=g}scheduleDoOnConnected(g,f,S,v){this.scheduledCallbacks.set(g,`${f}: ${S?"p":""}${v?"n":""}`),this.addCallbackEvent(f,S,v),this.data.numCallbacksScheduled++}runDoOnConnected(g,f=!1){this.scheduledCallbacks.get(g)&&this.scheduledCallbacks.delete(g),this.data.numCallbacksExecuted++,f&&this.data.numCallbacksExecutedImmediately++}getObjectRef(){return this.data}addCallbackEvent(g,f,S){arrayLimitedPush2(this.data.events,{evType:"callback",timestamp:Date.now(),logName:g,allowProvisional:f,mayRunImmediately:S},this.configProvider.config.diagnostics.collectionLimits.numTransportStateEvents)}addStateEvent(g,f,S){arrayLimitedPush2(this.data.events,{evType:"stateChanged",timestamp:Date.now(),changedState:g,previous:f,current:S},this.configProvider.config.diagnostics.collectionLimits.numTransportStateEvents);const v=this.stateTrackers[g]??new K_;v.state=S,this.stateTrackers[g]=v}},K_=class{constructor(){this.stopwatches={}}set state(g){if(this.stateInternal===g)return;this.running?.stop();const f=this.stopwatches[g]??new eT;this.stopwatches[g]=f,f.start(),this.running=f,this.stateInternal=g}get durations(){const g={};for(const f in this.stopwatches){const S=this.stopwatches[f];g[f]=S.elapsed}return g}dispose(){this.running?.stop(),this.running=void 0}},J_=/profile-level-id=(.{6})/,Y_=class{constructor(g,f,S=(()=>{}),v=(()=>this),C=(()=>{}),_=new Hy,T){this.configProvider=g,this.dmDiagnostics=f,this.addSessionStatsError=S,this.newNativeSession=v,this.commitNativeSession=C,this.dshDiagnostics=_,this.getSessionRef=T,this.data={startTime:Date.now(),duration:0,relayCandidate:"none",iceTransportPolicy:"none",iceServers:"none",sdpSemantics:"none",bundlePolicy:"none",iceCandidateErrors:[],H264Profiles:[],h264CodecCapabilities:{sendProfiles:[],receiveProfiles:[]},numInterfaces:0,statsReports:[],aggregatedModalityStats:{},multiViewStats:[],networkInfo:[],statsErrors:[],statsOnSubscribed:{},negotiation:{},recvVideoStreamCount:{min:0,max:0,mode:0},reportedReceiveBandwidth:[],reportedSendBandwidthLayouts:[],encodedStreamWorker:!1,audioCodecEvents:"none",totalVideoRecvMblocksRates:{macroblockRateReceivedMax:0,macroblockRateReceivedAvg:0,macroblockRateDecodedMax:0,macroblockRateDecodedAvg:0,macroblockRateMaxDecoderLossPercent:0,macroblockRateDecoderLossPercent:0},loopIntervalMax:-1,loopIntervalMedian:-1,fetchTimeMax:-1,fetchTimeMedian:-1,videoPerformanceEvent:[],localVideoPerformanceEvents:[],ovcToSubscriptionEvents:[],presentationAPIUserDuration:0,presentationAudioDuration:0,earlyMediaNumStatsPolls:0,audioRenderer:null},this.presentationAudioTelemetry=new H_,addGetterFields(this.data,{duration:()=>this.data.endTime?this.data.endTime-this.data.startTime:Date.now()-this.data.startTime,bandwidthReport:()=>this.bandwidthStatsRef?.getBandwidthReport(),presentationAPIUserDuration:()=>this.presentationAudioTelemetry.getPresentationAudioAPIUserDuration(),presentationAudioDuration:()=>this.presentationAudioTelemetry.getPresentationAudioDuration()}),Object.defineProperty(this.data,"IPAddress",{enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(this.data,"reflexiveLocalIP",{enumerable:!1,writable:!0,configurable:!0})}get deviceManager(){return this.dmDiagnostics}get audioLevel(){return this.analyzer?.getInputLevelNormalized()}get reflexiveLocalIP(){return this.data.reflexiveLocalIP}set bandwidthDiagnostic(g){this.bandwidthStatsRef=g}get callIsMuted(){return this.getSessionRef?.().callIsMuted}get sharingAudioLevel(){return this.analyzerSharing?.getInputLevelNormalized()}set relayCandidateInfo(g){this.data.relayCandidate=JSON.stringify(g)}set iceTransportPolicy(g){this.data.iceTransportPolicy=g}set reinvitelessContext(g){this.data.reinvitelessContext=g}set iceServers(g){const f=g.map((g=>{const f={...g};return f.username&&(f.username="true"),f.credential&&(f.credential="true"),f}));this.data.iceServers=JSON.stringify(f)}set sdpSemantics(g){this.data.sdpSemantics=g}set isCodecsSupported(g){this.data.codecSupport=g}set bundlePolicy(g){this.data.bundlePolicy=g}set latestRawReport(g){this.data.latestRawReport=g}set recvVideoStreamsCount(g){this.data.recvVideoStreamCount=g}set aggregatedStatsRef(g){this.data.aggregatedModalityStats=g}set multiViewStats(g){this.data.multiViewStats=g}set videoCapabilities(g){if(!g?.codecs)return;const f=[];g.codecs.forEach((g=>{if("h264"===g.mimeType&&g.sdpFmtpLine){const S=J_.exec(g.sdpFmtpLine)?.[1];S&&f.push(S)}})),this.data.H264Profiles=[...new Set(this.data.H264Profiles.concat(f))]}setSupportedH264Profiles(g,f){if(!g?.codecs&&!f?.codecs)return;const extractProfiles=g=>{const f=[];return g.codecs?.forEach((g=>{if("h264"===g.mimeType&&g.sdpFmtpLine){const S=J_.exec(g.sdpFmtpLine)?.[1];S&&!f.includes(S)&&f.push(S)}})),f};this.data.h264CodecCapabilities.sendProfiles=extractProfiles(g),this.data.h264CodecCapabilities.receiveProfiles=extractProfiles(f)}set sentBWSeed(g){var f;(f=this.data).initialBWSeed??(f.initialBWSeed=g),this.data.sentBWSeed=g}reportedSendBandwidthLayouts(g){arrayLimitedPush2(this.data.reportedSendBandwidthLayouts,g,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}set maxSessionBandwidth(g){this.data.maxSessionBandwidth=g}set bwStabilizationTime(g){this.data.bwStabilizationTime=g}set bwDownlinkStabilizationTime(g){this.data.bwDownlinkStabilizationTime=g}set statsOnSubscribed(g){this.data.statsOnSubscribed=g}set loopIntervalMax(g){this.data.loopIntervalMax=g}set loopIntervalMedian(g){this.data.loopIntervalMedian=g}set fetchTimeMax(g){this.data.fetchTimeMax=g}set fetchTimeMedian(g){this.data.fetchTimeMedian=g}set simulcastReport(g){this.data.simulcast=g}setTotalVideoRecvMblocksRates(g){this.data.totalVideoRecvMblocksRates=g}set dataChannelSessionState(g){this.data.dataChannelSessionState=g}set createChannelFailReason(g){this.data.dataChannelCreationError=g}setCandidateDetails(g){"host"===g.type&&"udp"===g.protocol?(this.data.numInterfaces++,this.data.IPAddress||(this.data.IPAddress=g.ip)):"srflx"!==g.type||this.data.reflexiveLocalIP||(this.data.reflexiveLocalIP=g.ip)}setAudioSendStream(g,f){if(this.configProvider.config.useAudioAnalyzer){const S=new My(g.rawStream);"ScreenShare"===f&&g.hasAudio()?(this.analyzerSharing?.dispose(),this.analyzerSharing=S):"Audio"===f&&(this.analyzer?.dispose(),this.analyzer=S)}}addNetworkInfo(g){arrayLimitedPush2(this.data.networkInfo,g,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addIceCandidateError(g){this.data.iceCandidateErrors.push(g)}clearIceCandidateErrors(){this.data.iceCandidateErrors=[]}registerEarlyMediaPoll(){this.data.earlyMediaNumStatsPolls++}addReportedReceiveBandwidth(g){arrayLimitedPush2(this.data.reportedReceiveBandwidth,g,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addOvcSubscriptionReport(g,f,S){const v=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];v?.ovc.count!==g&&arrayLimitedPush2(this.data.ovcToSubscriptionEvents,{ovc:{ts:Date.now(),count:g,subsCount:f,...S},subs:[]},this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents)}addSubscriptionToOvcEvent(g){const f=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];f&&arrayLimitedPush2(f.subs,{ts:Date.now(),count:g},this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents)}addStatsReport(g){arrayLimitedPush2(this.data.statsReports,g,this.configProvider.config.diagnostics.collectionLimits.numStatsReports)}addStatsError(g,f){const S=this.data.statsErrors.find((S=>S.error===f&&S.origin===g));S?S.count++:arrayLimitedPush2(this.data.statsErrors,{origin:g,error:f,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors),this.addSessionStatsError(`nativeSession:${g}`,f)}setPresentationAudioOnScreenSharing(g,f){this.presentationAudioTelemetry.updateScreenSharingStream(g,f)}handlePresentationAudioInputLevel(){this.presentationAudioTelemetry.handleInputLevel("Audio",this.audioLevel),this.presentationAudioTelemetry.handleInputLevel("ScreenShare",this.sharingAudioLevel)}terminate(){this.data.endTime=Date.now(),this.analyzer?.dispose(),this.analyzer=null,this.analyzerSharing?.dispose(),this.analyzerSharing=null}newQualityManagerDiagnostics(){const g=new zy(this.configProvider,((g,f)=>this.addStatsError(`qualityManagerDiagnostics:${g}`,f)));return this.data.qualityManager=g.getObjectRef(),g}newRemoteVideoManagerDiagnostics(){const g=new Ky(this.configProvider);return this.data.remoteVideoManager=g.getObjectRef(),g}newNegotiationDiagnostics(g){const f=new q_(this.configProvider,g);return this.data.negotiation=f.getObjectRef(),f}newSubscriptionManagerDiagnostics(){const g=new Wy(this.configProvider,(g=>this.addStatsError("subscriptionManagerDiagnostics",g)));return this.data.subscriptionManager=g.getObjectRef(),g}newDataChannelDiagnostics(g){const f=new _s(g);return this.data.dataChannel=f.getObjectRef(),f}newTransportStateDiagnostics(){const g=new z_(this.configProvider);return this.data.transportState=g.getObjectRef(),g}set encodedStreamWorker(g){this.data.encodedStreamWorker=g}set audioCodecEvents(g){this.data.audioCodecEvents=g}getObjectRef(){return this.data}registerVideoPerformanceEvent(g,f,S){const v={type:f,perfEvent:g,resRequestEvent:null,resChangedEvent:[],perfConstrainedOvc:S};arrayLimitedPush2(this.data.videoPerformanceEvent,v,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}registerLocalVideoPerformanceEvent(g){arrayLimitedPush2(this.data.localVideoPerformanceEvents,{timestamp:Date.now(),description:g.description,activeModalities:g.activeModalities,isTransient:g.isTransient},this.configProvider.config.diagnostics.collectionLimits.numPerformanceEvents)}registerResolutionChangeRequest(g){const f=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];f&&(f.resRequestEvent=g)}registerResolutionChangeEvent(g){const f=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];g.ts-f?.resRequestEvent?.ts<this.configProvider.config.diagnostics.performanceMonitoring.telemetryResolutionRequestSpanMs&&f.resChangedEvent.push(g)}set contributingSourcesError(g){this.data.contributingSourcesError=g}newAudioRendererDiagnostics(){return this.data.audioRenderer=this.getSessionRef?.().audioRenderer,this.data.audioRenderer?new W_(this.data.audioRenderer):null}},Q_=Symbol("sessionDiagnosticsRef"),X_=class{constructor(g,f,S,v,C,_){this.logger=g,this.configProvider=f,this.diagnosticsReport=S,this.dmDiagnostics=v,this.dshDiagnostics=new Hy,this.data={creationTime:Date.now(),callNumber:0,sessionId:"unknown",isMultiParty:!1,dtmfSuccessCount:0,dtmfFailureCount:0,iceInitTime:0,iceConnectedStateTime:0,negotiationCount:0,rejectedNegotiationCount:0,initialNegotiationCompleted:!1,finalAnswerTime:0,transportReconnectedCount:0,rollbackNegotiation:[],activeModalities:{},allowedAudioSend:!0,allowedVideoSend:!0,allowedScreensharingSend:!0,noIceCandidatesEventCount:{good:0,bad:0},noRelayIceCandidatesEventCount:{good:0,bad:0},microphoneInUseEventCount:{good:0,bad:0},cameraInUseEventCount:{good:0,bad:0},cameraFreezeEventCount:{start:0,end:0},rawMedia:{audio:{recv:{numAttempts:0,durationRatio:0},send:{numAttempts:0,durationRatio:0}}},ufds:[],remoteUfds:[],statsErrors:[],webrtcSessions:[],isOngoing:!1,duration:0,callMutedRatio:0,callOsMuted:0,callHwSilent:0,callSwMuted:0,callIsMuted:!1,callSpeakerMuted:0,callIsSpeaking:0,networkRecvUFD:void 0,networkSendUFD:void 0,zeroCaptureDevicesRatio:0,zeroRenderDevicesRatio:0,deviceRenderFailuresRatio:0,deviceCaptureFailuresRatio:0,deviceManager:void 0,relayTimers:void 0,authTokenFetcherStats:void 0,dominantSpeaker:this.dshDiagnostics.getObjectRef(),[Q_]:this,callConstraints:[],audioRenderer:{sinkNumOfReopenRequests:0,sinkNumOfSuccessfulReopens:0},elevation:[],batteryLevel:void 0},this.transportDisconnected=!1,this.commonMuteTracker=new eT,this.swMuteTracker=new eT,this.osMuteTracker=new eT,this.speakerMuteTracker=new eT,this.hwSilentTracker=new eT,this.isSpeakingTracker=new eT,this.networkRecvTracker=new tT,this.networkSendTracker=new tT,this.zeroCaptureTracker=new tT,this.zeroRenderTracker=new tT,this.deviceRenderTracker=new tT,this.deviceCaptureTracker=new tT,this.rawMediaTimers={audio:{send:new eT,recv:new eT}},this.dmFragmenter=new Z_(this.dmDiagnostics),this.durationTimer=new eT,this.data.callNumber=C,this.data.sessionId=_,this.durationTimer.start(),addGetterFields(this.data,{isOngoing:()=>void 0===this.data.terminationTime,duration:()=>this.durationTimer.elapsed,callMutedRatio:()=>getDurationRatio(this.commonMuteTracker.elapsed,this.data.duration),callOsMuted:()=>this.osMuteTracker.elapsed,callHwSilent:()=>this.hwSilentTracker.elapsed,callSwMuted:()=>this.swMuteTracker.elapsed,callIsMuted:()=>this.swMuteTracker.isRunning,callSpeakerMuted:()=>this.speakerMuteTracker.elapsed,callIsSpeaking:()=>this.isSpeakingTracker.elapsed,zeroCaptureDevicesRatio:()=>this.zeroCaptureTracker.getRatio("Bad"),zeroRenderDevicesRatio:()=>this.zeroRenderTracker.getRatio("Bad"),deviceRenderFailuresRatio:()=>this.deviceRenderTracker.getRatio("Bad"),deviceCaptureFailuresRatio:()=>this.deviceCaptureTracker.getRatio("Bad"),networkRecvUFD:()=>({good:this.networkRecvTracker.getCount("Good"),poor:this.networkRecvTracker.getCount("Poor"),bad:this.networkRecvTracker.getCount("Bad"),goodRatio:this.networkRecvTracker.getRatio("Good"),poorRatio:this.networkRecvTracker.getRatio("Poor"),badRatio:this.networkRecvTracker.getRatio("Bad")}),networkSendUFD:()=>({good:this.networkSendTracker.getCount("Good"),poor:this.networkSendTracker.getCount("Poor"),bad:this.networkSendTracker.getCount("Bad"),goodRatio:this.networkSendTracker.getRatio("Good"),poorRatio:this.networkSendTracker.getRatio("Poor"),badRatio:this.networkSendTracker.getRatio("Bad")}),deviceManager:()=>this.dmFragmenter.getFragment(this.dmDiagnostics),relayTimers:()=>this._relayManager?.getStats(),authTokenFetcherStats:()=>this._relayManager?.getAuthTokenStats(),callConstraints:()=>this.configProvider.getCallConstraintsTelemetry()}),addGetterFields(this.data.rawMedia.audio.recv,{durationRatio:()=>getDurationRatio(this.rawMediaTimers.audio.recv.elapsed,this.data.duration)}),addGetterFields(this.data.rawMedia.audio.send,{durationRatio:()=>getDurationRatio(this.rawMediaTimers.audio.send.elapsed,this.data.duration)})}get telemetryReport(){const g={type:"WebRtcMediaStats",data:this.diagnosticsReport.getSessionTelemetry(this.data.sessionId)},f={};return forOwnRec(g.data,((g,S,v)=>{let C=0;la.test(g)?(C=13,f[S]="IPv4"):ca.test(g)&&(C=4,f[S]="IPv6"),v[S]={type:C,value:g,__VALUE__:!0}})),g.data.metrics.piiFields={type:0,value:JSON.stringify(f),__VALUE__:!0},g}get mediaStatsReport(){return this.diagnosticsReport.getMediaSessionStats(this.data.sessionId)}get realtimeTelemetryReport(){return this.diagnosticsReport.getTeamsRealtimeTelemetry(this.data.sessionId)}get e2eDiagnostics(){return this.diagnosticsReport.getDiagnosticsForE2eTests(this.data.sessionId)}set relayManager(g){this._relayManager=g}set isMultiParty(g){this.data.isMultiParty=g}set mediaLegId(g){this.data.mediaLegId=g.process()}set ETag(g){this.data.ETag=g}set configIds(g){this.data.configIds=g}set reconnect(g){this.data.reconnect=g}set relay(g){this.data.relay={address:g.addresses.join(),expires:g.expires,realm:g.realm,credentials:!(!g.username||!g.password),ports:[g.udpPort?`udp:${g.udpPort}`:"",g.tcpPort?`tcp:${g.tcpPort}`:"",g.tlsPort?`tls:${g.tlsPort}`:""].join(","),fqdns:g.fqdns?g.fqdns.join():"none"}}set sessionError(g){this.data.error=g}set dtmfResult(g){g?this.data.dtmfSuccessCount++:this.data.dtmfFailureCount++}set swMute(g){g?this.swMuteTracker.start():this.swMuteTracker.stop(),this.updateCommonMute()}set speakerMute(g){g?this.speakerMuteTracker.start():this.speakerMuteTracker.stop()}set hwSilent(g){g?this.hwSilentTracker.start():this.hwSilentTracker.stop()}set isSpeaking(g){g?this.isSpeakingTracker.start():this.isSpeakingTracker.stop()}set iceInitTime(g){this.data.iceInitTime||(this.data.iceInitTime=g)}set finalAnswerTime(g){this.data.finalAnswerTime||(this.data.finalAnswerTime=g)}set iceConnectedStateTimestamp(g){this.data.iceConnectedStateTime||(this.data.iceConnectedStateTime=g)}set allowedModalities(g){this.data.allowedAudioSend=g.audio.some((g=>hasSendDirectionality(g))),this.data.allowedVideoSend=g.video.some((g=>hasSendDirectionality(g))),this.data.allowedScreensharingSend=g.sharing.some((g=>hasSendDirectionality(g)))}negotiationStart(g){var f;(f=this.data).initialNegotiationType??(f.initialNegotiationType=g),this.data.negotiationCount++}negotiationCompleted(g){this.data.initialNegotiationCompleted=!0,this.data.activeModalities=g,this.data.error=void 0}negotiationRejected(){this.data.rejectedNegotiationCount++}registerRollbackEvent(g){this.data.rollbackNegotiation.push({type:g.type,attempt:this.data.rollbackNegotiation.length+1,error:g.error})}registerRawMediaAccess(g,f,S){const v=this.data.rawMedia[g]?.[f];if(v){v.numAttempts++;const C=this.rawMediaTimers[g]?.[f];S?C?.start():C?.stop()}}registerQualityStateChangedEvent(g){switch(g.type){case"NoNetwork":"Good"===g.value?this.data.noIceCandidatesEventCount.good++:this.data.noIceCandidatesEventCount.bad++;break;case"NetworkRelaysNotReachable":"Good"===g.value?this.data.noRelayIceCandidatesEventCount.good++:this.data.noRelayIceCandidatesEventCount.bad++;break;case"DeviceCaptureNotFunctioning":this.deviceCaptureTracker.updateLevel(g.value),"Good"===g.value?this.data.microphoneInUseEventCount.good++:this.data.microphoneInUseEventCount.bad++;break;case"DeviceRenderNotFunctioning":this.deviceRenderTracker.updateLevel(g.value);break;case"VideoCapturerDeviceStartFailed":"Good"===g.value?this.data.cameraInUseEventCount.good++:this.data.cameraInUseEventCount.bad++;break;case"DeviceCaptureMute":"Bad"===g.value?this.osMuteTracker.start():this.osMuteTracker.stop(),this.updateCommonMute();break;case"NetworkRecvQuality":this.networkRecvTracker.updateLevel(g.value);break;case"NetworkSendQuality":this.networkSendTracker.updateLevel(g.value);break;case"ZeroCaptureDevicesEnumerated":this.zeroCaptureTracker.updateLevel(g.value);break;case"ZeroRenderDevicesEnumerated":this.zeroRenderTracker.updateLevel(g.value);break;case"VideoCaptureDeviceFreeze":"Good"===g.value?this.data.cameraFreezeEventCount.end++:this.data.cameraFreezeEventCount.start++}"DeviceSpeakWhileMuted"!==g.type&&arrayLimitedPush22(this.data.ufds,{...g,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numUFDs)}registerRemoteQualityStateChangedEvent(g,f){arrayLimitedPush22(this.data.remoteUfds,{...g,participantId:f,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numUFDs)}registerTransportConnected(){this.transportDisconnected&&(this.transportDisconnected=!1,this.data.transportReconnectedCount++)}registerTransportDisconnected(){this.transportDisconnected=!0}registerTransportFailed(){this.transportDisconnected=!1}terminated(g){this.commonMuteTracker.stop(),this.swMuteTracker.stop(),this.osMuteTracker.stop(),this.speakerMuteTracker.stop(),this.hwSilentTracker.stop(),this.isSpeakingTracker.stop(),this.rawMediaTimers.audio.recv.stop(),this.rawMediaTimers.audio.send.stop(),this.networkSendTracker.dispose(),this.networkRecvTracker.dispose(),this.zeroCaptureTracker.dispose(),this.zeroRenderTracker.dispose(),this.deviceCaptureTracker.dispose(),this.data.terminationReason=deepClone(g),this.data.terminationTime=Date.now(),this.durationTimer.stop(),this.dmFragmenter.terminated(this.dmDiagnostics)}addStatsError(g,f){const S=this.data.statsErrors.find((S=>S.error===f&&S.origin===g));this.logger.safe.error(`Stats error from '${g}': ${f} (${S?.count??1})`),S?S.count++:arrayLimitedPush22(this.data.statsErrors,{origin:g,error:f,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors)}newNativeSessionDiag(g=!0){let f;return f=new Y_(this.configProvider,this.dmDiagnostics,((g,f)=>this.addStatsError(g,f)),(g=>this.newNativeSessionDiag(g)),(()=>this.pushNativeSessionDiag(f.getObjectRef())),this.dshDiagnostics.resetState(),(()=>this.getObjectRef())),g&&arrayLimitedPush22(this.data.webrtcSessions,f.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numNativeSessions),f}pushNativeSessionDiag(g){arrayLimitedPush22(this.data.webrtcSessions,g,this.configProvider.config.diagnostics.collectionLimits.numNativeSessions)}getObjectRef(){return this.data}setBatteryLevel(g){this.data.batteryLevel=g}updateCommonMute(){this.swMuteTracker.isRunning||this.osMuteTracker.isRunning?this.commonMuteTracker.start():this.swMuteTracker.isRunning||this.osMuteTracker.isRunning||this.commonMuteTracker.stop()}registerElevation(g){arrayLimitedPush2(this.data.elevation,{event:g,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numElevation)}},Z_=class{constructor(g){this.initTimestamp=Number.MIN_SAFE_INTEGER,this.terminatedTimestamp=Number.MAX_SAFE_INTEGER,this.fragmentBase=this.sanitizeDiagnostics(g),this.initTimestamp=Date.now()}getFragment(g){const f=this.fragmentTerminated??g;return{devicesChangeCount:f.devicesChangeCount-this.fragmentBase.devicesChangeCount,deviceSelectionChangeCount:f.deviceSelectionChangeCount-this.fragmentBase.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:f.deviceSelectionChangeCountFromInterface-this.fragmentBase.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:f.devicesPollChangeCount-this.fragmentBase.devicesPollChangeCount,audioSourceNumOfSuccessfulReopens:f.audioSourceNumOfSuccessfulReopens-this.fragmentBase.audioSourceNumOfSuccessfulReopens||void 0,audioSourceNumOfReopenRequests:f.audioSourceNumOfReopenRequests-this.fragmentBase.audioSourceNumOfReopenRequests||void 0,audioCaptureDeviceErrorFlag:g.audioCaptureDeviceErrorFlags.filter((g=>g.timestamp>this.initTimestamp&&g.timestamp<this.terminatedTimestamp)).reduce(((g,f)=>Number(BigInt(g)|BigInt(f.audioDeviceErrorFlag))),0),audioRenderDeviceErrorFlag:g.audioRenderDeviceErrorFlags.filter((g=>g.timestamp>this.initTimestamp&&g.timestamp<this.terminatedTimestamp)).reduce(((g,f)=>Number(BigInt(g)|BigInt(f.audioDeviceErrorFlag))),0)}}terminated(g){this.fragmentTerminated=this.sanitizeDiagnostics(g),this.terminatedTimestamp=Date.now()}sanitizeDiagnostics(g){return{devicesChangeCount:g.devicesChangeCount,deviceSelectionChangeCount:g.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:g.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:g.devicesPollChangeCount,audioSourceNumOfSuccessfulReopens:g.audioSourceNumOfSuccessfulReopens,audioSourceNumOfReopenRequests:g.audioSourceNumOfReopenRequests,audioCaptureDeviceErrorFlag:0,audioRenderDeviceErrorFlag:0}}},eT=class{constructor(){this.startTime=0,this.elapsedInternal=0,this.countInternal=0}get isRunning(){return!!this.startTime}get elapsed(){return Math.round(this.startTime?this.elapsedInternal+Jt()-this.startTime:this.elapsedInternal)}get count(){return this.countInternal}start(){this.startTime||(this.startTime=Jt(),this.countInternal++)}stop(){this.startTime&&(this.elapsedInternal+=Jt()-this.startTime,this.startTime=0)}},tT=class{constructor(){this.currentLevel="Good",this.stopWatches={},this.startTime=Jt(),this.getStopWatch(this.currentLevel).start()}updateLevel(g){this.currentLevel!==g&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=g,this.getStopWatch(this.currentLevel).start())}getCount(g){const f=this.stopWatches[g];return f?f.count:0}getRatio(g){return getDurationRatio(this.getStopWatch(g).elapsed,Math.round((this.endTime||Jt())-this.startTime))}dispose(g){this.getStopWatch(this.currentLevel).stop(),this.endTime=Jt()}getStopWatch(g){let f=this.stopWatches[g];return f||(f=new eT,this.stopWatches[g]=f),f}};function getDurationRatio(g,f){return g/(f||1)}function compileAudioReport(g,f,S){return removeUndefinedFields({recv:removeUndefinedFields({id:f?.inboundRTP.id,ssrc:f?.inboundRTP.ssrc,mediaType:f?.inboundRTP.mediaType??f?.inboundRTP.kind,bytesReceived:sampleseries(g.audio?.recv,(g=>g.inboundRTP.bytesReceived)),packetsReceived:sampleseries(g.audio?.recv,(g=>g.inboundRTP.packetsReceived)),packetsLost:sampleseries(g.audio?.recv,(g=>g.inboundRTP.packetsLost)),googCodecName:f?.codec?.mimeType.split("/").pop(),googTrackId:f?.track?.trackIdentifier,transport_id:f?.transport?.id,transportId:f?.inboundRTP.transportId,transport_selectedCandidatePairId:f?.transport?.selectedCandidatePairId,transport_dtlsCipher:f?.transport?.dtlsCipher,transport_srtpCipher:f?.transport?.srtpCipher,pair_id:f?.transport?.selectedCandidatePair?.id,pair_responsesSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:f?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:f?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:f?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:f?.transport?.selectedCandidatePair?.writable,pair_requestsSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:sampleseries(g.audio?.recv,(g=>1e3*g.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:f?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:f?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:f?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:f?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:f?.transport?.selectedCandidatePair?.localCandidate?.ip??f?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:f?.transport?.selectedCandidatePair?.remoteCandidate?.ip??f?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:sampleseries(g.audio?.recv,(g=>g.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:f?.transport?.selectedCandidatePair?.nominated}),send:removeUndefinedFields({id:S?.outboundRTP.id,ssrc:S?.outboundRTP.ssrc,mediaType:S?.outboundRTP.mediaType??S?.outboundRTP.kind,bytesSent:sampleseries(g.audio?.send,(g=>g.outboundRTP.bytesSent)),packetsSent:sampleseries(g.audio?.send,(g=>g.outboundRTP.packetsSent)),packetsLost:sampleseries(g.audio?.send,(g=>g.remoteInboundRTP?.packetsLost)),googCodecName:S?.codec?.mimeType.split("/").pop(),googTrackId:S?.track?.trackIdentifier,transport_id:S?.transport?.id,transportId:S?.outboundRTP.transportId,transport_selectedCandidatePairId:S?.transport?.selectedCandidatePairId,transport_dtlsCipher:S?.transport?.dtlsCipher,transport_srtpCipher:S?.transport?.srtpCipher,pair_id:S?.transport?.selectedCandidatePair?.id,pair_responsesSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:S?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:S?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:S?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:S?.transport?.selectedCandidatePair?.writable,pair_requestsSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:sampleseries(g.audio?.send,(g=>1e3*g.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:S?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:S?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:S?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:S?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:S?.transport?.selectedCandidatePair?.localCandidate?.ip??S?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:S?.transport?.selectedCandidatePair?.remoteCandidate?.ip??S?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:sampleseries(g.audio?.send,(g=>g.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:S?.transport?.selectedCandidatePair?.nominated})})}function compileVideoTelemetryReport(g,f,S,v){return removeUndefinedFields({recv:removeUndefinedFields({id:S?.inboundRTP.id,ssrc:S?.inboundRTP.ssrc,mediaType:S?.inboundRTP.mediaType??S?.inboundRTP.kind,bytesReceived:sampleseries(f[g]?.recv,(g=>g.inboundRTP.bytesReceived)),packetsReceived:sampleseries(f[g]?.recv,(g=>g.inboundRTP.packetsReceived)),packetsLost:sampleseries(f[g]?.recv,(g=>g.inboundRTP.packetsLost)),googCodecName:S?.codec?.mimeType.split("/").pop(),codecImplementationName:S?.inboundRTP.decoderImplementation,googTrackId:S?.track?.trackIdentifier,transport_id:S?.transport?.id,transportId:S?.inboundRTP.transportId,transport_selectedCandidatePairId:S?.transport?.selectedCandidatePairId,transport_dtlsCipher:S?.transport?.dtlsCipher,transport_srtpCipher:S?.transport?.srtpCipher,pair_id:S?.transport?.selectedCandidatePair?.id,pair_responsesSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:S?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:S?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:S?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:S?.transport?.selectedCandidatePair?.writable,pair_requestsSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:sampleseries(f[g]?.recv,(g=>1e3*g.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:S?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:S?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:S?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:S?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:S?.transport?.selectedCandidatePair?.localCandidate?.ip??S?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:S?.transport?.selectedCandidatePair?.remoteCandidate?.ip??S?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:sampleseries(f[g]?.recv,(g=>g.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:S?.transport?.selectedCandidatePair?.nominated,framesDecoded:sampleseries(f[g]?.recv,(g=>g.inboundRTP.framesDecoded)),googFrameHeightReceived:sampleseries(f[g]?.recv,(g=>g.inboundRTP.frameHeight)),googFrameWidthReceived:sampleseries(f[g]?.recv,(g=>g.inboundRTP.frameWidth)),googFrameRateReceived:sampleseries(f[g]?.recv,(g=>g.extensions?.frameRateReceived||0)),googNacksSent:sampleseries(f[g]?.recv,(g=>g.inboundRTP.nackCount)),googPlisSent:sampleseries(f[g]?.recv,(g=>g.inboundRTP.pliCount)),keyFramesDecoded:sampleseries(f[g]?.recv,(g=>g.inboundRTP.keyFramesDecoded)),googFirsSent:sampleseries(f[g]?.recv,(g=>g.inboundRTP.firCount)),googJitterBufferMs:sampleseries(f[g]?.recv,(g=>g.extensions?.jitterBufferMs)),googFrameRateDecoded:sampleseries(f[g]?.recv,(g=>g.extensions?.frameRateDecoded||0)),googFrameRateOutput:S?.extensions?.trackRecvFps,jitter:S?.inboundRTP.jitter}),send:removeUndefinedFields({id:v?.outboundRTP.id,ssrc:v?.outboundRTP.ssrc,mediaType:v?.outboundRTP.mediaType??v?.outboundRTP.kind,bytesSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.bytesSent)),packetsSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.packetsSent)),packetsLost:sampleseries(f[g]?.send,(g=>g.remoteInboundRTP?.packetsLost)),googCodecName:v?.codec?.mimeType.split("/").pop(),codecImplementationName:v?.outboundRTP.encoderImplementation,googTrackId:v?.track?.trackIdentifier,transport_id:v?.transport?.id,transportId:v?.outboundRTP.transportId,transport_selectedCandidatePairId:v?.transport?.selectedCandidatePairId,transport_dtlsCipher:v?.transport?.dtlsCipher,transport_srtpCipher:v?.transport?.srtpCipher,pair_id:v?.transport?.selectedCandidatePair?.id,pair_responsesSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:v?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:v?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:v?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:v?.transport?.selectedCandidatePair?.writable,pair_requestsSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:sampleseries(f[g]?.send,(g=>1e3*g.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:v?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:v?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:v?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:v?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:v?.transport?.selectedCandidatePair?.localCandidate?.ip??v?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:v?.transport?.selectedCandidatePair?.remoteCandidate?.ip??v?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:sampleseries(f[g]?.send,(g=>g.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:v?.transport?.selectedCandidatePair?.nominated,framesEncoded:sampleseries(f[g]?.send,(g=>g.outboundRTP.framesEncoded)),googNacksReceived:sampleseries(f[g]?.send,(g=>g.outboundRTP.nackCount)),googPlisReceived:sampleseries(f[g]?.send,(g=>g.outboundRTP.pliCount)),googFirsReceived:sampleseries(f[g]?.send,(g=>g.outboundRTP.firCount)),keyFramesEncoded:sampleseries(f[g]?.send,(g=>g.outboundRTP.keyFramesEncoded)),googFrameHeightInput:v?.mediaSource?.height,googFrameWidthInput:v?.mediaSource?.width,googFrameRateInput:sampleseries(f[g]?.send,(g=>g.mediaSource?.framesPerSecond)),googFrameHeightSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.frameHeight)),googFrameWidthSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.frameWidth)),googFrameRateSent:sampleseries(f[g]?.send,(g=>g.extensions?.frameRateSent)),googRtt:sampleseries(f[g]?.send,(g=>1e3*(g.remoteInboundRTP?.roundTripTime??0)),!0),hugeFramesSent:v?.outboundRTP.hugeFramesSent,qpSum:sampleseries(f[g]?.send,(g=>g.outboundRTP.qpSum)),qualityLimitationDurations:v?JSON.stringify(v?.outboundRTP.qualityLimitationDurations):void 0,qualityLimitationReason:v?.outboundRTP.qualityLimitationReason,qualityLimitationResolutionChanges:v?.outboundRTP.qualityLimitationResolutionChanges,jitter:v?.remoteInboundRTP?.jitter,retransmittedPacketsSent:sampleseries(f[g]?.send,(g=>g.outboundRTP.retransmittedPacketsSent))})})}function compileExtensionsTelemetryReport(g,f,S){const v=f.config.diagnostics.telemetryLimits,C=g.aggregatedModalityStats,_=getLast(C.audio?.recv),T=getLast(C.audio?.send),I=getLast(C.video?.recv),b=getLast(C.video?.send),A=getLast(C.sharing?.recv),P=getLast(C.sharing?.send),getMaxCapsEvents=S=>S&&limitArraySize22(deepClone(S).map((f=>rebaseTime(limitArraySize22(f.events,v.numCapabilitiesApplied,1),"timestamp",g.startTime))),f.config.diagnostics.telemetryLimits.numCapabilitiesRequested),R=getMaxCapsEvents(g.qualityManager?.videoMaxCapabilitiesEvents),M=getMaxCapsEvents(g.qualityManager?.videoMaxCapabilitiesErrors),w=getMaxCapsEvents(g.qualityManager?.sharingMaxCapabilitiesEvents),O=getMaxCapsEvents(g.qualityManager?.sharingMaxCapabilitiesErrors),D="REMB"!==g.negotiation.bweType?g.bandwidthReport:void 0,N="REMB"===g.negotiation.bweType?g.bandwidthReport:void 0;return removeUndefinedFields({BundlePolicy:g.bundlePolicy,FakeIceCandidate:g.negotiation.fakeCandidate,h264AvailableProfiles:JSON.stringify(g.H264Profiles),h264CodecCapabilities:JSON.stringify(g.h264CodecCapabilities),IceConnectionState:g.transportState?.iceConnectionState,IceConnectionStatePrevious:g.transportState?.iceConnectionStatePrevious,IceServers:g.iceServers,IceTransportPolicy:g.iceTransportPolicy,NegotiatedSrtp:JSON.stringify(g.negotiation.negotiatedSrtp),OfferedSrtp:JSON.stringify(g.negotiation.offeredSrtp),RelayCandidate:g.relayCandidate,SdpSemantics:g.sdpSemantics,iceCandidateErrors:JSON.stringify(g.iceCandidateErrors),SignalingState:g.transportState?.signalingState,SignalingStatePrevious:g.transportState?.signalingStatePrevious,WebRTCStats_statsErrors:JSON.stringify(S),MaxSessionBandwidth:g.maxSessionBandwidth,Bandwidth_uplinkStabilizationTime:JSON.stringify(g.bwStabilizationTime),Bandwidth_downlinkStabilizationTime:JSON.stringify(g.bwDownlinkStabilizationTime),totalVideoControlMessages:g.qualityManager?.numVideoControlMessages,outOfOrderVideoControlMessages:g.qualityManager?.numOutOfOrderVideoControlMessages,webcamFreezeIntervals:g.qualityManager?.numWebcamFreezeIntervals,processedStreamFreezeIntervals:g.qualityManager?.numProcessedStreamFreezeIntervals,IPAddress:g.IPAddress??"none",ReflexiveLocalIP:g.reflexiveLocalIP??"none",NumberOfInterfaces:g.numInterfaces,StartTime:g.startTime,EndTime:g.endTime,AudioTransportRecvBitrate:_?.transport?.extensions?.recvBWAvg,AudioTransportSendBitrate:_?.transport?.extensions?.sendBWAvg,AudioPayloadRecvBitrate:_?.aggregated?.bitrateAvg,AudioPayloadSendBitrate:T?.aggregated?.bitrateAvg,VideoPayloadRecvBitrate:I?.aggregated?.bitrateAvg,VideoPayloadSendBitrate:b?.aggregated?.bitrateAvg,WebRTCStats_bweStat_googAvailableReceiveBandwidth:sampleseries(C.video?.recv,(g=>g.transport?.selectedCandidatePair?.availableIncomingBitrate))??sampleseries(C.video?.send,(g=>g.transport?.selectedCandidatePair?.availableIncomingBitrate)),WebRTCStats_bweStat_googAvailableSendBandwidth:sampleseries(C.video?.send,(g=>g.transport?.selectedCandidatePair?.availableOutgoingBitrate))??sampleseries(C.video?.recv,(g=>g.transport?.selectedCandidatePair?.availableOutgoingBitrate)),Bandwidth_jumpsHistogram:JSON.stringify(b?.transport?.extensions?.bwJumpsHistogram),StartCallBWESendSide:JSON.stringify(D?.startOfTheCall),EndCallBWESendSide:JSON.stringify(D?.endOfTheCall),BWEStdSendSide:JSON.stringify(D?.std),BwPercentilesSendSide:JSON.stringify(D?.bwPercentiles),AvgBwSendSide:JSON.stringify(D?.avgBwe),StartCallBWE:JSON.stringify(N?.startOfTheCall),EndCallBWE:JSON.stringify(N?.endOfTheCall),BWEStd:JSON.stringify(N?.std),BwPercentiles:JSON.stringify(N?.bwPercentiles),AvgBw:JSON.stringify(N?.avgBwe),WebRTCStats_ssrc:removeUndefinedFields({audio:compileAudioReport(C,_,T),video:compileVideoTelemetryReport("video",C,I,b),sharing:compileVideoTelemetryReport("sharing",C,A,P)}),Audio_recv_jitterBufferAvgSize:_?.aggregated?.avgJitterBufferSize,Audio_recv_packetsLostRateMax:round(_?.aggregated?.lossRateMax,6),Audio_recv_jitterAvg:_?.aggregated?.jitterAvg,Audio_recv_jitterMax:_?.aggregated?.jitterMax,Audio_recv_networkAvgLossRate:round(_?.aggregated?.networkAvgLossRate,6),Audio_recv_packetsLostAvg:_?.aggregated?.packetsLostAvg,Audio_recv_healedRatioAvg:_?.aggregated?.healedRatioAvg,Audio_recv_healedRatioMax:_?.aggregated?.healedRatioMax,Audio_send_rttAvg:T?.aggregated?.rttAvg&&round(1e3*T.aggregated.rttAvg),Audio_send_rttMax:T?.aggregated?.rttMax&&round(1e3*T.aggregated.rttMax),Audio_send_RawInputVolume:sampleseries(C.audio?.send,(g=>g.aggregated?.rawInputVolume)),Audio_send_packetsLostRateMax:round(T?.aggregated?.lossRateMax,6),Audio_send_presentationAPIUserDuration:g.presentationAPIUserDuration,Audio_send_presentationDuration:g.presentationAudioDuration,Video_recv_DurationSeconds:I?.aggregated?.duration,Video_recv_FreezeHistogram:JSON.stringify(I?.aggregated?.freezeCountHistogram),Video_recv_FreezeTimestamps:JSON.stringify(rebaseAndLimitHistogramTimestamps(I?.aggregated?.freezeTimestampsHistogram,g.startTime,v.numOfHistogramSamples)),Video_recv_LongestFreezeDuration:I?.aggregated?.longestFreeze,Video_recv_OngoingFreeze:I?.extensions?.isFrozen,Video_recv_OngoingFreezeDuration:I?.aggregated?.ongoingFreezeDuration,Video_recv_TotalFreezeDuration:I?.aggregated?.totalFreezeDuration,Video_recv_RecvAvgFreezeDuration:I?.aggregated?.avgFreezeDuration,Video_recv_NumResolutionSwitches:I?.aggregated?.numResolutionSwitches,Video_recv_ResolutionDurations:JSON.stringify(I?.aggregated?.resolutionDurations),Video_recv_StreamsMax:g.recvVideoStreamCount.max,Video_recv_StreamsMin:g.recvVideoStreamCount.min,Video_recv_StreamsMode:g.recvVideoStreamCount.mode,Video_recv_TimeToFirstFrame:g.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_TimeToFirstFrameSinceSubscriptionStart:g.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_bitrateAvg:I?.aggregated?.bitrateAvg,Video_recv_bitrateMax:I?.aggregated?.bitrateMax,Video_recv_frameRateAvg:I?.aggregated?.avgFrameRate,Video_recv_jitterBufferAvgSize:I?.aggregated?.avgJitterBufferSize,Video_recv_packetsLostRateMax:round(I?.aggregated?.lossRateMax,6),Video_recv_isRenderingEvents:JSON.stringify(limitArraySize22(g.remoteVideoManager?.isRenderingEvents.video,v.numIsRenderingEvents)),Video_recv_FpsHarmonicAverage:I?.aggregated?.fpsHarmonicAverage,Video_recv_PreferredResolution:g.remoteVideoManager?.preferredResolution.video?.toString(),Video_recv_statsOnSubscribed:JSON.stringify(g.statsOnSubscribed.video),Video_SubscriptionEvents:JSON.stringify(rebaseTime(g.subscriptionManager?.video.events,"ts",g.startTime)),Video_SubscriptionCounters:JSON.stringify(g.subscriptionManager?.video.counters),Video_send_CaptureFramerateAvg:b?.aggregated?.captureFramerateAvg,Video_send_DurationSeconds:b?.aggregated?.duration,Video_send_FreezeIntervals:b?.extensions?.captureFreezeIntervalsCount,Video_send_MaxCapabilities:JSON.stringify(R),Video_send_MaxCapabilitiesErrors:JSON.stringify(M),Video_send_OvershootDurations:JSON.stringify({fs:b?.aggregated?.totalFsOvershootDuration,fps:b?.aggregated?.totalFpsOvershootDuration,br:b?.aggregated?.totalBrOvershootDuration}),Video_send_OvershootEvents:limitRebaseAndStringifyEvents(b?.aggregated?.overshootEvents,v.numOvershootEvents,"timestamp",g.startTime),Video_send_QpAvg:b?.aggregated?.qpAvg,Video_send_bitrateAvg:b?.aggregated?.bitrateAvg,Video_send_bitrateMax:b?.aggregated?.bitrateMax,Video_send_frameRateAvg:b?.aggregated?.frameRateAvg,Video_send_AllocateBWAvg:b?.aggregated?.bweAvg,Video_send_CameraOpenWidth:b?.extensions?.cameraOpenResolution?.width,Video_send_CameraOpenHeight:b?.extensions?.cameraOpenResolution?.height,Video_send_packetsLostRateMax:round(b?.aggregated?.lossRateMax,6),Video_send_resolutionSwitches:JSON.stringify(b?.aggregated?.resolutionSwitches),Video_send_performanceEvents:limitRebaseAndStringifyEvents(g.localVideoPerformanceEvents,v.numPerformanceEvents,"timestamp",g.startTime),Video_send_Simulcast:JSON.stringify(g.simulcast?.video),Video_send_powerEfficientEncoderEvents:limitRebaseAndStringifyEvents(b?.extensions?.powerEfficientEncoderEvents,v.numPowerEfficientEncoderEvents,"timestamp",g.startTime),Video_send_powerEfficientEncoderEventOnCount:b?.extensions?.powerEfficientEncoderEventOnCount,Video_send_powerEfficientEncoderEventOffCount:b?.extensions?.powerEfficientEncoderEventOffCount,Sharing_recv_DurationSeconds:A?.aggregated?.duration,Sharing_recv_FreezeHistogram:JSON.stringify(A?.aggregated?.freezeCountHistogram),Sharing_recv_FreezeTimestamps:JSON.stringify(rebaseAndLimitHistogramTimestamps(A?.aggregated?.freezeTimestampsHistogram,g.startTime,v.numOfHistogramSamples)),Sharing_recv_LongestFreezeDuration:A?.aggregated?.longestFreeze,Sharing_recv_OngoingFreeze:A?.extensions?.isFrozen,Sharing_recv_TotalFreezeDuration:A?.aggregated?.totalFreezeDuration,Sharing_recv_RecvAvgFreezeDuration:A?.aggregated?.avgFreezeDuration,Sharing_recv_NumResolutionSwitches:A?.aggregated?.numResolutionSwitches,Sharing_recv_ResolutionDurations:JSON.stringify(A?.aggregated?.resolutionDurations),Sharing_recv_StreamsMax:g.recvVideoStreamCount.max,Sharing_recv_StreamsMin:g.recvVideoStreamCount.min,Sharing_recv_StreamsMode:g.recvVideoStreamCount.mode,Sharing_recv_TimeToFirstFrame:g.remoteVideoManager?.firstTimeToFirstFrameSharing,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:g.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_bitrateAvg:A?.aggregated?.bitrateAvg,Sharing_recv_bitrateMax:A?.aggregated?.bitrateMax,Sharing_recv_frameRateAvg:A?.aggregated?.avgFrameRate,Sharing_recv_jitterBufferAvgSize:A?.aggregated?.avgJitterBufferSize,Sharing_recv_packetsLostRateMax:round(A?.aggregated?.lossRateMax,6),Sharing_recv_FpsHarmonicAverage:A?.aggregated?.fpsHarmonicAverage,Sharing_recv_isRenderingEvents:JSON.stringify(limitArraySize22(g.remoteVideoManager?.isRenderingEvents.sharing,v.numIsRenderingEvents)),Sharing_recv_PreferredResolution:g.remoteVideoManager?.preferredResolution.sharing?.toString(),Sharing_recv_statsOnSubscribed:JSON.stringify(g.statsOnSubscribed.sharing),Sharing_SubscriptionEvents:JSON.stringify(rebaseTime(g.subscriptionManager?.sharing.events,"ts",g.startTime)),Sharing_SubscriptionCounters:JSON.stringify(g.subscriptionManager?.sharing.counters),Sharing_send_CaptureFramerateAvg:P?.aggregated?.captureFramerateAvg,Sharing_send_DurationSeconds:P?.aggregated?.duration,Sharing_send_MaxCapabilities:JSON.stringify(w),Sharing_send_MaxCapabilitiesErrors:JSON.stringify(O),Sharing_send_OvershootDurations:JSON.stringify({fs:P?.aggregated?.totalFsOvershootDuration,fps:P?.aggregated?.totalFpsOvershootDuration,br:P?.aggregated?.totalBrOvershootDuration}),Sharing_send_resolutionSwitches:P?.aggregated?.resolutionSwitches,Sharing_send_OvershootEvents:limitRebaseAndStringifyEvents(P?.aggregated?.overshootEvents,v.numOvershootEvents,"timestamp",g.startTime),Sharing_send_QpAvg:P?.aggregated?.qpAvg,Sharing_send_bitrateAvg:P?.aggregated?.bitrateAvg,Sharing_send_bitrateMax:P?.aggregated?.bitrateMax,Sharing_send_frameRateAvg:P?.aggregated?.frameRateAvg,Sharing_send_AllocateBWAvg:P?.aggregated?.bweAvg,Sharing_send_packetsLostRateMax:round(P?.aggregated?.lossRateMax,6),Sharing_send_Simulcast:JSON.stringify(g.simulcast?.sharing),Data_ProtocolCounters:JSON.stringify(g.dataChannel?.protocolCounters),Data_Error:g.dataChannel?.error,Data_SessionState:g.dataChannelSessionState?.toString(),Data_CreateChannelError:g.dataChannelCreationError,multipleVideoStreams:JSON.stringify(rebaseTime(g.multiViewStats,"startTime",g.startTime)),ReportedReceiveBandwidth:JSON.stringify(g.reportedReceiveBandwidth),ReportedSendBandwidth:JSON.stringify(g.reportedSendBandwidthLayouts),OvcToSubscriptions:JSON.stringify(g.ovcToSubscriptionEvents),EncodedStreamWorker:g.encodedStreamWorker,AudioCodecEvents:JSON.stringify(g.audioCodecEvents),HevcCodecSupport:JSON.stringify(g.codecSupport),MeetingScenario:JSON.stringify(g.negotiation.meetingScenario),IsTownHall:g.negotiation.isTownHall,InitialBWSeed:g.initialBWSeed,SentBWSeed:g.sentBWSeed,videoPerformanceEvent:JSON.stringify(g.videoPerformanceEvent),EarlyMedia_NumStatsPolls:g.earlyMediaNumStatsPolls})}var videoSendStatsFieldConverter=g=>removeUndefinedFields({id:g.outboundRTP.ssrc.toString(),codecName:g.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:g.extensions?.bitrate,jitter:g.remoteInboundRTP?.jitter,packets:g.outboundRTP.packetsSent,packetsPerSecond:g.extensions?.packetsPerSecond,packetsLost:g.remoteInboundRTP?.packetsLost,packetsLostPerSecond:g.extensions?.packetsLostPerSecond,rtt:g.remoteInboundRTP?.roundTripTime,frameRateInput:g.mediaSource?.framesPerSecond,frameWidthInput:g.mediaSource?.width,frameHeightInput:g.mediaSource?.height,framesEncoded:g.outboundRTP.framesEncoded,frameRateEncoded:g.extensions?.frameRateEncoded,framesSent:g.outboundRTP.framesSent,frameRateSent:g.extensions?.frameRateSent,frameWidthSent:g.outboundRTP.frameWidth,frameHeightSent:g.outboundRTP.frameHeight,keyFramesEncoded:g.outboundRTP.keyFramesEncoded,nackCount:g.outboundRTP.nackCount,firCount:g.outboundRTP.firCount,pliCount:g.outboundRTP.pliCount,transportId:g.outboundRTP.transportId,altLayouts:g.altLayouts?.map(videoSendStatsFieldConverter)}),videoRecvStatsFieldConverter=g=>removeUndefinedFields({id:g.inboundRTP.ssrc.toString(),codecName:g.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:g.extensions?.bitrate,jitter:g.inboundRTP.jitter,packets:g.inboundRTP.packetsReceived,packetsPerSecond:g.extensions?.packetsPerSecond,packetsLost:g.inboundRTP.packetsLost,packetsLostPerSecond:g.extensions?.packetsLostPerSecond,packetsDiscarded:g.inboundRTP.packetsDiscarded,rtt:g.remoteOutboundRTP?.roundTripTime,msi:g.renderer?.msi,jitterBufferMs:g.extensions?.jitterBufferMs,frameRateOutput:g.extensions?.frameRateDecoded,frameRateDecoded:g.extensions?.frameRateDecoded,frameRateReceived:g.extensions?.frameRateReceived,frameWidthReceived:g.inboundRTP.frameWidth,frameHeightReceived:g.inboundRTP.frameHeight,longestFreezeDuration:g.extensions?.longestFreeze,totalFreezeDuration:g.extensions?.totalFreezeDuration,framesReceived:g.inboundRTP.framesReceived,framesDropped:g.inboundRTP.framesDropped,framesDecoded:g.inboundRTP.framesDecoded,keyFramesDecoded:g.inboundRTP.keyFramesDecoded,nackCount:g.inboundRTP.nackCount,firCount:g.inboundRTP.firCount,pliCount:g.inboundRTP.pliCount,transportId:g.inboundRTP.transportId}),audioSendStatsFieldConverter=g=>removeUndefinedFields({id:g.outboundRTP.ssrc.toString(),codecName:g.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:g.extensions?.bitrate,jitter:g.remoteInboundRTP?.jitter,packets:g.outboundRTP.packetsSent,packetsPerSecond:g.extensions?.packetsPerSecond,packetsLost:g.remoteInboundRTP?.packetsLost,packetsLostPerSecond:g.extensions?.packetsLostPerSecond,packetsDiscarded:g.remoteInboundRTP?.packetsDiscarded,rtt:g.remoteInboundRTP?.roundTripTime,audioLevel:g.mediaSource?.audioLevel,transportId:g.outboundRTP.transportId}),audioRecvStatsFieldConverter=g=>removeUndefinedFields({id:g.inboundRTP.ssrc.toString(),codecName:g.codec?.mimeType?.split("/").pop().toUpperCase(),bitrate:g.extensions?.bitrate,jitter:g.inboundRTP.jitter,packets:g.inboundRTP.packetsReceived,packetsPerSecond:g.extensions?.packetsPerSecond,packetsLost:g.inboundRTP.packetsLost,packetsLostPerSecond:g.extensions?.packetsLostPerSecond,packetsDiscarded:g.inboundRTP.packetsDiscarded,rtt:g.remoteOutboundRTP?.roundTripTime,jitterBufferMs:g.extensions?.jitterBufferMs,audioLevel:g.inboundRTP.audioLevel,healedRatio:g.extensions?.healedRatio,transportId:g.inboundRTP.transportId}),dataChannelStatsFieldConverter=g=>removeUndefinedFields({id:g.id,state:g.state,dataChannelIdentifier:g.dataChannelIdentifier,messagesSent:g.messagesSent,bytesSent:g.bytesSent,messagesReceived:g.messagesReceived,bytesReceived:g.bytesReceived,sendBitrate:g.extensions?.sendBitrate,recvBitrate:g.extensions?.recvBitrate,messagesSentPerSecond:g.extensions?.sendMessageRate,messagesReceivedPerSecond:g.extensions?.recvMessageRate}),transportStatsFieldConverter=g=>removeUndefinedFields({id:g.id,rtt:g.selectedCandidatePair?.currentRoundTripTime,availableIncomingBitrate:g.selectedCandidatePair?.availableIncomingBitrate,availableOutgoingBitrate:g.selectedCandidatePair?.availableOutgoingBitrate,relayProtocol:g.selectedCandidatePair?.localCandidate?.relayProtocol,candidateType:`${g.selectedCandidatePair?.localCandidate?.candidateType??""}:${g.selectedCandidatePair?.remoteCandidate?.candidateType??""}`});function compileAudioSendReport(g){return(g.audio?.send??[]).map(audioSendStatsFieldConverter)}function compileAudioRecvReport(g){return(g.audio?.recv??[]).map(audioRecvStatsFieldConverter)}function compileVideoSendReport(g){return g.video?.send?.length?g.video.send.map(videoSendStatsFieldConverter):[]}function compileVideoRecvReport(g){return(g.video?.recv??[]).map(videoRecvStatsFieldConverter)}function compileScreenShareSendReport(g){return g.sharing?.send?.length?g.sharing.send.map(videoSendStatsFieldConverter):[]}function compileScreenShareRecvReport(g){return(g.sharing?.recv??[]).map(videoRecvStatsFieldConverter)}function compileDataChannelReport(g){return(g.data??[]).map(dataChannelStatsFieldConverter)}function compileTransportReport(g){return Object.values(g.transports??{}).map(transportStatsFieldConverter)}function compileMediaStatsReport(g){return{audio:{send:compileAudioSendReport(g),recv:compileAudioRecvReport(g)},video:{send:compileVideoSendReport(g),recv:compileVideoRecvReport(g)},screenShare:{send:compileScreenShareSendReport(g),recv:compileScreenShareRecvReport(g)},data:compileDataChannelReport(g),transports:compileTransportReport(g)}}function compileMediaStatsReportExtensions(g,f){const S=g.qualityManager&&limitArraySize22(deepClone(g.qualityManager.videoMaxCapabilitiesEvents),f.config.diagnostics.telemetryLimits.numCapabilitiesRequested),v=g.qualityManager&&limitArraySize22(deepClone(g.qualityManager.sharingMaxCapabilitiesEvents),f.config.diagnostics.telemetryLimits.numCapabilitiesRequested);return removeUndefinedFields({Video_SubscriptionEvents:JSON.stringify(g.subscriptionManager?.video.events),Sharing_SubscriptionEvents:JSON.stringify(g.subscriptionManager?.sharing.events),Video_send_MaxCapabilities:JSON.stringify(S),Sharing_send_MaxCapabilities:JSON.stringify(v),RelayCandidate:g.relayCandidate,Video_recv_TimeToFirstFrame:g.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_TimeToFirstFrame:g.remoteVideoManager?.firstTimeToFirstFrameSharing,Video_recv_TimeToFirstFrameSinceSubscriptionStart:g.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartVideo,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:g.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartSharing,IceServers:g.iceServers})}function compileMediaStatsReportMetrics(g,f,S){return removeUndefinedFields({DeviceEvents:JSON.stringify(rebaseTime(S.deviceManager.deviceTelemetryEvents.filter((g=>g.timestamp>f)),"timestamp",g.creationTime)),IceConnectedStateTime:1e4*g.iceConnectedStateTime})}function compileMetricsTelemetryReport(g,f,S,v){const C=v.config.diagnostics.telemetryLimits,_=g.webrtcSessions[g.webrtcSessions.length-1];return removeUndefinedFields({MediaLegId:g.mediaLegId,CreationTime:getHpTimeFromMillis(g.creationTime),CallNumber:g.callNumber,SessionId:g.sessionId,MultiParty:g.isMultiParty,ErrorType:g.error?.type??"none",ErrorDetail:g.error?.detail??"none",IncompatibleOffer:g.error?.type===qt.MEDIA_ERROR.incompatibleOffer,TerminationTime:getHpTimeFromMillis(g.terminationTime),TerminationReason_code:g.terminationReason?.code,TerminationReason_subCode:g.terminationReason?.subCode,TerminationReason_phrase:g.terminationReason?.phrase,TerminationReason_remoteTerminated:g.terminationReason?.remoteTerminated,TerminationReason_clientReasonPhrase:g.terminationReason?.clientReasonPhrase,TerminationReason_clientReasonSubCode:g.terminationReason?.clientReasonSubCode,TerminationReason_resultCategories:g.terminationReason?.resultCategories,CallDuration:getHpTimeFromMillis(g.duration),IceInitTime:getHpTimeFromMillis(g.iceInitTime),IceConnectedStateTime:getHpTimeFromMillis(g.iceConnectedStateTime),NegotiationCount:g.negotiationCount,RejectedNegotiationCount:g.rejectedNegotiationCount,InitialNegotiationCompleted:g.initialNegotiationCompleted,InitialNegotiationType:g.initialNegotiationType,FinalAnswerTime:getHpTimeFromMillis(g.finalAnswerTime),TransportReconnectedCount:g.transportReconnectedCount,RollbackNegotiation:JSON.stringify(g.rollbackNegotiation),Relay:g.relay?JSON.stringify(g.relay):void 0,ActiveModalities:JSON.stringify(g.activeModalities),AllowedAudioSend:g.allowedAudioSend,AllowedVideoSend:g.allowedVideoSend,AllowedScreensharingSend:g.allowedScreensharingSend,RelayManager:JSON.stringify(g.relayTimers),AuthTokenStats:JSON.stringify(g.authTokenFetcherStats),CallMutedRatio:g.callMutedRatio,CallOsMuted:getHpTimeFromMillis(g.callOsMuted),CallHwSilent:getHpTimeFromMillis(g.callHwSilent),CallSwMuted:getHpTimeFromMillis(g.callSwMuted),CallSpeakerMuted:getHpTimeFromMillis(g.callSpeakerMuted),CallIsSpeaking:getHpTimeFromMillis(g.callIsSpeaking),DtmfSuccess:g.dtmfSuccessCount,DtmfFailure:g.dtmfFailureCount,ContributingSourcesError:_.contributingSourcesError,ReconnectInProgress:g.reconnect?.isReconnecting,RetargetIncomingCount:g.reconnect?.retargetCount.incoming,RetargetOutgoingCount:g.reconnect?.retargetCount.outgoing,RetargetCompletedCount:g.reconnect?.retargetCount.completed,RetargetRejectedCount:g.reconnect?.retargetCount.rejected,EscalationAttemptedCount:g.reconnect?.escalationCount.attempted,EscalationCompletedCount:g.reconnect?.escalationCount.completed,EscalationRejectedCount:g.reconnect?.escalationCount.rejected,Elevation:JSON.stringify(g.elevation),ReconnectAttemptedCount:g.reconnect?.reconnectCount.attempted,ReconnectConnectedCount:g.reconnect?.reconnectCount.connected,ReconnectAttempts:limitRebaseAndStringifyEvents(g.reconnect?.records,C.numReconnects,"startTime",g.creationTime),NetworkEvents:limitRebaseAndStringifyEvents(g.reconnect?.tmpRecords,C.numNetworkEvents,"startTime",g.creationTime),NoIceCandidatesGoodEventCount:g.noIceCandidatesEventCount.good,NoIceCandidatesBadEventCount:g.noIceCandidatesEventCount.bad,NoRelayIceCandidatesGoodEventCount:g.noRelayIceCandidatesEventCount.good,NoRelayIceCandidatesBadEventCount:g.noRelayIceCandidatesEventCount.bad,MicrophoneInUseGoodEventCount:g.microphoneInUseEventCount.good,MicrophoneInUseBadEventCount:g.microphoneInUseEventCount.bad,CameraInUseGoodEventCount:g.cameraInUseEventCount.good,CameraInUseBadEventCount:g.cameraInUseEventCount.bad,CameraFreezeStartEventCount:g.cameraFreezeEventCount.start,CameraFreezeEndEventCount:g.cameraFreezeEventCount.end,NetworkRecvGood:g.networkRecvUFD.good,NetworkRecvGoodRatio:g.networkRecvUFD.goodRatio,NetworkRecvPoor:g.networkRecvUFD.poor,NetworkRecvPoorRatio:g.networkRecvUFD.poorRatio,NetworkRecvBad:g.networkRecvUFD.bad,NetworkRecvBadRatio:g.networkRecvUFD.badRatio,NetworkSendGood:g.networkSendUFD.good,NetworkSendGoodRatio:g.networkSendUFD.goodRatio,NetworkSendPoor:g.networkSendUFD.poor,NetworkSendPoorRatio:g.networkSendUFD.poorRatio,NetworkSendBad:g.networkSendUFD.bad,NetworkSendBadRatio:g.networkSendUFD.badRatio,Connection_Downlink:sampleseries(_.networkInfo,(g=>g.downlink)),Connection_EffectiveType:_.networkInfo.map((g=>g.effectiveType)).filter((g=>g)).join(","),Connection_Rtt:sampleseries(_.networkInfo,(g=>g.rtt)),Connection_SaveData:getLast(_.networkInfo)?.saveData,RawOutputAudioAccessAttempted:g.rawMedia.audio.recv.numAttempts,RawOutputAudioAccessDurationRatio:g.rawMedia.audio.recv.durationRatio,RawInputAudioOverrideAttempted:g.rawMedia.audio.send.numAttempts,RawInputAudioOverrideDurationRatio:g.rawMedia.audio.send.durationRatio,ZeroCaptureDevicesEnumeratedEventRatio:g.zeroCaptureDevicesRatio,ZeroRenderDevicesEnumeratedEventRatio:g.zeroRenderDevicesRatio,DeviceCaptureNotFunctioningEventRatio:g.deviceCaptureFailuresRatio,DeviceRenderNotFunctioningEventRatio:g.deviceRenderFailuresRatio,UFDs:limitRebaseAndStringifyEvents(g.ufds,C.numUFDs,"timestamp",g.creationTime),remoteUFDs:limitRebaseAndStringifyEvents(g.remoteUfds,C.numUFDs,"timestamp",g.creationTime),MediaQosEnabled:S.configuration.mediaConfig?.enableMediaQoS??!1,PortRangeConfigured:!!S.configuration.mediaConfig?.mediaPortRanges,hardwareConcurrency:S.configuration.userAgentConfig.hardwareConcurrency,ETag:g.ETag,ConfigIds:g.configIds,GPUName:S.configuration.userAgentConfig.unmaskedGlRenderer,PermissionStates:JSON.stringify(S.deviceManager.permissionStates),DeviceList:JSON.stringify(S.deviceManager.deviceList),DeviceListDebug:JSON.stringify(S.deviceManager.deviceDebugStrings),DevicesChangeCount:g.deviceManager.devicesChangeCount,DevicesPollChangeCount:g.deviceManager.devicesPollChangeCount,DeviceSelectionChangeCount:g.deviceManager.deviceSelectionChangeCount,DeviceSelectionChangeFromInterfaceCount:g.deviceManager.deviceSelectionChangeCountFromInterface,DevicesCount:JSON.stringify(S.deviceManager.devicesCount),UsedMicrophone:S.deviceManager.usedDevices?.microphone,UsedSpeaker:S.deviceManager.usedDevices?.speaker,UsedCamera:S.deviceManager.usedDevices?.camera,DeviceEvents:limitRebaseAndStringifyEvents(S.deviceManager.deviceTelemetryEvents.filter((g=>g.timestamp>f)),C.numDeviceEvents,"timestamp",g.creationTime),VideoEffects:limitRebaseAndStringifyEvents(S.deviceManager.videoEffectsEvents.filter((g=>g.timestamp>f)),C.numVideoEffectsEvents,"timestamp",g.creationTime),AudioEffects:limitRebaseAndStringifyEvents(S.deviceManager.audioEffectsEvents.filter((g=>g.timestamp>f)),C.numAudioEffectsEvents,"timestamp",g.creationTime),WorkerEvents:limitRebaseAndStringifyEvents(S.deviceManager.workerEvents.filter((g=>g.timestamp>f)),C.numWorkerEvents,"timestamp",g.creationTime),MediaByPassEnabled:!!S.configuration.mediaConfig.enableMediaBypass,CallConstraints:JSON.stringify(g.callConstraints),DominantSpeaker:JSON.stringify(generateDominantSpeakerReport(g.dominantSpeaker,g.terminationTime)),AudioSourceNumOfReopenRequests:g.deviceManager.audioSourceNumOfReopenRequests||void 0,AudioSourceNumOfSuccessfulReopens:g.deviceManager.audioSourceNumOfSuccessfulReopens||void 0,AudioCaptureErrorCodeFlagsInit:g.deviceManager.audioCaptureDeviceErrorFlag,AudioRenderErrorCodeFlagsInit:g.deviceManager.audioRenderDeviceErrorFlag,AudioSinkNumOfReopenRequests:g.audioRenderer.sinkNumOfReopenRequests,AudioSinkNumOfSuccessfulReopens:g.audioRenderer.sinkNumOfSuccessfulReopens,CallSetupTimeTracker:JSON.stringify(g.webrtcSessions[0].negotiation.callSetupTimeReport),LastSessionSetupTimeTracker:g.webrtcSessions.length>1?JSON.stringify(_.negotiation.callSetupTimeReport):void 0,BatteryLevel:g.batteryLevel})}function getHpTimeFromMillis(g){return 1e4*g}function generateDominantSpeakerReport(g,f=Number(new Date)){if(!g)return;const S=deepClone(g);return g.lastMsgDate&&(g.timeSinceLastMsg=g.lastMsgDate-f),delete S.lastMsgDate,delete S.lastHistory,removeUndefinedFields(S)}function getValue(g,f,S=0){const v=f.filter((g=>void 0!==g));let C;switch(g){case"Difference":C=v[v.length-1]-v[0];break;case"Average":C=v.reduce(((g,f)=>g+f),0)/v.length;break;case"LastValue":C=v[v.length-1]}return C||0===C?`${"number"==typeof C?+C.toFixed(S):C}`:void 0}function filterStats(g,f,S){return(S?g.map((g=>g?.[f]?.[S])):g.map((g=>g?.[f]))).filter((g=>void 0!==g)).reduce(((g,f)=>g.concat(f)),[])}function findTransportStats(g){const f=g.find((g=>g?.transports));return f?f.transports[Object.keys(f.transports)[0]]:void 0}function getVideoProcessing(g){const f=g[g.length-1]?.extensions?.powerEfficient;return void 0===f?"":f?"hw":"sw"}function getMediaDirection(g,f){return g&f?"Bidirectional":g?"ReceiveFromPeer":f?"SendToPeer":"Inactive"}function getSendActivityState(g){const f=g[g.length-1]?.extensions?.callIsMuted,S=g[g.length-1]?.extensions?.rawInputVolume;return f?"0":!f&&S>0?"2":f||0!==S?void 0:"1"}function compileAudioReport2(g,f){const S=filterStats(g,"audio","send"),v=filterStats(g,"audio","recv"),C=findTransportStats(g);if(S.length||v.length)return removeUndefinedFields({mediaType:"Audio",mediaDirection:getMediaDirection(v.length,S.length),"Received BW estimate":getValue("Average",v.map((g=>g?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Recv Loss Rate (Avg)":getValue("LastValue",v.map((g=>g?.extensions?.lossRate/100)),3),"Rtp Packets Received":getValue("Difference",v.map((g=>g?.inboundRTP.packetsReceived))),"Rtp Packet Sent":getValue("Difference",S.map((g=>g?.outboundRTP.packetsSent))),"Sent BW estimate":getValue("Average",S.map((g=>g?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Audio Codec":getValue("LastValue",S.map((g=>g?.codec?.mimeType)))?.split("/").pop(),"Send RTT (Avg)":getValue("LastValue",S.map((g=>g?.extensions?.rttAvg))),"Audio NW jitter avg":getValue("LastValue",v.map((g=>g?.extensions?.jitterAvg)),3),"Audio send bps":getValue("Average",S.map((g=>g?.extensions?.bitrate))),"JB delay (ms)":getValue("LastValue",v.map((g=>g?.extensions?.jitterBufferDelayMs))),"Recv Audio Codec":getValue("LastValue",v.map((g=>g?.codec?.mimeType)))?.split("/").pop(),"Current Render Device Name":f?.speaker,"Current Capture Device Name":f?.microphone,"Latest Network Type":C?.selectedCandidatePair?.localCandidate?.networkType,"Latest Transport Protocol":C?.selectedCandidatePair?.localCandidate?.protocol,"Latest Reflexive Address":ipAddressConverter(C?.extensions?.reflexiveLocalIP),"Local Address":ipAddressConverter(C?.selectedCandidatePair?.localCandidate?.ip),"Local short-term Healed Data Ratio":getValue("LastValue",v.map((g=>g?.extensions?.healedRatio))),"Send activity (0=muted; 1=inactive; 2=active)":getSendActivityState(S)})}function formatVideoStats(g){const f={},formatStats=S=>{g.map((g=>g?.video?.[S])).forEach((g=>{g?.forEach((g=>{var v;const C=g?.mediaEntity?.remoteSsrc;f[C]??(f[C]={}),(v=f[C])[S]??(v[S]=[]),f[C][S].push(g)}))}))};return formatStats("recv"),formatStats("send"),f}function compileVideoReport(g,f){const S=[],v=formatVideoStats(g);for(const{send:g,recv:C}of Object.values(v)){let v={mediaType:"Camera",mediaDirection:getMediaDirection(C?.length,g?.length)};C&&(v={...v,...compileVideoRecvReport2(C)}),g&&(v={...v,...compileVideoSendReport2(g,f)}),S.push(removeUndefinedFields(v))}return S}function compileVideoSendReport2(g,f){const S=getValue("LastValue",g.map((g=>g?.codec?.mimeType)))?.split("/").pop(),v=S?S+` ${getVideoProcessing(g)}`:void 0;return{"Rtp Packet Sent":getValue("Difference",g.map((g=>g?.outboundRTP.packetsSent))),"Sent BW estimate":getValue("Average",g.map((g=>g?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Current Bitrate":getValue("Average",g.map((g=>g?.extensions?.bitrate))),"Allocated Send Bandwidth Average":getValue("LastValue",g.map((g=>g?.extensions?.bitrateAvg))),"Send Actual Height":getValue("LastValue",g.map((g=>g?.outboundRTP.frameHeight))),"Send Actual Width":getValue("LastValue",g.map((g=>g?.outboundRTP.frameWidth))),"Send Current Frame Rate":getValue("Average",g.map((g=>g?.extensions?.frameRateSent))),"Send RTT (Avg)":getValue("LastValue",g.map((g=>g?.extensions?.rttAvg))),"Sent Codec Name":v,"Webcam Freeze Intervals":getValue("LastValue",g.map((g=>g?.extensions?.captureFreezeIntervalsCount))),"Current Capture Device Name":f?.camera,"Number of Sync Frame Request per Minute":getValue("LastValue",g.map((g=>g?.extensions?.pliRate)))}}function compileVideoRecvReport2(g){const f=getValue("LastValue",g.map((g=>g?.mediaEntity?.xSourceStreamId))),S=getValue("LastValue",g.map((g=>g?.codec?.mimeType)))?.split("/").pop(),v=S?S+` ${getVideoProcessing(g)}`:void 0;return{"Recv Loss Rate (Avg)":getValue("LastValue",g.map((g=>g?.extensions?.lossRate)),3),"Received BW estimate":getValue("Average",g.map((g=>g?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Receive Current Bitrate":getValue("Average",g.map((g=>g?.extensions?.bitrate))),"Rtp Packets Received":getValue("Difference",g.map((g=>g?.inboundRTP.packetsReceived))),"Receive Actual Height":getValue("LastValue",g.map((g=>g?.inboundRTP.frameHeight))),"Receive Actual Width":getValue("LastValue",g.map((g=>g?.inboundRTP.frameWidth))),"Receive Current Frame Rate":getValue("Average",g.map((g=>g?.extensions?.frameRateReceived))),"Received Codec Name":v,"Received Total Freeze Fraction (ms per min)":getValue("LastValue",g.map((g=>g?.extensions?.totalFreezeFraction))),videoSourceId:f?parseInt(f):void 0,"Received Fps Time Weighted Harmonic Average":getValue("LastValue",g.map((g=>g?.extensions?.fpsHarmonicAverage)))}}function compileSharingReport(g){const f=filterStats(g,"sharing","send"),S=filterStats(g,"sharing","recv");if(!S.length&&!f.length)return;let v={mediaType:"AppSharing",mediaDirection:"Bidirectional","Render Device Name":""};return S.length&&(v={...v,...compileVideoRecvReport2(S)}),f.length&&(v={...v,...compileVideoSendReport2(f,{microphone:void 0,camera:"Screen sharing",speaker:void 0})}),removeUndefinedFields(v)}function compileReports(g,f,S){const v=compileAudioReport2(g,f);v&&S.channels.push(v);const C=compileVideoReport(g,f);C.length&&S.channels.push(...C);const _=compileSharingReport(g);_&&S.channels.push(_)}function compileTeamsRealtimeTelemetryReport(g,f){const S=filterStats(g,"inactiveTracks"),v={channels:[]};return compileReports(g,f,v),S.length&&compileReports(S,void 0,v),v}function compileVideoReportForE2E(g,f,S,v,C){return removeUndefinedFields({recv:removeUndefinedFields({id:S?.inboundRTP.id,ssrc:S?.inboundRTP.ssrc,mediaType:S?.inboundRTP.mediaType??S?.inboundRTP.kind,bytes:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.bytesReceived),C),packets:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.packetsReceived),C),packetsLost:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.packetsLost),C),codec:S?.codec?.mimeType.split("/").pop(),codecReport:S?.aggregated?.codecReport,framesDecoded:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.framesDecoded),C),height:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.frameHeight),C),width:sampleseriesArr(f[g]?.recv,(g=>g.inboundRTP.frameWidth),C),frameRate:sampleseriesArr(f[g]?.recv,(g=>g.extensions?.frameRateReceived),C)}),send:removeUndefinedFields({id:v?.outboundRTP.id,ssrc:v?.outboundRTP.ssrc,mediaType:v?.outboundRTP.mediaType??v?.outboundRTP.kind,bytes:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.bytesSent),C),packets:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.packetsSent),C),packetsLost:sampleseriesArr(f[g]?.send,(g=>g.remoteInboundRTP?.packetsLost),C),codec:v?.codec?.mimeType.split("/").pop(),framesEncoded:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.framesEncoded),C),heightInput:v?.mediaSource?.height,widthInput:v?.mediaSource?.width,height:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.frameHeight),C),width:sampleseriesArr(f[g]?.send,(g=>g.outboundRTP.frameWidth),C),frameRate:sampleseriesArr(f[g]?.send,(g=>g.extensions?.frameRateSent),C)})})}function compileAudioReportForE2E(g,f,S,v){return removeUndefinedFields({recv:removeUndefinedFields({id:f?.inboundRTP.id,ssrc:f?.inboundRTP.ssrc,mediaType:f?.inboundRTP.mediaType??f?.inboundRTP.kind,bytes:sampleseriesArr(g.audio?.recv,(g=>g.inboundRTP.bytesReceived),v),packets:sampleseriesArr(g.audio?.recv,(g=>g.inboundRTP.packetsReceived),v),packetsLost:sampleseriesArr(g.audio?.recv,(g=>g.inboundRTP.packetsLost),v),codec:f?.codec?.mimeType.split("/").pop(),audioLevel:sampleseriesArr(g.audio?.recv,(g=>Math.floor(65535*g.inboundRTP.audioLevel)),v)}),send:removeUndefinedFields({id:S?.outboundRTP.id,ssrc:S?.outboundRTP.ssrc,mediaType:S?.outboundRTP.mediaType??S?.outboundRTP.kind,bytes:sampleseriesArr(g.audio?.send,(g=>g.outboundRTP.bytesSent),v),packets:sampleseriesArr(g.audio?.send,(g=>g.outboundRTP.packetsSent),v),packetsLost:sampleseriesArr(g.audio?.send,(g=>g.remoteInboundRTP?.packetsLost),v),codec:S?.codec?.mimeType.split("/").pop(),audioLevel:sampleseriesArr(g.audio?.send,(g=>Math.floor(65535*g.aggregated.audioLevel)),v)})})}function compileE2EDiagReport(g,f,S,v,C){const _=g.aggregatedModalityStats,T=getLast(_.audio?.recv),I=getLast(_.audio?.send),b=getLast(_.video?.recv),A=getLast(_.video?.send),P=getLast(_.sharing?.recv),R=getLast(_.sharing?.send),M=[],w=[];return g.statsOnSubscribed.video?.forEach((g=>M.push(g))),g.statsOnSubscribed.sharing?.forEach((g=>w.push(g))),removeUndefinedFields({multipleVideoStreams:g.multiViewStats,WebRTCStats_ssrc:removeUndefinedFields({audio:compileAudioReportForE2E(_,T,I,C),video:compileVideoReportForE2E("video",_,b,A,C),sharing:compileVideoReportForE2E("sharing",_,P,R,C)}),CallSwMuted:1e3*f.callSwMuted,DeviceEvents:rebaseTime(S.deviceManager.deviceTelemetryEvents.filter((g=>g.timestamp>v)),"timestamp",f.creationTime),VideoEffects:rebaseTime(S.deviceManager.videoEffectsEvents.filter((g=>g.timestamp>v)),"timestamp",f.creationTime),AudioEffects:rebaseTime(S.deviceManager.audioEffectsEvents.filter((g=>g.timestamp>v)),"timestamp",f.creationTime),statsErrors:f.statsErrors,WorkerEvents:rebaseTime(S.deviceManager.workerEvents.filter((g=>g.timestamp>v)),"timestamp",f.creationTime)})}var iT=class{constructor(g,f){this.rootRef=g,this.configProvider=f}get rawRootRef(){return this.rootRef}getSessionTelemetry(g){const f=this.getLatestSession(g);if(!f)return;const S={metrics:{},Extensions:{}},v=Jt();try{const g=f.callNumber>1?this.rootRef.sessions.find((g=>f.callNumber-1===g.callNumber)):void 0,v=g?.terminationTime??0,C=f.webrtcSessions[f.webrtcSessions.length-1];S.metrics=compileMetricsTelemetryReport(f,v,this.rootRef,this.configProvider),S.Extensions=compileExtensionsTelemetryReport(C,this.configProvider,f.statsErrors)}catch(g){f[Q_].addStatsError("DiagnosticsReport:getSessionTelemetry",stringifyObject2(g)),S.Extensions.WebRTCStats_statsErrors=JSON.stringify(f.statsErrors)}return S.metrics.ReportGenerationTimeMs=round(Jt()-v),S}getTeamsRealtimeTelemetry(g){const f=this.getLatestSession(g);if(f)try{const g=f.webrtcSessions[f.webrtcSessions.length-1],S=this.configProvider.config.diagnostics.teamsRealtimeTelemetry.pollingInterval;return compileTeamsRealtimeTelemetryReport(g.statsReports.slice(g.statsReports.length-S),this.rootRef.deviceManager.rawUsedDevices)}catch(g){throw f[Q_].addStatsError("DiagnosticsReport:getRealTimeTelemetry",stringifyObject2(g)),g}}getMediaSessionStats(g){const f=this.getLatestSession(g);if(f)try{const g=f.callNumber>1?this.rootRef.sessions.find((g=>f.callNumber-1===g.callNumber)):void 0,S=g?.terminationTime??0,v=f.webrtcSessions[f.webrtcSessions.length-1],C=v?.statsReports.length?v.statsReports[v.statsReports.length-1]:void 0,_=C?compileMediaStatsReport(C):void 0;return _&&(_.extensions=compileMediaStatsReportExtensions(v,this.configProvider),_.metrics=compileMediaStatsReportMetrics(f,S,this.rootRef)),_}catch(g){throw f[Q_].addStatsError("DiagnosticsReport:getMediaSessionStats",stringifyObject2(g)),g}}getDiagnosticsForE2eTests(g){const f=this.getLatestSession(g);let S={statsErrors:[]};if(f){try{const g=f.webrtcSessions[f.webrtcSessions.length-1],v=f.callNumber>1?this.rootRef.sessions.find((g=>f.callNumber-1===g.callNumber)):void 0,C=v?.terminationTime??0;S=compileE2EDiagReport(g,f,this.rootRef,C,this.configProvider.config.diagnostics.collectionLimits.numSamplesForE2E)}catch(g){const v="DiagnosticsReport:getDiagnosticsForE2eTests",C=stringifyObject2(g);f[Q_].addStatsError(v,C),arrayLimitedPush22(S.statsErrors,{origin:v,error:C,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors)}return S}}getLatestSession(g){return this.rootRef.sessions.filter((f=>f.sessionId===g)).sort(((g,f)=>g.callNumber-f.callNumber)).pop()}},nT=class{constructor(g,f){this.configProvider=g,this.deviceManagerDiagnostics=f,this.root={creationTime:Date.now(),numTotalSessions:0,deviceManager:this.deviceManagerDiagnostics.getObjectRef(),configuration:{stackConfig:this.configProvider.stackConfig,defaultConfig:this.configProvider.defaultConfig,mediaConfig:{},userAgentConfig:{isAudioOutputSelectionSupported:this.configProvider.userAgentConfig.isAudioOutputSelectionSupported,isBrowserRollbackSupported:this.configProvider.userAgentConfig.isBrowserRollbackSupported,hardwareConcurrency:oa.hardwareConcurrency,unmaskedGlRenderer:oa.unmaskedGlRenderer,hasMediaApi:oa.hasMediaApi(),hasCapabilitiesApi:oa.hasCapabilitiesApi(),hasUnifiedPlanSupport:void 0},consoleOverrides:this.configProvider.consoleOverrides,fullConfig:deepClone(this.configProvider.config),ecsConfigUpdates:[]},browserInfo:et.getBrowserInfo(),sessions:[]},this.diagnosticsReport=new iT(this.root,this.configProvider),this.configProvider.on("newConfigReceived",((g,f,S)=>{this.root.configuration.ecsConfigUpdates.push({timestamp:Date.now(),etag:f,configIds:S,config:g})})),this.configProvider.on("configUpdated",(()=>{this.root.configuration.consoleOverrides=this.configProvider.consoleOverrides,this.root.configuration.fullConfig=deepClone(this.configProvider.config)}))}get reportGenerator(){return this.diagnosticsReport}get rootRef(){return this.root}set mediaConfig(g){this.root.configuration.mediaConfig=g}newSession(g,f,S){this.root.configuration.userAgentConfig.hasUnifiedPlanSupport=this.configProvider.mediaConfig.simulcastSessionEnabled;const v=new X_(S,g,this.diagnosticsReport,this.root.deviceManager,++this.root.numTotalSessions,f);return arrayLimitedPush22(this.root.sessions,v.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numSessions),v}},rT=class _JamaLogger{constructor(g,f){this.safe=g,this.unsafe=f,this.safe||(this.safe=this.unsafe)}warn(...g){this.unsafe.warn(...g)}error(...g){this.unsafe.error(...g)}debug(...g){this.unsafe.debug(...g)}info(...g){this.unsafe.info(...g)}createChild(g){return new _JamaLogger(this.safe.createChild(g),this.unsafe.createChild(g))}},sT=M,aT=class{constructor(g){this.logger=g,this.extensionId="nkeimhogjdpnpccoofpliimaahmaaome",this.editorExtensionId="ncbjelpjchkpbikbpkcchkhkblodoama",this.logId="TeamsWebRTCLogs",this.loggingState="unknown",this.connectionCount=0,window.webRtcInternalsCollector=this}get isExtensionAvailable(){return"unavailable"!==this.loggingState}async updateSessionCount(g){this.isExtensionAvailable&&(0===this.connectionCount&&1===g?("stopped"===this.loggingState&&await this.discardLogs(),await this.initialStartLogging()):0===g&&await this.stopLogging(),this.connectionCount=g)}async collect(){return this.isExtensionAvailable?this.collectPromise?this.collectPromise:this.collectPromise=new Promise((async g=>{try{this.connectionCount>0&&(this.logger.safe.info(`Stopping logger for gathering, open connections: ${this.connectionCount}`),await this.stopLogging()),await this.storeLogs();const f=await this.gatherFromStorage();this.connectionCount>0&&await this.continueLogging(),g(f.length>0?f.join("\r\n"):"")}catch(f){this.logger.safe.error("Error while collecting logs",f),g(JSON.stringify(f))}this.collectPromise=void 0})):""}async initialStartLogging(){try{await this.startLogging()}catch(g){if(g?.includes("A log is already open"))try{const f=g.match(/State=(\w+)/);await this.cleanState(f?.[1]),await this.startLogging()}catch(g){this.logger.safe.error("Error while starting logging at cleanup phase",g),this.loggingState="unknown"}else this.logger.safe.error("Error while starting logging",g),this.loggingState="unavailable"}}async continueLogging(){try{await this.startLogging()}catch(g){this.logger.safe.error("Error while continuing logging",g),this.loggingState="stopped"}}async startLogging(){await this.sendMessage(this.extensionId,{method:"logging.start"}),this.logger.safe.info("Logging started"),this.loggingState="started"}async cleanState(g){try{if("started"===g)await this.stopLogging(),await this.discardLogs();else{if("stopped"!==g)throw new Error(`Unexpected logging state: ${g}`);await this.discardLogs()}}catch(g){this.logger.safe.error("Error while cleaning state",g)}}async stopLogging(){try{await this.sendMessage(this.extensionId,{method:"logging.stop"}),this.logger.safe.info("Logging stopped"),this.loggingState="stopped"}catch(g){this.logger.safe.error("Error while stopping logging",g)}}async discardLogs(){try{await this.sendMessage(this.extensionId,{method:"logging.discard"}),this.logger.safe.info("Logs discarded"),this.loggingState="closed"}catch(g){this.logger.safe.error("Error while discarding logs",g)}}async storeLogs(){try{await this.sendMessage(this.extensionId,{method:"logging.store",logId:this.logId}),this.logger.safe.info(`Logs stored to ${this.logId}`),this.loggingState="closed"}catch(g){this.logger.safe.error("Error while storing logs",g)}}async gatherFromStorage(){const g=[];let f={offset:0};do{f=await this.sendMessage(this.editorExtensionId,{api:"getWebRtcLog",logId:this.logId,offset:f.offset}),g.push(f.data),this.logger.safe.info(`Batch gathered with offset: ${f.offset}, moreData: ${f.moreData}`)}while(f.moreData);return this.logger.safe.info("Finished gathering"),g}sendMessage(g,f){return new Promise(((S,v)=>{const C=chrome.runtime;C.sendMessage(g,f,(g=>{if(!g||g?.error){const S=g?JSON.stringify(g.error):C.lastError;v(`sendMessage ${JSON.stringify(f)} failed with error: ${S}`)}S(g)}))}))}},oT=(()=>{let g;function getInstance(f,S){return S.config.enableWebRtcInternalsLogs&&et.isBrowser("EdgeAnaheim")&&chrome?.runtime?(g||(g=new aT(f)),g):(f.safe.info("WebRTC internal logging is disabled"),{collect:()=>Promise.resolve(""),updateSessionCount:()=>Promise.resolve()})}return{getInstance:getInstance}})(),lT=oT,cT=class{getId(){return 0}getDeviceId(){return qt.EMPTY_DEVICE_ID}getPreviewAsync(g,f){return Promise.resolve(null)}getDescription(){return"display"}getType(){return 1}getIcon(g,f){return Promise.resolve(null)}},dT=class{constructor(g){this.descr=g}getId(){return 0}getDeviceId(){return this.descr.browserId}getPreviewAsync(g,f){return Promise.resolve(null)}getDescription(){return this.descr.label}getType(){return 3}getIcon(g,f){return Promise.resolve(null)}},hT=class{constructor(g){this.deviceManager=g,this.sharingSource=new cT}onScreensChanged(g){return{dispose:()=>{}}}enumerateScreensAsync(){return Promise.resolve([this.sharingSource])}enumerateWindowsAsync(){return Promise.resolve([])}async enumerateCamerasAsync(){return(await this.deviceManager.enumerateDevicesAsync()).filter((g=>"camera"===g.kind)).map((g=>new dT(g)))}},uT=class{constructor(g){this.configProvider=g,this.data={records:[],tmpRecords:[],isReconnecting:!1,networkRecoveredCount:0,disconnectedRecoveredCount:0,reconnectCount:{attempted:0,connected:0},retargetCount:{incoming:0,outgoing:0,completed:0,rejected:0},escalationCount:{attempted:0,completed:0,rejected:0}}}registerState(g){const f="connected"===g?this.activeTmpRecord:this.getTmpRecord();f&&f.events[f.events.length-1]?.type!==g&&(f.events.push({type:g,time:Date.now()-f.startTime}),"networkOnline"===g?this.data.networkRecoveredCount++:"connected"===g&&this.data.disconnectedRecoveredCount++,"reconnect"!==g&&"connected"!==g||(f.endTime=Date.now()-f.startTime,this.activeTmpRecord=null))}registerReconnectAttempt(g){this.activeRecord&&(this.activeAttempt={direction:g,startTime:Date.now()-this.activeRecord.startTime,status:!1},this.data.isReconnecting=!0,arrayLimitedPush2(this.activeRecord.attempts,this.activeAttempt,this.configProvider.config.diagnostics.collectionLimits.numReconnectRecords))}registerReconnectAttemptStatus(g){"completed"===g&&(this.data.isReconnecting=!1),this.activeAttempt&&this.activeRecord&&(this.activeAttempt.endTime=Date.now()-this.activeRecord.startTime,this.activeAttempt.status="completed"===g)}registerReconnect(g){if(this.data.reconnectCount[g]++,this.data.isReconnecting="attempted"===g,"attempted"===g){if(this.activeRecord)return;this.activeRecord={startTime:Date.now(),attempts:[]},arrayLimitedPush2(this.data.records,this.activeRecord,this.configProvider.config.diagnostics.collectionLimits.numReconnects)}else if("connected"===g){if(!this.activeRecord)return;this.activeTmpRecord&&this.registerState("connected"),this.activeRecord.endTime=Date.now()-this.activeRecord.startTime,this.activeRecord=void 0,this.activeAttempt=void 0}}registerRetarget(g){this.data.retargetCount[g]++}registerEscalation(g){this.data.escalationCount[g]++}getObject(){return this.data}getTmpRecord(){return(!this.activeTmpRecord||this.activeTmpRecord.endTime>0)&&(this.activeTmpRecord={startTime:Date.now(),events:[]},this.data.tmpRecords.push(this.activeTmpRecord)),this.activeTmpRecord}},gT=class{constructor(){}process(g){return this.mediaLegId=g||this.mediaLegId||uniqueId().toUpperCase(),this.mediaLegId}},pT=class{constructor(g,f){this.relayManager=g,this.diagnostics=f}initialize(){}setRelayOverride(){}async queryRelaysAsync(g){const f=await this.relayManager.queryRelaysAsync(g);return f.length>0&&(this.diagnostics.relay=f[0]),f}getStats(){return this.relayManager.getStats?.()??{stats:{unavailable:"1"}}}getAuthTokenStats(){return this.relayManager.getAuthTokenStats()}},mT=class{constructor(g,f,S){this.stats=g,this.diag=f,S&&f&&(S.reconnect=f.getObject())}registerState(g){this.diag?.registerState(g)}registerReconnectAttempt(g){this.stats.registerReconnectAttempt(g),this.diag?.registerReconnectAttempt(g)}registerReconnectAttemptStatus(g){switch(g){case"completed":this.stats.registerReconnectAttemptCompleted();break;case"rejected":this.stats.registerReconnectAttemptRejected()}this.diag?.registerReconnectAttemptStatus(g)}registerReconnect(g){switch(g){case"attempted":this.stats.registerReconnectAttempted();break;case"connected":this.stats.registerReconnectConnected()}this.diag?.registerReconnect(g)}registerRetarget(g){switch(g){case"completed":this.stats.registerRetargetCompleted();break;case"rejected":this.stats.registerRetargetRejected();break;case"incoming":this.stats.registerRetargetIncoming();break;case"outgoing":this.stats.registerRetargetOutgoing()}this.diag?.registerRetarget(g)}registerEscalation(g){switch(g){case"attempted":this.stats.registerEscalationStart();break;case"completed":this.stats.registerEscalationCompleted();break;case"rejected":this.stats.registerEscalationRejected()}this.diag?.registerEscalation(g)}},fT=class{constructor(g){this.initialCallbacks=g,this.queueCallbacks={onTerminated:this.genCallback(this.initialCallbacks.onTerminated),onSessionErrorOccurred:this.genCallback(this.initialCallbacks.onSessionErrorOccurred),onNegotiationRequired:this.genCallback(this.initialCallbacks.onNegotiationRequired),onAudioStateChanged:this.genCallback(this.initialCallbacks.onAudioStateChanged),onAudioHwSilentChanged:this.genCallback(this.initialCallbacks.onAudioHwSilentChanged),onTransportDisconnected:this.genCallback(this.initialCallbacks.onTransportDisconnected),onTransportConnected:this.genCallback(this.initialCallbacks.onTransportConnected),onTransportInitialized:this.genCallback(this.initialCallbacks.onTransportInitialized),onTransportFailed:this.genCallback(this.initialCallbacks.onTransportFailed),onUpdateMediaDescriptionsRequired:this.genCallback(this.initialCallbacks.onUpdateMediaDescriptionsRequired),onTeamsRealtimeTelemetryReport:this.genCallback(this.initialCallbacks.onTeamsRealtimeTelemetryReport)},this.queue=[]}flush(){this.queue.forEach((g=>{g.method.apply(null,g.args)})),this.clear()}clear(){this.queue=[]}genCallback(g){return(...f)=>this.queue.push({method:g,args:f})}},ST=class{constructor(g,f){this.relayConfig=g,this.logger=f}async ensureOnline(){if(0===this.relayConfig.length)return this.logger.safe.warn("No TURN servers defined"),0;if(this.probeDeferred)return this.probeDeferred.promise;this.logger.safe.info(`Starting TURN probes with ${JSON.stringify(this.relayConfig[0].urls)}`),this.checkStart=Date.now();let g=0;this.probeDeferred=new dt;const check=async()=>{await this.performCheck()&&this.finalize()},spawnCheckAndScheduleNext=()=>{check(),g<3e3&&(g+=1e3),this.probeTimer=setTimeout(spawnCheckAndScheduleNext,g)};return spawnCheckAndScheduleNext(),this.probeDeferred.promise}finalize(){this.probeTimer&&(clearTimeout(this.probeTimer),this.probeTimer=0),this.probeDeferred&&(this.probeDeferred.resolve(Date.now()-this.checkStart),this.probeDeferred=null)}dispose(){this.finalize()}async performCheck(){this.logger.safe.info("Probing...");const g=this.tryCreatePc();if(!g)return!1;g.createDataChannel("probe");const f=new dt;function finalize(S){g.onicecandidate=void 0,g.close(),f.resolve(S)}let S=!1;return g.onicecandidate=g=>{const f=g.candidate;if(!f)return S||this.logger.safe.info("still offline"),void finalize(S);const v=f.type??parseCandidateString(f.candidate).type;"srflx"!==v&&"relay"!==v||(this.logger.safe.info(`Back online through ${v} candidate`),S=!0,"srflx"===v&&(this.ipFromRelay=f.address,finalize(!0)))},await g.setLocalDescription(await g.createOffer()),f.promise}tryCreatePc(){try{return new Xs.window.RTCPeerConnection({iceServers:this.relayConfig})}catch(g){return this.logger.safe.info(`Failed to create PC, errCode=${g.code}`),null}}},createIceServers=(g,f)=>g.reduce(((g,S)=>{const v=[],C=S.addresses&&S.addresses[0],_=S.fqdns&&S.fqdns.length>0,T=f.iceUdpAddressType,I=f.iceTcpAddressType,b=f.iceServerTransport;if(!C&&!_)return g;if(b.includes("udp")&&S.udpPort){const g=!_||"fqdn"!==T&&C?C:S.fqdns[0];v.push(`turn:${g}:${S.udpPort}?transport=udp`)}if(b.includes("tcp")&&S.tcpPort){const g=!_||"fqdn"!==I&&C?C:S.fqdns[0];v.push(`turn:${g}:${S.tcpPort}?transport=tcp`)}return b.includes("tls")&&S.tlsPort&&_&&v.push(`turns:${S.fqdns[0]}:${S.tlsPort}`),g.concat({urls:v,credential:S.password,username:S.username})}),[]),createProbeIceServers=(g,f)=>g.reduce(((g,S)=>{const v=[],C=S.addresses&&S.addresses[0],_=S.fqdns&&S.fqdns.length>0,T=f.iceUdpAddressType,I=f.iceServerTransport;if(!C&&!_)return g;if(I.includes("udp")&&S.udpPort){const g=!_||"fqdn"!==T&&C?C:S.fqdns[0];v.push(`stun:${g}:${S.udpPort}`)}return I.includes("tls")&&S.tlsPort&&_&&v.push(`turns:${S.fqdns[0]}:${S.tlsPort}`),g.concat({urls:v,credential:S.password,username:S.username})}),[]),vT=class{constructor(g,f,S,v,C,_,T,I){this.session=g,this.context=f,this.diagnostics=S,this.sessionOperationQueue=v,this.callback=C,this.sessionCallbacks=_,this.configProvider=T,this.relayManager=I,this.wasConnected=!1,this.isDisconnected=!1,this.isReconnectConference=!1,this.escalationType=0,this._isSignalingStable=!0,this.reconnectDelayTime=0,this._isReconnectScheduled=!1,this.isDisposing=!1,this.isWaitingForNetwork=!1,this.onOnline=()=>{this.logger.safe.info("onOnline: Network is up"),this.diagnostics.registerState("networkOnline"),this.isOnlineDeferred?.resolve(),this.isOnlineDeferred=null},this.onOffline=()=>{this.logger.safe.info("onOffline: Network is down"),this.diagnostics.registerState("networkOffline"),this.isOnlineDeferred=new dt},this.logger=f.getLogger().createChild("ReconnectManagerV2"),this.ufdManager=f.getUfdManager(),this.session.callbacks=_,this.reconnectManagerMessageQueue=new fT(_),window.addEventListener("online",this.onOnline),window.addEventListener("offline",this.onOffline)}get isOnline(){return!this.isOnlineDeferred}async createRelayProber(){if(!this._relayProber){const g=Date.now(),f=createProbeIceServers(await this.relayManager.queryRelaysAsync({relayType:"turn"}),this.configProvider.config),S=Date.now()-g;this.logger.safe.info(`RelayProber configuration fetched in ${S} ms`),S>5e3&&this.diagnostics.registerState("relayConfigFetched"),this._relayProber=new ST(f,this.logger.createChild("RelayProber"))}return this._relayProber}dispose(){this.isDisposing=!0,window.removeEventListener("online",this.onOnline),window.removeEventListener("offline",this.onOffline),this._relayProber?.dispose(),this.isOnlineDeferred?.reject(new Error("dispose")),this.reconnectTimer&&this.resetReconnectTimer()}get settings(){return(this.reconnectSession||this.session).getSessionConfig().config}getCurrentSession(){return this.reconnectSession||this.session}getMainSession(){return this.session||this.reconnectSession}getReconnectSession(){return this.reconnectSession}async onIceDisconnect(g){if(this.wasConnected)this.raiseReconnectEvent("Bad",g);else if(!this.settings.reconnectWithNoRelays&&!this.session.hasRelayCandidates())return void this.onReconnectFailed("no relays",g);if(this.isDisconnected=!0,!this.isReconnecting()&&!this.isWaitingForNetwork)return this.logger.safe.info(`[${g}] reconnect attempt after iceDisconnect error`),this.session.transportStateProvider?.isFailed&&this.diagnostics.registerState("failed"),this.diagnostics.registerReconnect("attempted"),this.reconnectAsync(g)}onTransportDisconnect(g){this.isDisconnected=!0,this.wasConnected&&(this.diagnostics.registerState("disconnected"),this.handleTmpConnectivityLoss(g))}onConnected(g){this.isDisconnected=!1,this.logger.safe.info(`[${g}] set allow UFD`),this.diagnostics.registerState("connected"),this.raiseReconnectEvent("Good",g),this.wasConnected=!0,this._relayProber?.finalize()}onNegotiationCompletedAsync(g){return this.logger.safe.info(`[${g}] handle negotiation completed`),this.setSignalingState(!0),this.isReconnecting()&&(this.diagnostics.registerRetarget("completed"),2===this.escalationType&&this.blockCurrentSession(g)),Promise.resolve()}async onSessionErrorOccurred(g,f){this.logger.safe.info(`[${f}] handle session error`,stringifyObject2(g)),await this.rejectReconnect(f),this.isReconnectAllowed()?await this.scheduleReconnectRetry(f,!1,!1):this.callback.onSessionErrorOccurred(g,f,this.wasConnected)}onNegotiationRejection(g,f){this.logger.safe.info(`[${f}] handle negotiation rejection`),this.diagnostics.registerRetarget("rejected");const S=1===this.escalationType;return this.rejectReconnect(f).then((()=>{const v=g.type===qt.RENEGOTIATION_ERROR.glare&&S;(g.type!==qt.RENEGOTIATION_ERROR.glare||S)&&(this.isRecoverableError(g.type)||v?this.scheduleReconnectRetry(f,v,S):this.onReconnectFailed(stringifyObject2(g),f))}))}async ensureNetwork(g){const f=this.isOnline;if(!this.isOnline){this.logger.safe.info(`[${g}] waiting for network...`);try{await this.isOnlineDeferred.promise}catch(f){return void this.logger.safe.info(`${g} call disposed while waiting for network`)}this.logger.safe.info(`[${g}] network seems up`)}if(this.isDisconnected){const S=await this.createRelayProber(),v=await S.ensureOnline();this.logger.safe.info(`[${g}] probing complete in ${v} ms`),this.diagnostics.registerState("relaysUp"),f&&v<1e3&&this.logger.safe.info(`[${g}] looks like network failed on remote side, recovery was quick`)}}oldSessionIsOnline(g){return!!this.session?.transportStateProvider?.isConnected&&(this.logger.safe.info(`[${g}] old session recovered`),this.isReconnecting()||this.diagnostics.registerReconnect("connected"),!0)}async waitForNetworkAndTryLightweightRecovery(g){const f=this.oldSessionIsOnline(g);if(f||!this.settings.reconnectWithProbes)return f;this.setReconnectTimer(),this.isWaitingForNetwork=!0;const S=this.getMaxNetworkWaitTime();return this.logger.safe.info(`[${g}] can wait up to ${S} ms`),await Promise.race([this.ensureNetwork(g),delay(S)]),this.isWaitingForNetwork=!1,this.session&&(this.session.transportStateProvider?.isConnected||this.session.transportStateProvider?.isFailed||(this.logger.safe.info(`[${g}] giving session a moment to recover`),await delay(this.settings.reconnectWaitTimeAfterProbe)),this.oldSessionIsOnline(g))?(this.resetReconnectTimer(),!0):this.checkIfTimerFailed(g)?(this.logger.safe.info(`[${g}] session reconnect timer reached during network checks`),!0):!!this.isDisposing&&(this.logger.safe.info(`[${g}] session is disposed`),!0)}reconnectAsync(g,f=!1,S=!1,v){return this.logger.safe.info(`[${g}] queueing reconnect, force=${f}, escalation=${S}`),this.diagnostics.registerReconnectAttempt(S?"local escalation":"out"),this.context.getSmallCallTelemetry()?.setEventType("reconnect"),this._isReconnectScheduled=!0,S&&(this.escalationType=1,this.onReconnectCompleted=v),this.sessionOperationQueue.queueOperation((async()=>{if(this._isReconnectScheduled=!1,f||!await this.waitForNetworkAndTryLightweightRecovery(g))return this.isReconnecting()?(this.logger.safe.info(`[${g}] ongoing reconnect is in progress`),void this.sessionOperationQueue.completeCurrentOperation()):(this.diagnostics.registerState("reconnect"),await this.initReconnect(g),await this.reconnectSession.configureModalitiesAsync(this.getConfiguredModalities(),g),void this.sessionOperationQueue.completeCurrentOperation());this.sessionOperationQueue.completeCurrentOperation()}),g)}async acceptReconnectStartAsync(g,f){return this.logger.safe.info(`[${f}] accepting reconnect`),this.diagnostics.registerRetarget("incoming"),g?(this.escalationType=2,this.diagnostics.registerEscalation("attempted")):(!this.isReconnecting()&&this.isDisconnected?this.diagnostics.registerReconnect("attempted"):this.isReconnecting()&&await this.rejectReconnect(f),this.diagnostics.registerState("reconnect"),this.diagnostics.registerReconnectAttempt("in")),this.initReconnect(f)}acceptReconnectFinish(g){const f=this.getConfiguredModalities();return this.reconnectSession.configureModalitiesAsync(f,g).then((()=>f))}isReconnecting(){return!!this.reconnectSession}isReconnectScheduled(){return this._isReconnectScheduled}cleanUp(){this.sessionCallbacks=null,this.reconnectSession=null}async terminateAsync(g){try{await(this.session?.terminate(g,{}))}catch{}try{await this.terminateReconnectSessionAsync(g,!0)}catch{}this.cleanUp()}completeReconnect(g){return this.logger.safe.info(`[${g}] completing reconnect`),2===this.escalationType&&(this.unblockCurrentSession(g),this.diagnostics.registerEscalation("completed")),this.escalationType=0,this.reconnectSession&&(this.context.config.isConference=this.isReconnectConference,this.disposeActiveSession(g),this.session=this.reconnectSession,this.reconnectManagerMessageQueue.clear(),this.diagnostics.registerReconnectAttemptStatus("completed"),this._isSignalingStable||this.diagnostics.registerRetarget("completed"),this.isDisconnected&&this.diagnostics.registerReconnect("connected"),this.resetReconnectTimer(),this.reconnectDelayTime=0,this.reconnectSession=null,this.negotiationPausePromise=null,this.session.callbacks=this.sessionCallbacks||{}),Promise.resolve()}async rejectReconnect(g){this.logger.safe.info(`[${g}] rejecting reconnect`),this.setSignalingState(!1),2===this.escalationType&&this.diagnostics.registerEscalation("rejected"),this.escalationType=0,this.reconnectSession&&(await this.terminateReconnectSessionAsync(g,!1),this.diagnostics.registerReconnectAttemptStatus("rejected")),this.session&&(this.reconnectManagerMessageQueue.flush(),this.session.callbacks=this.sessionCallbacks,this.unblockCurrentSession(g))}configureModalitiesAsync(g,f,S){this.lastKnownConfiguredModalities=g;const v=[];return this.session&&v.push(this.session.configureModalitiesAsync(g,f,S)),this.reconnectSession&&v.push(this.reconnectSession.configureModalitiesAsync(g,f,S)),Promise.all(v).then((()=>Promise.resolve()))}canSendDtmf(){return this.getMainSession().canSendDtmf()}muteHold(g,f){this.getMainSession().muteHold(g,f)}muteInputAsync(g){return this.getMainSession().muteInputAsync(g)}unmuteInputAsync(g){return this.getMainSession().unmuteInputAsync(g)}muteOutputAsync(g){return this.getMainSession().muteOutputAsync(g)}unmuteOutputAsync(g){return this.getMainSession().unmuteOutputAsync(g)}async getSpeakerVolume(g){return this.getMainSession().getSpeakerVolume(g)}async setSpeakerVolume(g,f){return this.getMainSession().setSpeakerVolume(g,f)}_deviceSelectionChanged(){this.session&&this.session.deviceSelectionChanged(),this.reconnectSession&&this.reconnectSession.deviceSelectionChanged()}disposeActiveSession(g){if(this.session&&this.isReconnecting()){this.logger.safe.info(`[${g}] About to dispose current session...`);const f=this.session;return this.lastKnownConfiguredModalities=this.session.getConfiguredModalities(),f.callbacks=this.reconnectManagerMessageQueue.queueCallbacks,f.move(this.reconnectSession,g),this.session=null,f.terminate(g,{},!1)}return Promise.resolve()}registerRetargetOutgoing(){this.diagnostics.registerRetarget("outgoing")}isSignalingStable(){return this._isSignalingStable}getConfiguredModalities(){return this.getMainSession().getConfiguredModalities()||this.lastKnownConfiguredModalities}checkIfTimerFailed(g){return!(this.isReconnectAllowed()||this.session&&!this.session.transportStateProvider?.isFailed||(this.onReconnectFailed("the time limit was reached",g),0))}async scheduleReconnectRetry(g,f,S){const v=this.getReconnectDelayTime();if(this.logger.safe.info(`[${g}] scheduling reconnect retry attempt in ${v}`),await delay(v),f||!this.checkIfTimerFailed(g))return this.reconnectAsync(g,S,S,this.onReconnectCompleted)}isRecoverableError(g){return qt.RENEGOTIATION_ERROR.media===g||qt.RENEGOTIATION_ERROR.signaling===g}async resetReconnectSession(g){this.logger.safe.info(`[${g}] Resetting reconnect session. Session exists: old: ${!!this.session}, new: ${!!this.reconnectSession}`),this.isReconnectConference=0!==this.escalationType||this.context.config.isConference;const f=0!==this.escalationType||this.context.config.isConference&&this.wasConnected&&!this.isDisconnected,S=this.getMainSession(),v=this.configProvider.getConfigView(this.isReconnectConference,S.getSessionConfig()),C=S.clone(f,v);C.callbacks={...this.sessionCallbacks,onTransportConnected:g=>{2!==this.escalationType&&this.completeReconnect(g),this.onReconnectCompleted?.(),this.raiseReconnectEvent("Good",g),this.sessionCallbacks.onTransportConnected(g)}},this.session&&(this.session.callbacks={...this.reconnectManagerMessageQueue.queueCallbacks,onSessionErrorOccurred:(g,f)=>(g.type!==qt.MEDIA_ERROR.iceConnectionError&&this.reconnectManagerMessageQueue.queueCallbacks.onSessionErrorOccurred(g,f),Promise.resolve())}),this.reconnectSession&&(this.reconnectSession.move(C,g),this.logger.safe.info(`[${g}] reconnect session still exists during reconnect clone operation`),await this.terminateReconnectSessionAsync(g,!1)),this.logger.safe.info(`[${g}] New session reset.`),this.reconnectSession=C}async initReconnect(g){this.logger.safe.info(`[${g}] initiate reconnect`),this.setReconnectTimer(),await this.resetReconnectSession(g),this.setSignalingState(!1),this.session&&(this.blockCurrentSession(g),await Promise.all([this.reconnectSession.muteInputAsync(g),this.reconnectSession.muteOutputAsync(g)]))}blockCurrentSession(g){this.logger.safe.debug(`[${g}] blocking current session negotiations`),this.negotiationPausePromise=this.session.pauseNegotiations(g)}unblockCurrentSession(g){this.negotiationPausePromise&&(this.logger.safe.debug(`[${g}] unblocking current session negotiations`),this.negotiationPausePromise.resolve(),this.negotiationPausePromise=null)}raiseReconnectEvent(g,f){this.ufdManager.signalEvent("NetworkReconnect",g,"Audio",!0,f)}async terminateReconnectSessionAsync(g,f){if(this.reconnectSession){const S=new fT(this.sessionCallbacks);this.reconnectSession.callbacks={...S.queueCallbacks,onTerminated:f?this.sessionCallbacks.onTerminated:S.queueCallbacks.onTerminated},await this.reconnectSession.terminate(g,{},!1),S.clear(),this.reconnectSession=null}}setReconnectTimer(){const g=this.wasConnected?this.settings.reconnectTimeLimit:this.settings.initialReconnectTimeLimit;g>0&&!this.reconnectTimer&&(this.reconnectTimerStart=Date.now(),this.reconnectTimer=window.setTimeout((()=>this.resetReconnectTimer()),g))}resetReconnectTimer(){clearTimeout(this.reconnectTimer),this.reconnectTimer=null}isReconnectAllowed(){return!!this.reconnectTimer&&!this.isDisposing}getReconnectDelayTime(){return 1e3*Math.min(++this.reconnectDelayTime,this.settings.maxReconnectDelayTime)}getMaxNetworkWaitTime(){const g=this.reconnectTimerStart>0?Date.now()-this.reconnectTimerStart:0;return Math.max(this.settings.reconnectTimeLimit-g,0)}onReconnectFailed(g,f){this.callback.onSessionErrorOccurred({type:qt.MEDIA_ERROR.iceConnectionError,detail:`Reconnect failed, error - ${stringifyObject2(g)}`},f,this.wasConnected)}setSignalingState(g){this._isSignalingStable=g}async handleTmpConnectivityLoss(g){this.logger.safe.info(`[${g}] Session went into disconnected state, giving it ${this.settings.losingConnectivityTimeoutMs}ms to recover`),-1!==this.settings.losingConnectivityTimeoutMs&&(await delay(this.settings.losingConnectivityTimeoutMs),this.isDisconnected&&this.raiseReconnectEvent("Poor",g)),this.isDisconnected&&this.settings.reconnectOnDisconnect&&(this.logger.safe.info(`[${g}] Session is still down, triggering reconnect`),this.onIceDisconnect(g))}},CT=class{constructor(g,f){this.stats=g,this.diagnostics=f}set mediaLegId(g){this.stats.setMediaLegId(g.process()),this.diagnostics&&(this.diagnostics.mediaLegId=g)}set isMultiParty(g){g&&this.stats.setMultiParty(),this.diagnostics&&(this.diagnostics.isMultiParty=g)}set allowedModalities(g){this.stats.setSendModalities(g),this.diagnostics&&(this.diagnostics.allowedModalities=g)}set sessionError(g){this.stats.setError(g),this.diagnostics&&(this.diagnostics.sessionError=g)}set finalAnswerTime(g){this.stats.setFinalAnswerTimestamp(g),this.diagnostics&&(this.diagnostics.finalAnswerTime=g)}set dtmfResult(g){this.stats.dtmfResult(g),this.diagnostics&&(this.diagnostics.dtmfResult=g)}set swMute(g){this.stats.setSwMute(g),this.diagnostics&&(this.diagnostics.swMute=g)}set speakerMute(g){this.stats.setSpeakerMute(g),this.diagnostics&&(this.diagnostics.speakerMute=g)}set hwSilent(g){this.stats.setHwSilent(g),this.diagnostics&&(this.diagnostics.hwSilent=g)}set isSpeaking(g){this.stats.setSpeakingState(g),this.diagnostics&&(this.diagnostics.isSpeaking=g)}set iceConnectedStateTimestamp(g){this.stats.setIceConnectedStateTimestamp(g),this.diagnostics&&(this.diagnostics.iceConnectedStateTimestamp=g)}set iceInitTime(g){this.stats.setIceInitTimestamp(g),this.diagnostics&&(this.diagnostics.iceInitTime=g)}set ETag(g){this.stats.setETag(g),this.diagnostics&&(this.diagnostics.ETag=g)}set configIds(g){this.stats.setConfigIds(g),this.diagnostics&&(this.diagnostics.configIds=g)}set relay(g){this.stats.setRelay(g),this.diagnostics&&(this.diagnostics.relay=g)}negotiationStart(g){switch(this.diagnostics?.negotiationStart(g),g){case"Offering":this.stats.negotiation.offering.started();break;case"Answering":this.stats.negotiation.answering.started()}}negotiationCompleted(g){this.stats.negotiation.current.completed(g),this.diagnostics?.negotiationCompleted(g)}negotiationRejected(){this.stats.negotiation.current.rejected(),this.diagnostics?.negotiationRejected()}registerTransportConnected(){this.stats.registerTransportConnected(),this.diagnostics?.registerTransportConnected()}registerTransportDisconnected(){this.stats.registerTransportDisconnected(),this.diagnostics?.registerTransportDisconnected()}registerTransportFailed(){this.stats.registerTransportFailed(),this.diagnostics?.registerTransportFailed()}registerRollbackEvent(g){this.stats.registerRollbackEvent(g),this.diagnostics?.registerRollbackEvent(g)}registerRawMediaAccess(g,f,S){"send"===f?this.stats.registerSetInputRawMedia(S):this.stats.registerOutputRawMediaAccess(),this.diagnostics?.registerRawMediaAccess(g,f,S)}registerQualityStateChangedEvent(g){this.stats.registerQualityStateChangedEvent(g),this.diagnostics?.registerQualityStateChangedEvent(g)}terminated(g){this.stats.terminated(g),this.diagnostics?.terminated(g)}registerRemoteQualityStateChangedEvent(g,f){this.stats.registerRemoteQualityStateChangedEvent(g,f),this.diagnostics?.registerRemoteQualityStateChangedEvent(g,f)}},yT=class{constructor(g){this.logger=g,this.operationQueue=null,this.currentOperationDeferred=null,this.operationQueue=new zC(this.logger)}queueOperation(g,f=generateCauseId()){this.logger.safe.info(`[${f}] queueing operation`);const S=new dt,v=this.operationQueue.add((()=>(this.currentOperationDeferred=S,g())),f);return this.operationQueue.add(S,f),v}completeCurrentOperation(){this.currentOperationDeferred&&(this.logger.safe.info("completing operation"),this.currentOperationDeferred.resolve())}},ET=class extends Ht{constructor(g,f,S,v,C,_,T,I=S.getLogger().createChild("SessionV2",f)){super(I),this.context=S,this.callback=v,this.statistics=C,this.configProvider=_,this.diagnostics=T,this.logger=I,this.audioStreamStates={[qt.STREAMING_STATE.inactive]:[qt.STREAMING_STATE.started,qt.STREAMING_STATE.active,qt.STREAMING_STATE.failed],[qt.STREAMING_STATE.started]:[qt.STREAMING_STATE.active,qt.STREAMING_STATE.removed,qt.STREAMING_STATE.stopped,qt.STREAMING_STATE.failed],[qt.STREAMING_STATE.active]:[qt.STREAMING_STATE.removed,qt.STREAMING_STATE.stopped,qt.STREAMING_STATE.failed]},this.mediaLegId=new gT,this.rejectedNegotiations=0,this.negotiationState=null,this.audioStreamState=qt.STREAMING_STATE.inactive,this.deviceManagerDisposables=[],this.visibilityChangedHandler=()=>{if(this.logger.safe.debug(`document.visibilityState changed: ${document.visibilityState}`),"visible"===document.visibilityState&&this.pcClosedInfo){const g=this.pcClosedInfo;this.pcClosedInfo=null,Date.now()<g.timestamp+this.configProvider.config.reconnectWakeupTimeLimit?(this.logger.safe.info(`[${g.causeId}] start reconnect after wakeup`),this.startReconnect(g.causeId)):(this.logger.safe.info(`[${g.causeId}] terminate a call after wakeup because allowed time limit for reconnect exceeded`),this.endCallOnFailure(g.mediaError,g.causeId))}"hidden"===document.visibilityState&&this.context.getSmallCallTelemetry()?.setEventType("visibilityHidden")},this.ufdManager=S.getUfdManager(),this.ufdManagerDisposable=this.ufdManager.on("onQualityChanged",(g=>this.qualityChanged(g))),this.sessionOperationQueue=new yT(this.logger),this.mediaLegId=new gT,this.diagnosticsWrapper=new CT(this.statistics,this.diagnostics),this.statistics.setId(f),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.diagnosticsWrapper.ETag=this.configProvider.ETag,this.diagnosticsWrapper.configIds=this.configProvider.ecsConfigIds,this.diagnosticsWrapper.isMultiParty=!!S.config.isConference,this.recoverableErrors=this.configProvider.config.recoverableMediaErrors.split(","),this.forceReconnectErrors=this.configProvider.config.forceReconnectErrors.split(",");const b=this.getSessionCallbacks();g.callbacks=b,g.relayManagerProvider=this,this.reconnectManager=new vT(g,S,new mT(this.statistics,this.diagnostics?new uT(this.configProvider):void 0,this.diagnostics),this.sessionOperationQueue,this.getReconnectManagerCallbacks(),b,this.configProvider,this.getRelayManager()),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.deviceManagerDisposables.push(this.deviceManager.on("onDevicesPermissionChanged",(()=>this.diagnosticsWrapper.allowedModalities=this.getAllowedModalities()))),this.deviceManagerDisposables.push(this.deviceManager.on("onSelectedDevicesChanged",(()=>this.deviceSelectionChanged()))),this.deviceManagerDisposables.push(this.deviceManager.on("onDevicesChanged",((g,f)=>this.deviceListChanged(f)))),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount()),this.diagnostics&&(this.diagnostics.relayManager=this.getRelayManager()),this.ufdManager.applyCurrentState((g=>this.qualityChanged(g))),document.addEventListener("visibilitychange",this.visibilityChangedHandler),this.requestWakeLock()}async requestWakeLock(){if(oa.isWakeLockSupported()&&this.configProvider.config.useWakeLockApi)try{this.wakeLock=await window.navigator.wakeLock.request("screen")}catch(g){this.logger.safe.info(`Wakelock request failed - ${g.message}`)}}enableTeamsRealTimeTelemetry(){this.realtimeTelemetryInterval||(this.logger.safe.info("teams realtime telemetry is enabled"),this.getSessionCallbacks().onTeamsRealtimeTelemetryReport(),this.realtimeTelemetryInterval=window.setInterval((()=>{this.getSessionCallbacks().onTeamsRealtimeTelemetryReport()}),1e3*this.configProvider.config.diagnostics.teamsRealtimeTelemetry.pollingInterval))}getMediaStatsReport(){return this.diagnostics?.mediaStatsReport}createOfferAsync(g,f){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Offering");try{const S=await this.getCurrentSession().createOfferAsync(g,f);return this.updateSelectedDevices(),S.mediaLegId=this.mediaLegId.process(S.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.reconnectManager.isReconnecting()&&!this.reconnectManager.isSignalingStable()&&(this.reconnectManager.registerRetargetOutgoing(),S.newOffer=!0),S}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}),g)}registerRemoteQualityStateChangedEvent(g,f){this.diagnosticsWrapper.registerRemoteQualityStateChangedEvent(g,f)}setCallConstraints(g,f){return this.getCurrentSession().setCallConstraints(g,f)}processOfferAsync(g,f){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Answering"),g.mediaLegId=this.mediaLegId.process(g.mediaLegId);try{g.newOffer&&await this.reconnectManager.acceptReconnectStartAsync(g.escalationOccurring,f);const S=await this.getCurrentSession().processOfferAsync(g,f);if(g.newOffer){const g=await this.reconnectManager.acceptReconnectFinish(f);return S.sharing===qt.MEDIA_STATE.sendReceive&&(S.sharing=g.sharing===qt.MEDIA_STATE.send?qt.MEDIA_STATE.send:qt.MEDIA_STATE.receive),S}return S}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}),f)}async processAnswerAsync(g,f,S,v){try{return this.configProvider.config.muteDuringRemotePranswer&&(S&&!this.callMuteState&&(this.logger.safe.info(`[${f}] Muting input before processing full answer`),await this.muteInputAsync(f),this.lastMuteFromPranswer=!0),!S&&this.lastMuteFromPranswer&&(this.logger.safe.info(`[${f}] Unmuting input before processing full answer`),await this.unmuteInputAsync(f),this.lastMuteFromPranswer=!1)),await this.getCurrentSession().processAnswerAsync(g,f,S,v)}catch(g){throw this.lastMuteFromPranswer=!1,this.diagnosticsWrapper.sessionError=g,g}}async completeNegotiationAsync(g){this.rejectedNegotiations=0;try{const f=await this.getCurrentSession().completeNegotiationAsync(g);return this.negotiationState=f,this.diagnosticsWrapper.finalAnswerTime=Date.now(),this.diagnosticsWrapper.negotiationCompleted?.(f.activeModalities),await this.reconnectManager.onNegotiationCompletedAsync(g),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}ignoreNotReconnectError(g){return g.detail?.type!==qt.MEDIA_ERROR.incompatibleOriginator}async rejectNegotiationAsync(g,f){this.logger.safe.info(`[${f}] rejectNegotiationAsync`,g);try{if(this.reconnectManager.isReconnecting()&&this.ignoreNotReconnectError(g))return await this.reconnectManager.onNegotiationRejection(g,f),this.registerNegotiationRejection(this.negotiationState),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState;{const S=await this.getCurrentSession().rejectNegotiationAsync(g,f,this.isRenegotiationAllowed(g.type));return this.sessionOperationQueue.completeCurrentOperation(),this.registerNegotiationRejection(S),S}}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}completeEscalationAsync(g){return this.reconnectManager.completeReconnect(g)}rejectEscalationAsync(g){return this.reconnectManager.rejectReconnect(g)}async terminate(g,f){this.logger.safe.info(`terminate reject reason: ${JSON.stringify(f||"")}`),this.registerVideoEffectsTelemetryEvent(this.deviceManager.effectsManager.getStats("Video","StatsQuery")),this.registerAudioEffectsTelemetryEvent(this.deviceManager.effectsManager.getStats("Audio")),this.statistics.setPermissionStates(await this.deviceManager.getKnownPermissionStates()),this.diagnosticsWrapper.terminated(f);const always=()=>this.cleanUp();return this.reconnectManager.terminateAsync(g).then(always,always)}async getStatsAsync(g){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.getMainSession().getStatsAsync(g).then((g=>this.prepareStats(g)))}getLastKnownStats(g=!1){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.prepareStats(this.getMainSession().getLastKnownStats(g),g)}getCallTechnicalInfo(){return this.diagnostics?.realtimeTelemetryReport}async createAnswerAsync(g,f){try{const S=await this.getCurrentSession().createAnswerAsync(g,f);return this.updateSelectedDevices(),S.mediaLegId=this.mediaLegId.process(S.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,S}catch(g){throw this.diagnosticsWrapper.sessionError=g,g}}configureModalitiesAsync(g,f,S){return forOwn(g,((f,S)=>{f||delete g[S]})),this.reconnectManager.configureModalitiesAsync(g,f,S)}getAllowedModalities(){return this.deviceManager.getAllowedModalities()}createRemoteRenderer(g){return this.getMainSession().createRemoteRenderer(g)}async sendDtmf(g){try{const f=await this.getMainSession().sendDtmf(g);return this.diagnosticsWrapper.dtmfResult=!0,f}catch(g){throw this.diagnosticsWrapper.dtmfResult=!1,g}}canSendDtmf(){return this.reconnectManager.canSendDtmf()}muteHold(g,f){this.reconnectManager.muteHold(g,f)}muteInputAsync(g){return this.callMuteState=!0,this.diagnosticsWrapper.swMute=!0,this.lastMuteFromPranswer=!1,this.reconnectManager.muteInputAsync(g)}unmuteInputAsync(g){return this.callMuteState=!1,this.diagnosticsWrapper.swMute=!1,this.lastMuteFromPranswer=!1,this.reconnectManager.unmuteInputAsync(g)}muteOutputAsync(g){return this.diagnosticsWrapper.speakerMute=!0,this.reconnectManager.muteOutputAsync(g)}unmuteOutputAsync(g){return this.diagnosticsWrapper.speakerMute=!1,this.reconnectManager.unmuteOutputAsync(g)}async getSpeakerVolume(g){return this.reconnectManager.getSpeakerVolume(g)}async setSpeakerVolume(g,f){return this.reconnectManager.setSpeakerVolume(g,f)}getAcceptedTypes(){return this.reconnectManager.getCurrentSession().getAcceptedTypes()}useNullAudioStreamClient(){this.getCurrentSession().useNullAudioStreamClient()}createAudioElement(g){this.getCurrentSession().createAudioElement(g)}getIncomingRawAudioStream(g){return this.diagnosticsWrapper.registerRawMediaAccess("audio","recv",!0),this.getCurrentSession().getIncomingRawAudioStream(g)}getUnmixedAudioProvider(){return this.getCurrentSession().getUnmixedAudioProvider()}deviceSelectionChanged(){this.updateSelectedDevices(),this.reconnectManager._deviceSelectionChanged()}registerDeviceTelemetryEvent(g){this.getCurrentSession().onDeviceEvent(g),this.statistics.registerDeviceTelemetryEvent(g)}registerVideoEffectsTelemetryEvent(g){this.statistics.registerVideoEffectsTelemetryEvent(g)}registerAudioEffectsTelemetryEvent(g){this.statistics.registerAudioEffectsTelemetryEvent(g)}reconnectAsync(g,f=!1,S){return this.reconnectManager.reconnectAsync(g,!0,f,S)}isReconnecting(){return this.reconnectManager.isReconnecting()}getRelayManager(){return this.relayManager??(this.relayManager=new pT(this.context.maContext.getRelayManager(),this.diagnosticsWrapper))}getSessionConfig(){return this.reconnectManager.getCurrentSession().getSessionConfig()}getDiagnostics(){return this.diagnostics}getLocalMediaTrackId(g){return this.reconnectManager.getMainSession().getLocalMediaTrackId(g)}getSubscriptionManager(){return this.getCurrentSession().getSubscriptionManager()}getDisabledModalities(){return this.getCurrentSession().getDisabledModalities()}configureSpatialAudio(g,f){this.getCurrentSession().configureSpatialAudio(g,f)}setParticipantSpatialAudioPositions(g,f){this.getCurrentSession().setParticipantSpatialAudioPositions(g,f)}startMediaDescriptionsUpdateAsync(g,f){return this.getCurrentSession().startMediaDescriptionsUpdateAsync(g,f)}completeMediaDescriptionsUpdateAsync(g){return this.getCurrentSession().completeMediaDescriptionsUpdateAsync(g)}rejectMediaDescriptionsUpdateAsync(g,f){return this.getCurrentSession().rejectMediaDescriptionsUpdateAsync(g,f)}processNotification(g,f){this.getCurrentSession().processNotification(g,f)}getMediaControlPlaneInstance(){return this.getCurrentSession().getMediaControlPlaneInstance()}async cleanUp(){this.callback=null,this.deviceManagerDisposables.forEach((g=>g.dispose())),this.ufdManagerDisposable.dispose(),this.reconnectManager.dispose(),this.pcClosedInfo=null,document.removeEventListener("visibilitychange",this.visibilityChangedHandler),window.clearInterval(this.realtimeTelemetryInterval),this.wakeLock&&(await this.wakeLock.release(),this.wakeLock=null)}updateSelectedDevices(){const g=this.deviceManager.getSelectedDevices(),getDeviceName=g=>g?this.deviceManager.getDeviceNameAsync(g).then((g=>scrubDeviceLabelPii(g,this.configProvider.config.devices.piiSafeWords))):Promise.resolve("none");Promise.all([getDeviceName(g.microphone),getDeviceName(g.speaker),getDeviceName(g.camera)]).then((([g,f,S])=>{this.statistics.setUsedDevices({microphone:g,speaker:f,camera:S})}))}getCurrentSession(){return this.reconnectManager.getCurrentSession()}getMainSession(){return this.reconnectManager.getMainSession()}setAudioStreamState(g,f,S){this.isAudioStateValid(g)?this.raiseAudioStateChanged(g,f,S):this.logger.safe.error(`[${f}] audio state transition is invalid: ${this.audioStreamState} -> ${g}`)}isAudioStateValid(g){return this.audioStreamStates[this.audioStreamState].indexOf(g)>=-1}raiseAudioStateChanged(g,f,S){if(this.logger.safe.info(`[${f}] audio state changed to ${g}`),this.callback.onAudioStateChanged){const f={content:"audio",direction:"receive",stream:g};this.callback.onAudioStateChanged(f,S)}}getReconnectManagerCallbacks(){return{onSessionErrorOccurred:(g,f,S)=>{this.isNetworkMediaError(g)&&!S&&this.ufdManager.raisePendingWhitelistingUFD(),this.endCallOnFailure(g,f)}}}isNetworkMediaError(g){return g.type===qt.MEDIA_ERROR.iceConnectionError||g.type===qt.MEDIA_ERROR.noNetworkError}isRecoverableMediaError(g){return this.recoverableErrors.includes(g.type)}startReconnect(g=generateCauseId()){return this.reconnectManager.onIceDisconnect(g)}shouldForceReconnect(g){return this.forceReconnectErrors.includes(g.type)}isUnexpectedPcClose(g){return g.type===qt.MEDIA_ERROR.unexpectedClose}getSessionCallbacks(){return this.sessionCallbacks||(this.sessionCallbacks={onTerminated:()=>{this.logger.safe.warn("call onTerminated"),this.event("onTerminated").raise(this)},onSessionErrorOccurred:(g,f=generateCauseId())=>this.isUnexpectedPcClose(g)?this.handlePcClosed(g,f):this.shouldForceReconnect(g)?this.reconnectManager.reconnectAsync(f,!0):this.isRecoverableMediaError(g)?this.reconnectManager.isReconnecting()?this.reconnectManager.onSessionErrorOccurred(g,f):this.startReconnect(f):(this.endCallOnFailure(g,f),Promise.resolve()),onNegotiationRequired:(g,f)=>this.callback.onNegotiationRequired(g,f),onAudioHwSilentChanged:g=>{this.diagnosticsWrapper.hwSilent=g},onAudioStateChanged:(g,f)=>{this.setAudioStreamState(g,f)},onTransportConnected:(g=generateCauseId())=>{this.logger.safe.info(`[${g}] Transport connectivity established`),this.ufdManager.cancelPendingWhitelistingUFD(),this.reconnectManager.onConnected(g),this.diagnosticsWrapper.registerTransportConnected(),this.diagnosticsWrapper.iceConnectedStateTimestamp=Date.now(),this.callback?.onTransportConnected(g)},onTransportDisconnected:(g=generateCauseId())=>{this.logger.safe.warn(`[${g}] Transport connectivity lost`),this.reconnectManager.onTransportDisconnect(g),this.diagnosticsWrapper.registerTransportDisconnected(),this.callback?.onTransportDisconnected?.(g)},onTransportFailed:()=>{this.diagnosticsWrapper.registerTransportFailed(),this.callback?.onTransportFailed?.()},onTransportInitialized:()=>{this.diagnosticsWrapper.iceInitTime=Date.now()},onUpdateMediaDescriptionsRequired:(g,f)=>this.callback.onUpdateMediaDescriptionsRequired(g,f),onTeamsRealtimeTelemetryReport:()=>this.callback.onRealtimeTelemetryReport()}),this.sessionCallbacks}registerNegotiationRejection(g){this.rejectedNegotiations++,this.diagnosticsWrapper.negotiationRejected?.(),g.rollback&&this.diagnosticsWrapper.registerRollbackEvent(g.rollback)}isRenegotiationAllowed(g){return this.rejectedNegotiations<this.context.configProvider.config.renegotiationAttempts&&!this.reconnectManager.isReconnectScheduled&&(qt.RENEGOTIATION_ERROR.signaling===g||qt.RENEGOTIATION_ERROR.media===g)}prepareStats(g,f=!1){this.statistics.setDeviceList(this.deviceManager.getDeviceDescriptions(),this.deviceManager.getDeviceListDebugInfo()),this.statistics.setRelayManagerTimers(this.getRelayManager().getStats()),this.statistics.setVideoEffectStats(this.context.callDeviceManager.getDeviceManager("Video").effectsManager.getStats("Video","StatsQuery")),this.statistics.setAudioEffectStats(this.deviceManager.effectsManager.getStats("Audio"));const S=this.statistics.generateStatistics(g,this.mediaLegId,f);return this.configProvider.config.diagnostics.features.useNewerStatisticsMetrics&&(S.data.metrics=this.diagnostics?.telemetryReport?.data.metrics),!g.data.Extensions?.StartTime&&this.configProvider.config.diagnostics.features.useFallbackToNewExtensions&&(S.data.Extensions=this.diagnostics?.telemetryReport?.data.Extensions),S}deviceListChanged(g){g&&this.statistics.deviceChangedByPoll(),this.statistics.devicesChanged(),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount())}qualityChanged(g){const f=g.deviceManagerId;!f||this.context.callDeviceManager.hasDevice(f)?(this.context.getSmallCallTelemetry()?.setEventType(g.type),this.callback?.onQualityChanged&&(this.diagnosticsWrapper.registerQualityStateChangedEvent(g),"DeviceSpeakWhileMuted"===g.type&&(this.diagnosticsWrapper.isSpeaking="Good"!==g.value),this.callback.onQualityChanged(g))):this.logger.info(`${f} - is not added to Call, skipping UFD.`)}endCallOnFailure(g,f,S){this.callback&&(this.callback.onSessionErrorOccurred&&this.callback.onSessionErrorOccurred(g,f),this.diagnosticsWrapper.sessionError=g,this.setAudioStreamState(qt.STREAMING_STATE.failed,f,S))}async handlePcClosed(g,f){const S=this.configProvider.config.reconnectWakeupTimeLimit;return this.logger.safe.info(`[${f}] handle unexpected PC closed event`,`visibilityState=${document.visibilityState}, wakeupLimit=${this.configProvider.config.reconnectWakeupTimeLimit}`),"visible"===document.visibilityState?this.startReconnect(f):S?void(this.pcClosedInfo={timestamp:Date.now(),causeId:f,mediaError:g}):this.endCallOnFailure(g,f,"suspended")}},_T=class{constructor(g){this.creationTime=g,this.records=[],this.activeRecord=null,this.activeAttempt=null,this.reconnectState=!1}getReport(){return this.records.length?JSON.stringify(this.records):""}isReconnecting(){return this.reconnectState}onReconnectStart(){this.reconnectState=!0,this.activeRecord||(this.activeRecord={attempts:[],endTime:null,startTime:Date.now()-this.creationTime},this.records.push(this.activeRecord))}onReconnectAttempt(g){if(!this.activeRecord)return null;this.activeAttempt={direction:g,status:!1,endTime:null,startTime:this.getTimestamp()},this.reconnectState=!0,this.activeRecord.attempts.push(this.activeAttempt)}onReconnectConnected(){if(!this.activeRecord)return null;this.reconnectState=!1,this.activeRecord.endTime=this.getTimestamp(),this.activeRecord=this.activeAttempt=null}onReconnectCompleted(){this.reconnectState=!1,this.resolveReconnectAttempt(!0)}onReconnectRejected(){this.resolveReconnectAttempt(!1)}resolveReconnectAttempt(g){this.activeAttempt&&this.activeRecord&&(this.activeAttempt.status=g,this.activeAttempt.endTime=this.getTimestamp())}getTimestamp(){return Date.now()-this.creationTime-this.activeRecord.startTime}},TT=window.navigator,IT=class{constructor(g="Good"){this.stopWatches=[],this.currentLevel=g,this.getStopWatch(g).start()}updateLevel(g){this.currentLevel!==g&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=g,this.getStopWatch(this.currentLevel).start())}getCount(g){const f=this.stopWatches[g];return f?f.count:0}getElapsed(g){const f=this.stopWatches[g];return f?f.elapsed:0}getStopWatch(g){let f=this.stopWatches[g];return f||(f=new eT,this.stopWatches[g]=f),f}},bT=RegExp(/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\:[0-9]{2,5})?$/),AT=RegExp(/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(:[0-9]{2,5})?$/),PT=class{constructor(g,f,S){this.configProvider=g,this.callNumber=f,this.sessionDiagnostics=S,this.negotiation={offering:this.offering(),answering:this.answering(),current:this.current()},this.creationTime=Date.now(),this.negotiationCount=0,this.initialNegotiationCompleted=!1,this.activeModalities={},this.multiParty=!1,this.noIceCandidatesGoodEventCount=0,this.noIceCandidatesBadEventCount=0,this.noRelayIceCandidatesGoodEventCount=0,this.noRelayIceCandidatesBadEventCount=0,this.cameraInUseBadEventCount=0,this.cameraInUseGoodEventCount=0,this.microphoneInUseBadEventCount=0,this.microphoneInUseGoodEventCount=0,this.cameraFreezeStartEventCount=0,this.cameraFreezeEndEventCount=0,this.networkRecv=new IT,this.networkSend=new IT,this.retargetIncomingCount=0,this.retargetOutgoingCount=0,this.retargetCompletedCount=0,this.retargetRejectedCount=0,this.reconnectAttemptedCount=0,this.reconnectConnectedCount=0,this.escalationAttemptedCount=0,this.escalationCompletedCount=0,this.escalationRejectedCount=0,this.durationTimer=new eT,this.terminationReason={},this.terminationTime=0,this.sessionId="0",this.rejectedNegotiationCount=0,this.mediaError={type:"none",detail:"none"},this.incompatibleOffer=!1,this.dtmfSuccess=0,this.dtmfFailure=0,this.relay=null,this.relayManagerTimers=null,this.allowedAudioSend=!0,this.allowedVideoSend=!0,this.allowedScreensharingSend=!0,this.iceInitTime=0,this.finalAnswerTime=0,this.iceConnectedStateTime=0,this.usedDevices=null,this.deviceSelectionChangeCount=0,this.devicesChangeCount=0,this.devicesPollChangeCount=0,this.mute=new eT,this.osMute=new eT,this.hwSilent=new eT,this.isSpeaking=new eT,this.swMute=new eT,this.speakerMute=new eT,this.deviceTelemetryEvents=[],this.videoEffectsTelemetryEvents=new Uv(this.configProvider.config.effectsTelemetryBufferSize),this.audioEffectsTelemetryEvents=new Uv(this.configProvider.config.effectsTelemetryBufferSize),this.devicesCount=null,this.reconnectStats=new _T(this.creationTime),this.transportDisconnected=!1,this.transportReconnectedCount=0,this.ufds=[],this.remoteUfds=[],this.mediaQosEnabled=!1,this.portRangeConfigured=!1,this.rollbackNegotiation=[],this.rawOutputAudioAccess={attempt:0,timer:new eT},this.rawInputAudioOverride={attempt:0,timer:new eT},this.connectionEffectiveTypeSeries=new Uv(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionRttSeries=new Uv(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionDownlinkSeries=new Uv(this.configProvider.config.navConnectionNumSamplesToCollect),this.navigatorConnectionInterval=setInterval((()=>{const g=TT?.connection;g&&("number"==typeof g.downlink&&this.connectionDownlinkSeries.add(g.downlink),"number"==typeof g.rtt&&this.connectionRttSeries.add(g.rtt),"number"==typeof g.effectiveType&&this.connectionEffectiveTypeSeries.add(g.effectiveType))}),this.configProvider.config.navConnectionPollingInterval),this.durationTimer.start()}terminated(g){this.terminationReason=deepClone(g),this.terminationTime=Date.now(),this.durationTimer.stop(),this.osMute.stop(),this.swMute.stop(),this.hwSilent.stop(),this.isSpeaking.stop(),this.mute.stop(),this.speakerMute.stop(),this.rawInputAudioOverride.timer.stop(),this.rawOutputAudioAccess.timer.stop(),clearInterval(this.navigatorConnectionInterval)}setMultiParty(){this.multiParty=!0}updateCommonMute(){this.swMute.isRunning||this.osMute.isRunning?this.mute.start():this.mute.stop()}setDeviceList(g,f){this.deviceList=g.map((g=>({label:scrubDeviceLabelPii(g.label,this.configProvider.config.devices.piiSafeWords),kind:g.kind}))),f&&(this.deviceDebugStrings=deepClone(f))}setPermissionStates(g){this.permissionStates=g}setSwMute(g){g?this.swMute.start():this.swMute.stop(),this.updateCommonMute()}setSpeakerMute(g){g?this.speakerMute.start():this.speakerMute.stop()}setHwSilent(g){g?this.hwSilent.start():this.hwSilent.stop()}setSpeakingState(g){g?this.isSpeaking.start():this.isSpeaking.stop()}setETag(g){this.ETag=g}setConfigIds(g){this.configIds=g}setVideoEffectStats(g){g&&this.videoEffectsTelemetryEvents.add(g)}setAudioEffectStats(g){g&&this.audioEffectsTelemetryEvents.add(g)}registerQualityStateChangedEvent(g){switch(g.type){case"NoNetwork":"Good"===g.value?this.noIceCandidatesGoodEventCount++:this.noIceCandidatesBadEventCount++;break;case"NetworkRelaysNotReachable":"Good"===g.value?this.noRelayIceCandidatesGoodEventCount++:this.noRelayIceCandidatesBadEventCount++;break;case"DeviceCaptureNotFunctioning":"Good"===g.value?this.microphoneInUseGoodEventCount++:this.microphoneInUseBadEventCount++;break;case"VideoCapturerDeviceStartFailed":"Good"===g.value?this.cameraInUseGoodEventCount++:this.cameraInUseBadEventCount++;break;case"DeviceCaptureMute":"Audio"===g.mediaType&&("Bad"===g.value?this.osMute.start():this.osMute.stop(),this.updateCommonMute());break;case"NetworkRecvQuality":this.networkRecv.updateLevel(g.value);break;case"NetworkSendQuality":this.networkSend.updateLevel(g.value);break;case"VideoCaptureDeviceFreeze":"Good"===g.value?this.cameraFreezeEndEventCount++:this.cameraFreezeStartEventCount++}"DeviceSpeakWhileMuted"!==g.type&&this.ufds.push({...g,timestamp:Date.now()-this.creationTime}),this.ufds.length>this.configProvider.config.maxStoredUFDCount&&this.ufds.shift()}registerRemoteQualityStateChangedEvent(g,f){arrayLimitedPush22(this.remoteUfds,{...g,participantId:f,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numUFDs)}registerRetargetIncoming(){this.retargetIncomingCount++}registerRetargetOutgoing(){this.retargetOutgoingCount++}registerRetargetCompleted(){this.retargetCompletedCount++}registerRetargetRejected(){this.retargetRejectedCount++}registerEscalationStart(){this.escalationAttemptedCount++}registerEscalationCompleted(){this.escalationCompletedCount++}registerEscalationRejected(){this.escalationRejectedCount++}registerRollbackEvent(g){g&&this.rollbackNegotiation.push({type:g.type,attempt:this.rollbackNegotiation.length+1,error:g.error?g.error:""})}registerReconnectAttempted(){this.reconnectAttemptedCount++,this.reconnectStats.onReconnectStart()}registerReconnectConnected(){this.reconnectConnectedCount++,this.reconnectStats.onReconnectConnected()}registerDeviceTelemetryEvent(g){g.timestamp=g.timestamp-this.creationTime,this.deviceTelemetryEvents.push(g)}registerVideoEffectsTelemetryEvent(g){g&&(g.timestamp=g.timestamp-this.creationTime,this.videoEffectsTelemetryEvents.add(g))}registerAudioEffectsTelemetryEvent(g){if(g){g.timestamp=g.timestamp-this.creationTime;const f=this.audioEffectsTelemetryEvents.items.pop();f&&this.audioEffectsChanged(f,g)&&this.audioEffectsTelemetryEvents.add(f),this.audioEffectsTelemetryEvents.add(g)}}audioEffectsChanged(g,f){return g.payload.fallback!==f.payload.fallback||void 0!==f.payload.userNoiseSuppressionMethod&&g.payload.userNoiseSuppressionMethod!==f.payload.userNoiseSuppressionMethod||void 0!==f.payload.userAudioEffect&&g.payload.userAudioEffect!==f.payload.userAudioEffect}registerReconnectAttempt(g){this.reconnectStats.onReconnectAttempt(g)}registerReconnectAttemptCompleted(){this.reconnectStats.onReconnectCompleted()}registerReconnectAttemptRejected(){this.reconnectStats.onReconnectRejected()}setMediaLegId(g){this.mediaLegId=g}setId(g){this.sessionId=g}setError(g){g.type===qt.MEDIA_ERROR.incompatibleOffer&&(this.incompatibleOffer=!0),this.mediaError.type=g.type||qt.MEDIA_ERROR.internalError,this.mediaError.detail=g.detail||g.toString()}setRelay(g){this.relay={address:g.addresses.join(),expires:g.expires,realm:g.realm,credentials:!(!g.username||!g.password),ports:[g.udpPort?`udp:${g.udpPort}`:"",g.tcpPort?`tcp:${g.tcpPort}`:"",g.tlsPort?`tls:${g.tlsPort}`:""].join(","),fqdns:g.fqdns?g.fqdns.join():"none"}}setRelayManagerTimers(g){this.relayManagerTimers=g}setSendModalities(g){this.allowedAudioSend=g.audio.some((g=>hasSendDirectionality(g))),this.allowedVideoSend=g.video.some((g=>hasSendDirectionality(g))),this.allowedScreensharingSend=g.sharing.some((g=>hasSendDirectionality(g)))}setIceInitTimestamp(g){this.iceInitTime||(this.iceInitTime=g)}setFinalAnswerTimestamp(g){this.finalAnswerTime||(this.finalAnswerTime=g)}setIceConnectedStateTimestamp(g){this.iceConnectedStateTime||(this.iceConnectedStateTime=g)}dtmfResult(g){g?++this.dtmfSuccess:++this.dtmfFailure}setUsedDevices(g){this.usedDevices&&JSON.stringify(g)!==JSON.stringify(this.usedDevices)&&this.deviceSelectionChangeCount++,this.usedDevices=g}setDevicesCount(g){this.devicesCount=g}setMediaQosEnabled(g){this.mediaQosEnabled=g}setPortRangeConfigured(g){this.portRangeConfigured=g}devicesChanged(){this.devicesChangeCount++}deviceChangedByPoll(){this.devicesPollChangeCount++}registerOutputRawMediaAccess(){this.rawOutputAudioAccess.attempt++,this.rawOutputAudioAccess.timer.start()}registerSetInputRawMedia(g){this.rawInputAudioOverride.attempt++,g?this.rawInputAudioOverride.timer.start():this.rawInputAudioOverride.timer.stop()}getReport(){const g=this.usedDevices||{microphone:"none",speaker:"none",camera:"none"};return{RawOutputAudioAccessDurationRatio:this.getDurationRatio(this.rawOutputAudioAccess.timer.elapsed),RawOutputAudioAccessAttempted:this.rawOutputAudioAccess.attempt,RawInputAudioOverrideDurationRatio:this.getDurationRatio(this.rawInputAudioOverride.timer.elapsed),RawInputAudioOverrideAttempted:this.rawInputAudioOverride.attempt,SessionId:this.sessionId,CallNumber:this.callNumber,NoIceCandidatesBadEventCount:this.noIceCandidatesBadEventCount,NoIceCandidatesGoodEventCount:this.noIceCandidatesGoodEventCount,NoRelayIceCandidatesBadEventCount:this.noRelayIceCandidatesBadEventCount,NoRelayIceCandidatesGoodEventCount:this.noRelayIceCandidatesGoodEventCount,CameraInUseBadEventCount:this.cameraInUseBadEventCount,CameraInUseGoodEventCount:this.cameraInUseGoodEventCount,MicrophoneInUseBadEventCount:this.microphoneInUseBadEventCount,MicrophoneInUseGoodEventCount:this.microphoneInUseGoodEventCount,CameraFreezeStartEventCount:this.cameraFreezeStartEventCount,CameraFreezeEndEventCount:this.cameraFreezeEndEventCount,RetargetIncomingCount:this.retargetIncomingCount,RetargetOutgoingCount:this.retargetOutgoingCount,RetargetCompletedCount:this.retargetCompletedCount,RetargetRejectedCount:this.retargetRejectedCount,ReconnectAttemptedCount:this.reconnectAttemptedCount,ReconnectConnectedCount:this.reconnectConnectedCount,EscalationAttemptedCount:this.escalationAttemptedCount,EscalationCompletedCount:this.escalationCompletedCount,EscalationRejectedCount:this.escalationRejectedCount,CreationTime:this.getHpTimeFromMillis(this.creationTime),InitTime:this.getHpTimeFromMillis(this.creationTime),TerminationTime:this.getHpTimeFromMillis(this.terminationTime),CallDuration:this.getHpTimeFromMillis(this.getCurrentDuration()),InitialNegotiationType:this.initialNegotiationType||"none",InitialNegotiationCompleted:this.initialNegotiationCompleted,ActiveModalities:JSON.stringify(this.activeModalities),NegotiationCount:this.negotiationCount,RejectedNegotiationCount:this.rejectedNegotiationCount,MediaLegId:this.mediaLegId,MultiParty:this.multiParty,ErrorType:this.mediaError.type,ErrorDetail:this.mediaError.detail,TerminationReason:this.terminationReason,IncompatibleOffer:this.incompatibleOffer,DtmfSuccess:this.dtmfSuccess,DtmfFailure:this.dtmfFailure,Relay:this.relay?JSON.stringify(this.relay):"none",RelayManager:this.relayManagerTimers?JSON.stringify(this.relayManagerTimers):"none",AllowedAudioSend:this.allowedAudioSend,AllowedVideoSend:this.allowedVideoSend,AllowedScreensharingSend:this.allowedScreensharingSend,IceInitTime:this.getHpTimeFromMillis(this.iceInitTime),FinalAnswerTime:this.getHpTimeFromMillis(this.finalAnswerTime),IceConnectedStateTime:this.getHpTimeFromMillis(this.iceConnectedStateTime),UsedMicrophone:g.microphone,UsedSpeaker:g.speaker,UsedCamera:g.camera,DeviceSelectionChangeCount:this.deviceSelectionChangeCount,DevicesChangeCount:this.devicesChangeCount,DevicesPollChangeCount:this.devicesPollChangeCount,DevicesCount:this.devicesCount?JSON.stringify(this.devicesCount):"none",ETag:this.ETag||"",ConfigIds:this.configIds?Array.isArray(this.configIds)?this.configIds.join(","):this.configIds:"",CallMutedRatio:this.getDurationRatio(this.mute.elapsed),CallOsMuted:this.getHpTimeFromMillis(this.osMute.elapsed),CallHwSilent:this.getHpTimeFromMillis(this.hwSilent.elapsed),CallSwMuted:this.getHpTimeFromMillis(this.swMute.elapsed),CallSpeakerMuted:this.getHpTimeFromMillis(this.speakerMute.elapsed),CallIsSpeaking:this.getHpTimeFromMillis(this.isSpeaking.elapsed),NetworkRecvGood:this.networkRecv.getCount("Good")-1,NetworkRecvPoor:this.networkRecv.getCount("Poor"),NetworkRecvBad:this.networkRecv.getCount("Bad"),NetworkSendGood:this.networkSend.getCount("Good")-1,NetworkSendPoor:this.networkSend.getCount("Poor"),NetworkSendBad:this.networkSend.getCount("Bad"),NetworkRecvGoodRatio:this.getDurationRatio(this.networkRecv.getElapsed("Good")),NetworkRecvPoorRatio:this.getDurationRatio(this.networkRecv.getElapsed("Poor")),NetworkRecvBadRatio:this.getDurationRatio(this.networkRecv.getElapsed("Bad")),NetworkSendGoodRatio:this.getDurationRatio(this.networkSend.getElapsed("Good")),NetworkSendPoorRatio:this.getDurationRatio(this.networkSend.getElapsed("Poor")),NetworkSendBadRatio:this.getDurationRatio(this.networkSend.getElapsed("Bad")),DeviceEvents:JSON.stringify(this.deviceTelemetryEvents),DeviceList:JSON.stringify(this.deviceList),DeviceListDebug:JSON.stringify(this.deviceDebugStrings),VideoEffects:JSON.stringify(this.videoEffectsTelemetryEvents.items),AudioEffects:JSON.stringify(this.audioEffectsTelemetryEvents.items),PermissionStates:JSON.stringify(this.permissionStates),ReconnectAttempts:this.reconnectStats.getReport(),NetworkEvents:JSON.stringify(rebaseTime(limitArraySize22(this.sessionDiagnostics?.getObjectRef().reconnect?.tmpRecords,this.configProvider.config.diagnostics.telemetryLimits.numNetworkEvents),"startTime",this.creationTime)),ReconnectInProgress:this.reconnectStats.isReconnecting(),TransportReconnectedCount:this.transportReconnectedCount,UFDs:JSON.stringify(this.ufds),remoteUFDs:JSON.stringify(this.remoteUfds),MediaQosEnabled:this.mediaQosEnabled,PortRangeConfigured:this.portRangeConfigured,RollbackNegotiation:JSON.stringify(this.rollbackNegotiation),hardwareConcurrency:oa.hardwareConcurrency,GPUName:oa.unmaskedGlRenderer,Connection_Downlink:sampleseries(this.connectionDownlinkSeries.items,(g=>g)),Connection_EffectiveType:this.connectionEffectiveTypeSeries.items.filter((g=>g)).join(","),Connection_Rtt:sampleseries(this.connectionRttSeries.items,(g=>g)),Connection_SaveData:TT?.connection?.saveData,MediaByPassEnabled:!!this.configProvider.mediaConfig.mediaBypassEnabled,CallConstraints:JSON.stringify(this.configProvider.getCallConstraintsTelemetry()),DominantSpeaker:JSON.stringify(generateDominantSpeakerReport(this.sessionDiagnostics?.getObjectRef().dominantSpeaker,this.terminationTime))}}generateStatistics(g,f,S=!1){if(this.setMediaLegId(f.process()),"WebRtcMediaStats"!==g.type)throw new Error(`Unknown stats type - ${g.type}`);if(S){const g=this.deviceTelemetryEvents.length;this.deviceTelemetryEvents.splice(0,g-1),this.deviceDebugStrings=uy,this.audioEffectsTelemetryEvents.clear()}g.data.metrics=this.getReport();const v=this.sessionDiagnostics?.getObjectRef().statsErrors;if(v?.length)if(g.data.Extensions?.WebRTCStats?.statsErrors){const f=JSON.parse(g.data.Extensions.WebRTCStats.statsErrors);f.push(...v),g.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(f)}else g.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(v);const C={};return forOwnRec(g.data,((g,f,S)=>{let v=0;bT.test(g)?(v=13,C[f]="IPv4"):AT.test(g)&&(v=4,C[f]="IPv6"),S[f]={type:v,value:g,__VALUE__:!0}})),g.data.metrics.piiFields={type:0,value:JSON.stringify(C),__VALUE__:!0},g}registerTransportConnected(){this.transportDisconnected&&(this.transportDisconnected=!1,this.transportReconnectedCount++)}registerTransportDisconnected(){this.transportDisconnected=!0}registerTransportFailed(){this.transportDisconnected=!1}resetError(){this.setError({type:"none",detail:"none"})}offering(){return{started:()=>{this.currentNegotiationType="Offering",this.negotiationStarted()}}}answering(){return{started:()=>{this.currentNegotiationType="Answering",this.negotiationStarted()}}}negotiationStarted(){this.initialNegotiationType=this.initialNegotiationType||this.currentNegotiationType,++this.negotiationCount}current(){return{completed:g=>{this.initialNegotiationCompleted=!0,this.activeModalities=g,this.resetError()},rejected:()=>{++this.rejectedNegotiationCount}}}getDurationRatio(g){const f=this.getCurrentDuration();return g/(0!==f?f:1)}getCurrentDuration(){return this.durationTimer.elapsed}getHpTimeFromMillis(g){return 1e4*g}},RT=class{constructor(g,f,S,v){this.onActiveSpeakersChanged=g,this.onDominantSpeakersChanged=f,this.logger=S,this.diagnostics=v}setStrategy(g){this.disposeStrategy(),this.dshStrategy=g,this.dshStrategy?.setOnDominantSpeakerChanged(this.onDominantSpeakerHistoryChanged.bind(this)),this.diagnostics?.setCurrentActiveStrategy("client")}onContributingSourcesChanged(g){this.onActiveSpeakersChanged(g),this.diagnostics?.contributingSourcesChanged(),this.dshStrategy?.setSources(g)}onDominantSpeakerHistoryChanged(g,f){this.onDominantSpeakersChanged(g),this.diagnostics?.recordHistoryEvent(g,f),"client"!==f&&this.dshStrategy&&(this.logger.safe.info("Disposing client DSH strategy and switching to MP provided DSH"),this.disposeStrategy())}dispose(){this.disposeStrategy(),this.onActiveSpeakersChanged=null,this.onDominantSpeakersChanged=null}disposeStrategy(){this.dshStrategy?.dispose(),this.dshStrategy=null}},MT=class{constructor(g){this.listener=g,this.streams=[]}add(g){this.streams.some((f=>f.getId()===g.getId()))||(this.streams.push(g),this.listener.streamAdded(g))}remove(g){let f;remove2(this.streams,(S=>S.getId()===g&&(f=S,!0)))&&this.listener.streamRemoved(f)}getStreams(){return this.streams}clear(){this.streams.forEach((g=>g.dispose())),this.streams=[]}},wT=__toESM2(we()),OT=class{constructor(g,f,S){this.logger=g,this.qualityManager=f,this.configProvider=S}getControlItem(){return this.controlItem}setControlItem(g){this.controlItem=g}dispose(){this.controlItem=null}setVideoControlMessage(g){this.controlItem=this.messageToControlItem(g),this.logger.safe.info(`BW limit requested to ${this.controlItem.bandwidth}`)}modifyDescriptor(g){if(!this.controlItem)return g;const f=wT.parse(g.sdp);if(!f.media[1])return this.logger.unsafe.warn("video modality is disabled, skipping sdp modification, ",g),g;const S=this.getCurrentResolutionBitrate();this.logger.safe.info(`Select the BW limit as min of requested ${this.controlItem.bandwidth} and Current Resolution Max BR ${S}`);const v=this.getSessionBitrate(f),C=Math.min(S,this.controlItem.bandwidth,v);if(f.media[1].bandwidth)f.media[1].bandwidth[0].limit=C;else{const g={limit:C,type:"AS"};f.media[1].bandwidth=[g]}return g.sdp=wT.write(f),g}messageToControlItem(g){const f=new Zy(g.controlVideoStreaming.controlInfo[0].fmtParams),S="max-br",v=1.2;if(!f.contains(S))return null;const C=Math.round(+f.get(S)*v);return{sourceId:g.controlVideoStreaming.controlInfo[0].sourceId,streamMsid:g.controlVideoStreaming.controlInfo[0].streamMsid,bandwidth:C}}getCurrentResolutionBitrate(){const g=this.qualityManager.getCurrentResolution(),f=ei.Send.getResolutionByFs(g);return g&&f?Math.floor(ei.Send.getBitrateForResolution(f.width,f.height).maxBitrate/1e3):Number.MAX_VALUE}getSessionBitrate(g){let f=Number.MAX_SAFE_INTEGER;return this.configProvider.mediaConfig.maxBandwidthInKbps&&(f=this.configProvider.mediaConfig.maxBandwidthInKbps),g.bandwidth&&(f=Math.min(+g.bandwidth[0].limit,f)),f-(this.configProvider.config.audioBandwidthInKbps||0)}},DT=class{constructor(g,f,S){this.pc=g,this.configProvider=f,this.logger=S.createChild("MediaRollbackModifier")}modifyDescriptor(g){const f=wT.parse(g.sdp);return wT.parse(this.pc.localDescription.sdp).media.forEach(((g,S)=>{const v=f.media[S];(isMediaDisabled(g)&&!g.bundleOnly||!v||isMediaDisabled(v))&&(this.logger.safe.info(`Adding disabled media ${g.type}, position ${S}`),f.media[S]=disabledMedia(g.type,void 0,g.protocol,void 0))})),new m_(this.configProvider).modify(f),g.sdp=wT.write(f),g}},NT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(g){if(!g)return;const f=new Set;if(g.send){this.diagnostics.handlePresentationAudioInputLevel();for(const S of g.send)try{f.add(S.outboundRTP.id);let g=this.sendExtenders.get(S.outboundRTP.id)??new FT(this.diagnostics,this.configProvider);S.outboundRTP.bytesSent<g.lastBytes&&(g=new FT(this.diagnostics,this.configProvider)),this.sendExtenders.set(S.outboundRTP.id,g),g.processSample(S)}catch(g){this.diagnostics.addStatsError("AudioStatsProcessor:send",stringifyObject2(g))}}if(clearMap(this.sendExtenders,f),f.clear(),g.recv)for(const S of g.recv)try{f.add(S.inboundRTP.id);let g=this.recvExtenders.get(S.inboundRTP.id)??new kT(this.configProvider);S.inboundRTP.bytesReceived<g.lastBytes&&(g=new kT(this.configProvider)),this.recvExtenders.set(S.inboundRTP.id,g),g.processSample(S)}catch(g){this.diagnostics.addStatsError("AudioStatsProcessor:recv",stringifyObject2(g))}clearMap(this.recvExtenders,f)}},kT=class{constructor(g){this.configProvider=g,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new Xv(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.bytesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.totalSamplesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.concealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.silentConcealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.concealedRatioAverager=new Hv,this.stretchedRatioAverager=new Hv,this.codecSwitchesTracker=new zv,this.packetDurationTracker=new zv,this.jitterAverager=new Hv,this.jitterBufferDelayAverager=new Hv,this.lastBytes=0}processSample(g){let f,S,v,C,_;const T=this.lossRateCalculator.calculate(g.inboundRTP.packetsReceived,g.inboundRTP.packetsLost)??0;this.lastBytes=g.inboundRTP.bytesReceived,this.bytesReceivedDiff.captureSample(g.inboundRTP.bytesReceived,g.inboundRTP.timestamp),this.totalSamplesReceivedDiff.captureSample(g.inboundRTP.totalSamplesReceived,g.inboundRTP.timestamp),this.concealedSamplesDiff.captureSample(g.inboundRTP.concealedSamples,g.inboundRTP.timestamp),this.silentConcealedSamplesDiff.captureSample(g.inboundRTP.silentConcealedSamples,g.inboundRTP.timestamp);const I=this.bytesReceivedDiff.delta&&8*this.bytesReceivedDiff.delta;this.packetsDelta.captureSample(g.inboundRTP.packetsReceived,g.inboundRTP.timestamp),this.packetsLostDelta.captureSample(g.inboundRTP.packetsLost,g.inboundRTP.timestamp);const b=g.inboundRTP.jitterBufferDelay&&g.inboundRTP.jitterBufferEmittedCount&&round(g.inboundRTP.jitterBufferDelay/g.inboundRTP.jitterBufferEmittedCount*1e3,0);if(this.jitterAverager.captureSample(1e3*g.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(g.inboundRTP.jitterBufferDelay),f=this.totalSamplesReceivedDiff.delta&&this.concealedSamplesDiff.delta&&this.silentConcealedSamplesDiff.delta&&round((this.concealedSamplesDiff.delta-this.silentConcealedSamplesDiff.delta)/this.totalSamplesReceivedDiff.delta),g.customHealerStats){g.customHealerStats.numSamplesPerFrame&&(C=g.customHealerStats.decodedSamples/g.customHealerStats.numSamplesPerFrame,_=g.customHealerStats.cngSamples/g.customHealerStats.numSamplesPerFrame),f=g.customHealerStats.healedSamples/(g.customHealerStats.decodedSamples+g.customHealerStats.healedSamples),v=g.customHealerStats.concealSamples&&g.customHealerStats.concealSamples/(g.customHealerStats.decodedSamples+g.customHealerStats.healedSamples),S=g.customHealerStats.stretchSamples&&g.customHealerStats.stretchSamples/(g.customHealerStats.decodedSamples+g.customHealerStats.healedSamples);const T=g.customHealerStats.packetDurationInMs&&g.customHealerStats.packetDurationInMs>100?100:g.customHealerStats.packetDurationInMs;this.concealedRatioAverager.captureSample(v),this.stretchedRatioAverager.captureSample(S),this.codecSwitchesTracker.captureSample(`${g.customHealerStats.pullAdspPayloadType}`),this.packetDurationTracker.captureSample(`${T}`)}g.extensions={lossRate:T,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,healedRatio:f,jitterBufferMs:b,bitrate:I||0,customHealerStats:g.customHealerStats&&{concealedDataRatio:v,concealedDataRatioMax:this.concealedRatioAverager.maxSample,stretchedDataRatio:S,stretchedDataRatioMax:this.stretchedRatioAverager.maxSample,numberOfDecodedFrames:C,usageMetricsCodecId:this.codecSwitchesTracker.sortedDurations,percentageOfPtime:this.packetDurationTracker.durationRatios,pushPacketProcessingTimes:g.customHealerStats.pushProcessingTimes,pullPacketProcessingTimes:g.customHealerStats.pullProcessingTimes,pullProcessingTimePerStreamNumber:g.customHealerStats.pullProcessingTimePerStreamNumber,pullTimings:g.customHealerStats.pullTimings,cnpPushCount:g.customHealerStats.cnpPushCount,cnpPullCount:g.customHealerStats.cnpPullCount,numberOfCNFrames:_,redPacketsCount:g.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:g.customHealerStats.pullNumOfStreamsCounter},jitterAvg:round(this.jitterAverager.avg),jitterBufferDelayMs:round(this.jitterBufferDelayAverager.avg)},this.duration++}},LT=class{constructor(){this.duration=0,this.lossRateAverager=new Hv,this.bitrateAverager=new Hv,this.jitterBufferAverager=new Hv,this.jitterAverager=new Hv,this.jitterBufferDelayAverager=new Hv,this.healedRatioAverager=new Hv}processSample(g,f,S){const v=g[0],C={inboundRTP:v.inboundRTP};if(v.transport&&Object.defineProperty(C,"transport",{value:v.transport,configurable:!1,enumerable:!1}),v.codec&&(C.codec=v.codec),v.track&&(C.track=v.track),v.remoteOutboundRTP&&(C.remoteOutboundRTP=v.remoteOutboundRTP),v.extensions){this.lossRateAverager.captureSample(v.extensions.lossRate),this.bitrateAverager.captureSample(v.extensions.bitrate),this.healedRatioAverager.captureSample(v.extensions.healedRatio),this.jitterBufferAverager.captureSample(v.extensions.jitterBufferMs),this.jitterAverager.captureSample(1e3*v.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(v.inboundRTP.jitterBufferDelay);const g=v.inboundRTP.packetsReceived+v.inboundRTP.packetsLost;C.aggregated={lossRateMax:this.lossRateAverager.maxSample,lossRateAvg:this.lossRateAverager.avg,networkAvgLossRate:g>0?v.inboundRTP.packetsLost/g:0,packetsLostAvg:this.duration>0?v.inboundRTP.packetsLost/this.duration:0,duration:this.duration,bitrateAvg:round(this.bitrateAverager.avg,0),bitrateMax:round(this.bitrateAverager.maxSample,0),jitterAvg:this.jitterAverager.avg,jitterMax:this.jitterAverager.maxSample,avgJitterBufferSize:this.jitterBufferAverager.avg,healedRatioAvg:this.healedRatioAverager.avg,healedRatioMax:this.healedRatioAverager.maxSample,customHealerStats:v.extensions.customHealerStats&&{concealedDataRatio:v.extensions.customHealerStats.concealedDataRatio,concealedDataRatioMax:v.extensions.customHealerStats.concealedDataRatioMax,stretchedDataRatio:v.extensions.customHealerStats.stretchedDataRatio,stretchedDataRatioMax:v.extensions.customHealerStats.stretchedDataRatioMax,numberOfDecodedFrames:v.extensions.customHealerStats.numberOfDecodedFrames,usageMetricsCodecId:v.extensions.customHealerStats.usageMetricsCodecId,percentageOfPtime:v.extensions.customHealerStats.percentageOfPtime,pushPacketProcessingTimes:v.extensions.customHealerStats.pushPacketProcessingTimes,pullPacketProcessingTimes:v.extensions.customHealerStats.pullPacketProcessingTimes,pullProcessingTimePerStreamNumber:v.extensions.customHealerStats.pullProcessingTimePerStreamNumber,pullTimings:v.extensions.customHealerStats.pullTimings,cnpPushCount:v.extensions.customHealerStats.cnpPushCount,cnpPullCount:v.extensions.customHealerStats.cnpPullCount,numberOfCNFrames:v.extensions.customHealerStats.numberOfCNFrames,redPacketsCount:v.extensions.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:v.extensions.customHealerStats.pullNumOfStreamsCounter}},this.duration++}arrayLimitedPush22(f,C,S)}},FT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new Xv(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.bytesSendDiff=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.rttAverager=new Hv,this.lastBytes=0}processSample(g){const f=this.lossRateCalculator.calculate(g.remoteInboundRTP?.packetsReceived,g.remoteInboundRTP?.packetsLost)??0;this.packetsDelta.captureSample(g.outboundRTP.packetsSent,g.outboundRTP.timestamp),this.packetsLostDelta.captureSample(g.remoteInboundRTP?.packetsLost,g.remoteInboundRTP?.timestamp),this.lastBytes=g.outboundRTP.bytesSent,this.bytesSendDiff.captureSample(g.outboundRTP.bytesSent,g.outboundRTP.timestamp);const S=this.bytesSendDiff.delta;this.rttAverager.captureSample(1e3*(g.remoteInboundRTP?.roundTripTime??0)),g.extensions={lossRate:f,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,bitrate:S?8*S:0,rttAvg:round(this.rttAverager.avg),callIsMuted:this.diagnostics.callIsMuted,rawInputVolume:this.diagnostics.audioLevel},this.duration++}},xT=class{constructor(g){this.diagnostics=g,this.duration=0,this.lossRateAverager=new Hv,this.bitrateAverager=new Hv,this.rttAverager=new Hv}processSample(g,f,S){const v=g[0],C={outboundRTP:v.outboundRTP};v.transport&&Object.defineProperty(C,"transport",{value:v.transport,configurable:!1,enumerable:!1}),v.codec&&(C.codec=v.codec),v.track&&(C.track=v.track),v.mediaSource&&(C.mediaSource=v.mediaSource),v.remoteInboundRTP&&(C.remoteInboundRTP=v.remoteInboundRTP),v.extensions&&(this.lossRateAverager.captureSample(v.extensions.lossRate),this.bitrateAverager.captureSample(v.extensions.bitrate),this.rttAverager.captureSample(v.remoteInboundRTP?.roundTripTime),C.aggregated={duration:this.duration,lossRateMax:this.lossRateAverager.maxSample,bitrateAvg:round(this.bitrateAverager.avg,0),bitrateMax:round(this.bitrateAverager.maxSample,0),rttAvg:round(this.rttAverager.avg),rttMax:round(this.rttAverager.maxSample),rawInputVolume:this.diagnostics.audioLevel,audioLevel:v.track?.audioLevel??v.mediaSource?.audioLevel},this.duration++),arrayLimitedPush22(f,C,S)}},UT=M,VT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(g){if(!g)return;const f=new Set;if(g.send&&(0,UT.flatMap)(g.send,(g=>[g,...g.altLayouts??[]])).forEach((g=>{try{f.add(g.outboundRTP.id);let S=this.sendExtenders.get(g.outboundRTP.id)??new $T(this.diagnostics,this.configProvider);g.outboundRTP.bytesSent<S.lastBytes&&(S=new $T(this.diagnostics,this.configProvider)),this.sendExtenders.set(g.outboundRTP.id,S),S.processSample(g)}catch(g){this.diagnostics.addStatsError("VideoStatsProcessor:send",stringifyObject2(g))}})),clearMap(this.sendExtenders,f),f.clear(),g.recv)for(const S of g.recv)try{f.add(S.inboundRTP.id);let g=this.recvExtenders.get(S.inboundRTP.id)??new BT(this.configProvider);S.inboundRTP.bytesReceived<g.lastBytes&&(g=new BT(this.configProvider)),this.recvExtenders.set(S.inboundRTP.id,g),g.processSample(S)}catch(g){this.diagnostics.addStatsError("VideoStatsProcessor:recv",stringifyObject2(g))}clearMap(this.recvExtenders,f)}},BT=class{constructor(g){this.configProvider=g,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new Xv(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.bytesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.framesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.framesDecodedDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.trackFramesDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.decodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new Gv(2):new jv,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.freezeHistogram=new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.harmonicDecodedFps=new Kv(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.prevTimeToFirstFrame=-1,this.hasPrevFramerate=!1,this.lastBytes=0,this.macroblockStatsTracker=new iC}processSample(g){const f=this.lossRateCalculator.calculate(g.inboundRTP.packetsReceived,g.inboundRTP.packetsLost)??0;this.framesReceivedDelta.captureSample(g.inboundRTP.framesReceived,g.inboundRTP.timestamp),this.framesDecodedDelta.captureSample(g.inboundRTP.framesDecoded,g.inboundRTP.timestamp),this.trackFramesDelta.captureSample(g.inboundRTP.framesReceived??g.track?.framesReceived,g.inboundRTP.timestamp),this.packetsDelta.captureSample(g.inboundRTP.packetsReceived,g.inboundRTP.timestamp),this.packetsLostDelta.captureSample(g.inboundRTP.packetsLost,g.inboundRTP.timestamp);const S=this.framesReceivedDelta.delta,v=this.framesDecodedDelta.delta;this.harmonicDecodedFps.captureSample(v),this.decodeTimeDelta.captureSample(g.inboundRTP.totalDecodeTime,g.inboundRTP.timestamp);const C=this.decodeTimeDelta.delta&&v&&round(this.decodeTimeDelta.delta/v*1e3,2),_=v>0&&S>0,T=g.renderer?.timeToFirstFrame??(_?0:-1);this.freezeHistogram.active=-1!==T&&-1!==this.prevTimeToFirstFrame&&!_,"sharing"===g.mediaEntity?.modality&&this.configProvider.config.diagnostics.features.useTwoSampleVBSSFreezeDetection&&(this.freezeHistogram.active=this.freezeHistogram.active&&!this.hasPrevFramerate),this.prevTimeToFirstFrame=T,this.hasPrevFramerate=_,this.lastBytes=g.inboundRTP.bytesReceived,this.bytesReceivedDelta.captureSample(g.inboundRTP.bytesReceived,g.inboundRTP.timestamp);const I=this.bytesReceivedDelta.delta,b=g.inboundRTP.jitterBufferEmittedCount&&round((g.inboundRTP.jitterBufferDelay??0)/g.inboundRTP.jitterBufferEmittedCount*1e3),A=calcMacroblockRate(g.inboundRTP.frameWidth,g.inboundRTP.frameHeight,S||0),P=calcMacroblockRate(g.inboundRTP.frameWidth,g.inboundRTP.frameHeight,v||0);this.macroblockStatsTracker.captureSample(A,P),g.extensions={lossRate:f,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,frameRateReceived:S,frameRateDecoded:v,trackRecvFps:this.trackFramesDelta.delta,decodeTime:C||0,jitterBufferMs:b,bitrate:I?8*I:0,isFrozen:this.freezeHistogram.active,macroblockRateReceived:A,macroblockRateDecoded:P,macroblockRateStats:this.macroblockStatsTracker.getReport(),longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,powerEfficient:void 0!==g.inboundRTP.powerEfficientDecoder?g.inboundRTP.powerEfficientDecoder:isPowerEfficient(g.inboundRTP.decoderImplementation),totalFreezeFraction:this.duration?this.freezeHistogram.totalDuration/this.duration:0,fpsHarmonicAverage:round(this.harmonicDecodedFps.harmonicMean)},this.duration++}},HT=class{constructor(g){this.configProvider=g,this.duration=0,this.lossRateAverager=new Hv,this.bitrateAverager=new Hv,this.jitterAverager=new Hv,this.frameRateAverager=new Hv,this.freezeHistogram=new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.harmonicDecodedFps=new Kv(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.resolutionDurations=new zv,this.codecCalculator=new nC}processSample(g,f,S){const v=g.sort(((g,f)=>f.inboundRTP.frameHeight*f.inboundRTP.frameWidth-g.inboundRTP.frameHeight*g.inboundRTP.frameWidth))[0],C={inboundRTP:v.inboundRTP};v.transport&&Object.defineProperty(C,"transport",{value:v.transport,configurable:!1,enumerable:!1}),v.codec&&(C.codec=v.codec,this.configProvider.config.isAv1Allowed&&"sharing"===v.mediaEntity?.modality&&this.codecCalculator.captureSample(v.codec.mimeType,v.renderer?.msi)),v.track&&(C.track=v.track),v.remoteOutboundRTP&&(C.remoteOutboundRTP=v.remoteOutboundRTP),v.extensions&&(C.extensions=v.extensions),v.extensions&&(this.harmonicDecodedFps.captureSample(v.extensions.frameRateDecoded),this.lossRateAverager.captureSample(v.extensions.lossRate),this.bitrateAverager.captureSample(v.extensions.bitrate),this.jitterAverager.captureSample(1e3*(v.inboundRTP.jitter??0)),this.frameRateAverager.captureSample(v.extensions.frameRateReceived??v.extensions.frameRateDecoded),this.freezeHistogram.active=v.extensions.isFrozen,v.inboundRTP.frameWidth&&v.inboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${v.inboundRTP.frameWidth}x${v.inboundRTP.frameHeight}`),C.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,avgFrameRate:round(this.frameRateAverager.avg),fpsHarmonicAverage:round(this.harmonicDecodedFps.harmonicMean),avgJitterBufferSize:round(this.jitterAverager.avg),bitrateAvg:round(this.bitrateAverager.avg,0),bitrateMax:round(this.bitrateAverager.maxSample,0),bitrateMinNonZero:round(this.bitrateAverager.minNonZeroSample,0),ongoingFreezeDuration:this.freezeHistogram.ongoingDuration,numFreezes:this.freezeHistogram.numEvents,avgFreezeDuration:round(this.freezeHistogram.avgDuration),longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,freezeCountHistogram:this.freezeHistogram.counts,freezeTimestampsHistogram:this.freezeHistogram.timestamps,numResolutionSwitches:this.resolutionDurations.changeCount,resolutionDurations:this.resolutionDurations.durations,resolutionDurationRatios:this.resolutionDurations.durationRatios,macroblockRateStats:v.extensions.macroblockRateStats,codecReport:this.codecCalculator?.report},this.duration++),arrayLimitedPush2(f,C,S)}},$T=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new Xv(this.configProvider.config.disableNormalizationToCalculatePacketLossRate),this.lossRateAverager=new Hv,this.freezeHistogram=new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.hasPrevFramerate=!1,this.captureFreezeIntervalsCount=0,this.bytesSendDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.encodedFramesDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.sentFramesDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.harmonicEncodedFps=new Kv(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.encodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new Gv(2):new jv,this.qpDelta=this.useLastSampleDeltaPerSecondConverter?new Gv(3):new jv,this.fsOvershoot=new Qv("fs"),this.fpsOvershoot=new Qv("fps",1),this.brOvershoot=new Qv("br"),this.plisDelta=new jv,this.pliRate=new eC(60),this.resolutionSwitcherTracker=new tC(this.configProvider.config.diagnostics.collectionLimits.numResolutionSwitches),this.bitrateAverager=new Hv,this.rttAverager=new Hv,this.powerEfficientEncoderChangeTracker=new rC(this.configProvider.config.diagnostics.collectionLimits.numPowerEfficientEncoderEvents),this.lastBytes=0}processSample(g){const f=this.lossRateCalculator.calculate(g.remoteInboundRTP?.packetsReceived,g.remoteInboundRTP?.packetsLost);this.lossRateAverager.captureSample(f),this.plisDelta.captureSample(g.outboundRTP.pliCount),this.pliRate.captureSample(this.plisDelta.delta),this.packetsDelta.captureSample(g.outboundRTP.packetsSent,g.outboundRTP.timestamp),this.packetsLostDelta.captureSample(g.remoteInboundRTP?.packetsLost,g.remoteInboundRTP?.timestamp),this.lastBytes=g.outboundRTP.bytesSent,this.bytesSendDelta.captureSample(g.outboundRTP.bytesSent,g.outboundRTP.timestamp);const S=this.bytesSendDelta.delta,v=S?8*S:void 0;this.bitrateAverager.captureSample(v),this.rttAverager.captureSample(1e3*(g.remoteInboundRTP?.roundTripTime??0)),this.encodedFramesDelta.captureSample(g.outboundRTP.framesEncoded,g.outboundRTP.timestamp);const C=this.encodedFramesDelta.delta;this.sentFramesDelta.captureSample(g.outboundRTP.framesSent,g.outboundRTP.timestamp);const _=this.sentFramesDelta.delta||0;this.harmonicEncodedFps.captureSample(C);const T=g.mediaSource?.framesPerSecond;0===T&&void 0!==this.lastCaptureFramerate&&this.lastCaptureFramerate>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFramerate=T;const I=C>0&&_>0;this.freezeHistogram.active=!I,"sharing"===g.mediaEntity?.modality&&this.configProvider.config.diagnostics.features.useTwoSampleVBSSFreezeDetection&&(this.freezeHistogram.active=this.freezeHistogram.active&&!this.hasPrevFramerate),this.hasPrevFramerate=I,this.encodeTimeDelta.captureSample(g.outboundRTP.totalEncodeTime,g.outboundRTP.timestamp);const b=this.encodeTimeDelta.delta&&C&&round(this.encodeTimeDelta.delta/C*1e3,2);this.qpDelta.captureSample(g.outboundRTP.qpSum,g.outboundRTP.timestamp);const A=this.qpDelta.delta&&C&&round(this.qpDelta.delta/C,2);g.outboundRTP.frameWidth&&g.outboundRTP.frameHeight&&this.resolutionSwitcherTracker.captureSample(g.outboundRTP.frameWidth,g.outboundRTP.frameHeight);const P=this.diagnostics.deviceManager?.latestCameraOpenResolution,R=g.appliedCapabilities??g.requestedCapabilities;R&&(void 0!==g.outboundRTP.frameHeight&&void 0!==g.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(g.outboundRTP.frameHeight/16*(g.outboundRTP.frameWidth/16),R.maxFs),this.fpsOvershoot.captureSample(_,R.maxFps),R.maxBr&&this.brOvershoot.captureSample(v,R.maxBr));const M=[...this.fsOvershoot.events,...this.brOvershoot.events,...this.fpsOvershoot.events];if(M.sort(((g,f)=>g.timestamp-f.timestamp)),g.outboundRTP.frameHeight&&(g.outboundRTP.powerEfficientEncoder||g.outboundRTP.encoderImplementation)){const f=void 0!==g.outboundRTP.powerEfficientEncoder?g.outboundRTP.powerEfficientEncoder:isPowerEfficient(g.outboundRTP.encoderImplementation);this.powerEfficientEncoderChangeTracker.captureSample(f,g.outboundRTP.frameHeight)}g.extensions={cameraOpenResolution:P,lossRate:f,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,pliRate:this.pliRate.getRate(),frameRateEncoded:this.encodedFramesDelta.delta,frameRateSent:_,bitrate:v||0,encodeTime:b||0,qp:A||0,isFrozen:this.freezeHistogram.active,longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,ongoingFreezeDuration:this.freezeHistogram.ongoingDuration,freezeCountHistogram:this.freezeHistogram.counts,captureFreezeIntervalsCount:this.captureFreezeIntervalsCount,isFsOvershooting:this.fsOvershoot.isOvershooting,isFpsOvershooting:this.fpsOvershoot.isOvershooting,isBrOvershooting:this.brOvershoot.isOvershooting,totalFsOvershootDuration:this.fsOvershoot.totalDuration,totalFpsOvershootDuration:this.fpsOvershoot.totalDuration,totalBrOvershootDuration:this.brOvershoot.totalDuration,overshootEvents:M,powerEfficient:this.powerEfficientEncoderChangeTracker.curPowerEfficientEncoderState,powerEfficientEncoderEvents:this.powerEfficientEncoderChangeTracker.events,powerEfficientEncoderEventOnCount:this.powerEfficientEncoderChangeTracker.eventOnCount,powerEfficientEncoderEventOffCount:this.powerEfficientEncoderChangeTracker.eventOffCount,bitrateAvg:round(this.bitrateAverager.avg,0),rttAvg:round(this.rttAverager.avg)},this.duration++}},jT=class{constructor(g){this.configProvider=g,this.duration=0,this.lossRateAverager=new Hv,this.bitrateAverager=new Hv,this.sendBWEAverager=new Hv,this.rttAverager=new Hv,this.framerateAverager=new Hv,this.captureFpsAverager=new Hv,this.captureFreezeIntervalsCount=0,this.lastCaptureFps=void 0,this.resolutionDurations=new zv,this.fsOvershoot=new Qv("fs"),this.fpsOvershoot=new Qv("fps",1),this.brOvershoot=new Qv("br"),this.harmonicEncodedFps=new Kv(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax)}processSample(g,f,S){g.length>1&&g.sort(((g,f)=>{const S=g.appliedCapabilities??g.requestedCapabilities,v=f.appliedCapabilities??f.requestedCapabilities;return S?.maxMbps&&v?.maxMbps?v.maxMbps-S.maxMbps:0}));const v=g[0],C={outboundRTP:v.outboundRTP};if(v.transport&&Object.defineProperty(C,"transport",{value:v.transport,configurable:!1,enumerable:!1}),v.codec&&(C.codec=v.codec),v.track&&(C.track=v.track),v.mediaSource&&(C.mediaSource=v.mediaSource),v.remoteInboundRTP&&(C.remoteInboundRTP=v.remoteInboundRTP),v.extensions&&(C.extensions=v.extensions),v.extensions){this.lossRateAverager.captureSample(v.extensions.lossRate),this.bitrateAverager.captureSample(v.extensions.bitrate),this.sendBWEAverager.captureSample(v.transport?.selectedCandidatePair?.availableOutgoingBitrate),this.rttAverager.captureSample(v.remoteInboundRTP?.roundTripTime),this.framerateAverager.captureSample(v.extensions.frameRateSent);const g=v.mediaSource?.framesPerSecond;this.captureFpsAverager.captureSample(g),0===g&&void 0!==this.lastCaptureFps&&this.lastCaptureFps>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFps=g,v.outboundRTP.frameWidth&&v.outboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${v.outboundRTP.frameWidth}x${v.outboundRTP.frameHeight}`);const f=v.appliedCapabilities??v.requestedCapabilities;f&&(void 0!==v.outboundRTP.frameHeight&&void 0!==v.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(v.outboundRTP.frameHeight/16*(v.outboundRTP.frameWidth/16),f.maxFs),this.fpsOvershoot.captureSample(v.extensions.frameRateSent,f.maxFps),f.maxBr&&this.brOvershoot.captureSample(v.extensions?.bitrate,f.maxBr)),this.harmonicEncodedFps.captureSample(v.extensions.frameRateEncoded);const S=[...this.fsOvershoot.events,...this.fpsOvershoot.events,...this.brOvershoot.events];S.sort(((g,f)=>g.timestamp-f.timestamp)),C.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,frameRateAvg:round(this.framerateAverager.avg),captureFramerateAvg:round(this.captureFpsAverager.avg),fpsHarmonicAverage:round(this.harmonicEncodedFps.harmonicMean),qpAvg:round(v.outboundRTP.qpSum/v.outboundRTP.framesSent),rttAvg:round(this.rttAverager.avg),bitrateAvg:round(this.bitrateAverager.avg,0),bitrateMax:round(this.bitrateAverager.maxSample,0),bitrateMinNonZero:round(this.bitrateAverager.minNonZeroSample,0),bweAvg:round(this.sendBWEAverager.avg,0),captureFreezeIntervalsCount:this.captureFreezeIntervalsCount,numResolutionSwitches:this.resolutionDurations.changeCount,resolutionDurations:this.resolutionDurations.durations,resolutionDurationRatios:this.resolutionDurations.durationRatios,isFsOvershooting:this.fsOvershoot.isOvershooting,isFpsOvershooting:this.fpsOvershoot.isOvershooting,isBrOvershooting:this.brOvershoot.isOvershooting,totalFsOvershootDuration:this.fsOvershoot.totalDuration,totalFpsOvershootDuration:this.fpsOvershoot.totalDuration,totalBrOvershootDuration:this.brOvershoot.totalDuration,overshootEvents:S},this.duration++}arrayLimitedPush2(f,C,S)}},GT=class{constructor(g){this.configProvider=g,this.samplesCountPerSubscription=0,this.data=new Uv(this.configProvider.config.diagnostics.collectionLimits.numVideoSubscriptionStats)}prepareCollectingStatsOnSubscribed(g){this.samplesCountPerSubscription=0,this.data.add({timestamp:Date.now(),framesDecoded:[],bytesReceived:[],height:[],msi:g})}captureStatsOnSubscribed(g,f,S){if(this.samplesCountPerSubscription>=this.configProvider.config.diagnostics.collectionLimits.numVideoStatsAfterSubscription)return;const v=getLast(this.data.items);v&&(g&&v.framesDecoded.push(g),f&&v.bytesReceived.push(f),S&&v.height.push(S)),this.samplesCountPerSubscription++}get videoStatsOnSubscribed(){return this.data.items}},qT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.extenders=new Map}processStats(g){const f=new Set;for(const S in g)try{f.add(S);const v=g[S],C=this.extenders.get(v.id)??new WT(this.configProvider,this.diagnostics);this.extenders.set(v.id,C),C.processSample(v)}catch(g){this.diagnostics.addStatsError("TransportStatsProcessor",stringifyObject2(g))}clearMap(this.extenders,f)}},WT=class{constructor(g,f){this.configProvider=g,this.diagnostics=f,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.bwJumpsHistogramCollector=new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),this.sendBWEAverager=new Hv,this.recvBWEAverager=new Hv,this.sendBW=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.recvBW=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.sendBWAverager=new Hv,this.recvBWAverager=new Hv}processSample(g){this.sendBWEAverager.captureSample(g.selectedCandidatePair?.availableOutgoingBitrate),this.recvBWEAverager.captureSample(g.selectedCandidatePair?.availableIncomingBitrate),this.sendBW.captureSample(g.selectedCandidatePair?.bytesSent,g.selectedCandidatePair?.timestamp),this.recvBW.captureSample(g.selectedCandidatePair?.bytesReceived,g.selectedCandidatePair?.timestamp);const f=this.sendBW.delta,S=this.recvBW.delta,v=f?8*f:void 0,C=S?8*S:void 0;this.sendBWAverager.captureSample(v),this.recvBWAverager.captureSample(C);const _=g.selectedCandidatePair?.availableOutgoingBitrate;_&&(this.bwJumpsHistogramCollector.active=this.bwJumpsHistogramCollector.active&&_<this.configProvider.config.webrtcBWJumpUpperLimit||_<this.configProvider.config.webrtcBWJumpLowerLimit),g.extensions={sendBWEAvg:round(this.sendBWEAverager.avg,0),sendBWEMax:round(this.sendBWEAverager.maxSample,0),recvBWEAvg:round(this.recvBWEAverager.avg,0),recvBWEMax:round(this.recvBWEAverager.maxSample,0),sendBitrate:v,recvBitrate:C,sendBWAvg:round(this.sendBWAverager.avg,0),sendBWMax:round(this.sendBWAverager.maxSample,0),recvBWAvg:round(this.recvBWAverager.avg,0),recvBWMax:round(this.recvBWAverager.maxSample,0),bwJumpsHistogram:this.bwJumpsHistogramCollector.counts,reflexiveLocalIP:this.diagnostics.reflexiveLocalIP}}},zT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.extenders=new Map}processStats(g){if(!g)return;const f=new Set;for(const S of g)try{f.add(S.id);const g=this.extenders.get(S.id)??new KT(this.configProvider);this.extenders.set(S.id,g),g.processSample(S)}catch(g){this.diagnostics.addStatsError("DataChannelStatsProcessor",stringifyObject2(g))}clearMap(this.extenders,f)}},KT=class{constructor(g){this.configProvider=g,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.sendBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.recvBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.sendMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv,this.recvMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new Gv:new jv}processSample(g){this.sendBytesDeltaCalculator.captureSample(g.bytesSent,g.timestamp),this.recvBytesDeltaCalculator.captureSample(g.bytesReceived,g.timestamp);const f=this.sendBytesDeltaCalculator.delta,S=this.recvBytesDeltaCalculator.delta,v=f?8*f:void 0,C=S?8*S:void 0;this.sendMessagesDeltaCalculator.captureSample(g.messagesSent,g.timestamp),this.recvMessagesDeltaCalculator.captureSample(g.messagesReceived,g.timestamp);const _=this.sendMessagesDeltaCalculator.delta,T=this.recvMessagesDeltaCalculator.delta;g.extensions={sendBitrate:v,recvBitrate:C,sendMessageRate:_,recvMessageRate:T}}},JT=class{constructor(g,f,S,v){this.slidingWindowSize=g,this.maxDeviation=f,this.minBandwidth=S,this.directionalityCheck=v,this.slidingWindow=new Uv(this.slidingWindowSize),this.currentModality=null,this.previousModality=null,this.inProcess=!1}processBandwidth(g,f,S){this.currentModality?this.handleStopEvent(f,S):this.handleStartEvent(f,S),this.inProcess&&(this.stabilizationTime++,this.slidingWindow.add(g),this.inProcess=!this.slidingWindow.isFull||!this.isBandwidthStable())}getReport(g=!1){if(void 0!==this.stabilizationTime)return{time:this.inProcess?this.stabilizationTime:Math.max(this.stabilizationTime-this.slidingWindowSize,0),bandwidth:g?round(this.averageBandwidth,2):this.averageBandwidth,finished:!this.inProcess,modality:this.previousModality}}handleStartEvent(g,f){this.currentModality=this.GetModalityString(g),f&&this.currentModality&&!this.previousModality&&(this.previousModality=this.currentModality,this.stabilizationTime=0,this.slidingWindow.clear(),this.inProcess=!0)}handleStopEvent(g,f){f&&(this.directionalityCheck(g.audio)||this.directionalityCheck(g.video)||this.directionalityCheck(g.sharing))||(this.currentModality=null,this.inProcess=!1)}GetModalityString(g){return[this.directionalityCheck(g.audio)?qt.MODALITY.audio:null,this.directionalityCheck(g.video)?qt.MODALITY.video:null,this.directionalityCheck(g.sharing)?qt.MODALITY.sharing:null].filter(Boolean).join(", ")}isBandwidthStable(){if(this.averageBandwidth=average(this.slidingWindow.items),this.averageBandwidth<this.minBandwidth)return!1;{const g=this.averageBandwidth*this.maxDeviation,f=this.averageBandwidth-g,S=this.averageBandwidth+g;return this.slidingWindow.items.every((g=>isInRange(g,f,S)))}}},YT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.uplinkStabilizationTelemetry=new JT(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,hasSendDirectionality),this.downlinkStabilizationTelemetry=new JT(this.configProvider.config.downlinkBWStabilizationSlidingWindowSize,this.configProvider.config.downlinkBWStabilizationMaxDeviation,this.configProvider.config.downlinkBWStabilizationMinBandwidth,hasReceiveDirectionality),this.bandwidthCalculator=new Zv,this.bandwidthAvg=new Hv}processStats(g){const f=this.diagnostics.getObjectRef(),S=f?.negotiation.activeModalities;if(!S||!g.transports)return;const v=g.transports[Object.keys(g.transports)[0]],C=f?.reportedReceiveBandwidth?.[f.reportedReceiveBandwidth.length-1],_=v?.selectedCandidatePair?.availableOutgoingBitrate,T=g.audio?.send?.length>0||g.video?.send?.length>0||g.sharing?.send?.length>0,I=g.audio?.recv?.length>0||g.video?.recv?.length>0||g.sharing?.recv?.length>0;this.bweType!==f?.negotiation.bweType&&(this.bandwidthCalculator=new Zv,this.bandwidthAvg=new Hv,this.bweType=f?.negotiation.bweType);const b="REMB"===f?.negotiation.bweType?"availableIncomingBitrate":"availableOutgoingBitrate",A=v?.selectedCandidatePair?.[b];this.bandwidthCalculator.captureSample(A),this.bandwidthAvg.captureSample(A);try{this.uplinkStabilizationTelemetry.processBandwidth(_,S,T),this.downlinkStabilizationTelemetry.processBandwidth(C,S,I)}catch(g){this.diagnostics.addStatsError("BandwidthStatsProcessor",stringifyObject2(g))}}getStabilizedReport(g=!1){return this.uplinkStabilizationTelemetry.getReport(g)}getDownlinkStabilizedReport(g=!1){return this.downlinkStabilizationTelemetry.getReport(g)}calculateBwPercentiles(){if(!this.bandwidthCalculator.getFirst())return;const g=this.configProvider.config.bwPercentiles,f={};return g.forEach((g=>{Object.defineProperty(f,g,{value:this.bandwidthCalculator.calculatePercentile(g/100),enumerable:!0})})),f}getBandwidthReport(){return{startOfTheCall:this.bandwidthCalculator.getFirst(),endOfTheCall:this.bandwidthCalculator.getLast(),std:this.bandwidthCalculator.calculateStd(),bwPercentiles:this.calculateBwPercentiles(),avgBwe:round(this.bandwidthAvg.avg,2)}}},QT=class{constructor(g,f){this.diagnostics=g,this.configProvider=f,this.videoSimulcastStreamsData={},this.videoLayoutProcessor=new XT(this.diagnostics,qt.MODALITY.video),this.sharingSimulcastStreamsData={},this.sharingLayoutProcessor=new XT(this.diagnostics,qt.MODALITY.sharing)}processStats(g){if(g.video?.send?.length){const f=g.video.send[0],S=[f,...f.altLayouts??[]];this.processSimulcastStream(S,this.videoSimulcastStreamsData),this.videoLayoutProcessor.processLayout(S)}if(g.sharing?.send?.length){const f=g.sharing.send[0],S=[f,...f.altLayouts??[]];this.processSimulcastStream(S,this.sharingSimulcastStreamsData),this.sharingLayoutProcessor.processLayout(S)}this.diagnostics.simulcastReport=this.getSimulcastDiagnostics()}processSimulcastStream(g,f){const{numAggregatedSamples:S}=this.configProvider.config.diagnostics.telemetryLimits;for(const v of g){const g=v.outboundRTP.rid;if(!g)continue;f[g]??(f[g]={sentLayerProcessor:new eI,appliedLayerProcessor:new eI,requestedLayerProcessor:new eI,encoderProcessor:new ZT,debugResolutionTracker:new zv,outboundStats:[],report:{ssrc:v.outboundRTP.ssrc,time:{requested:0,applied:0,sent:0},duration:{requested:0,applied:0,sent:0},restarts:{requested:0,applied:0,sent:0},resolution:{requested:{},applied:{},sent:{}},framerate:{requested:{},applied:{},sent:{}},bitrate:{requested:{},applied:{},sent:{}},encoder:{},stats:{},overshootEvents:[]}});const C=f[g],{sentLayer:_,requestedLayer:T,appliedLayer:I}=this.getLayers(v);C.sentLayerProcessor.processLayer(_),C.appliedLayerProcessor.processLayer(I),C.requestedLayerProcessor.processLayer(T),C.encoderProcessor.processVideo(v),I&&_&&C.debugResolutionTracker.captureSample(`${I.width}x${I.height}:${_.width}x${_.height}`),arrayLimitedPush2(C.outboundStats,v.outboundRTP,S),C.report.time.sent=C.sentLayerProcessor.getTime(),C.report.time.applied=C.appliedLayerProcessor.getTime(),C.report.time.requested=C.requestedLayerProcessor.getTime(),C.report.duration.sent=C.sentLayerProcessor.getDuration(),C.report.duration.applied=C.appliedLayerProcessor.getDuration(),C.report.duration.requested=C.requestedLayerProcessor.getDuration(),C.report.restarts.sent=C.sentLayerProcessor.getRestarts(),C.report.restarts.applied=C.appliedLayerProcessor.getRestarts(),C.report.restarts.requested=C.requestedLayerProcessor.getRestarts(),C.report.resolution.sent=C.sentLayerProcessor.getResolutionDurations(),C.report.resolution.applied=C.appliedLayerProcessor.getResolutionDurations(),C.report.resolution.requested=C.requestedLayerProcessor.getResolutionDurations(),C.report.resolution.debug=C.debugResolutionTracker.durations,C.report.framerate.sent=C.sentLayerProcessor.getFpsDurations(),C.report.framerate.applied=C.appliedLayerProcessor.getFpsDurations(),C.report.framerate.requested=C.requestedLayerProcessor.getFpsDurations(),C.report.bitrate.sent=C.sentLayerProcessor.getBitrateDurations(),C.report.bitrate.applied=C.appliedLayerProcessor.getBitrateDurations(),C.report.bitrate.requested=C.requestedLayerProcessor.getBitrateDurations(),C.report.encoder=C.encoderProcessor.getEncoderReport(),C.report.stats.fir=sampleseries(C.outboundStats,(g=>g.firCount)),C.report.stats.nack=sampleseries(C.outboundStats,(g=>g.nackCount)),C.report.stats.pli=sampleseries(C.outboundStats,(g=>g.pliCount)),C.report.stats.packetsSent=sampleseries(C.outboundStats,(g=>g.packetsSent)),C.report.overshootEvents=v.extensions?.overshootEvents,C.report.totalBrOvershootDuration=v.extensions?.totalBrOvershootDuration,C.report.totalFpsOvershootDuration=v.extensions?.totalFpsOvershootDuration,C.report.totalFsOvershootDuration=v.extensions?.totalFsOvershootDuration,C.report.totalFreezeDuration=v.extensions?.totalFreezeDuration,C.report.ongoingFreezeDuration=v.extensions?.ongoingFreezeDuration,C.report.freezeHistogram=v.extensions?.freezeCountHistogram}}getSimulcastDiagnostics(){if(!isEmpty(this.videoSimulcastStreamsData)||!isEmpty(this.sharingSimulcastStreamsData))return{video:{streams:Object.fromEntries(Object.entries(this.videoSimulcastStreamsData).map((([g,{report:f}])=>[g,f]))),layouts:this.videoLayoutProcessor.getLayoutReport()},sharing:{streams:Object.fromEntries(Object.entries(this.sharingSimulcastStreamsData).map((([g,{report:f}])=>[g,f]))),layouts:this.sharingLayoutProcessor.getLayoutReport()}}}getLayers(g){const f=g.outboundRTP.rid,S=this.diagnostics.getObjectRef().qualityManager,findCurrentCapability=g=>Object.values(g).find((g=>g.rid===f)),v="sharing"===g.mediaEntity?.modality?findCurrentCapability(S.currentSharingSsrcAppliedCapabilities):findCurrentCapability(S.currentVideoSsrcAppliedCapabilities),C="sharing"===g.mediaEntity?.modality?findCurrentCapability(S.currentSharingSsrcRequestedCapabilities):findCurrentCapability(S.currentVideoSsrcRequestedCapabilities);return{sentLayer:g.outboundRTP.frameHeight&&{height:g.outboundRTP.frameHeight,width:g.outboundRTP.frameWidth,framerate:g.extensions?.frameRateSent,bitrate:g.extensions?.bitrate},appliedLayer:v&&convertStreamSenderParamsToLayer(v),requestedLayer:C&&convertStreamSenderParamsToLayer(C)}}},XT=class{constructor(g,f){this.diagnostics=g,this.modality=f,this.sentResolutionTracker=new zv,this.requestedResolutionTracker=new zv,this.appliedResolutionTracker=new zv,this.debugResolutionTracker=new zv}processLayout(g){const getLayoutResolution=g=>g.filter((g=>g.width&&g.height)).sort(((g,f)=>g.height-f.height)).map((g=>`${g.width}x${g.height}`)).join(":"),mapCapabilities=g=>Object.values(g).map(convertStreamSenderParamsToLayer),f=getLayoutResolution(g.map((g=>({height:g.outboundRTP.frameHeight,width:g.outboundRTP.frameWidth,framerate:g.extensions?.frameRateSent,bitrate:g.extensions?.bitrate})))),S=this.diagnostics.getObjectRef().qualityManager,v="sharing"===this.modality?S.currentSharingSsrcAppliedCapabilities:S.currentVideoSsrcAppliedCapabilities,C="sharing"===this.modality?S.currentSharingSsrcRequestedCapabilities:S.currentVideoSsrcRequestedCapabilities,_=getLayoutResolution(mapCapabilities(v)),T=getLayoutResolution(mapCapabilities(C));f&&this.sentResolutionTracker.captureSample(f),T&&this.requestedResolutionTracker.captureSample(T),_&&this.appliedResolutionTracker.captureSample(_),_&&f&&this.debugResolutionTracker.captureSample(`${_}->${f}`)}getLayoutReport(){return{requested:this.requestedResolutionTracker.durations,sent:this.sentResolutionTracker.durations,applied:this.appliedResolutionTracker.durations,debug:this.debugResolutionTracker.durations}}},ZT=class{constructor(){this.report={}}processVideo(g){var f,S;const{encoderImplementation:v,frameWidth:C,frameHeight:_,rid:T}=g.outboundRTP,{encodeTime:I}=g.extensions;if(!v||!_)return;const b=getEncoderName(v,T),A=`${C}x${_}`;(f=this.report)[b]??(f[b]={resolutionTracker:new zv,encodingHistograms:{},report:{resolution:{},encodeTime:{},restarts:0}});const P=this.report[b];P.resolutionTracker.captureSample(A),(S=P.encodingHistograms)[A]??(S[A]=new zv),P.encodingHistograms[A].captureSample(bucketizeEncodeTime(I)),P.report.resolution=P.resolutionTracker.durations,P.report.encodeTime[A]=P.encodingHistograms[A].durations,this.prevEncoder&&this.prevEncoder!==b&&P.report.restarts++,this.prevEncoder=b}getEncoderReport(){return Object.fromEntries(Object.entries(this.report).map((([g,{report:f}])=>[g,f])))}},eI=class{constructor(){this.resolutionTracker=new zv,this.fpsTracker=new zv,this.bitrateTracker=new zv,this.durationTracker=new eT,this.startedAt=0}processLayer(g){g?(this.startedAt||(this.startedAt=Jt()),this.durationTracker.start(),this.resolutionTracker.captureSample(`${g.width}x${g.height}`),this.fpsTracker.captureSample(bucketizeFramerate(g.framerate)),this.bitrateTracker.captureSample(bucketizeBitrate(g.bitrate))):this.durationTracker.stop()}getResolutionDurations(){return this.resolutionTracker.durations}getFpsDurations(){return this.fpsTracker.durations}getBitrateDurations(){return this.bitrateTracker.durations}getRestarts(){return Math.max(0,this.durationTracker.count-1)}getTime(){return this.startedAt}getDuration(){return this.durationTracker.elapsed}};function convertStreamSenderParamsToLayer(g){const f={...ei.Send.getResolutionByFs(g.maxFs)};return 405===g.maxFs&&(f.width=426,f.height=240),{width:f.width,height:f.height,framerate:g.maxFps,bitrate:g.maxBr}}function getEncoderName(g,f){if(g.startsWith("SimulcastEncoderAdapter")){const S=g.indexOf("(")+1,v={},C=g.indexOf(")");g.substring(S,C).split(",").forEach(((g,f)=>{v[`${f+1}`]=g.trim()})),g=v[f]??"Unknown"}switch(g){case"OpenH264":return"H264:SW";case"ExternalEncoder":case"MediaFoundationVideoEncodeAccelerator":case"VideoToolbox":case"WMFVideoEncoder":case"VTVideoEncoder":case"VaapiVideoEncodeAccelerator":return"H264:HW";default:return"H264:Other"}}function bucketizeBitrate(g){return bucketize(g,[{limit:4e6,label:"4M+"},{limit:25e5,label:"2.5M-4M"},{limit:15e5,label:"1.5M-2.5M"},{limit:1e6,label:"1M-1.5M"},{limit:8e5,label:"800k-1M"},{limit:5e5,label:"500k-800k"},{limit:25e4,label:"250k-500k"},{limit:1e5,label:"100k-250k"},{limit:5e4,label:"50k-100k"},{limit:1e4,label:"10k-50k"},{limit:0,label:"0-10k"}])}function bucketizeFramerate(g){return bucketize(g,[{limit:60,label:"60+"},{limit:30,label:"31-60"},{limit:15,label:"16-30"},{limit:7,label:"8-15"},{limit:3,label:"4-7"},{limit:1,label:"1-3"}])}function bucketizeEncodeTime(g){return bucketize(g,[{limit:100,label:"100+ ms"},{limit:30,label:"30-100 ms"},{limit:10,label:"10-30 ms"},{limit:5,label:"5-10 ms"},{limit:2,label:"2-5 ms"},{limit:1,label:"1-2 ms"}])}function bucketize(g,f){for(const{limit:S,label:v}of f)if(g>S)return v;return`${g}`}var tI=class{constructor(g,f){this.configProvider=g,this.diagnostics=f,this.dataChannelStatsProcessor=new zT(this.diagnostics,this.configProvider),this.transportStatsProcessor=new qT(this.diagnostics,this.configProvider),this.audioStatsProcessor=new NT(this.diagnostics,this.configProvider),this.videoStatsProcessor=new VT(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new VT(this.diagnostics,this.configProvider),this.bandwidthStatsProcessor=new YT(this.diagnostics,this.configProvider),this.simulcastStatsProcessor=new QT(this.diagnostics,this.configProvider),this.macroblockStatsTracker=new iC,this.statsAggregators={audio:{recv:new LT,send:new xT(this.diagnostics)},video:{recv:new HT(this.configProvider),send:new jT(this.configProvider)},sharing:{recv:new HT(this.configProvider),send:new jT(this.configProvider)}},this.aggregatedModalityStats={},this.recvVideoStreamsCounter=new $v,this.multiviewData={},this.multiviewKeySet=new Set,this.statsOnSubscribedData={video:{},sharing:{}},this.statsOnSubscribed={video:[],sharing:[]},this.diagnostics.aggregatedStatsRef=this.aggregatedModalityStats,this.diagnostics.statsOnSubscribed=this.statsOnSubscribed,this.diagnostics.bandwidthDiagnostic=this.bandwidthStatsProcessor}processStats(g){this.dataChannelStatsProcessor.processStats(g.data),this.transportStatsProcessor.processStats(g.transports),this.audioStatsProcessor.processStats(g.audio),this.videoStatsProcessor.processStats(g.video),this.sharingStatsProcessor.processStats(g.sharing),this.bandwidthStatsProcessor.processStats(g),this.diagnostics.bwStabilizationTime=this.bandwidthStatsProcessor.getStabilizedReport(!0),this.diagnostics.bwDownlinkStabilizationTime=this.bandwidthStatsProcessor.getDownlinkStabilizedReport(!0),this.recvVideoStreamsCounter.captureSample(g.video?.recv?.length),this.diagnostics.recvVideoStreamsCount={min:this.recvVideoStreamsCounter.min,max:this.recvVideoStreamsCounter.max,mode:this.recvVideoStreamsCounter.mode};try{this.processAggregated(g)}catch(g){this.diagnostics.addStatsError("webrtcStatistics:processAggregated",stringifyObject2(g))}try{this.processMultiview(g.video?.recv??[])}catch(g){this.diagnostics.addStatsError("webrtcStatistics:processMultiview",stringifyObject2(g))}try{this.simulcastStatsProcessor.processStats(g)}catch(g){this.diagnostics.addStatsError("webrtcStatistics:processSimulcastStats",stringifyObject2(g))}try{const g=navigator?.connection;g&&this.diagnostics.addNetworkInfo({downlink:g.downlink,rtt:g.rtt,effectiveType:g.effectiveType,saveData:g.saveData})}catch(g){this.diagnostics.addStatsError("webrtcStatistics:processStats(networkInfo)",stringifyObject2(g))}try{this.processMacroblockRateStats(g.video?.recv)}catch(g){this.diagnostics.addStatsError("webrtcStatistics: processMacroblockRateStats",stringifyObject2(g))}}signalNoConnection(){this.transportStatsProcessor=new qT(this.diagnostics,this.configProvider),this.audioStatsProcessor=new NT(this.diagnostics,this.configProvider),this.videoStatsProcessor=new VT(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new VT(this.diagnostics,this.configProvider)}processMultiview(g){const f=new Set;for(const S of g){const g=S.inboundRTP.id;f.add(g);let v=this.multiviewData[g];v&&this.multiviewKeySet.has(g)?v.stats.duration++:(v={bitrateAverager:new Hv,jitterAverager:new Hv,frameRateAverager:new Hv,freezeHistogram:new Wv(this.configProvider.config.diagnostics.collectionLimits.numOfHistogramSamples),resolutionDurations:new zv,isRenderingEvents:[],statsOnSubscribed:new GT(this.configProvider),stats:{ssrc:S.inboundRTP.ssrc,startTime:Date.now(),duration:0,framesDecoded:[],bytesReceived:[],height:[],width:[]}},v.statsOnSubscribed.prepareCollectingStatsOnSubscribed(S.renderer?.msi),this.multiviewData[g]=v),v.statsOnSubscribed.captureStatsOnSubscribed(S.inboundRTP.framesDecoded,S.inboundRTP.bytesReceived,S.inboundRTP.frameHeight),v.bitrateAverager.captureSample(S.extensions?.bitrate),v.jitterAverager.captureSample(1e3*(S.inboundRTP.jitter??0)),v.frameRateAverager.captureSample(S.extensions.frameRateReceived),v.freezeHistogram.active=S.extensions?.isFrozen,S.inboundRTP.frameWidth&&S.inboundRTP.frameHeight&&v.resolutionDurations.captureSample(`${S.inboundRTP.frameWidth}x${S.inboundRTP.frameHeight}`);const C=S.renderer?.isRendering??!1;(!v.isRenderingEvents.length&&C||v.isRenderingEvents.length&&getLast(v.isRenderingEvents).isRendering!==C)&&arrayLimitedPush22(v.isRenderingEvents,{isRendering:C,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents),v.stats.frameRateAvg=round(v.frameRateAverager.avg),v.stats.bitrateAvg=round(v.bitrateAverager.avg,0),v.stats.bitrateMax=round(v.bitrateAverager.maxSample,0),v.stats.bitrateMinNonZero=round(v.bitrateAverager.minNonZeroSample),v.stats.freezeHistogram=v.freezeHistogram.counts,v.stats.freezeTimestamps=v.freezeHistogram.timestamps,v.stats.avgFreezeDuration=round(v.freezeHistogram.avgDuration),v.stats.totalFreezeDuration=v.freezeHistogram.totalDuration,v.stats.ongoingFreeze=v.freezeHistogram.active,v.stats.ongoingFreezeDuration=v.freezeHistogram.ongoingDuration,v.stats.numResolutionSwitches=v.resolutionDurations.changeCount,v.stats.rendererSize=`${S.renderer?.rendererSize?.width}x${S.renderer?.rendererSize?.height}`,v.stats.resolutionDurations=v.resolutionDurations.durations,v.stats.timeToFirstFrame=S.renderer?.timeToFirstFrame,v.stats.timeToFirstFrameSinceSubscriptionStart=S.renderer?.timeToFirstFrameSinceSubscriptionStart,v.stats.isRenderingEvents=v.isRenderingEvents,v.stats.statsOnSubscribed=v.statsOnSubscribed.videoStatsOnSubscribed,v.stats.msi=S.renderer?.msi,v.stats.rendererStates=S.renderer?.rendererStates,arrayLimitedPush22(v.stats.framesDecoded,S.inboundRTP.framesDecoded,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),arrayLimitedPush22(v.stats.bytesReceived,S.inboundRTP.bytesReceived,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),arrayLimitedPush22(v.stats.height,S.inboundRTP.frameHeight,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),arrayLimitedPush22(v.stats.width,S.inboundRTP.frameWidth,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples);const _=S.extensions?.macroblockRateStats??{};for(const g in _)v.stats[g]=round(_[g],0)}this.diagnostics.multiViewStats=Object.values(this.multiviewData).map((g=>g.stats)),this.multiviewKeySet=f}processAggregated(g){for(const f of["audio","video","sharing"])if(g[f])for(const S in g[f])this.processAggregatedModality(g,f,S)}processAggregatedModality(g,f,S){var v,C;const _=g[f]?.[S]?.length??0;_>0&&((v=this.aggregatedModalityStats)[f]??(v[f]={}),(C=this.aggregatedModalityStats[f])[S]??(C[S]=[]),_>1&&("audio"===f||"sharing"===f)&&this.diagnostics.addStatsError("webrtcStatistics:processAggregatedModality",`Multiple ${f} ${S} streams: ${_}`),this.statsAggregators[f][S].processSample(g[f][S],this.aggregatedModalityStats[f][S],this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),"sharing"!==f&&"video"!==f||"recv"!==S||this.processStatsOnSubscribed(g[f][S],f))}processStatsOnSubscribed(g,f){const S=new Set;for(const v of g)if(v.inboundRTP){const g=`${v.inboundRTP.id}x${v.renderer?.msi}`;let C=this.statsOnSubscribedData[f]?.[g];S.add(g),C||(C=new GT(this.configProvider),C.prepareCollectingStatsOnSubscribed(v.renderer?.msi),this.statsOnSubscribedData[f][g]=C,this.statsOnSubscribed[f].push(...C.videoStatsOnSubscribed)),C.captureStatsOnSubscribed(v.inboundRTP.framesDecoded,v.inboundRTP.bytesReceived)}clearObj(this.statsOnSubscribedData[f],S)}processMacroblockRateStats(g){if(!g?.length)return;let f=0,S=0;for(const v of g)f+=v.extensions?.macroblockRateReceived,S+=v.extensions?.macroblockRateDecoded;this.macroblockStatsTracker.captureSample(f,S),this.diagnostics.setTotalVideoRecvMblocksRates(this.macroblockStatsTracker.getReport())}},iI=M,nI=class{constructor(g,f,S,v){this.logger=g,this.configProvider=f,this.diagnostics=S,this.mediaManager=v,this.webrtcStats=new tI(this.configProvider,this.diagnostics),this.ssrcToRecvTrackMap=new Map,this.activeChannels={}}setAudioDecoderStatsProvider(g){this.audioDecoderStatsProvider=g}signalNoConnection(){this.webrtcStats.signalNoConnection()}processRawReport(g){this.diagnostics.latestRawReport=g;const f={loopTime:-1,fetchTime:-1,convertTime:-1,processingTime:-1,legacyProcessingTime:-1};try{let S=Jt(),v=S;const C=this.convertStatsReport(g);return C.perfCounters=f,S=Jt(),f.convertTime=S-v,v=S,this.webrtcStats.processStats(C),this.diagnostics.addStatsReport(C),S=Jt(),f.processingTime=S-v,C}catch(g){const f=stringifyObject2(g);return this.logger.safe.error(`Error processing raw stats: ${f}`),void this.diagnostics.addStatsError("StatisticsGatherer:processRawReport",f)}}setSsrcTrackPair(g,f){null===f?this.ssrcToRecvTrackMap.delete(g):this.ssrcToRecvTrackMap.set(g,f)}convertStatsReport(g){const f={transports:this.processTransportStats(g)};return this.appendPcStats(g,f),this.appendSendMediaStats(g,f),this.appendRecvMediaStats(g,f),g["data-channel"]&&(f.data=Object.values(g["data-channel"])),f}processTransportStats(g){if(g.transport){const f={};for(const S in g.transport){const v=g.transport[S];if(f[S]=shallowClone(v),v.selectedCandidatePairId){const C=shallowClone(g["candidate-pair"][v.selectedCandidatePairId]);C.localCandidate=g["local-candidate"][C.localCandidateId],C.remoteCandidate=g["remote-candidate"][C.remoteCandidateId],f[S].selectedCandidatePair=C}v.localCertificateId&&g.certificate&&(f[S].localCertificate=g.certificate[v.localCertificateId]),v.remoteCertificateId&&g.certificate&&(f[S].remoteCertificate=g.certificate[v.remoteCertificateId])}return f}if(g["candidate-pair"]){const f={};for(const S in g["candidate-pair"]){const v=shallowClone(g["candidate-pair"][S]);v.selected&&(v.localCandidate=g["local-candidate"][v.localCandidateId],v.remoteCandidate=g["remote-candidate"][v.remoteCandidateId],f.faketransport={id:"faketransport",timestamp:v.timestamp,type:"transport",selectedCandidatePair:v,selectedCandidatePairId:v.id})}return f}}appendPcStats(g,f){let S="";g["peer-connection"]&&(Object.keys(g["peer-connection"]).forEach((g=>{""===S?S=g:(this.logger.safe.error(`Unexpected second peer connection stats id ${g}, also found ${S}`),this.diagnostics.addStatsError("StatisticsGatherer","Unexpected second peer connection stats"))})),f.peerConnection=g["peer-connection"][S])}appendSendMediaStats(g,f){var S,v,C,_;for(const T in g["outbound-rtp"]){const I=g["outbound-rtp"][T],b={outboundRTP:I};I.codecId&&g.codec&&(b.codec=g.codec[I.codecId]),Object.defineProperty(b,"transport",{value:f.transports[I.transportId??"faketransport"],configurable:!1,enumerable:!1}),I.remoteId&&g["remote-inbound-rtp"]&&(b.remoteInboundRTP=g["remote-inbound-rtp"][I.remoteId]),I.mediaSourceId&&g["media-source"]&&(b.mediaSource=g["media-source"][I.mediaSourceId]),I.trackId&&g.track&&(b.track=g.track[I.trackId]);const A=getEntityByLocalTrack(this.mediaManager,b.track?.trackIdentifier??b.mediaSource?.trackIdentifier,I.rid)??getEntityByLocalSSRC(this.mediaManager,I.ssrc,I.rid)??getMediaEntityByMid(this.mediaManager,b.outboundRTP.mid,I.rid);if(!A?.getLocalTrackId())continue;b.mediaEntity=A.serialize(),!b.mediaSource&&b.mediaEntity&&g["media-source"]&&(b.mediaSource=Object.values(g["media-source"]).find((g=>g.trackIdentifier===b.mediaEntity.localTrackId)));const P="video"===I.kind?"sharing"===A?.getModality()?"sharing":"video":I.kind;if((S=this.activeChannels)[P]??(S[P]={}),(v=this.activeChannels[P]).send??(v.send={}),hasSendDirectionality(this.diagnostics.getObjectRef().negotiation.activeModalities?.[P])){if(f[P]||(f[P]={}),f[P].send||(f[P].send=[]),"video"===I.kind){const g=getRequestedCapabilitiesBySsrc(this.diagnostics,P,I.ssrc)??getRequestedCapabilitiesBySsrc(this.diagnostics,P,0);g&&(b.requestedCapabilities=g);const S=getAppliedCapabilitiesBySsrc(this.diagnostics,P,I.ssrc)??getAppliedCapabilitiesBySsrc(this.diagnostics,P,0);S&&(b.appliedCapabilities=S);const v=f[P].send.find((g=>g.outboundRTP.trackId===b.outboundRTP.trackId));if(v){const g=parseInt(v.outboundRTP.rid,10)>parseInt(b.outboundRTP.rid,10);if(!v.altLayouts&&g&&(v.altLayouts=[]),g)v.altLayouts.push(b);else{b.altLayouts=[],b.altLayouts.push(v);const g=f[P].send.indexOf(v);f[P].send[g]=b}continue}}this.activeChannels[P].send[I.id]=b,f[P].send.push(b)}else this.activeChannels[P].send[I.id]&&"sharing"!==P&&(f.inactiveTracks??(f.inactiveTracks={}),(C=f.inactiveTracks)[P]??(C[P]={}),(_=f.inactiveTracks[P]).send??(_.send=[]),f.inactiveTracks[P].send.push(this.activeChannels[P].send[I.id]))}}appendRecvMediaStats(g,f){var S,v,C,_;const T=this.diagnostics.getObjectRef().subscriptionManager?.subscribedTrackIds;for(const I in g["inbound-rtp"]){const b=g["inbound-rtp"][I],A={inboundRTP:b};b.codecId&&g.codec&&(A.codec=g.codec[b.codecId]),"audio"===b.kind&&A.inboundRTP.ssrc===this.audioDecoderStatsProvider?.ssrc&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("replacing recv audio stats with custom audio decoder stats"),A.codec||(A.codec={transportId:b.transportId??"faketransport",id:"fakeCodec",payloadType:999,timestamp:b.timestamp,type:"codec",mimeType:"unk"}),A.codec.mimeType=this.audioDecoderStatsProvider.codecName,A.inboundRTP=(0,iI.merge)(A.inboundRTP,this.audioDecoderStatsProvider.getWebRtcCompatibleStats()),A.customHealerStats=this.audioDecoderStatsProvider.getWasmStats()),f.transports[b.transportId??"faketransport"]&&Object.defineProperty(A,"transport",{value:f.transports[b.transportId??"faketransport"],configurable:!1,enumerable:!1}),b.remoteId&&g["remote-outbound-rtp"]&&(A.remoteOutboundRTP=g["remote-outbound-rtp"][b.remoteId]);const P=A.inboundRTP.trackIdentifier??this.ssrcToRecvTrackMap.get(b.ssrc);if(b.trackId||P){b.trackId&&g.track?A.track=g.track[b.trackId]:P&&(A.track={id:"ssrcToTrackId",kind:b.kind,timestamp:b.timestamp,type:"track",trackIdentifier:P});const f=getRendererDiagnosticsByTrack(this.diagnostics,A.track?.trackIdentifier);f&&(A.renderer=f)}const R=getEntityByRemoteTrack(this.mediaManager,A.track?.trackIdentifier)??getEntityByRemoteSSRC(this.mediaManager,b.ssrc);if(!R)continue;A.mediaEntity=R.serialize();const M="video"===b.kind&&A.track?"sharing"===R?.getModality()?"sharing":"video":b.kind;(S=this.activeChannels)[M]??(S[M]={}),(v=this.activeChannels[M]).recv??(v.recv={}),"video"!==b.kind||T.some((g=>g&&g===A.track?.trackIdentifier))?hasReceiveDirectionality(this.diagnostics.getObjectRef().negotiation.activeModalities?.[M])&&(f[M]||(f[M]={}),f[M].recv||(f[M].recv=[]),this.activeChannels[M].recv[b.id]=A,f[M].recv.push(A)):this.activeChannels[M].recv[b.id]&&"sharing"!==M&&(f.inactiveTracks??(f.inactiveTracks={}),(C=f.inactiveTracks)[M]??(C[M]={}),(_=f.inactiveTracks[M]).recv??(_.recv=[]),f.inactiveTracks[M].recv.push(this.activeChannels[M].recv[b.id]))}}};function verifyRidIfPresent(g,f){return!f||g.getSimulcastContext()?.activeRids.map(String).some((g=>g===f))}function getEntityByRemoteSSRC(g,f){return g.getMediaEntities().find((g=>g.getRemoteSsrc()===f))}function getEntityByRemoteTrack(g,f){const S=g.getMediaEntities();return void 0!==f?S.find((g=>g.getRemoteTrackId()===f)):void 0}function getEntityByLocalSSRC(g,f,S){return g.getMediaEntities().find((g=>g.getLocalSsrc()===f&&verifyRidIfPresent(g,S)))}function getEntityByLocalTrack(g,f,S){const v=g.getMediaEntities();return f?v.find((g=>g.getLocalTrackId()===f&&verifyRidIfPresent(g,S))):void 0}function getRequestedCapabilitiesBySsrc(g,f,S){const v=g.getObjectRef().qualityManager;return"video"===f?v?.currentVideoSsrcRequestedCapabilities[`${S}`]:"sharing"===f?v?.currentSharingSsrcRequestedCapabilities[`${S}`]:void 0}function getAppliedCapabilitiesBySsrc(g,f,S){const v=g.getObjectRef().qualityManager;return"video"===f?v?.currentVideoSsrcAppliedCapabilities[`${S}`]:"sharing"===f?v?.currentSharingSsrcAppliedCapabilities[`${S}`]:void 0}function getRendererDiagnosticsByTrack(g,f){return g.getObjectRef().remoteVideoManager?.renderers.find((g=>g.trackId===f))}function getMediaEntityByMid(g,f,S){const v=g.getMediaEntities();return f?v.find((g=>g.getMid()===f&&verifyRidIfPresent(g,S))):void 0}var rI=class{constructor(){this.googCandidatePair={},this.ssrc={},this.googComponent={},this.VideoBwe={bweforvideo:{}}}},sI=class{constructor(){this.statistics=new rI,this.statsDiffMap=new Map,this.ssrcTrackMap=new Map}build(g){return this.statistics=new rI,this.constructGoogCandidatePair(g),this.constructGoogSsrc(g),this.constructGoogComponent(g),this.constructDataChannel(g),this.constructBwe(g),this.statistics}setSsrcTrackPair(g,f){null===f?this.ssrcTrackMap.delete(g):this.ssrcTrackMap.set(g,f)}setAudioDecoderStatsProvider(g){this.audioDecoderStatsProvider=g}constructGoogSsrc(g){const f={};if(g.hasOwnProperty("outbound-rtp")){const S=g["outbound-rtp"];Object.keys(S).forEach((v=>{const C=`ssrc_${S[v].ssrc}_send`,_=this.constructSendSsrc(g,S[v]);f[C]=_}))}if(g.hasOwnProperty("inbound-rtp")){const S=g["inbound-rtp"];Object.keys(S).forEach((v=>{const C=`ssrc_${S[v].ssrc}_recv`,_=this.constructRecvSsrc(g,S[v]);f[C]=_}))}this.statistics.ssrc=f}constructSendSsrc(g,f){const S=f.trackId?g.track[f.trackId]:null,v=f.mediaSourceId?g["media-source"][f.mediaSourceId]:null,C=g["remote-inbound-rtp"]?.[f.remoteId],_=`ssrc_${f.ssrc}_send`,T=v?.trackIdentifier??S?.trackIdentifier??this.ssrcTrackMap.get(f.ssrc);let I={id:_,ssrc:f.ssrc,mediaType:f.mediaType??f.kind,bytesSent:f.bytesSent,bytesSentDiff:this.calculateDiff(_,f.bytesSent,4),packetsSent:f.packetsSent,packetsLost:C?.packetsLost,jitter:C?.jitter,googRtt:this.getRtt(C),googCodecName:this.getCodec(g,f.codecId),transportId:f.transportId,googTrackId:T};return"audio"===I.mediaType&&(I={...I,...this.constructAudioSendSsrc(f,v)}),"video"===I.mediaType&&(I={...I,...this.constructVideoSendSsrc(f,v,_,S)}),removeUndefinedFields(I)}constructAudioSendSsrc(g,f){return{audioInputLevel:f?.audioLevel,totalAudioEnergy:f?.totalAudioEnergy,fecPacketsSent:g.fecPacketsSent}}constructVideoSendSsrc(g,f,S,v){return{framesEncoded:g.framesEncoded,googFrameRateEncoded:this.calculateDiff(S,g.framesEncoded,2),googFrameRateSent:this.calculateDiff(S,g.framesSent??v?.framesSent,1),googFrameRateInput:f?.framesPerSecond,googFrameHeightSent:g.frameHeight??v?.frameHeight,googFrameWidthSent:g.frameWidth??v?.frameWidth,googFrameHeightInput:f?.height,googFrameWidthInput:f?.width,hugeFramesSent:g.hugeFramesSent??v?.hugeFramesSent,keyFramesEncoded:g.keyFramesEncoded,qpSum:g.qpSum,qp:this.calculateDiff(S,g.qpSum,8),googPlisReceived:g.pliCount,googFirsReceived:g.firCount,googNacksReceived:g.nackCount,qualityLimitationDurations:g.qualityLimitationDurations,qualityLimitationReason:g.qualityLimitationReason,qualityLimitationResolutionChanges:g.qualityLimitationResolutionChanges,codecImplementationName:g.encoderImplementation,rid:g.rid,encodeTime:g.totalEncodeTime&&Math.round(1e3*this.calculateDiff(S,g.totalEncodeTime,6))}}constructRecvSsrc(g,f){const S=f.trackId?g.track[f.trackId]:null,v=`ssrc_${f.ssrc}_recv`,C=f.trackIdentifier??S?.trackIdentifier??this.ssrcTrackMap.get(f.ssrc);let _={id:v,ssrc:f.ssrc,mediaType:f.mediaType??f.kind,bytesReceived:f.bytesReceived,bytesReceivedDiff:this.calculateDiff(v,f.bytesReceived,5),packetsReceived:f.packetsReceived,packetsLost:f.packetsLost,jitter:f.jitter,googJitterBufferMs:f.jitterBufferEmittedCount&&Math.round(f.jitterBufferDelay/f.jitterBufferEmittedCount*1e3),googCodecName:this.getCodec(g,f.codecId),googTrackId:C,transportId:f.transportId};return"audio"===_.mediaType&&(_={..._,...this.constructAudioRecvSsrc(f,S)}),"video"===_.mediaType&&(_={..._,...this.constructVideoRecvSsrc(f,v,S)}),removeUndefinedFields(_)}constructAudioRecvSsrc(g,f){const S=this.audioDecoderStatsProvider?.ssrc===g.ssrc?this.audioDecoderStatsProvider?.getWebRtcCompatibleStats():g,v={audioOutputLevel:S.audioLevel??f?.audioLevel,totalAudioEnergy:S.totalAudioEnergy??f?.totalAudioEnergy,concealedSamples:S.concealedSamples,silentConcealedSamples:S.silentConcealedSamples,totalSamplesReceived:S.totalSamplesReceived,healedRatio:S.totalSamplesReceived&&(S.concealedSamples-S.silentConcealedSamples)/S.totalSamplesReceived,fecPacketsReceived:S.fecPacketsReceived,fecPacketsDiscarded:S.fecPacketsDiscarded,packetsDiscarded:S.packetsDiscarded};if(this.audioDecoderStatsProvider?.ssrc===g.ssrc){v.googJitterBufferMs=S.jitterBufferEmittedCount&&Math.round(S.jitterBufferDelay/S.jitterBufferEmittedCount*1e3),v.googCodecName=this.audioDecoderStatsProvider.codecName;const g=this.audioDecoderStatsProvider.getDecoderStats();v.pushCount=g.pushCount,v.pushErrCount=g.pushErrCount,v.pullCount=g.pullCount,v.pullErrCount=g.pullErrCount}return v}constructVideoRecvSsrc(g,f,S){return{framesDecoded:g.framesDecoded,googFrameRateDecoded:this.calculateDiff(f,g.framesDecoded,3),googFrameRateReceived:this.calculateDiff(f,g.framesReceived??S?.framesReceived,0),googFrameHeightReceived:g.frameHeight??S?.frameHeight,googFrameWidthReceived:g.frameWidth??S?.frameWidth,keyFramesDecoded:g.keyFramesDecoded,googPlisSent:g.pliCount,googFirsSent:g.firCount,googNacksSent:g.nackCount,codecImplementationName:g.decoderImplementation,decodeTime:g.totalDecodeTime&&Math.round(1e3*this.calculateDiff(f,g.totalDecodeTime,7))}}constructGoogCandidatePair(g){const f=g["candidate-pair"];f&&Object.keys(f).forEach((S=>{const v=this.constructPair(g,f[S]);this.statistics.googCandidatePair[v.id]=v}))}constructPair(g,f){const S=g["local-candidate"][f.localCandidateId],v=g["remote-candidate"][f.remoteCandidateId];return removeUndefinedFields({bytesReceived:f.bytesReceived,bytesSent:f.bytesSent,googTransportType:S.protocol,googRtt:f.currentRoundTripTime?Math.round(1e3*f.currentRoundTripTime):void 0,googLocalAddress:`${S.ip?S.ip:S.address}:${S.port}`,googLocalCandidateType:S.candidateType,localRelayProtocol:S.relayProtocol,localNetworkType:S.networkType,googRemoteAddress:`${v.ip?v.ip:v.address}:${v.port}`,googRemoteCandidateType:v.candidateType,googActiveConnection:f.nominated,requestsReceived:f.requestsReceived,requestsSent:f.requestsSent,responsesReceived:f.responsesReceived,responsesSent:f.responsesSent,consentRequestsSent:f.consentRequestsSent,id:f.id,remoteCandidateId:f.remoteCandidateId,localCandidateId:f.localCandidateId,googWritable:f.writable,selected:f.selected,packetsDiscardedOnSend:f.packetsDiscardedOnSend})}constructGoogComponent(g){g.transport&&Object.keys(g.transport).forEach((f=>{this.statistics.googComponent[f]={id:f,selectedCandidatePairId:g.transport[f].selectedCandidatePairId}}))}constructDataChannel(g){if(!g.hasOwnProperty("data-channel"))return;const f=g["data-channel"];this.statistics.data=Object.keys(f).map((g=>{const S=f[g];return{bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,dataChannelIdentifier:S.dataChannelIdentifier,label:S.label,messagesReceived:S.messagesReceived,messagesSent:S.messagesSent,protocol:S.protocol,state:S.state,timestamp:S.timestamp,type:S.type}}))}constructBwe(g){const f=Object.values(g["outbound-rtp"]??{})?.find((g=>{const f=g.mediaType??g.kind;return"audio"===f||"video"===f}));if(!f)return;const S=g.transport?.[f.transportId];if(!S)return;const v=g["candidate-pair"]?.[S.selectedCandidatePairId];if(!v)return;const C={googAvailableSendBandwidth:v.availableOutgoingBitrate,googAvailableReceiveBandwidth:v.availableIncomingBitrate};this.statistics.VideoBwe.bweforvideo=removeUndefinedFields(C)}getRtt(g){const f=g?.roundTripTime;return f?Math.round(1e3*f):void 0}getCodec(g,f){if(f&&g.codec&&g.codec[f])return g.codec[f].mimeType.split("/").pop()}calculateDiff(g,f,S){if(void 0===f)return;let v=f;const C=this.statsDiffMap.has(g)?this.statsDiffMap.get(g):new Map;if(C.has(S)){const g=C.get(S);g<=f&&(v=f-g)}return C.set(S,f),this.statsDiffMap.set(g,C),isNaN(v)?void 0:v}},aI=M,oI=M,lI=class{constructor(g){this.healedRatio=0,this.healedRatioMax=0,this.healedRatioDuration=0,this.healedRatioTotal=0,this.totalSamplesReceivedDiff=0;const f=g.config;this.networkDetectionDuration=f.webrtcStatNetworkDetectionDuration,this.networkRecvQualityDiagnostics=f.networkRecvQualityDiagnostics,this.networkRecvQualityDiagnostics&&(this.healedRatioAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesDiffAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesDiffAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedDiffAccumulator=new Uv(f.webrtcHealedRatioExtendedWindowSize))}captureHealedRatioSamples(g,f,S){!g||!f||!S||g.length<=this.networkDetectionDuration||f.length<=this.networkDetectionDuration||S.length<=this.networkDetectionDuration||this.setHealedRatioPerDuration(g,f,S)}getHealedRatioMax(){return this.healedRatioMax}getHealedRatioAvg(){return this.healedRatioDuration?this.healedRatioTotal/this.healedRatioDuration:0}getHealedRatio(){return this.healedRatio}getTotalSamplesReceivedDiff(){return this.totalSamplesReceivedDiff}setHealedRatioPerDuration(g,f,S){const v=-1-this.networkDetectionDuration,C=Math.max((0,oI.last)(g)-(0,oI.nth)(g,v),0),_=Math.max((0,oI.last)(f)-(0,oI.nth)(f,v),0);this.totalSamplesReceivedDiff=Math.max((0,oI.last)(S)-(0,oI.nth)(S,v),0),0!==this.totalSamplesReceivedDiff&&(this.healedRatio=(C-_)/this.totalSamplesReceivedDiff,this.healedRatioDuration++,this.healedRatioTotal+=this.healedRatio,this.healedRatioMax=Math.max(this.healedRatioMax,this.healedRatio),this.networkRecvQualityDiagnostics&&(this.concealedSamplesAccumulator.add((0,oI.last)(g)),this.silentConcealedSamplesAccumulator.add((0,oI.last)(f)),this.totalSamplesReceivedAccumulator.add((0,oI.last)(S)),this.concealedSamplesDiffAccumulator.add(C),this.silentConcealedSamplesDiffAccumulator.add(_),this.totalSamplesReceivedDiffAccumulator.add(this.totalSamplesReceivedDiff),this.healedRatioAccumulator.add(this.healedRatio)))}getDiagnostics(g){return{quality:(0,oI.last)(g),qualityLevels:g,concealedSamples:this.concealedSamplesAccumulator.items,silentConcealedSamples:this.silentConcealedSamplesAccumulator.items,totalSamplesReceived:this.totalSamplesReceivedAccumulator.items,concealedSamplesDiff:this.concealedSamplesDiffAccumulator.items,silentConcealedSamplesDiff:this.silentConcealedSamplesDiffAccumulator.items,totalSamplesReceivedDiff:this.totalSamplesReceivedDiffAccumulator.items,healedRatio:this.healedRatioAccumulator.items.map((g=>round(g)))}}},cI=class{constructor(g){this.configProvider=g,this.audioAnalyzers=new Map,this.jitterBufferDuration=0,this.jitterBufferTotal=0,this.jitterTotal=0,this.jitterDuration=0,this.rttDuration=0,this.rttTotal=0,this.rttMax=0,this.jitterMax=0}captureJitterBuffer(g){this.jitterBufferDuration+=qt.TIME_INTERVAL.SEC_1,this.jitterBufferTotal+=g}captureJitter(g){const f=1e3*g;this.jitterTotal+=f,this.jitterMax=Math.max(f,this.jitterMax),this.jitterDuration+=qt.TIME_INTERVAL.SEC_1}getJitterAvg(){return this.jitterDuration?round(this.jitterTotal/this.jitterDuration):0}getAvgJitterBuffer(){return this.jitterBufferDuration?Math.round(this.jitterBufferTotal/this.jitterBufferDuration):0}captureRtt(g){if(null!==g){const f=parseInt(g);this.rttDuration+=qt.TIME_INTERVAL.SEC_1,this.rttTotal+=f,this.rttMax=Math.max(this.rttMax,f)}}getAvgRtt(){return this.rttDuration?round(this.rttTotal/this.rttDuration):0}getMaxRtt(){return this.rttMax}getJitterMax(){return this.jitterMax}updateSendStream(g,f){if(!this.configProvider.config.useAudioAnalyzer)return;const S=this.audioAnalyzers.get(f);S&&(S.dispose(),this.audioAnalyzers.delete(f)),g?.rawStream?.getAudioTracks().length&&this.audioAnalyzers.set(f,new My(g.rawStream))}getInputLevel(g){const f=this.audioAnalyzers.get(g);return f?.getInputLevelNormalized()}},dI=class{constructor(g,f){this.dropBadBandwidth=g,this.dropGoodBandwidth=f,this.dropDurationCounts={},Object.keys(qt.HISTOGRAM_BATCH).forEach((g=>{this.dropDurationCounts[g]=0}))}recordSendBandwidth(g){this.currentDropDuration&&g<this.dropGoodBandwidth||g<this.dropBadBandwidth?this.initiateDrop():this.currentDropDuration&&g>this.dropGoodBandwidth&&this.recoverDrop()}getReport(){const g=shallowClone(this.dropDurationCounts);return this.currentDropDuration&&(g.ongoingDuration=this.currentDropDuration),g}initiateDrop(){this.currentDropDuration?this.currentDropDuration++:this.currentDropDuration=1}recoverDrop(){for(const g of Object.keys(qt.HISTOGRAM_BATCH))if(this.currentDropDuration<=qt.HISTOGRAM_BATCH[g]){this.dropDurationCounts[g]+=1,this.currentDropDuration=0;break}}},hI=M,uI=class{constructor(g,f,S,v){this.lowThreshold=g,this.highThreshold=f,this.isLowerBetter=S,this.curInLowerRange=S,this.stateTracker=new gI(v)}onSample(g,f){let S=this.curInLowerRange;this.curInLowerRange?g>this.highThreshold&&(S=!1):g<this.lowThreshold&&(S=!0);const v=this.stateTracker.onNewState(this.getQuality(S),f);return v!==this.getQuality(this.curInLowerRange)&&(this.curInLowerRange=S),v}getQuality(g){return g===this.isLowerBetter?"Good":"Bad"}},gI=class{constructor(g){this.stickinessTime=g}onNewState(g,f){return"Good"!==g&&"Bad"!==g?this.curState:0===this.stickinessTime?g:g===this.curState?(this.stickTimerStarted=0,this.curState):("Bad"===this.curState?0===this.stickTimerStarted?this.stickTimerStarted=f:f-this.stickTimerStarted>this.stickinessTime&&(this.curState=g,this.stickTimerStarted=0):(this.curState=g,this.stickTimerStarted=0),this.curState)}},pI=class{constructor(g,f,S,v){this.stateProcessor=g,this.windowSize=f,this.extendedWindowSize=S,this.addDiagnosticData=v,this.dataAccumulator=new Uv(S),this.avgAccumulator=new Uv(S)}getLatestSendQuality(g,f,S){if(this.dataAccumulator.add(g),this.dataAccumulator.items.length>=this.windowSize){const g=this.dataAccumulator.items.slice(-this.windowSize),S=(0,hI.mean)(g);return this.addDiagnosticData&&this.avgAccumulator.add(S),this.stateProcessor.onSample(S,f)}return S}getData(){return this.dataAccumulator.items.map((g=>round(g)))}getAggregatedData(){return this.avgAccumulator.items.map((g=>round(g)))}},mI=class{constructor(g,f,S){this.configProvider=g,this.newStatsApi=f,this.webrtcHealedRatio=S,this.sendAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiffAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostDiffAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.totalAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendQualityAccumulator=new Uv(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiagnosticsEnabled=this.configProvider.config.networkSendQualityDiagnostics,this.recvDiagnosticsEnabled=this.configProvider.config.networkRecvQualityDiagnostics,this.recvQualityAccumulator=new Uv(this.configProvider.config.webrtcHealedRatioExtendedWindowSize);const v=Number(this.configProvider.config.webrtcStatNetworkDetectionHysteresis);this.networkDetectionBadLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionBadLevel)+v/2,this.networkDetectionBadLevelLow=this.networkDetectionBadLevelHigh-v,this.networkDetectionGoodLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionGoodLevel)+v/2,this.networkDetectionGoodLevelLow=this.networkDetectionGoodLevelHigh-v;const C=new uI(g.config.webrtcJitterLowThreshold,g.config.webrtcJitterHighThreshold,!0,g.config.webrtcJitterSticknessTime),_=new uI(g.config.webrtcLossRateLowThreshold,g.config.webrtcLossRateHighThreshold,!0,g.config.webrtcLossRateSticknessTime);this.jitterCalculator=new pI(C,g.config.webrtcJitterWindowSize,g.config.webrtcJitterExtendedWindowSize,this.sendDiagnosticsEnabled),this.lossRateCalculator=new pI(_,g.config.webrtcLossRateWindowSize,g.config.webrtcLossRateExtendedWindowSize,this.sendDiagnosticsEnabled)}calculateNetworkSendQualityLevel(g,f,S,v){if(!g||!f)return{quality:v};if(g.length<2||f.length<2||(0,hI.last)(g)<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return{quality:v};const C=Date.now(),_=(0,hI.last)(S),T=this.jitterCalculator.getLatestSendQuality(_,C,v),[I,b]=g.slice(-2),[A,P]=f.slice(-2),R=this.getLossRate(b,I,P,A),M=this.lossRateCalculator.getLatestSendQuality(R,C,v),w="Good"===T&&"Good"===M?"Good":"Bad";return this.sendDiagnosticsEnabled&&(this.sendAccumulator.add(b),this.lostAccumulator.add(P),this.sendQualityAccumulator.add(w)),this.sendDiagnosticsEnabled?{quality:w,packetsSend:this.sendAccumulator.items,packetsLost:this.lostAccumulator.items,packetsSendDiff:this.sendDiffAccumulator.items,packetsLostDiff:this.lostDiffAccumulator.items,lossRates:this.lossRateCalculator.getData(),lossRatesAggregated:this.lossRateCalculator.getAggregatedData(),jitter:this.jitterCalculator.getData(),jitterAggregated:this.jitterCalculator.getAggregatedData(),qualityLevels:this.sendQualityAccumulator.items}:{quality:w}}calculateNetworkRecvQualityLevel(g){if(this.newStatsApi){const f=g;return this.calculateNetworkRecvQualityLevelNewStatsApi(f.concealedSamples,f.silentConcealedSamples,f.totalSamplesReceived,f.oldNetworkLevel)}{const f=g;return this.calculateNetworkRecvQualityLevelLegacyStatsApi(f.googDecodingCTN,f.googDecodingPLC,f.oldNetworkLevel)}}calculateNetworkRecvQualityLevelLegacyStatsApi(g,f,S){const v=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!g||!f||g.length<2*v)return{quality:S};let C=g.length-1-v;const _=g[g.length-1];for(;C>=0&&_-g[C]<100*v;)C--;if(C<0)return{quality:S};const T=_-g[C],I=f[f.length-1]-f[C];if(T<=0)return{quality:S};const b=I/T;return{quality:this.getRecvQuality(b,S)}}calculateNetworkRecvQualityLevelNewStatsApi(g,f,S,v){const C=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!g||g.length<=C||!f||f.length<=C||!S||S.length<=C)return{quality:v};if((0,hI.last)(S)<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality)return{quality:v};if(0===this.webrtcHealedRatio.getTotalSamplesReceivedDiff())return{quality:v};const _=this.webrtcHealedRatio.getHealedRatio(),T=this.getRecvQuality(_,v);return this.recvDiagnosticsEnabled?(this.recvQualityAccumulator.add(T),this.webrtcHealedRatio.getDiagnostics(this.recvQualityAccumulator.items)):{quality:T}}getRecvQuality(g,f){return g<this.networkDetectionGoodLevelLow?"Good":g<this.networkDetectionGoodLevelHigh?"Good"===f?"Good":"Poor":g<this.networkDetectionBadLevelLow?"Poor":g<this.networkDetectionBadLevelHigh?"Bad"===f?"Bad":"Poor":"Bad"}getLossRate(g,f,S,v){const C=g-f,_=S-v,T=C+_;return this.sendDiagnosticsEnabled&&(this.sendDiffAccumulator.add(C),this.lostDiffAccumulator.add(_),this.totalAccumulator.add(T)),T>0?_/T:0}},fI=class{constructor(g){this.configProvider=g,this.qualityLimitationReasonEvents=[]}setQualityLimitationReason(g){this.lastQualityLimitationReason!==g&&this.qualityLimitationReasonEvents.push({event:g,startTime:Date.now(),endTime:Date.now()}),this.qualityLimitationReasonEvents.length>this.configProvider.config.maxStoredQualityLimitationReasonEvents&&this.qualityLimitationReasonEvents.shift(),this.lastQualityLimitationReason=g}getQualityLimitationReasonEvents(){return this.qualityLimitationReasonEvents.reduce(((g,f,S)=>"none"===f.event?g:[...g,{...f,endTime:this.qualityLimitationReasonEvents[S+1]?.startTime??Date.now()}]),[])}},SI=class{constructor(){this.bitrateData={[qt.MEDIA_DIRECTION.SEND]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0,allocateBW:0,allocateBWSamples:0},[qt.MEDIA_DIRECTION.RECV]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0}}}captureSample(g,f){const S=Date.now()/1e3;if(0!==this.bitrateData[g].lastTimestamp&&f>this.bitrateData[g].lastBytes){const v=S-this.bitrateData[g].lastTimestamp,C=8*(f-this.bitrateData[g].lastBytes)/v;this.onBitrateSample(g,C)}this.bitrateData[g].lastTimestamp=S,this.bitrateData[g].lastBytes=f}getMax(g){return Math.round(this.bitrateData[g].maxSample)}getAvg(g){return 0===this.bitrateData[g].nSamples?0:Math.round(this.bitrateData[g].bitrateTotal/this.bitrateData[g].nSamples)}stopCapture(g){this.bitrateData[g].lastBytes=0,this.bitrateData[g].lastTimestamp=0}onBitrateSample(g,f){f>this.bitrateData[g].maxSample&&(this.bitrateData[g].maxSample=f),this.bitrateData[g].bitrateTotal+=f,this.bitrateData[g].nSamples++}captureAllocateBandwidth(g){if(g){const f=parseInt(g[g.length-1]);this.bitrateData[qt.MEDIA_DIRECTION.SEND].allocateBW+=f,this.bitrateData[qt.MEDIA_DIRECTION.SEND].allocateBWSamples+=1}}getAllocateBandwidthAvg(){const g=this.bitrateData[qt.MEDIA_DIRECTION.SEND].allocateBW,f=this.bitrateData[qt.MEDIA_DIRECTION.SEND].allocateBWSamples;if(g>0&&f>0)return Math.floor(g/f)}},vI=class{constructor(g,f){this.maxAppliedCapabilitiesCount=f,this.events=[],this.events.push({eventType:"req",timestamp:Date.now(),capabilities:g.capabilities,isSimulcast:g.isSimulcastEnabled})}setMaxCapabilitiesApplied(g){this.events.push({eventType:"app",timestamp:Date.now(),capabilities:g.capabilities,error:g.error?`${g.error}`:"none"}),this.maxAppliedCapabilitiesCount&&this.events.length>this.maxAppliedCapabilitiesCount+1&&this.events.splice(1,1)}getEvents(){return this.events}},CI=class{constructor(g,f){this.configProvider=g,this.logger=f,this.resolutionChangeRequestRecords={},this.currentResolutionsByRid={},this.resolutionChangeCounterByRid={},this.events=[],this.errors=[]}setMaxCapabilitesRequested(g){const f=new vI(g,this.configProvider.config.webrtcLastAppliedVideoCapabilitiesCount);this.events.push({causeId:g.causeId,seq:f}),this.recordResolutionChange(g),this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.length>this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.shift()}setMaxCapabilitesApplied(g){const f=this.events.find((f=>f.causeId===g.causeId));f?(f.seq.setMaxCapabilitiesApplied(g),g.error&&this.errors.push(f)):this.logger.safe.warn(`Requested capabilities with id ${g.causeId} not found`)}getEvents(){return this.events.map((g=>({causeId:g.causeId,events:g.seq.getEvents()})))}getErrors(){return this.errors.map((g=>({causeId:g.causeId,events:g.seq.getEvents()})))}getResolutionRecords(){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo)return{req:this.resolutionChangeRequestRecords,count:this.resolutionChangeCounterByRid}}recordResolutionChange(g){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo){const f=Object.keys(this.currentResolutionsByRid),getRid=g=>g.rid||"default";[...f,...g.capabilities.map((g=>getRid(g)))].forEach((f=>{const S=g.capabilities.find((g=>getRid(g)===f)),v=this.currentResolutionsByRid[f]||0,C=S?.maxFs||0;if(v===C)return;this.resolutionChangeRequestRecords[f]||(this.resolutionChangeRequestRecords[f]=[],this.resolutionChangeCounterByRid[f]=0);const _=this.resolutionChangeRequestRecords[f].find((g=>g.from===v&&g.to===C));_?_.counter++:this.resolutionChangeRequestRecords[f].push({from:v,to:C,counter:1}),this.currentResolutionsByRid[f]=C,this.resolutionChangeCounterByRid[f]++}))}}},yI=class{constructor(){this.delayCur=[],this.delayTotal=0,this.delayEventCount=0}analyzeDelay(g,f){if(f&&""!==f){this.delayCur.length===g&&this.delayCur.shift();const S=parseInt(f);this.delayCur.push(S),this.delayTotal+=S,this.delayEventCount+=qt.TIME_INTERVAL.SEC_1}}getDelayCur(){if(this.delayCur.length>0){const g=this.delayCur.reduce(((g,f)=>g+f))/this.delayCur.length;return g<0?0:g}}getDelayAvg(){if(this.delayEventCount>0&&this.delayTotal>0){const g=this.delayTotal/this.delayEventCount;return g<0?0:g}}},EI=class{constructor(g,f){this.configProvider=g,this.startTime=f,this.recvTotalFreezeDuration=-1,this.recvFreezeDurations=[],this.recvFreezeIsOngoing=!1,this.recvCurrentFreezeDuration=0,this.recvFreezeCount=0,this.receiveFreezeDurationCounts={},this.longestRecvFreezeDuration=0,this.sendCameraFreezeIntervalsCount=0,this.previousInputFrame=0,this.recvCurrentFreezeStartTimestamp=0,this.receiveFreezeDurationTimestamps={},this.finalFreezeIsOngoing=!1,this.finalRecvCurrentFreezeDuration=0,this.mediaStarted=!1,this.lastBytesRecv=0,this.currentLowBitrateDuration=0,Object.keys(qt.HISTOGRAM_BATCH).forEach((g=>{this.receiveFreezeDurationCounts[g]=0,this.receiveFreezeDurationTimestamps[g]=[]}))}gatherFreezeData({frameRateDecoded:g,frameRateRecv:f,bytesReceived:S,mediaType:v}){if(g){const C=parseInt(g[g.length-1],10),_=f?.length>0?parseInt(f[f.length-1],10):void 0;void 0!==S&&"ScreenShare"!==v&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&!this.configProvider.config.isRenderingBasedOnRawStatistics&&this.calculateBitrate(S,C),-1===this.recvTotalFreezeDuration&&(this.recvTotalFreezeDuration=0),C>0&&(this.mediaStarted=!0),0!==C&&0!==_||!this.mediaStarted?C>0&&(void 0===_||_>0)&&this.recvFreezeIsOngoing&&this.stopRecvDataGathering(!1):(this.recvFreezeIsOngoing||(this.recvCurrentFreezeStartTimestamp=Date.now()-this.startTime),this.recvFreezeIsOngoing=!0,this.recvCurrentFreezeDuration+=qt.TIME_INTERVAL.SEC_1,this.recvTotalFreezeDuration+=qt.TIME_INTERVAL.SEC_1)}}getIsRendering(g){return this.recvCurrentFreezeDuration<g&&this.currentLowBitrateDuration<g&&this.mediaStarted}detectCaptureFreeze(g){if(g){const f=parseInt(g[g.length-1],10);this.previousInputFrame>0&&0===f&&(this.sendCameraFreezeIntervalsCount+=1),this.previousInputFrame=f}}getSendCameraFreezeIntervals(){return this.sendCameraFreezeIntervalsCount>0?this.sendCameraFreezeIntervalsCount:void 0}stopRecvDataGathering(g=!0){this.finalFreezeIsOngoing=this.recvFreezeIsOngoing,this.recvFreezeIsOngoing=!1,g&&(this.mediaStarted=!1),this.recvCurrentFreezeDuration>0&&(this.populateLongestRecvFreezeDuration(),this.populateRecvFreezeDurationCounts(),this.recvFreezeDurations.push(this.recvCurrentFreezeDuration),this.recvFreezeCount+=1),this.finalRecvCurrentFreezeDuration=this.recvCurrentFreezeDuration,this.recvCurrentFreezeDuration=0}getRecvFreezeDurationCounts(){return this.recvFreezeCount>0?JSON.stringify(this.receiveFreezeDurationCounts):void 0}getRecvFreezeDurationTimestamps(g){if(0===this.recvFreezeCount)return;const f={};return Object.keys(this.receiveFreezeDurationTimestamps).forEach((S=>{const v=this.receiveFreezeDurationTimestamps[S].length;f[S]=v>g?this.receiveFreezeDurationTimestamps[S].slice(v-g):this.receiveFreezeDurationTimestamps[S]})),JSON.stringify(f)}getRecvFreezeIsOngoing(g){return this.finalRecvCurrentFreezeDuration>=g&&this.finalFreezeIsOngoing}getRecvTotalFreezeDuration(){return this.recvTotalFreezeDuration>=0?this.recvTotalFreezeDuration:void 0}getRecvAvgFreezeDuration(){if(this.recvTotalFreezeDuration>0&&this.recvFreezeCount>0)return this.recvTotalFreezeDuration/this.recvFreezeCount}getLongestRecvFreezeDuration(){return this.longestRecvFreezeDuration>0?this.longestRecvFreezeDuration:void 0}populateRecvFreezeDurationCounts(){for(const g of Object.keys(qt.HISTOGRAM_BATCH))if(this.recvCurrentFreezeDuration<=qt.HISTOGRAM_BATCH[g]){this.receiveFreezeDurationCounts[g]+=1,this.receiveFreezeDurationTimestamps[g].push(this.recvCurrentFreezeStartTimestamp);break}this.recvCurrentFreezeStartTimestamp=0}populateLongestRecvFreezeDuration(){this.recvCurrentFreezeDuration>this.longestRecvFreezeDuration&&(this.longestRecvFreezeDuration=this.recvCurrentFreezeDuration)}calculateBitrate(g,f){const S=125,v=(g-this.lastBytesRecv)/S;this.lastBytesRecv=g,v<this.configProvider.config.notRenderingLowBitrateThreshold&&f<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}},_I=class{constructor(){this.mediaData={[qt.MEDIA_DIRECTION.SEND]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0},[qt.MEDIA_DIRECTION.RECV]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0}},this.gatheringSendData=!1}captureMediaData(g,f,S){const v=this.mediaData[g];if(g===qt.MEDIA_DIRECTION.SEND&&(this.gatheringSendData=!0),f){const g=parseInt(f[f.length-1],10);v.totalFrameCount+=g}if(S){-1===v.totalMediaDuration&&(v.totalMediaDuration=0);const g=parseInt(S[S.length-1],10);v.mediaStarted||g>0&&(v.mediaStarted=!0,v.mediaStartTimestamp=new Date)}v.mediaStarted&&(v.totalMediaDuration+=qt.TIME_INTERVAL.SEC_1)}captureFrameRate(g){const f=this.mediaData[qt.MEDIA_DIRECTION.SEND];if(g){const S=parseInt(g[g.length-1],10);f.cameraFrameRate+=S}}stopRecvDataGathering(){const g=this.mediaData[qt.MEDIA_DIRECTION.RECV],f=(new Date).getTime();g.timeSinceLastDecode=g.totalMediaDuration>0?Math.round((f-g.mediaStartTimestamp.getTime())/1e3):0,g.mediaStarted=!1}isGatheringSendData(){return this.gatheringSendData}stopSendDataGathering(){const g=this.mediaData[qt.MEDIA_DIRECTION.SEND],f=new Date;g.timeSinceLastDecode=g.totalMediaDuration>0?Math.round((f.getTime()-g.mediaStartTimestamp.getTime())/1e3):0,this.gatheringSendData=!1,g.mediaStarted=!1}getAvgFrameRate(g){const f=this.mediaData[g];if(f.totalMediaDuration>0&&f.totalFrameCount>0)return f.totalFrameCount/f.totalMediaDuration}getTotalDuration(g){const f=this.mediaData[g];return f.totalMediaDuration>=0?f.totalMediaDuration:void 0}getTimeSinceLastDecode(g){const f=this.mediaData[g];return f.timeSinceLastDecode>0?f.timeSinceLastDecode:void 0}getSendCameraFramerate(){const g=this.mediaData[qt.MEDIA_DIRECTION.SEND];if(g.totalMediaDuration>0)return g.cameraFrameRate/g.totalMediaDuration}},TI={fs:0,fps:1},II=class{constructor(g){this.logger=g,this.allowed=new Map,this.lastParams=new Map,this.currentEvents=new Map,this.finishedEvents=[]}setMaxCapabilities(g){g.forEach((g=>{if(g.ssrc||0===g.ssrc){this.finishIfActive(g.ssrc),this.allowed.set(g.ssrc,{fs:g.maxFs+TI.fs,fps:g.maxFps+TI.fps});const f=this.lastParams.get(g.ssrc);f&&this.setCurrentParams(g.ssrc,f.fs,f.fps)}}))}setCurrentParams(g,f,S){this.lastParams.set(g,{fs:f,fps:S});const v=this.getAllowedParams(g);v&&(f>v.fs||S>v.fps)?(this.captureOvershoot(g,S,v.fps,"fps"),this.captureOvershoot(g,f,v.fs,"fs")):v&&this.finishIfActive(g)}flush(){this.currentEvents.forEach(((g,f)=>this.finishIfActive(f)))}getEvents(){const g=[...deepClone(this.finishedEvents)],f=Date.now();return this.currentEvents.forEach((S=>S.forEach((S=>g.push({ssrc:S.ssrc,timestamp:S.timestamp,duration:f-S.timestamp,overshootType:S.overshootType,amount:S.amount}))))),g}captureOvershoot(g,f,S,v){const C=this.currentEvents.get(g)||[],_=C.findIndex((g=>g.overshootType===v)),T=C[_],I=f-S,b=TI[v];I<=b&&T?(T.duration=Date.now()-T.timestamp,this.finishedEvents.push(T),this.logger.debug(`stopped overshooting ${v} by ${T.amount}`),C.splice(_,1)):I>b&&!T?(this.logger.safe.info(`overshooting ${v} by ${f-S}`),C.push({ssrc:g,timestamp:Date.now(),duration:-1,overshootType:v,amount:{min:I,max:I}})):I>b&&T&&(T.amount={min:Math.min(T.amount.min,I),max:Math.max(T.amount.max,I)}),C.length?this.currentEvents.set(g,C):this.currentEvents.has(g)&&this.currentEvents.delete(g)}getAllowedParams(g){const f=this.allowed.get(g);return f||this.allowed.get(0)}finishIfActive(g){const f=this.currentEvents.get(g);if(f){const S=Date.now();f.forEach((f=>{f.duration=S-f.timestamp,this.finishedEvents.push(f),this.logger.debug(`finished overshooting ${f.overshootType} by min:${f.amount.min} max:${f.amount.max} for ${f.duration}ms for ssrc ${g}`)})),this.currentEvents.delete(g)}}},bI=class{constructor(){this.qpData={[qt.MEDIA_DIRECTION.SEND]:{frames:0,qpSum:0},[qt.MEDIA_DIRECTION.RECV]:{frames:0,qpSum:0}}}captureQpData(g,f,S){const v=this.qpData[g];if(S&&S.length>0){const g=parseInt(S[S.length-1],10);g>0&&(v.frames=g)}if(f){const g=parseInt(f,10);g>0&&(v.qpSum=g)}}getQpAverage(g){const f=this.qpData[g];if(f.qpSum>0&&f.frames>0)return f.qpSum/f.frames}},AI=class{constructor(){this.resolutionChangedCount=0,this.resDurations={},this.preferredResolutionDurations={},this.preferredResolutions=[]}get resolutionSwitchCount(){return this.resolutionChangedCount}get resolutionDurationRatios(){return this.countResolutionDurationRatio(this.resDurations)}get preferredResolutionDurationRatios(){return this.countResolutionDurationRatio(this.preferredResolutionDurations)}get preferredResolution(){return this.preferredResolutions}captureSample(g){g&&g.width&&g.height&&(this.isResolutionChanged(this.lastResolution,g)&&this.resolutionChanged(g),this.updateResolutionDuration(this.getResolutionKey(g),this.resDurations)),this.lastPreferredResolution&&this.updatePreferredResolutionDurations()}capturePreferredResolution(g,f){const S=this.getResolutionKey(g);this.preferredResolution.includes(S)||(this.preferredResolutions.length>=f&&this.preferredResolutions.shift(),this.preferredResolutions.push(S)),this.isResolutionChanged(this.lastPreferredResolution,g)&&(this.preferredResolutionChanged(g),this.updatePreferredResolutionDurations())}getResolutionKey(g){return`${g.width}x${g.height}`}isResolutionChanged(g,f){return!g||g.width!==f.width||g.height!==f.height}countResolutionDurationRatio(g){const f={};let S=0;for(const f in g)S+=g[f];for(const v in g)f[v]=round(g[v]/S*100,2);return f}updatePreferredResolutionDurations(){this.updateResolutionDuration(this.getResolutionKey(this.lastPreferredResolution),this.preferredResolutionDurations)}updateResolutionDuration(g,f){f[g]||(f[g]=0),f[g]++}preferredResolutionChanged(g){this.lastPreferredResolution=g}resolutionChanged(g){this.lastResolution=g,this.resolutionChangedCount++}},PI=class{constructor(){this.streamsTimers={}}countRecvStreams(g){const f=`${g}`;this.streamsTimers.hasOwnProperty(f)||(this.streamsTimers[f]=0),this.streamsTimers[f]++}getStreamCounts(){const g={min:void 0,max:void 0,mode:void 0},f=Object.keys(this.streamsTimers).map(Number);return 0===f.length||1===f.length&&0===f[0]||(g.min=Math.min(...f.filter((g=>g>0))),g.max=Math.max(...f),g.mode=f.reduce(((g,f)=>this.streamsTimers[f]>this.streamsTimers[g]?f:g),f[0])),g}},RI=class{constructor(g){this.configProvider=g,this.subscriptionEvents=[],this.subscriptionCounters={attempted:0,subscribed:0,unsubscribed:0,failed:0}}addSubscriptionEvent(g){switch(this.subscriptionEvents.length>this.configProvider.config.webrtcSubscriptionEventLimit&&this.subscriptionEvents.shift(),this.subscriptionEvents.push(g),g.evt){case 1:this.subscriptionCounters.attempted++;break;case 2:this.subscriptionCounters.subscribed++;break;case 3:this.subscriptionCounters.unsubscribed++;break;case-1:this.subscriptionCounters.failed++}}getSubscriptionEvents(){return this.subscriptionEvents.length>0?{events:this.subscriptionEvents}:void 0}getSubscriptionCounters(){return this.subscriptionEvents.length>0?this.subscriptionCounters:void 0}},MI=class{constructor(g,f,S,v="Video"){this.startTime=g,this.configProvider=f,this.logger=S,this.mediaType=v,this.subscriptionCounter=0,this.videoFreezeTelemetry=new EI(this.configProvider,this.startTime),this.videoDelayTelemetry=new yI,this.videoSubscriptionEvents=new RI(this.configProvider),this.videoQPEvents=new bI,this.videoResolutionTelemetry=new AI,this.videoGeneralTelemetry=new _I,this.videoStreamsCounters=new PI,this.videoBitrate=new SI,this.videoMaxCapabilities=new CI(this.configProvider,this.logger),this.videoOvershoot=new II(this.logger),this.videoQualityLimitations=new fI(this.configProvider),this.videoStatsOnSubscribed=new GT(this.configProvider),this.videoResolutionSwitchTracker=new tC(this.configProvider.config.diagnostics?.collectionLimits?.numResolutionSwitches),this.timeToFirstFrame=-1,this.timeToFirstFrameSinceSubscriptionStart=-1,this.currentTrackId="",this.recvTotalFreezeDurationMs=0,this.isRenderingEvents=[]}get trackId(){return this.currentTrackId}set trackId(g){this.currentTrackId=g}get isRecvDataGatheringEnabled(){return this.subscriptionCounter>0}startStopRecvDataGathering(g){this.logger.safe.info("Receive data gathering is "+(g?"enabled":"disabled")),g?this.subscriptionCounter++:this.subscriptionCounter--,this.subscriptionCounter<0&&this.logger.safe.error(`Subscription counter should not be less than 0. Actual value is ${this.subscriptionCounter}`),0===this.subscriptionCounter&&this.stopRecvGathering()}stopDataGathering(){this.stopRecvGathering(),this.stopSendGathering()}stopRecvGathering(){this.videoFreezeTelemetry.stopRecvDataGathering(),this.videoGeneralTelemetry.stopRecvDataGathering(),this.videoBitrate.stopCapture(qt.MEDIA_DIRECTION.RECV)}isSendGathering(){return this.videoGeneralTelemetry.isGatheringSendData()}stopSendGathering(){this.videoGeneralTelemetry.stopSendDataGathering(),this.videoBitrate.stopCapture(qt.MEDIA_DIRECTION.SEND),this.videoOvershoot.flush()}gatherRecvFreezeData(g,f,S){this.videoFreezeTelemetry.gatherFreezeData({frameRateDecoded:g,frameRateRecv:f,bytesReceived:S,mediaType:this.mediaType})}detectCaptureFreeze(g){this.videoFreezeTelemetry.detectCaptureFreeze(g)}getRecvFreezeDurationCounts(){return this.videoFreezeTelemetry.getRecvFreezeDurationCounts()}getRecvFreezeDurationTimestamps(){return this.videoFreezeTelemetry.getRecvFreezeDurationTimestamps(this.configProvider.config.maxVideoFreezeTimestampsInBucket)}getRecvTotalFreezeDuration(){return this.videoFreezeTelemetry.getRecvTotalFreezeDuration()}setRecvTotalFreezeDurationMs(g){this.recvTotalFreezeDurationMs=void 0!==g?this.recvTotalFreezeDurationMs+=g:void 0}analyzeDelay(g,f){this.videoDelayTelemetry.analyzeDelay(g,f)}getDelayCur(){return this.videoDelayTelemetry.getDelayCur()}getDelayAvg(){return this.videoDelayTelemetry.getDelayAvg()}addSubscriptionEvent(g){this.videoSubscriptionEvents.addSubscriptionEvent(g)}getSubscriptionEvents(){return this.videoSubscriptionEvents.getSubscriptionEvents()}getSubscriptionCounters(){return this.videoSubscriptionEvents.getSubscriptionCounters()}captureQpData(g,f,S){this.videoQPEvents.captureQpData(g,f,S)}getQpAverage(g){return this.videoQPEvents.getQpAverage(g)}captureMediaData(g,f,S){this.videoGeneralTelemetry.captureMediaData(g,f,S)}getIsRendering(){const g=this.configProvider.config.notRenderingTimeInterval["Video"===this.mediaType?"video":"sharing"];return this.videoFreezeTelemetry.getIsRendering(g)}captureFrameRate(g){this.videoGeneralTelemetry.captureFrameRate(g)}getTotalDuration(g){return this.videoGeneralTelemetry.getTotalDuration(g)}captureResolutionSample(g){this.videoResolutionTelemetry.captureSample(g)}countRecvStreams(g){this.videoStreamsCounters.countRecvStreams(g)}captureBitrateSample(g,f){this.videoBitrate.captureSample(g,f)}captureAllocateBandwidth(g){this.videoBitrate.captureAllocateBandwidth(g)}capturePreferredResolution(g,f){this.videoResolutionTelemetry.capturePreferredResolution(g,f)}setMaxCapabilitesRequested(g,f=!1){this.videoMaxCapabilities.setMaxCapabilitesRequested(g),f||1===g.capabilities.length&&!g.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(g.capabilities)}setMaxCapabilitesApplied(g,f=!1){this.videoMaxCapabilities.setMaxCapabilitesApplied(g),f||1===g.capabilities.length&&!g.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(g.capabilities)}getMaxCapabilitiesEvents(){const g=this.videoMaxCapabilities.getEvents();return JSON.stringify(g)}getMaxCapabilitiesResolutionChanges(){const g=this.videoMaxCapabilities.getResolutionRecords();return g?JSON.stringify(g):""}getMaxCapabilitiesErrors(){const g=this.videoMaxCapabilities.getErrors();return g?JSON.stringify(g):""}setCurrentParameters(g,f,S){this.videoOvershoot.setCurrentParams(g,f.height/16*(f.width/16),S)}setMaxCapabilitiesOvershoot(g){this.videoOvershoot.setMaxCapabilities(g)}getOvershootEvents(){let g=this.videoOvershoot.getEvents();return g=g.slice(Math.max(0,g.length-(this.configProvider.config.maxReportedOvershootingEvents+1)),g.length),g.forEach((g=>g.timestamp=g.timestamp-this.startTime)),JSON.stringify(g)}getOvershootTotalDurations(){const g=this.videoOvershoot.getEvents();return g.forEach((g=>g.timestamp=g.timestamp-this.startTime)),JSON.stringify({fs:g.reduce(((g,f)=>"fs"===f.overshootType?g+f.duration:g),0),fps:g.reduce(((g,f)=>"fps"===f.overshootType?g+f.duration:g),0)})}setQualityLimitationReason(g){this.videoQualityLimitations.setQualityLimitationReason(g)}getQualityLimitationReasonEvents(){return this.videoQualityLimitations.getQualityLimitationReasonEvents()}captureTimeToFirstFrame(g,f){-1!==g&&(this.timeToFirstFrame=g,this.timeToFirstFrameSinceSubscriptionStart=f)}getTimeToFirstFrame(){return this.timeToFirstFrame}setIsRendering(g){arrayLimitedPush22(this.isRenderingEvents,{isRendering:g,ts:Date.now()},this.configProvider.config.diagnostics.telemetryLimits.numIsRenderingEvents)}setMsi(g){this.msi=g}setLocalMsi(g){this.localMsi=g}prepareCollectingStatsOnSubscribed(g){this.videoStatsOnSubscribed.prepareCollectingStatsOnSubscribed(g)}captureStatsOnSubscribed(g,f){this.videoStatsOnSubscribed.captureStatsOnSubscribed(g,f)}calculateResolutinSwitches(g,f){this.videoResolutionSwitchTracker.captureSample(g,f)}getReport(g,f,S=!1){const v={};if(v[f+"DurationSeconds"]=this.getTotalDuration(g),v[f+"QpAvg"]=this.getQpAverage(g),v[f+"frameRateAvg"]=this.videoGeneralTelemetry.getAvgFrameRate(g),v[f+"bitrateAvg"]=this.videoBitrate.getAvg(g),v[f+"bitrateMax"]=this.videoBitrate.getMax(g),g===qt.MEDIA_DIRECTION.SEND)v[f+"DelayCur"]=this.getDelayCur(),v[f+"DelayAvg"]=this.getDelayAvg(),v[f+"TimeSinceLastEncodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(g),v[f+"AllocateBWAvg"]=this.videoBitrate.getAllocateBandwidthAvg(),v[f+"CaptureFramerateAvg"]=this.videoGeneralTelemetry.getSendCameraFramerate(),v[f+"FreezeIntervals"]=this.videoFreezeTelemetry.getSendCameraFreezeIntervals(),v[f+"MaxCapabilities"]=S?"":this.getMaxCapabilitiesEvents(),v[f+"MaxCapabilitiesErrors"]=S?"":this.getMaxCapabilitiesErrors(),v[f+"OvershootEvents"]=this.getOvershootEvents(),v[f+"OvershootDurations"]=this.getOvershootTotalDurations(),v[f+"qualityLimitationReasonEvents"]=JSON.stringify(this.getQualityLimitationReasonEvents()),v[f+"MaxCapabilitiesResolutions"]=this.getMaxCapabilitiesResolutionChanges(),v[f+"ResolutionsSwitches"]=this.videoResolutionSwitchTracker.switches?JSON.stringify(this.videoResolutionSwitchTracker.switches):"";else if(g===qt.MEDIA_DIRECTION.RECV){v[f+"TimeSinceLastDecodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(g),v[f+"FreezeHistogram"]=this.getRecvFreezeDurationCounts(),v[f+"FreezeTimestamps"]=this.getRecvFreezeDurationTimestamps(),v[f+"LongestFreezeDuration"]=this.videoFreezeTelemetry.getLongestRecvFreezeDuration(),v[f+"RecvAvgFreezeDuration"]=this.videoFreezeTelemetry.getRecvAvgFreezeDuration(),v[f+"TotalFreezeDuration"]=this.getRecvTotalFreezeDuration(),v[f+"TotalFreezeDurationMs"]=this.recvTotalFreezeDurationMs,v[f+"OngoingFreeze"]=this.videoFreezeTelemetry.getRecvFreezeIsOngoing(this.configProvider.config.webrtcEndOfCallFreezeThreshold),v[f+"NumResolutionSwitches"]=this.videoResolutionTelemetry.resolutionSwitchCount,v[f+"PreferredResolution"]=this.videoResolutionTelemetry.preferredResolution,v[f+"PreferredResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.preferredResolutionDurationRatios),v[f+"ResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.resolutionDurationRatios);const S=this.videoStreamsCounters.getStreamCounts();v[f+"StreamsMin"]=S.min,v[f+"StreamsMax"]=S.max,v[f+"StreamsMode"]=S.mode,v[f+"TimeToFirstFrame"]=this.timeToFirstFrame,v[f+"TimeToFirstFrameSinceSubscriptionStart"]=this.timeToFirstFrameSinceSubscriptionStart,v[f+"LocalMsi"]=this.localMsi,v[f+"Msi"]=this.msi,v[f+"isRenderingEvents"]=JSON.stringify(this.isRenderingEvents),v[f+"statsOnSubscribed"]=JSON.stringify(this.videoStatsOnSubscribed.videoStatsOnSubscribed)}return v}},wI=Symbol("mslbase"),OI=Symbol("mslsamples"),DI=class{constructor(g,f){this.logger=g,this.configProvider=f,this.currentLayouts={},this.collectedModalitySessions=[],this.startTimestamp=Date.now()}get collectedSessions(){return this.collectedModalitySessions}get highestFidelitySSRC(){if(!this.currentModalitySession)return;let g;for(const f in this.currentLayouts)g=this.getHigherFidelitySSRC(f,g);return parseInt(g)}processStats(g){const f=Object.values(g.ssrc??{}).filter((g=>g.rid&&g.ssrc&&g.googFrameHeightInput&&this.lastMaxCapabilitiesEvent?.capabilities.some((f=>f.rid===g.rid)))),S=new Map(f.map((g=>[`${g.ssrc}`,g.rid])));for(const g in this.currentLayouts)S.has(g)||this.collectLayout(g);!this.currentModalitySession&&S.size>0&&(this.currentModalitySession={timestamp:Date.now()-this.startTimestamp,duration:0,numLayouts:0,layouts:[]},this.logger.safe.info("Modality session started")),f.forEach((g=>{this.currentLayouts[`${g.ssrc}`]||this.addLayout(g)})),0===S.size&&this.currentModalitySession&&this.collectSession(),f.forEach((g=>this.processLayoutData(g)))}setMaxCapabilities(g,f){if(this.lastMaxCapabilitiesEvent=g,Object.keys(this.currentLayouts).length)for(const S of g.capabilities){const v=Object.values(this.currentLayouts).find((g=>g.rid===S.rid));v&&(f?(arrayLimitedPush22(v.fmtp,{...S,timestamp:Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-v.timestamp,causeId:g.causeId},this.configProvider.config.simulcastTelemetryNumFMTP),v.gatherer.setMaxCapabilitesApplied(g)):v.gatherer.setMaxCapabilitesRequested(g),v.gatherer.setMaxCapabilitiesOvershoot([S]))}}finish(){this.logger.safe.info("Finishing statistics gathering");for(const g in this.currentLayouts)this.collectLayout(g);this.currentModalitySession&&this.collectSession()}addLayout(g){const f=`${g.ssrc}`,S=g.rid,v=this.lastMaxCapabilitiesEvent?.capabilities.find((g=>g.rid===S));this.logger.safe.info(`Adding layout for ssrc ${f} rid ${S}`);const C=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,_=new MI(C,this.configProvider,this.logger.createChild(`Telemetry#${f}`));this.currentLayouts[f]={ssrc:g.ssrc,rid:S,fmtp:[{...v,timestamp:C,causeId:this.lastMaxCapabilitiesEvent?.causeId}],timestamp:C,duration:0,gatherer:_,[wI]:{firCount:g.googFirsReceived,nackCount:g.googNacksReceived,pliCount:g.googPlisReceived,framesEncoded:g.framesEncoded,bytesSent:g.bytesSent,packetsSent:g.packetsSent,packetsLost:g.packetsLost,qpSum:g.qpSum},[OI]:{firCount:[],nackCount:[],pliCount:[],framesEncoded:[],bytesSent:[],packetsSent:[],packetsLost:[],qpSum:[],frameHeightInput:[],frameHeightSent:[],frameRateInput:[],frameRateSent:[]}},_.setMaxCapabilitiesOvershoot([v]),this.currentModalitySession.numLayouts++}processLayoutData(g){const f=`${g.ssrc}`,S=this.currentLayouts[f];this.processMediaStats(S,g),S.gatherer.captureMediaData(qt.MEDIA_DIRECTION.SEND,[String(g.googFrameRateSent)],[String(g.framesEncoded)]),S.gatherer.captureFrameRate([String(g.googFrameRateInput)]),S.gatherer.captureQpData(qt.MEDIA_DIRECTION.SEND,String(g.qpSum),[String(g.framesEncoded)]),S.gatherer.captureBitrateSample(qt.MEDIA_DIRECTION.SEND,g.bytesSent),S.gatherer.detectCaptureFreeze([String(g.googFrameRateInput)]),S.gatherer.setCurrentParameters(g.ssrc,{width:g.googFrameWidthSent,height:g.googFrameHeightSent},g.googFrameRateSent)}processMediaStats(g,f){const S=g[wI],v=f.googFirsReceived-S.firCount,C=f.googNacksReceived-S.nackCount,_=f.googPlisReceived-S.pliCount,T=f.framesEncoded-S.framesEncoded,I=f.bytesSent-S.bytesSent,b=f.packetsSent-S.packetsSent,A=f.packetsLost-S.packetsLost,P=f.qpSum-S.qpSum,R=g[OI],M=this.configProvider.config.webrtcStatStoredRecordsNumber;arrayLimitedPush22(R.firCount,v,M),arrayLimitedPush22(R.nackCount,C,M),arrayLimitedPush22(R.pliCount,_,M),arrayLimitedPush22(R.framesEncoded,T,M),arrayLimitedPush22(R.bytesSent,I,M),arrayLimitedPush22(R.packetsSent,b,M),arrayLimitedPush22(R.packetsLost,A,M),arrayLimitedPush22(R.qpSum,P,M),arrayLimitedPush22(R.frameHeightInput,f.googFrameHeightInput,M),arrayLimitedPush22(R.frameHeightSent,f.googFrameHeightSent,M),arrayLimitedPush22(R.frameRateInput,f.googFrameRateInput,M),arrayLimitedPush22(R.frameRateSent,f.googFrameRateSent,M)}collectLayout(g){this.logger.safe.info(`Collecting layout for ssrc ${g}`),this.currentLayouts[g].duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-this.currentLayouts[g].timestamp,this.currentLayouts[g].gatherer.isSendGathering()&&this.currentLayouts[g].gatherer.stopSendGathering();const f=this.currentLayouts[g].gatherer.getReport(qt.MEDIA_DIRECTION.SEND,"",!1);for(const S in f)this.currentLayouts[g][S]=f[S];for(const f in this.currentLayouts[g][OI])this.currentLayouts[g][f]=sampleseries(this.currentLayouts[g][OI][f],(g=>g));delete this.currentLayouts[g].gatherer,arrayLimitedPush22(this.currentModalitySession.layouts,this.currentLayouts[g],this.configProvider.config.simulcastTelemetryLayoutsPerSession),delete this.currentLayouts[g]}collectSession(){this.logger.safe.info("Collecting session");for(const g in this.currentLayouts)this.collectLayout(g);this.currentModalitySession.duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,arrayLimitedPush22(this.collectedModalitySessions,this.currentModalitySession,this.configProvider.config.simulcastTelemetryNumModalitySessions),this.currentModalitySession=void 0,this.lastMaxCapabilitiesEvent=void 0}getHigherFidelitySSRC(g,f){if(!g||!f)return g||f;const[S]=this.currentLayouts[g].fmtp.slice(-1),[v]=this.currentLayouts[f].fmtp.slice(-1);return(S?.maxMbps??0)>0&&(v?.maxMbps??0)>0?S.maxMbps>v.maxMbps?g:f:g||f}},NI=["googFrameHeightReceived","googFrameWidthReceived","googFrameHeightSent","googFrameWidthSent","googFrameRateInput","googFrameRateSent","googNacksSent","googNacksReceived","googPlisSent","googPlisReceived","googFirsSent","googFirsReceived","framesDecoded","googFrameRateDecoded","googFrameRateReceived","framesEncoded","packetsLost","packetsSent","packetsReceived","bytesReceived","bytesSent","googEncodeUsagePercent","audioInputLevel","audioOutputLevel","googDecodingCTN","googDecodingPLC","keyFramesEncoded","keyFramesDecoded","googRtt","concealedSamples","silentConcealedSamples","totalSamplesReceived","healedRatio","jitter","googJitterBufferMs","qpSum","fecPacketsReceived","fecPacketsDiscarded","fecPacketsSent","packetsDiscarded","pushCount","pushErrCount","pullCount","pullErrCount"],kI=["bytesSent","bytesReceived","googRtt","packetsSent","requestsSent","consentRequestsSent","responsesSent","requestsReceived","responsesReceived"],LI=["googAvailableReceiveBandwidth","googAvailableSendBandwidth","googTransmitBitrate"];function catchStatsErrors(g,f,S){const v=S.value;S.value=function(...g){try{return v.apply(this,g)}catch(g){this.processStatsError(f,g)}}}var FI=10,xI=class{constructor(g,f,S,v,C,_){this.logger=g,this.sessionInfo=f,this.configProvider=S,this.mediaManager=v,this.multiparty=C,this.newStatsApi=_,this.statsErrors=[],this.subscribedTrackIds=[],this.iceCandidateErrors=[],this.terminated=!1,this.hwSilent=!1,this.isSpeaking=!1,this.networkSendLevel={quality:"Good"},this.networkRecvLevel={quality:"Good"},this.audioTelemetry=new cI(this.configProvider),this.cameraOpenResolution={width:0,height:0},this.streamSenderStarted={},this.totalVideoControlMessages=0,this.outOfOrderVideoControlMessages=0,this.subscribedTrackSsrc=[],this.multiViewVideoTelemetry={},this.h264AvailableProfiles=[],this.h264CodecCapabilities={sendProfiles:[],receiveProfiles:[]},this.timeToFirstFrame={},this.timeToFirstFrameSinceSubscriptionStart={},this.missedInitialPreferredResolution={},this.MSIDs=new Set,this.MSIDsPairs={},this.timerTrackerManager=new G_(this.configProvider.config.enableTimerTracker),this.extensions={WebRTCStats:{},AudioTransportRecvBitrate:0,AudioTransportSendBitrate:0,AudioPayloadSendBitrate:0,AudioPayloadRecvBitrate:0,VideoPayloadSendBitrate:0,VideoPayloadRecvBitrate:0,TimerAudioTransportRecvBitrate:0,TimerAudioTransportSendBitrate:0,TimerAudioPayloadRecvBitrate:0,TimerAudioPayloadSendBitrate:0,TimerVideoPayloadRecvBitrate:0,TimerVideoPayloadSendBitrate:0,StartTime:Date.now(),EndTime:Date.now(),Audio_recv_jitterBufferAvgSize:0,Audio_recv_jitterMax:0,Audio_recv_jitterAvg:0,Audio_send_rttAvg:0,Audio_send_rttMax:0,MaxSessionBandwidth:0,Video_recv_MSIDs:[],Audio_send_presentationUserAPIDuration:"",Audio_send_presentationDuration:""},this.report={type:"WebRtcMediaStats",data:{Extensions:this.extensions}},this.lastSSRCs=new Map,this.videoTelemetry=new MI(this.extensions.StartTime,this.configProvider,this.logger.createChild("Video"),"Video"),this.sharingTelemetry=new MI(this.extensions.StartTime,this.configProvider,this.logger.createChild("Sharing"),"ScreenShare"),this.bandwidthTelemetry=new dI(this.configProvider.config.webrtcBWJumpLowerLimit,this.configProvider.config.webrtcBWJumpUpperLimit),this.stabilizationTelemetry=new JT(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,hasSendDirectionality),this.storedRecordsNumber=Number(this.configProvider.config.webrtcStatStoredRecordsNumber),this.hwSilentDetectionDuration=Number(this.configProvider.config.webrtcStatHwSilentDetectionDuration),this.hwSilentDetectionLevel=Number(this.configProvider.config.webrtcStatHwSilentDetectionLevel),this.audioHealedRatioTelemetry=new lI(this.configProvider),this.networkQualityTelemetry=new mI(this.configProvider,this.newStatsApi,this.audioHealedRatioTelemetry),this.speakingWhileMutedBadDuration=Number(this.configProvider.config.webrtcSpeakingWhileMutedBadDuration),this.speakingWhileMutedDetectionLevel=Number(this.configProvider.config.webrtcSpeakingWhileMutedDetectionLevel),this.videoDelayTimePeriod=this.configProvider.config.webrtcVideoDelayThreshold,this.maxStoredPreferredResolutions=this.configProvider.config.maxStoredPreferredResolutionCount,this.simulcastVideo=new DI(this.logger.createChild("simulcastVideo"),this.configProvider),this.simulcastSharing=new DI(this.logger.createChild("simulcastSharing"),this.configProvider)}get currentVideoRecvTrackId(){return this.extensions.WebRTCStats.ssrc_video_recv?.googTrackId}get currentSharingRecvTrackId(){return this.extensions.WebRTCStats.ssrc_sharing_recv?.googTrackId}get isMultiViewVideoTelemetry(){return Object.getOwnPropertyNames(this.multiViewVideoTelemetry).length>0}onDeviceEvent(g){if("stream_acquired"===g.eventType){const f=g.payload;"Video"===f.mediaType&&(this.cameraOpenResolution=f.resolution)}}onMaxCapabilitiesRequested(g){(g.modality===qt.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesRequested(g),(g.modality===qt.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(g,!1)}onMaxCapabilitiesApplied(g){(g.modality===qt.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesApplied(g),(g.modality===qt.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(g,!0)}setSubscribedTrackIds(g){this.subscribedTrackIds=g||[]}setSubscribedTrackSsrc(g){this.subscribedTrackSsrc=g||[]}addSubscriptionEvent(g,f,S,v,C,_,T){const I={evt:g,ts:Date.now()-this.extensions.StartTime,msi:S,localMsi:v,duration:_};C&&(I.error=stringifyObject2(C));const b=this.getHandlerForModality(f);if(b.addSubscriptionEvent(I),T&&this.setMSIDsPair(S,v,T),1===g||3===g){const f=1===g;b.startStopRecvDataGathering(f)}2===g&&b.prepareCollectingStatsOnSubscribed(S)}setMSIDsPair(g,f,S){const v=`ssrc_${S.replace(/\D/g,"")}_recv`;this.MSIDsPairs[v]={msi:g,localMsi:f}}getHandlerForModality(g){switch(g){case qt.MODALITY.video:return this.videoTelemetry;case qt.MODALITY.sharing:return this.sharingTelemetry;default:throw new Error(`Handler not found for modality: ${g}`)}}setTerminated(){this.extensions.EndTime=(new Date).getTime(),this.terminated=!0}startWaitingForStreamStart(g){this.streamStartDetection||this.sessionInfo.setOfferedModalities(g),this.streamStartDetection=!0}processStatsDict(g){if(this.processSimulcastStats(g),this.constructWebRtcReportForSingleStream(this.extensions.WebRTCStats,g),this.streamStartDetection&&(this.setStartTime(this.sessionInfo.offeredModalities)||this.terminated)&&(this.streamStartDetection=!1),Object.keys(this.missedInitialPreferredResolution).length>0&&(this.currentVideoRecvTrackId||this.currentSharingRecvTrackId)&&this.setMissedInitialPreferredResolution(),this.constructWebRTCDataReport(this.extensions.WebRTCStats,g),this.calculateHwSilentState(),this.calculateSpeakingState(),this.setHealedRatioSamples(),this.calculateNetworkRecvQualityLevel(),this.calculateNetworkSendQualityLevel(),this.sessionInfo.activeModalities&&(this.processBandwidthStats(),this.processAudioStats(),this.processVideoStatsRecv(this.videoTelemetry,this.extensions.WebRTCStats.ssrc_video_recv,!0),this.processVideoStatsSend(this.videoTelemetry,this.extensions.WebRTCStats.ssrc_video_send),this.processSharingStats(),this.processStreamsCounters()),this.configProvider.config.enableMultiViewStats){const f=this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS]?this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS]:{};this.constructWebRtcReportForMultipleStreams(f,g);for(const g of Object.keys(f)){const S=f[g];this.processVideoStatsRecv(this.multiViewVideoTelemetry[g],S)}this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS]=f}this.extensions.WebRTCStats.statsErrors=JSON.stringify(this.statsErrors)}setTimeToFirstFrame(g,f,S){S in this.timeToFirstFrame||(this.timeToFirstFrame[S]=g,this.timeToFirstFrameSinceSubscriptionStart[S]=f)}getCurrentTimeToFirstFrame(g){return this.timeToFirstFrame[g]?this.timeToFirstFrame[g]:-1}getCurrentTimeToFirstFrameSinceSubscriptionStart(g){return this.timeToFirstFrameSinceSubscriptionStart[g]?this.timeToFirstFrameSinceSubscriptionStart[g]:-1}getVideoTelemetryBySsrc(g){let f;return this.extensions.WebRTCStats.ssrc_video_recv&&this.extensions.WebRTCStats.ssrc_video_recv.id===g?f=this.videoTelemetry:this.extensions.WebRTCStats.ssrc_sharing_recv&&this.extensions.WebRTCStats.ssrc_sharing_recv.id===g?f=this.sharingTelemetry:this.isMultiViewVideoTelemetry&&(f=this.multiViewVideoTelemetry[g]),f}getIsRendering(g){const f=this.getVideoTelemetryBySsrc(g);return f?f.getIsRendering():void 0}setFreezeDuration(g,f){for(const S of Object.keys(this.multiViewVideoTelemetry))this.multiViewVideoTelemetry[S].trackId===f&&this.isSubscribed(f)&&this.multiViewVideoTelemetry[S].setRecvTotalFreezeDurationMs(g);this.currentSharingRecvTrackId===f&&this.isSubscribed(f)&&this.sharingTelemetry.setRecvTotalFreezeDurationMs(g),this.currentVideoRecvTrackId===f&&this.isSubscribed(f)&&this.videoTelemetry.setRecvTotalFreezeDurationMs(g)}addVideoControlMessage(g){this.totalVideoControlMessages++,g&&this.outOfOrderVideoControlMessages++}setStreamSenderStarted(g,f){this.streamSenderStarted[g]=f}addReportedReceiveBandwidth(g){this.limitCaptureAmount(this.extensions,"ReportedReceiveBandwidth",g)}setHealedRatioSamples(){this.audioHealedRatioTelemetry.captureHealedRatioSamples(this.extensions?.WebRTCStats?.ssrc_audio_recv?.concealedSamples,this.extensions?.WebRTCStats?.ssrc_audio_recv?.silentConcealedSamples,this.extensions?.WebRTCStats?.ssrc_audio_recv?.totalSamplesReceived)}processSimulcastStats(g){this.simulcastVideo.processStats(g),this.simulcastSharing.processStats(g)}processBandwidthStats(){const g=this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth;if(g){const f=this.streamSenderStarted.Video||this.streamSenderStarted.ScreenShare;this.bandwidthTelemetry.recordSendBandwidth(g[g.length-1]),this.stabilizationTelemetry.processBandwidth(parseInt(g[g.length-1]),this.sessionInfo.activeModalities,f)}}processAudioStats(){if(this.extensions.WebRTCStats.ssrc_audio_send&&this.limitCaptureAmount(this.extensions,"Audio_send_RawInputVolume",this.audioTelemetry.getInputLevel("Audio")),void 0!==this.extensions.WebRTCStats.ssrc_audio_recv?.googJitterBufferMs&&this.audioTelemetry.captureJitterBuffer((0,aI.last)(this.extensions.WebRTCStats.ssrc_audio_recv.googJitterBufferMs)),void 0!==this.extensions.WebRTCStats.ssrc_audio_recv?.jitter&&this.audioTelemetry.captureJitter((0,aI.last)(this.extensions.WebRTCStats.ssrc_audio_recv.jitter)),this.extensions.WebRTCStats.ssrc_audio_send?.googRtt){const g=this.extensions.WebRTCStats.ssrc_audio_send.googRtt;this.audioTelemetry.captureRtt(g[g.length-1])}}stopGatheringIfNeeded(g,f,S,v){const C=`${f}${S}`;v!==this.lastSSRCs.get(C)&&(this.lastSSRCs.set(C,v),f===qt.MEDIA_DIRECTION.SEND?g.stopSendGathering():g.stopRecvGathering())}processVideoStatsSend(g,f){f&&hasSendDirectionality(this.sessionInfo.activeModalities.video)?(this.stopGatheringIfNeeded(g,qt.MEDIA_DIRECTION.SEND,"Video",f.ssrc),g.captureMediaData(qt.MEDIA_DIRECTION.SEND,f.googFrameRateSent,f.framesEncoded),g.captureFrameRate(f.googFrameRateInput),g.analyzeDelay(this.videoDelayTimePeriod,f.googAvgEncodeMs),g.captureQpData(qt.MEDIA_DIRECTION.SEND,f.qpSum,f.framesEncoded),g.captureBitrateSample(qt.MEDIA_DIRECTION.SEND,this.getLastSampleInt(f.bytesSent)),g.detectCaptureFreeze(f.googFrameRateInput),g.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),g.setCurrentParameters(parseInt(f.ssrc),{width:this.getLastSampleInt(f.googFrameWidthSent),height:this.getLastSampleInt(f.googFrameHeightSent)},this.getLastSampleInt(f.googFrameRateSent)),g.setQualityLimitationReason(f.qualityLimitationReason),this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo&&g.calculateResolutinSwitches(this.getLastSampleInt(f.googFrameWidthSent),this.getLastSampleInt(f.googFrameHeightSent))):g.isSendGathering()&&(g.stopSendGathering(),this.lastSSRCs.delete(`${qt.MEDIA_DIRECTION.SEND}Video`))}processVideoStatsRecv(g,f,S=!1){f&&hasReceiveDirectionality(this.sessionInfo.activeModalities.video)&&this.videoTelemetry.isRecvDataGatheringEnabled?(S&&this.stopGatheringIfNeeded(g,qt.MEDIA_DIRECTION.RECV,"Video",f.ssrc),g.trackId=f.googTrackId,g.gatherRecvFreezeData(f.googFrameRateDecoded,f.googFrameRateReceived,this.getLastSampleInt(f.bytesReceived)),g.captureMediaData(qt.MEDIA_DIRECTION.RECV,f.googFrameRateReceived,f.googFrameRateDecoded),g.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(f.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(f.googTrackId)),g.captureQpData(qt.MEDIA_DIRECTION.RECV,f.qpSum,f.framesDecoded),g.captureBitrateSample(qt.MEDIA_DIRECTION.RECV,this.getLastSampleInt(f.bytesReceived)),g.captureResolutionSample({width:this.getLastSampleInt(f.googFrameWidthReceived),height:this.getLastSampleInt(f.googFrameHeightReceived)}),g.captureStatsOnSubscribed(this.getLastSampleInt(f.framesDecoded),this.getLastSampleInt(f.bytesReceived))):S&&this.lastSSRCs.delete(`${qt.MEDIA_DIRECTION.RECV}Video`)}processSharingStats(){const g=this.extensions.WebRTCStats.ssrc_sharing_send,f=this.extensions.WebRTCStats.ssrc_sharing_recv;g&&hasSendDirectionality(this.sessionInfo.activeModalities.sharing)?(this.stopGatheringIfNeeded(this.sharingTelemetry,qt.MEDIA_DIRECTION.SEND,"Sharing",g.ssrc),this.sharingTelemetry.captureMediaData(qt.MEDIA_DIRECTION.SEND,g.googFrameRateSent,g.framesEncoded),this.sharingTelemetry.captureFrameRate(g.googFrameRateInput),this.sharingTelemetry.analyzeDelay(this.videoDelayTimePeriod,g.googAvgEncodeMs),this.sharingTelemetry.captureQpData(qt.MEDIA_DIRECTION.SEND,g.qpSum,g.framesEncoded),this.sharingTelemetry.captureBitrateSample(qt.MEDIA_DIRECTION.SEND,this.getLastSampleInt(g.bytesSent)),this.sharingTelemetry.detectCaptureFreeze(g.googFrameRateInput),this.sharingTelemetry.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),this.sharingTelemetry.setCurrentParameters(parseInt(g.ssrc),{width:this.getLastSampleInt(g.googFrameWidthSent),height:this.getLastSampleInt(g.googFrameHeightSent)},this.getLastSampleInt(g.googFrameRateSent)),this.limitCaptureAmount(this.extensions,"Sharing_send_RawInputVolume",this.audioTelemetry.getInputLevel("ScreenShare"))):this.sharingTelemetry.isSendGathering()&&(this.sharingTelemetry.stopSendGathering(),this.lastSSRCs.delete(`${qt.MEDIA_DIRECTION.SEND}Sharing`)),f&&hasReceiveDirectionality(this.sessionInfo.activeModalities.sharing)&&this.sharingTelemetry.isRecvDataGatheringEnabled?(this.stopGatheringIfNeeded(this.sharingTelemetry,qt.MEDIA_DIRECTION.RECV,"Sharing",f.ssrc),this.sharingTelemetry.trackId=f.googTrackId,this.sharingTelemetry.gatherRecvFreezeData(f.googFrameRateDecoded,f.googFrameRateReceived),this.sharingTelemetry.captureMediaData(qt.MEDIA_DIRECTION.RECV,f.googFrameRateReceived,f.googFrameRateDecoded),this.sharingTelemetry.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(f.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(f.googTrackId)),this.sharingTelemetry.captureQpData(qt.MEDIA_DIRECTION.RECV,f.qpSum,f.framesDecoded),this.sharingTelemetry.captureBitrateSample(qt.MEDIA_DIRECTION.RECV,this.getLastSampleInt(f.bytesReceived)),this.sharingTelemetry.captureResolutionSample({width:this.getLastSampleInt(f.googFrameWidthReceived),height:this.getLastSampleInt(f.googFrameHeightReceived)}),this.sharingTelemetry.captureStatsOnSubscribed(this.getLastSampleInt(f.framesDecoded),this.getLastSampleInt(f.bytesReceived))):this.lastSSRCs.delete(`${qt.MEDIA_DIRECTION.RECV}Sharing`)}processStreamsCounters(){const g=this.extensions.WebRTCStats.recvCounters;g&&(this.videoTelemetry.countRecvStreams(g[qt.MODALITY.video]),this.sharingTelemetry.countRecvStreams(g[qt.MODALITY.sharing]))}setMissedInitialPreferredResolution(){forOwn(this.missedInitialPreferredResolution,((g,f)=>{this.setPreferredResolution(f,g)})),this.missedInitialPreferredResolution={}}setPreferredResolution(g,f,S){if((S===qt.MEDIA_TYPE.video&&!this.currentVideoRecvTrackId||S===qt.MEDIA_TYPE.sharing&&!this.currentSharingRecvTrackId)&&(this.missedInitialPreferredResolution[g]=f),this.currentVideoRecvTrackId===g&&this.videoTelemetry.capturePreferredResolution(f,this.maxStoredPreferredResolutions),this.currentSharingRecvTrackId===g&&this.sharingTelemetry.capturePreferredResolution(f,this.maxStoredPreferredResolutions),this.isMultiViewVideoTelemetry){const S=this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(g)];S&&S.capturePreferredResolution(f,this.maxStoredPreferredResolutions)}}setIsRendering(g,f,S){f===qt.MEDIA_TYPE.video&&this.videoTelemetry.setIsRendering(g),f===qt.MEDIA_TYPE.sharing&&this.sharingTelemetry.setIsRendering(g),this.isMultiViewVideoTelemetry&&this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(S)]?.setIsRendering(g)}setMaxSessionBandwidth(g){this.extensions.MaxSessionBandwidth=g}isSubscribed(g,f){let S=this.subscribedTrackIds.some((f=>f===g));return!S&&this.configProvider.config.subscribeToSsrcForVideo&&(S=this.subscribedTrackSsrc.some((g=>g===`${f}`))),S||!this.multiparty&&this.configProvider.config.subscribeToSsrcForVideo}getReport(g=!1,f=!1){try{f&&this.resetPairValues(),g||(this.videoTelemetry.stopDataGathering(),this.sharingTelemetry.stopDataGathering());const S=this.videoTelemetry.getTotalDuration(qt.MEDIA_DIRECTION.RECV),v=this.videoTelemetry.getTotalDuration(qt.MEDIA_DIRECTION.SEND),C=this.sharingTelemetry.getTotalDuration(qt.MEDIA_DIRECTION.RECV),_=this.sharingTelemetry.getTotalDuration(qt.MEDIA_DIRECTION.SEND);if(S>=0&&(forOwn(this.videoTelemetry.getReport(qt.MEDIA_DIRECTION.RECV,"Video_recv_",f),((g,f)=>this.extensions[f]=g)),!isEmpty(this.multiViewVideoTelemetry))){const g=[];for(const S of Object.keys(this.multiViewVideoTelemetry)){const v={id:S};forOwn(this.multiViewVideoTelemetry[S].getReport(qt.MEDIA_DIRECTION.RECV,"Video",f),((g,f)=>{void 0!==g&&(v[f]=g)})),g.push(v)}this.extensions[qt.MULTIPLE_RECV_STREAMS]=JSON.stringify(g)}C>=0&&forOwn(this.sharingTelemetry.getReport(qt.MEDIA_DIRECTION.RECV,"Sharing_recv_",f),((g,f)=>this.extensions[f]=g)),v>=0&&(forOwn(this.videoTelemetry.getReport(qt.MEDIA_DIRECTION.SEND,"Video_send_",f),((g,f)=>this.extensions[f]=g)),this.extensions.Bandwidth_jumpsHistogram=JSON.stringify(this.bandwidthTelemetry.getReport()),this.extensions.Bandwidth_uplinkStabilizationTime=JSON.stringify(this.stabilizationTelemetry.getReport(!0)),this.extensions.Video_send_CameraOpenWidth=this.cameraOpenResolution.width,this.extensions.Video_send_CameraOpenHeight=this.cameraOpenResolution.height),_>=0&&forOwn(this.sharingTelemetry.getReport(qt.MEDIA_DIRECTION.SEND,"Sharing_send_",f),((g,f)=>this.extensions[f]=g)),g||f||(this.simulcastVideo.finish(),this.extensions.Video_send_Simulcast=JSON.stringify(this.simulcastVideo.collectedSessions),this.simulcastSharing.finish(),this.extensions.Sharing_send_Simulcast=JSON.stringify(this.simulcastSharing.collectedSessions)),this.iceCandidateErrors.length>0&&(this.extensions.iceCandidateErrors=JSON.stringify(this.iceCandidateErrors)),this.extensions.Audio_recv_jitterBufferAvgSize=this.audioTelemetry.getAvgJitterBuffer(),this.extensions.Audio_recv_jitterMax=this.audioTelemetry.getJitterMax(),this.extensions.Audio_recv_jitterAvg=this.audioTelemetry.getJitterAvg(),this.extensions.Video_SubscriptionEvents=f?"":JSON.stringify(this.videoTelemetry.getSubscriptionEvents()),this.extensions.Video_SubscriptionCounters=f?"":JSON.stringify(this.videoTelemetry.getSubscriptionCounters()),this.extensions.Sharing_SubscriptionEvents=f?"":JSON.stringify(this.sharingTelemetry.getSubscriptionEvents()),this.extensions.Sharing_SubscriptionCounters=f?"":JSON.stringify(this.sharingTelemetry.getSubscriptionCounters()),this.extensions.Audio_recv_healedRatioMax=this.audioHealedRatioTelemetry.getHealedRatioMax(),this.extensions.Audio_recv_healedRatioAvg=this.audioHealedRatioTelemetry.getHealedRatioAvg(),this.extensions.Audio_send_rttAvg=this.audioTelemetry.getAvgRtt(),this.extensions.Audio_send_rttMax=this.audioTelemetry.getMaxRtt();for(const g of Object.keys(this.extensions))void 0===this.extensions[g]&&delete this.extensions[g];return delete this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS],this.sessionInfo.fillExtensionInfo(this.extensions),Object.keys(this.extensions.WebRTCStats).length>0&&!this.extensions.WebRTCStats.hasStatsError&&this.calculateAverages(),this.extensions.H264_available_profiles=this.h264AvailableProfiles.join(),this.extensions.H264_codec_capabilities=JSON.stringify(this.h264CodecCapabilities),this.extensions.Video_recv_MSIDs=Array.from(this.MSIDs),this.totalVideoControlMessages>0&&(this.extensions.totalVideoControlMessages=this.totalVideoControlMessages,this.extensions.outOfOrderVideoControlMessages=this.outOfOrderVideoControlMessages),deepClone(this.report)}catch(g){throw this.processStatsError("Report",g),{error:g,partialReport:deepClone(this.report)}}}getAudioHwSilent(){return this.hwSilent}getSpeakingState(){return this.isSpeaking}getNetworkSendLevel(){return this.networkSendLevel}getNetworkRecvLevel(){return this.networkRecvLevel}addIceCandidateError(g){this.iceCandidateErrors.push(g)}clearIceCandidateErrors(){this.iceCandidateErrors=[]}addH264AvailableProfiles(g){this.h264AvailableProfiles=[...new Set(this.h264AvailableProfiles.concat(g))]}setSupportedH264Profiles(g,f){this.h264CodecCapabilities.sendProfiles=g,this.h264CodecCapabilities.receiveProfiles=f}updateSendStream(g,f){this.audioTelemetry.updateSendStream(g,f)}getTimerTracker(g,f){return this.timerTrackerManager.getTimerTracker(g,f)}resetPairValues(){Object.keys(this.extensions.WebRTCStats).forEach((g=>{delete this.extensions.WebRTCStats[g].pair}))}limitCaptureAmount(g,f,S){void 0!==S&&(g[f]=Array.isArray(g[f])?g[f]:[],g[f].push(S),g[f].length>this.storedRecordsNumber&&g[f].shift())}setStartTime(g){const f=this.extensions.WebRTCStats;if(!f.ssrc_audio_send||!f.ssrc_audio_recv)return!1;const setupCounter=(g,f)=>!g||f&&-1===f?f:(new Date).getTime();return this.extensions.TimerAudioPayloadRecvBitrate=hasReceiveDirectionality(g.audio)?setupCounter(f.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioPayloadRecvBitrate):-1,this.extensions.TimerAudioPayloadSendBitrate=hasSendDirectionality(g.audio)?setupCounter(f.ssrc_audio_send.bytesSent,this.extensions.TimerAudioPayloadSendBitrate):-1,this.extensions.TimerAudioTransportRecvBitrate=hasReceiveDirectionality(g.audio)?setupCounter(f.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioTransportRecvBitrate):-1,this.extensions.TimerAudioTransportSendBitrate=hasSendDirectionality(g.audio)?setupCounter(f.ssrc_audio_send.bytesSent,this.extensions.TimerAudioTransportSendBitrate):-1,!!(f.ssrc_video_send&&f.ssrc_video_recv&&(this.extensions.TimerVideoPayloadRecvBitrate=hasReceiveDirectionality(g.video)?setupCounter(f.ssrc_video_recv.bytesReceived,this.extensions.TimerVideoPayloadRecvBitrate):-1,this.extensions.TimerVideoPayloadSendBitrate=hasSendDirectionality(g.video)?setupCounter(f.ssrc_video_send.bytesSent,this.extensions.TimerVideoSendBitrate):-1,this.extensions.TimerVideoPayloadRecvBitrate&&this.extensions.TimerVideoPayloadSendBitrate&&this.extensions.TimerAudioPayloadRecvBitrate&&this.extensions.TimerAudioPayloadSendBitrate&&this.extensions.TimerAudioTransportRecvBitrate&&this.extensions.TimerAudioTransportSendBitrate))}calculateAverages(){const g=this.extensions.EndTime,doTheCalc=(f,S)=>f&&g-S>0&&0!==S&&-1!==S?Math.round(8*f/(g-S)):0,getCounter=g=>{const f=g.split(".").reduce(((g,f)=>null==g?g:g[f]),this.extensions.WebRTCStats);return Array.isArray(f)?f[f.length-1]:f};this.extensions.AudioPayloadRecvBitrate=doTheCalc(getCounter("ssrc_audio_recv.bytesReceived"),this.extensions.TimerAudioPayloadRecvBitrate),this.extensions.AudioPayloadSendBitrate=doTheCalc(getCounter("ssrc_audio_send.bytesSent"),this.extensions.TimerAudioPayloadSendBitrate),this.extensions.VideoPayloadRecvBitrate=doTheCalc(getCounter("ssrc_video_recv.bytesReceived"),this.extensions.TimerVideoPayloadRecvBitrate),this.extensions.VideoPayloadSendBitrate=doTheCalc(getCounter("ssrc_video_send.bytesSent"),this.extensions.TimerVideoPayloadSendBitrate),this.extensions.AudioTransportRecvBitrate=doTheCalc(getCounter("ssrc_audio_send.pair.bytesReceived"),this.extensions.TimerAudioTransportRecvBitrate),this.extensions.AudioTransportSendBitrate=doTheCalc(getCounter("ssrc_audio_send.pair.bytesSent"),this.extensions.TimerAudioTransportSendBitrate)}addFilteredFields(g,f,S=[]){for(const v in f)if(f.hasOwnProperty(v)&&"type"!==v)if(-1!==S.indexOf(v)){const S=g[v]||[];S.push(this.formatFields(f,v)),S.length>this.storedRecordsNumber&&S.shift(),g[v]||(g[v]=S)}else g[v]=f[v]}formatFields(g,f){const S=g[f];switch(f){case"audioInputLevel":case"audioOutputLevel":return this.newStatsApi?Math.floor(65535*S):2*S;case"googJitterBufferMs":return parseInt(S);case"healedRatio":return round(parseFloat(S),this.configProvider.config.healedRatioPrecision);case"jitter":return round(parseFloat(S),this.configProvider.config.jitterPrecision);default:return S}}processSource(g,f,S){let v;if(this.addFilteredFields(g,f,NI),f.transportId){const C=S.googComponent?.[f.transportId];g.transport||(g.transport={}),C&&(this.addFilteredFields(g.transport,C),C.selectedCandidatePairId&&(v=S.googCandidatePair?.[C.selectedCandidatePairId]))}else v=Object.values(S.googCandidatePair).find((g=>g.selected));v&&(g.pair||(g.pair={}),this.addFilteredFields(g.pair,v,kI))}getWebrtcReport(g,f,S,v){const C=g.ssrc[S],_=v?C.id.replace(/[0-9]+/,v):C.id;f[_]?C.ssrc!==f[_].ssrc&&(_.endsWith("video_send")?this.videoTelemetry.stopSendGathering():_.endsWith("video_recv")?this.videoTelemetry.stopRecvGathering():_.endsWith("sharing_send")?this.sharingTelemetry.stopSendGathering():_.endsWith("sharing_recv")&&this.sharingTelemetry.stopRecvGathering()):f[_]={},this.processSource(f[_],C,g)}constructWebRTCDataReport(g,f){if(!f.data?.length)return;const S=f.data.sort(((g,f)=>f.timestamp-g.timestamp)),v=S.find((g=>"open"===g.state));g.data=v||S[0]}constructWebRtcReportForSingleStream(g,f){if(!f.ssrc)return;const S=this.selectSsrcsToCollect(f.ssrc);g.recvCounters=S.recvCounters,delete S.recvCounters,delete S.multiRecv,forOwn(S,(S=>{forOwn(S,((S,v)=>{this.getWebrtcReport(f,g,S,v)}))})),f.VideoBwe?.bweforvideo&&(g.bweStat||(g.bweStat={}),this.addFilteredFields(g.bweStat,f.VideoBwe.bweforvideo,LI))}constructWebRtcReportForMultipleStreams(g,f){f.ssrc&&this.selectSsrcsToCollect(f.ssrc).multiRecv.forEach((S=>this.getWebrtcReport(f,g,S)))}getMediaType(g,f){let S=f?f.getModality():g.mediaType;return g.googTrackId?.match("applicationsharing")&&S!==qt.MEDIA_TYPE.sharing&&(S=qt.MEDIA_TYPE.sharing),S}selectSsrcsToCollect(g){const f={send:{},recv:{},recvCounters:{video:0,sharing:0},multiRecv:[]};if(!this.sessionInfo.activeModalities)return f;let S=[];for(const v of Object.keys(g)){const C=g[v],_=C.googTrackId;if(!_&&C.mediaType!==qt.MEDIA_TYPE.audio)continue;const T=this.getMediaEntity(_,C),I=this.getMediaType(C,T),b=T?.getXSourceStreamId();if(v.endsWith("send"))switch(I){case qt.MEDIA_TYPE.audio:hasSendDirectionality(this.sessionInfo.activeModalities.audio)&&(f.send.audio=v);break;case qt.MEDIA_TYPE.video:if(this.extensions.Video_send_SourceId=b,this.simulcastVideo.highestFidelitySSRC){this.simulcastVideo.highestFidelitySSRC===C.ssrc&&(f.send.video=v);break}this.streamSenderStarted.Video&&hasSendDirectionality(this.sessionInfo.activeModalities.video)&&T?.getLocalTrackId()&&(T?.getLocalTrackId()===C.googTrackId||this.configProvider.config.statsAllowAnyVideoSendTrack&&!f.send.video)&&(!C.rid||"1"===C.rid)&&(f.send.video=v);break;case qt.MEDIA_TYPE.sharing:if(this.simulcastSharing.highestFidelitySSRC){this.simulcastSharing.highestFidelitySSRC===C.ssrc&&(f.send.sharing=v);break}this.streamSenderStarted.ScreenShare&&hasSendDirectionality(this.sessionInfo.activeModalities.sharing)&&T?.getLocalTrackId()===C.googTrackId&&(f.send.sharing=v);break;default:this.logger.warn(`Unknown media type '${I}'`)}else if(v.endsWith("recv"))switch(I){case qt.MEDIA_TYPE.audio:hasReceiveDirectionality(this.sessionInfo.activeModalities.audio)&&(f.recv.audio=v);break;case qt.MEDIA_TYPE.video:void 0!==b&&this.MSIDs.add(b),this.isSubscribed(C.googTrackId,C.ssrc)&&hasReceiveDirectionality(this.sessionInfo.activeModalities.video)&&(S.push(C),+C.googFrameRateReceived>0&&f.recvCounters[qt.MODALITY.video]++);break;case qt.MEDIA_TYPE.sharing:this.isSubscribed(C.googTrackId,C.ssrc)&&hasReceiveDirectionality(this.sessionInfo.activeModalities.sharing)&&(f.recv.sharing=v,+C.googFrameRateReceived>0&&f.recvCounters[qt.MODALITY.sharing]++);break;default:this.logger.warn(`Unknown media type '${I}'`)}}if(S.length>0){S=S.sort(((g,f)=>+f.googFrameHeightReceived-+g.googFrameHeightReceived));const g=S.find((g=>g.mediaType===qt.MEDIA_TYPE.video));g&&(f.recv.video=g.id),this.multiparty&&this.configProvider.config.enableMultiViewStats&&(f.multiRecv=S.map((g=>g.id)),f.multiRecv.forEach((g=>{this.multiViewVideoTelemetry[g]||(this.multiViewVideoTelemetry[g]=new MI(this.extensions.StartTime,this.configProvider,this.logger.createChild(`Video[${g}]`,"Video")),this.multiViewVideoTelemetry[g].setMsi(this.MSIDsPairs[g]?.msi),this.multiViewVideoTelemetry[g].setLocalMsi(this.MSIDsPairs[g]?.localMsi),this.multiViewVideoTelemetry[g].prepareCollectingStatsOnSubscribed(this.MSIDsPairs[g]?.msi))})))}return f}getMediaEntityForTrack(g){if(g)return this.mediaManager.getMediaEntities().find((f=>f.getLocalTrackId()===g||f.getRemoteTrackId()===g))}getMediaEntityByRemoteSsrc(g){if(g)return this.mediaManager.getMediaEntities().find((f=>f.getRemoteSsrc()===+g))}getMediaEntity(g,f){const S=`${f.ssrc}`,v=f.id;let C=this.getMediaEntityForTrack(g);return!C&&this.configProvider.config.subscribeToSsrcForVideo&&v.endsWith("recv")&&(C=this.getMediaEntityByRemoteSsrc(S)),C}calculateHwSilentState(){const g=this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!g||g.length<2*this.hwSilentDetectionDuration)return;let f=!0;for(let S=g.length-this.hwSilentDetectionDuration-1;S<g.length;S++)if(g[S]>this.hwSilentDetectionLevel){f=!1;break}this.hwSilent!==f&&(this.hwSilent=f,this.logger.safe.info(`HW silent changed to ${this.hwSilent}`))}calculateSpeakingState(){const g=this.newStatsApi&&this.configProvider.config.useAudioAnalyzer?this.extensions.Audio_send_RawInputVolume:this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!g||g.length<=this.speakingWhileMutedBadDuration)return;let f=!1;for(let S=g.length-this.speakingWhileMutedBadDuration;S<g.length;S++)if(g[S]>this.speakingWhileMutedDetectionLevel){f=!0;break}this.isSpeaking=f}calculateNetworkRecvQualityLevel(){this.configProvider.config.enableNetworkRecvQualityUFD&&this.extensions.WebRTCStats.ssrc_audio_recv&&(this.networkRecvLevel=this.networkQualityTelemetry.calculateNetworkRecvQualityLevel({googDecodingCTN:this.extensions.WebRTCStats.ssrc_audio_recv.googDecodingCTN??[],googDecodingPLC:this.extensions.WebRTCStats.ssrc_audio_recv.googDecodingPLC??[],concealedSamples:this.extensions.WebRTCStats.ssrc_audio_recv.concealedSamples??[],silentConcealedSamples:this.extensions.WebRTCStats.ssrc_audio_recv.silentConcealedSamples??[],totalSamplesReceived:this.extensions.WebRTCStats.ssrc_audio_recv.totalSamplesReceived??[],oldNetworkLevel:this.networkRecvLevel.quality}))}calculateNetworkSendQualityLevel(){this.extensions.WebRTCStats.ssrc_audio_send&&(this.networkSendLevel=this.networkQualityTelemetry.calculateNetworkSendQualityLevel(this.extensions.WebRTCStats.ssrc_audio_send.packetsSent,this.extensions.WebRTCStats.ssrc_audio_send.packetsLost,this.extensions.WebRTCStats.ssrc_audio_send.jitter,this.networkSendLevel.quality))}processStatsError(g,f){const S=stringifyObject2(f);this.logger.safe.error(`webrtcStatistics error [${g}]: ${S}`);const v=this.statsErrors.find((f=>f.error===S&&f.origin===g));v?v.count++:this.statsErrors.push({origin:g,error:S,count:1}),this.statsErrors.length>FI&&this.statsErrors.splice(1)}getLastSampleInt(g){return"number"==typeof g?g:g&&parseInt(g[g.length-1])||0}getSsrcIdFromMultipleVideoStream(g){let f;const S=this.extensions.WebRTCStats[qt.MULTIPLE_RECV_STREAMS]||{};for(const v in S){const C=S[v];if(C&&C.googTrackId===g){f=v;break}}return f}};__decorateClass([catchStatsErrors],xI.prototype,"onDeviceEvent",1),__decorateClass([catchStatsErrors],xI.prototype,"onMaxCapabilitiesRequested",1),__decorateClass([catchStatsErrors],xI.prototype,"onMaxCapabilitiesApplied",1),__decorateClass([catchStatsErrors],xI.prototype,"addSubscriptionEvent",1),__decorateClass([catchStatsErrors],xI.prototype,"processSimulcastStats",1),__decorateClass([catchStatsErrors],xI.prototype,"processBandwidthStats",1),__decorateClass([catchStatsErrors],xI.prototype,"processAudioStats",1),__decorateClass([catchStatsErrors],xI.prototype,"processVideoStatsSend",1),__decorateClass([catchStatsErrors],xI.prototype,"processVideoStatsRecv",1),__decorateClass([catchStatsErrors],xI.prototype,"processSharingStats",1),__decorateClass([catchStatsErrors],xI.prototype,"processStreamsCounters",1),__decorateClass([catchStatsErrors],xI.prototype,"setMissedInitialPreferredResolution",1),__decorateClass([catchStatsErrors],xI.prototype,"setPreferredResolution",1),__decorateClass([catchStatsErrors],xI.prototype,"setIsRendering",1),__decorateClass([catchStatsErrors],xI.prototype,"setMaxSessionBandwidth",1),__decorateClass([catchStatsErrors],xI.prototype,"setStartTime",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateAverages",1),__decorateClass([catchStatsErrors],xI.prototype,"addFilteredFields",1),__decorateClass([catchStatsErrors],xI.prototype,"formatFields",1),__decorateClass([catchStatsErrors],xI.prototype,"processSource",1),__decorateClass([catchStatsErrors],xI.prototype,"getWebrtcReport",1),__decorateClass([catchStatsErrors],xI.prototype,"constructWebRTCDataReport",1),__decorateClass([catchStatsErrors],xI.prototype,"constructWebRtcReportForSingleStream",1),__decorateClass([catchStatsErrors],xI.prototype,"constructWebRtcReportForMultipleStreams",1),__decorateClass([catchStatsErrors],xI.prototype,"selectSsrcsToCollect",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateHwSilentState",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateSpeakingState",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateNetworkRecvQualityLevel",1),__decorateClass([catchStatsErrors],xI.prototype,"calculateNetworkSendQualityLevel",1);var UI="VideoBwe",VI="bweforvideo",BI="googAvailableReceiveBandwidth",HI="googAvailableSendBandwidth",$I="mediaType",jI="framesDecoded",GI="googFrameRateDecoded",qI="googFrameRateReceived",WI="googFrameRateInput",zI="googTrackId";function unwrapResults(g){const f={};return g.result().forEach((g=>{g.names().forEach((S=>{f[g.type]=f[g.type]||{},f[g.type][g.id]=f[g.type][g.id]||{},f[g.type][g.id][S]=g.stat(S)})),f[g.type][g.id].id=g.id})),f}var KI=class extends Ht{constructor(g,f,S,v){super(),this.logger=g,this.configProvider=f,this.mediaManager=S,this.window=Xs.window,this._sessionInfo=new B_,this.statisticsMapper=new sI,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.webRtcStatistics=new xI(this.logger.createChild("WebrtcStatistics"),this._sessionInfo,this.configProvider,S,v,this.useNewStatsApi)}setAudioDecoderStatsProvider(g){this.statisticsMapper?.setAudioDecoderStatsProvider(g)}get sessionInfo(){return this._sessionInfo}get isDisposed(){return null===this.pc&&0===this.interval}initialize(g){this.pc=g}startWaitingForStreamStart(g){this.webRtcStatistics.startWaitingForStreamStart(g)}onDeviceEvent(g){this.webRtcStatistics.onDeviceEvent(g)}onMaxCapabilitiesRequested(g){this.webRtcStatistics.onMaxCapabilitiesRequested(g)}onMaxCapabilitiesApplied(g){this.webRtcStatistics.onMaxCapabilitiesApplied(g)}onSendersChanged(g,f){this.webRtcStatistics.setStreamSenderStarted(g,f)}addSubscriptionEvent(g,f,S,v,C,_,T){this.webRtcStatistics.addSubscriptionEvent(g,f,S,v,C,_,T)}setSubscribedTrackIds(g){this.webRtcStatistics.setSubscribedTrackIds(g)}setSubscribedTrackSsrc(g){this.webRtcStatistics.setSubscribedTrackSsrc(g)}setPreferredResolution(g,f,S){this.webRtcStatistics.setPreferredResolution(g,f,S)}setIsRendering(g,f,S){this.webRtcStatistics.setIsRendering(g,f,S)}setMaxSessionBandwidth(g){this.webRtcStatistics.setMaxSessionBandwidth(g)}setTerminated(){this.webRtcStatistics.setTerminated()}addIceCandidateError(g){this.webRtcStatistics.addIceCandidateError(g)}clearIceCandidateErrors(){this.webRtcStatistics.clearIceCandidateErrors()}updateSendStream(g,f){this.webRtcStatistics.updateSendStream(g,f)}getTimerTracker(g,f){return this.webRtcStatistics.getTimerTracker(g,f)}setH264AvailableProfiles(g){if(!g?.codecs)return;let f=[];g.codecs.forEach((g=>{if("h264"===g.mimeType&&g.sdpFmtpLine){const S=/profile-level-id=(.{6})/.exec(g.sdpFmtpLine);S?.[1]&&(f=f.concat(S[1]))}})),this.webRtcStatistics.addH264AvailableProfiles(f)}setSupportedH264Profiles(g,f){if(!g?.codecs&&!f?.codecs)return;const extractProfiles=g=>{const f=[];return g.codecs?.forEach((g=>{if("h264"===g.mimeType&&g.sdpFmtpLine){const S=/profile-level-id=(.{6})/.exec(g.sdpFmtpLine)?.[1];S&&!f.includes(S)&&f.push(S)}})),f},S=extractProfiles(g),v=extractProfiles(f);this.webRtcStatistics.setSupportedH264Profiles(S,v)}processRawReport(g){this.processStatsDict(this.statisticsMapper.build(g))}processLegacyReport(g){this.processStatsDict(unwrapResults(g))}getReport(g,f=!1){const S=this.webRtcStatistics.getReport(g,f);return this.addStreamInfoForE2ETests(S),S}dispose(){this.interval&&(this.window.clearInterval(this.interval),this.interval=0),this.pc=null}getLastStatistics(){return this.statistics}setTimeToFirstFrame(g,f,S){this.webRtcStatistics.setTimeToFirstFrame(g,f,S)}setFreezeDuration(g,f){this.webRtcStatistics.setFreezeDuration(g,f)}addVideoControlMessage(g=!1){this.webRtcStatistics.addVideoControlMessage(g)}setSsrcTrackPair(g,f){this.statisticsMapper.setSsrcTrackPair(g,f)}updateStatsWithLocalSsrcTrackInfo(){for(const g of this.mediaManager.getMediaEntities()){const f=g.getLocalSsrc();f&&this.statisticsMapper.setSsrcTrackPair(f,g.getLocalTrackId())}}addReportedReceiveBandwidth(g){this.webRtcStatistics.addReportedReceiveBandwidth(g)}addStreamInfoForE2ETests(g){const f=this._sessionInfo.negotiatedModalities;if(f&&!this.isDisposed)try{g.localStreams=this.getSendersReport(this.pc.getSenders(),{audio:hasSendDirectionality(f.audio),video:hasSendDirectionality(f.video)}),g.remoteStreams=this.getReceiversReport(this.pc.getReceivers(),{audio:hasReceiveDirectionality(f.audio),video:hasReceiveDirectionality(f.video)})}catch(g){this.logger.safe.warn(`addStreamInfoForE2ETests failed: ${stringifyObject2(g)}`)}}getReceiversReport(g,f){const S=[];return g.forEach((g=>{const v={tracks:[]};S.push(v),g.track&&("audio"===g.track.kind&&f.audio||"video"===g.track.kind&&f.video)&&v.tracks.push({stream:void 0,track:g.track})})),S}getSendersReport(g,f){const S=[],v={tracks:[]};return S.push(v),g.forEach((g=>{g.track&&("audio"===g.track.kind&&f.audio||"video"===g.track.kind&&f.video)&&v.tracks.push({stream:void 0,track:g.track})})),S}processStatsDict(g){this.webRtcStatistics.processStatsDict(g);let f=0,S=0;const v=g[UI]?.[VI];v&&(f=Number(v[BI]),S=Number(v[HI]));const C=1e3*((this.configProvider.mediaConfig.maxBandwidthInKbps||Math.floor(Number.MAX_SAFE_INTEGER/1e3))-(this.configProvider.config.audioBandwidthInKbps||0)),_=isNaN(f)?0:f,T=isNaN(S)?0:S,I={estimatedReceiveBandwidth:Math.min(_,C),estimatedSendBandwidth:Math.min(T,C),remoteVideoStreams:{},localVideoStreams:{},isSpeaking:this.webRtcStatistics.getSpeakingState(),audioHwSilent:this.webRtcStatistics.getAudioHwSilent(),networkSendLevel:this.webRtcStatistics.getNetworkSendLevel(),networkRecvLevel:this.webRtcStatistics.getNetworkRecvLevel()};forOwn(g.ssrc,(g=>{if("video"!==g[$I])return;const f=g[zI],S=g.id;-1!==S.indexOf("_recv")?(I.remoteVideoStreams[f]={trackId:f,frameRateReceived:Number(g[qI]),frameRateDecoded:Number(g[GI]),framesDecoded:Number(g[jI])},this.configProvider.config.isRenderingBasedOnRawStatistics||(I.remoteVideoStreams[f].isRendering=this.webRtcStatistics.getIsRendering(S))):f&&-1!==S.indexOf("_send")&&(I.localVideoStreams[f]={trackId:f,ssrc:Number(g.ssrc),frameRateInput:Number(g[WI])})})),deepEqual(this.statistics,I)||(this.statistics=I,this.notifyStatisticsChanged())}notifyStatisticsChanged(){this.event("onStatisticsChanged").raise(this.statistics)}},JI=class extends Ht{constructor(g,f,S,v,C){super(),this.logger=g,this.configProvider=f,this.diagnostics=S,this.mediaManager=v,this.window=Xs.window,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.loopIntervalTracker=new Jv(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.loopIntervalAggregator=new Yv,this.fetchTimeTracker=new Jv(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.fetchTimeAggregator=new Yv,this.gathererV1=new KI(this.logger.createChild("V1"),this.configProvider,this.mediaManager,C),this.gathererV1.on("onStatisticsChanged",(g=>this.event("onStatisticsChanged").raise(g))),this.useNewStatsApi&&f.config.diagnostics.sideBySide&&(this.gathererV2=new nI(this.logger.createChild("V2"),this.configProvider,this.diagnostics,this.mediaManager))}initialize(g){this.pc=g,this.gathererV1.initialize(g),this.interval??(this.interval=this.window.setInterval((()=>this.processStats()),this.configProvider.config.webrtcStatPollInterval))}setAudioDecoderStatsProvider(g){this.gathererV1.setAudioDecoderStatsProvider(g),this.gathererV2?.setAudioDecoderStatsProvider(g)}dispose(){super.dispose(),this.interval&&(this.window.clearInterval(this.interval),this.interval=void 0),this.gathererV1.dispose(),this.pc=void 0}get isDisposed(){return!this.pc&&void 0===this.interval}async processStats(){if(this.configProvider.config.diagnostics.collectWhileNotConnected){if(!this.pc||"closed"===this.pc.iceConnectionState)return}else if(!this.pc||"connected"!==this.pc.iceConnectionState&&"completed"!==this.pc.iceConnectionState)return void this.gathererV2?.signalNoConnection();if(this.useNewStatsApi){const g=Jt(),f=void 0===this.loopTimer?-1:g-this.loopTimer;this.loopTimer=g,this.loopIntervalTracker.captureSample(f),this.loopIntervalAggregator.captureSample(this.loopIntervalTracker.getReport());const S=this.loopIntervalAggregator.getReport();S&&(this.diagnostics.loopIntervalMax=S.max,this.diagnostics.loopIntervalMedian=S.median);const v={};(await this.pc.getStats()).forEach((g=>{this.cleanupPii(g);const f=g.type;delete g.type,v[f]??(v[f]={}),v[f][g.id]=g}));const C=Jt()-g;this.fetchTimeTracker.captureSample(C),this.fetchTimeAggregator.captureSample(this.fetchTimeTracker.getReport());const _=this.fetchTimeAggregator.getReport();_&&(this.diagnostics.fetchTimeMax=_.max,this.diagnostics.fetchTimeMedian=_.median);const T=this.gathererV2?.processRawReport(v);let I=Jt();this.gathererV1.processRawReport(v),I=Jt()-I,T&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Raising onDiagnosticUpdated event"),this.event("onDiagnosticUpdated").raise(T)),T?.perfCounters&&(T.perfCounters.loopTime=f,T.perfCounters.fetchTime=C,T.perfCounters.legacyProcessingTime=I)}else this.pc.getStats((g=>{g.result&&this.gathererV1.processLegacyReport(g)}))}cleanupPii(g){switch(g.type){case"local-candidate":case"remote-candidate":{const f=g;Object.defineProperty(f,"address",{enumerable:!1}),Object.defineProperty(f,"url",{enumerable:!1}),Object.defineProperty(f,"relatedAddress",{enumerable:!1}),Object.defineProperty(f,"ip",{enumerable:!1}),Object.defineProperty(f,"usernameFragment",{enumerable:!1});break}case"certificate":{const f=g;Object.defineProperty(f,"fingerprint",{enumerable:!1}),Object.defineProperty(f,"base64Certificate",{enumerable:!1});break}}}get sessionInfo(){return this.gathererV1.sessionInfo}onMaxCapabilitiesApplied(g){this.gathererV1.onMaxCapabilitiesApplied(g)}clearIceCandidateErrors(){this.gathererV1.clearIceCandidateErrors()}setSsrcTrackPair(g,f){this.gathererV1.setSsrcTrackPair(g,f),this.gathererV2?.setSsrcTrackPair(g,f)}addSubscriptionEvent(g,f,S,v,C,_,T){this.gathererV1.addSubscriptionEvent(g,f,S,v,C,_,T)}setSubscribedTrackSsrc(g){this.gathererV1.setSubscribedTrackSsrc(g)}addIceCandidateError(g){this.gathererV1.addIceCandidateError(g)}setH264AvailableProfiles(g){this.gathererV1.setH264AvailableProfiles(g)}setSupportedH264Profiles(g,f){this.gathererV1.setSupportedH264Profiles(g,f)}setTerminated(){this.gathererV1.setTerminated()}onDeviceEvent(g){this.gathererV1.onDeviceEvent(g)}getReport(g,f=!1){const S=this.gathererV1.getReport(g,f);if(this.gathererV2&&this.configProvider.config.diagnostics.sideBySide){const g=this.loopIntervalAggregator.getReport();g&&(S.data.Extensions.LoopIntervalMax=`${round(g.max,1)}`,S.data.Extensions.LoopIntervalMedian=`${round(g.median,1)}`);const f=this.fetchTimeAggregator.getReport();f&&(S.data.Extensions.FetchTimeMax=`${round(f.max,1)}`,S.data.Extensions.FetchTimeMedian=`${round(f.median,1)}`);const v=this.diagnostics.getObjectRef();S.data.Extensions.multipleVideoStreams=JSON.stringify(rebaseTime(v.multiViewStats,"startTime",v.startTime)),S.data.Extensions.OvcToSubscriptions=JSON.stringify(v.ovcToSubscriptionEvents),S.data.Extensions.videoPerformanceEvent=JSON.stringify(v.videoPerformanceEvent);const C=v.bandwidthReport;"REMB"===v.negotiation.bweType?(S.data.Extensions.StartCallBWE=JSON.stringify(C?.startOfTheCall),S.data.Extensions.EndCallBWE=JSON.stringify(C?.endOfTheCall),S.data.Extensions.BWEStd=JSON.stringify(C?.std),S.data.Extensions.BwPercentiles=JSON.stringify(C?.bwPercentiles),S.data.Extensions.AvgBwe=JSON.stringify(C?.avgBwe)):(S.data.Extensions.StartCallBWESendSide=JSON.stringify(C?.startOfTheCall),S.data.Extensions.EndCallBWESendSide=JSON.stringify(C?.endOfTheCall),S.data.Extensions.BWEStdSendSide=JSON.stringify(C?.std),S.data.Extensions.BwPercentilesSendSide=JSON.stringify(C?.bwPercentiles),S.data.Extensions.AvgBwSendSide=JSON.stringify(C?.avgBwe)),S.data.Extensions.InitialBWSeed=JSON.stringify(v.initialBWSeed),S.data.Extensions.SentBWSeed=JSON.stringify(v.sentBWSeed),S.data.Extensions.Bandwidth_downlinkStabilizationTime=JSON.stringify(v.bwDownlinkStabilizationTime),S.data.Extensions.ReinvitelessContext=JSON.stringify(v.reinvitelessContext),S.data.Extensions.ReportedSendBandwidth=JSON.stringify(v.reportedSendBandwidthLayouts),S.data.Extensions.Data_ProtocolCounters=JSON.stringify(v.dataChannel?.protocolCounters),S.data.Extensions.Data_Error=v.dataChannel?.error,S.data.Extensions.Data_SessionState=v.dataChannelSessionState?.toString(),S.data.Extensions.Data_CreateChannelError=v.dataChannelCreationError;const _=v.aggregatedModalityStats?.video?.recv||[],T=v.aggregatedModalityStats?.audio?.recv||[],I=v.aggregatedModalityStats?.sharing?.recv||[],b=v.aggregatedModalityStats?.video?.send||[],A=v.aggregatedModalityStats?.sharing?.send||[],P=S.data.Extensions.WebRTCStats,R=_[_.length-1],M=I[I.length-1],w=T[T.length-1],O=b[b.length-1],D=A[A.length-1],N=R?.aggregated?.macroblockRateStats??{},k=w?.aggregated?.customHealerStats??{};if(k?.pullPacketProcessingTimes){const g=getPercentilesProviderFromSampleFreqs(k.pullPacketProcessingTimes);k.pullPacketProcessingTimeP50=g.getPercentile(.5),k.pullPacketProcessingTimeP95=g.getPercentile(.95)}if(k?.pushPacketProcessingTimes){const g=getPercentilesProviderFromSampleFreqs(k.pushPacketProcessingTimes);k.pushPacketProcessingTimeP50=g.getPercentile(.5),k.pushPacketProcessingTimeP95=g.getPercentile(.95)}for(const g in N)S.data.Extensions[`Video_recv_${g}`]=`${round(N[g],0)}`;for(const g in v.totalVideoRecvMblocksRates)S.data.Extensions[`totalVideoRecv_${g}`]=`${round(v.totalVideoRecvMblocksRates[g],0)}`;for(const g in k)if(void 0!==k[g]){const f="number"!=typeof k[g]?JSON.stringify(k[g]):k[g];S.data.Extensions[`Audio_recv_customHealer_${g}`]=f}S.data.Extensions.MeetingScenario=JSON.stringify(v.negotiation.meetingScenario),S.data.Extensions.IsTownHall=JSON.stringify(v.negotiation.isTownHall),S.data.Extensions.Audio_send_presentationAPIUserDuration=JSON.stringify(v.presentationAPIUserDuration),S.data.Extensions.Audio_send_presentationDuration=JSON.stringify(v.presentationAudioDuration),S.data.Extensions.CodecSupport=JSON.stringify(v.codecSupport),S.data.Extensions.Video_recv_FpsHarmonicAverage=R?.extensions.fpsHarmonicAverage?.toString(),S.data.Extensions.Sharing_recv_FpsHarmonicAverage=M?.extensions.fpsHarmonicAverage?.toString(),S.data.Extensions.Sharing_recv_CodecReport=JSON.stringify(M?.aggregated?.codecReport),S.data.Extensions.Video_send_performanceEvents=JSON.stringify(limitArraySize22(rebaseTime(v.localVideoPerformanceEvents,"timestamp",v.startTime),this.configProvider.config.diagnostics.telemetryLimits.numPerformanceEvents)),P?.ssrc_sharing_send&&((P?.ssrc_sharing_send).retransmittedPacketsSent=sampleseries(v.aggregatedModalityStats?.sharing?.send,(g=>g.outboundRTP.retransmittedPacketsSent))),this.configProvider.config.diagnostics.features.takeFreezeTelemetryFromGathererV2&&(_.length&&(S.data.Extensions.Video_recv_FreezeHistogram=JSON.stringify(R.aggregated?.freezeCountHistogram),S.data.Extensions.Video_recv_LongestFreezeDuration=JSON.stringify(R?.aggregated?.longestFreeze),S.data.Extensions.Video_recv_OngoingFreeze=JSON.stringify(R?.extensions?.isFrozen),S.data.Extensions.Video_recv_OngoingFreezeDuration=JSON.stringify(R?.aggregated?.ongoingFreezeDuration),S.data.Extensions.Video_recv_TotalFreezeDuration=JSON.stringify(R?.aggregated?.totalFreezeDuration),S.data.Extensions.Video_recv_RecvAvgFreezeDuration=JSON.stringify(R?.aggregated?.avgFreezeDuration),S.data.Extensions.Video_recv_FreezeTimestamps=JSON.stringify(rebaseAndLimitHistogramTimestamps(R?.aggregated?.freezeTimestampsHistogram,v.startTime,this.configProvider.config.diagnostics.telemetryLimits.numOfHistogramSamples))),I.length&&(S.data.Extensions.Sharing_recv_FreezeHistogram=JSON.stringify(M.aggregated?.freezeCountHistogram),S.data.Extensions.Sharing_recv_LongestFreezeDuration=JSON.stringify(M?.aggregated?.longestFreeze),S.data.Extensions.Sharing_recv_OngoingFreeze=JSON.stringify(M?.extensions?.isFrozen),S.data.Extensions.Sharing_recv_OngoingFreezeDuration=JSON.stringify(M?.aggregated?.ongoingFreezeDuration),S.data.Extensions.Sharing_recv_TotalFreezeDuration=JSON.stringify(M?.aggregated?.totalFreezeDuration),S.data.Extensions.Sharing_recv_RecvAvgFreezeDuration=JSON.stringify(M?.aggregated?.avgFreezeDuration),S.data.Extensions.Sharing_recv_FreezeTimestamps=JSON.stringify(rebaseAndLimitHistogramTimestamps(M?.aggregated?.freezeTimestampsHistogram,v.startTime,this.configProvider.config.diagnostics.telemetryLimits.numOfHistogramSamples)))),S.data.Extensions.EarlyMedia={NumStatsPolls:`${v.earlyMediaNumStatsPolls}`},S.data.Extensions.Audio_recv_packetsLostRateMax=`${round(w?.aggregated?.lossRateMax,6)||0}`,S.data.Extensions.Audio_recv_networkAvgLossRate=`${round(w?.aggregated?.networkAvgLossRate,6)||0}`,S.data.Extensions.Video_recv_packetsLostRateMax=`${round(R?.aggregated?.lossRateMax,6)||0}`,S.data.Extensions.Sharing_recv_packetsLostRateMax=`${round(M?.aggregated?.lossRateMax,6)||0}`,S.data.Extensions.Video_send_packetsLostRateMax=`${round(O?.aggregated?.lossRateMax,6)||0}`,S.data.Extensions.Sharing_send_packetsLostRateMax=`${round(D?.aggregated?.lossRateMax,6)||0}`,this.configProvider.config.diagnostics.features.useNewSimulcastTelemetryExtension&&(S.data.Extensions.Video_send_Simulcast=JSON.stringify(v.simulcast?.video),S.data.Extensions.Sharing_send_Simulcast=JSON.stringify(v.simulcast?.sharing)),S.data.Extensions.Video_send_powerEfficientEncoderEvents=limitRebaseAndStringifyEvents(O?.extensions?.powerEfficientEncoderEvents,this.configProvider.config.diagnostics.telemetryLimits.numPowerEfficientEncoderEvents,"timestamp",v.startTime),S.data.Extensions.Video_send_powerEfficientEncoderEventOnCount=JSON.stringify(O?.extensions?.powerEfficientEncoderEventOnCount),S.data.Extensions.Video_send_powerEfficientEncoderEventOffCount=JSON.stringify(O?.extensions?.powerEfficientEncoderEventOffCount)}return removeUndefinedFields(S)}startWaitingForStreamStart(g){this.gathererV1.startWaitingForStreamStart(g)}getTimerTracker(g,f){return this.gathererV1.getTimerTracker(g,f)}getLastStatistics(){return this.gathererV1.getLastStatistics()}updateSendStream(g,f){this.gathererV1.updateSendStream(g,f)}setSubscribedTrackIds(g){this.gathererV1.setSubscribedTrackIds(g)}setMaxSessionBandwidth(g){this.gathererV1.setMaxSessionBandwidth(g)}updateStatsWithLocalSsrcTrackInfo(){this.gathererV1.updateStatsWithLocalSsrcTrackInfo()}onSendersChanged(g,f){this.gathererV1.onSendersChanged(g,f)}setPreferredResolution(g,f,S){this.gathererV1.setPreferredResolution(g,f,S)}setIsRendering(g,f,S){this.gathererV1.setIsRendering(g,f,S)}setTimeToFirstFrame(g,f,S){this.gathererV1.setTimeToFirstFrame(g,f,S)}setFreezeDuration(g,f){this.gathererV1.setFreezeDuration(g,f)}addVideoControlMessage(g){this.gathererV1.addVideoControlMessage(g)}onMaxCapabilitiesRequested(g){this.gathererV1.onMaxCapabilitiesRequested(g)}addReportedReceiveBandwidth(g){this.gathererV1.addReportedReceiveBandwidth(g)}},YI=101,QI=[48e3,32e3,24e3,16e3,12e3],XI=class{constructor(g){this.context=g,this.cname=uniqueId(),this.dataMedia={type:qt.MEDIA_TYPE.data,protocol:qt.PROFILES.rtpSavp,port:0},this.configProvider=g.configProvider,this.logger=g.getLogger().createChild("WebkitSdpTrans")}fixTelephoneEvent(g){let f;return QI.forEach((f=>{removeCodec(g,{codec:"telephone-event",rate:f})})),updatePayload(g,YI,999),forOneCodec(g,{codec:"telephone-event",rate:8e3},(g=>(f=g.rtp.payload,g.rtp.payload=YI,g))),updatePayload(g,999,f||YI),f}toLocal(g,f,S){const v=f.isEmpty(),C=deepClone(g);let _;return C.media.forEach((g=>{if("audio"===g.type)v&&(_=this.fixTelephoneEvent(g)),fixComfortNoise(g);else{_&&updatePayload(g,YI,_);const S=f.getLocalSsrcs().get(getModality(g));this.enforceFixedSsrc(g,S)}const C=getAllowedCodecs(this.configProvider,g.type);"offer"===S&&filterCodecs2(g,C,v,this.logger)})),new g_(this.configProvider).modify(C),delete C.extmapAllowMixed,C}toOffer(g,f,S){return this.fromNative(g,f,S,!0)}toAnswer(g,f,S){return this.fromNative(g,f,S,!1)}toRemote(g,f,S,v){const C=deepClone(g);let _,T,I=this.configProvider.mediaConfig.maxBandwidthInKbps;C.bandwidth&&(!I||I>+g.bandwidth[0].limit)&&(I=+g.bandwidth[0].limit),C.media.forEach(((g,S)=>{f.getMediaEntity(S).isDisabled()&&g.type!==qt.MEDIA_TYPE.audio&&(g.port=0)}));let b=getBundle2(C);if(!b){let g=!1;C.media.forEach(((S,v)=>{const C=f.getMediaEntity(v);!g&&C.isEnabled()?(S.mid=C.getMid(),g=!0):(C.disable(),S.port=0)})),g&&(C.groups||(C.groups=[]),b={type:"BUNDLE"},C.groups.push(b))}C.media.forEach((g=>{const f=getModality(g);S[f]===qt.MEDIA_STATE.send&&(g.direction&&g.direction.toLowerCase()===qt.MEDIA_STATE.receive||(g.direction=qt.MEDIA_STATE.receive))}));const A=C.media.filter((g=>g.type===qt.MEDIA_TYPE.video));if(A.length>0){const g=A.filter((g=>0!==g.port));if(g.length>0){T=deepClone(g[0]),T.bandwidth&&delete T.bandwidth;const f=this.configProvider.config.audioBandwidthInKbps?this.configProvider.config.audioBandwidthInKbps:0;I&&I-f>0&&(T.bandwidth=[{limit:I-f,type:"AS"}]),T.mid="video",T.direction=null,delete T.label,T.ssrcs=[],T.ssrcGroups=[],delete T.msid,g.forEach((g=>{g.ssrcs&&(T.ssrcs=T.ssrcs.concat(g.ssrcs)),g.ssrcGroups&&(T.ssrcGroups=T.ssrcGroups.concat(g.ssrcGroups)),T.direction=mergeDirections(T.direction,g.direction||qt.MEDIA_STATE.sendReceive)})),removeUnifiedPlanExtensions(T)}else T=disabledMedia2(qt.MEDIA_TYPE.video,void 0,A[0].protocol,A[0].payloads)}const P=C.media.find((g=>g.type===qt.MEDIA_TYPE.audio));if(P)if(0!==P.port)_=deepClone(P),_.mid="audio",delete _.label,removeG722Codec(_),fixComfortNoise(_),removeUnifiedPlanExtensions(_);else{_=disabledMedia2(qt.MEDIA_TYPE.audio,void 0,P.protocol,P.payloads);const g=C.media.find((g=>!!g.iceUfrag));g&&(_.port=9,_.direction="inactive",_.mid="audio",_.iceUfrag=g.iceUfrag,_.icePwd=g.icePwd,_.rtcpMux="rtcp-mux",g.crypto&&(_.crypto=g.crypto),g.fingerprint&&(_.fingerprint=g.fingerprint,_.setup=g.setup),_.rtp=[{payload:0,codec:"PCMU",rate:8e3}],_.payloads="0")}C.media.forEach(((g,f)=>{g.type===qt.MEDIA_TYPE.data&&(g.type=qt.MEDIA_TYPE.dataChannel,g.payloads=qt.PAYLOAD_TYPE.DATA_CHANNEL,g.protocol=qt.PROFILES.udpDtlsSctp,g.mid="data",delete g.xDataProtocol,delete g.direction,isMediaDisabled(g)&&(C.media[f]=disabledMedia2(g.type,void 0,g.protocol,g.payloads)))}));const R=allowDataChannel(this.context)?C.media.find((g=>g.type===qt.MEDIA_TYPE.dataChannel)):null;C.media=[_,T,R].filter((g=>g)),f.getMediaEntities()[0].getModality()!==qt.MODALITY.audio&&C.media.reverse();const M=preferSdesSrtp(this.context.configProvider,this.context.config.isPstnCall),w=getSrtpInfo(g);return C.media.forEach((g=>{g.type!==qt.MEDIA_TYPE.dataChannel&&(!M&&g.fingerprint&&g.crypto&&delete g.crypto,g.protocol=!w.dtls||w.sdes&&M?qt.PROFILES.rtpSavpf:qt.PROFILES.udpTlsRtpSavpf)})),"offer"===v&&(filterCodecs2(_,this.configProvider.config.allowedAudioCodecs,!1,this.logger),filterCodecs2(T,this.configProvider.config.allowedVideoCodecs,!1,this.logger)),fixBundling(C,this.configProvider.mediaConfig.isTransportUnbundled),C}splitMedia(g,f,S,v,C){const _=g.getMid(),T=g.getModality(),I=deepClone(f);if(I.label=getLabelForModality(T),I.direction=v,I.mid=_,I.ssrcs=[],I.ssrcGroups=[],g.getModality()===qt.MODALITY.data)return I.type=qt.MEDIA_TYPE.data,I.payloads=qt.PAYLOAD_TYPE.X_DATA,I;const b=S.filter((g=>g.modality===T));if(b&&b.length){const g=[];f.ssrcs&&(b.forEach((S=>{const v=f.ssrcs.filter((g=>"msid"===g.attribute&&S.trackId===getTrackId(g.value))).map((g=>g.id));g.push(...v)})),I.ssrcs=f.ssrcs.filter((f=>g.indexOf(+f.id)>-1)),I.ssrcs.forEach((g=>{"cname"===g.attribute&&(g.value=this.cname)}))),f.ssrcGroups&&(I.ssrcGroups=f.ssrcGroups.filter((f=>f.ssrcs.split(" ").find((f=>g.indexOf(+f)>-1)))))}else{if(v===qt.MEDIA_STATE.send||v===qt.MEDIA_STATE.sendReceive)return disabledMedia2(f.type,getLabelForModality(T),f.protocol,f.payloads);v!==qt.MEDIA_STATE.receive&&v!==qt.MEDIA_STATE.inactive||(C[f.type].ssrcs?.[0]?I.ssrcs=[{id:C[f.type].ssrcs[0].id,attribute:"cname",value:this.cname}]:f.type===qt.MEDIA_TYPE.audio?I.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:f.type===qt.MEDIA_TYPE.video&&(I.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}return I}fromNative(g,f,S,v){const C=deepClone(g),_=this.configProvider.mediaConfig.maxBandwidthInKbps;_&&(C.bandwidth=[{limit:_,type:"CT"}]),new p_(this.configProvider).modify(C);const T=C.media.find((g=>g.type===qt.MEDIA_TYPE.audio)),I=C.media.find((g=>g.type===qt.MEDIA_TYPE.video)),b=C.media.find((g=>g.type===qt.MEDIA_TYPE.dataChannel)),A={};A[qt.MODALITY.audio]=T,A[qt.MODALITY.video]=I,A[qt.MODALITY.sharing]=I,A[qt.MODALITY.data]=b||this.dataMedia;const P={};P[qt.MEDIA_TYPE.audio]=T,P[qt.MEDIA_TYPE.video]=I,P[qt.MEDIA_TYPE.data]=b||this.dataMedia;const R={};return R[qt.MODALITY.audio]=f.getMediaEntitiesByModality(qt.MODALITY.audio)[0],R[qt.MODALITY.video]=f.getMediaEntitiesByModality(qt.MODALITY.video)[0],R[qt.MODALITY.sharing]=f.getMediaEntitiesByModality(qt.MODALITY.sharing)[0],R[qt.MODALITY.data]=f.getMediaEntitiesByModality(qt.MODALITY.data)[0],C.media=[],f.getMediaEntities().forEach((g=>{let _,T=S[g.getModality()];!g.isEnabled()||0===A[g.getModality()].port||g!==R[g.getModality()]&&T===qt.MEDIA_STATE.send?(_=disabledMedia2(g.getType(),getLabelForModality(g.getModality()),A[g.getModality()].protocol,A[g.getModality()].payloads),A[g.getModality()].payloads===qt.PAYLOAD_TYPE.DATA_CHANNEL&&(_.payloads=qt.PAYLOAD_TYPE.DATA_CHANNEL)):(T!==qt.MEDIA_STATE.inactive&&g!==R[g.getModality()]&&(T=qt.MEDIA_STATE.receive),_=this.splitMedia(g,A[g.getModality()],f.getLocalTracksInfo(),T,P),g!==R[g.getModality()]&&(_.candidates=[]));const I=A[g.getModality()].setup;I&&("actpass"!==I?g.setExtension("setup",I):v&&void 0!==g.getExtension("setup")&&(_.setup="actpass"!==g.getExtension("setup")?g.getExtension("setup"):I));const b=A[g.getModality()].iceUfrag,M=g.getExtension("iceUfrag");g.setExtension("iceRestart",!!b&&!!M&&M!==b),g.setExtension("iceUfrag",b),isMediaDisabled(_)&&g.disable(),C.media.push(_)})),new wE(this.context,S.data).modify(C),fixBundling(C,this.configProvider.mediaConfig.isTransportUnbundled),C}enforceFixedSsrc(g,f){let S=-1;if(!g.ssrcs)return;const v=[];if(g.ssrcs.forEach((g=>{"msid"===g.attribute&&v.push({ssrc:g.id,trackId:getTrackId(g.value)})})),g.ssrcs.forEach((g=>{"cname"===g.attribute&&S++,f&&(g.id=this.getVideoSSRC(S,f))})),g.ssrcGroups){const f=g.ssrcs.filter((g=>"cname"===g.attribute)).map((g=>g.id));g.ssrcGroups.forEach(((g,S)=>{g.ssrcs=[f[2*S],f[2*S+1]].join(" ")}))}}getVideoSSRC(g,f){return g%2==1?f+50:f}};function removeG722Codec(g){removeCodec(g,{codec:"g722",rate:8e3,encoding:2})}function removeUnifiedPlanExtensions(g){const f=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);g.ext&&(g.ext=g.ext.filter((g=>!f.has(g.uri))))}function fixComfortNoise(g){removeCodec(g,{codec:"CN",rate:16e3})}function getBundle2(g){return g.groups?g.groups.find((g=>"BUNDLE"===g.type)):null}function fixBundling(g,f){const S=g.groups?.findIndex((g=>"BUNDLE"===g.type)),v=g.groups?g.groups[S]:void 0;v&&(f?(v.mids=g.media.filter((g=>g.type===qt.MEDIA_TYPE.video)).map((g=>g.mid)).filter((g=>g)).join(" "),v.mids||delete g.groups[S]):v.mids=g.media.map((g=>g.mid)).filter((g=>g)).join(" "))}function disabledMedia2(g,f,S,v){return{type:g,port:0,label:f,payloads:v,protocol:S}}function getTrackId(g){return g.split(" ")[1]}function mergeDirections(g,f){return g===qt.MEDIA_STATE.sendReceive||f===qt.MEDIA_STATE.sendReceive?qt.MEDIA_STATE.sendReceive:g===f?g:g&&f&&g!==f?qt.MEDIA_STATE.sendReceive:g||f}function filterCodecs2(g,f,S,v){f.length&&g?.port&&filterCodecs(g,convertToCodecInfo(f),S,v)}var ZI=__toESM2(we()),eb=class{getCapabilities(g){const f=RTCRtpReceiver.getCapabilities(g);return f.codecs.forEach((g=>{g.mimeType=g.mimeType.toLowerCase().split("/").pop()})),Promise.resolve(f)}},tb=class{getCapabilities(g){const f=RTCRtpSender.getCapabilities(g);return f.codecs.forEach((g=>{g.mimeType=g.mimeType.toLowerCase().split("/").pop()})),Promise.resolve(f)}},ib=class{constructor(g,f){this.noRequiredCodecsWorkaround=f,this.selfGlobal=g.global.capabilityGatherer=g.global.capabilityGatherer||{},this.getCapabilities("video")}async getCapabilities(g){if("video"!==g&&"audio"!==g)return Promise.reject(new Error(`capabilities for ${g} are not supported`));if(!this.selfGlobal.gatherTask){const g=new dt;this.selfGlobal.gatherTask=g.promise;const f=void 0!==Xs.window.webkitRTCPeerConnection,S=f?new Xs.window.webkitRTCPeerConnection(null):new Xs.window.RTCPeerConnection(null),createOfferWrapper=g=>f?new Promise(((f,v)=>{S.createOffer(f,v,g)})):(this.noRequiredCodecsWorkaround&&S.addTrack(S.addTransceiver("video").receiver.track),S.createOffer(g));try{const f=await createOfferWrapper({offerToReceiveVideo:1,offerToReceiveAudio:1}),v={};ZI.parse(f.sdp).media.forEach((g=>{v[g.type]=g.rtp.map((f=>{const S={mimeType:f.codec.toLowerCase()};if("video"===g.type){const v=g.fmtp?.find((g=>g.payload===f.payload));S.sdpFmtpLine=v?.config}return S}))})),S.close(),g.resolve(v)}catch(f){this.selfGlobal.gatherTask=null,S.close(),g.reject(f)}}return this.selfGlobal.gatherTask.then((f=>({codecs:f[g]})))}},nb={build:(g,f,S=!1,v=!1)=>v?new tb:!f&&oa.hasCapabilitiesApi()?new eb:new ib(g,S)},rb=__toESM2(we()),sb="rollback";function SessionDescription2(){const g=[].slice.apply(arguments);let f=g[0]&&isRollback(g[0].type);g.splice(0,f?1:0,null);const S=new(Function.prototype.bind.apply(Xs.window.RTCSessionDescription,g)),v=Object.getOwnPropertyDescriptor(Xs.window.RTCSessionDescription.prototype,"type");return Object.defineProperty(S,"type",{get:()=>f?sb:v.get.call(S),set(g){f=isRollback(g),f||v.set.call(S,g)}}),S}function isRollback(g){return sb===g}var ab={build:()=>SessionDescription2},ob=[{codec:"telephone-event",rate:8e3},{codec:"cn",rate:16e3}];function PeerConnection(g){const f=[],S=ab.build(),v=[].slice.apply(arguments);v.splice(0,1,null),overrideSetting("iceTransportPolicy","iceTransports");const C=new(Function.prototype.bind.apply(Xs.window.webkitRTCPeerConnection,v));function overrideSetting(g,f){v[1]?.[g]&&(v[1][f]=v[1][g])}function shim(){shimPromises(),shimSetRemoteDescription(),shimCreateAnswer(),shimCreateOffer(),shimSenders()}function shimPromises(){[{name:"createOffer",reverseArgs:!0},"createAnswer","setRemoteDescription","setLocalDescription"].forEach((function(g){const f=g.name||g,S=C[f];C[f]=function(){const f=arguments;return new Promise((function(v,_){const T=[v,_];f.length>0&&T.splice(g.reverseArgs?T.length:0,0,f[0]),S.apply(C,T)}))}}))}function Sender(g,f){let S;Object.defineProperty(this,"dtmf",{get:()=>"audio"===g.kind?(S=S||C.createDTMFSender(g),S):null}),this.track=g,this._stream=f}function shimSenders(){C.getSenders&&C.addTrack&&C.removeTrack||(C.getSenders=function(){return f.slice()},C.addTrack=function(g,S){if(!g||!S)throw new Error("both media track and stream need to be provided");C.getLocalStreams().some((function(g){return g.id===S.id}))||C.addStream(S);let v=f.find((function(f){return f.track.id===g.id}));return v||(v=new Sender(g,S),f.push(v)),v},C.removeTrack=function(g){C.getLocalStreams().filter((function(f){return f.id===g._stream.id})).forEach((function(g){C.removeStream(g)})),remove2(f,(f=>f===g))})}function shimCreateOffer(){const g=C.createOffer;C.createOffer=function(f){const S=arguments;return f&&f.offerToReceiveVideo>1&&(f.offerToReceiveVideo=1),g.apply(C,S)}}function shimSetRemoteDescription(){["createOffer","createAnswer","setLocalDescription"].forEach((function(f){const S=C[f];C[f]=function(){const f=arguments;return g.getCapabilities("video").then((function(){return S.apply(S,f)}))}}));const f=C.setRemoteDescription;C.setRemoteDescription=function(S){return g.getCapabilities("video").then((function(g){const v=g.codecs,C=rb.parse(S.sdp);return C.media.forEach((function(g){if("video"===g.type&&(g.rtp.some((function(g){return v.some((function(f){return g.codec.toLowerCase()===f.mimeType}))}))?suppressH264FormatParameters(g):g.port=0),!hasDtls(g)){const f=getBundle(C);f?g.crypto=f.crypto:g.port||C.media.some((function(f){return!!f.port&&(g.crypto=f.crypto,!0)}))}})),S.sdp=rb.write(C),f(S)}))}}function shimCreateAnswer(){const g=C.createAnswer;C.createAnswer=function(){const f=arguments;return g.apply(C,f).then((function(g){if(!C.localDescription?.sdp)return g;const f=rb.parse(C.localDescription.sdp),v=[];if(f.media.forEach((function(g){ob.forEach((function(f){forOneCodec(g,f,(function(g){v.push(g)}))}))})),v.length){const f=rb.parse(g.sdp);let C=!1;f.media.forEach((function(g){v.forEach((function(f){forOneCodec(g,{codec:f.rtp.codec,rate:f.rtp.rate},(function(g){g.rtp.payload!==f.rtp.payload&&(g.rtp.payload=f.rtp.payload,C=!0)}))}))})),C&&(g=new S({type:g.type,sdp:rb.write(f)}))}return g}))}}function suppressH264FormatParameters(g){forOneCodec(g,{codec:"h264",rate:9e4},(function(g){if(g.fmtp){const f=new Zy,S=new Zy(g.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((function(g){if(S.contains(g)){let v=S.get(g);"profile-level-id"===g&&(v="42C02A"),f.setIfMissing(g,v)}})),g.fmtp.config=f.toString()}}))}function hasDtls(g){return"RTP/SAVPF"!==g.protocol}return shim(),C}var lb={build:g=>PeerConnection.bind(null,g)},cb=class{constructor(g){const f=g.configProvider.config.useSdpCapabilitiesLegacySession,S=g.configProvider.config.noRequiredCodecsWorkaround;this.RTCRtpReceiver=nb.build(g,f,S),this.SdpTransform=XI,this.RTCPeerConnection=lb.build(this.RTCRtpReceiver),this.RTCSessionDescription=ab.build()}};function UnsupportedAdapter(){function throwUnsupported(){throw new Error("unsupported platform")}this.SdpTransform=throwUnsupported,this.RTCPeerConnection=throwUnsupported,this.RTCSessionDescription=throwUnsupported,this.RTCRtpReceiver=throwUnsupported,this.RTCRtpSender=throwUnsupported}function isWebkitRtc(){return void 0!==Xs.window.webkitRTCPeerConnection}var db={build:g=>isWebkitRtc()?new cb(g):new UnsupportedAdapter},hb=class{constructor(g,f,S,v){this.logger=g,this.configProvider=f,this.activeSpeakerManager=S,this.contributingSourcesProvider=v,this.lastSources=[],this.emptySourcesCount=0,this.poll=()=>{const g=this.contributingSourcesProvider?.getContributingSources();if(!g)return this.logger.safe.info(`Contributing sources are not supported on this client. Retries attempts: ${this.emptySourcesCount}`),void(this.emptySourcesCount>0?(this.emptySourcesCount--,this.timer=window.setTimeout(this.poll,this.configProvider.config.webrtcContributingSourcesPollingInterval)):this.dispose());this.activeSpeakerManager.onContributingSourcesChanged(g.filter((g=>{const f=this.lastSources.find((f=>f.source===g.source));return!f||f.timestamp!==g.timestamp})).map((g=>g.source))),this.updateLastSources(g),this.timer=window.setTimeout(this.poll,this.configProvider.config.webrtcContributingSourcesPollingInterval)},this.emptySourcesCount=this.configProvider.config.webrtcContributingSourcesPollingEmptySources,this.startPolling(this.configProvider.config.webrtcContributingSourcesPollingStartDelay)}dispose(){this.stopPolling(),this.contributingSourcesProvider=void 0}useCustomCodec(g){g?this.stopPolling():this.startPolling()}updateContributingSources(g){this.activeSpeakerManager.onContributingSourcesChanged(g)}startPolling(g=this.configProvider.config.webrtcContributingSourcesPollingInterval){!this.timer&&this.contributingSourcesProvider&&(this.logger.safe.info("Polling started"),this.timer=window.setTimeout(this.poll,g))}stopPolling(){this.timer&&(this.logger.safe.info("Polling stopped"),window.clearTimeout(this.timer),this.timer=void 0)}updateLastSources(g){this.lastSources=g.map((g=>({source:g.source,timestamp:g.timestamp})))}},ub=class{constructor(g,f,S,v){this.logger=g,this.peerConnection=f,this.logDiagnosticsError=S,this.sessionDiagnostics=v}getContributingSources(){try{if(!this.peerConnection?.getReceivers)return;const g=this.peerConnection.getReceivers().find((g=>"audio"===g.track.kind));return g?g.getContributingSources?.():[]}catch(g){return this.logger.safe.error("Failed to get contributing sources",g),void(this.logDiagnosticsError&&this.sessionDiagnostics&&(this.sessionDiagnostics.contributingSourcesError=`${g}`))}}},gb=class{constructor(g){this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.localSsrcs=new Map,this.ssrcGenerator=new hE,this.logger=g.logger.createChild("MM"),this.configProvider=g.configProvider,this.numVideoChannels=g.numVideoChannels}fromOffer(g,f){g.media.forEach((g=>{if(g.type===qt.MEDIA_TYPE.audio)qt.MODALITY.audio in f&&this.addMediaEntity(qt.MODALITY.audio);else if(g.type===qt.MEDIA_TYPE.video){if(qt.MODALITY.video in f)for(let g=0;g<this.numVideoChannels;g++)this.addMediaEntity(qt.MODALITY.video);qt.MODALITY.sharing in f&&this.addMediaEntity(qt.MODALITY.sharing)}else g.type===qt.MEDIA_TYPE.data&&qt.MODALITY.data in f&&this.addMediaEntity(qt.MODALITY.data)}))}fromRemote(g,f){g.media.forEach(((g,S)=>{const v=getModality(g);if(isMediaDisabled(g)||!(v in f))this.mediaEntities[S]?this.mediaEntities[S].disable():this.addDisabledMediaEntity(v),this.mediaEntities[S].setRemoteStreamId(null),this.mediaEntities[S].setRemoteTrackId(null);else{if(this.mediaEntities[S]?this.mediaEntities[S].update(v,g.mid||this.generateMid(S)):this.addMediaEntity(v,g.mid||this.generateMid(S)),g.msid)this.mediaEntities[S].setRemoteStreamId(g.msid.split(" ")[0]),this.mediaEntities[S].setRemoteTrackId(g.msid.split(" ")[1]);else if(g.ssrcs){const f=g.ssrcs.find((g=>"msid"===g.attribute));f?(this.mediaEntities[S].setRemoteStreamId(f.value.split(" ")[0]),this.mediaEntities[S].setRemoteTrackId(f.value.split(" ")[1])):this.logger.safe.warn(`No ssrc msid for media of type ${g.type} with mid ${g.mid}`)}const f=g.xSourceStreamId||this.generateSourceStreamId(S);this.mediaEntities[S].setXSourceStreamId(f)}}))}isEmpty(){return 0===this.mediaEntities.length}addMediaEntity(g,f){this.createMediaEntity(g,f||this.generateMid(this.mediaEntities.length))}addDisabledMediaEntity(g){this.createMediaEntity(g)}getMediaEntities(){return this.mediaEntities}createMediaEntity(g,f){const S=SE.create(this.configProvider,g,f);return this.mediaEntities.push(S),S}getMediaEntity(g){return this.mediaEntities[g]}getMediaEntityByMid(g){return this.mediaEntities.find((f=>f.getMid()===g))}getMediaEntitiesByModality(g){return this.mediaEntities.filter((f=>f.getModality()===g))}getMediaEntityByRemoteStreamId(g){return this.mediaEntities.find((f=>f.getRemoteStreamId()===g))}getMediaEntityByLocalTrackId(g){return this.mediaEntities.find((f=>f.getLocalTrackId()===g))}getMediaEntityByXSourceStreamId(g){return this.mediaEntities.find((f=>f.getXSourceStreamId()===g))}reset(){this.mediaEntities=[]}syncModalities(g,f,S){this.disableModalities(f),S||(this.enableModalities(f),this.addModalities(f))}enableModalities(g){this.mediaEntities.forEach(((f,S)=>{f.getModality()in g&&f.isDisabled()&&f.update(f.getModality(),this.generateMid(S))}))}disableModalities(g){this.mediaEntities.forEach((f=>{f.getModality()in g||f.disable()}))}setRollbackUpdateHandler(g){}addModalities(g){const f={};this.mediaEntities.map((g=>g.getModality())).forEach((g=>{f[g]=!0}));for(const S in g)S in f||this.addMediaEntity(S)}setLocalTracksInfo(g){this.mediaTracks=g,this.updateLocalSsrc(this.mediaTracks)}getLocalTracksInfo(){return this.mediaTracks}getLocalSsrcs(){return this.localSsrcs}updateMediaEntitiesWithLocalTracks(){this.mediaTracks&&(this.mediaEntities.forEach((g=>g.setLocalTrackId(null))),this.mediaTracks.forEach((g=>{const f=this.getMediaEntitiesByModality(g.modality)[0];f?f.setLocalTrackId(g.trackId):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(g.modality)}`)})))}updateMediaEntitiesWithActivityState(g,f){}backup(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((g=>{this.mediaEntitiesBackup.push(g.clone())}))}commit(){this.mediaEntitiesBackup=[]}rollback(){this.mediaEntities=this.mediaEntitiesBackup}generateSourceStreamId(g){return g+10}generateMid(g){return`media_${g}`}updateLocalSsrc(g){g.forEach((g=>{if(!this.localSsrcs.get(g.modality)){const f=this.ssrcGenerator.nextVideoStreamSsrc().min;this.logger.safe.debug(`Ssrc updated for modality: ${g.modality}: ${f}`),this.localSsrcs.set(g.modality,f)}}))}},pb=__toESM2(we()),mb=class{constructor(g,f,S,v,C){this.logger=g,this.RtcDescType=f,this.sessionDescription=S,this.negotiationQueue=v,this.mediaManager=C}configure(g){this.peerConnection=g}renegotiateNow(){return this.renegotiate(null,!0)}renegotiate(g,f=!1,S="local"){if(!this.peerConnection)throw new Error("trying to renegotiate without a peerConnection");const v="local"===S?this.createNegotiationTaskForHaveLocalOffer(g):this.createNegotiationTaskForHaveRemoteOffer();return f?(this.logger.safe.info(`forced ${S} renegotiation starting`),Promise.resolve(v())):this.negotiationQueue.add(v)}normalizeRemoteSdpSDES(g,f){if(f.media[0].crypto)g.media.forEach((g=>{delete g.fingerprint,delete g.setup,g.crypto=g.crypto.filter((g=>f.media[0].crypto.some((f=>f.id===g.id)))).slice(0,1)})),g.fingerprint&&delete g.fingerprint;else{const f=this.mediaManager.getMediaEntities().find((g=>void 0!==g.getExtension("setup")));g.media.forEach((g=>{const S=f?.getExtension("setup")||"actpass";"actpass"===g.setup&&(g.setup="active"===S?"passive":"active")}))}}normalizeRemoteSdpExtensions(g,f){g.media.forEach(((g,S)=>{const v=new Set(f.media[S].ext?.map((g=>g.value))||[]);g.ext=g.ext?.filter((g=>v.has(g.value)))}))}createNegotiationTaskForHaveLocalOffer(g){return async()=>{let f=this.peerConnection.remoteDescription.sdp;const S=this.peerConnection.localDescription.sdp;this.logger.safe.info(`local renegotiation starting remoteSdp=${!!f} localSdp=${!!S}`);const v=pb.parse(f),C=pb.parse(S);this.normalizeRemoteSdpSDES(v,C),this.normalizeRemoteSdpExtensions(v,C),f=pb.write(v);let _=new this.RtcDescType({sdp:f,type:"answer"});g&&g.forEach((g=>{_=g.modifyDescriptor(_)}));try{this.logger.safe.info("creating offer");const g=await this.peerConnection.createOffer(),f=this.sessionDescription.createLocalOffer(g.sdp),S=new this.RtcDescType({sdp:f.toLocal(),type:"offer"});this.logger.safe.info("setting local description"),this.logger.unsafe.debug(`local description, sdp: ${S.sdp}`),await this.peerConnection.setLocalDescription(S),this.logger.safe.info("setting remote description"),this.logger.unsafe.debug(`remote description, sdp: ${_.sdp}`),await this.peerConnection.setRemoteDescription(_),this.logger.safe.debug("local renegotiation done")}catch(g){throw this.logger.safe.error("local renegotiation failed: ",g.toString()),g}}}createNegotiationTaskForHaveRemoteOffer(){return this.logger.safe.info("createNegotiationTaskForRemote"),async()=>{this.logger.safe.info("proceed with setting local sdp start");try{this.logger.safe.info("creating answer");const g=await this.peerConnection.createAnswer();this.logger.safe.info("applying answer");const f=this.sessionDescription.createLocalAnswer(g.sdp),S=new this.RtcDescType({sdp:f.toLocal(),type:"answer"});this.logger.safe.info("setting [answer] local description"),this.logger.unsafe.debug(`[answer] local description, sdp: ${S.sdp}`),await this.peerConnection.setLocalDescription(S),this.logger.safe.info("local answer for renegotiation is done")}catch(g){throw this.logger.safe.error("local answer for renegotiation failed: ",g.toString()),g}}}},fb=15e3,Sb=5e3,vb=class{constructor(g,f,S){this.settings=g,this.listener=f,this.logger=S,this.lastSendBW=0,this.coolingDown=!1,this.cooldownTimer=null,this.cooldownEnd=0,this.active=!1,this.maxResolution=this.settings.maxResolution,this.settings.scalingEnabled?this.active=!0:this.logger.safe.info("Resolution management disabled: no resolution management for 1x1 calls")}dispose(){this.currentResolution=null,this.pendingResolution=null,this.maxResolution=null,this.listener=null,this.active=!1,clearTimeout(this.cooldownTimer),this.cooldownTimer=null,this.listener=null}setMaxResolution(g){const f=ei.Send.getResolutionByFs(g);f!==this.maxResolution&&(this.logger.safe.info(`Setting max resolution: ${f}`),this.maxResolution=f,this.lastSendBW&&this.processEstimatedBandwidth(this.lastSendBW))}updateEstimatedSendBandwidth(g){g!==this.lastSendBW&&(this.logger.safe.debug(`Send BW: ${g}`),this.processEstimatedBandwidth(g))}resetCurrentResolution(){this.currentResolution=null}getCurrentResolution(){return this.currentResolution?.fs}setCurrentResolution(g){this.currentResolution=g}applyRes(g){this.pendingResolution=g,this.coolingDown&&(!this.currentResolution||g.fs>this.currentResolution.fs)||(this.coolingDown=!0,this.logger.safe.info(`Changing resolution to ${g}`),this.listener&&this.listener.onResolutionChanged(g.fs).then((f=>{f?(g===this.pendingResolution&&(this.pendingResolution=null),this.coolingDown&&!this.currentResolution&&(this.coolingDown=!1),this.currentResolution=g,this.cooldown()):(this.logger.safe.info("Unable to apply resolution at the moment"),this.cooldown(Sb))})).catch((g=>{this.logger.safe.error(`Error while applying new resolution: ${JSON.stringify(g)}`),this.pendingResolution=null})))}cooldown(g=fb){!this.active||this.coolingDown&&this.cooldownEnd-Date.now()>fb||(this.cooldownTimer&&clearTimeout(this.cooldownTimer),this.coolingDown=!0,this.cooldownEnd=Date.now()+fb,this.cooldownTimer=setTimeout((()=>{this.logger.safe.debug("Resolution changer cooled down"),this.coolingDown=!1,this.cooldownTimer=null,this.pendingResolution?this.proposeResolution(this.pendingResolution):this.processEstimatedBandwidth(this.lastSendBW)}),g))}proposeResolution(g){let f=g;this.maxResolution&&this.maxResolution.fs<f.fs&&(f=this.maxResolution),this.currentResolution&&f.fs===this.currentResolution.fs||this.applyRes(f)}processEstimatedBandwidth(g){const{lowRes:f,highRes:S}=ei.Send.getResolutionForBitrate(g),v=g<this.lastSendBW?S:f;g<this.lastSendBW&&v&&this.currentResolution&&this.currentResolution.fs<v.fs||(v&&this.proposeResolution(v),this.lastSendBW=g)}};function calculateEstimatedSendBandwidth(g,f){const S=f.config.maxBandwidthInKbpsFallback>0?f.config.maxBandwidthInKbpsFallback:Math.floor(Number.MAX_SAFE_INTEGER/1e3),v=1e3*((f.mediaConfig.maxBandwidthInKbps||S)-(f.config.audioBandwidthInKbps||0)),C=g.transport?.selectedCandidatePair?.availableOutgoingBitrate??0;return Math.min(v,C)}var Cb=class extends Ht{constructor(g,f){super(f),this.configProvider=g,this.logger=f,this.lastReportedAgo=1/0,this._forceUpdate=!1}forceUpdate(){this._forceUpdate=!0}onBandwidthChanged(g){this._forceUpdate?this.updateBandwidth(g,"forceUpdate"):this.processEstimatedBandwidth(g)}processEstimatedBandwidth(g){if(this.lastReportedAgo++,!g||this.bandwidth===g)return;const f=this.configProvider.config.webrtcSendBandwidthIgnoredUpdateLimit,S=this.configProvider.config.webrtcSendBandwidthThreshold,v=this.lastReportedAgo===1/0,C=!f&&!S,_=f&&this.lastReportedAgo>=f,T=S&&Math.abs((g-this.bandwidth)/this.bandwidth)>=S;if(v||C||_||T){const f=+v|+C<<1|+_<<2|+T<<3,S=this.getUpdateReason(f);this.updateBandwidth(g,S)}}updateBandwidth(g,f){this.bandwidth=g,this.logger.safe.debug(`Updating send bandwidth: ${this.bandwidth}, reason: ${f}`),this.notifySendBandwidthChanged()}notifySendBandwidthChanged(){this._forceUpdate=!1,this.event("onSendBandwidthChanged").raise(this.bandwidth),this.lastReportedAgo=0}getUpdateReason(g){return 1&g?"firstReport":2&g?"throttlingDisabled":4&g?"noReportsForTooLong":8&g?"bigMovement":"none"}},yb=class{constructor(g,f,S,v,C,_,T){this.listener=g,this.statisticsGatherer=f,this.diagnostics=S,this.logger=v,this.configProvider=C,this.isSimulcastEnabled=T,this.serialQueue=new zC(this.logger),this.modality=qt.MODALITY.video;const I=_.maxResolution?{maxFs:_.maxResolution.fs}:null;this.validator=new gC(this.logger.createChild("CapsValidator"),I),this.resolutionManager=new vb(_,this,this.logger.createChild("rm")),this.statisticsGatherer.on("onStatisticsChanged",(g=>this.onStatisticsChanged(g))),this.statisticsGatherer.on("onDiagnosticUpdated",(g=>this.onDiagnosticUpdated(g)))}async setMaxCapabilities(g,f){const S={modality:this.modality,causeId:g,capabilities:f,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(S),this.diagnostics?.onMaxCapabilitiesRequested(S),this.causeId=g;const v=this.validator.ensureValidity(f[0]);this.streamSenderParams={...f[0],...v},this.resolutionManager.setMaxResolution(this.streamSenderParams.maxFs),this.configProvider.mediaConfig.simulcastSessionEnabled&&await this.applyCapabilities(this.getParamsToApply())}resetCurrentResolution(){this.resolutionManager.resetCurrentResolution()}getCurrentResolution(){return this.resolutionManager.getCurrentResolution()}setCurrentResolution(g){this.resolutionManager.setCurrentResolution(g)}async onResolutionChanged(g){return this.applyCapabilities(this.getParamsToApply(g))}dispose(){this.resolutionManager.dispose(),this.resolutionManager=null}async applyCapabilities(g){return g?this.lastAppliedSenderParams===g?(this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(g)}`),!0):(this.logger.safe.info(`Capabilities to apply: ${JSON.stringify(g)}`),this.lastAppliedSenderParams=g,this.listener.onReceiveCapabilitiesChanged(this.modality,this.causeId,[g])):(this.logger.safe.error("Send capabilities are not set. Cannot apply constraints"),!1)}getParamsToApply(g){if(!this.streamSenderParams)return null;const f=g||this.resolutionManager.getCurrentResolution();if(!f||this.streamSenderParams.maxFs<=f)return this.streamSenderParams;const S=shallowClone(this.streamSenderParams);return S.maxFs=f,S}onStatisticsChanged(g){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.resolutionManager.updateEstimatedSendBandwidth(g.estimatedSendBandwidth)}onDiagnosticUpdated(g){try{if(this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation){if(!g.video?.send?.length||!g.video.send[0])return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Estimating send bandwidth");const f=calculateEstimatedSendBandwidth(g.video.send[0],this.configProvider);this.resolutionManager.updateEstimatedSendBandwidth(f)}}catch(g){this.logger.error("Failed to processes diagnostics update: "+g)}}};__decorateClass([sequentialize()],yb.prototype,"applyCapabilities",1);var Eb=class{constructor(g,f,S,v,C){this.modality=g,this.listener=f,this.statisticsGatherer=S,this.diagnostics=v,this.isSimulcastEnabled=C}setMaxCapabilities(g,f){const S={modality:this.modality,causeId:g,capabilities:f,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(S),this.diagnostics?.onMaxCapabilitiesRequested(S),this.listener.onReceiveCapabilitiesChanged(this.modality,g,f)}dispose(){}resetCurrentResolution(){}getCurrentResolution(){return null}setCurrentResolution(g){}},_b=class{constructor(g,f,S,v,C,_){this.logger=g,this.settings=f,this.listener=S,this.statsGatherer=v,this.diagnostics=C,this.configProvider=_,this.mediaSourceModels=[],this.pendingCapabilities=new Map}dispose(){this.mediaSourceModels.forEach((g=>{g.handler&&(g.handler.dispose(),g.handler=null)})),this.mediaSourceModels=null}updateRegisteredSources(g){this.logger.safe.info(`Local media params updated: ${JSON.stringify(g)}`);const f=[];this.mediaSourceModels.forEach((g=>f.push(g.sourceId)));const S=g.map((g=>g.sourceId)),v=subtractFrom(f,S);this.removeSourcesWithIds(v);const C=subtractFrom(S,f);this.addSourcesWithIds(C,g)}setMaxCapabilities(g,f){for(const S of g){if(!S.capabilities.length)continue;if(!S.sourceId){this.logger.safe.info(`SourceId is not defined to apply recv capabilities: ${JSON.stringify(S)}`);continue}const g=this.getModelWithSourceId(S.sourceId);if(!g){this.logger.safe.info(`Model is not registered for sourceId: ${S.sourceId}`),this.configProvider.config.enableCachingFMTP&&this.pendingCapabilities.set(S.sourceId,S);continue}this.logger.safe.info(`Capabilities handler found for sourceId: ${S.sourceId}`);const v=this.getOrCreateHandlerForModel(g,S.isSimulcast);v?v.setMaxCapabilities(S.causeId||f,S.capabilities):this.logger.safe.info(`Handler is not found for sourceId: ${S.sourceId}`)}this.logger.safe.debug("Max capabilities application completed")}setPendingCapabilities(){if(!this.configProvider.config.enableCachingFMTP)return;this.logger.safe.info(`Apply pending capabilities for sources [${Array.from(this.pendingCapabilities.keys())}]`);const g=Array.from(this.pendingCapabilities.values());this.setMaxCapabilities(g),this.pendingCapabilities.clear()}clearPendingCapabilities(){this.pendingCapabilities.clear()}resetCurrentResolution(){const g=this.mediaSourceModels.find((g=>g.modality===qt.MODALITY.video));g?.handler&&g.handler.resetCurrentResolution()}getCurrentResolution(){const g=this.mediaSourceModels.find((g=>g.modality===qt.MODALITY.video));return g?.handler?g.handler.getCurrentResolution():this.currentResolution?.fs}setCurrentResolution(g){const f=this.mediaSourceModels.find((g=>g.modality===qt.MODALITY.video));f?.handler?f.handler.setCurrentResolution(g):this.currentResolution=g}getOrCreateHandlerForModel(g,f){return g.handler||(g.handler=this.getCapabilitiesHandler(g.modality,f)),g.handler}addSourcesWithIds(g,f){g.forEach((g=>{const S=f.find((f=>f.sourceId===g));this.registerSource(g,S.modality)}))}removeSourcesWithIds(g){g.forEach((g=>this.unregisterSource(g)))}registerSource(g,f){this.logger.safe.info(`SourceId ${g} registered with mediaType: ${f}`),this.mediaSourceModels.push({modality:f,sourceId:g})}unregisterSource(g){const f=this.mediaSourceModels.find((f=>f.sourceId===g));f?(f.handler&&f.handler.dispose(),this.mediaSourceModels.splice(this.mediaSourceModels.indexOf(f),1),this.logger.safe.info(`SourceId ${g} unregistered`)):this.logger.safe.info(`Model doesn't exist with sourceId ${g}`)}getModelWithSourceId(g){return this.mediaSourceModels.find((f=>f.sourceId===g))}getCapabilitiesHandler(g,f){if(g===qt.MODALITY.audio)return null;if(g===qt.MODALITY.video&&!f&&this.settings.customBwEstimationEnabled){const g=new yb(this.listener,this.statsGatherer,this.diagnostics,this.logger.createChild("ach"),this.configProvider,this.settings,f);return this.currentResolution&&g.setCurrentResolution(this.currentResolution),g}return new Eb(g,this.listener,this.statsGatherer,this.diagnostics,f)}},Tb=class extends Ht{constructor(g,f,S,v,C,_){super(g),this.logger=g,this.multiParty=f,this.configProvider=S,this.mediaManager=v,this.statsGatherer=C,this.diagnostics=_,this.rendererResolutions=new Map,this.rendererResolutionsApplied=new Map,this.rendererResolutionMax=new Map,this.hasPendingLimitResolutionUpdate=!1,this.spotlightedRenderers=[]}addRenderer(g){this.rendererResolutions.set(g,{width:0,height:0}),g.on("onRendererSizeChanged",((g,f)=>{this.onRendererSizeChanged(g,f)})),this.scheduleUpdateLimitedResolutions()}removeRenderer(g){this.rendererResolutions.delete(g),this.rendererResolutionsApplied.delete(g),this.rendererResolutionMax.delete(g),this.scheduleUpdateLimitedResolutions()}clearRenderers(){this.rendererResolutions.clear(),this.rendererResolutionsApplied.clear(),this.rendererResolutionMax.clear()}getMaxAllowedVideoFS(){const g=this.getMaxHeightFromConfig(this.sizedRenderersCount);return this.getMaxFSForHeight(g)}limitResolutionOnPoorPerformance(g){const f=this.getRendererByMsi(g);if(!f)return;const S=f.resolution.height>f.resolution.width,v=ei.Recv.getNextLowerResolution(f.resolution.width,f.resolution.height);if(!v)return;const C={width:S?v.height:v.width,height:S?v.width:v.height};this.rendererResolutionMax.set(f.renderer,C),this.diagnostics?.registerResolutionChangeRequest({ts:Date.now(),msi:f.renderer.getMsi(),res:C}),this.logger.safe.info(`Poor perf. Limiting resolution for renderer msi: ${f.renderer.getMsi()} from ${f.resolution.height}p to ${C.height}p`),this.onRendererSizeChanged(f.renderer,C)}get renderersCount(){return this.rendererResolutions.size}get sizedRenderersCount(){return this.configProvider.config.excludeUnsizedRenderersFromMultiviewResolutionLimits?[...this.rendererResolutions.values()].filter((g=>g.height>0)).length:this.renderersCount}getMaxFSForHeight(g){return this.limitMaxFS(ei.Recv.getMaxFsForHeight(g))}getRendererByMsi(g){for(const[f,S]of this.rendererResolutions.entries())if(f.getMsi()===g)return{renderer:f,resolution:S};return null}applyRendererResolution(g,f){this.setMaxFSCapabilities(g,f),this.rendererResolutionsApplied.set(g,f);const S=g.getMediaStream()&&g.getMediaStream().getVideoTracks();S?.[0]&&this.statsGatherer.setPreferredResolution(S[0].id,f,g.getModality())}onRendererSizeChanged(g,f){this.rendererResolutions.set(g,f),this.scheduleUpdateLimitedResolutions()}scheduleUpdateLimitedResolutions(){this.hasPendingLimitResolutionUpdate||(this.hasPendingLimitResolutionUpdate=!0,window.setTimeout((()=>{this.hasPendingLimitResolutionUpdate=!1;const g=this.groupMaxRenderersResolutionsByMsi();this.logger.safe.info(`Updating resolution limits: renderers count ${this.renderersCount}, with size: ${this.sizedRenderersCount}, resolution limits: ${JSON.stringify(this.configProvider.config.multiviewResolutionLimits)}`),this.spotlightedRenderers=this.findSpotlightedRenderers(),this.spotlightedRenderers.length>0&&this.logger.safe.info(`Spotlighted renderers: ${this.spotlightedRenderers.map((g=>g.getMsi()))}, max spotlight height: ${this.configProvider.config.maxSpotlightResolution}`);for(const[f,S]of this.rendererResolutions.entries()){if(!S.height)continue;const v=g.get(f.getMsi()),C=this.limitRendererResolution(f,v||S),_=this.rendererResolutionsApplied.get(f);(!_||_.height!==C.height||_.width!==C.width)&&this.applyRendererResolution(f,C)}}),this.configProvider.config.multiviewResolutionLimitUpdateThrottleDelay))}findSpotlightedRenderers(){if(this.sizedRenderersCount<=1||!this.configProvider.config.isSpotlightEnabled)return[];let g=!1,f=0;for(const[S,v]of this.rendererResolutions.entries())v.height&&v.height!==f&&(f&&(g=!0),f=v.height);if(!g)return[];const S=new Ss(((g,f)=>g.resolution.width>f.resolution.width));for(const[g,f]of this.rendererResolutions.entries())S.enqueue({renderer:g,resolution:f});const v=[];let C=this.configProvider.config.maxNumberOfPinnedVideos;for(;C;){const g=S.peek()?.resolution?.width,f=[];for(;S.peek()?.resolution?.width===g;)f.push(S.dequeue().renderer);if(!(C-f.length>=0))break;C-=f.length,v.push(...f)}return v}getMaxHeightFromConfig(g,f=!1){return f?this.configProvider.config.maxSpotlightResolution:this.configProvider.config.multiviewResolutionLimits[`${g}`]||this.configProvider.config.multiviewResolutionLimits.more}getMaxHeight(g){const f=this.spotlightedRenderers.some((f=>f.getMsi()===g.getMsi()));let S=this.getMaxHeightFromConfig(this.sizedRenderersCount,f);const v=this.rendererResolutionMax.get(g);return v&&(S=Math.min(S,Math.min(v.height,v.width))),S}limitRendererResolution(g,f){const S=this.getMaxHeight(g);if(!S)return f;if(f.height>f.width&&f.width>S){const g=S/f.width;return{height:Math.ceil(f.height*g),width:S,limited:!0}}if(f.width>f.height&&f.height>S){const g=S/f.height;return{height:S,width:Math.ceil(f.width*g),limited:!0}}return f}setMaxFSCapabilities(g,f){const S=g.getMediaStream();if(!S)return void this.logger.safe.warn("renderer has no stream attached");const v=this.mediaManager.getMediaEntityByRemoteStreamId(S.id);if(!v?.getLocalRecvCapabilities())return void this.logger.safe.warn(`no capabilities for provided modality: ${g.getModality()}`);const C=f.limited?this.getMaxFSForHeight(f.height):this.getMaxFS(f.width,f.height),_=v.getLocalRecvCapabilities();_.setMaxFS(C,(()=>{if(this.logger.safe.info(`updated max-fs video capability to ${C} for renderer msi: ${g.getMsi()}`),this.multiParty&&this.configProvider.config.webrtcMultiPartyRecvVideoSignaling){const f=g.getMsi(),v=_.buildFmtp();this.event("onSourceRequestRequired").raise(S.id,f,v)}else this.event("onNegotiationRequired").raise()}))}getMaxFS(g,f){return this.limitMaxFS(ei.Recv.getMaxFsForHeight(f))}limitMaxFS(g){return this.multiParty?Math.min(g,this.configProvider.config.webrtcMultiPartyRecvVideoMaxFS):Math.min(g,this.configProvider.config.webrtcRecvVideoMaxFS)}groupMaxRenderersResolutionsByMsi(){const g=new Map;return this.rendererResolutions.forEach(((f,S)=>{const v=S.getMsi(),C=g.get(v);(!C||f.width>C.width&&f.height>C.height)&&g.set(v,f)})),g}},Ib=class extends Ht{constructor(g,f){super(),this.configProvider=g,this.getModality=f,this.isRendering=!1,this.currentFreezeDuration=0,this.mediaStarted=!1,this.lastBytesRecv=0,this.currentLowBitrateDuration=0}captureRawStatistics(g){const f=g.googFrameRateDecoded,S=g.googFrameRateReceived,v=g.bytesReceived;void 0!==v&&this.getModality()!==qt.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateBitrate(v,f),f>0&&(this.mediaStarted=!0),0===f||0===S?this.currentFreezeDuration+=qt.TIME_INTERVAL.SEC_1:f>0&&(void 0===S||S>0)&&(this.currentFreezeDuration=0);const C=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(C)}updateRenderingTracker(g){const f=g.extensions.frameRateDecoded||0,S=g.extensions.frameRateReceived||0,v=g.extensions.bitrate;void 0!==v&&this.getModality()!==qt.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateLowBitrateDuration(v,f),f>0&&(this.mediaStarted=!0),0===f||0===S?this.currentFreezeDuration+=qt.TIME_INTERVAL.SEC_1:f>0&&(void 0===S||S>0)&&(this.currentFreezeDuration=0);const C=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(C)}calculateLowBitrateDuration(g,f){g/1e3<this.configProvider.config.notRenderingLowBitrateThreshold&&f<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}calculateBitrate(g,f){const S=8*(g-this.lastBytesRecv);this.lastBytesRecv=g,this.calculateLowBitrateDuration(S,f)}setIsRendering(g){const f=this.currentFreezeDuration<g&&this.currentLowBitrateDuration<g&&this.mediaStarted;f!==this.isRendering&&(this.isRendering=f,this.event("onIsRenderingChanged").raise(this.isRendering))}},bb=class extends Ht{constructor(g,f,S){super(),this.videoElement=g,this.configProvider=f,this.getTimeToFirstFrame=S,this.prevCurrentTime=0,this.prevDecodedFrameCount=0,this.prevTimestamp=Date.now(),this.currentFreezeDuration=0,this.freezeDurationTimer=window.setInterval((()=>{this.calcFreezeDurationMs()}),this.configProvider.config.freezeIntervalFrequency)}calcFreezeDurationMs(){const g=this.videoElement.currentTime,f=g===this.prevCurrentTime,S=this.videoElement.webkitDecodedFrameCount,v=void 0===S||S===this.prevDecodedFrameCount;if(this.prevCurrentTime=g,this.prevDecodedFrameCount=S,-1!==this.getTimeToFirstFrame())if(f&&v){const g=Date.now();this.currentFreezeDuration+=g-this.prevTimestamp,this.prevTimestamp=g}else{if(this.currentFreezeDuration>this.configProvider.config.freezeMinDuration){const g=this.calcFreeze();this.event("onFreezeEnded").raise(g)}this.currentFreezeDuration=0}this.prevTimestamp=Date.now()}getEndOfTheFreeze(){let g=0;return this.currentFreezeDuration>0&&(g=this.calcFreeze(),this.currentFreezeDuration=0),g}dispose(){const g=this.getEndOfTheFreeze();this.event("onFreezeEnded").raise(g),clearInterval(this.freezeDurationTimer)}calcFreeze(){const g=Date.now()-this.prevTimestamp;return this.currentFreezeDuration+g}},Ab=class extends Ht{constructor(g,f,S,v){super(),this.videoElement=g,this.minInterval=f,this.maxInterval=S,this.window=Xs.window,this.devicePixelRatio=v&&window.devicePixelRatio||1,this.originalVideoElementSize={width:g.offsetWidth,height:g.offsetHeight},this.initializeSizeTracking()}get width(){return this.originalVideoElementSize.width*this.devicePixelRatio}get height(){return this.originalVideoElementSize.height*this.devicePixelRatio}initializeSizeTracking(){const g=Math.floor(Math.random()*Math.abs(this.maxInterval-this.minInterval))+this.minInterval;this.elementSizeTrackingRef=this.window.setInterval((()=>{this.videoElementSizeChanged()&&(this.saveCurrentVideoElementSize(),this.raiseChanged())}),g)}triggerVideoElementSizeChange(){this.originalVideoElementSize.height&&this.originalVideoElementSize.width&&this.raiseChanged()}dispose(){this.elementSizeTrackingRef&&this.window.clearInterval(this.elementSizeTrackingRef)}videoElementSizeChanged(){return this.originalVideoElementSize.width!==this.videoElement.offsetWidth||this.originalVideoElementSize.height!==this.videoElement.offsetHeight}saveCurrentVideoElementSize(){this.originalVideoElementSize.width=this.videoElement.offsetWidth,this.originalVideoElementSize.height=this.videoElement.offsetHeight}},Pb=class extends ey{constructor(g,f,S,v,C,_){super(C,g.createChild("remote"),f),this.diagnostics=S,this.subscriptionManager=v,this.sessionDiagnostics=_,this.disposed=!1,this.currentIsRendering=!1,this.startTimeTTFF=0,this.timeToFirstFrame=-1,this.isTimeToFirstFrameReported=!1,this.configProvider.config.freezeIntervalFrequency&&(this.freezeTracker=new bb(this.getVideoElement(),this.configProvider,(()=>this.timeToFirstFrame)),this.freezeTracker.on("onFreezeEnded",(g=>{this.diagnostics?.addFreezeDuration(g),this.event("onFreezeEnded").raise(g)}))),this.configProvider.config.isRenderingBasedOnRawStatistics&&(this.isRenderingTracker=new Ib(this.configProvider,this.getModality.bind(this)),this.isRenderingChangedSubscription=this.isRenderingTracker.on("onIsRenderingChanged",(g=>{this.setIsRendering(g)}))),this.overlayStats=new QC(this.configProvider.config.showStatsInCall,C,this)}getEndOfTheFreeze(){return this.freezeTracker?.getEndOfTheFreeze()}resetTimeToFirstFrameFlag(){this.isTimeToFirstFrameReported=!1}setIsRendering(g){this.currentIsRendering!==g&&(this.currentIsRendering=g,this.captureIsRenderingEvent(g))}updateStatsOverlay(g,f){this.overlayStats.setStats(g,f)}updateIsRenderingTracker(g){this.isRenderingTracker?.updateRenderingTracker(g)}subscribeVideoAsync(g,f){return this.timeToFirstFrameSinceSubscriptionStart=Date.now(),new Promise(((S,v)=>{this.modality=f?qt.MODALITY.sharing:qt.MODALITY.video,this.diagnostics&&(this.diagnostics.msi=g,this.diagnostics.modality=this.modality),this.trackElementSizeChange(),this.unsubscribe(),this.on("onVideoSizeChanged",((f,S)=>{if(this.modality===qt.MODALITY.video&&this.sessionDiagnostics?.registerResolutionChangeEvent({ts:Date.now(),msi:g,res:{width:f,height:S}}),this.isTimeToFirstFrameReported)return;if(-1===this.timeToFirstFrame){const g=Date.now();this.timeToFirstFrame=g-this.startTimeTTFF,this.timeToFirstFrameSinceSubscriptionStart=Date.now()-this.timeToFirstFrameSinceSubscriptionStart}const v=this.getTrackId();v&&(this.diagnostics.timeToFirstFrameSinceSubscriptionStart=this.timeToFirstFrameSinceSubscriptionStart,this.diagnostics.timeToFirstFrame=this.timeToFirstFrame,this.sizeTracker?.triggerVideoElementSizeChange(),this.event("onVideoStarted").raise(this.timeToFirstFrame,this.timeToFirstFrameSinceSubscriptionStart,v),this.isTimeToFirstFrameReported=!0)})),this.on("onVideoRendererStateChanged",(g=>{this.diagnostics.addStateChange(g)}));const C=this.subscriptionManager.subscribeVideo(this.modality,g);this.subscription=C,this.logger.safe.info(`subscribing renderer to type: ${C.modality} msi: ${C.msi}`),C.setOnMediaStreamChangedHandler((g=>{const f=this.getMediaStream();this.attachMediaStream(g),g&&(this.startTimeTTFF=Date.now());const v=this.getTrackId();v&&this.diagnostics&&(this.diagnostics.trackId=v),this.logger.safe.info(`subscribed renderer to type: ${C.modality} msi: ${C.msi} on stream #${g?g.id:"none"}`),g&&f!==g&&this.sizeTracker?.triggerVideoElementSizeChange(),S()})),C.setOnErrorHandler((f=>{this.logger.safe.error(`failed to subscribe renderer ${stringifyObject2(f)}`),"webRtcSession cleanup"===JSON.stringify(f)&&(this.logger.safe.info(`Retry to subscribe to video stream with msi: ${g}. Previous session was cleaned up`),this.subscriptionManager.streamChangedByMsi(g),S()),v(f)}))}))}dispose(){this.disposed?this.logger.safe.warn("renderer already disposed"):(this.disposed=!0,this.logger.safe.info("disposing"),this.unsubscribe(),this.captureIsRenderingEvent(!1),this.freezeTracker?.dispose(),this.sizeTracker?.dispose(),this.isRenderingChangedSubscription?.dispose(),this.overlayStats.dispose(),this.diagnostics?.dispose(),this.event("onRendererDisposed").raise(this),super.dispose())}getModality(){return this.modality}getMsi(){return this.subscription?.msi??-1}getLocalMsi(){return this.subscription?.localMsi}getCurrentResolution(){return this.resolution??{width:0,height:0}}unsubscribeNow(){this.subscription?.unsubscribe(),this.subscription=null}trackElementSizeChange(){const g=this.modality===qt.MODALITY.sharing,f=g?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMin:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMin,S=g?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMax:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMax;f&&S?(this.sizeTracker=new Ab(this.getVideoElement(),f,S,this.configProvider.config.enableDevicePixelRatio),this.sizeTracker.changed((()=>this.onSizeTrackerChanged()))):this.logger.safe.info("skipping video size tracking")}onSizeTrackerChanged(){this.resolution={width:this.sizeTracker.width,height:this.sizeTracker.height},this.logger.safe.info(`video renderer size changed to ${this.resolution.width}x${this.resolution.height}`),this.diagnostics&&(this.diagnostics.rendererSize=this.resolution),this.event("onRendererSizeChanged").raise(this,this.resolution)}unsubscribe(){this.subscription?.dispose(),this.subscription=null}captureIsRenderingEvent(g){this.diagnostics&&(this.diagnostics.isRendering=g),this.event("onIsRenderingChanged").raise(g,this.getModality(),this.getTrackId())}},Rb=class{constructor(g,f,S,v,C,_){this.logger=g,this.configProvider=f,this.statsGatherer=S,this.sessionDiagnostics=v,this.remoteVideoResolutionManager=C,this.domOverrides=_,this.remoteRendererSubscriptions=new Map,this.diagnostics=v?.newRemoteVideoManagerDiagnostics()}createRenderer(g,f,S){const v=new Pb((S??this.logger).createChild("videorenderer"),this.configProvider,this.diagnostics?.newRendererDiagnostics(),f,g,this.sessionDiagnostics);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(v.getVideoElement()),this.addRenderer(v),v}moveRenderers(g){this.renderers.forEach((f=>{f.resetTimeToFirstFrameFlag(),g.addRenderer(f),this.removeRenderer(f)}))}getMaxAllowedVideoFS(){return this.remoteVideoResolutionManager.getMaxAllowedVideoFS()}dispose(){this.renderers.forEach((g=>g.resetTimeToFirstFrameFlag())),this.renderers.forEach((g=>{const f=g.getTrackId(),S=g.getEndOfTheFreeze();this.statsGatherer.setFreezeDuration(S,f)})),this.remoteRendererSubscriptions.forEach(((g,f)=>{f.dispose(),g.forEach((g=>g.dispose()))})),this.remoteRendererSubscriptions.clear(),this.remoteVideoResolutionManager.clearRenderers()}processStatsReport(g){this.configProvider.config.isRenderingBasedOnRawStatistics&&this.onDiagnosticUpdated(g),this.updateOverlayStats(g)}processLegacyStats(g){this.configProvider.config.isRenderingBasedOnRawStatistics||this.renderers.forEach((f=>{const S=f.getTrackId();if(g.remoteVideoStreams[S]){const v=g.remoteVideoStreams[S].isRendering;void 0!==v&&f.setIsRendering(v)}}))}playVideo(){this.renderers.forEach((g=>g.playVideo()))}get renderers(){return Array.from(this.remoteRendererSubscriptions,(([g])=>g))}addRenderer(g){this.remoteRendererSubscriptions.set(g,this.subscribeOnEvents(g)),this.logger.safe.info("Added renderer to manager"),this.remoteVideoResolutionManager.addRenderer(g)}generateVideoRecvStats(g){const f=new Map,processRecvStats=g=>{g?.forEach((g=>{const S=g.track?.trackIdentifier??g.inboundRTP.trackIdentifier;f.set(S,g)}))};return processRecvStats(g.sharing?.recv),processRecvStats(g.video?.recv),f}updateOverlayStats(g){const f=this.generateVideoRecvStats(g);this.renderers.forEach((S=>{const v=S.getTrackId();f.has(v)&&g.audio?.recv?.length&&S.updateStatsOverlay(f.get(v),g.audio.recv[0])}))}onDiagnosticUpdated(g){const f=[...g.video?.recv??[],...g.sharing?.recv??[]];if(f.length){const g=new Map;f.forEach((f=>{g.set(f.track?.trackIdentifier,f)})),this.renderers.forEach((f=>{const S=f.getTrackId();g.has(S)&&f.updateIsRenderingTracker(g.get(S))}))}}subscribeOnEvents(g){return[g.on("onRendererDisposed",(g=>this.onRendererDisposed(g))),g.on("onVideoStarted",((g,f,S)=>this.onVideoStarted(g,f,S))),g.on("onFreezeEnded",(f=>{const S=g.getTrackId();this.statsGatherer.setFreezeDuration(f,S)})),g.on("onIsRenderingChanged",((g,f,S)=>this.statsGatherer.setIsRendering(g,f,S)))]}onRendererDisposed(g){this.logger.safe.debug("Renderer removed from manager"),this.removeRenderer(g),this.domOverrides.onMediaElementRemoved&&this.domOverrides.onMediaElementRemoved(g.getVideoElement())}removeRenderer(g){this.remoteRendererSubscriptions.get(g).forEach((g=>g.dispose())),this.remoteRendererSubscriptions.delete(g),this.remoteVideoResolutionManager.removeRenderer(g)}onVideoStarted(g,f,S){this.statsGatherer.setTimeToFirstFrame(g,f,S)}},Mb=class extends Ht{constructor(g,f,S){super(),this.configProvider=f,this.callDeviceManager=S,this.lastFramerateInput=-1,this.trackInfo=[],this.timeoutId=null,this.logger=g.createChild("localStreamWatcher"),this.callDeviceManagerSub=S.on("onSelectedVirtualDevicesChanged",(()=>{this.logger.info("VirtualDevice changed, updating subscriptions"),this.handleDeviceManagerChange()}))}get effectsManager(){return this.callDeviceManager.getDeviceManager("Video").effectsManager}startWatching(g,f){(this.configProvider.config.videoCaptureFreezeTimeout||f)&&(this.trackInfo=g,this.performanceMonitor=f,this.configProvider.config.videoCaptureFreezeTimeout&&(this.videoEffectManagerSubscription||(this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(g=>this.onVideoFreezeDetected(g))))))}stopWatching(){this.trackInfo=[],this.videoEffectManagerSubscription?.dispose(),this.videoEffectManagerSubscription=null,this.performanceMonitor=void 0,0!==this.lastFramerateInput||this.timeoutId||this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")),this.disposeTimer(),this.lastFramerateInput=-1}dispose(g){this.callDeviceManagerSub?.dispose(),super.dispose(g),this.stopWatching()}onDiagnosticUpdated(g){if(!this.trackInfo.length||!g.video?.send?.length)return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Updating local video stream watcher");const f=g.video?.send[0],S=[];let v,C=0;[f,...f.altLayouts??[]].forEach((g=>{const f=g.mediaSource,_=f?.framesPerSecond??0;this.trackInfo.some((g=>g.trackId===f.trackIdentifier))&&((!v||C<_)&&(v=f,C=_),this.performanceMonitor&&S.push(g.outboundRTP))})),this.performanceMonitor?.monitor(S),this.configProvider.config.videoCaptureFreezeTimeout&&(v?C!==this.lastFramerateInput&&(0===C?this.scheduleCaptureFreezeStart(v.trackIdentifier,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${v.trackIdentifier}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=C):this.logger.safe.warn("WebRTC Stats for send video not found"))}onStatisticsChanged(g){if(!this.trackInfo.length||!this.configProvider.config.videoCaptureFreezeTimeout)return;let f;Object.keys(g.localVideoStreams).forEach((S=>{const v=g.localVideoStreams[S];this.trackInfo.some((g=>g.trackId===v.trackId))&&(!f||f.frameRateInput<v.frameRateInput)&&(f=v)})),f?f.frameRateInput!==this.lastFramerateInput&&(0===f.frameRateInput?this.scheduleCaptureFreezeStart(f.trackId,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${f.trackId}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=f.frameRateInput):this.logger.safe.warn("WebRTC Stats for send video not found")}onVideoFreezeDetected(g){this.logger.info(`onVideoCaptureFreeze, webcam freeze detected trackId: ${g}`),this.event("onVideoCaptureFreeze").raise(!1,!0)}scheduleCaptureFreezeStart(g,f){this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,this.logger.safe.info(`onVideoCaptureFreeze start for trackId: ${g} (isWebcamStream: ${f})`),this.event("onVideoCaptureFreeze").raise(!0,f)}),this.configProvider.config.videoCaptureFreezeTimeout)}disposeTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handleDeviceManagerChange(){this.videoEffectManagerSubscription?.dispose(),this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(g=>this.onVideoFreezeDetected(g)))}},wb=class{constructor(g){this.queue=[],this.logger=g}cleanup(){this.queue.forEach((g=>{g.reject({notSent:g.tones})})),this.queue=[]}waitForNotification(g){return g?(this.logger.unsafe.info("sending dtmf tones: ",g),new Promise(((f,S)=>{this.queue.push({tones:g,resolve:f,reject:S})}))):Promise.reject(new Error("invalid input"))}toneSent(g){this.queue[0]&&(g===this.queue[0].tones[0]?(this.queue[0].tones=this.queue[0].tones.substr(1),""===this.queue[0].tones&&(this.queue[0].resolve(),this.queue.shift())):(this.queue[0].reject(new Error(`sent tone does not match: expected '${this.queue[0].tones[0]}' got '${g}'`)),this.queue.shift(),this.toneSent(g)))}},Ob=class{constructor(g){this.webRtcSender=null,this.configProvider=g.configProvider,this.queue=new wb(g.logger)}sendDtmf(g,f){return g?.getSenders?(this.syncSender(g),this.webRtcSender?(this.webRtcSender.ontonechange=this.onToneChange.bind(this),this.webRtcSender.insertDTMF(this.webRtcSender.toneBuffer+f,this.configProvider.config.dtmf.toneDuration,this.configProvider.config.dtmf.toneGap),this.queue.waitForNotification(f)):Promise.reject(new Error("not available"))):Promise.reject(new Error("bad peerConnection"))}canSendDtmf(g){return!!g?.getSenders&&(this.syncSender(g),!!this.webRtcSender&&this.webRtcSender.canInsertDTMF)}dispose(){this.queue.cleanup()}syncSender(g){const f=g.getSenders().filter((g=>g.track&&"audio"===g.track.kind)).filter((g=>g.dtmf?.canInsertDTMF))[0];this.webRtcSender&&f&&f.dtmf!==this.webRtcSender&&(this.webRtcSender.ontonechange=null,this.queue.cleanup()),this.webRtcSender=f?f.dtmf:null}onToneChange(g){g.tone&&this.queue.toneSent(g.tone)}},Db={build:g=>new Ob(g)},Nb=class extends Ht{constructor(g,f,S,v,C){super(S),this.pc=g,this.cryptoMethod=f,this.logger=S,this.configProvider=v,this.diagnostics=C,this.iceConnectionStateInternal="new",this.isWaitingAcceptProvisionalInternal=!1,this.state="new",this.toBeCalledOnConnected=[],this.toBeCalledOnProvisionalConnected=[],this.handleSignalingStateChange=()=>{const g=this.pc.signalingState,f=this.signalingStateInternal;if(this.logger.safe.info(`RTCPeerConnection onsignalingstatechange signalingState: ${this.signalingStateInternal} -> ${g}`),this.signalingStateInternal=g,this.diagnostics.signalingState=g,this.event("signalingStateChanged").raise(this.signalingStateInternal,f,generateCauseId()),!this.configProvider.config.useDtlsTrasportConnectionCheck||this.transport||1!==this.cryptoMethod||this.hasPcConnectionState)return;const S=this.pc.getReceivers().find((g=>!!g.transport));this.transport=S?.transport,this.transport&&(this.transport.onstatechange=this.handleDtlsTransportStateChange)},this.handleIceConnectionStateChange=()=>{const g=this.pc.iceConnectionState;this.logger.safe.info(`RTCPeerConnection oniceconnectionstatechange iceConnectionState: ${g} pc.signalingState: ${this.pc.signalingState}`),this.iceConnectionStateInternal=g,this.diagnostics.iceConnectionState=g,this.event("iceConnectionStateChanged").raise(this.iceConnectionStateInternal,generateCauseId()),this.shouldRaise(0)&&this.updateState(g)},this.handleConnectionStateChange=()=>{const g=this.pc.connectionState;this.logger.safe.info(`RTCPeerConnection onconnectionStatechange connectionState: ${g} pc.signalingState: ${this.pc.signalingState}`),this.connectionStateInternal=g,this.diagnostics.connectionState=g,this.event("connectionStateChanged").raise(this.connectionStateInternal,generateCauseId()),this.shouldRaise(1)&&this.updateState(g)},this.handleDtlsTransportStateChange=()=>{const g=this.transport.state;this.logger.safe.info(`RTCDtlsTransport onstatechange state: ${g} pc.signalingState: ${this.pc.signalingState}`),this.dtlsStateInternal=g,this.diagnostics.dtlsTransportState=g,this.event("dtlsTransportStateChanged").raise(this.dtlsStateInternal,generateCauseId()),this.shouldRaise(3)&&this.updateState(g)},this.iceConnectionStateInternal=this.pc.iceConnectionState,this.connectionStateInternal=this.pc.connectionState,this.signalingStateInternal=this.pc.signalingState,this.pc.oniceconnectionstatechange=this.handleIceConnectionStateChange,this.pc.onsignalingstatechange=this.handleSignalingStateChange,this.logger.safe.debug(`ctor ctryptoMethod ${1===this.cryptoMethod?"dtls":"sdes"}, hasPcConnectionState ${this.hasPcConnectionState}`),1===this.cryptoMethod&&this.hasPcConnectionState&&(this.pc.onconnectionstatechange=this.handleConnectionStateChange),this.diagnostics.hasConnectionState=this.hasPcConnectionState}get hasPcConnectionState(){return"connectionState"in this.pc&&this.configProvider.config.useConnectionState}get isWaitingAcceptProvisional(){return this.isWaitingAcceptProvisionalInternal}set isWaitingAcceptProvisional(g){this.isWaitingAcceptProvisionalInternal!==g&&(this.logger.safe.debug(`isProvisional set ${this.isWaitingAcceptProvisionalInternal} -> ${g}`),this.isWaitingAcceptProvisionalInternal=g,this.diagnostics.provisional=g,this.updateState(this.state,!1))}get iceConnectionState(){return this.iceConnectionStateInternal}get signalingState(){return this.signalingStateInternal}get isIceConnected(){return"connected"===this.iceConnectionStateInternal||"completed"===this.iceConnectionStateInternal}get isTransportConnected(){return"connected"===this.state||"completed"===this.state}get isFailed(){return this.configProvider.config.transportStateFailedFix?"failed"===this.state:"failed"===this.state||"closed"===this.state}get isConnected(){return this.isTransportConnected&&"closed"!==this.signalingStateInternal}doOnConnected(g,f="unknown",S=!1,v=!0){return this.diagnostics.scheduleDoOnConnected(g,f,S,v),v&&this.isConnected&&(S||!this.isWaitingAcceptProvisionalInternal)?(this.logger.safe.info(`Running callback immediately ${f}`),this.diagnostics.runDoOnConnected(g,!0),void g()):S?(this.logger.safe.info(`Queuing provisional connected callback '${f}'`),void this.toBeCalledOnProvisionalConnected.push(g)):(this.logger.safe.info(`Queuing connected callback '${f}'`),void this.toBeCalledOnConnected.push(g))}dispose(){this.pc.oniceconnectionstatechange=void 0,this.pc.onsignalingstatechange=void 0,this.transport&&(this.transport.onstatechange=void 0),this.pc.onconnectionstatechange&&(this.pc.onconnectionstatechange=void 0),this.diagnostics.dispose()}updateState(g,f=!0){if(f&&(this.statePrevious=this.state),this.state=g,this.event("stateChanged").raise(this.state,this.statePrevious,generateCauseId()),this.diagnostics.transportState=g,this.isConnected){if(!this.isWaitingAcceptProvisionalInternal&&this.toBeCalledOnConnected.length)for(this.logger.safe.info(`Running ${this.toBeCalledOnConnected.length} callbacks on connected`);this.toBeCalledOnConnected.length;){const g=this.toBeCalledOnConnected.shift();this.diagnostics.runDoOnConnected(g),g()}if(this.toBeCalledOnProvisionalConnected.length)for(this.logger.safe.info(`Running ${this.toBeCalledOnProvisionalConnected.length} callbacks on provisional connected`);this.toBeCalledOnProvisionalConnected.length;){const g=this.toBeCalledOnProvisionalConnected.shift();this.diagnostics.runDoOnConnected(g),g()}}}shouldRaise(g){switch(g){case 3:if(1!==this.cryptoMethod)throw new Error(`DTLS transport is used with cryptoMethod=${this.cryptoMethod}`);return!this.configProvider.config.ignoreClosedDtlsTransportState||"closed"!==this.transport.state;case 1:return 1===this.cryptoMethod&&!this.transport;case 0:return!(!this.configProvider.config.ignoreClosedDtlsTransportState||!this.transport||"closed"!==this.pc.iceConnectionState)||0===this.cryptoMethod||!this.transport&&!this.hasPcConnectionState||this.transport&&"disconnected"===this.pc.iceConnectionState||"connected"===this.transport?.state&&"connected"===this.pc.iceConnectionState;default:return this.logger.safe.error(`unknown StateMethod=${g}`),!1}}},kb=class{constructor(g,f,S,v,C,_){this.logger=g,this.emulator=f,this.qualityManager=S,this.diagnostics=v,this.configProvider=C,this.statsGatherer=_,this.previousSequenceNumber=new Map,this.modifiers=this.configProvider.mediaConfig.simulcastSessionEnabled?[]:[new OT(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider)]}dispose(){this.cleanupDevToolsInjector(),this.modifiers&&(this.modifiers.forEach((g=>g.dispose())),this.modifiers=null),this.emulator=null,this.logger=this.logger.createChild("DISPOSED")}handleMessage(g){const f=g.controlInfo[0].sourceId;if(this.previousSequenceNumber.has(f)&&g.sequenceNumber<this.previousSequenceNumber.get(f))return this.statsGatherer.addVideoControlMessage(!0),this.diagnostics?.addVideoControlMessage(!0),this.logger.safe.info(`Discarded old media stream control message for sourceId ${f}: (${JSON.stringify(g)})`),Promise.resolve();this.previousSequenceNumber.set(f,g.sequenceNumber),this.statsGatherer.addVideoControlMessage(),this.diagnostics?.addVideoControlMessage(),this.configProvider.config.enableDevtoolsAPI&&this.injectFmtpHandler(g);const S={controlVideoStreaming:g};return this.configureResolution(S),this.modifiers.length?(this.modifiers.forEach((g=>g.setVideoControlMessage(S))),this.emulator.renegotiate(this.modifiers)):Promise.resolve()}configureResolution(g){this.logger.safe.info(`Signaling FMTP: ${JSON.stringify(g.controlVideoStreaming)}`);const f=String(g.controlVideoStreaming.sequenceNumber),S=g.controlVideoStreaming.controlInfo[0].fmtParamsList,v=g.controlVideoStreaming.controlInfo[0].fmtParams,C=S&&this.configProvider.config.webrtcFmtParamListSupported?this.parseFmtParamsList(S):[this.parseFmtParams(v)],_=+g.controlVideoStreaming.controlInfo[0].sourceId,T=[{causeId:f,isSimulcast:C.some((g=>void 0!==g.rid))||C.length>1,capabilities:C,sourceId:_}];this.qualityManager.setMaxCapabilities(T)}parseFmtParamsList(g){return g.map((g=>this.parseFmtParams(g)))}parseFmtParams(g){const f=new Zy(g);return{maxFs:+f.get(qt.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+f.get(qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+f.get(qt.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+f.get(qt.VIDEO_CAPABILITIES.MAX_BR_PATH),ssrc:+f.get(qt.VIDEO_CAPABILITIES.SSRC_PATH),rid:f.get(qt.VIDEO_CAPABILITIES.RID_PATH),keyframe:this.shouldGenerateKeyFrame(f),vlaDebug:f.get(qt.VIDEO_CAPABILITIES.VLA_DEBUG)}}shouldGenerateKeyFrame(g){return g.get(qt.VIDEO_CAPABILITIES.KEYFRAME_PATH)?!!+g.get(qt.VIDEO_CAPABILITIES.KEYFRAME_PATH):this.configProvider.config.webrtcAllowRestoreKeyframe}injectFmtpHandler(g){const f=window;f?.webMA&&(f.webMA.fmtp||(f.webMA.fmtp={handleMessage:this.handleMessage.bind(this)}),f.webMA.fmtp.lastFmtp=g)}cleanupDevToolsInjector(){const g=window;g?.webMA&&delete g.webMA.fmtp}},Lb=(g=>(g[g.ThreeStreamSimulcast=0]="ThreeStreamSimulcast",g[g.HardwareEncoder=1]="HardwareEncoder",g[g.Encode1080P=2]="Encode1080P",g[g.BroadcastMode=3]="BroadcastMode",g))(Lb||{}),Fb=class extends Ht{constructor(g,f){super(f),this.mediaType=g,this.logger=f,this.features={}}notify(){super.raiseChanged()}find(g){var f;return(f=this.features)[g]??(f[g]={})}set(g,f,S){const v=this.find(g);let C=!1;return void 0!==f&&v.server!==f&&(this.logger.safe.info(`Server support for [${this.mediaType}][${Lb[g]}] changed from ${v.server} to ${f}`),v.server=f,C=!0),void 0!==S&&v.client!==S&&(this.logger.safe.info(`Client support for [${this.mediaType}][${Lb[g]}] changed from ${v.client} to ${S}`),v.client=S,C=!0),C}toggleServer(g,f){return!!this.set(g,f,void 0)&&(this.notify(),!0)}toggleClient(g,f){return!!this.set(g,void 0,f)&&(this.notify(),!0)}toggle(g,f){return!!this.set(g,f,f)&&(this.notify(),!0)}hasAnySupport(g){const f=this.find(g);return!0===f.client||!0===f.server}hasFullSupport(g){const f=this.find(g);return!0===f.client&&!0===f.server}hasClientSupport(g){return!0===this.find(g).client}hasServerSupport(g){return!0===this.find(g).server}},xb=class extends Ht{constructor(g){super(g),this.logger=g,this.modalities={Video:new Fb("Video",this.logger),ScreenShare:new Fb("ScreenShare",this.logger)},this.blocked=new Set;for(const g of Object.keys(this.modalities))this.modalities[g].changed((()=>{this.notify(this.modalities[g],!1)}))}notify(g,f){this.blocked.has(g.mediaType)&&!0!==f||(this.blocked.add(g.mediaType),this.logger.safe.info(`Notify: ${g.mediaType}`),this.event("onVideoFeaturesChanged").raise(g),this.blocked.delete(g.mediaType))}manageFeatureSupport(g){for(const g of Object.values(this.modalities))this.blocked.add(g.mediaType);g();for(const g of[...this.blocked])this.notify(this.modalities[g],!0)}get(g){if(!this.modalities[g])throw this.logger.safe.error(`Unsupported media type: ${g}`),new Error(`Unsupported media type: ${g}`);return this.modalities[g]}},Ub=class _MediaMessageGenerator2{constructor(g){this.configProvider=g}getVideoControlMessage(g,f,S){const v={controlVideoStreaming:{sequenceNumber:++_MediaMessageGenerator2.sequence,globalTimeStamp:(new Date).toString(),controlInfo:[{control:"start",sourceId:f,streamMsid:g}]}};return S&&(v.controlVideoStreaming.controlInfo[0].fmtParams=fmtParamsToString(S)),v}getSourceRequestMessage(g,f,S,v){if(!S)throw new Error("Failed to construct SourceRequestMessage, missing fmtParams");const C={sourceId:f,streamMsid:g,fmtParams:S};return C.subStreamIndex=v,{type:"sr",controlVideoStreaming:{sequenceNumber:++_MediaMessageGenerator2.sequence,controlInfo:C}}}getSignalingSourceRequestMessage(g,f,S,v,C){if(!v)throw new Error("Failed to construct SourceRequestMessage, missing fmtParams");const _={sourceId:f,streamMsid:g,fmtParams:v};return _.subStreamIndex=C,{applyChannelParameters:{multiChannelParameter:{mids:[S],mediaParameter:JSON.stringify({controlVideoStreaming:{sequenceNumber:++_MediaMessageGenerator2.sequence,controlInfo:_}})}}}}getBandwidthInfoMessage(g){return{type:"ssbwe",BwMessage:g}}getMaxVideoSendCapabilitiesMessage(g){const{streamMIDs:f,capabilities:S,useMax:v,sendMaxFs:C,sendMaxMbps:_}=g;let T=ceilToMacroblock(S.maxWidth),I=ceilToMacroblock(S.maxHeight);v&&(T=I=Math.max(T,I));const b={[qt.VIDEO_CAPABILITIES.MAX_FPS_PATH]:S.maxFps,[qt.VIDEO_CAPABILITIES.MAX_WIDTH]:T,[qt.VIDEO_CAPABILITIES.MAX_HEIGHT]:I};return C&&(b[qt.VIDEO_CAPABILITIES.MAX_FS_PATH]=S.maxFs),_&&(b[qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH]=S.maxMbps),{applyChannelParameters:{multiChannelParameter:{mids:f,mediaParameter:JSON.stringify({maxVideoSendCapabilities:{caps:b}})}}}}getMaxVideoSendCapabilitiesContent(g,f,S,v){const C={};if(S){let g=ceilToMacroblock(S.maxWidth),f=ceilToMacroblock(S.maxHeight);this.configProvider.config.maxSendVideoCapabilities.useMaximumWidthHeight&&(g=f=Math.max(g,f)),C[qt.VIDEO_CAPABILITIES.MAX_WIDTH]=g,C[qt.VIDEO_CAPABILITIES.MAX_HEIGHT]=f,C[qt.VIDEO_CAPABILITIES.MAX_FPS_PATH]=S.maxFps,this.configProvider.config.maxSendVideoCapabilities.sendMaxFs&&(C[qt.VIDEO_CAPABILITIES.MAX_FS_PATH]=S.maxFs),this.configProvider.config.maxSendVideoCapabilities.sendMaxMbps&&(C[qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH]=S.maxMbps)}else v&&[qt.VIDEO_CAPABILITIES.MAX_WIDTH,qt.VIDEO_CAPABILITIES.MAX_HEIGHT,qt.VIDEO_CAPABILITIES.MAX_FPS_PATH,qt.VIDEO_CAPABILITIES.MAX_FS_PATH,qt.VIDEO_CAPABILITIES.MAX_MBPS_PATH].forEach((g=>{v[g]&&(C[g]=v[g])}));const _=g.getSimulcastContext();let T,I,b,A;if(_&&_.config.layerScaleFactors.length>2&&(T=_.config.layerScaleFactors.length,I=_.config.layerScaleFactors.length,f.hasClientSupport(0)||(I=2),this.configProvider.config.minFrameSizeForThreeStreamSimulcast&&S&&S.maxFs<this.configProvider.config.minFrameSizeForThreeStreamSimulcast&&(I=2)),void 0!==T&&(C[qt.VIDEO_CAPABILITIES.MAX_STREAMS]=T),void 0!==I&&(C[qt.VIDEO_CAPABILITIES.MAX_LAYERS]=I),f.hasClientSupport(3)&&this.configProvider.config.broadcastMode?.prioritizeLayoutOnServer){const g=this.configProvider.config.broadcastMode;g.priorityLayoutMinFS&&g.priorityLayoutMinFPS&&(A=g.priorityLayoutMinFS,A*=g.priorityLayoutMinFPS),g.priorityLayoutMinBitrate&&(b=g.priorityLayoutMinBitrate)}return b&&(C[qt.VIDEO_CAPABILITIES.PRIORITY_LAYOUT_MIN_BITRATE]=b),A&&(C[qt.VIDEO_CAPABILITIES.PRIORITY_LAYOUT_MIN_MBPR]=A),f.hasClientSupport(1)&&this.configProvider.config.preferredHardwareLadderType&&(C[qt.VIDEO_CAPABILITIES.LADDER_TYPE]=this.configProvider.config.preferredHardwareLadderType),C}getMultiChannelParametersMessage(g,f){return{applyChannelParameters:{multiChannelParameter:{mids:g,mediaParameter:JSON.stringify(f)}}}}};Ub.sequence=0;var Vb=Ub,Bb=class{constructor(g,f,S,v){this.logger=g,this.configProvider=f,this.sender=S,this.mediaControlPlane=v,this.messageGenerator=new Vb(this.configProvider),this.lastVideoSendMaxCapabilities={}}sendSourceRequest(g,f,S,v,C){if(this.configProvider.config.useApplyChannelParametersForSourceRequests){const _=this.messageGenerator.getSourceRequestMessage(g,f,v,C),T=this.messageGenerator.getSignalingSourceRequestMessage(g,f,S,v,C);return this.sendMessage("ApplyChannelParametersSourceRequest",_,T)}const _=this.messageGenerator.getVideoControlMessage(g,f,v?.[0]);return this.sendMessage("ControlVideoStreaming",_)}sendMaxVideoSendCapabilities(g,f){const S=this.messageGenerator.getMaxVideoSendCapabilitiesMessage({streamMIDs:g,capabilities:f,sendMaxFs:this.configProvider.config.maxSendVideoCapabilities.sendMaxFs,sendMaxMbps:this.configProvider.config.maxSendVideoCapabilities.sendMaxMbps,useMax:this.configProvider.config.maxSendVideoCapabilities.useMaximumWidthHeight});return this.sendMessage("ApplyChannelParametersVideoCapabilities",S)}async sendBandwidthInfo(g){const f=this.messageGenerator.getBandwidthInfoMessage(g);return this.mediaControlPlane?.sendMsg(f)}sendMaxVideoSendCapabilitiesV2(g,f,S){if(void 0===this.lastVideoSendMaxCapabilities[g.getMid()]){if(!S)return this.logger.safe.info("Skip sending empty max-capabilities message"),Promise.resolve();this.lastVideoSendMaxCapabilities[g.getMid()]={}}const v=this.messageGenerator.getMaxVideoSendCapabilitiesContent(g,f,S,this.lastVideoSendMaxCapabilities[g.getMid()]);if(S||!deepEqual(this.lastVideoSendMaxCapabilities[g.getMid()],v)){this.lastVideoSendMaxCapabilities[g.getMid()]=v;const f=this.messageGenerator.getMultiChannelParametersMessage([g.getMid()],{maxVideoSendCapabilities:{caps:v}});return this.sendMessage("ApplyChannelParametersVideoCapabilities",f)}return this.logger.safe.info("Skip sending duplicate max-capabilties message"),Promise.resolve()}async sendMessage(g,f,S){let v;return"ApplyChannelParametersSourceRequest"===g&&(v=f.controlVideoStreaming.sequenceNumber),this.logger.safe.info(`sending video control message: ${JSON.stringify(f)}`),this.sender.send(g,f,v,S)}},Hb=0,$b=class _WebRtcSession{constructor(g,f,S){this.context=g,this.callId=f,this.callback=S,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc-"+ ++Hb),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.webrtcAdapter=db.build({global:this.context.maContext,configProvider:this.configProvider}),this.iceHostCandidateOnly=this.multiParty&&getFrom("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new gb({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:!1}),this.sessionDescription=V_.build({sdpTransform:new this.webrtcAdapter.SdpTransform(this.context),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:this.getStreamTransformConfiguration()}),this.allowedMediaContentType=getFrom("webrtcAllowedMediaContentType",this.context.config,this.configProvider.config).concat(),this.receiveStreamCollection=new MT({streamAdded:g=>this.streamAdded(g),streamRemoved:g=>this.streamRemoved(g)}),this.stats=new JI(this.logger.createChild("stats"),this.configProvider,void 0,this.mediaManager,this.multiParty),this.maxResolution=this.multiParty?ei.Send.getResolutionByFs(this.configProvider.config.webrtcMultipartyMaxScalingFs):ei.Send.getResolutionByFs(this.configProvider.config.webrtcMaxScalingFs),this.qualityManager=new _b(this.logger.createChild("qm"),{scalingEnabled:this.configProvider.config.webrtcVideoScaling,cooldownTimeout:this.configProvider.config.webrtcResolutionManagerCooldownTimeout,retryDelay:this.configProvider.config.webrtcResolutionManagerRetryDelay,maxResolution:this.maxResolution,customBwEstimationEnabled:!0},{onReceiveCapabilitiesChanged:(g,f,S)=>this.applyCapabilitiesForModality(g,f,S)},this.stats,void 0,this.configProvider),this.localVideoStreamWatcher=new Mb(this.logger,this.configProvider,this.context.callDeviceManager),this.activeSpeakerManager=new RT(this.callback.onContributingSourcesChanged,this.callback.onDominantSpeakerChanged,this.logger.createChild("ActiveSpeakerManager")),this.senders={},this.negotiationQueue=new zC(this.logger),this.negotiationEmulator=new mb(this.logger.createChild("negotiationEmulator"),this.webrtcAdapter.RTCSessionDescription,this.sessionDescription,this.negotiationQueue,this.mediaManager),this.streamConfigurationHandler=new kb(this.logger,this.negotiationEmulator,this.qualityManager,null,this.configProvider,this.stats),this.mediaMessageController=new Bb(this.logger,this.configProvider,{send:this.context.sendWebRtcMediaNotificationAsyncCallback}),this.toBeCalledAfterConnected=[],this.iceTransportPolicy=this.configProvider.config.iceTransportPolicyForced||this.context.config.iceTransportPolicy||qt.ICE_TRANSPORT_POLICY.all,this.isMuteHold=!1,this.peerConnection=null,this.mediaStreams=new Map,this.doAudioMute=this.context.config.muted,this.iceCandidatesDeferred=new dt,this.relayCandidateGathered=!1,this.iceCandidatesTimer=null,this.triggerRenegotiationFlag=!1,this.canTriggerRenegotiation=!0,this.noIceCandidates=!1,this.noRelayIceCandidates=!1,this.forceMediaStreamUpdate=!1,this.negotiatedModalities={},this.disabledModalities={},this.iceDisconnectedTimer=null,this.statisticsReport=Promise.resolve({}),this.terminated=!1,this.initiator=!1,this.streamsChangedListener=null,this.dtmfSender=Db.build({logger:this.logger,configProvider:this.configProvider}),this.mediaContentType=getFrom("webrtcMediaContentType",this.context.config,this.configProvider.config),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new qy(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:g=>this.onStreamsChanged(g)}),this.remoteVideoResolutionManager=new Tb(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.stats),this.remoteVideoManager=new Rb(this.logger.createChild("RemoteVideoManager"),this.configProvider,this.stats,void 0,this.remoteVideoResolutionManager,this.context.maContext.domOverrides),this.hwSilent=!1,this.configuredModalitiesPromise=Promise.resolve(),this.negotiationCompletedPromise=new dt,this.ssrcGenerator=new hE,this.ssrcs={Audio:this.getSsrcRangeForMediaType("Audio"),Video:this.getSsrcRangeForMediaType("Video"),ScreenShare:this.getSsrcRangeForMediaType("ScreenShare")},this.forceKeyFramePromise=null,this.transportStateProvider={isFailed:this.isFailed.bind(this),isConnected:this.isConnected.bind(this)},this.ufdManager=g.getUfdManager(),this.stats.on("onStatisticsChanged",(g=>{this.remoteVideoManager.processLegacyStats(g),this.localVideoStreamWatcher?.onStatisticsChanged(g),this.updateQualityLevels(g)})),this.negotiationCompletedPromise.promise.catch((()=>{})),this.negotiationCompletedPromise.reject("placeholder"),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((g,f,S)=>this.requestSource(g,f,S))),this.setSubsForSubscriptionManager(),this.localVideoStreamWatcher.on("onVideoCaptureFreeze",(g=>{this.isConnected()&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",g?"Bad":"Good","Video")})),this.configProvider.mediaConfig.maxBandwidthInKbps&&this.stats.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.createAudioRenderer(),this.configProvider.config.webrtcVideoScaling&&this.onOptimalVideoReceiversCountChanged(this.configProvider.config.nonEstimatedDefaultVideoReceiversCount)}get audioStream(){return this.mediaStreams.get("Audio")}get videoStream(){return this.mediaStreams.get("Video")}get displayStream(){return this.mediaStreams.get("ScreenShare")}useNullAudioStreamClient(){}getIncomingRawAudioStream(){return null}configureSpatialAudio(g,f){}setParticipantSpatialAudioPositions(g,f){}getAcceptedTypes(){return this.allowedMediaContentType}clone(g=!1){const f=shallowClone(this.context);f.config=shallowClone(this.context.config),f.config.webrtcMediaContentType=this.mediaContentType,f.config.webrtcAllowedMediaContentType=this.allowedMediaContentType,g?f.config.isConference=!0:(f.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(f.config.webrtcIceGatheringTimeoutIncreased=!0));const S=new _WebRtcSession(f,this.callId,this.callback);return this.relayManagerProvider&&(S.relayManagerProvider=this.relayManagerProvider),S.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,S}setInternals(g){g.subscriptionManager&&(this.subscriptionManager&&this.subscriptionManager.dispose(),this.subscriptionManager=g.subscriptionManager,this.subscriptionManager.setStreamProvider({getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:g=>this.onStreamsChanged(g)}),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),g.audioRenderer&&(g.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=g.audioRenderer),g.remoteVideoManager&&g.remoteVideoManager.moveRenderers(this.remoteVideoManager)}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(g=>this.stats.setSubscribedTrackIds(g))),this.subscriptionManager.on("onTrackSsrcChanged",(g=>this.stats.setSubscribedTrackSsrc(g))),this.subscriptionManager.on("onSubscriptionChanged",((g,f,S,v,C,_)=>this.stats.addSubscriptionEvent(g,f,S,v,null,C,_))),this.subscriptionManager.on("onSubscriptionFailed",((g,f,S,v,C)=>this.stats.addSubscriptionEvent(g,f,S,v,C)))]}move(g,f){g.setInternals({subscriptionManager:this.subscriptionManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager}),g.muteHold(this.isMuteHold,f),this.doAudioMute?g.muteInputAsync(f):g.unmuteInputAsync(f),this.subscriptionManager=null,this.audioRenderer=null,this.callbacks.onTerminated=null}setMute(g,f,S){this.logger.safe.info(`[${S}] call setMuteAsync with mute state ${f}, audio stream exists: ${!!this.audioStream}`),"Audio"===g&&this.audioStream?this.audioStream.setMuted(f,S):"Video"===g&&this.videoStream?this.videoStream.setMuted(f,S):"ScreenShare"===g&&this.displayStream&&this.displayStream.setMuted(f,S),this.updateQualityLevels(this.stats.getLastStatistics())}setCallConstraints(g,f){return Promise.reject(new Error("Not supported"))}configureModalitiesAsync(g,f){const S=this.configuredModalitiesPromise.then((()=>{if(!g||!g.audio&&!g.video&&!g.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(g)}`);const S=!this.configuredModalities||!areNegotiatedDirectionsFulfilled(g,this.negotiatedModalities);return this.configuredModalities=g,this.logger.safe.info(`[${f}] configure modalities`,`audio: ${g.audio}`,`video: ${g.video}`,`sharing: ${g.sharing}`,`peerconnection: ${!!this.peerConnection}`,`pc.signalingState: ${this.peerConnection?this.peerConnection.signalingState:"-"}`,`needNewRenegotiation: ${S}`),S&&this.triggerRenegotiation(!1,f),this.configuredModalities}));return this.configuredModalitiesPromise=S.catch((g=>{this.logger.safe.warn(`[${f}] Error during configuring modalities: ${stringifyObject2(g)}`)})).then((()=>{})),S.then((()=>{}))}getConfiguredModalities(){return this.configuredModalities}getDisabledModalities(){return this.disabledModalities}getSubscriptionManager(){return null}createAudioElement(g){}createOfferAsync(g){const f=this.negotiationQueue.add((()=>new Promise((f=>{this.logger.safe.info(`[${g}] create [offer] configured: ${JSON.stringify(this.configuredModalities)}`),this.initiator=!0,this.throwIfModalitiesNotConfigured("no configured modalities to create offer for"),this.canTriggerRenegotiation=!1,this.negotiatingModalities=this.configuredModalities,this.offeredModalities=this.negotiatingModalities,this.configProvider.config.webrtcNegotiateDisabledDataModality&&!this.offeredModalities[qt.MODALITY.data]&&this.multiParty&&(this.offeredModalities[qt.MODALITY.data]=qt.MEDIA_STATE.inactive),isOnHold(this.offeredModalities)&&!isEmpty(this.negotiatedModalities)&&Object.keys(this.offeredModalities).forEach((g=>{void 0===this.negotiatedModalities[g]&&delete this.offeredModalities[g]})),f(this.updatePeerConnectionStreamsAsync(this.offeredModalities,!0,!0,g).then((()=>{const f=this.createNegotiationConstraints(this.offeredModalities);return this.logger.safe.info(`[${g}] create [offer] offered: ${JSON.stringify(this.offeredModalities)} constraints: ${JSON.stringify(f)}`),this.peerConnection.createOffer(f)})).then((f=>{this.logger.unsafe.debug(`[${g}] create [offer] offer from peer connection`,"sdp:",f.sdp);const S=this.sessionDescription.createLocalOffer(f.sdp);this.hasIceCandidates(S)||this.resetCandidateGathering(g),this.stats.startWaitingForStreamStart(this.offeredModalities);const v=new this.webrtcAdapter.RTCSessionDescription({sdp:S.toLocal(),type:"offer"});return this.setupIceGatheringTimeout(g),Promise.all([this.peerConnection.setLocalDescription(v),this.iceCandidatesDeferred.promise])})).then((()=>{const f=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp);f.updateModalities(this.offeredModalities),this.checkIceCandidates(f);const S=f.toOffer();this.logger.unsafe.debug("CREATE OFFER","sdp:",S);const v={blob:S,contentType:this.mediaContentType};return""===this.configProvider.config.webrtcRequiredFeatures||this.multiParty||(v.requiredFeatures=this.configProvider.config.webrtcRequiredFeatures),this.configProvider.countryCode&&(v.clientLocation=this.configProvider.countryCode),this.doRetargetIfNeeded(v,f,g),v})))}))),g);return this.resetNegotiationQueue(g),f}processOfferAsync(g,f){const S=this.negotiationQueue.add((()=>new Promise((S=>{const v=g.blob;if(this.logger.unsafe.debug(`[${f}] process [offer]`,"sdp:",v),this.configProvider.config.webrtcCompareContentTypeInOffer&&(assertContentTypeSupported(g.contentType,this.allowedMediaContentType),this.mediaContentType=g.contentType),g.requiredFeatures){const f=this.configProvider.config.webrtcRejectedFeatures.split(",");throwIfFeatureNotSupported(g.requiredFeatures.split(","),f)}this.initiator=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(v),this.canTriggerRenegotiation=!1,this.offeredModalities=invertModalities(this.offeredDescription.getModalities()),this.peerConnection||(this.context.configProvider.mediaConfig.isTransportUnbundled?this.context.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.couldBeUnbundled():this.context.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.isUnbundled());let C=Promise.resolve(this.offeredModalities);if(hasSendDirectionality(this.offeredModalities.video)||hasReceiveDirectionality(this.offeredModalities.video)||hasSendDirectionality(this.offeredModalities.sharing)||hasReceiveDirectionality(this.offeredModalities.sharing)){const g=this.offeredDescription.getVideoCodecs();C=this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video").then((S=>{if(!S.codecs.some((f=>g.some((g=>f.mimeType===g))))){this.logger.safe.warn(`[${f}] offer doesn't contain any supported video codecs`);const g=shallowClone(this.offeredModalities);return this.disabledModalities.video=g.video,this.disabledModalities.sharing=g.sharing,g.video=void 0,g.sharing=void 0,g}return this.offeredModalities})).catch((g=>(this.logger.safe.error(`[${f}] failed to get video capability ${stringifyObject2(g)}`),this.offeredModalities)))}S(C.then((g=>(this.logger.safe.info(`[${f}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(g)}`),g))))}))),f);return this.resetNegotiationQueue(f),S}createAnswerAsync(g,f){return new Promise((S=>{if(g)return void S({blob:"",contentType:this.mediaContentType});this.logger.safe.info(`[${f}] create [answer] offered: ${JSON.stringify(this.offeredModalities)} configured: ${JSON.stringify(this.configuredModalities)}`),this.throwIfModalitiesNotConfigured("no configured modalities to create answer for"),this.negotiatingModalities=this.configuredModalities;let v=negotiateModalities(this.offeredModalities,this.negotiatingModalities);const C=this.offeredDescription.clone();S(this.updatePeerConnectionStreamsAsync(v,!0,!1,f).then((()=>this.handleCodecSwitchUnsupported(f))).then((()=>{this.offeredDescription.setModalities(v);const g=this.offeredDescription.toRemote();this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources();const S=new this.webrtcAdapter.RTCSessionDescription({sdp:g,type:"offer"});return this.updateDescriptor(S,C),this.logger.unsafe.info(`[${f}] create [answer] set remote description`,"negotiated:",v,"sdp:",S.sdp),this.peerConnection.setRemoteDescription(S)})).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.updatePeerConnectionStreamsAsync(v,!1,!0,f)))).then((()=>(this.handleSharingRecvCapabilities(C),this.handleVideoRecvCapabilities(C)))).then((()=>this.peerConnection.createAnswer())).then((g=>{this.logger.unsafe.debug(`[${f}] create [answer] answer from peer connection`,"sdp:",g.sdp);const S=this.sessionDescription.createLocalAnswer(g.sdp);this.hasIceCandidates(S)||this.resetCandidateGathering(f),this.stats.startWaitingForStreamStart(v);const C=new this.webrtcAdapter.RTCSessionDescription({sdp:S.toLocal(),type:"answer"});return this.setupIceGatheringTimeout(f),Promise.all([this.peerConnection.setLocalDescription(C),this.iceCandidatesDeferred.promise])})).then((()=>{const g=this.sessionDescription.createLocalAnswer(this.peerConnection.localDescription.sdp);g.updateModalities(v),this.checkIceCandidates(g);const S=g.toAnswer();v=g.getModalities(),areNegotiatedDirectionsAcceptable(this.configuredModalities,this.negotiatingModalities,v)||this.triggerRenegotiation(!0,f),this.setNegotiatedModalities(v),this.stats.sessionInfo.setBweType(g.getBweType()),this.logger.unsafe.debug("CREATE ANSWER","sdp:",S);const C={blob:S,contentType:this.mediaContentType};return this.configProvider.countryCode&&(C.clientLocation=this.configProvider.countryCode),C})))}))}processAnswerAsync(g,f,S){const v=g.blob;if(this.logger.unsafe.debug(S?"PROCESS PRANSWER":"PROCESS ANSWER","sdp:",v),S)return this.logger.safe.info(`[${f}] process [pranswer] ignored`),Promise.resolve();this.mediaContentType=g.contentType,-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType);const C=this.sessionDescription.createRemoteAnswer(v),_=C.clone(),T=invertModalities(C.getModalities());this.setNegotiatedModalities(T),C.setModalities(this.negotiatedModalities);const I=C.toRemote();this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources(),this.stats.sessionInfo.setBweType(C.getBweType());const b=new this.webrtcAdapter.RTCSessionDescription({sdp:I,type:"answer"});return this.updateDescriptor(b,_),this.logger.unsafe.info(`[${f}] process [answer] set remote description`,"negotiated:",this.negotiatedModalities,"sdp:",b.sdp),this.peerConnection.setRemoteDescription(b).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.negotiatedModalities))).then((()=>(this.handleSharingRecvCapabilities(_),this.handleVideoRecvCapabilities(_)))).then((g=>{g&&this.triggerRenegotiation(!0,f)}))}completeNegotiationAsync(g){return new Promise((f=>{this.mediaManager.commit();const S=this.configuredModalities,v=this.forceMediaStreamUpdate&&!isOnHold(this.negotiatedModalities)||!areNegotiatedDirectionsAcceptable(S,this.negotiatingModalities,this.negotiatedModalities)||this.triggerRenegotiationFlag,C=!v;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${g}] negotiation completed isComplete: ${C} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),v&&this.triggerRenegotiation(!1,g),this.negotiationCompletedPromise.resolve(),f({isComplete:C,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})}))}rejectNegotiationAsync(g,f,S=!1){return Promise.resolve().then((()=>{if(this.mediaManager.rollback(),this.logger.safe.warn(`[${f}] negotiation rejected isComplete: ${!S} error: ${stringifyObject2(g)} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),this.peerConnection){if("have-local-offer"===this.peerConnection.signalingState)return this.logger.safe.info(`[${f}] rolling back local description`),this.configProvider.config.webrtcHandleRollback?(this.logger.safe.info(`[${f}] rolling back using local renegotiation`),this.negotiationEmulator.renegotiateNow().then((()=>{this.logger.safe.info(`[${f}] rolling back using local complete`)}))):this.peerConnection.setLocalDescription(new this.webrtcAdapter.RTCSessionDescription({type:"rollback"}));this.logger.safe.error(`[${f}] cannot rollback local description in currrent state: ${this.peerConnection.signalingState}`)}})).then((()=>{this.canTriggerRenegotiation=!0,this.negotiationCompletedPromise.reject("negotiation rejected"),this.getAddedMediaTypes(this.negotiatedModalities,this.negotiatingModalities).forEach((g=>{this.removeTrackByMediaType(g),this.disposeStreamByMediaType(g)})),this.registerLocalStreams()})).then((()=>(S&&(this.logger.safe.info(`[${f}] retrying failed negotiation`),this.triggerRenegotiation(!1,f)),{isComplete:!S,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})))}startMediaDescriptionsUpdateAsync(g){return Promise.reject(new Error("Not supported"))}completeMediaDescriptionsUpdateAsync(g){return Promise.reject(new Error("Not supported"))}rejectMediaDescriptionsUpdateAsync(g,f){return Promise.reject(new Error("Not supported"))}createRemoteRenderer(g){return this.remoteVideoManager.createRenderer(g,this.subscriptionManager,this.logger)}getStatsAsync(g){return this.terminated||(this.statisticsReport=this.statisticsReport.then((()=>this.stats.getReport(g))).catch((g=>(this.logger.safe.error(`getting statistics should never fail: ${g.error}`),g.partialReport)))),this.statisticsReport}getLastKnownStats(g=!1){return this.stats.getReport(!1,g)}muteHold(g,f){this.isMuteHold=g;const S=[qt.MODALITY.audio,qt.MODALITY.video,qt.MODALITY.sharing].filter((g=>hasSendDirectionality(this.negotiatedModalities[g])&&(g!==qt.MODALITY.audio||!this.doAudioMute)));for(const v of S)this.setMute(modalityToMediaType(v),g,f)}async muteInputAsync(g){this.doAudioMute=!0,this.setMute("Audio",!0,g)}async unmuteInputAsync(g){this.doAudioMute=!1,this.setMute("Audio",!1,g)}muteOutputAsync(g){return this.audioRenderer.setMuted(!0,g),Promise.resolve()}unmuteOutputAsync(g){return this.audioRenderer.setMuted(!1,g),Promise.resolve()}async getSpeakerVolume(g){return this.audioRenderer.getSpeakerVolume(g)}async setSpeakerVolume(g,f){return this.audioRenderer.setSpeakerVolume(g,f)}sendDtmf(g){return this.dtmfSender.sendDtmf(this.peerConnection,g)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}pauseNegotiations(g=generateCauseId()){const f=new dt;return this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(f,g)})),f}onDeviceEvent(g){this.stats.onDeviceEvent(g)}deviceSelectionChanged(){this.peerConnection&&(this.audioRenderer&&this.audioRenderer.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),isOnHold(this.negotiatedModalities)||(this.forceMediaStreamUpdate=!0,this.triggerRenegotiation(!0)))}async terminate(g,f,S=!0){this.logger.safe.info(`[${g}] terminate`),this.stats.setTerminated(),this.canTriggerRenegotiation=!1,this.cleanUp(g);try{S&&await this.getStatsAsync(!1)}catch(f){this.logger.safe.error(`[${g}] Error while gathering stats ${stringifyObject2(f)}`)}finally{this.stats.dispose(),this.terminated=!0}}processNotification(g,f){"DominantSpeakerInfo"===g&&this.activeSpeakerManager.onDominantSpeakerHistoryChanged(f.previousDominantSpeakerHistory,"signaling"),"ControlVideoStreaming"===g&&this.streamConfigurationHandler.handleMessage(f)}cleanUp(g){this.negotiationQueue.dispose(),this.localVideoStreamWatcher.dispose(),this.remoteVideoManager.dispose(),this.resetPeerConnection(g),this.subscriptionManagerSubs.forEach((g=>g.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.clearIceDisconnectedTimer(),this.callbacks.onTerminated&&this.callbacks.onTerminated(),this.negotiationCompletedPromise.reject("webRtcSession cleanup")}resetPeerConnection(g){this.logger.safe.info(`[${g}] reset peer connection`),this.audioRenderer&&this.audioRenderer.dispose(),this.dtmfSender&&(this.dtmfSender.dispose(),this.dtmfSender=null),this.peerConnection&&this.peerConnection.close(),this.toBeCalledAfterConnected=[],this.disposeStreams(),this.peerConnection=null,this.contributingSources?.dispose(),this.activeSpeakerManager.dispose(),this.negotiationEmulator.configure(null),this.peerConnectionPromise=null,this.resetCandidateGathering(g),this.canTriggerRenegotiation=!0,this.negotiatedModalities={}}resetNegotiationQueue(g=generateCauseId()){this.negotiationCompletedPromise.reject("promise expired"),this.setNegotiationPromise(new dt,g)}setNegotiationPromise(g,f=generateCauseId()){this.terminated||(this.negotiationCompletedPromise=g,this.negotiationQueue.add(this.negotiationCompletedPromise,f))}updateQualityLevels(g){if(!g)return;this.hwSilent!==g.audioHwSilent&&(this.hwSilent=g.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.ufdManager.signalEvent("NetworkRecvQuality",g.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:g.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",g.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:g.networkSendLevel});const f=!(!g.isSpeaking||!this.doAudioMute);this.ufdManager.signalEvent("DeviceSpeakWhileMuted",f?"Bad":"Good")}triggerRenegotiation(g,f=generateCauseId()){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${f}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired&&this.callbacks.onNegotiationRequired(f)):g&&(this.logger.safe.info(`[${f}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}throwIfModalitiesNotConfigured(g){if(!this.configuredModalities)throw new Error(g)}addTrack(g,f,S){if(!g)return;const v=this.modalityByMediaType(S);if(this.logger.safe.info(`add media track kind: ${g.kind} id: ${g.id}`),this.senders[v])throw new Error("track already created, modality:"+v+", kind:"+g.kind+", id:"+g.id);"closed"!==this.peerConnection.iceConnectionState&&(this.senders[v]=this.peerConnection.addTrack(g,f))}registerMediaSources(){const g=[];if(this.mediaStreams.forEach(((f,S)=>{const v={sourceId:this.getSourceIdForStream(f),defaultSSRC:this.ssrcs[S].min,modality:this.modalityByMediaType(S)};g.push(v)})),this.qualityManager.updateRegisteredSources(g),this.videoStream){const g=this.videoStream.getResolution();this.qualityManager.setCurrentResolution(new Xt(g.width,g.height))}}updateStream(g,f){return g.start().then((()=>{try{const S=this.mediaStreams.get(f);if(S&&g.isSameStream(S))return g.dispose(),null;if(this.updateSsrcRangeForMediaType(f),this.removeTrackByMediaType(f),this.disposeStreamByMediaType(f),!this.peerConnection)return g.dispose(),null;if(this.addTrack(g.rawTrack,g.rawStream,f),g.onApplyConstraints=S=>{this.removeTrackByMediaType(f),S.then((()=>{this.addTrack(g.rawTrack,g.rawStream,f),this.registerLocalStreams(),this.mediaManager.updateMediaEntitiesWithLocalTracks()}))},this.mediaStreams.set(f,g),"Video"===f){const g=[this.getMediaTrackInfo(f)];this.localVideoStreamWatcher.startWatching(g)}}catch(S){throw this.removeTrackByMediaType(f),this.disposeStreamByMediaType(f),g.dispose(),S}}))}getSourceIdForStream(g){const f=g.rawStream.getTracks()[0].id,S=this.mediaManager.getMediaEntityByLocalTrackId(f);return S?(this.logger.safe.info(`Media entity found: ${JSON.stringify(S.getXSourceStreamId())}`),S.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(f)}`),0)}updatePeerConnectionStreamsAsync(g,f,S,v){const C=hasSendDirectionality(this.negotiatedModalities.audio),_=hasSendDirectionality(this.negotiatedModalities.video),T=hasSendDirectionality(this.negotiatedModalities.sharing),I=isOnHold(this.negotiatedModalities),b=hasSendDirectionality(g.audio),A=hasSendDirectionality(g.video),P=hasSendDirectionality(g.sharing),R=isOnHold(g);return I||R||(this.stats.onSendersChanged("Audio",b),this.stats.onSendersChanged("Video",A),this.stats.onSendersChanged("ScreenShare",P)),this.assurePeerConnectionAsync(v).then((async()=>{if(this.logger.safe.info("updatePeerConnectionStreamsAsync","pc state",this.peerConnection.signalingState,"hold","[",I,"->",R,"]","audio","[",C,"->",b,"]","video","[",_,"->",A,"]","sharing","[",T,"->",P,"]"),I!==R){if(this.videoStream&&this.videoStream.setHold(R),this.audioStream&&this.audioStream.setHold(R),this.displayStream&&this.displayStream.setHold(R),R)return;if(!R&&this.audioStream){this.removeTrackByMediaType("Audio");const g=this.audioStream.clone();this.audioStream.dispose(),this.mediaStreams.set("Audio",g),this.addTrack(this.audioStream.rawStream.getAudioTracks()[0],this.audioStream.rawStream,"Audio")}}if((C!==b||_!==A||T!==P||this.forceMediaStreamUpdate)&&(S&&(this.forceMediaStreamUpdate=!1),f&&(this.logger.safe.info("not using any media(track api) track, remove all senders"),b||(this.removeTrackByMediaType("Audio"),this.disposeStreamByMediaType("Audio")),S&&A||(this.removeTrackByMediaType("Video"),this.disposeStreamByMediaType("Video")),S&&P||(this.removeTrackByMediaType("ScreenShare"),this.disposeStreamByMediaType("ScreenShare"))),S)){const g=[];if(A){const f=await this.deviceManager.getVideoStream(!1);g.push(this.updateStream(f,"Video"))}if(P){const f=this.deviceManager.getDisplayStream();g.push(this.updateStream(f,"ScreenShare"))}if(b){const f=await this.deviceManager.getAudioStream(!1);g.push(this.updateStream(f,"Audio").then((()=>{this.audioStream.setMuted(this.doAudioMute)})))}return Promise.all(g).then((()=>this.registerLocalStreams()))}}))}getMediaTrackInfo(g){const f=this.modalityByMediaType(g),S=this.mediaStreams.get(g).rawStream.getTracks()[0].id;return S||this.logger.safe.error(`No media track for modality found: ${f}`),{trackId:S,modality:f}}getSsrcRangeForMediaType(g){const f={min:1,max:1};switch(g){case"Audio":return this.ssrcGenerator.nextAudioStreamSsrc();case"Video":case"ScreenShare":return this.ssrcGenerator.nextVideoStreamSsrc();default:return f}}updateSsrcRangeForMediaType(g){"Video"!==g&&"ScreenShare"!==g||(this.ssrcs[g]=this.ssrcGenerator.nextVideoStreamSsrc())}getStreamTransformConfiguration(){return{unifiedPlanEnabled:!1,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}registerLocalStreams(){const g=[];this.mediaStreams.forEach(((f,S)=>{g.push(this.getMediaTrackInfo(S))})),this.mediaManager.setLocalTracksInfo(g)}handleVideoRecvCapabilities(g){if(this.configProvider.config.enableLocalVideoConstraints&&hasReceiveDirectionality(g.getModalities().video)){if(this.videoStream){const f=g.getVideoRecvCapabilities();if(!f)return this.logger.safe.error("No fmt params found for video modality"),Promise.resolve(!1);const S=this.generateReceiveCapabilities(f,this.videoStream);this.qualityManager.setMaxCapabilities([S])}this.logger.safe.error("remote endpoint didn't specify video receive capability")}return Promise.resolve(!1)}handleSharingRecvCapabilities(g){if(this.configProvider.config.enableLocalVideoConstraints&&hasReceiveDirectionality(g.getModalities().sharing)&&this.displayStream){const f=g.getSharingRecvCapabilities();if(!f)return void this.logger.safe.error("No fmt params found for sharing modality");const S=this.generateReceiveCapabilities(f,this.displayStream);this.qualityManager.setMaxCapabilities([S])}}generateReceiveCapabilities(g,f){const S={ssrc:0,rid:"0",keyframe:!1,...g},v={causeId:generateCauseId(),isSimulcast:!1,sourceId:this.getSourceIdForStream(f),capabilities:[S]};return this.logger.safe.info(`Generated receive capabilities for stream ${f.id}: ${JSON.stringify(v)}`),v}updateDescriptor(g,f){const S=f.getVideoRecvCapabilities(),v={sourceId:0,streamMsid:0,bandwidth:0};if(S&&this.videoStream&&!this.displayStream&&(v.sourceId=this.getSourceIdForStream(this.videoStream),v.streamMsid=this.videoStream.id,v.bandwidth=S.maxBr?S.maxBr:Number.MAX_VALUE),v.bandwidth>0){v.bandwidth=Math.floor(v.bandwidth/1200);const f=new OT(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider);f.setControlItem(v),f.modifyDescriptor(g)}}removeTrackByMediaType(g){return this.removeTracksByModality(this.modalityByMediaType(g))}modalityByMediaType(g){switch(g){case"Audio":return qt.MODALITY.audio;case"Video":return qt.MODALITY.video;case"ScreenShare":return qt.MODALITY.sharing;default:throw new Error(`Modality is not defined for media type: ${g}`)}}removeTracksByModality(g){this.forceKeyFramePromise&&"sharing"===g?this.forceKeyFramePromise.then((()=>{this.removeTracksByModality(g)})):g in this.senders&&(this.logger.safe.info(`remove sender track kind: ${this.senders[g].track.kind} track id: ${this.senders[g].track.id}`),"closed"!==this.peerConnection.iceConnectionState&&this.peerConnection.removeTrack(this.senders[g]),delete this.senders[g])}handleCodecSwitchUnsupported(g){return this.offeredDescription.isCodecSwitchSupported()?Promise.resolve():this.webrtcAdapter.RTCRtpReceiver.getCapabilities(qt.MEDIA_TYPE.audio).then((g=>{const f=g.codecs.map((g=>g.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(f)})).catch((f=>{this.logger.safe.error(`[${g}] failed to set primary codec based on audio capability ${stringifyObject2(f)}`)}))}disposeStreamByMediaType(g){const f=this.mediaStreams.get(g);f&&(this.mediaStreams.delete(g),f.dispose(),"Video"===g&&this.localVideoStreamWatcher.stopWatching())}disposeStreams(){this.mediaStreams.forEach(((g,f)=>this.disposeStreamByMediaType(f)))}assurePeerConnectionAsync(g){if(!this.peerConnectionPromise){if(!this.relayManagerProvider)throw new Error("relay manager provider is not set!");this.logger.safe.info("fetching relay details from RelayManager...");const f={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};this.peerConnectionPromise=this.relayManagerProvider.getRelayManager().queryRelaysAsync(f).then((f=>{if(this.terminated)throw new Error("session already disposed");const S={optional:[]},v=createIceServers(f,this.configProvider.config),C=this.configureCrypto(S);this.configureCpuThreshold(S),this.logger.safe.info("create peer connection");const _=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle",T=this.peerConnection=new this.webrtcAdapter.RTCPeerConnection({iceServers:v,rtcpMuxPolicy:"require",iceTransportPolicy:this.iceTransportPolicy,bundlePolicy:_,sdpSemantics:"plan-b",audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===C,offerExtmapAllowMixed:!1},S);this.negotiationEmulator.configure(T),this.stats.initialize(T),this.stats.sessionInfo.setIceServers(v),this.stats.sessionInfo.setIceTransportPolicy(this.iceTransportPolicy),this.stats.sessionInfo.setBundlePolicy(_);const I=this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video"),b=this.webrtcAdapter.RTCRtpSender.getCapabilities("video");this.stats.setH264AvailableProfiles(I),this.stats.setSupportedH264Profiles(b,I),T.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${T.signalingState}`)},T.onsignalingstatechange=()=>{this.stats.sessionInfo.setSignalingConnectionState(T.signalingState),this.logger.safe.info(`onsignalingstatechange signalingState: ${T.signalingState}`)},T.onicecandidateerror=g=>{const[f,S]=[g.address,g.port];this.logger.safe.warn(`On ICE candidate error ${g.url} | ${f}:${S}: code ${g.errorCode}: ${g.errorText}`),this.isConnected()&&!this.iceCandidatesDeferred.isPending||this.stats.addIceCandidateError({address:f,port:+S,url:g.url,errorCode:g.errorCode,errorText:g.errorText})};const onAddStream=g=>{if(!this.isConnected())return this.logger.safe.info("onaddstream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>onAddStream(g)));const f=g.stream;this.logger.safe.info(`onaddstream stream: ${f.id}`);let S=this.mediaManager.getMediaEntityByRemoteStreamId(f.id);if(S||(this.logger.safe.info(`cannot find media entity with stream id ${f.id} trying to fallback`),f.getAudioTracks()[0]&&(S=this.mediaManager.getMediaEntitiesByModality(qt.MODALITY.audio)[0])),S){const g=this.createReceiveStream(f,S);this.receiveStreamCollection.add(g)}else this.logger.safe.error(`could not find media entity for an added stream: ${f.id}`)};T.onaddstream=onAddStream,T.ontrack=g=>{this.logger.safe.info(`ontrack track: ${g.track}`)};const onRemoveStream=g=>{if(!this.isConnected())return this.logger.safe.info("onremovestream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>onRemoveStream(g)));this.logger.safe.info(`onremovestream stream: ${g.stream.id}`),this.receiveStreamCollection.remove(g.stream.id)};T.onremovestream=onRemoveStream,T.onicecandidate=f=>{const S=f.candidate;if(S){const f=parseCandidateString(S.candidate);this.logger.safe.info(`[${g}] onicecandidate candidate: prio:${f.priority} type:${f.type} port:${f.port}`),this.logger.unsafe.info(`[${g}] candidate details: ${S.candidate}`),!this.relayCandidateGathered&&S.candidate.indexOf("typ relay")>-1&&(this.stats.sessionInfo.setRelayCandidateInfo({priority:S.priority||S.candidate.split(" ")[3],time:Date.now()-this.iceRelayCandidatesGatherStartTime}),this.relayCandidateGathered=!0)}else this.logger.safe.info(`[${g}] onicecandidate candidate: null`);if(!this.iceCandidatesDeferred.isPending)return;const C=!this.initiator||!this.context.config.webrtcIceGatheringTimeoutIncreased,_=this.iceHostCandidateOnly||0===v.length;if(!S&&C||_){S&&this.logger.safe.info(`[${g}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${g}] Is connected:`,this.isConnected(),T.iceConnectionState,T.signalingState);let f=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&S&&(f=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledIceCandidates()),f&&this.completeCandidateGathering(g)}else if(this.relayCandidateGathered){let f=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&(f=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledRelayIceCandidates()),f&&(this.stats.clearIceCandidateErrors(),this.completeCandidateGathering(g))}},T.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${T.iceGatheringState}`)},T.oniceconnectionstatechange=()=>{const g=generateCauseId();if(!this.terminated){if(this.stats.sessionInfo.setIceConnectionState(T.iceConnectionState),this.logger.safe.info(`[${g}] oniceconnectionstatechange iceConnectionState: ${T.iceConnectionState} pc.signalingState: ${T.signalingState}`),"connected"===T.iceConnectionState||"completed"===T.iceConnectionState)this.onTransportConnected(g);else if("failed"===T.iceConnectionState){if(this.iceCandidatesDeferred.isPending)return this.logger.safe.info(`[${g}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(g);this.raiseError({type:qt.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},g),this.configProvider.config.webrtcCloseAfterIceFailure&&T.close(),this.onTransportFailed()}"disconnected"===T.iceConnectionState?(this.onTransportDisconnected(g),this.startIceDisconnectedTimer(g)):this.clearIceDisconnectedTimer()}},this.multiParty&&(this.contributingSources=new hb(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new ub(this.logger.createChild("ContributingSourcesProvider"),T)))}))}return this.peerConnectionPromise}configureCrypto(g){let f=!1;const S=preferSdesSrtp(this.context.configProvider,this.context.config.isPstnCall);if(this.offeredDescription){const g=this.offeredDescription.getSrtpInfo();this.stats.sessionInfo.setOfferedSrtpInfo(g),f=!g.dtls||g.sdes&&S}else f=S;return f&&(this.logger.safe.info("configuring peer connection to use sdes"),g.optional.push({DtlsSrtpKeyAgreement:!1})),this.stats.sessionInfo.setNegotiatedSrtpInfo({dtls:!f,sdes:!!f}),f?0:1}configureCpuThreshold(g){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&g.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(g){this.iceCandidatesDeferred.isPending&&(this.logger.safe.info(`[${g}] ICE candidates gathered completely`),this.iceCandidatesDeferred.resolve())}onTransportConnected(g){if(this.logger.safe.info(`[${g}] audio transport connected`),this.stats.clearIceCandidateErrors(),!this.terminated)for(this.callbacks.onAudioStateChanged(qt.STREAMING_STATE.active,g),this.callbacks.onTransportConnected&&this.callbacks.onTransportConnected(g);this.toBeCalledAfterConnected.length;)this.toBeCalledAfterConnected.shift()()}onTransportDisconnected(g){this.callbacks.onTransportDisconnected&&this.callbacks.onTransportDisconnected(g)}onTransportFailed(){this.callbacks.onTransportFailed&&this.callbacks.onTransportFailed()}startIceDisconnectedTimer(g){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${g}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise CONSTANTS.MEDIAthis._ERROR.iceConnectionError`),this.raiseError({type:qt.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},g)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(g,f=generateCauseId()){this.logger.safe.error(`[${f}] Media error occurred type: ${g.type} detail: ${g.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(g,f)}createNegotiationConstraints(g){function canReceive(g){return!!g&&(hasReceiveDirectionality(g)||"inactive"===g)}return{offerToReceiveAudio:canReceive(g.audio),offerToReceiveVideo:canReceive(g.video)||canReceive(g.sharing)}}resetCandidateGathering(g){this.logger.safe.info(`[${g}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new dt}checkIceCandidates(g){const f=this.hasIceCandidates(g);if(f===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:qt.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(f){const f=this.hasRelayIceCandidates(g);if(f===this.noRelayIceCandidates){if(!f&&("connected"===this.peerConnection.iceConnectionState||"completed"===this.peerConnection.iceConnectionState))return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasIceCandidates(g){return this.configProvider.mediaConfig.isTransportUnbundled?g.hasUnbundledIceCandidates():g.hasIceCandidates()}hasRelayIceCandidates(g){return this.configProvider.mediaConfig.isTransportUnbundled?g.hasUnbundledRelayIceCandidates():g.hasRelayIceCandidates()}doRetargetIfNeeded(g,f,S){const v=f.isIceRestart();this.logger.safe.info(`[${S}] ICE restart: ${v}`),this.context.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription?.isMSRTC()&&v&&!this.multiParty&&f.getSrtpInfo().sdes&&(g.newOffer=!0)}getAddedMediaTypes(g,f){g||(g={}),f||(f={});const S=[];return isModalityAdded(g.audio,f.audio)&&S.push("Audio"),isModalityAdded(g.video,f.video)&&S.push("Video"),isModalityAdded(g.sharing,f.sharing)&&S.push("ScreenShare"),S}applyCapabilitiesForModality(g,f,S){return g===qt.MODALITY.video?this.applyCapabilitiesForVideo(f,S[0]):g===qt.MODALITY.sharing?this.applyCapabilitiesForSharing(f,S[0]):Promise.resolve(!1)}applyCapabilitiesForSharing(g,f){return this.displayStream?this.applyCapabilities(this.displayStream,f).then((S=>(this.stats.onMaxCapabilitiesApplied({causeId:g,modality:qt.MODALITY.sharing,capabilities:[f]}),this.configProvider.config.webrtcAllowRestoreKeyframe?this.forceKeyframe(this.senders[qt.MODALITY.sharing]).then((()=>S)):Promise.resolve(S)))):(this.logger.safe.info(`${JSON.stringify(f)} is ignored as no sharing stream is sent, no renegotiation`),Promise.resolve(!1))}forceKeyframe(g){if(!g)return this.logger.safe.error("forceKeyframe: No sender available for sharing"),null;if(this.forceKeyFramePromise)return this.logger.safe.warn("forceKeyframe: already in progress"),this.forceKeyFramePromise;this.logger.safe.info("Restoring keyframe");const f=g.track;return this.forceKeyFramePromise=g.replaceTrack(null).then((()=>g.replaceTrack(f))).then((()=>{this.forceKeyFramePromise=null,this.logger.safe.info("Restoring keyframe finished")})).catch((g=>{this.forceKeyFramePromise=null,this.logger.safe.error(`Restoring keyframe failed: ${g}`),delete this.senders[qt.MODALITY.sharing]})),this.forceKeyFramePromise}applyCapabilitiesForVideo(g,f){return this.negotiationCompletedPromise.isPending?(this.logger.safe.info("##### Renegotiation is in progress, no local resolution switch for now #####"),this.negotiationCompletedPromise.promise.then((()=>Promise.resolve(!1)))):this.videoStream?this.scheduleApplyCapabilities(this.videoStream,g,f):(this.logger.safe.info(`${JSON.stringify(f)} is ignored as no video is sent, no renegotiation`),Promise.resolve(!0))}scheduleApplyCapabilities(g,f,S){this.logger.safe.info("Queueing local renegotiation...");let v=!1;return this.negotiationQueue.add((()=>(this.logger.safe.info("############# LOCAL RENEGOTIATION START #############"),this.applyCapabilities(g,S).then((()=>{this.stats.onMaxCapabilitiesApplied({causeId:f,modality:qt.MODALITY.video,capabilities:[S]}),v=!0})))),f),this.negotiationEmulator.renegotiate().then((()=>(this.logger.safe.info(`############# LOCAL RENEGOTIATION END. RESULT: ${v}  #############`),v)))}applyCapabilities(g,f){return g?(this.logger.safe.info(`Changing resolution to ${JSON.stringify(f)}`),g.applyCapabilities(f)):(this.logger.safe.info(`Resolution ${JSON.stringify(f)} ignored, no stream is being sent`),Promise.resolve(!1))}onOptimalVideoReceiversCountChanged(g){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(g)}getStreams(){return this.receiveStreamCollection.getStreams()}onStreamsChanged(g){this.streamsChangedListener=g}notifyStreamsChanged(){this.logger.safe.info(`Scheduling stream changed notification: ${this.streamsChangedNotificationScheduled}`),this.streamsChangedNotificationScheduled||this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.streamsChangedNotificationScheduled=!1,this.streamsChangedListener&&this.streamsChangedListener()}))}streamAdded(g){qt.MODALITY.audio===g.getModality()&&(this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),this.audioRenderer.play(g.getMediaStream())),this.notifyStreamsChanged()}streamRemoved(g){qt.MODALITY.audio===g.getModality()&&this.audioRenderer.getStream()===g.getMediaStream()&&this.audioRenderer.stop(),this.notifyStreamsChanged()}setNegotiatedModalities(g){this.negotiatedModalities=g,this.stats.sessionInfo.setNegotiatedModalities(g)}setupIceGatheringTimeout(g){this.iceRelayCandidatesGatherStartTime=Date.now();const f=this.context.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!f)return;this.iceCandidatesTimer>0&&clearTimeout(this.iceCandidatesTimer);const S=this.iceCandidatesDeferred;this.iceCandidatesTimer=setTimeout((()=>{this.iceCandidatesTimer=0,S.isPending&&(this.logger.safe.warn(`[${g}] ICE candidates gathering terminated due to timeout ${f}`),S.resolve())}),f)}createAudioRenderer(){this.audioRenderer=new WC(this.logger.createChild("AudioRenderer"),this.configProvider),this.context.maContext.domOverrides.onMediaElementAdded&&this.audioRenderer.on("onAudioElementAdded",this.context.maContext.domOverrides.onMediaElementAdded),this.context.maContext.domOverrides.onMediaElementRemoved&&this.audioRenderer.on("onAudioElementRemoved",this.context.maContext.domOverrides.onMediaElementRemoved)}isConnected(){const g=this.peerConnection;return g&&("connected"===g.iceConnectionState||"completed"===g.iceConnectionState)}isFailed(){return this.peerConnection&&("failed"===this.peerConnection.iceConnectionState||"closed"===this.peerConnection.iceConnectionState)}hasRelayCandidates(){return this.relayCandidateGathered}createReceiveStream(g,f){const S=this.configProvider.config.addFmtpToInitialSubscription?f.getLocalRecvCapabilities():null,v=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&f.getModality()!==qt.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null;return new $y(g,null,f.getModality(),+f.getXSourceStreamId(),this,S,v)}requestSource(g,f,S){if(!this.multiParty)return Promise.resolve();const v=this.mediaManager.getMediaEntityByRemoteStreamId(g);return!this.isMuteHold&&this.negotiatedModalities[v.getModality()]!==qt.MEDIA_STATE.inactive||-1===f?this.negotiationCompletedPromise.isPending?this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>this.requestSource(g,f,S))):Promise.resolve().then((()=>this.mediaMessageController.sendSourceRequest(v.getXSourceStreamId(),f,v?.getMid(),S,v.getSubstreamIndex()))):delay(10).then((()=>this.requestSource(g,f,S)))}getSessionConfig(){return this.configProvider}getUnmixedAudioProvider(){return null}};function isModalityAdded(g,f){return!hasSendDirectionality(g)&&hasSendDirectionality(f)}var jb={build:(g,f,S)=>new $b(g,f,S)},Gb=M,qb=class extends Ht{constructor(g,f){super(f),this.logger=f,this.id=-1,this.parentId=-1,this.rawStream=null,this.rawTrack=null,this.deviceId=null,this.mediaType=g}start(){return this.logger.safe.debug("start"),Promise.resolve()}clone(){return this.logger.safe.debug("clone"),this}setMuted(g,f){this.logger.safe.debug("setMuted")}setHold(g){this.logger.safe.debug("setHold")}getResolution(){return this.logger.safe.debug("getResolution"),{width:240,height:180}}getFrameRate(){return this.logger.safe.debug("getFrameRate"),1}hasAudio(){return this.logger.safe.debug("hasAudio"),!1}hasVideo(){return this.logger.safe.debug("hasVideo"),!1}isSameStream(g){return this.logger.safe.debug("isSameStream"),g===this}applyCapabilities(g){return this.logger.safe.debug("applyCapabilities"),Promise.resolve(!1)}onApplyConstraints(g){this.logger.safe.debug("onApplyConstraints")}update(g){this.logger.safe.debug("update")}isActive(){return!1}isDisposed(){return!1}},Wb=class _SessionStreamsProvider2 extends Ht{constructor(g,f,S,v,C){super(C),this.callDeviceManager=g,this.configProvider=f,this.sessionConfig=S,this.serialQueue=v,this.logger=C,this.mediaStreams={Audio:null,Video:null,ScreenShare:null},this.streamSubscriptions=new Map,this.deviceManagerSubscriptions=[],this.isNullAudioStream=!1}get currentMediaTypes(){return keys(this.mediaStreams).filter((g=>!!this.mediaStreams[g]))}async getStreams(){return this.mediaStreams}useNullAudioStreamClient(){this.isNullAudioStream=!0}async update(g,f){const S=keys(g).filter((f=>g[f]));return deepEqual(S,this.currentMediaTypes)?(this.logger.safe.info("Requested modalities have not changed. Do nothing"),sendStreamsToModalities(this.mediaStreams)):(this.logger.safe.info(`Starting media session with modalities: ${JSON.stringify(g)}`),await this.updateStreams(S,f),this.subscribeOnDeviceManagerEvents(),sendStreamsToModalities(this.mediaStreams))}async stopAsync(){this.logger.safe.info("Stopping streams async"),this.stop()}stop(){this.logger.safe.info("Stopping streams"),this.unsubscribeFromDeviceManagerEvents(),keys(this.mediaStreams).forEach((g=>this.removeStreamByType(g)))}dispose(){this.stop(),super.dispose()}async updateStreams(g,f){const S=this.getAvailableMediaTypes(),v=(0,Gb.intersection)(g,S),C=keys(this.mediaStreams).filter((g=>this.mediaStreams[g])),_=f?[]:subtractFrom(v,C),T=subtractFrom(C,v);_.length&&this.logger.safe.info(`Adding media streams for types: ${JSON.stringify(_)}`),await Promise.all(_.map((async g=>{await this.addStream(g,!1),this.mediaStreams[g]&&this.event("onStreamAdded").raise(g)}))),T.length&&this.logger.safe.info(`Removing media streams for types: ${JSON.stringify(T)}`),T.forEach((g=>{this.event("onStreamRemoving").raise(g),this.removeStreamByType(g)}))}getAvailableMediaTypes(){const g=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices(),f=[];return g.microphone&&f.push("Audio"),g.camera&&f.push("Video"),f.push("ScreenShare"),f}async addStream(g,f){if(this.mediaStreams[g])return void this.logger.safe.warn(`Stream with type: ${g} is already registered`);const S=await this.getStream(g,f);this.subscribeOnMediaStreamEvents(S);try{await S.start()}catch(f){return this.logger.safe.error(`Media stream request error: ${JSON.stringify(f)}`),void this.event("onStreamError").raise(g,f)}this.mediaStreams[g]=S}removeStreamByType(g){const f=this.mediaStreams[g];f?(this.unsubscribeFromMediaStreamEvents(f),f.dispose(),this.mediaStreams[g]=null):this.logger.safe.warn(`Stream with type: ${g} is not registered`)}async updateStream(g,f,S=!1){S&&"Audio"===g?await this.updateStreamWithEffect(g):(this.removeStreamByType(g),await this.addStream(g,f)),this.event("onStreamUpdated").raise(g)}async updateStreamWithEffect(g){const f=this.mediaStreams[g];f&&this.unsubscribeFromMediaStreamEvents(f);const S=await this.getStreamByMediaType(g,!0);this.subscribeOnMediaStreamEvents(S);try{await S.start()}catch(f){return this.logger.safe.error(`updateStreamWithEffect. Media stream request error: ${JSON.stringify(f)}`),void this.event("onStreamError").raise(g,f)}this.mediaStreams[g]=S,f?.dispose()}subscribeOnMediaStreamEvents(g){if(this.streamSubscriptions.has(g))return;const f=[];f.push(g.on("onStreamClientError",((g,f)=>this.onStreamError(g,f)))),f.push(g.on("onStreamClientDisposing",(g=>this.onStreamDisposing(g)))),this.streamSubscriptions.set(g,f)}unsubscribeFromMediaStreamEvents(g){this.streamSubscriptions.has(g)&&(this.streamSubscriptions.get(g).forEach((g=>g.dispose())),this.streamSubscriptions.delete(g))}async getStream(g,f){const S=this.mediaStreams[g];return S?(this.logger.safe.info(`Stream exists with id: ${S.id}, type: ${g}`),S):this.getStreamByMediaType(g,f)}async getStreamByMediaType(g,f){switch(g){case"Audio":return this.isNullAudioStream?new qb("Audio",this.logger.createChild("NullStreamClient")):this.getDeviceManagerByType("Audio").getAudioStream(f,"sessionStream");case"Video":return this.getDeviceManagerByType("Video").getVideoStream(f,"sessionStream",!1,this.sessionConfig.outgoingVideoMaxFS);case"ScreenShare":return this.getDeviceManagerByType("ScreenShare").getDisplayStream("sessionStream");default:throw new Error(`Media type is not supported: ${g}`)}}getMediaTypeForStream(g){const f=Object.keys(this.mediaStreams).find((f=>this.mediaStreams[f]===g));return f||this.logger.safe.error(`Media type is not found for stream: ${stringifyObject2(g)}`),f}subscribeOnDeviceManagerEvents(){if(0!==this.deviceManagerSubscriptions.length)return;if(this.callDeviceManager.isVirtualDeviceEnabled){const g=this.callDeviceManager.on("onSelectedVirtualDevicesChanged",((g,f)=>{const S=g;if(!g.camera){this.logger.info("Virtual DeviceID for camera is undefined, falling back to default device");const{camera:g}=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices();S.camera=g}this.callDeviceManager.isModalityEnabled("Video")&&f.camera!==S.camera&&(this.logger.info("Updating stream for camera"),this.updateStreamForVirtualDeviceChange("Video")),this.callDeviceManager.isModalityEnabled("ScreenShare")&&f.screenshare!==S.screenshare&&(this.logger.info("Updating stream for screenshare"),this.updateStreamForVirtualDeviceChange("ScreenShare"))}));this.deviceManagerSubscriptions.push(g)}const g=this.callDeviceManager.getDefaultDeviceManager();this.deviceManagerSubscriptions.push(g.on("onSelectedDevicesChanged",((g,f)=>this.onSelectedDevicesChanged(g,f))),g.on("onStreamUpdateRequested",((g,f)=>this.requestStreamUpdate(g,!1,f))),g.on("onAudioSharingToggled",(g=>this.onAudioSharingToggled(g))))}unsubscribeFromDeviceManagerEvents(){0!==this.deviceManagerSubscriptions.length&&(this.deviceManagerSubscriptions.forEach((g=>g.dispose())),this.deviceManagerSubscriptions=[])}getMediaTypesToUpdate(g,f){const S=[];return this.currentMediaTypes.some((g=>"Audio"===g))&&g.microphone&&g.microphone!==f.microphone&&S.push("Audio"),!this.callDeviceManager.getSelectedDevices().camera&&this.currentMediaTypes.some((g=>"Video"===g))&&g.camera&&g.camera!==f.camera&&S.push("Video"),S}removeStream(g){const f=this.getMediaTypeForStream(g);this.removeStreamByType(f)}async onSelectedDevicesChanged(g,f){if(this.configProvider.config.enablePermissionsWorkaround&&_SessionStreamsProvider2.isDeviceListEmpty(g,f))return void this.logger.safe.info("Device list is empty, permission workaround enabled");const S=this.getMediaTypesToUpdate(g,f);this.logger.safe.info(`Media types to update: ${JSON.stringify(S)}`),await Promise.all(S.map((g=>this.updateStream(g,!1))))}async onAudioSharingToggled(g){if(this.configProvider.config.postponeAudioMixerForAudioSharing&&g)return this.updateStream("ScreenShare",!0)}async requestStreamUpdate(g,f,S=!1){if(this.currentMediaTypes.some((f=>f===g))||f)return this.logger.safe.debug(`UpdateStream with media type: ${g}, force: ${f}`),this.updateStream(g,f,S);this.logger.safe.debug(`Stream with media type: ${g} is not active. Do nothing`)}onStreamError(g,f){this.removeStream(g)}onStreamDisposing(g){this.removeStream(g)}static isDeviceListEmpty(g,f){return!g.camera&&!g.microphone||!f.microphone&&!f.camera}getDeviceManagerByType(g){return this.callDeviceManager.getDeviceManager(g)}async updateStreamForVirtualDeviceChange(g){return this.updateStream(g,!1)}};__decorateClass([sequentialize()],Wb.prototype,"getStreams",1),__decorateClass([sequentialize()],Wb.prototype,"update",1),__decorateClass([sequentialize()],Wb.prototype,"stopAsync",1),__decorateClass([sequentialize()],Wb.prototype,"onSelectedDevicesChanged",1),__decorateClass([sequentialize()],Wb.prototype,"onAudioSharingToggled",1),__decorateClass([sequentialize()],Wb.prototype,"requestStreamUpdate",1),__decorateClass([sequentialize()],Wb.prototype,"updateStreamForVirtualDeviceChange",1);var zb=Wb,Kb=M,Jb=[5e4,1e6,15e5,2e6,25e5,375e4,4e6],Yb=[7e4,2e5,4e5,8e5,15e5,2499990,25e5];function createBandwidthAllocatorPerMediaType(g,f){const S=new Qb(g.createChild("BandwidthAllocator"));return S.setLadder("ScreenShare",f.config.sharingBitrateLadderOverride||Jb),S.setLadder("Video",f.config.videoBitrateLadderOverride||Yb),S}var Qb=class{constructor(g){this.logger=g,this.availableBandwidth=0,this.receivers=new Map,this.currentLayout={},this.ladders={}}setAvailableBandwidth(g){this.availableBandwidth=g,this.logger.safe.debug(`Total available bandwidth updated: ${g}`),this.updateLayouts()}getAvailableBandwidth(){return this.availableBandwidth}addReceiverCapability(g,f){this.logger.safe.debug(`Receiver maxBr set: ${g}/${f}`),this.receivers.set(g,f),this.updateLayouts()}getReceiverCapabilities(){const g={};for(const f of Object.keys(this.receivers)){const S=this.receivers.get(f);S&&(g[f]=S)}return g}removeReceiver(g){this.logger.safe.debug(`Receiver maxBr removed: ${g}`),this.receivers.delete(g),this.updateLayouts()}getLayouts(){return this.currentLayout}setLadder(g,f){this.ladders[g]=f}updateLayouts(){const g=this.generateLayouts();(0,Kb.isEqual)(g,this.currentLayout)||(this.currentLayout=g,this.logger.safe.debug(`Bandwidth distribution updated: ${stringifyObject2(g)}`))}generateLayouts(){const g={},f={};for(const S of Object.keys(this.ladders)){const v=this.receivers.get(S);v&&(f[S]=v||Number.MAX_SAFE_INTEGER,g[S]=0)}let S=this.availableBandwidth,v=0;const runLoop=()=>{if(!S)return!1;for(const g of Object.values(f))if(g)return!0;return!1};for(;runLoop();){for(const C of Object.keys(g)){const _=this.ladders[C];let T=_[v]||_[_.length-1];T=Math.min(T,S,f[C]),g[C]+=T,S-=T,f[C]-=T}v++}return g}};function getVideoBandwidthLadder(g,f){const S=g.config.bandwidthAllocatorV2;let v=[],C=-1;for(const g of S.videoLadders)(f>=g.maxFS&&C<g.maxFS||-1===C)&&(v=g.ladder,C=g.maxFS);return v}function createBandwidthAllocatorV2(g,f){const S=new Xb(g.createChild("BandwidthAllocator2"));return S.setPriority("ScreenShare","Video"),S.setLadder("ScreenShare",f.config.bandwidthAllocatorV2.sharingLadder),S.setLadder("Video",getVideoBandwidthLadder(f,f.config.bandwidthAllocatorV2.defaultVideoMaxFS)),S}var Xb=class{constructor(g){this.logger=g,this.availableBandwidth=0,this.receivers=new Map,this.currentLayout={},this.ladder=[],this.priority=[]}getReceiverCapabilities(){const g={};for(const f of Object.keys(this.receivers)){const S=this.receivers.get(f);S&&(g[f]=S)}return g}setAvailableBandwidth(g){this.availableBandwidth=g,this.logger.safe.debug(`Total available bandwidth updated: ${g}`),this.updateLayouts()}getAvailableBandwidth(){return this.availableBandwidth}addReceiverCapability(g,f){this.logger.safe.debug(`Receiver maxBr set: ${g}/${f}`),this.receivers.set(g,f),this.updateLayouts()}removeReceiver(g){this.logger.safe.debug(`Receiver maxBr removed: ${g}`),this.receivers.delete(g),this.updateLayouts()}getLayouts(){return this.currentLayout}setPriority(...g){this.priority=g}setLadder(g,f){this.logger.safe.info(`Set ladder for ${g}: ${JSON.stringify(f)}`);for(const f of this.ladder)delete f[g];-1===this.priority.indexOf(g)&&this.priority.push(g);for(let S=0;S<f.length;++S)S>=this.ladder.length&&this.ladder.push({}),this.ladder[S][g]=f[S]}updateLayouts(){const g=this.generateLayouts();(0,Kb.isEqual)(g,this.currentLayout)||(this.currentLayout=g,this.logger.safe.debug(`Bandwidth distribution updated: ${stringifyObject2(g)}`))}generateLayouts(){const g={};let f=this.availableBandwidth;for(const f of this.priority)this.receivers.get(f)&&(g[f]=0);for(let S=0;S<this.ladder.length&&f;++S){const v=this.ladder[S];for(const S of this.priority){const C=v[S];if(C&&this.receivers.get(S)){const v=Math.max(0,Math.min(C-g[S],f));f-=v,g[S]+=v}}}if(f){const S=f;let v=0;for(const g of this.priority)v+=this.receivers.get(g)??0;for(const C of this.priority){const _=this.receivers.get(C);if(_){const T=Math.min(f,Math.ceil(_*S/v));T&&this.logger.safe.info(`[AllocateSurplus][${C}] ${g[C]} + ${_} | ${f}`),f-=T,g[C]+=T}}}return g}},Zb=class{constructor(g,f,S){this.timeout=f,this.logger=S,this.isFirstTimeDeferred=!0,this.internalCallback=f=>{this.logger.safe.debug(`Trigger reason: ${f}`),g()}}invoke(g){this.logger.safe.debug(`Schedule shouldDefer: ${g}`),this.isFirstTimeDeferred?g?(this.isFirstTimeDeferred=!1,this.startTimer()):(this.stopTimer(),this.internalCallback("request")):this.timeoutId&&g||this.internalCallback("request")}dispose(){this.stopTimer()}startTimer(){this.timeoutId||(this.timeoutId=setTimeout((()=>{this.internalCallback("timeout"),this.timeoutId=void 0}),this.timeout),this.logger.safe.debug(`Timer started for : ${this.timeout}ms`))}stopTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0,this.logger.safe.debug("Timer stopped"))}},eA=class{constructor(g){this.logger=g,this.currentFrameSize=ei.Send.initialResolution.fs}setAvailableBandwidth(g){g!==this.lastSendBW&&(this.logger.safe.debug(`Available bandwidth updated ${g}`),this.processEstimatedBandwidth(g))}setMaxFrameSize(g){this.logger.safe.debug(`SetMaxFrameSize ${g}`),g!==this.maxFrameSize?(this.maxFrameSize=g,this.lastSendBW?(this.logger.safe.debug(`Setting max frame size: ${g}`),this.processEstimatedBandwidth(this.lastSendBW)):this.logger.safe.debug("Last send bwe is not defined. Do nothing")):this.logger.safe.debug(`Max frame size did not change. Do nothing, maxFs: ${g}`)}getFrameSize(){return this.currentFrameSize}processEstimatedBandwidth(g){if(this.logger.safe.debug(`Process estimated bandwidth ${g}`),0===g)return this.lastSendBW=0,void this.proposeResolution(0);const{lowRes:f,highRes:S}=ei.Send.getResolutionForBitrate(g);this.logger.safe.debug("low",f,"hi",S);const v=g<this.lastSendBW?S.fs:f.fs;g<this.lastSendBW&&this.currentFrameSize<v?this.logger.safe.debug(`proposed resolution is above the existing one, so we should stay on the current resolution, last bw: ${g}`):(v&&this.proposeResolution(v),this.logger.safe.debug(`Updating last bw: ${g}`),this.lastSendBW=g)}proposeResolution(g){this.logger.safe.debug(`Propose resolution ${g}`);const f=this.maxFrameSize?Math.min(g,this.maxFrameSize):g;f!==this.currentFrameSize&&(this.currentFrameSize=f,this.logger.safe.debug(`Proposed new frame size: ${f} based on bandwidth: ${this.lastSendBW}`))}},tA=1e8,iA=[{bwe:2e5,param:5e5},{bwe:5e5,param:12e5},{bwe:8e5,param:25e5},{bwe:12e5,param:4e6}],nA=[{bwe:2e5,param:240},{bwe:3e5,param:405},{bwe:5e5,param:920},{bwe:9e5,param:2040}],limitParamByBwe=(g,f,S)=>{for(const v of S)if(f<v.bwe)return Math.min(g,v.param);return g},limitStreamMaxBitrate=(g,f,S=iA)=>limitParamByBwe(g,f,S),limitStreamMaxResolution=(g,f,S=nA)=>limitParamByBwe(g,f,S),rA=class extends Ht{constructor(g,f,S){super(f),this.configProvider=g,this.logger=f,this.layoutsNumber=S,this.totalBandwidth=tA,this.totalBandwidthMax=0,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),this.outputLayouts=null,super.dispose()}setAvailableBandwidth(g){this.storeAvailableBandwidth(g),this.inputLayouts?(this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.debug("Layouts are not set. Skip update")}setLayouts(g,f){this.storeAvailableBandwidth(f),g.length===this.layoutsNumber?(this.logger.safe.debug(`Set layouts: ${JSON.stringify(g)}`),this.inputLayouts=this.getPrioritizedLayouts(g),this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.warn(`Incorrect number of layouts! ${JSON.stringify(g)}, expected ${this.layoutsNumber}`)}getLayouts(){return this.inputLayouts}getPrioritizedLayouts(g){return g}checkForChangesAndNotify(){const g=this.getLayouts();deepEqual(this.outputLayouts,g)?this.logger.safe.debug("Layout has not changed, skip update"):(this.outputLayouts=g.slice(),this.event("onLayoutsChanged").raise())}storeAvailableBandwidth(g){this.logger.safe.debug(`Set available bandwidth: ${g}`),this.totalBandwidth=g,this.totalBandwidthMax=Math.max(this.totalBandwidthMax,this.totalBandwidth)}},sA=class extends rA{constructor(g,f){super(g,f,2),this.resolutionManager=new eA(this.logger.createChild("BWEControlledResolutionManager"))}getLayouts(){return this.hiFiLayout?[this.loFiLayout,this.hiFiLayout]:[this.loFiLayout]}dispose(){super.dispose(),this.resolutionManager=null}getHighLayoutBandwidth(g){const f=this.inputLayouts?.[0].maxBr||0,S=Math.max(g-f,0);this.logger.safe.debug(`Setting available bandwidth for layouts. High: ${S}, low: ${f||"not set"}, total: ${g}`);const v=this.configProvider.config.specCompliantSimulcast?.allowedBweOvershootRatio||1;return Math.floor(S*v)}recalculateLayouts(){const g=this.hiFiLayout,f=this.getHighLayoutBandwidth(this.totalBandwidth);this.resolutionManager.setAvailableBandwidth(f),this.resolutionManager.setMaxFrameSize(this.inputLayouts[1].maxFs),this.loFiLayout=this.getMinimalLayoutParams(this.inputLayouts),this.hiFiLayout=this.getHighLayoutParams(this.inputLayouts,f,this.loFiLayout),this.loFiLayout=this.adjustLowLayoutBasedOnHighLayout(this.hiFiLayout,this.loFiLayout,g)}adjustLowLayoutBasedOnHighLayout(g,f,S){return this.configProvider.config.useMediaQualityControllerForceKeyFrame&&!g&&S&&(this.logger.safe.debug("Forcing kayframe on low layout due to disabling high layout"),f.keyframe=!0),g?(f.maxBr===g.maxBr&&f.maxBr--,f):f}getPrioritizedLayouts(g){return g.sort(((g,f)=>g.maxFs-f.maxFs?g.maxFs-f.maxFs:g.maxFps-f.maxFps))}getHighLayoutParams(g,f,S){const v=g[1];if(v.maxBr<=f)return this.logger.safe.debug(`High layout bandwidth suits requested caps. Applying as-is: ${JSON.stringify(v)}`),v;const C={...g[1],maxFs:this.resolutionManager.getFrameSize(),maxBr:Math.min(f,g[1].maxBr),maxFps:g[1].maxFps},_=C.maxBr<S.maxBr||C.maxFs<S.maxFs||C.maxFs===S.maxFs&&C.maxFps<=S.maxFps,T=`Potential high layout: ${JSON.stringify(C)}`;return!this.hiFiLayout&&_?(this.logger.safe.debug(`High layout is already disabled. Do nothing. ${T}`),null):this.hiFiLayout&&_?(this.logger.safe.debug(`High layout gets disabled. ${T}`),null):(this.hiFiLayout&&deepEqual(C,this.hiFiLayout)?this.logger.safe.debug(`High layout has not been changed. Do nothing. ${T}`):this.hiFiLayout?this.logger.safe.debug(`High layout updated. ${T}`):this.logger.safe.debug(`High layout enabled. ${T}`),C)}getMinimalLayoutParams(g){const f=Math.min(g[0].maxBr,g[1].maxBr),S=this.configProvider.config.specCompliantSimulcast.maxBrControlEnabled?limitStreamMaxBitrate(f,this.totalBandwidth,this.configProvider.config.specCompliantSimulcast.bitrateToBweTable):f;return{...g[0],maxBr:S,maxFps:Math.min(g[0].maxFps,g[1].maxFps),maxFs:Math.min(g[0].maxFs,g[1].maxFs)}}},aA=class extends rA{constructor(g,f,S){super(f,S,1),this.couldLimitFs=g}getLayouts(){return[this.layout]}recalculateLayouts(){let g=this.inputLayouts[0].maxFs;if(this.configProvider.config.specCompliantSimulcast.allowResLimit&&this.couldLimitFs&&this.totalBandwidthMax){const f=this.configProvider.config.specCompliantSimulcast.fsToBweTable;g=limitStreamMaxResolution(this.inputLayouts[0].maxFs,this.totalBandwidthMax,f)}const f=this.configProvider.config.specCompliantSimulcast.bitrateToBweTable,S=limitStreamMaxBitrate(this.inputLayouts[0].maxBr,this.totalBandwidth,f);this.layout={...this.inputLayouts[0],maxFs:g,maxBr:S}}},oA=class extends Ht{constructor(g){super(g),this.logger=g,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),super.dispose()}setAvailableBandwidth(g){this.logger.safe.debug(`Available bandwidth updated ${g}`)}setLayouts(g,f){this.layouts=g,this.setAvailableBandwidth(f)}getLayouts(){return this.layouts}},compareQuality=(g,f)=>g.maxFs===f.maxFs?g.maxFps===f.maxFps?g.maxBr-f.maxBr:g.maxFps-f.maxFps:g.maxFs-f.maxFs,compareMBPR=(g,f)=>g.maxFs===f.maxFs?g.maxFps-f.maxFps:g.maxFs-f.maxFs,lA=class extends Ht{constructor(g,f,S){super(S),this.settings=g,this.configProvider=f,this.logger=S,this.totalBandwidthMax=0,this.totalBandwidth=tA,this.inputLayouts=null,this.outputLayouts=null,this.maxOutputLayers=0,this.ladder=[],this.settings.ladder?this.ladder.push(...this.settings.ladder):this.ladder.push(...ei.Send.getResolutions())}dispose(){this.logger.safe.debug("Disposed"),super.dispose()}setAvailableBandwidth(g){this.updateAvailableBandwidth(g),this.update()}setLayouts(g,f){this.inputLayouts=g,this.updateAvailableBandwidth(f),this.update()}getLayouts(){return this.outputLayouts??[]}updateAvailableBandwidth(g){this.totalBandwidth!==Math.max(1,g)&&(this.logger.safe.debug(`Available bandwidth updated ${g}`),this.totalBandwidth=Math.max(1,g),this.totalBandwidthMax=Math.max(this.totalBandwidthMax,this.totalBandwidth))}debug(g,f,...S){let v;const format=g=>({FS:g.maxFs,FPS:g.maxFps,BR:g.maxBr,KF:g.keyframe?"1":"0",id:`rid:${g.rid}`??`0x${g.ssrc.toString(16).padStart(8,"0")}`});v=Array.isArray(f)?f.map(format):format(f),this.logger.safe.info(`${g}: <${S.map((g=>JSON.stringify(g))).join("><")}> ${JSON.stringify(v)}`)}update(){const g=this.settings.allowedOvershoot||1,f=this.adjustLayout(this.inputLayouts,this.totalBandwidth*g);if(deepEqual(this.outputLayouts,f))this.logger.safe.debug("Layout has not changed, skip update");else{if(this.settings.allowLayerBitrateOverlap&&f.length&&f.length<this.inputLayouts.length&&(this.setMinimumQuality(f[0],this.inputLayouts),this.debug("SetMinimumQuality",f[0])),this.outputLayouts&&this.settings.forceKeyFrameWhenLayerIsRemoved&&this.outputLayouts.length>f.length)for(const g of f)this.logger.safe.debug(`Force key frame for rid:${g.rid}`),g.keyframe=!0;this.outputLayouts=f,this.maxOutputLayers=Math.max(this.maxOutputLayers,this.outputLayouts.length),this.event("onLayoutsChanged").raise()}}adjustLayout(g,f){const S=[];if(g.length){if(g=g.map((g=>Object.assign({},g))).sort(compareQuality),this.debug("OriginalLayout",g),this.settings.minFrameSizeForSimulcast?.length>1){const f=this.settings.minFrameSizeForSimulcast;3===g.length&&2===f?.length&&g[g.length-1].maxFs<f[1]&&this.debug("DisableLowResStream",g.pop())}for(this.settings.highPriorityLayoutMinFS&&g.length>1&&g[g.length-1].maxFs>=this.settings.highPriorityLayoutMinFS&&this.settings.lowPriorityLayoutMaxFS?.length&&this.limitResolutionOnLowerSimulcastStreams(g);g.length>0&&f>0;){const v=g.shift();this.debug("Next",v,f),this.settings.allowLayerBitrateOverlap||this.setMinimumQuality(v,g);let C=f-v.maxBr;if(S.length>0){if(C<0&&this.degradeBitrateOrResolution(v,f)&&(this.debug("DegradeBitrateOrResolution",v),C=f-v.maxBr),C>=0){let g=!1;for(const f of S)if(g=compareMBPR(f,v)>=0,this.settings.allowLayerBitrateOverlap||v.maxBr<f.maxBr&&(g=!0),g){this.debug("Drop",v,S.length);break}g||(S.push(v),this.debug("Accept",v,S.length))}}else S.push(v),this.debug("Accept",v,S.length);f=C}this.debug("AdjustedLayout",S,f)}if(1===S.length)if(this.settings.minSinglecastBitrate||this.settings.singlecastLadder){const g=Math.max(this.settings.minSinglecastBitrate??this.totalBandwidth,this.totalBandwidth);S[0].maxBr>g&&this.degradeBitrateOrResolution(S[0],g,this.settings.singlecastLadder)&&this.debug("DegradeSinglecast",S[0],g)}else{if(this.settings.limitMaxResolution&&this.maxOutputLayers<=1){const g=this.configProvider.config.specCompliantSimulcast?.fsToBweTable;S[0].maxFs=limitStreamMaxResolution(S[0].maxFs,this.totalBandwidthMax,g),this.debug("LimitMaxFS",S[0],this.totalBandwidthMax)}if(this.settings.limitMaxBitrate){const g=this.configProvider.config.specCompliantSimulcast?.bitrateToBweTable;S[0].maxBr=limitStreamMaxBitrate(S[0].maxBr,this.totalBandwidth,g),this.debug("LimitMaxBitrate",S[0],this.totalBandwidth)}}return S}limitResolutionOnLowerSimulcastStreams(g){const f=g.pop();if(1===g.length){const f=this.settings.lowPriorityLayoutMaxFS[0];this.degradeResolutionTo(g[0],f)&&this.debug("DegradeResolutionTo",g[0],0,f)}else{const f=[...this.settings.lowPriorityLayoutMaxFS];f.sort(),g.splice(Math.min(2,f.length));for(let S=0;S<g.length;++S)this.degradeResolutionTo(g[S],f[S])&&this.debug("DegradeResolutionTo",g[S],S,f[S])}g.push(f)}setMinimumQuality(g,f){for(const S of f)g.maxBr=Math.min(S.maxBr,g.maxBr),g.maxFs=Math.min(S.maxFs,g.maxFs),g.maxFps=Math.min(S.maxFps,g.maxFps),g.maxMbps=g.maxFs*g.maxFps}degradeResolutionTo(g,f){for(;g.maxFs>f;)if(!this.degradeResolution(g))return!1;return!0}degradeResolution(g){const f=this.mapLayoutToLadder(g);if(f>=this.ladder.length)return!1;if(f>0){const S=this.ladder[f-1];return g.maxBr=Math.min(g.maxBr,S.maxBitrate),g.maxMbps=S.fs*S.fps,g.maxFps=S.fps,g.maxFs=S.fs,!0}return!1}degradeBitrateOrResolution(g,f,S){S??(S=this.ladder);const v=this.mapLayoutToLadder(g,S);if(v>=S.length)return!1;if(f>=S[v].minBitrate)return g.maxBr=f,!0;let C=v;for(;C>0;){const v=S[--C];if(f>=v.minBitrate)return g.maxMbps=v.fs*v.fps,g.maxFps=v.fps,g.maxFs=v.fs,g.maxBr=Math.min(f,v.maxBitrate),!0}return!1}mapLayoutToLadder(g,f){let S=0;for(f??(f=this.ladder);S<f.length&&!(f[S].fs>=g.maxFs&&f[S].fps>=g.maxFps);)++S;return S}},cA=class extends Ht{constructor(g,f,S,v){super(v),this.supportSingleBwControl=g,this.firstTime=f,this.configProvider=S,this.logger=v,this.multiStream=!1,this.wasMultistream=!0,this.deferredOperation=new Zb((()=>this.updateStrategy()),this.configProvider.config.layoutControlTimeout,this.logger.createChild("DeferredOperation")),this.simulcastStrategySettings=void 0,this.wasMultistream=!1,this.createStrategy(this.multiStream,this.firstTime)}configure(g){const f=this.isMultiStream(g);this.multiStream!==f&&(this.multiStream=f,this.simulcastStrategySettings||this.deferredOperation.invoke(this.multiStream&&!this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled))}onFeaturesChanged(g){const f={},S=this.configProvider.config.specCompliantSimulcast;let v=!1;g.hasServerSupport(0)&&(v=!0),g.hasClientSupport(2)&&this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy&&(v=!0),g.hasClientSupport(3)&&this.configProvider.config.broadcastMode?.prioritizeLayoutOnClient&&(v=!0),f.limitMaxBitrate=S?.maxBrControlEnabled,f.limitMaxResolution=S?.allowResLimit,f.allowedOvershoot=S?.allowedBweOvershootRatio,f.forceKeyFrameWhenLayerIsRemoved=this.configProvider.config.useMediaQualityControllerForceKeyFrame,v&&f.limitMaxResolution&&(f.limitMaxResolution=this.firstTime&&!this.wasMultistream),g.hasClientSupport(2)&&(g.hasClientSupport(1)||(f.highPriorityLayoutMinFS=this.configProvider.config.video1080p?.software?.highPriorityLayoutMinFS,f.lowPriorityLayoutMaxFS=this.configProvider.config.video1080p?.software?.lowPriorityLayoutMaxFS),f.minSinglecastBitrate=this.configProvider.config.video1080p?.minSinglecastBitrate,this.configProvider.config.video1080p?.singlecastLayoutLadder&&(f.singlecastLadder=createResolutionTable(this.configProvider.config.video1080p.singlecastLayoutLadder))),g.hasClientSupport(3)&&(f.highPriorityLayoutMinFS=this.configProvider.config.broadcastMode?.priorityLayoutMinFS,f.lowPriorityLayoutMaxFS=this.configProvider.config.broadcastMode?.lowPriorityLayoutMaxFS),g.hasServerSupport(0)&&(f.minSinglecastBitrate=f.minSinglecastBitrate??S?.minSinglecastBitrate,f.allowLayerBitrateOverlap=S?.allowLayerBitrateOverlap,S?.singlecastLadder&&(f.singlecastLadder=f.singlecastLadder??createResolutionTable(S?.singlecastLadder)),S.dropLowResolutionHigherStreams&&(f.minFrameSizeForSimulcast=S.video?.minFsForSimulcast)),!!this.simulcastStrategySettings===v&&deepEqual(f,this.simulcastStrategySettings)||(v?(this.logger.safe.info(`[SLCS] Configure [${this.simulcastStrategySettings?"existing":"initial"}][${this.wasMultistream}]: ${JSON.stringify(f)}`),this.simulcastStrategySettings=f):(this.simulcastStrategySettings&&this.logger.safe.info("[SLCS] Disable"),this.simulcastStrategySettings=void 0),this.deferredOperation.invoke(!1))}setLayouts(g,f){deepEqual(this.latestLayouts,g)&&this.latestBandwidth===f?this.logger.safe.debug("Layouts and bandwidth are not changed. Skipping update"):(this.latestLayouts=g,this.latestBandwidth=f,this.strategy.setLayouts(this.latestLayouts,f))}setAvailableBandwidth(g){this.latestBandwidth!==g?(this.strategy.setAvailableBandwidth(g),this.latestBandwidth=g):this.logger.safe.debug("Bandwidth is not changed. Skipping update")}getLayouts(){return this.strategy.getLayouts()}dispose(){this.strategy.dispose(),this.strategy=null,this.deferredOperation.dispose(),this.deferredOperation=null,super.dispose()}updateStrategy(){this.strategy.dispose(),this.createStrategy(this.multiStream),this.latestLayouts&&this.strategy.setLayouts(this.latestLayouts,this.latestBandwidth)}isMultiStream(g){return g>1}createStrategy(g,f=!1){this.strategy=this.getNewStrategy(g,f),this.strategy.on("onLayoutsChanged",(()=>{this.wasMultistream=this.wasMultistream||this.isMultiStream(this.strategy.getLayouts().length),this.event("onLayoutsChanged").raise()}))}getNewStrategy(g,f){return this.simulcastStrategySettings?new lA(this.simulcastStrategySettings,this.configProvider,this.logger.createChild("SimulcastLayoutControlStrategy")):g?new sA(this.configProvider,this.logger.createChild("BWEControlledStrategy")):this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled&&this.supportSingleBwControl?new aA(f,this.configProvider,this.logger.createChild("BWEControlledStrategySingle")):new oA(this.logger.createChild("NoControlStrategy"))}},dA=class extends Ht{constructor(g,f,S){super(f),this.configProvider=g,this.logger=f,this.videoFeatures=S,this.bandwidthAllocator=null,this.sendBandwidthCalculator=new Cb(this.configProvider,this.logger.createChild("SendBandwidthCalculator")),this.layoutProviders=new Map,this.hadLayoutProvider=new Set,this.useNewBandwidthAllocator=!1,this.highestVideoMaxFsWithSharingEnabled=0,this.bandwidthAllocator=createBandwidthAllocatorPerMediaType(this.logger,this.configProvider),this.sendBandwidthCalculator.on("onSendBandwidthChanged",(g=>this.onAvailableBandwidthChanged(g))),this.configProvider.config.sendBandwidthSeedValue&&this.bandwidthAllocator.setAvailableBandwidth(this.configProvider.config.sendBandwidthSeedValue),this.useVideoFeatures("Video")&&this.videoFeatures.on("onVideoFeaturesChanged",(g=>{if(this.useVideoFeatures(g.mediaType)){const f=this.layoutProviders.get(g.mediaType);f&&f.onFeaturesChanged(g)}if(!this.useNewBandwidthAllocator&&this.configProvider.config.bandwidthAllocatorV2.enableAllocator){let f=!1;g.hasServerSupport(0)&&(f=!0),g.hasClientSupport(2)&&this.configProvider.config.video1080p?.useNewBandwidthAllocator&&(f=!0),f&&this.switchBandwidthAllocator()}}))}dispose(){this.bandwidthAllocator=null,this.layoutProviders.forEach((g=>g.dispose())),this.layoutProviders.clear(),this.layoutProviders=null,super.dispose()}addReceiver(g,f){this.logger.safe.debug(`Set receiver max capabilities for ${g}: ${JSON.stringify(f)}`),this.configureProviders(g,f.length);const S=f.map((g=>g.maxBr)).reduce(((g,f)=>g+f));if(this.useNewBandwidthAllocator&&"Video"===g&&this.layoutProviders.has("ScreenShare")&&this.configProvider.config.bandwidthAllocatorV2.enableDynamicVideoLadder){const g=Math.max(...f.map((g=>g.maxFs)));g>this.highestVideoMaxFsWithSharingEnabled&&(this.highestVideoMaxFsWithSharingEnabled=g,this.bandwidthAllocator.setLadder("Video",getVideoBandwidthLadder(this.configProvider,g)))}this.bandwidthAllocator.addReceiverCapability(g,S);const v=this.bandwidthAllocator.getLayouts();this.layoutProviders.get(g).setLayouts(f,v[g]),this.updateBandwidthDistribution()}removeReceiver(g){this.logger.safe.debug(`Removing receiver for ${g}`),this.layoutProviders.get(g)?.dispose(),this.layoutProviders.delete(g),this.highestVideoMaxFsWithSharingEnabled=0,this.bandwidthAllocator.removeReceiver(g),this.updateBandwidthDistribution()}getLayouts(g){return this.layoutProviders.get(g).getLayouts()}onStatisticsChanged(g){this.sendBandwidthCalculator.onBandwidthChanged(g.estimatedSendBandwidth)}onDiagnosticUpdated(g){g.video?.send?.length&&g.video?.send[0]&&(this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Estimating send bandwidth"),this.sendBandwidthCalculator.onBandwidthChanged(calculateEstimatedSendBandwidth(g.video.send[0],this.configProvider)))}useVideoFeatures(g){return!("Video"!==g||!this.configProvider.config.specCompliantSimulcast?.enableSimulcastLayoutControlStrategy&&!this.configProvider.config.broadcastMode?.prioritizeLayoutOnClient&&!this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy)}switchBandwidthAllocator(){const g=createBandwidthAllocatorV2(this.logger,this.configProvider);g.setAvailableBandwidth(this.bandwidthAllocator.getAvailableBandwidth());const f=this.bandwidthAllocator.getReceiverCapabilities();for(const S of Object.keys(f))g.addReceiverCapability(S,f[S]);this.useNewBandwidthAllocator=!0,this.bandwidthAllocator=g,this.updateBandwidthDistribution()}configureProviders(g,f){if(!this.layoutProviders.has(g)){const f=this.createProvider(g);this.layoutProviders.set(g,f)}this.useVideoFeatures(g)&&f>2&&this.videoFeatures.get(g).toggleServer(0,!0),this.layoutProviders.get(g).configure(f)}createProvider(g){const f=new cA("Video"===g,!this.hadLayoutProvider.has(g),this.configProvider,this.logger.createChild(`LG:${g}`));return f.on("onLayoutsChanged",(()=>{const S=f.getLayouts();this.logger.safe.debug(`New layouts generated: ${JSON.stringify(S)}`),this.event("onLayoutsUpdated").raise(g)})),this.hadLayoutProvider.add(g),this.useVideoFeatures(g)&&f.onFeaturesChanged(this.videoFeatures.get(g)),f}onAvailableBandwidthChanged(g){this.bandwidthAllocator.setAvailableBandwidth(g),this.updateBandwidthDistribution()}updateBandwidthDistribution(){const g=this.bandwidthAllocator.getLayouts();for(const[f,S]of Object.entries(g))this.layoutProviders.get(f)?.setAvailableBandwidth(S);this.configProvider.config.mediaControlPlaneConfig?.enableSendBandwidthNotificationsEnabled&&this.event("onBandwidthAllocationUpdated").raise(g)}},hA=M;function mergeCapabilitiesWithCallConstraints(g,f,S){if("Video"!==g||!S)return S;const{maxBitrate:v,maxResolution:C,maxFramerate:_}=f.config.outgoingVideoLimit??{},T=v??1/0;let I=C?convertResolutionToFramesize(C):1/0,b=_??1/0;return f.config.sendVideoCapabilityManager?.isEnabled&&(I=1/0,b=1/0),T===1/0&&I===1/0&&b===1/0?S:S.map((g=>({...g,maxFs:getMinDefined(g.maxFs,I),maxBr:getMinDefined(g.maxBr,T),maxFps:getMinDefined(g.maxFps,b)})))}var uA=new Set(["maintain-framerate","maintain-resolution","balanced"]),gA=class{constructor(g,f){this.configProvider=g,this.logger=f}async setActive(g,f){const S=this.getSenderParameters(g);return S.encodings[0].active=f,this.setSenderParameters(g,S,"setActive")}getScaleFactor(g,f){if(!f.width||!f.height)return this.logger.safe.warn("Stream resolution is not set yet. Cannot calculate scale factor. Returning 1"),1;const S=ei.Send.getResolutionByFs(g);let v=Math.min(f.width,f.height)/S.height;return this.logger.safe.debug(`Scale factor is taken from resolution: ${JSON.stringify(f)} and new Fs: ${g} as ${v}`),v<1&&(this.logger.safe.warn("Scale factor cannot be less than 1! Limiting to 1"),v=1),v}async generateKeyFrameIfNeeded(g,f){if(!f.track)return void this.logger.safe.info("No track attached. Skipping");const S=this.getSenderParameters(f),v=g.filter((g=>g.keyframe)).map((g=>g.rid));if(0!==v.length&&S.encodings.some((g=>g.active)))if(this.configProvider.config.useKeyFrameApi){const g=[];S.encodings.forEach((f=>{!f.active||f.rid&&!v.includes(f.rid)?g.push({keyFrame:!1}):g.push({keyFrame:!0})})),await this.setSenderParameters(f,S,"generateKeyFrameAPI",!0,{encodingOptions:g})}else{const g=S.encodings.map(((g,f)=>g.active?g.rid&&!v.includes(g.rid)?null:{idx:f,factor:g.scaleResolutionDownBy||1}:null)).filter((g=>g));for(const f of g)S.encodings[f.idx].scaleResolutionDownBy=f.factor*this.configProvider.config.forceKeyFrameV2ScaleFactor;this.logger.safe.debug(`Restoring keyframe starting. Update scaleResolutionDownBy for encodings: ${JSON.stringify(S.encodings)}`),await this.setSenderParameters(f,S,"generateKeyFrameStart");const C=this.getSenderParameters(f);for(const f of g)C.encodings[f.idx].scaleResolutionDownBy=f.factor;await this.setSenderParameters(f,C,"generateKeyFrameEnd"),this.logger.safe.debug(`Restoring keyframe completed. Set scaleResolutionDownBy back for encodings: ${JSON.stringify(C.encodings)}`)}else this.logger.safe.info("No keyframes needed. Skipping")}getSenderParameters(g){const f=g.getParameters();if(f.encodings?.length||(f.encodings=[{}]),this.configProvider.config.reuseLastSetParameters&&this.lastSetEncodings){this.logger.safe.info(`Override returned encodings ${JSON.stringify(f.encodings)}`);const g=(0,hA.merge)((0,hA.cloneDeep)(f.encodings),this.lastSetEncodings);this.logger.safe.info(`Overrided encodings ${JSON.stringify(g)}`),f.encodings=g}return f}async setSenderParameters(g,f,S,v=!0,C){try{await g.setParameters(f,C),this.logger.safe.info(`${S}: Parameters applied for sender: encodings: ${JSON.stringify(f.encodings)}, degradationPreference: ${f.degradationPreference}`),this.lastSetEncodings=f.encodings}catch(g){const C=`${S}: setParameters failed. Parameters: ${JSON.stringify(f.encodings)}, error:  ${stringifyObject2(g)}`;if(this.logger.safe.error(C),v)throw new Error(C)}}getAdjustedBitrate(g,f){let S=g||0;const{maxBitrate:v}=ei.Send.getBitrateForResolution(f.width,f.height);return S=Math.min(S||v,v),S}async updateStreamParameters(g,f,S){if(g.getCurrentConstraints().withEffect&&f?.maxFs){const S=ei.Send.getResolutionByFs(f.maxFs),v={width:S.width,height:S.height};this.logger.safe.info(`Applying video constrains for video effetcs ${JSON.stringify(v)}`),g.resetEffectsOutputConstraints(v)}S&&await g.applyCapabilities(f)}augmentDegradationPreference(g,f){uA.has(f)&&g.degradationPreference!==f&&(g.degradationPreference=f,this.logger.safe.info(`degradationPreference changed to: ${g.degradationPreference}`))}async setEncodingsActiveState(g,f,S){this.logger.safe.info(S);const v=this.getSenderParameters(g);return v.encodings.forEach((g=>g.active=f)),this.setSenderParameters(g,v,S)}},pA=class{constructor(g,f,S){this.config=g,this.configProvider=f,this.logger=S,this.capabilitiesHelper=new gA(this.configProvider,this.logger)}get streamResolution(){return this.stream?.getCurrentConstraints().withEffect?this._streamResolutionFromCapabilities:this._streamResolution}setSender(g){this.rtpSender=g}updateStream(g){this.stream=g,this._streamResolution=g.getResolution(),this._streamResolutionFromCapabilities=this._streamResolution}setActive(g){return this.capabilitiesHelper.setActive(this.rtpSender,g)}async setCapabilities(g){(0,hA.isEqual)(this.currentCapabilities,g)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(g)}. Do nothing`):(this.defaultCapabilities=(0,hA.cloneDeep)(g),this.currentCapabilities=(0,hA.cloneDeep)(g),await this.applyLastCapabilities(),await this.capabilitiesHelper.generateKeyFrameIfNeeded(g,this.rtpSender))}async updateStreamQualityParams(g,f,S){if(g&&!(0,hA.isEqual)(this.streamResolution,g))return this._streamResolution=g,this._streamResolutionFromCapabilities=g,this.logger.safe.info(`Stream params changed: ${JSON.stringify(g)}@${f}@${S} id: ${this.rtpSender.track?.id}`),this.applyLastCapabilities();this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(g)}@${f}`)}async startSender(){return shouldDisableVideoSendersTroughSetParams(this.configProvider,this.stream)||shouldDisableAudioSendersTroughSetParams(this.configProvider,this.stream)?this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!0,"Starting senders."):void 0}async stopSender(){return this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!1,"Stopping senders.")}async applyLastCapabilities(){if(!this.currentCapabilities)return void this.logger.safe.info("Capabilities are not set. Do nothing");this.currentCapabilities=mergeCapabilitiesWithCallConstraints(this.stream.mediaType,this.configProvider,this.defaultCapabilities),await this.applyStreamCapabilities(this.currentCapabilities);const g=this.capabilitiesHelper.getSenderParameters(this.rtpSender),f=(0,hA.cloneDeep)(g);return this.currentCapabilities.forEach((f=>{const S=this.getEncondingIndexForRid(f.rid,g.encodings);this.updateEncodingsWithCaps(g.encodings[S],f)})),this.capabilitiesHelper.augmentDegradationPreference(g,this.configProvider.config.degradationPreference),this.updateActiveStates(g,this.currentCapabilities),this.logger.safe.info(`Encoding params new: ${JSON.stringify(g.encodings)}, old: ${JSON.stringify(f.encodings)}`),this.capabilitiesHelper.setSenderParameters(this.rtpSender,g,"applyCapabilities")}async applyCallConstraints(g){return this.logger.safe.info(`[${g}] Applying call constraints`),this.applyLastCapabilities()}async applyStreamCapabilities(g){if("Video"!==this.stream.mediaType||!g.length)return;let f=g[0];for(const S of g)f.maxFs<S.maxFs&&(f=S);if(g.length>1){const S=this.configProvider.config.specCompliantSimulcast.video.minFsForSimulcast;if(f=(0,hA.cloneDeep)(f),S?.length>0)for(let v=0;v<S.length;++v)g.length>v+1&&(f.maxFs=Math.max(S[v]||0,f.maxFs),f.maxFps=Math.max(...g.map((g=>g.maxFps))))}const S=this.configProvider.config.specCompliantSimulcast.video.useApplyConstraints;await this.capabilitiesHelper.updateStreamParameters(this.stream,f,S),S&&(this._streamResolution=this.stream.getResolution())}getEncondingIndexForRid(g,f){if(!g)return this.logger.safe.error("No RID found in incoming params. Returning index 0"),0;const S=f.findIndex((f=>f.rid===g));return S<0||S-1>this.config.layerScaleFactors.length?(this.logger.safe.error("Incorrect index deduced from requested RID. Returning index 0"),0):S}updateEncodingsWithCaps(g,f){g?(g.maxBitrate=f.maxBr,g.scaleResolutionDownBy=this.capabilitiesHelper.getScaleFactor(f.maxFs,this.streamResolution),g.maxFramerate=f.maxFps,this.config.defaultScalabilityMode&&(g.scalabilityMode=this.config.defaultScalabilityMode)):this.logger.safe.error(`SenderParams does not exist for caps: ${JSON.stringify(f)}`)}updateActiveStates(g,f){const S=g.encodings.map((g=>g.rid)),v=S.filter((g=>f.some((f=>g===f.rid)))),C=subtractFrom(S,v);v.forEach((f=>this.changeEncodingState(g,f,!0))),C.forEach((f=>this.changeEncodingState(g,f,!1)))}changeEncodingState(g,f,S){const v=g.encodings.find((g=>g.rid===f));v?v.active=S:this.logger.safe.error(`Encoding not found for RID: ${f}`)}},mA=class{constructor(g,f){this.configProvider=g,this.logger=f,this.capabilitiesHelper=new gA(this.configProvider,this.logger)}get params(){return this.currentCapabilities?.find((g=>"1"===g.rid))??this.currentCapabilities?.[0]}get useSetParameter(){if("ScreenShare"===this.stream.mediaType){if(this.configProvider.config.useSetParametersToApplySSCapabilities)return this.logger.safe.info("useSetParametersToApplySSCapabilities: true"),!0;if(!1===this.configProvider.config.useSetParametersToApplySSCapabilities)return this.logger.safe.info("useSetParametersToApplySSCapabilities: false"),!1}return!!this.configProvider.config.useSetParametersToApplyCapabilities&&(this.logger.safe.info("useSetParametersToApplyCapabilities"),!0)}async applyCallConstraints(g){return this.logger.safe.info(`[${g}] Applying call constraints`),this.applyLastCapabilities(3)}setSender(g){this.rtpSender=g}updateStream(g){this.stream=g,this.streamResolution=g.getResolution()}setActive(g){return this.capabilitiesHelper.setActive(this.rtpSender,g)}async setCapabilities(g){(0,hA.isEqual)(this.currentCapabilities,g)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(g)}. Do nothing`):1===g.length?(this.defaultCapabilities=(0,hA.cloneDeep)(g),this.currentCapabilities=(0,hA.cloneDeep)(g),await this.applyLastCapabilities(0),await this.capabilitiesHelper.generateKeyFrameIfNeeded(g,this.rtpSender)):this.logger.safe.error("Incorrect number of sender params!")}async updateStreamQualityParams(g,f,S){if(g&&!(0,hA.isEqual)(this.streamResolution,g))return this.streamResolution=g,this.logger.safe.debug(`Stream params changed: ${JSON.stringify(g)}@${f}`),this.applyLastCapabilities(S);this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(g)}@${f}`)}async startSender(g){this.logger.safe.info(`Replace sender with track: ${g.id}`),await this.rtpSender.replaceTrack(g),this.logger.safe.info("replaceTrack completed"),shouldDisableVideoSendersTroughSetParams(this.configProvider,this.stream)&&await this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!0,"Starting senders."),shouldDisableAudioSendersTroughSetParams(this.configProvider,this.stream)&&await this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!0,"Starting senders."),this.configProvider.config.applySenderParamsBeforeStart&&this.currentCapabilities&&await this.capabilitiesHelper.generateKeyFrameIfNeeded(this.currentCapabilities,this.rtpSender)}async stopSender(){return shouldDisableVideoSendersTroughSetParams(this.configProvider,this.stream)||shouldDisableAudioSendersTroughSetParams(this.configProvider,this.stream)?this.capabilitiesHelper.setEncodingsActiveState(this.rtpSender,!1,"Stopping senders."):(this.logger.safe.info("Replace sender with track: null"),await this.rtpSender.replaceTrack(null),void this.logger.safe.info("replaceTrack completed"))}async applyLastCapabilities(g){this.currentCapabilities?(this.currentCapabilities=mergeCapabilitiesWithCallConstraints(this.stream.mediaType,this.configProvider,this.defaultCapabilities),this.logger.safe.info(`Applying params: ${JSON.stringify(this.params)}`),await this.applyParams(this.params,g),await this.applyBitrate(this.params.maxBr)):this.logger.safe.debug("Capabilities are not yet set, nothing to apply")}applyBitrate(g){let f=g||0;return"Video"===this.stream.mediaType&&(f=this.capabilitiesHelper.getAdjustedBitrate(f,this.streamResolution)),this.setSingleEncodingParameters(this.rtpSender,{maxBitrate:f},"applyBitrate",!1)}async applyParams(g,f){if(this.useSetParameter)return this.setSingleEncodingParameters(this.rtpSender,{scaleResolutionDownBy:this.capabilitiesHelper.getScaleFactor(g.maxFs,this.streamResolution),maxFramerate:g.maxFps},"applyParams");2!==f&&await this.capabilitiesHelper.updateStreamParameters(this.stream,g,!0)}async setSingleEncodingParameters(g,f,S,v=!0){const C=this.capabilitiesHelper.getSenderParameters(g);return(0,hA.merge)(C.encodings[0],f),0===C.encodings[0].maxBitrate&&(this.configProvider.config.setParametersMaxBitrateUndefined?C.encodings[0].maxBitrate=void 0:delete C.encodings[0].maxBitrate),this.capabilitiesHelper.augmentDegradationPreference(C,this.configProvider.config.degradationPreference),this.capabilitiesHelper.setSenderParameters(this.rtpSender,C,S,v)}},fA=class{constructor(g,f,S){this.transitionStates=g,this.logger=S,this.stateCurrent=f}get state(){return this.stateCurrent}isDestinationStateValid(g){return this.transitionStates[this.stateCurrent].indexOf(g)>-1}setState(g){return this.isDestinationStateValid(g)?(this.stateCurrent=g,!0):(g!==this.stateCurrent&&this.logger.safe.info(`Invalid state transition ${this.stateCurrent} -> ${g}`),!1)}isCurrentStateMatchedWith(g){return this.stateCurrent===g||(this.logger.safe.info(`State does not match. Current: ${this.stateCurrent} required: ${g}`),!1)}},SA=class extends Ht{constructor(g,f){super(g),this.logger=g,this.configProvider=f,this.audioContext=new Xs.window.AudioContext(this.configProvider.config.audioSharingContextOptions),this.destination=this.audioContext.createMediaStreamDestination(),this.streamNodeMap=new Map,this.logger.safe.info(`Destination stream: ${this.destination.stream.id}, track: ${this.getDestinationTrack().id}`),this.subscribeOnMediaTrackEvents(this.getDestinationTrack())}get numberOfStreams(){return this.streamNodeMap.size}addSourceStream(g){if(!g.rawStream)return;if(this.streamNodeMap.has(g.rawStream))return;const f=g.on("onStreamClientDisposing",(()=>{this.removeSourceStream(g.rawStream),f.dispose()}));this.logger.safe.info(`Add stream: ${g.rawStream.id}, track: ${getTrack(g.rawStream).id}`),this.addStream(g.rawStream,g.mediaType)}getDestinationTrack(){return getTrack(this.destination.stream)}dispose(){super.dispose(),this.unsubscribeFromMediaTrackEvents(this.getDestinationTrack());for(const g of this.streamNodeMap.keys())this.removeSourceStream(g);this.audioContext.close(),this.audioContext=null}addStream(g,f="Audio"){const S=this.audioContext.createMediaStreamSource(g);S.connect(this.destination),this.streamNodeMap.set(g,{mediaType:f,sourceNode:S})}removeSourceStream(g){const f=this.streamNodeMap.get(g);f&&(this.logger.safe.info(`Remove stream: ${g.id}, track: ${getTrack(g).id}`),f.sourceNode.disconnect(),this.streamNodeMap.delete(g))}subscribeOnMediaTrackEvents(g){g.onended=f=>{this.logger.safe.info(`Track ${g.id} ended: ${JSON.stringify(f)}`)},g.onmute=()=>{this.logger.safe.info(`Track ${g.id} muted`)},g.onunmute=()=>{this.logger.safe.info(`Track ${g.id} unmuted`)}}unsubscribeFromMediaTrackEvents(g){g.onended=null,g.onmute=null,g.onunmute=null}};function getTrack(g){return g.getAudioTracks()[0]}var vA=class extends Ht{constructor(g,f,S,v,C,_,T){super(),this.mediaConnection=g,this.contextStream=S,this.logger=v,this.configProvider=C,this.encStreamsManager=_,this.capabilitiesManager=T,this.isMuted=!1,this.isActiveInternal=!1,this.stream=f.clone("streamSender ctor"),this.subscribeOnStreamClientMuted(),this.capabilitiesManager.updateStream(this.stream)}get rawTrack(){return this.audioMixer?.getDestinationTrack()||this.stream.rawTrack}get trackId(){return this.rawTrack?.id}applyCallConstraints(g){return this.capabilitiesManager.applyCallConstraints(g)}async init(){this.sender=await this.createSender(),this.isActiveInternal=!0,this.addStreamTransforms(),this.capabilitiesManager.setSender(this.sender)}async start(){this.isActive()?this.logger.safe.info("Already active. Do nothing"):(this.logger.safe.info("Starting"),this.isActiveInternal=!0,await this.capabilitiesManager.startSender(this.rawTrack),this.logger.safe.info("Started"))}async stop(){this.isActive()?(this.logger.safe.info("Stopping"),this.isActiveInternal=!1,await this.capabilitiesManager.stopSender(),this.logger.safe.info("Stopped")):this.logger.safe.info("Already stopped. Do nothing")}async setCapabilities(g){this.configProvider.config.applySenderParamsBeforeStart||await this.start();try{await this.capabilitiesManager.setCapabilities(g)}catch(g){this.logger.safe.error(`Error setting capabilities: ${stringifyObject2(g)}`)}await this.start()}updateStreamQualityParams(g,f,S){return this.capabilitiesManager.updateStreamQualityParams(g,f,S)}setMuted(g,f,S){this.isMuted=g,this.stream.setMuted(g,f),g&&this.audioMixer&&1!==this.audioMixer.numberOfStreams||this.audioMuteTransform?.mute(g),!this.configProvider.config.requestNewStreamOnUnmute||g||S||this.stream.isActive()||this.event("onNewStreamNeeded").raise()}async setHold(g,f){if(this.configProvider.config.holdSkipActivation)return;const S=!g;this.logger.safe.info(`[${f}] change isActive state to ${S}`);try{return this.capabilitiesManager.setActive(S)}catch(g){const v=this.configProvider.config.holdRetryActivationDelay;if(v>=0)return this.logger.safe.info(`[${f}] retrying after delay of ${v}`),await delay(v),this.logger.safe.info(`[${f}] change isActive state to ${S}, second attempt`),this.capabilitiesManager.setActive(S);throw g}}async setMainStream(g){return this.stream.dispose(),this.onStreamClientMutedSubscription?.dispose(),this.stream=g.clone("streamSender setMainStream"),this.stream.setMuted(this.isMuted),this.audioMixer?.addSourceStream(this.stream),this.isActive()&&(this.logger.safe.info(`Replace sender with track: ${this.rawTrack?.id}`),await this.sender.replaceTrack(this.rawTrack),this.logger.safe.info("Replace completed")),this.capabilitiesManager.updateStream(this.stream),this.subscribeOnStreamClientMuted(),this.capabilitiesManager.applyLastCapabilities(1)}async addAdditionalStream(g){if("Audio"===this.stream.mediaType){if(this.configProvider.config.postponeAudioMixerForAudioSharing&&this.setupAudioMixer(),this.audioMixer||this.logger.safe.error(`addAdditionalStream is called when audioMixer is not created. Main stream type is ${this.stream.mediaType}.`),this.audioMixer?.addSourceStream(g),this.audioMuteTransform?.mute(!1),this.configProvider.config.postponeAudioMixerForAudioSharing){if(!this.sender)return void this.logger.safe.error("Sender not created, cannot replace track");this.logger.safe.info(`addAdditionalStream replace sender with track: ${this.rawTrack?.id}`),await this.sender.replaceTrack(this.rawTrack),this.logger.safe.info("addAdditionalStream replace completed")}}else this.logger.safe.error("Not adding additional stream for non-audio stream")}dispose(){this.removeSender(),this.cleanUp()}async terminateAsync(){await this.removeSenderAsync(),this.cleanUp()}getActiveStreamIndexes(){return this.getSenderParameters().encodings.filter((g=>g.active)).map((g=>+g.rid))}isActive(){return this.sender&&(shouldDisableVideoSendersTroughSetParams(this.configProvider,this.stream)||shouldDisableAudioSendersTroughSetParams(this.configProvider,this.stream))?this.getSenderParameters().encodings[0].active:this.isActiveInternal}removeSender(){this.logger.safe.info("Removing sender from pc");try{this.mediaConnection.removeSender(this.sender)}catch(g){this.logger.safe.warn(`Error removing sender: ${stringifyObject2(g)}`)}}async removeSenderAsync(){this.logger.safe.info("Removing sender from pc");try{await this.mediaConnection.removeSenderAsync(this.sender)}catch(g){this.logger.safe.warn(`Error removing sender: ${stringifyObject2(g)}`)}}async createSender(){return this.configProvider.config.postponeAudioMixerForAudioSharing||this.setupAudioMixer(),this.mediaConnection.createSender(this.rawTrack,this.contextStream,mediaTypeToModality(this.stream.mediaType))}addStreamTransforms(){const g=this.encStreamsManager.initTransformsCollection(this.sender,"Sender",this.stream.mediaType);g&&("Audio"===this.stream.mediaType?this.configProvider.config.useInsertableStreams?.audioExtendedMute&&(this.audioMuteTransform=new Ja(this.logger.createChild("SendAudioPayload")),g.addTransform(this.audioMuteTransform)):this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&g.addTransform(new Wa(this.logger.createChild(`SendStreamAnalyzer [${this.stream.mediaType}]`))))}setupAudioMixer(){this.configProvider.config.enableAudioSharing?"Audio"===this.stream.mediaType?this.configProvider.config.audioSharingMemoryLeakFix&&this.audioMixer?this.logger.safe.debug("Audio mixer already created, not creating new one"):(this.audioMixer=new SA(this.logger.createChild("AudioMixer"),this.configProvider),this.audioMixer.addSourceStream(this.stream)):this.logger.safe.error("Not setting up audio mixer for non-audio stream"):this.logger.safe.info("Audio sharing is disabled, not setting up audio mixer")}getSenderParameters(){const g=this.sender.getParameters();return g.encodings?.length||(g.encodings=[{}]),g}subscribeOnStreamClientMuted(){this.configProvider.config.recoverOnStreamUnmute&&(this.onStreamClientMutedSubscription=this.stream.on("onStreamClientMuted",(async(g,f)=>{f||await this.capabilitiesManager.applyLastCapabilities(1)})))}cleanUp(){super.dispose(),this.encStreamsManager.clearTransformsCollection(this.sender),this.sender=null,this.audioMixer?.dispose(),this.stream.dispose(),this.onStreamClientMutedSubscription?.dispose(),this.stream=null,this.isActiveInternal=!1}},CA=class _SimulcastStreamSender2 extends Ht{constructor(g,f,S,v,C,_,T,I,b,A,P){super(),this.mediaConnection=g,this.mainStream=f,this.contextStream=S,this.mediaType=v,this.serialQueue=C,this.logger=_,this.configProvider=T,this.isAlwaysActive=I,this.encStreamsManager=b,this.simulcastContext=A,this.sendVideoCapabilityManager=P,this.isMuted=!1,this.isHold=!1,this.previousParameters=[],this.state=new fA(_SimulcastStreamSender2.transitionStates,"NotStarted",this.logger.createChild("state")),this.pendingStream=null,this.pendingParams=null,this.lastAppliedParams=null,this.subscribeOnQualityUpdates(this.mainStream),P&&this.sendVideoCapabilityManager.on("onCapabilitiesChanged",(g=>{this.event("onMaxVideoSendCapabilitiesChanged").raise(g),this.configProvider.config.applyMaxCapabilitiesToSenderParamsDirectly&&this.lastAppliedParams&&!this.pendingParams&&this.updateParameters(this.lastAppliedParams)}))}async start(){this.state.setState("Started")&&(this.sender=new vA(this.mediaConnection,this.mainStream,this.contextStream,this.logger.createChild("Sender"),this.configProvider,this.encStreamsManager,this.getCapabilitiesManager(this.simulcastContext)),await this.sender.init(),this.notifyMaxVideoSendCapabilitiesChanged(),this.configProvider.config.deactiveAudioSender&&"Audio"===this.mediaType&&(this.logger.safe.info("start(): Deactivating audio sender"),await this.sender.stop()),this.sender.on("onNewStreamNeeded",(()=>{this.logger.safe.info("onNewStreamNeeded"),this.event("onNewStreamNeeded").raise()})))}async activate(){if(this.state.setState("Active")&&(this.pendingStream&&(this.logger.safe.info("activate(): updating from pendingStream"),await this.updateStreamInternal(this.pendingStream),this.pendingStream=null),this.isAlwaysActive&&!this.isMuted&&"Audio"===this.mediaType&&(this.logger.safe.info("activate(): starting sender"),await this.sender.start()),this.isAlwaysActive?(this.event("onSendersChanged").raise(this,!0),this.logger.safe.info("Sender set to always active")):await this.sender.stop(),this.configProvider.config.enableCachingFMTP&&this.pendingParams)){const updateParams=async()=>{this.configProvider.config.enableCachingFMTPDelay>0&&(this.logger.safe.info("Applying delay before applying pending parameters"),await delay(this.configProvider.config.enableCachingFMTPDelay)),this.logger.safe.info("Apply pending parameters");const g=this.updateParametersInternal(this.pendingParams);return this.pendingParams=null,g};this.configProvider.config.enableCachingFMTPAwait?(this.logger.safe.info("Apply pending parameters"),await updateParams()):(this.logger.safe.info("Apply pending parameters in background"),updateParams().catch((g=>this.logger.safe.error("Error applying pending parameters",g))))}}updateStream(g){return this.updateStreamInternal(g)}async addAdditionalStream(g){return this.sender.addAdditionalStream(g)}async updateParameters(g){if(this.state.isCurrentStateMatchedWith("Active"))return this.updateParametersInternal(g);this.configProvider.config.enableCachingFMTP?(this.logger.safe.info("Postpone params update until sender is activated"),this.pendingParams=g):this.logger.safe.warn("Ignore params update as sender is not activated")}async terminateAsync(){this.state.setState("Disposed")&&(this.logger.safe.info("Terminating async"),await this.sender.terminateAsync(),this.cleanUp())}dispose(){this.state.setState("Disposed")&&(this.logger.safe.info("Disposing"),this.sender.dispose(),this.cleanUp())}async setHold(g,f){if(this.isHold!==g)return this.logger.safe.info(`[${f}] Setting hold to: ${g}`),this.isHold=g,this.sender.setHold(g,f);this.logger.safe.info(`[${f}] Already in hold=${g} state`)}setMuted(g,f,S){this.logger.safe.info(`[${f}] Setting muted to: ${g}`),this.isMuted=g,this.sender.setMuted(this.isMuted,f,S),!this.isMuted&&"Audio"===this.mediaType&&this.state.isCurrentStateMatchedWith("Active")&&this.sender.start()}getActiveStreamIndexes(){return this.sender?this.sender.getActiveStreamIndexes():[]}getTrackInfo(){return{modality:mediaTypeToModality(this.mediaType),trackId:this.sender.trackId}}applyCallConstraints(g){return this.sendVideoCapabilityManager?.applyCallConstraints(g),this.sender.applyCallConstraints(g)}getCapabilitiesManager(g){return g?.shouldUseSimulcast()?new pA(g.config,this.configProvider,this.logger.createChild("SimCapMgrV2")):new mA(this.configProvider,this.logger.createChild("SnglCapMgrV2"))}async updateStreamInternal(g){return this.logger.info(`updateStreamInternal(): id: ${g.id}, parentId: ${g.parentId}), mediaType: ${this.mediaType}`),this.state.isCurrentStateMatchedWith("Active")?this.mainStream!==g?(this.logger.safe.debug(`Switching streams: ${this.mainStream.parentId}:${this.mainStream.id} -> ${g.parentId}:${g.id}`),this.unsubscribeFromQualityEvents(),this.mainStream.dispose(),this.mainStream=g,this.subscribeOnQualityUpdates(this.mainStream),this.notifyMaxVideoSendCapabilitiesChanged(),await this.sender.setMainStream(this.mainStream),this.logger.debug(`track info after stream update: ${JSON.stringify(this.getTrackInfo())}`),this.sender.updateStreamQualityParams(this.mainStream.getResolution(),this.mainStream.getFrameRate(),1)):void this.logger.safe.info("Stream has not been changed. Skipping update"):(this.logger.safe.info("Postponing stream update until sender is activated"),void this.setPendingStream(g))}async updateParametersInternal(g){if(this.configProvider.config.applyMaxCapabilitiesToSenderParamsDirectly){this.lastAppliedParams=g;const f=this.sendVideoCapabilityManager?.getCapabilities();f&&(g=g.map((g=>{const S={...g};return S.maxFs>f.maxFs&&(this.logger.safe.info(`Reducing SSRC:${S.ssrc} video FS from ${S.maxFs} to ${f.maxFs}`),S.maxFs=f.maxFs),S.maxFps>f.maxFps&&(this.logger.safe.info(`Reducing SSRC:${S.ssrc} video FPS from ${S.maxFps} to ${f.maxFps}`),S.maxFps=f.maxFps),S})))}await this.sender.setCapabilities(g),compareArraysBy(this.previousParameters,g,((g,f)=>g.ssrc===f.ssrc))||(this.previousParameters=g,this.event("onSendersChanged").raise(this,!0))}setPendingStream(g){this.pendingStream=g;const f=g.on("onStreamClientDisposing",(()=>{this.pendingStream===g&&(this.pendingStream=null,f.dispose())}))}subscribeOnQualityUpdates(g){this.sub=g.on("onStreamQualityChanged",((g,f,S,v)=>this.updateStreamQualityParams(f,S,v)))}updateStreamQualityParams(g,f,S){return S===lr.EffectQualityChangeReason.Performance&&this.notifyMaxVideoSendCapabilitiesChanged({resolution:g,fps:f}),this.sender.updateStreamQualityParams(g,f,2)}unsubscribeFromQualityEvents(){this.sub?.dispose(),this.sub=null}notifyMaxVideoSendCapabilitiesChanged(g){if(!["Video","ScreenShare"].includes(this.mediaType))return;const{width:f,height:S}=g?.resolution??this.mainStream.getResolution(),v=g?.fps??this.mainStream.getFrameRate();if(!f||!S||!v)return;const C=new Xt(f,S),_={maxFs:C.fs,maxMbps:C.fs*v,maxFps:v,maxWidth:C.width,maxHeight:C.height};this.logger.safe.info(`Capabilities for ${this.mediaType} stream: ${JSON.stringify(_)}`),this.sendVideoCapabilityManager?this.sendVideoCapabilityManager.manage(_,!g):this.event("onMaxVideoSendCapabilitiesChanged").raise(_)}cleanUp(){this.sendVideoCapabilityManager?.dispose(),this.sendVideoCapabilityManager=null,this.unsubscribeFromQualityEvents(),this.mainStream.dispose(),this.mainStream=null,this.pendingStream&&this.pendingStream.dispose(),this.pendingStream=null,this.sender=null,this.contextStream=null,this.event("onSendersChanged").raise(this,!1),super.dispose()}};CA.transitionStates={NotStarted:["Started","Disposed"],Started:["Active","Disposed"],Active:["NotStarted","Disposed"],Disposed:[]},__decorateClass([sequentialize()],CA.prototype,"start",1),__decorateClass([sequentialize()],CA.prototype,"activate",1),__decorateClass([sequentialize()],CA.prototype,"updateStream",1),__decorateClass([sequentialize()],CA.prototype,"addAdditionalStream",1),__decorateClass([sequentialize()],CA.prototype,"updateParameters",1),__decorateClass([sequentialize()],CA.prototype,"terminateAsync",1),__decorateClass([sequentialize()],CA.prototype,"setHold",1),__decorateClass([sequentialize()],CA.prototype,"updateStreamQualityParams",1);var yA=CA,EA=class{constructor(g){this.durationThreshold=g,this.signals={}}track(g,f){void 0===this.signals[g]&&(this.signals[g]={wasNotified:!1}),this.signals[g].currentTime=Jt(),!!this.signals[g].currentState!=!!f&&(this.signals[g].currentState=f,this.signals[g].lastChanged=this.signals[g].currentTime,this.signals[g].wasNotified=!1)}update(g){const f=[];for(const f of Object.keys(g))void 0===this.signals[f]&&(this.signals[f]={wasNotified:!1});for(const f of Object.keys(this.signals))this.track(f,g[f]);for(const g in this.signals){const S=this.signals[g];if(void 0!==S.currentState){if(S.wasNotified)continue;S.currentTime-S.lastChanged>=this.durationThreshold&&(S.wasNotified=!0,f.push(S.currentState))}}return f}},_A=class extends Ht{constructor(g,f){super(),this.logger=g,this.timeout=-1,this.signals=new EA(f.performanceMonitor.durationThreshold??3e3),this.config={monitorQualityLimitationReasons:f.performanceMonitor?.monitorQualityLimitationReasons,monitorMaxFS:f.performanceMonitor?.monitorMaxFS,mitigationTimeout:f.performanceMonitor?.mitigation?.timeout,startupDelay:f.performanceMonitor?.startupDelay}}key(g,f){return`${g.rid}:${f}`}suspend(g){g>0&&(this.logger.safe.info(`Suspending for ${(g/1e3).toFixed(1)} seconds`),this.timeout=Jt()+g)}acceptLayout(g){return g.some((g=>void 0===g.rid))?(this.logger.safe.info("Ignore layout with missing RID"),!1):!(this.caps&&Math.max(0,...g.map((g=>g.maxFs)))>this.caps.maxFs)||(this.logger.safe.info("Ignore layout update while waiting for maxCapabilities to propagate to server"),!1)}resetLayout(){this.signals.update({}),this.layout=void 0}updateMaxCapabilities(g){this.logger.safe.info(`Max capabilities updated: ${JSON.stringify(g)}`),this.caps&&g.maxFs<this.caps.maxFs&&this.layout?.length>0&&(this.logger.safe.info("Stop monitoring current layout as maxFS will be reduced"),this.resetLayout()),this.caps=g}updateLayout(g){if((g||this.layout)&&this.logger.safe.info(`New layout: ${JSON.stringify(g)}`),g&&this.acceptLayout(g)){if((g=g.map((g=>Object.assign({},g)))).sort(((g,f)=>g.maxFs===f.maxFs?g.maxFps===f.maxFps?g.maxBr-f.maxBr:g.maxFps-f.maxFps:g.maxFs-f.maxFs)),this.layout?.length)for(let f=0;f<g?.length;++f){const S=g[f],v=this.layout.find((g=>g.rid===S.rid));v&&v.maxFs!==S.maxFs&&(this.logger.safe.info(`Reset '${this.key(v,"FS")}'`),this.signals.track(this.key(v,"FS"),void 0))}this.layout=g,-1===this.timeout&&(this.timeout=0,this.logger.safe.info("Starting performance monitor"),this.suspend(this.config.startupDelay))}else this.resetLayout(),this.timeout=-1}onMitigationApplied(){this.logger.safe.info("Mitigation was applied - resetting current layout"),this.resetLayout(),this.suspend(this.config.mitigationTimeout)}monitor(g){const f={};let S=0;if(!this.layout||this.layout.length<1||g.length<this.layout.length||this.timeout>Jt())return void this.signals.update(f);for(this.timeout>0&&(this.logger.safe.info("Resuming"),this.timeout=0),S=0;S<this.layout.length;++S){const v=this.layout[S],C=g.find((g=>g.rid===v.rid));if(C){const g=Math.ceil(C.frameWidth/qt.MACROBLOCK_SIZE)*Math.ceil(C.frameHeight/qt.MACROBLOCK_SIZE);if(this.config.monitorQualityLimitationReasons){const g=C.qualityLimitationReason;-1!==this.config.monitorQualityLimitationReasons.indexOf(`${g}`)&&(f[this.key(v,"QL")]={layout:v,type:"QL",expected:"none",actual:g})}this.config.monitorMaxFS&&g<v.maxFs&&(f[this.key(v,"FS")]={layout:v,type:"FS",expected:v.maxFs,actual:g})}}const v=this.signals.update(f).map((g=>{const f=Object.assign({},g);return f.layout=this.layout?.find((g=>g.rid===f.layout.rid))??f.layout,f}));v.length&&(this.logger.safe.info(`Raise event: ${JSON.stringify(v)}`),this.event("onVideoQualityDegraded").raise(v))}},TA=class extends Ht{constructor(g,f,S,v){super(g),this.logger=g,this.configProvider=f,this.diagnostics=S,this.videoFeatureManager=v,this.activeModalities=new Set,this.callbacks=[];const C=this.configProvider.config.specCompliantSimulcast?.performanceMonitor?.mitigation??{};this.config={allowDisabling1080pSinglecast:C.enableFor1080pSinglecast,allowDisabling1080pSimulcast:C.enableFor1080pSimulcast,allowDisablingThreeStreamSimulcast:C.enableForThreeStreamSimulcast,allowReversals:C.enableReversals}}hasSoftwareEncodedVideoAndSharing(){return!this.videoFeatureManager.get("Video").hasClientSupport(1)&&!this.videoFeatureManager.get("ScreenShare").hasClientSupport(1)&&this.hasActiveSenders("Video","ScreenShare")}hasActiveSenders(...g){return g.every((g=>this.activeModalities.has(g)))}getAdaptationInfo(g,f){return{description:g,activeModalities:[...this.activeModalities],isTransient:f&&this.config.allowReversals}}notify(g){this.logger.safe.warn(`${g.description} activeModalities: ${g.activeModalities.join("/")} isTansient: ${g.isTransient}`),this.diagnostics.registerLocalVideoPerformanceEvent(g)}schedule(g,f,S){this.callbacks.push({mediaType:g,state:f,callback:S})}override(g,f,S){this.configProvider.config[g]=f,this.logger.safe.info(`Overwriting ${g} with ${this.configProvider.config[g]}. Reason: ${S}`)}disable1080pSoftwareEncode(g){const f=this.videoFeatureManager.get("Video");if(!g.find((g=>g.maxFs===qt.MAX_FS_1080P)))return!1;if(!f.hasClientSupport(2))return!1;if(f.hasClientSupport(1))return!1;if(1===g.length&&!this.config.allowDisabling1080pSinglecast)return this.logger.safe.info("Will not disable 1080p for singlecast"),!1;if(g.length>1&&!this.config.allowDisabling1080pSimulcast)return this.logger.safe.info("Will not disable 1080p for simulcast"),!1;const S=this.configProvider.config.performanceFallbackMaxFsFor1080pSend,v={},C={webrtcCameraOpenFs:this.configProvider.config.webrtcCameraOpenFs,maxCameraFsViaCallConstraints:this.configProvider.config.maxCameraFsViaCallConstraints,webrtcVideoCapabilityMaxFS:this.configProvider.config.webrtcVideoCapabilityMaxFS};for(const g in C)C[g]>0&&(v[g]=Math.min(S,C[g]));const _=Object.keys(v);if(_.some((g=>C[g]!==v[g]))){_.forEach((g=>{this.override(g,v[g],"mitigating 1080p performance issues")})),this.event("onNewStreamNeeded").raise(v.webrtcCameraOpenFs);const g=this.getAdaptationInfo("Disabled software 1080p",this.hasSoftwareEncodedVideoAndSharing());return g.isTransient&&this.schedule("ScreenShare",!1,(()=>{_.forEach((g=>{this.override(g,C[g],"removing mitigation for 1080p performance issues")})),this.event("onNewStreamNeeded").raise(),this.notify(this.getAdaptationInfo("Re-enabled software 1080p",!0))})),this.notify(g),!0}return!1}disableThreeStreamSimulcast(g){const f=this.videoFeatureManager.get("Video");if(3!==g.length)return!1;if(!this.config.allowDisablingThreeStreamSimulcast)return this.logger.safe.info("Will not disable 3-stream simulcast"),!1;if(f.hasClientSupport(1))return!1;if(f.hasFullSupport(0)){const g=this.getAdaptationInfo("Disabled 3-stream simulcast",this.hasSoftwareEncodedVideoAndSharing());return f.toggleClient(0,!1),g.isTransient&&this.schedule("ScreenShare",!1,(()=>{f.toggleClient(0,!0),this.notify(this.getAdaptationInfo("Re-enabled Three stream simulcast",!0))})),this.notify(g),!0}return!1}updateSenderState(g,f){if(f===this.activeModalities.has(g))return;f?this.activeModalities.add(g):this.activeModalities.delete(g);const S=this.callbacks.filter((S=>S.mediaType===g&&S.state===f));this.callbacks=this.callbacks.filter((S=>S.mediaType!==g||S.state!==f));for(const g of S)g.callback()}mitigatePerformanceIssue(g){return!!this.disable1080pSoftwareEncode(g)||!!this.disableThreeStreamSimulcast(g)}},IA=class{constructor(g,f,S){this.callback=g,this.logger=f,this.settings=S,this.triggers=0,this.budget=0,this.budget=this.burst}get interval(){return this.settings?.interval??0}get burst(){return this.settings?.burst??0}cancel(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}schedule(){this.timer||(this.timer=setTimeout((()=>{this.cancel(),this.commit()||(this.budget=Math.min(this.budget+1,this.burst)),this.budget<this.burst&&this.schedule()}),this.interval))}commit(){return this.triggers>0&&(this.callback.apply(this),this.triggers=0,!0)}dispose(){this.cancel()}trigger(){++this.triggers,0!==this.burst||0!==this.interval?this.burst?(this.budget>0&&(--this.budget,this.commit(),this.cancel(),this.budget||this.logger.safe.warn(`Max burst limit reached: ${this.burst}`)),this.triggers>0&&this.logger.safe.debug(`Triggered while out of budget: ${this.triggers} / ${this.burst}`),this.schedule()):this.timer||(this.commit(),this.schedule()):this.commit()}},bA=class extends Ht{constructor(g,f,S,v){super(g),this.logger=g,this.configProvider=f,this.frameSizeLimits={},this.initialMaxFS=this.configProvider.config.webrtcCameraOpenFs,this.subs=[],this.cadence=new IA(this.commitCallConstraints.bind(this),this.logger.createChild("Cadence"),this.configProvider.config.sendVideoCapabilityManager?.constraintsCadence),this.configProvider.config.enableVideoFeatureManager&&S&&(this.features=S.get("Video"),this.subs.push(S.on("onVideoFeaturesChanged",(g=>{"Video"===g.mediaType&&this.onFeaturesChanged(g)})))),v&&this.subs.push(v.on("onNewStreamNeeded",(g=>{this.limitFrameSize("Performance",g),this.updateConstraintsAndNotify()}))),this.configProvider.config.video1080p?.software?.isEnabled&&this.limitFrameSize("Software1080P",qt.MAX_FS_1080P),this.settings=this.configProvider.config.sendVideoCapabilityManager,this.settings.defaultFS&&(this.initialMaxFS=this.settings.defaultFS);const C=this.getCallConstraints().maxFS;C&&C!==this.initialMaxFS&&(this.logger.safe.info(`Detected initial resolution opt-in: ${this.initialMaxFS} => ${C}`),this.limitFrameSize("Opt-In",C))}getCapabilities(){if(this.appliedCapabilities)return{...this.appliedCapabilities}}applyCallConstraints(g){this.lastCauseId=g,this.cadence.trigger()}manage(g,f){f&&(this.streamConstraints={maxFPS:g.maxFps,maxFS:g.maxFs},this.features&&this.streamConstraints.maxFS>=qt.MAX_FS_1080P&&this.configProvider.config.video1080p?.useSimulcastLayoutControlStrategy&&this.features.toggleClient(2,!0)),this.requestedCapabilities={...g},this.updateConstraintsAndNotify()}dispose(g){for(const f of this.subs)f.dispose(g);this.subs=[],this.cadence.dispose(),super.dispose()}onFeaturesChanged(g){const checkClient=(f,S)=>{this.limitFrameSize(Lb[f],g.hasClientSupport(f)?S:void 0)};checkClient(1,this.configProvider.config.hardwareEncodedVideoMaxFS),checkClient(3,this.configProvider.config.broadcastMode?.maxVideoFS),this.updateConstraintsAndNotify()}getCallConstraints(){const g=this.configProvider.config.outgoingVideoLimit,f={},S="number"==typeof g?g:g?.maxResolution;return S&&(f.maxFS=convertResolutionToFramesize(S)),f.maxFPS="number"==typeof g?void 0:g?.maxFramerate,f}commitCallConstraints(){this.limitFrameSize("Opt-In",this.getCallConstraints().maxFS,this.lastCauseId),this.updateConstraintsAndNotify()}buildCapabilities(){const g={...this.requestedCapabilities};if(this.constraints?.maxFS<g.maxFs||this.constraints?.maxFPS<g.maxFps){g.maxFps=getMinDefined(this.constraints.maxFPS,g.maxFps),g.maxFs=getMinDefined(this.constraints.maxFS,g.maxFs);const f={...ei.Send.getResolutionByFs(g.maxFs)};g.maxMbps=f.fs*g.maxFps,g.maxWidth=f.width,g.maxHeight=f.height}return g}limitFrameSize(g,f,S){this.frameSizeLimits[g]!==f&&(S?this.logger.safe.info(`[${S}] FS limit for '${g}' changed from ${this.frameSizeLimits[g]} to ${f}`):this.logger.safe.info(`FS limit for '${g}' changed from ${this.frameSizeLimits[g]} to ${f}`),this.frameSizeLimits[g]=f)}notify(){this.appliedCapabilities=this.buildCapabilities(),this.requestedCapabilities.maxFs!==this.appliedCapabilities.maxFs&&this.logger.safe.debug(`Changed video send capability max-fs from ${this.requestedCapabilities.maxFs} to ${this.appliedCapabilities.maxFs}`),this.requestedCapabilities.maxFps!==this.appliedCapabilities.maxFps&&this.logger.safe.debug(`Changed video send capability max-fps from ${this.requestedCapabilities.maxFps} to ${this.appliedCapabilities.maxFps}`),this.logger.safe.info(`Reporting video capabilities: ${JSON.stringify(this.appliedCapabilities)}`),this.event("onCapabilitiesChanged").raise(this.appliedCapabilities)}updateConstraintsAndNotify(){this.updateConstraints()&&this.notify()}updateConstraints(){const g=this.getCallConstraints(),f={};let S=!1;for(const g of this.settings.priorityOrder)if(this.frameSizeLimits[g]>0){S=-1!==this.settings.allowOptIn.indexOf(g),f.maxFS=this.frameSizeLimits[g],this.logger.safe.info(`Using FS ${f.maxFS} from '${g}'. Opt-In is ${S?"allowed":"not allowed"}`);break}if(void 0===f.maxFS&&(f.maxFS=this.initialMaxFS,S=this.settings.maxFS>this.initialMaxFS),f.maxFPS=g.maxFPS,this.frameSizeLimits["Opt-In"]>0){const g=this.frameSizeLimits["Opt-In"];(g<f.maxFS||S)&&(this.logger.safe.info(`Applying opt-in: ${f.maxFS} => ${g}`),f.maxFS=g)}if(this.streamConstraints&&(this.logger.safe.debug(`Applying stream constraints: ${JSON.stringify(this.streamConstraints)} to ${JSON.stringify(f)}`),f.maxFS&&(f.maxFS=getMinDefined(f.maxFS,this.streamConstraints.maxFS)),f.maxFPS&&(f.maxFPS=getMinDefined(f.maxFPS,this.streamConstraints.maxFPS))),f.maxFS===this.constraints?.maxFS&&f.maxFPS===this.constraints?.maxFPS||(this.logger.safe.info(`Final constraints changed from ${JSON.stringify(this.constraints)} to ${JSON.stringify(f)}`),this.constraints=f),this.constraints&&this.requestedCapabilities){if(this.appliedCapabilities){const g=this.buildCapabilities();return g.maxFs!==this.appliedCapabilities.maxFs||g.maxFps!==this.appliedCapabilities.maxFps}return!0}return!1}},AA=class extends Ht{constructor(g,f,S,v,C,_,T,I,b,A,P){super(f),this.mediaManager=g,this.logger=f,this.callDeviceManager=S,this.configProvider=v,this.sessionConfig=C,this.statisticsGatherer=_,this.diagnostics=T,this.qmDiagnostics=I,this.isMultiparty=b,this.encStreamsManager=A,this.videoFeatureManager=P,this.senders=new Map,this.senderSubs=new Map,this.senderId=0,this.previousMediaModalities={Audio:!1,Video:!1,ScreenShare:!1},this.muted=new Map([["Audio",!1],["Video",!1]]),this.serialQueue=new zC(this.logger),this.streamsProvider=new zb(this.callDeviceManager,this.configProvider,this.sessionConfig,this.serialQueue,this.logger.createChild("StreamsProvider")),this.streamProviderSubscriptions=[this.streamsProvider.on("onStreamAdded",(g=>this.onStreamUpdated(g,!1))),this.streamsProvider.on("onStreamUpdated",(g=>this.onStreamUpdated(g,!0)))],this.localVideoStreamWatcher=new Mb(this.logger,this.configProvider,this.callDeviceManager),this.localVideoStreamWatcherSub=this.localVideoStreamWatcher.on("onVideoCaptureFreeze",((g,f)=>this.onVideoCaptureFreeze(g,f))),this.configProvider.config.useMediaQualityController&&(this.mediaQualityController=new dA(this.configProvider,this.logger.createChild("MQC"),this.videoFeatureManager),this.mediaQualityController.on("onLayoutsUpdated",(g=>{const f=this.mediaQualityController.getLayouts(g);return this.logger.safe.debug(`Update layouts for ${g}: ${JSON.stringify(f)}`),"Video"===g&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateLayout(f),this.updateParameters(this.lastCauseId,g,f)})),this.mediaQualityController.on("onBandwidthAllocationUpdated",(g=>{this.event("onBandwidthAllocationChanged").raise(g)}))),this.configProvider.config.specCompliantSimulcast?.performanceMonitor&&(this.simulcastPerformanceMonitor=new _A(this.logger.createChild("SPM"),this.configProvider.config.specCompliantSimulcast),this.simulcastPerformanceMonitor.on("onVideoQualityDegraded",(g=>this.onVideoQualityDegraded(g)))),this.configProvider.config.specCompliantSimulcast?.performanceMonitor?.mitigation&&(this.simulcastPerformanceAdaptationManager=new TA(this.logger.createChild("SPAM"),this.configProvider,this.diagnostics,this.videoFeatureManager),this.simulcastPerformanceAdaptationManager.on("onNewStreamNeeded",(g=>{this.configProvider.config.sendVideoCapabilityManager?.isEnabled||(this.sessionConfig.outgoingVideoMaxFS=g,this.streamsProvider.requestStreamUpdate("Video",!0))})))}dispose(){this.senders.forEach(((g,f)=>{this.event("onSendStreamChanged").raise(null,f),this.configProvider.config.disposeSendersSync?g.dispose():g.terminateAsync()})),this.senders.clear(),this.senderSubs.forEach((g=>g.forEach((g=>g.dispose())))),this.senderSubs.clear(),this.streamProviderSubscriptions.forEach((g=>g.dispose())),this.streamProviderSubscriptions=[],this.configProvider.config.disposeStreamsSync?this.streamsProvider.stop():this.streamsProvider.stopAsync(),this.localVideoStreamWatcherSub.dispose(),this.localVideoStreamWatcher.dispose(),this.logger=this.logger.createChild("DISPOSED"),this.mediaQualityController?.dispose(),super.dispose()}registerRtpSenderManager(g){this.logger.safe.debug(`Registering RTP sender manager ${g}`),this.mediaConnection=g}useNullAudioStreamClient(){this.logger.safe.debug("Using null audio stream client"),this.streamsProvider.useNullAudioStreamClient()}get pendingStreamsPromise(){return this.streamsPromise}clearStreamsPromise(){this.streamsPromise=void 0}async update(g,f,S,v){v?.mark("startUpdateStreams");let C=getSendStreamModalities(g,this.configProvider.config.streamModalitiesExcludeData);const _=0!=(1&f),T=0!=(2&f),I=0!=(4&f);I&&(C={Audio:!0,Video:!1,Data:!1,ScreenShare:!1});const b=I?Promise.resolve(C):this.streamsProvider.update(C,_);let A,P;return T||I?(delete C.Data,A=shallowClone(C),P=_?void 0:A):(A=await b,P=A),this.logger.safe.info(`[${S}] Streams updated, modalities requested: ${JSON.stringify(C)} (flags: ${f}), result: ${JSON.stringify(A)}`),v?.markAndMeasure("startUpdateStreams","updateStreamsWithModalities"),await this.updateSenders(P,S),v?.markAndMeasure("updateStreamsWithModalities","updateSenders"),T&&(this.streamsPromise=(async()=>{const f=await b;return this.streamsPromise=void 0,await this.updateSenders(f,S),this.setAndUpdateLocalTracksInfo(!1),this.mergeAndSaveModalities(f,g)})()),this.applyMuteState(S,!0),this.setAndUpdateLocalTracksInfo(!1),this.mergeAndSaveModalities(A,g)}mergeAndSaveModalities(g,f){this.previousMediaModalities=shallowClone(g);const S=shallowClone(f);return forOwn(f,((f,v)=>{const C=modalityToMediaType(v);hasSendDirectionality(f)&&!g[C]&&(S[v]=removeSendDirectionality(f))})),S}async activate(g){this.logger.safe.info(`[${g}] activate senders`),await Promise.all([...this.senders.values()].map((async g=>g.activate()))),this.setAndUpdateLocalTracksInfo(!1)}applyCallConstraints(g){const f=this.senders.get("Video");return f?f.applyCallConstraints(g):(this.logger.info(`[${g}] Caching call constraints until sender is created`),this.callConstraintsCauseId=g,this.applyCallConstraintsDeferred=new dt,this.applyCallConstraintsDeferred.promise)}async applyCapabilities(g,f,S){this.logger.safe.info(`[${g}] Applying incoming ${f} FMTP: ${JSON.stringify(S)}`);const v=modalityToMediaType(f);this.lastCauseId=g;let C=S;return this.mediaQualityController&&(this.mediaQualityController.addReceiver(v,S),C=this.mediaQualityController.getLayouts(v)),this.simulcastPerformanceAdaptationManager?.updateSenderState(v,!0),this.updateParameters(g,v,C)}getLocalMediaSources(){const g=this.getTracksInfo(),f=[];return g.forEach((g=>{f.some((f=>f.modality===g.modality))||f.push({sourceId:this.getSourceIdForTrack(g),modality:g.modality})})),f}setMuted(g,f,S){this.muted.set(g,f),this.applyMuteState(S,!1)}async setHold(g,f){await Promise.all([...this.senders.values()].map((async S=>S.setHold(g,f))))}onStatisticsChanged(g){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.mediaQualityController?.onStatisticsChanged(g),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher||this.localVideoStreamWatcher.onStatisticsChanged(g)}onDiagnosticUpdated(g){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation&&this.mediaQualityController?.onDiagnosticUpdated(g),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher&&this.localVideoStreamWatcher.onDiagnosticUpdated(g)}async updateParameters(g,f,S){try{const v=this.senders.get(f);v?await v.updateParameters(S):this.logger.safe.info(`[${this.lastCauseId}] Capabilities ignored ${JSON.stringify(S)}, no ${JSON.stringify(f)} sender`),this.logger.safe.debug(`[${g}] Capabilities completed`);const C={modality:mediaTypeToModality(f),causeId:g,capabilities:S};this.statisticsGatherer.onMaxCapabilitiesApplied(C),this.qmDiagnostics.onMaxCapabilitiesApplied(C)}catch(v){const C=stringifyObject2(v);this.logger.safe.error(`[${g}] Error applying capabilities ${C}`);const _={modality:mediaTypeToModality(f),causeId:g,capabilities:S,error:C};this.statisticsGatherer.onMaxCapabilitiesApplied(_),this.qmDiagnostics.onMaxCapabilitiesApplied(_)}}applyMuteState(g,f){for(const[S,v]of this.muted)this.senders.get(S)&&this.senders.get(S).setMuted(v,g,f)}setAndUpdateLocalTracksInfo(g){const f=this.getTracksInfo();this.logger.safe.debug(`Local tracks info: ${JSON.stringify(f)}`),this.mediaManager.setLocalTracksInfo(f),g&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statisticsGatherer.updateStatsWithLocalSsrcTrackInfo())}getTracksInfo(){const g=[];return this.senders.forEach((f=>g.push(f.getTrackInfo()))),g}async updateSenders(g,f=generateCauseId()){const S=await this.streamsProvider.getStreams(),v=g||sendStreamsToModalities(S);this.logger.safe.info(`[${f}] Updating senders with modalities: ${JSON.stringify(v)}, override: ${!!g}`),await Promise.all(keys(v).map((async g=>{const S=v[g];if(S===this.previousMediaModalities[g])return;if(!S)return this.logger.safe.info(`[${f}] Removing sender for ${JSON.stringify(g)}`),void await this.removeSender(g);const C=(await this.streamsProvider.getStreams())?.[g];if(await this.createAndStartSender(C,g),this.logger.safe.info(`[${f}] Sender for ${JSON.stringify(g)} is added`),this.applyCallConstraintsDeferred&&"Video"===g){const g=this.senders.get("Video");try{await g.applyCallConstraints(this.callConstraintsCauseId),this.applyCallConstraintsDeferred.resolve()}catch(g){this.applyCallConstraintsDeferred.reject(g)}this.applyCallConstraintsDeferred=void 0,this.callConstraintsCauseId=void 0}await this.addAudioSharingStream(C),this.event("onSendStreamChanged").raise(C,g)}))),this.logger.safe.info(`[${f}] Senders updated. Enabled: ${JSON.stringify(Object.keys(v).filter((g=>v[g])))}`)}createCapabilityManager(g,f){if("Video"===g&&this.configProvider.config.sendVideoCapabilityManager?.isEnabled)return new bA(f.createChild("SVCM"),this.configProvider,this.videoFeatureManager,this.simulcastPerformanceAdaptationManager)}createAndStartSender(g,f){if(this.senders.get(f))return this.logger.safe.error(`Sender already created, modality: ${JSON.stringify(f)}`),this.senders.get(f).start();const S=this.mediaManager.getMediaEntitiesByModality(mediaTypeToModality(f))[0],v=S?.getSimulcastContext(),C=!this.configProvider.config.specCompliantSimulcast?.disableTilde&&!!v?.shouldUseSimulcast(),_="Audio"===f||!this.isMultiparty||C,T=this.logger.createChild(`Sender_${JSON.stringify(f)}:${this.senderId++}`),I=this.createCapabilityManager(f,T),b=new yA(this.mediaConnection,g||new qb(f,this.logger.createChild("tempStream")),new MediaStream,f,this.serialQueue,T,this.configProvider,_,this.encStreamsManager,v,I);this.senders.set(f,b);const A=[b.on("onSendersChanged",((g,f)=>this.onSenderStateChanged(g,f))),b.on("onNewStreamNeeded",(()=>this.streamsProvider.requestStreamUpdate(f,!0))),b.on("onMaxVideoSendCapabilitiesChanged",(g=>{this.event("onMaxVideoSendCapabilitiesChanged").raise(f,g),"Video"===f&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateMaxCapabilities(g)}))];return this.senderSubs.set(b,A),b.start()}async removeSender(g){const f=this.senders.get(g);f&&(this.senders.delete(g),this.event("onSendStreamChanged").raise(null,g),await f.terminateAsync(),this.senderSubs.get(f).forEach((g=>g.dispose())),this.senderSubs.delete(f),this.logger.safe.info(`Removed sender with mediaType: ${JSON.stringify(g)}`)),this.mediaQualityController?.removeReceiver(g),this.simulcastPerformanceAdaptationManager?.updateSenderState(g,!1),"Video"===g&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.updateLayout(void 0)}getSourceIdForTrack(g){const f=g.trackId,S=this.mediaManager.getMediaEntityByLocalTrackId(f);return S?(this.logger.safe.info(`Media entity found: ${JSON.stringify(S.getXSourceStreamId())}`),S.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(f)}`),0)}onVideoCaptureFreeze(g,f){g||(f?this.qmDiagnostics.registerWebcamFreeze():this.qmDiagnostics.registerProcessedStreamFreeze()),this.event("onVideoCaptureFreeze").raise(g)}onVideoQualityDegraded(g){const f=this.mediaQualityController?.getLayouts("Video")??[];let S=!1;for(const v of g)if(this.logger.safe.warn(`rid:${v.layout.rid} ${v.type} degraded - expected: ${v.expected}, actual: ${v.actual}`),!S&&this.simulcastPerformanceAdaptationManager)switch(v.type){case"QL":"cpu"===v.actual&&(S=this.simulcastPerformanceAdaptationManager.mitigatePerformanceIssue(f));break;case"FS":"1"===v.layout.rid&&(S=this.simulcastPerformanceAdaptationManager.mitigatePerformanceIssue(f))}S&&this.simulcastPerformanceMonitor&&this.simulcastPerformanceMonitor.onMitigationApplied()}async onStreamUpdated(g,f){if(!this.senders.has(g))return void this.logger.safe.warn(`Sender with media type ${g} does not exist, do not update media stream`);let S=(await this.streamsProvider.getStreams())[g];if(S||(this.logger.safe.info(`Stream is missing for mediaType: ${g}, using fake stream...`),S=new qb(g,this.logger.createChild("NullStreamClient"))),S.isDisposed())return void this.logger.safe.info(`Stream is already disposed for mediaType: ${g}`);this.event("onSendStreamChanged").raise(S,g);const v=this.senders.get(g);await this.addAudioSharingStream(S),await v.updateStream(S),this.logger.safe.debug(`Stream updated for mediaType: ${g}, updated: ${f}`),this.setAndUpdateLocalTracksInfo(f)}onSenderStateChanged(g,f){if(this.mediaManager.updateMediaEntitiesWithActivityState(g.mediaType,g.getActiveStreamIndexes()),this.statisticsGatherer.onSendersChanged(g.mediaType,f),"Video"===g.mediaType)if(f){const g=this.getTracksInfo().filter((g=>g.modality===qt.MODALITY.video));this.localVideoStreamWatcher.startWatching(g,this.simulcastPerformanceMonitor)}else this.localVideoStreamWatcher.stopWatching()}async addAudioSharingStream(g){"ScreenShare"===g?.mediaType&&g?.hasAudio()&&(this.logger.safe.info("Adding audio stream from sharing to audio sender"),await(this.senders.get("Audio")?.addAdditionalStream(g)))}};function getSendStreamModalities(g,f=!0){const S={Audio:hasSendDirectionality(g.audio),Video:hasSendDirectionality(g.video),ScreenShare:hasSendDirectionality(g.sharing)};return f||(S.Data=hasSendDirectionality(g.data)),S}var PA=class{constructor(g,f,S,v,C){this.recvStream=g,this.mainTrack=f,this.receiveStreamCollection=S,this.logger=v,this.settings=C,this.removeOtherTracks(f),this.subscribeOnStreamEvents()}get stream(){return this.recvStream.getMediaStream()}dispose(){this.unsubscribeFromStreamEvents(),this.receiveStreamCollection=null,this.mainTrack=null,this.recvStream.dispose()}getId(){return this.recvStream.getId()}getModality(){return this.recvStream.getModality()}getMsi(){return this.recvStream.getMsi()}getMediaStream(){return this.stream}getReceiver(){return this.recvStream.getReceiver()}requestSource(g){return this.recvStream.requestSource(g)}getSourceStreamId(){return this.recvStream.getSourceStreamId()}getSubstreamIndex(){return this.recvStream.getSubstreamIndex()}removeOtherTracks(g){this.settings.onAddTrackRemoveOtherTracks&&this.stream.getTracks().forEach((f=>{f.id!==g.id&&this.stream.removeTrack(f)}))}subscribeOnStreamEvents(){const logEvent=g=>this.logger.safe.info(`${g} track: ${this.mainTrack.id}, stream: ${this.stream.id}`);this.stream.onremovetrack=()=>{logEvent("onremovetrack"),this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onended=()=>{logEvent("onended"),this.settings.removeRecvStreamOnEnded&&this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onmute=()=>logEvent("onmute"),this.mainTrack.onunmute=()=>logEvent("onunmute")}unsubscribeFromStreamEvents(){this.stream.onremovetrack=null,this.mainTrack.onended=null,this.mainTrack.onmute=null,this.mainTrack.onunmute=null}},RA=class{constructor(g){this.startTimestamp=0,this.totalTime=0,this.lastActiveTime=0,this.id=g}},MA=class{constructor(g){this.speakersHistory=[],this.sources=[],this.configProvider=g.configProvider,this.ping=this.setupTimer()}setSources(g=[]){const f=g.map(this.getOrCreateSource.bind(this)),S=this.excludeSources(this.sources,f);f.forEach((g=>{this.isAlreadyActive(g)||this.updateSourceTimestamp(g),this.updateSourceLastActiveTime(g)})),S.forEach((g=>{this.updateTotalTime(g),this.resetStartTimestamp(g)})),this.ping||(this.ping=this.setupTimer())}setOnDominantSpeakerChanged(g){this.callback=g}dispose(){this.clearTimer(),this.sources=null,this.callback=null}excludeSources(g,f){return g.filter((g=>!f.some((f=>g.id===f.id))))}trigger(){if(!this.hasAnyoneSpoken())return void this.clearTimer();const byActivity=(g,f)=>f.totalTime-g.totalTime||f.lastActiveTime-g.lastActiveTime,toSourceId=g=>g.id,g=this.sources.map(this.updateTotalTime).sort(byActivity).map(toSourceId).slice(0,this.configProvider.config.ovcMaxCount);g.length&&!deepEqual(this.speakersHistory,g)&&(this.speakersHistory=g,this.callback&&this.callback(this.speakersHistory,"client")),this.sources.map(this.resetTotalTime).filter(this.isAlreadyActive).forEach(this.updateSourceTimestamp)}isAlreadyActive(g){return!!g.startTimestamp}setupTimer(){return window.setInterval(this.trigger.bind(this),this.configProvider.config.activeSpeaker.timeToPromote)}clearTimer(){this.ping&&(clearInterval(this.ping),this.ping=null)}getOrCreateSource(g){if(this.isExist(g))return this.sourceById(g);{const f=new RA(g);return this.sources.push(f),f}}isExist(g){return this.sources.some((f=>g===f.id))}hasAnyoneSpoken(){return this.sources.some((g=>0!==g.startTimestamp||0!==g.totalTime))}sourceById(g){return this.sources.find((f=>g===f.id))}updateSourceTimestamp(g){g.startTimestamp=Date.now()}updateSourceLastActiveTime(g){g.lastActiveTime=Date.now()}updateTotalTime(g){return g.startTimestamp&&(g.totalTime+=Date.now()-g.startTimestamp),g}resetStartTimestamp(g){return g.startTimestamp=0,g}resetTotalTime(g){return g.totalTime=0,g}},wA=class extends Ht{constructor(g,f){super(),this.configProvider=g,this.logger=f,this.bandwidthEstimationAvailable=!1,this.smoothingWindow=[],this.totalSamples=0,this.isStarted=!1,this.maxCountStatic=this.configProvider.config.ovcMaxCount,this.previousParticipantsCount=0,this.isMcpSrAvailable=!1;const S=window.navigator;this.updateStaticConstraint(S.hardwareConcurrency,this.configProvider.config.ovcAvailableConcurrencyForBiggerGrid,4),this.updateStaticConstraint(S.deviceMemory,this.configProvider.config.ovcMemoryForBiggerGrid,4),this.throttler=new OA(this.logger.createChild("ovcThrottler"),this.configProvider.config.ovcRampDownCooldown,this.configProvider.config.ovcRampUpCooldown)}start(){this.logger.safe.debug("Starting OptimalVideoCountCalculator"),this.isStarted=!0,this.throttler.changed((()=>this.event("calculatorStateChanged").raise(2,{ovc:this.throttler.value,ovcPayload:this.payload})))}stop(){this.isStarted=!1}dispose(){super.dispose(),this.logger.safe.debug("Disposing OptimalVideoCountCalculator"),this.throttler.dispose()}processEstimatedBandwidth(g){this.bandwidthConstrainedOvc=this.getOVCEstimate(g),this.payload={bandwidth:g,reason:0},this.throttler.setValue(this.getOvcValue(),0)}updateParticipantCount(g){if(!this.configProvider||g===this.previousParticipantsCount)return;const f=this.configProvider.config.ovcXLParticipantsCount;g>f&&this.previousParticipantsCount<=f&&(this.maxCountStatic=this.configProvider.config.ovcMaxCountXL),g<=f&&this.previousParticipantsCount>f&&(this.configProvider.config.multiStreamSupported&&this.isMcpSrAvailable?this.maxCountStatic=this.configProvider.config.ovcMaxCountMultiStream:this.maxCountStatic=this.configProvider.config.ovcMaxCount),this.previousParticipantsCount=g,this.payload?.bandwidth&&(this.bandwidthConstrainedOvc=this.getOVCEstimate(this.payload.bandwidth),this.payload.reason=2),this.throttler.setValue(this.getOvcValue(),2)}setPerfConstrainedValue(g){this.perfConstrainedOvc=g,this.logger.safe.info(`Setting perfConstrainedOvc to ${g}`),this.payload&&this.getOvcValue()===g&&(this.payload={reason:1}),this.throttler.setValue(this.getOvcValue(),1)}mcpSourceRequestsAvailable(){this.configProvider.config.multiStreamSupported&&(this.isMcpSrAvailable=!0,this.maxCountStatic===this.configProvider.config.ovcMaxCount&&(this.maxCountStatic=this.configProvider.config.ovcMaxCountMultiStream),this.payload?.bandwidth&&(this.bandwidthConstrainedOvc=this.getOVCEstimate(this.payload.bandwidth),this.payload.reason=2),this.throttler.setValue(this.getOvcValue(),2))}getOVCEstimate(g){this.bandwidthEstimationAvailable||(this.bandwidthEstimationAvailable=this.isStarted&&g>0&&(this.totalSamples++>=this.configProvider.config.ovcIgnoreFirstSamples||Math.floor(g)/this.configProvider.config.ovcBandwidthPerVideoReceiver>=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount));let f=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount;return this.bandwidthEstimationAvailable&&(f=Math.floor(this.sampleSmoothed(g)/this.configProvider.config.ovcBandwidthPerVideoReceiver)),f}getOvcValue(){return Math.max(1,Math.min(this.bandwidthConstrainedOvc??this.maxCountStatic,this.perfConstrainedOvc??this.maxCountStatic,this.maxCountStatic))}sampleSmoothed(g){if(this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples?this.smoothingWindow.shift():this.smoothingWindow.length===this.configProvider.config.ovcSlidingWindowSamples-1&&(this.smoothingWindow=this.smoothingWindow.map((()=>g))),this.smoothingWindow.push(g),this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples){const g=this.smoothingWindow.slice().sort(),f=average(g);return g[g.length-1]-(g[g.length-1]-f*(1-this.configProvider.config.ovcSlidingWindowPercentile))}return g}updateStaticConstraint(g,f,S){g&&g<f&&(this.maxCountStatic=Math.min(this.maxCountStatic,S))}},OA=class extends Ht{constructor(g,f,S){super(g),this.logger=g,this.throttleDownCooldown=f,this.throttleUpCooldown=S,this.wasRampingUp=!0,this.lastUpdateTime=0}get value(){return this.lastValue}setValue(g,f){if(g===this.lastValue)return;const S=g>this.lastValue,v=void 0!==this.lastValue&&S!==this.wasRampingUp?S?this.throttleUpCooldown:this.throttleDownCooldown:-1,C=Date.now();C-this.lastUpdateTime<v&&(2!==f||S)||(void 0!==this.lastValue&&(this.lastUpdateTime=C,this.wasRampingUp=S),this.logger.safe.info(`optimal video receivers count updated ${this.lastValue} -> ${g}, reason: ${f}`),this.lastValue=g,this.raiseChanged())}},DA=class _CPUUsageMetricCollector2{constructor(g,f=30){this.logger=g,this.maxEventNum=f,this.report=[],this.started=!1}isSupported(){return Boolean(window.chrome?.runtime?.connect)}start(){this.isSupported?(this.started=!0,this.logger.debug("Starting collecting CPU metric"),this.port=window.chrome.runtime.connect(_CPUUsageMetricCollector2.extensionID,{name:_CPUUsageMetricCollector2.extensionName}),this.port.onMessage.addListener((g=>{g&&arrayLimitedPush22(this.report,{timeStamp:Date.now(),value:g},this.maxEventNum)}))):this.logger.debug("Chrome runtime is not supported")}stop(){this.port?.disconnect(),this.port=null,this.started=!1}getSamples(){return this.report}getLastSample(){return getLast(this.report)}getCurrentCpuSample(){return new Promise(((g,f)=>{this.started&&g(getLast(this.report)),this.isSupported()||f("Not supported"),this.port=window.chrome.runtime.connect(_CPUUsageMetricCollector2.extensionID,{name:_CPUUsageMetricCollector2.extensionName}),this.port.onMessage.addListener((S=>{this.stop(),S||f("Not supported"),g({timeStamp:Date.now(),value:S})}))}))}clearStats(){this.report=[]}};DA.extensionID="nkeimhogjdpnpccoofpliimaahmaaome",DA.extensionName="processCpu";var NA=DA,kA=class{constructor(g){this.logger=g,this.started=!1}static isSupported(){return void 0!==globalThis.PressureObserver}get cpuState(){return this.currentCpuState}start(){if(this.logger.safe.debug("Starting CPU pressure observer"),this.started)this.logger.safe.debug("CPU pressure observer is already started");else{try{this.cpuObserver=new globalThis.PressureObserver((g=>{g.forEach((f=>{"cpu"===f.source&&this.currentCpuState!==f.state&&(this.logger.safe.debug(`CPU pressure state changed: ${JSON.stringify(g)}`),this.currentCpuState=f.state)}))}),{sampleRate:1})}catch(g){throw this.logger.safe.error(`Error while creating pressure observer: ${g}`),g}this.started=!0,this.cpuObserver?.observe("cpu")}}stop(){this.started=!1,this.cpuObserver?.disconnect()}},LA=class extends Ht{constructor(g,f,S,v){super(),this.statsGatherer=g,this.diagnostics=f,this.configProvider=S,this.logger=v,this.paused=!1,this.started=!1,this.trackInterval=this.configProvider.config.diagnostics.performanceMonitoring.remoteVideoTrackInterval,this.badPerfIds=new Set,this.perfTrackerMap=new Map,this.subs=[],this.rendererFpsCap=40,this.configProvider.config.diagnostics.performanceMonitoring.useComputePressure&&kA.isSupported()&&(this.cpuPressureObserver=new kA(this.logger)),this.configProvider.config.diagnostics.performanceMonitoring.useCpuSample&&(this.cpuMetricCollector=new NA(this.logger,this.configProvider.config.diagnostics.performanceMonitoring.cpuMetricCollector))}start(){this.logger.safe.debug("Starting RemoteVideoPerformanceCalculator"),this.started?this.logger.safe.debug("RemoteVideoPerformanceCalculator already running. Do nothing."):(this.calculatorStrategy=BC.getStrategy(this.configProvider),this.started=!0,this.cpuPressureObserver?.start(),this.subs.push(this.statsGatherer.on("onDiagnosticUpdated",(g=>this.processStats(g)))))}stop(){this.logger.safe.debug("Stopping RemoteVideoPerformanceCalculator"),this.started=!1,this.subs.forEach((g=>{g.dispose()})),this.cpuMetricCollector?.stop(),this.cpuPressureObserver?.stop()}dispose(){this.logger.safe.debug("Disposing RemoteVideoPerformanceCalculator"),this.cleanupMaps(),this.stop()}cleanupMaps(){this.badPerfIds.clear(),this.perfTrackerMap.clear()}async processStats(g){try{if(this.paused)return;if(!g.video?.recv?.length)return;this.configProvider.config.diagnostics.traceLogging&&this.logger.safe.debug("Caught onDiagnosticUpdated: Calculating remote video performance"),g.video?.recv?.forEach((async f=>{const S=f.renderer?.msi;if(!this.perfTrackerMap.has(S)){const g={id:f.mediaEntity?.remoteTrackId,decodeTimeTracker:new Jv(this.trackInterval),macroblockLossTracker:new Jv(this.trackInterval),macroblockMaxLossTracker:0,freezeDurationPercent:0,frameHeight:0,frameWidth:0,rendererFps:new Jv(this.trackInterval),incomingFps:new Jv(this.trackInterval),framesReceived:0,framesDecoded:0,decoder:"",msi:S};this.perfTrackerMap.set(S,g)}const v=this.perfTrackerMap.get(S);if(f.inboundRTP.totalDecodeTime&&f.inboundRTP.framesDecoded){const g=round(f.inboundRTP.totalDecodeTime/f.inboundRTP.framesDecoded*1e3,2);v.decodeTimeTracker.captureSample(g)}const C=f.extensions?.macroblockRateStats?.macroblockRateDecoderLossPercent;v.macroblockLossTracker.captureSample(C),v.macroblockMaxLossTracker=f.extensions?.macroblockRateStats?.macroblockRateMaxDecoderLossPercent,f.extensions?.duration&&(v.freezeDurationPercent=f.extensions?.totalFreezeDuration/f.extensions?.duration*100),v.frameHeight=f.inboundRTP.frameHeight||0,v.frameWidth=f.inboundRTP.frameWidth||0,void 0!==f.extensions?.frameRateDecoded&&void 0!==f.inboundRTP.framesPerSecond&&f.extensions?.frameRateDecoded<=this.rendererFpsCap&&f.inboundRTP.framesPerSecond<=this.rendererFpsCap&&(v.rendererFps.captureSample(f.extensions?.frameRateDecoded),v.incomingFps.captureSample(f.inboundRTP.framesPerSecond)),f.inboundRTP.framesReceived&&f.inboundRTP.framesDecoded&&(v.framesReceived=f.inboundRTP.framesReceived,v.framesDecoded=f.inboundRTP.framesDecoded),v.decoder=f.inboundRTP.decoderImplementation,v.rendererFps.isReportComplete()&&v.incomingFps.isReportComplete()&&v.decodeTimeTracker.isReportComplete()&&(this.paused=!0,await this.checkQuality(v,g.perfCounters,g.video?.recv?.length),this.paused=!1)}))}catch(g){this.logger.error("Failed to processes diagnostics update: "+g)}}async checkQuality(g,f,S){if(!S)return;const v=[];let C;try{C=await(this.cpuMetricCollector?.getCurrentCpuSample())}catch{this.logger.safe.debug("CPU sampling is not supported")}const _={ts:Date.now(),trackId:g.id,decodeTime:g.decodeTimeTracker.getReport(),macroblockLossPercent:g.macroblockLossTracker.getReport(),macroblockMaxLossPercent:g.macroblockMaxLossTracker,freezeDurationPercent:g.freezeDurationPercent,perfCounters:f,cpuUsage:C,rendererFps:g.rendererFps.getReport(),incomingFps:g.incomingFps.getReport(),framesDecoded:g.framesDecoded,framesReceived:g.framesReceived,msi:g.msi,frameHeight:g.frameHeight,decoder:g.decoder};v.push(_);const T=this.calculatorStrategy.checkQuality(g);if(0===T){if(this.logger.safe.debug(`Bad perf detected for msi ${g.msi}: ${JSON.stringify(v)}`),this.configProvider.config.diagnostics.performanceMonitoring.usePerfConstrainedOvc&&!ei.Recv.getNextLowerResolution(g.frameWidth,g.frameHeight)){const g=Math.max(S-1,1);return this.logger.info(`Min resolution reached, decreasing OVC to: ${g}`),this.diagnostics.registerVideoPerformanceEvent(v,1,g),this.event("calculatorStateChanged").raise(2,{ovc:g}),void this.perfTrackerMap.clear()}this.diagnostics.registerVideoPerformanceEvent(v,1),this.event("calculatorStateChanged").raise(1,{msi:g.msi})}2===T&&(this.diagnostics.registerVideoPerformanceEvent(v,0),this.logger.safe.debug(`Good perf detected for msi ${g.msi}: ${JSON.stringify(v)}`),this.event("calculatorStateChanged").raise(0,{msi:g.msi})),this.perfTrackerMap.delete(g.msi)}},FA=class extends Ht{constructor(g,f,S,v){super(),this.statsGatherer=g,this.diagnostics=f,this.configProvider=S,this.logger=v,this.calculators=new Map,this.subs=[]}on(g,f){switch(g){case"onIncomingVideoQualityChanged":this.addCalculator(0),this.startCalculator(0);break;case"onOptimalVideoCountChanged":this.addCalculator(2),this.startCalculator(2)}return this.subscribe({changed:void 0,on:{name:String(g),handler:f}})}addCalculator(g){let f=this.calculators.get(g);if(!f){switch(g){case 0:if(!this.configProvider.config.diagnostics.performanceMonitoring.enableRemoteVideoCalculator)return;f=new LA(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("RemoteVideoPerformanceCalculator"));break;case 2:if(!this.configProvider.config.enableOptimalVideoCount)return;f=new wA(this.configProvider,this.logger.createChild("OptimalVideoCountCalculator"));break;case 1:throw new Error("Not implemented")}this.subs.push(f.on("calculatorStateChanged",((f,S)=>{this.handleChanged(g,f,S)}))),this.calculators.set(g,f)}}startCalculator(g){this.logger.safe.debug(`adding calculator with id ${g}`);const f=this.calculators.get(g);f&&f.start()}stopCalculator(g){this.logger.safe.debug(`stopping calculator with id ${g}`);const f=this.calculators.get(g);f&&f.stop()}processNotification(g,f){switch(g){case"BandwidthNotification":this.calculators.get(2)?.processEstimatedBandwidth(f.bw);break;case"ParticipantCountChanged":this.calculators.get(2)?.updateParticipantCount(f.count);break;case"McpSourceRequestsAvailable":this.calculators.get(2)?.mcpSourceRequestsAvailable();break;default:this.logger.safe.info(`Notification message handler not found for type: ${g}`)}}dispose(){super.dispose(),this.calculators.forEach((g=>{g.dispose()})),this.subs.forEach((g=>{g.dispose()}))}handleChanged(g,f,S){switch(this.logger.info(`calculatorStateChanged  ${f}: calculatorType ${g} ${JSON.stringify(S)}`),g){case 0:if(2===f){this.calculators.get(2)?.setPerfConstrainedValue(S?.ovc);break}this.configProvider.config.diagnostics.performanceMonitoring.enableLowerResolution&&this.event("onIncomingVideoQualityChanged").raise(f,S?.msi);break;case 2:this.event("onOptimalVideoCountChanged").raise(S?.ovc,S?.ovcPayload)}}},xA=M,UA=class{constructor(g){this.configProvider=g,this.outboundNetworkQuality="Good",this.inboundNetworkQuality="Good",this.jitterAccumulator=new Uv(this.configProvider.config.webrtcJitterWindowSize),this.healedRatioAccumulator=new Uv(this.configProvider.config.webrtcHealedRatioWindowSize),this.jitterStateProcessor=new uI(g.config.webrtcJitterLowThreshold,g.config.webrtcJitterHighThreshold,!0,g.config.webrtcJitterSticknessTime),this.lossRateStateProcessor=new uI(g.config.webrtcLossRateLowThreshold,g.config.webrtcLossRateHighThreshold,!0,g.config.webrtcLossRateSticknessTime)}processReport(g){g.audio?.recv?.length&&(this.inboundNetworkQuality=this.processInboundSample((0,xA.last)(g.audio.recv))),g.audio?.send?.length&&(this.outboundNetworkQuality=this.processOutboundSample((0,xA.last)(g.audio.send)))}getInboundNetworkQuality(){return this.inboundNetworkQuality}getOutboundNetworkQuality(){return this.outboundNetworkQuality}processInboundSample(g){const f=this.inboundNetworkQuality,{totalSamplesReceived:S}=g.inboundRTP,{healedRatio:v}=g.extensions??{};null!=v&&this.healedRatioAccumulator.add(v);const C=(0,xA.mean)(this.healedRatioAccumulator.items);return!S||S<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality?f:C&&this.healedRatioAccumulator.isFull?this.determineInboundQualityLevel(C):f}determineInboundQualityLevel(g){const f=this.inboundNetworkQuality,S=this.configProvider.config.webrtcStatNetworkDetectionHysteresis,v=this.configProvider.config.webrtcStatNetworkDetectionBadLevel,C=this.configProvider.config.webrtcStatNetworkDetectionGoodLevel;return g<C-S/2?"Good":g<C+S/2?"Good"===f?"Good":"Poor":g<v-S/2?"Poor":g<v+S/2?"Bad"===f?"Bad":"Poor":"Bad"}processOutboundSample(g){const f=this.outboundNetworkQuality,{packetsSent:S,timestamp:v}=g.outboundRTP,{jitter:C}=g.remoteInboundRTP??{},{lossRate:_}=g.extensions??{};if(!S||S<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return f;null!=C&&this.jitterAccumulator.add(C);const T=(0,xA.mean)(this.jitterAccumulator.items),I=this.jitterAccumulator.isFull?this.jitterStateProcessor.onSample(T,v):"Good",b=_?this.lossRateStateProcessor.onSample(_,v):"Good";return"Good"===I&&"Good"===b?"Good":"Bad"}},VA=M,BA=class{constructor(g){this.configProvider=g,this.speechWindow=new Uv(g.config.webrtcSpeakingWhileMutedDetectionWindow)}processReport(g){if(!g.audio?.send?.length)return!1;const f=g.audio.send[0],{rawInputVolume:S,callIsMuted:v}=f.extensions??{},{audioLevel:C}=f.mediaSource??{},{useAudioAnalyzer:_,webrtcSpeakingWhileMutedDetectionLevel:T}=this.configProvider.config;if(!v)return this.speechWindow.clear(),!1;const I=_?S:C;return null!=I&&this.speechWindow.add(I),!!this.speechWindow.isFull&&(0,VA.mean)(this.speechWindow.items)>T}},HA=class{constructor(g){this.context=g,this.cname=uniqueId()}toLocal(g,f,S){return this.modify({sdpSource:0,sdpType:S},g,f)}toOffer(g,f,S){return this.modify({sdpSource:1,sdpType:"offer"},g,f,S)}toAnswer(g,f,S){return this.modify({sdpSource:1,sdpType:"answer"},g,f,S)}toRemote(g,f,S,v,C=!1){return this.modify({sdpSource:2,sdpType:v,isOrWasProvisional:C},g,f,S)}modify(g,f,S,v){const C=new EE(this.context,S,v,this.cname).build(g),_=deepClone(f);return C.modify(_),_}},$A=class{get sdp(){return this.originalDescription.sdp}set sdp(g){this.originalDescription=new Xs.window.RTCSessionDescription({sdp:g,type:this.originalDescription.type})}get type(){return this.originalDescription.type}set type(g){this.originalDescription=new Xs.window.RTCSessionDescription({sdp:this.originalDescription.sdp,type:g})}constructor(g){this.originalDescription=new Xs.window.RTCSessionDescription(g)}toJSON(){return this.originalDescription.toJSON()}},jA=class{constructor(g,f,S,v,C,_,T,I,b,A,P){this.logger=g,this.configProvider=f,this.diagnostics=S,this.reinvitelessContext=v,this.mediaManager=C,this.audioCodecManager=_,this.ufdManager=T,this.sessionContext=I,this.qualityManager=b,this.streamSendersManager=A,this.callbacks=P,this.negotiationQueue=new zC(this.logger),this.negotiatedModalitiesInternal={},this.disabledModalitiesInternal={},this.initiatorInternal=!1,this.noIceCandidates=!1,this.noRelayIceCandidates=!1,this.isRollbackSupported=!1,this.canTriggerRenegotiation=!0,this.triggerRenegotiationFlag=!1,this.capabilityGatherer=nb.build({global:this.sessionContext.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround),this.mediaContentTypeInternal=getFrom("webrtcMediaContentType",this.sessionContext.config,this.configProvider.config),this.allowedMediaContentTypeInternal=getFrom("webrtcAllowedMediaContentType",this.sessionContext.config,this.configProvider.config).concat(),this.useNGC1webrtcContentType=getFrom("useNGC1webrtcContentType",this.sessionContext.config,this.configProvider.config),this.negotiationCompletedDefer=new dt,this.iceCandidatesDeferred=new dt,this.iceCandidateReceivedInternal=!1,this.initialNegotiationCompleted=!1,this.terminated=!1,this.sessionDescription=V_.build({sdpTransform:new HA(this.sessionContext),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:{unifiedPlanEnabled:!0,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}),this.negotiationEmulator=new mb(this.logger.createChild("negotiationEmulator"),$A,this.sessionDescription,this.negotiationQueue,this.mediaManager),this.negotiationCompletedDefer.promise.catch((()=>{})),this.negotiationCompletedDefer.reject("placeholder")}get configuredModalities(){return this.configuredModalitiesInternal}get offeredModalities(){return this.offeredModalitiesInternal}get disabledModalities(){return this.disabledModalitiesInternal}get negotiatedModalities(){return this.negotiatedModalitiesInternal}get allowedMediaContentType(){return this.allowedMediaContentTypeInternal}get negotiationCompletedPromise(){return this.negotiationCompletedDefer}get iceRelayGatheringStartTime(){return this.iceRelayCandidatesGatherStartTime}get iceCandidatesDefer(){return this.iceCandidatesDeferred}get initiator(){return this.initiatorInternal}set rollbackSupported(g){this.isRollbackSupported=g}set iceCandidateReceived(g){this.iceCandidateReceivedInternal=g}get mediaContentType(){return this.useNGC1webrtcContentType?qt.CONTENT_TYPE.SDP_NGC:this.mediaContentTypeInternal}setInternals(g,f,S){this.logger.safe.debug(`Setting internals tm: ${!!g} tsp: ${!!f} dc: ${!!S}`),this.transceiverManager=g,this.transportStateProvider=f,this.dataChannel=S}terminate(g){this.logger.safe.info(`[${g}] terminating`),this.terminated=!0,this.canTriggerRenegotiation=!1,this.negotiatedModalitiesInternal={},this.resetCandidateGathering(g),this.negotiationCompletedDefer.reject("webRtcSession cleanup"),this.negotiationQueue.dispose()}pauseNegotiations(g=generateCauseId()){const f=new dt;return this.negotiationCompletedDefer.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(f,g)})),f}async configureModalities(g,f,S){const getPendingPromise=async()=>{if(await this.configureModalitiesPromise,!g.audio&&!g.video&&!g.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(g)}`);const v=shallowClone(g),C=shallowClone(this.negotiatedModalities);this.configProvider.config.alwaysNegotiateDataChannel&&(delete v.data,delete C.data);const _=!this.configuredModalities||!areNegotiatedDirectionsFulfilled(v,C);this.logger.safe.info(`[${f}] configureModalities ${stringifyObject2(this.configuredModalities)} -> ${stringifyObject2(g)} (${_?`update from ${stringifyObject2(this.negotiatedModalities)}`:"fulfilled"})`),this.configuredModalities=g,_&&!this.updateSendStreamsReinviteless(f,S)&&(this.configProvider.config.removeSendersOnConfigureModalities&&!isOnHold(this.configuredModalities)&&await this.streamSendersManager.update(g,1,f),this.triggerRenegotiation(!1,f,S))};return this.configureModalitiesPromise=getPendingPromise(),this.configureModalitiesPromise.catch((g=>{this.logger.safe.warn(`[${f}] Error during configuring modalities: ${stringifyObject2(g)}`)})),this.configureModalitiesPromise}async completeNegotiation(g){this.mediaManager.commit();let f=areNegotiatedDirectionsAcceptable(this.configuredModalities,this.negotiatingModalities,this.negotiatedModalities)&&!this.triggerRenegotiationFlag;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${g}] negotiation completed isComplete: ${f} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`);let S=this.negotiatedModalities;if(this.streamSendersManager.pendingStreamsPromise){this.logger.safe.info(`[${g}] Waiting for stream acquisitions to complete...`);const v=await this.streamSendersManager.pendingStreamsPromise;this.streamSendersManager.clearStreamsPromise(),this.logger.safe.info(`[${g}] Stream acquisitions completed: ${stringifyObject2(v)}`),areNegotiatedDirectionsAcceptable(v,this.negotiatingModalities,this.negotiatedModalities)||(this.logger.safe.warn(`[${g}] Some streams were not acquired successfully, considering the negotiation as incomplete`),S=v,f=!1)}return f||this.triggerRenegotiation(!1,g),this.initialNegotiationCompleted=!0,this.negotiationCompletedDefer.resolve(),{isComplete:f,activeModalities:S,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiatorInternal}}async rejectNegotiation(g,f,S=!1){let v;this.mediaManager.rollback(),this.logger.safe.warn(`[${f}] negotiation rejected isComplete: ${!S} error: ${stringifyObject2(g)} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),this.qualityManager.clearPendingCapabilities();const C=removeChangedSendDirection(this.negotiatedModalities,this.negotiatingModalities);this.logger.safe.debug(`[${f}] configured modalities for rollback: ${JSON.stringify(C)}`),this.transceiverManager?.syncTransceivers(C),this.sessionContext.getSmallCallTelemetry()?.setEventType("rejectNegotiation"),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data);const _=isOnHold(C);isOnHold(this.negotiatedModalities)!==_&&await this.streamSendersManager.setHold(_,f),_?this.logger.safe.info(`[${f}] Hold is configured. Not updating streams`):await this.streamSendersManager.update(C,0,f);const T=this.transportStateProvider?.signalingState;if("have-local-offer"===T){v={},this.logger.safe.info(`[${f}] rolling back local description`);try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRollback){v.type="LocalRN",this.logger.safe.info(`[${f}] rolling back using local renegotiation`);const g=[this.callbacks.getRollbackModifier(this.logger)];await this.negotiationEmulator.renegotiate(g,!0),this.logger.safe.info(`[${f}] rolling back using local complete`)}else this.logger.safe.info(`[${f}] rolling back using rollback`),v.type="Rollback",await this.callbacks.setLocalDescription({type:"rollback"})}catch(g){this.logger.safe.error(`[${f}] rollback error: ${stringifyObject2(g)}`),v.error=g}}else if("have-remote-offer"===T){v={};try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRemoteRollback){v.type="RemoteRN",this.logger.safe.info(`[${f}] applying answer for remote renegotiation`);const g=[this.callbacks.getRollbackModifier(this.logger)];await this.negotiationEmulator.renegotiate(g,!0,"remote")}else this.logger.safe.info(`[${f}] rolling back using rollback on remote description`),v.type="Rollback",await this.callbacks.setRemoteDescription({type:"rollback"})}catch(g){this.logger.safe.error(`[${f}] rollback error: ${stringifyObject2(g)}`),v.error=g}}else this.callbacks.hasPC()&&this.logger.safe.error(`[${f}] cannot rollback local description in current state: ${this.transportStateProvider.signalingState}`);return this.canTriggerRenegotiation=!0,this.negotiationCompletedDefer.reject("negotiation rejected"),S&&(this.logger.safe.info(`[${f}] retrying failed negotiation`),this.triggerRenegotiation(!1,f)),{isComplete:!S,activeModalities:C,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiatorInternal,rollback:v}}triggerRenegotiation(g,f=generateCauseId(),S){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${f}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired(f,S)):g&&(this.logger.safe.info(`[${f}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}configureCrypto(g,f){let S=!1;const v=preferSdesSrtp(this.configProvider,f);if(this.offeredDescription){const g=this.offeredDescription.getSrtpInfo();this.diagnostics.offeredSrtp=g,S=!g.dtls||g.sdes&&v}else S=v;return S&&(this.logger.safe.info("configuring peer connection to use sdes"),g.optional.push({DtlsSrtpKeyAgreement:!1})),this.diagnostics.negotiatedSrtp={dtls:!S,sdes:!!S},S?0:1}createOffer(g,f){const S=this.negotiationQueue.add((()=>this.createOfferAsync(g,f)),g);return this.resetNegotiationQueue(g),S}processOffer(g,f){const S=this.negotiationQueue.add((()=>this.processOfferAsync(g,f)),f);return this.resetNegotiationQueue(f),S}async createAnswer(g,f){if((this.sessionContext.config.isPstnCall?!this.configProvider.config.createProvisionalAnswer.enabledPstn:!this.configProvider.config.createProvisionalAnswer.enabled)&&g)return this.logger.safe.info("createAnswer(): Ignoring provisional answer"),{blob:"",contentType:this.mediaContentType};const S=g?"pranswer":"answer",v=g?"createProvisionalAnswerAsync":"createAnswerAsync",C=this.diagnostics.getTimerTracker(v,{first:!0});if(C.mark("start"),this.logger.safe.info(`[${f}] create [${S}] offered: ${JSON.stringify(this.offeredModalities)} configured: ${JSON.stringify(this.configuredModalities)}`),!this.configuredModalities)throw new Error("no configured modalities to create answer for");let _=this.negotiatingModalities=negotiateModalities(this.offeredModalities,this.configuredModalities);await this.callbacks.assurePC(f,C.clone("assurePeerConnectionAsync"));const T=this.transportStateProvider.isWaitingAcceptProvisional;if(this.transportStateProvider.isWaitingAcceptProvisional=g,C.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${f}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.transportStateProvider.signalingState)}`),!this.offeredDescription.isCodecSwitchSupported())try{const g=(await this.capabilityGatherer.getCapabilities(qt.MEDIA_TYPE.audio)).codecs.map((g=>g.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(g)}catch(g){this.logger.safe.error(`[${f}] failed to set primary codec based on audio capability ${stringifyObject2(g)}`)}C.markAndMeasure("assurePeerConnectionAsync","handleCodecSwitchUnsupported"),this.audioCodecManager.prepareForNegotiation(this.initiatorInternal),this.offeredDescription.setModalities(_),await this.detectSendProfileSupport();const I=this.offeredDescription.toRemote(g||T);this.configProvider.config.createProvisionalAnswer.streamsBeforeSetFullRD&&!g&&T&&["have-remote-offer","stable"].includes(this.transportStateProvider.signalingState)&&!this.initialNegotiationCompleted&&(this.logger.safe.info(`[${f}] create [${S}] provisional was applied, requesting streams and activating senders before set remote description is finished`),await this.updateStreamSenders(C,f,g,_)),this.logger.unsafe.info(`[${f}] create [${S}] set remote description', 'negotiated:`,_,"sdp:",I),await this.callbacks.setRemoteDescription({sdp:I,type:"offer"}),C.markAndMeasure("handleCodecSwitchUnsupported","setRemoteDescription"),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data),await this.updateStreamSenders(C,f,g,_),C.markAndMeasure("assurePeerConnectionAsync","assureStreamsAndDataChannel"),C.markAndMeasure("setRemoteDescription","assureStreamsAndDataChannel"),this.callbacks.onTransportInitialized();const b=this.configProvider.config.createProvisionalAnswer.setProperAnswerType?await this.callbacks.createAnswer({type:S}):await this.callbacks.createAnswer();C.markAndMeasure("assureStreamsAndDataChannel","createAnswer"),this.logger.unsafe.info(`[${f}] create [${S}] answer from peer connection type: ${b.type}, sdp:`,b.sdp);const A=this.sessionDescription.createLocalAnswer(b.sdp);this.hasIceCandidates(A)||this.resetCandidateGathering(f),this.callbacks.startWaitingForStreamStart(_),this.setupIceGatheringTimeout(f);const P=A.toLocal();this.logger.unsafe.info(`[${f}] create [${S}] set local description sdp:`,P),await this.callbacks.setLocalDescription({sdp:P,type:this.configProvider.config.createProvisionalAnswer.setProperAnswerType?S:"answer"}),C.markAndMeasure("createAnswer","sLD"),await this.iceCandidatesDeferred.promise,C.markAndMeasure("sLD","candidates");const R=this.sessionDescription.createLocalAnswer(this.callbacks.getLocalDescription().sdp);this.fixLocalDescription(R),R.updateModalities(_),this.checkIceCandidates(R),g&&this.configProvider.config.createProvisionalAnswer.forceRecvonly&&(this.logger.safe.info(`[${f}] create [${S}] munge returned local sdp to recvonly modalities`),R.forceRecvonly());const M=R.toAnswer();this.audioCodecManager.decoder?.setRecvPayloads(R.getPayloadsForMedia(qt.MEDIA_TYPE.audio)),this.checkAudioCodecNegotiated(f),g?this.logger.safe.debug(`[${f}] create [${S}] skip stream senders manager activation`):(this.logger.safe.debug(`[${f}] create [${S}] activating stream senders manager`),await this.streamSendersManager.activate(f)),C.markAndMeasure("candidates","streamSendersManagerActivate"),g?this.logger.safe.debug(`[${f}] create [${S}] skip updating sources and capabilities`):(this.logger.safe.debug(`[${f}] create [${S}] updating sources and capabilities`),this.callbacks.updateLocalMediaSources(),this.applyReceiveCapabilities(f)),_=R.getModalities(),this.reinvitelessContext.enabled&&(_=removeChangedSendDirection(this.negotiatingModalities,_)),areNegotiatedDirectionsAcceptable(this.configuredModalities,this.negotiatingModalities,_)||this.triggerRenegotiation(!0,f),this.negotiatedModalities=_,this.diagnostics.bweType=R.getBweType(),this.logger.unsafe.info(`[${f}] CREATE ANSWER`,"sdp:",M);const w={blob:M,contentType:this.mediaContentType};return this.configProvider.countryCode&&(w.clientLocation=this.configProvider.countryCode),this.reinvitelessContext.enabled&&(w.mediaDescriptions=this.getMediaDescriptions(_)),this.callbacks.setBWSeed(w),C.markAndMeasure("start",v),w}async detectSendProfileSupport(){if(this.configProvider.config.preferredH264VideoSendProfile||this.configProvider.config.preferredH264SharingSendProfile){let g=this.capabilityGatherer;this.configProvider.config.learnCodecSendCapabilitiesFromSenderApi&&(g=nb.build({global:this.sessionContext.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround,!0));const f=await g.getCapabilities("video"),S=this.mediaManager.getMediaEntities().filter((g=>{const f=g.getModality();return f===qt.MEDIA_TYPE.video||f===qt.MEDIA_TYPE.sharing})).filter((g=>g.isEnabled()));for(const g of f.codecs)if(g.sdpFmtpLine&&g.mimeType.toLocaleLowerCase().includes("h264")){const f=g.sdpFmtpLine.match(/profile-level-id=([a-fA-F0-9]{6})/);2===f?.length&&S.forEach((g=>g.addSupportedSendProfile("H264",f[1])))}}}async updateStreamSenders(g,f,S,v){this.transceiverManager.syncTransceivers(v),this.mediaManager.getMediaEntities().forEach((g=>{g.setExtension("midApplied",!0)}));const C=isOnHold(this.negotiatingModalities);if(isOnHold(this.negotiatedModalities)!==C&&(g?.mark("startConfigureHold"),await this.streamSendersManager.setHold(C,f),g?.markAndMeasure("startConfigureHold","configureHold")),C)this.logger.safe.info(`[${f}] Hold is configured. Not updating streams`);else{let C=this.configProvider.config.negotiationParallelStreamAcquisitionCreateAnswer&&!this.initialNegotiationCompleted?2:0;S&&(C=4),await this.streamSendersManager.update(v,C,f),g?.markAndMeasure("configureHold","updateStreams")}}configureBroadcastScenario(g,f){const S=this.configProvider.config.broadcastMode;this.diagnostics.meetingScenario=g.meetingScenario,(S?.prioritizeLayoutOnServer||S?.prioritizeLayoutOnClient||S?.maxSessionBandwidthKbps)&&g.meetingScenario&&S.townHallScenarioNames?.length&&-1!==S.townHallScenarioNames.map((g=>g.toLowerCase())).indexOf(g.meetingScenario.toLowerCase())&&(this.sessionContext.config.isTownHall=!0,this.diagnostics.isTownHall=!0,S?.maxSessionBandwidthKbps&&this.configProvider.overrideMaxSessionBandwidth(S.maxSessionBandwidthKbps)&&(this.logger.safe.info(`Adjusting maxSessionBandwidth for TownHall: ${this.configProvider.mediaConfig.maxBandwidthInKbps}`),this.triggerRenegotiation(!0,f)))}async processAnswer(g,f,S,v=!1){try{const C=g.blob;this.logger.unsafe.debug(S?`[${f}] PROCESS PRANSWER`:`[${f}] PROCESS ANSWER`,"sdp:",C);const _=S?"pranswer":"answer";if(S&&(!acceptProvisionalAnswer(this.sessionContext,v)||"have-local-offer"!==this.transportStateProvider.signalingState))return void this.logger.safe.info(`[${f}] process [${_}] ignored`);this.configureBroadcastScenario(g,f);const T=this.diagnostics.getTimerTracker(S?"processProvisionalAnswerAsync":"processAnswerAsync",{first:!0});T.mark("start");const I=this.sessionDescription.createRemoteAnswer(C);let b=invertModalities(I.getModalities());this.reinvitelessContext.enabled&&(b=removeChangedSendDirection(this.offeredModalities,b)),I.setModalities(b),await this.detectSendProfileSupport();const A=I.toRemote();if(S||(this.useNGC1webrtcContentType||(this.mediaContentType=g.contentType),-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType),isOnHold(b)||(await this.streamSendersManager.update(b,1,f),T.markAndMeasure("start","streamSendersManagerUpdate"),hasSendDirectionality(this.offeredModalities.data)&&!b.data&&this.dataChannel?.disable()),this.negotiatedModalities=b,this.callbacks.updateLocalMediaSources(),this.diagnostics.bweType=I.getBweType()),this.callbacks.onTransportInitialized(),this.logger.unsafe.info(`[${f}] process [${_}] set remote description`,"negotiated:",b,"sdp:",A),T.mark("startSetRemoteDescription"),await this.callbacks.setRemoteDescription({sdp:A,type:_}),T.markAndMeasure("startSetRemoteDescription","setRemoteDescription"),S)return;await this.streamSendersManager.activate(f),T.markAndMeasure("setRemoteDescription","streamSendersManagerActivate"),this.applyReceiveCapabilities(f),this.checkAudioCodecNegotiated(f),this.transceiverManager.syncTransceivers(b),T.markAndMeasure("start","processAnswerAsync")}catch(g){if(S)return void this.logger.safe.warn(`Error thrown during pranswer generation, ignoring: ${stringifyObject2(g)}`);throw g}}async createOfferAsync(g,f){const S=this.diagnostics.getTimerTracker("createOfferAsync",{first:!0});if(S.mark("start"),this.logger.safe.info(`[${g}] create [offer] configured: ${JSON.stringify(this.configuredModalities)}`),this.initiatorInternal=!0,!this.configuredModalities)throw new Error("no configured modalities to create offer for");this.canTriggerRenegotiation=!1,this.negotiatingModalities=this.configuredModalities,await this.callbacks.assurePC(g,S.clone("assurePeerConnectionAsync")),S.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${g}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.transportStateProvider.signalingState)}`),isOnHold(this.negotiatingModalities)&&!isEmpty(this.negotiatedModalities)&&Object.keys(this.negotiatingModalities).forEach((g=>{void 0===this.negotiatedModalities[g]&&delete this.negotiatingModalities[g]})),this.transceiverManager?.assureTransceivers(this.negotiatingModalities),this.dataChannel?.updateDataModalityState(this.negotiatingModalities.data);const v=isOnHold(this.negotiatingModalities);let C;isOnHold(this.negotiatedModalities)!==v&&(S?.mark("startConfigureHold"),await this.streamSendersManager.setHold(v,g),S?.markAndMeasure("startConfigureHold","configureHold")),v?(this.logger.safe.info(`[${g}] Hold is configured. Not updating streams`),C=this.negotiatingModalities):(C=await this.streamSendersManager.update(this.negotiatingModalities,this.configProvider.config.negotiationParallelStreamAcquisitionCreateOffer&&!this.initialNegotiationCompleted?2:0,g),S?.markAndMeasure("configureHold","updateStreams"),this.dataChannel&&this.negotiatingModalities.data&&(C.data=this.negotiatingModalities.data)),S.markAndMeasure("assurePeerConnectionAsync","assureStreamsAndDataChannel"),this.offeredModalities=C,!allowDataChannel(this.sessionContext)&&this.configProvider.config.webrtcNegotiateDisabledDataModality&&!this.offeredModalities[qt.MODALITY.data]&&this.sessionContext.config?.isConference&&(this.offeredModalities[qt.MODALITY.data]=qt.MEDIA_STATE.inactive),this.audioCodecManager.prepareForNegotiation(this.initiatorInternal),this.logger.safe.info(`[${g}] create [offer] offered: ${JSON.stringify(this.offeredModalities)}`);const _=await this.callbacks.createOffer();S.markAndMeasure("assureStreamsAndDataChannel","createOffer"),this.logger.unsafe.info(`[${g}] create [offer] offer from peer connection, sdp: ${_.sdp}`);const T=this.sessionDescription.createLocalOffer(_.sdp);this.hasIceCandidates(T)||this.resetCandidateGathering(g),this.callbacks.startWaitingForStreamStart(C),this.setupIceGatheringTimeout(g);const I=T.toLocal();this.logger.unsafe.info(`[${g}] create [offer] set local description`,"sdp:",I),await this.callbacks.setLocalDescription({sdp:I,type:"offer"}),S.markAndMeasure("createOffer","sLD"),await this.iceCandidatesDeferred.promise,S.markAndMeasure("sLD","candidates");const b=this.sessionDescription.createLocalOffer(this.callbacks.getLocalDescription().sdp);this.fixLocalDescription(b),b.updateModalities(this.offeredModalities),this.checkIceCandidates(b);const A=b.toOffer();this.logger.unsafe.info(`[${g}] CREATE OFFER`,"sdp:",A);const P={blob:A,contentType:this.mediaContentType};""===this.configProvider.mediaConfig.webrtcRequiredFeatures||this.sessionContext.config.isConference||(P.requiredFeatures=this.configProvider.mediaConfig.webrtcRequiredFeatures),this.audioCodecManager.decoder?.setRecvPayloads(b.getPayloadsForMedia(qt.MEDIA_TYPE.audio)),this.configProvider.countryCode&&(P.clientLocation=this.configProvider.countryCode),this.mediaManager.getMediaEntities().forEach((g=>{g.setExtension("midApplied",!0)}));const R=T.isIceRestart();return this.logger.safe.info(`[${g}] ICE restart: ${R}`),this.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription?.isMSRTC()&&R&&!this.sessionContext.config.isConference&&T.getSrtpInfo().sdes&&(P.newOffer=!0),this.reinvitelessContext.enabled&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),P.mediaDescriptions=this.getMediaDescriptions(this.offeredModalities)),f&&(P.negotiationTag=f),this.callbacks.setBWSeed(P),S.markAndMeasure("start","createOfferAsync"),P}async processOfferAsync(g,f){const S=this.diagnostics.getTimerTracker("processOfferAsync",{first:!0});S.mark("start"),this.mediaManager.backup();const v=g.blob;if(this.logger.unsafe.info(`[${f}] process [offer]`,"sdp:",v),this.configProvider.config.webrtcCompareContentTypeInOffer&&!this.useNGC1webrtcContentType&&(assertContentTypeSupported(g.contentType,this.allowedMediaContentType),this.mediaContentType=g.contentType),this.configureBroadcastScenario(g,f),this.offerOriginator&&this.offerOriginator!==g.originator&&this.configProvider.config.rejectIncompatibleOriginator)throw{detail:"mediaContent.originator is different on renegotiation",type:qt.MEDIA_ERROR.incompatibleOriginator};if(this.offerOriginator=g.originator,g.requiredFeatures){const f=this.configProvider.mediaConfig.webrtcRejectedFeatures.split(",");throwIfFeatureNotSupported(g.requiredFeatures.split(","),f)}if(this.initiatorInternal=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(v),this.configProvider.config.multiStreamSupported){const g=getMultiStreamCountFromSdp(v),S=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;this.configProvider.mediaConfig.multiStreamChannelsOffered=g,g<S&&(this.logger.safe.info(`Received ${g} multi stream channels, ${S} channels supported`),this.triggerRenegotiation(!0,f))}this.canTriggerRenegotiation=!1,this.offeredModalities=invertModalities(this.offeredDescription.getModalities()),this.callbacks.hasPC()||(this.configProvider.mediaConfig.isTransportUnbundled?this.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.couldBeUnbundled():this.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.isUnbundled());let C=this.configProvider.config.removeUnsupportedVideoModality?this.offeredModalities:shallowClone(this.offeredModalities);if(hasSendDirectionality(this.offeredModalities.video)||hasReceiveDirectionality(this.offeredModalities.video)||hasSendDirectionality(this.offeredModalities.sharing)||hasReceiveDirectionality(this.offeredModalities.sharing)){const g=this.offeredDescription.getVideoCodecs();try{S.mark("startGetCapabilities");const v=await this.capabilityGatherer.getCapabilities("video");S.markAndMeasure("startGetCapabilities","getCapabilities"),v.codecs.some((f=>g.some((g=>f.mimeType===g&&this.configProvider.config.primaryVideoCodecs.includes(g)))))||(this.logger.safe.warn(`[${f}] offer doesn't contain any supported video codecs`),this.disabledModalities.video=C.video,this.disabledModalities.sharing=C.sharing,delete C.video,delete C.sharing)}catch(g){this.logger.safe.error(`[${f}] failed to get video capability ${stringifyObject2(g)}`)}}return(!allowDataChannel(this.sessionContext)&&(hasSendDirectionality(this.offeredModalities.data)||hasReceiveDirectionality(this.offeredModalities.data))||"Failed"===this.dataChannel?.state)&&(this.logger.safe.info(`[${f}] Supressing data modality as data channel is not possible`),C=shallowClone(C),delete C.data),S.markAndMeasure("start","processOfferAsync"),this.logger.safe.info(`[${f}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(C)}`),C}async startMediaDescriptionsUpdate(g,f){this.dataChannel?.updateDataModalityState(this.reinvitelessRequestedModalities?.data);const S=isOnHold(this.negotiatedModalities),v=isOnHold(this.reinvitelessRequestedModalities);return S!==v&&await this.streamSendersManager.setHold(v,g),v?this.reinvitelessAppliedModalities=this.reinvitelessRequestedModalities:(this.reinvitelessAppliedModalities=await this.streamSendersManager.update(this.reinvitelessRequestedModalities,0,g),this.dataChannel&&this.reinvitelessRequestedModalities.data&&(this.reinvitelessAppliedModalities.data=this.reinvitelessRequestedModalities.data)),this.callbacks.updateLocalMediaSources(),await this.streamSendersManager.activate(g),this.getMediaDescriptions(this.reinvitelessAppliedModalities,f)}async completeMediaDescriptionsUpdate(g){this.logger.safe.info(`[${g}] complete media descriptions update`),this.negotiatedModalities=this.reinvitelessAppliedModalities;const f=this.reinvitelessAppliedModalities,S=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:f,requestedModalities:S}}async rejectMediaDescriptionsUpdate(g,f=!1){this.logger.safe.info(`[${g}] reject media descriptions update`),f&&(this.logger.safe.info(`[${g}] trigger renegotiation after failed media descriptions update`),this.triggerRenegotiation(!1,g));const S=await this.streamSendersManager.update(this.negotiatedModalities,1,g),v=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:S,requestedModalities:v}}getMediaDescriptions(g,f){if(isOnHold(g))return{};const S=[];for(const f of this.mediaManager.getMediaEntities()){if(!f.getExtension("reinviteless"))continue;const v=g[f.getModality()],C={mid:f.getMid(),direction:!f.getLocalTrackId()&&hasSendDirectionality(v)?removeSendDirectionality(v):v};S.push(C)}return{descriptions:S,negotiationTag:f}}updateSendStreamsReinviteless(g,f){if(isEmpty(this.negotiatedModalities)||isOnHold(this.negotiatedModalities)||isOnHold(this.configuredModalities))return!1;this.reinvitelessRequestedModalities=shallowClone(this.negotiatedModalities);for(const[g,f]of Object.entries(this.configuredModalities)){const S=this.mediaManager.getMediaEntitiesByModality(g)[0];S?.getExtension("reinviteless")&&(this.reinvitelessRequestedModalities[g]=f)}return!deepEqual(this.reinvitelessRequestedModalities,this.negotiatedModalities)&&(this.callbacks.onUpdateMediaDescriptionsRequired(g,f),deepEqual(this.reinvitelessRequestedModalities,this.configuredModalities))}checkAudioCodecNegotiated(g){const f=this.audioCodecManager.negotiationCompleted();if(this.audioCodecManager.decoder?.getUnmixedAudioProvider()?.configured){const S=f?"Good":"Bad";this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable",S,"Audio",!0,g)}}fixLocalDescription(g){this.configProvider.config.insertFakeCandidateIfNeeded&&(this.iceCandidateReceivedInternal||!this.iceCandidateReceivedInternal&&this.transportStateProvider.isIceConnected)&&(this.diagnostics.fakeCandidate=g.insertFakeCandidateIfNeeded()),g.fixDataModality()}applyReceiveCapabilities(g){const f=this.mediaManager.getMediaEntities().map((g=>g.getRemoteRecvCapabilities()));this.sessionContext.config?.isConference?this.qualityManager.setPendingCapabilities():this.qualityManager.setMaxCapabilities(f,g)}resetNegotiationQueue(g){this.negotiationCompletedDefer.reject("promise expired"),this.setNegotiationPromise(new dt,g)}setNegotiationPromise(g,f=generateCauseId()){this.terminated||(this.negotiationCompletedDefer=g,this.negotiationQueue.add(this.negotiationCompletedDefer,f))}hasIceCandidates(g){return this.configProvider.mediaConfig.isTransportUnbundled?g.hasUnbundledIceCandidates():g.hasIceCandidates()}checkIceCandidates(g){const f=this.hasIceCandidates(g);if(f===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:qt.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(f){const f=this.hasRelayIceCandidates(g);if(f===this.noRelayIceCandidates){if(!f&&this.transportStateProvider.isIceConnected)return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasRelayIceCandidates(g){return this.configProvider.mediaConfig.isTransportUnbundled?g.hasUnbundledRelayIceCandidates():g.hasRelayIceCandidates()}setupIceGatheringTimeout(g){this.iceRelayCandidatesGatherStartTime=Date.now();const f=this.sessionContext.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!f)return;this.iceCandidatesTimer&&clearTimeout(this.iceCandidatesTimer);const S=this.iceCandidatesDeferred;this.iceCandidatesTimer=window.setTimeout((()=>{this.iceCandidatesTimer=void 0,S.isPending&&(this.logger.safe.warn(`[${g}] ICE candidates gathering terminated due to timeout ${f}`),S.resolve())}),f)}resetCandidateGathering(g){this.logger.safe.info(`[${g}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new dt,this.iceCandidateReceivedInternal=!1}set offeredModalities(g){this.offeredModalitiesInternal=g,this.diagnostics.offeredModalities=g}set negotiatedModalities(g){this.logger.safe.info(`setNegotiatedModalities ${JSON.stringify(g)}`),this.negotiatedModalitiesInternal=g,this.diagnostics.negotiatedModalities=g}set configuredModalities(g){this.configuredModalitiesInternal=g}set mediaContentType(g){this.mediaContentTypeInternal=g}};function acceptProvisionalAnswer(g,f=!1){const S=!g.configProvider.config.acceptProvisionalAnswerFromPstnOnly||f;return g.config.isPstnCall?g.configProvider.config.acceptProvisionalAnswerPstn&&S:g.configProvider.config.acceptProvisionalAnswer}var GA=class{constructor(g){this.mcpConfig=g,this.data={sourceRequestsSignaling:{},sourceRequestsMCP:{},fallbackMCPMessagesCounter:0,sourceRequestsResponses:{},errors:[]}}setRecord(g,f,S){const v={sequenceNumber:f,timestamp:Date.now(),sourceId:S?.sourceId,fmtp:S?.fmtParams};g.records??(g.records=[]),arrayLimitedPush22(g.records,v,this.mcpConfig.storedSRRecordsCount)}recordSignalingOperation(g,f){var S;(S=this.data.sourceRequestsSignaling)[g]??(S[g]={counter:0}),this.data.sourceRequestsSignaling[g].counter++}recordMCPOperation(g,f,S){var v;(v=this.data.sourceRequestsMCP)[g]??(v[g]={counter:0}),this.data.sourceRequestsMCP[g].counter++,this.mcpConfig.verboseTelemetry&&this.setRecord(this.data.sourceRequestsMCP[g],f,S)}recordError(g,f){const S=[Date.now(),f,g];arrayLimitedPush22(this.data.errors,S,this.mcpConfig.storedSRRecordsCount)}recordSignalingOperationDuration(g,f){const S=this.data.sourceRequestsSignaling[g]?.records?.find((g=>g.sequenceNumber===f));S&&(S.duration=Date.now()-S.timestamp)}recordMCPMessageFallback(g,f){if(this.data.fallbackMCPMessagesCounter++,this.mcpConfig.verboseTelemetry){const S=this.data.sourceRequestsMCP[f]?.records?.find((f=>f.sequenceNumber===g));S&&(S.fallback=!0,S.fallbackTimestamp=Date.now())}}recordSrResultReceived(g,f,S){var v;if(this.mcpConfig.verboseTelemetry){const v=this.data.sourceRequestsMCP[S]?.records?.find((g=>g.sequenceNumber===f));v&&(v.duration=Date.now()-v.timestamp,v.result=g)}(v=this.data.sourceRequestsResponses)[g]??(v[g]=0),this.data.sourceRequestsResponses[g]++}getObjectRef(){return this.data}},qA=5,WA=class{constructor(g){this.mcpConfig=g,this.storage={createTime:Date.now(),startedCount:0,stoppedCount:0,clientCapabilities:[],events:[]},this.sourceRequestSenderDiagnostics=new GA(this.mcpConfig)}get getSourceRequestSenderDiagnostics(){return this.sourceRequestSenderDiagnostics}logStarted(){if(this.storage.startedCount++,this.storage.startedCount>qA)return;const g={startedTs:duration(this.storage.createTime),mpCapabilities:{},sentMessages:{},recvMessages:{},sentFailed:0,recvFailed:0,cachedDshReceived:!1};this.storage.events.push(g),this.lastEventConnecting=!0}logStopped(){this.storage.stoppedCount++;const g=this.getCurrentDCSessionEvent();g&&(g.stoppedTs=duration(this.storage.createTime)),this.lastEventConnecting=!1}logSentMsg(g){var f,S;const v=this.getCurrentDCSessionEvent();v&&((f=v.sentMessages)[S=g.type]??(f[S]=0),v.sentMessages[g.type]++)}logReceivedMsg(g){var f,S;this.lastEventConnecting=!1;const v=this.getCurrentDCSessionEvent();v&&((f=v.recvMessages)[S=g.type]??(f[S]=0),v.recvMessages[g.type]++,"dsh"!==g.type||v.handshakeDuration||(v.cachedDshReceived=!0))}logHandshakeStarted(g){const f=this.getCurrentDCSessionEvent();f&&(f.handshakeStartedTs=Date.now()),this.storage.clientCapabilities=g}logHandshakeCompleted(g){const f=this.getCurrentDCSessionEvent();f&&(f.handshakeDuration||(f.handshakeDuration=duration(f.handshakeStartedTs)),f.mpCapabilities.send=g.send_capabilities,f.mpCapabilities.recv=g.receive_capabilities)}logHandshakeFailed(g){const f=this.getCurrentDCSessionEvent();f&&(f.handshakeDuration=duration(f.handshakeStartedTs),f.handshakeFailedWithError=g)}logSentFailed(g){const f=this.getCurrentDCSessionEvent();f&&(f.sentFailed++,f.lastSentFailed={ts:duration(this.storage.createTime),error:g})}logRecvFailed(g){const f=this.getCurrentDCSessionEvent();f&&(f.recvFailed++,f.lastRecvFailed={ts:duration(this.storage.createTime),error:g})}logTimeout(){if(this.storage.startedCount>=qA&&!this.lastEventConnecting)return;const g={timeoutTs:Date.now()},f=this.getCurrentDCSessionEvent();f&&(g.handshakeStartedTs=f.handshakeStartedTs),this.lastEventConnecting&&this.storage.events.pop(),this.storage.events.push(g),this.lastEventConnecting=!1}getReport(){const g=this.sourceRequestSenderDiagnostics.getObjectRef();return this.storage.sourceRequestsReport=g,this.storage}getCurrentDCSessionEvent(){const g=this.storage.events[this.storage.events.length-1];return this.storage.startedCount<=qA&&void 0!==g?.startedTs?g:null}};function duration(g){return Date.now()-g}var zA=4294967292,KA=class extends Ke{constructor(g,f,S){super(),this.dataChannel=g,this.logger=f,this.mcpConfig=S,this.mcpState="Created",this.handshakeTimeout=null,this.telemetryLogger=new WA(this.mcpConfig),this.mcpSupportedFeatures={sourceRequestsEnabled:!1,sourceRequestsResponseEnabled:!1,dominantSpeakerHistoryEnabled:this.mcpConfig?.enableDominantSpeakerHistory,senderSideBandwidthEstimationEnabled:!1},this.subscribeToDataChannel()}getTelemetryLogger(){return this.telemetryLogger}mcpFeaturesSupported(g){return this.mcpSupportedFeatures[g]}switchMcpFeature(g,f){this.logger.warn(`Switching ${g} to ${f}`),this.mcpSupportedFeatures[g]=f}getConfig(){return this.mcpConfig??{}}getMcpState(){return this.mcpState}dispose(){super.dispose(),clearTimeout(this.handshakeTimeout),this.handshakeTimeout=null,this.mcpState="Inactive",this.switchMcpFeature("sourceRequestsEnabled",!1),this.switchMcpFeature("sourceRequestsResponseEnabled",!1)}getTelemetryReport(){return this.logger.debug(`Telemetry ${JSON.stringify(this.telemetryLogger.getReport())}`),this.telemetryLogger.getReport()}async sendMsg(g){return this.sendMsgInternal(g)}async onDCStarted(){this.logger.info("Data channel is started, starting handshake"),this.telemetryLogger.logStarted(),await this.startHandshake()}async onDCStopped(){this.logger.info("Data channel handler is stopped"),this.telemetryLogger.logStopped(),this.mcpState="Inactive"}subscribeToDataChannel(){this.dataChannel.on("onStateChanged",(()=>this.onDataChannelStateChanged())),this.dataChannel.on("onmessage",((g,f,S)=>this.processIncomingData(g,S)))}onDataChannelStateChanged(){switch(this.dataChannel.state){case"Connected":this.onDCStarted();break;case"Closed":case"Destroyed":this.onDCStopped()}}async startHandshake(){try{this.mcpState="Handshaking";const g=[];this.mcpConfig.enableDominantSpeakerHistory&&g.push("dsh"),this.mcpConfig.enableBweNotifications&&g.push("bwe"),this.mcpConfig.enableSourceRequests&&g.push("sr"),this.mcpConfig.enableSendBandwidthNotificationsEnabled&&g.push("ssbwe"),this.telemetryLogger.logHandshakeStarted(g),this.logger.info(`Send syn, client capabilities: ${JSON.stringify(g)}`),await this.sendMsgInternal({type:"syn",client_capabilities:g}),this.handshakeTimeout=window.setTimeout((()=>{this.handshakeTimeout=null,this.telemetryLogger.logTimeout(),this.mcpState="TimedOut",this.switchMcpFeature("sourceRequestsEnabled",!1),this.logger.warn(`Timeout after ${this.mcpConfig.handshakeTimeout}ms, raising onHandshakeTimeout`),this.event("onHandshakeTimeout").raise()}),this.mcpConfig.handshakeTimeout)}catch(g){this.logger.error(`Handshake failed with: ${stringifyObject2(g)}`),this.telemetryLogger.logHandshakeFailed(stringifyObject2(g))}}async sendMsgInternal(g){const f=Array.isArray(g)?g:[g],S=(new TextEncoder).encode(JSON.stringify(f)),v=new Uint8Array(1+S.length);v[0]=1,v.set(S,1);try{await this.dataChannel.sendMessage(18,void 0,v,[zA]);for(const g of f)this.telemetryLogger.logSentMsg(g)}catch(g){throw this.logger.error(`Send failed: ${stringifyObject2(g)}`),this.telemetryLogger.logSentFailed(stringifyObject2(g)),g}}processIncomingData(g,f){if(18!==g)return;if(1!==f[0]){const g=`Unsupported header version ${f[0]}`;return this.logger.info(g),void this.telemetryLogger.logRecvFailed(g)}const S=new DataView(f.buffer,1);let v;try{const g=(new TextDecoder).decode(S);v=JSON.parse(g)}catch(g){return this.logger.error(`Failed to parse received data, error ${stringifyObject2(g)}`),void this.telemetryLogger.logRecvFailed(stringifyObject2(g))}for(const g of v)switch(this.telemetryLogger.logReceivedMsg(g),g.type){case"syn":break;case"ack":this.processAckMsg(g);break;case"bwe":this.processBweMsg(g);break;case"dsh":this.processDshMsg(g);break;case"sr_res":this.processSrResMsg(g);break;default:{const f=`Unsupported msg type ${g.type}`;this.logger.error(f),this.telemetryLogger.logRecvFailed(f)}}}processDshMsg(g){this.mcpConfig.enableDominantSpeakerHistory&&(this.logger.debug(`DSH received: ${JSON.stringify(g)}`),this.event("mpDshChanged").raise(g.history))}processSrResMsg(g){this.mcpConfig.enableSourceRequests&&this.event("mpSrResReceived").raise(g.sequenceNumber,g.result),this.mcpState="Active"}processBweMsg(g){this.mcpConfig.enableBweNotifications&&this.event("mpSendBandwidthChanged").raise(g.bw)}processAckMsg(g){this.telemetryLogger.logHandshakeCompleted(g),this.logger.info(`Ack received: ${JSON.stringify(g)}`),this.switchMcpFeature("dominantSpeakerHistoryEnabled",!(!this.mcpConfig.enableDominantSpeakerHistory||!g.send_capabilities?.includes("dsh"))),this.switchMcpFeature("sourceRequestsEnabled",!(!this.mcpConfig.enableSourceRequests||!g.receive_capabilities?.includes("sr"))),this.switchMcpFeature("sourceRequestsResponseEnabled",!(!this.mcpConfig.enableSourceRequests||!g.send_capabilities?.includes("sr_res"))),this.switchMcpFeature("senderSideBandwidthEstimationEnabled",!(!this.mcpConfig.enableSendBandwidthNotificationsEnabled||!g.receive_capabilities?.includes("ssbwe"))),this.logger.info(`Mcp handshake completed:\n            Dominant speaker history: ${this.mcpSupportedFeatures.dominantSpeakerHistoryEnabled},\n            Source requests: ${this.mcpSupportedFeatures.sourceRequestsEnabled},\n            Source requests response: ${this.mcpSupportedFeatures.sourceRequestsResponseEnabled},\n            Bandwidth estimation response: ${this.mcpSupportedFeatures.senderSideBandwidthEstimationEnabled}`),this.event("mcpHandshakeCompleted").raise(),clearTimeout(this.handshakeTimeout),this.handshakeTimeout=null,this.mcpState="Active"}},JA=class{constructor(g,f,S){this.mediaControlPlane=g,this.sendSignalingMessage=f,this.logger=S,this.pendingSourceRequests=new Map,this.mediaControlPlane&&(this.diagnostics=this.mediaControlPlane.getTelemetryLogger().getSourceRequestSenderDiagnostics,this.mediaControlPlane.on("mpSrResReceived",((g,f)=>this.onMsgReceived(g,f))))}mapToSignalingOperation(g){switch(g){case"ApplyChannelParametersSourceRequest":case"ApplyChannelParametersVideoCapabilities":return 0;case"ControlVideoStreaming":return 1;default:return this.logger.error("Unknown send operation"),null}}send(g,f,S,v){switch(g){case"ApplyChannelParametersSourceRequest":return this.sendMcpMessage(g,f,S,v);case"ApplyChannelParametersVideoCapabilities":case"ControlVideoStreaming":return this.sendSignalingMessage?(this.diagnostics?.recordSignalingOperation(g),this.sendSignalingMessage(this.mapToSignalingOperation(g),f)):Promise.reject(new Error("no signaling session"));default:return this.logger.warn(`Unable to send message reason: Operation unknown ${g}`),Promise.reject(new Error("Unable to send message"))}}setResendingMechanism(g,f,S,v){const C=window.setTimeout((()=>{this.logger.warn(`Timed out message ${g}, sending message through signaling`),this.resendPendingMessageThroughSignaling(g,v)}),this.mediaControlPlane?.getConfig().sourceRequestsMessagesTimeout);this.pendingSourceRequests.set(g,{sequenceNumber:g,timeoutId:C,deferred:f,message:S,operation:v})}isAllowedToSendMcpMessage(){if(!this.mediaControlPlane)return!1;const g=this.mediaControlPlane.getMcpState(),f=this.mediaControlPlane.getConfig();return"Created"!==g&&("Handshaking"===g?f.sendBeforeAck&&f.enableSourceRequests:"Active"===g&&this.mediaControlPlane.mcpFeaturesSupported("sourceRequestsEnabled"))}isResendingMechanismRequired(g){return this.mediaControlPlane.getConfig().setResendingMechanism&&"ApplyChannelParametersSourceRequest"===g}async sendMcpMessage(g,f,S,v){if(this.isAllowedToSendMcpMessage()){const C=new dt;this.isResendingMechanismRequired(g)&&this.setResendingMechanism(S,C,v,g);try{return this.diagnostics.recordMCPOperation(g,S,f.controlVideoStreaming?.controlInfo),await this.mediaControlPlane.sendMsg(f),this.logger.info(`Sending ${f.type} by MCP sequenceNumber:${S}`),this.isResendingMechanismRequired(g)?C.promise:Promise.resolve()}catch(f){const v=stringifyObject2(f);this.diagnostics.recordError(v,S),this.logger.error(`sendMsgInternal failed with error: ${v}`),this.isResendingMechanismRequired(g)&&this.clearPendingSourceRequestTimeout(S)}}if(!this.sendSignalingMessage)throw new Error("no signaling session");return this.diagnostics?.recordSignalingOperation(g),this.logger.info(`Sending SR by signaling sequenceNumber:${S}`),this.sendSignalingMessage(this.mapToSignalingOperation(g),v)}async resendPendingMessageThroughSignaling(g,f){this.diagnostics.recordMCPMessageFallback(g,f);const S=this.pendingSourceRequests.get(g);try{this.diagnostics.recordSignalingOperation(S.operation),await this.sendSignalingMessage(this.mapToSignalingOperation(S.operation),S.message),S.deferred.resolve()}catch{this.logger.warn(`Failed to resend source request via signaling ${g}`),S.deferred.reject(new Error("Sending source request failed via signaling"))}finally{this.clearPendingSourceRequestTimeout(g)}}clearPendingSourceRequestTimeout(g){const f=this.pendingSourceRequests.get(g);f&&(this.pendingSourceRequests.delete(g),clearTimeout(f.timeoutId))}onMsgReceived(g,f){this.logger.info(`Received SR result: ${f} for sequenceNumber: ${g}`);const S=this.pendingSourceRequests.get(g);if(S){switch(this.diagnostics.recordSrResultReceived(f,g,S.operation),f){case"ok":case"duplicate":case"out_of_order":S.deferred.resolve();break;default:S.deferred.reject(`SequenceNumber: ${g} failed with ${f}!`)}this.clearPendingSourceRequestTimeout(g)}else this.logger.warn(`No pending SR found for sequenceNumber: ${g}`)}},YA=0,QA=class _WebRtcSession2{constructor(g,f,S){this.context=g,this.callId=f,this.callback=S,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc2-"+ ++YA),this.videoFeatureManager=new xb(this.logger.createChild("VFM")),this.ufdManager=this.context.getUfdManager(),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.capabilityGatherer=nb.build({global:this.context.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround),this.reinvitelessContext=makeReinvitelessContext(this.context.config.reinvitelessConfig,this.multiParty),this.iceHostCandidateOnly=this.multiParty&&getFrom("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new CE({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:this.multiParty,reinviteltessContext:this.reinvitelessContext}),this.receiveStreamCollection=new MT({streamAdded:g=>this.streamAdded(g),streamRemoved:g=>this.streamRemoved(g)}),this.diagnostics=this.context.diagnostics,this.qmDiagnostics=this.diagnostics.newQualityManagerDiagnostics(),this.statsGatherer=new JI(this.logger.createChild("stats"),this.configProvider,this.diagnostics,this.mediaManager,this.multiParty),this.networkQualityDiagnostics=new UA(this.configProvider),this.speechDetectionDiagnostics=new BA(this.configProvider),this.qualityManager=new _b(this.logger.createChild("qm"),{scalingEnabled:this.configProvider.config.webrtcVideoScaling,customBwEstimationEnabled:this.configProvider.config.webrtcEnabledCustomBwEstimationForVideo},this,this.statsGatherer,this.qmDiagnostics,this.configProvider),this.activeSpeakerManager=new RT(this.callback.onContributingSourcesChanged,this.callback.onDominantSpeakerChanged,this.logger.createChild("ActiveSpeakerManager"),this.diagnostics.dshDiagnostics),this.wasConnected=!1,this.isAudioInputMuted=this.context.config.muted,this.isAudioOutputMuted=!1,this.relayCandidateGathered=!1,this.iceDisconnectedTimer=null,this.statisticsReport=Promise.resolve({type:"WebRtcMediaStats",data:{}}),this.terminated=!1,this.dtmfSender=Db.build({logger:this.logger,configProvider:this.configProvider}),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new qy(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:g=>this.streamsChangedListener=g},this.diagnostics.newSubscriptionManagerDiagnostics()),this.remoteVideoResolutionManager=new Tb(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.statsGatherer,this.diagnostics),this.remoteVideoManager=new Rb(this.logger.createChild("RemoteVideoManager"),this.configProvider,this.statsGatherer,this.diagnostics,this.remoteVideoResolutionManager,this.context.maContext.domOverrides),this.encStreamsManager=new Ca(this.configProvider,this.context.maContext.getEncodedStreamsWorkerProvider?.(),this.logger.createChild("EncodedStreamsManager")),this.streamSendersManager=new AA(this.mediaManager,this.logger.createChild("SSM"),this.context.callDeviceManager,this.configProvider,this.context.config,this.statsGatherer,this.diagnostics,this.qmDiagnostics,this.multiParty,this.encStreamsManager,this.videoFeatureManager),this.hwSilent=!1,this.deviceManagerSubs=[],this.isMuteHold=!1,this.rawIncomingAudioStreamManager=new es(this.logger.createChild("rawIncomingAudioStream")),this.useNullAudioStream=!1,this.audioCodecManager=new Ua(this.encStreamsManager,this.logger,this.configProvider),this.perfMonitorSubs=[],this.performanceMonitor=new FA(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("PerformanceMonitor")),this.negotiation=new jA(this.logger.createChild("negotiation"),this.configProvider,this.diagnostics.newNegotiationDiagnostics(this.statsGatherer.sessionInfo),this.reinvitelessContext,this.mediaManager,this.audioCodecManager,this.ufdManager,this.context,this.qualityManager,this.streamSendersManager,{onNegotiationRequired:(g,f)=>this.callbacks.onNegotiationRequired?.(g,f),onUpdateMediaDescriptionsRequired:(g,f)=>this.callbacks.onUpdateMediaDescriptionsRequired?.(g,f),updateLocalMediaSources:this.updateLocalMediaSources.bind(this),assurePC:this.assurePeerConnectionAsync.bind(this),hasPC:()=>!!this.peerConnection,createOffer:g=>this.peerConnection.createOffer(g),createAnswer:g=>this.peerConnection.createAnswer(g),setLocalDescription:g=>this.peerConnection.setLocalDescription(g),getLocalDescription:()=>this.peerConnection.localDescription,setRemoteDescription:g=>this.peerConnection.setRemoteDescription(g),setBWSeed:this.setBWSeed.bind(this),onTransportInitialized:()=>this.callbacks.onTransportInitialized(),startWaitingForStreamStart:g=>{this.statsGatherer.startWaitingForStreamStart(g)},getRollbackModifier:g=>new DT(this.peerConnection,this.configProvider,g)}),this.streamConfigurationHandler=new kb(this.logger,this.negotiation.negotiationEmulator,this.qualityManager,this.qmDiagnostics,this.configProvider,this.statsGatherer),this.pauseNegotiations=this.negotiation.pauseNegotiations.bind(this.negotiation),this.configureModalitiesAsync=this.negotiation.configureModalities.bind(this.negotiation),this.createOfferAsync=this.negotiation.createOffer.bind(this.negotiation),this.processOfferAsync=this.negotiation.processOffer.bind(this.negotiation),this.createAnswerAsync=this.negotiation.createAnswer.bind(this.negotiation),this.processAnswerAsync=this.negotiation.processAnswer.bind(this.negotiation),this.completeNegotiationAsync=this.negotiation.completeNegotiation.bind(this.negotiation),this.rejectNegotiationAsync=this.negotiation.rejectNegotiation.bind(this.negotiation),this.startMediaDescriptionsUpdateAsync=this.negotiation.startMediaDescriptionsUpdate.bind(this.negotiation),this.completeMediaDescriptionsUpdateAsync=this.negotiation.completeMediaDescriptionsUpdate.bind(this.negotiation),this.rejectMediaDescriptionsUpdateAsync=this.negotiation.rejectMediaDescriptionsUpdate.bind(this.negotiation),this.statsGatherer.on("onDiagnosticUpdated",(g=>this.processStatsReport(g))),this.statsGatherer.on("onStatisticsChanged",(g=>this.processLegacyStats(g))),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.negotiation.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((g,f,S)=>this.requestSource(g,f,S))),this.setSubsForSubscriptionManager(),this.setSubsForStreamManagerEvents(),this.configProvider.mediaConfig.maxBandwidthInKbps&&(this.statsGatherer.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.diagnostics.maxSessionBandwidth=this.configProvider.mediaConfig.maxBandwidthInKbps),this.createAudioRenderer(),this.setSubsForDeviceManager(),this.context.callDeviceManager.isVirtualDeviceEnabled&&this.setupCallDeviceManagerSubs(),this.configProvider.config.enableActiveSpeakerBasedDSH&&this.activeSpeakerManager.setStrategy(new MA({configProvider:this.configProvider})),this.perfMonitorSubs.push(this.performanceMonitor.on("onIncomingVideoQualityChanged",((g,f)=>{this.onIncomingVideoQualityChanged(g,f)}))),this.configProvider.config.webrtcVideoScaling&&(this.perfMonitorSubs.push(this.performanceMonitor.on("onOptimalVideoCountChanged",((g,f)=>{this.onOptimalVideoCountChanged(g,f)}))),this.onOptimalVideoCountChanged(this.configProvider.config.nonEstimatedDefaultVideoReceiversCount)),this.configProvider.config.setBWSeed&&(this.bandwidthCache=new oC(this.configProvider)),this.diagnostics.reinvitelessContext=this.reinvitelessContext,this.multiParty&&this.configProvider.config.enableVideoFeatureManager&&this.videoFeatureManager.manageFeatureSupport((()=>{if(this.detectVideoFeatures(),this.configProvider.config.enableDevtoolsAPI){const g=window?.webMA;g?.initVideoFeatures&&g.initVideoFeatures(this.videoFeatureManager)}}))}initializeMediaControlPlane(g){const f=this.dataChannel.getDataChannel(g);f?(this.mediaControlPlane=new KA(f,this.logger.createChild("MediaControlPlane"),this.configProvider.config.mediaControlPlaneConfig),this.mediaControlPlane.on("mpSendBandwidthChanged",(g=>{this.performanceMonitor.processNotification("BandwidthNotification",{bw:g}),this.bandwidthCache?.saveSeed(g),this.statsGatherer.addReportedReceiveBandwidth(g),this.diagnostics.addReportedReceiveBandwidth(g)})),this.mediaControlPlane.on("mcpHandshakeCompleted",(()=>{this.callback.onUpdateSignalingDSHMessageSubscription(!this.mediaControlPlane.mcpFeaturesSupported("dominantSpeakerHistoryEnabled")),this.mediaControlPlane.mcpFeaturesSupported("dominantSpeakerHistoryEnabled")&&this.diagnostics.dshDiagnostics.setCurrentActiveStrategy("server"),this.mediaControlPlane.mcpFeaturesSupported("sourceRequestsEnabled")&&(this.subscriptionManager.mcpSourceRequestsAvailable(),this.notifyStreamsChanged()),this.mediaControlPlane.mcpFeaturesSupported("senderSideBandwidthEstimationEnabled")&&this.configProvider.config.specCompliantSimulcast.enableSimulcastLayoutControlStrategy&&this.videoFeatureManager.get("Video").toggleServer(0,!0)})),this.mediaControlPlane.on("onHandshakeTimeout",(()=>{this.configProvider.config.enableSignalingDSHFallback&&this.callback.onUpdateSignalingDSHMessageSubscription(!0)})),this.mediaControlPlane.on("mpDshChanged",(g=>{this.activeSpeakerManager.onDominantSpeakerHistoryChanged(g,"server")}))):this.logger.safe.error(`[${g}] Unable to initialize MediaControlPlane due to datachannel creation failure`)}getMediaControlPlaneInstance(){return this.mediaControlPlane}getAcceptedTypes(){return this.negotiation.allowedMediaContentType}clone(g,f){const S=shallowClone(this.context);S.config=shallowClone(this.context.config),S.config.webrtcMediaContentType=this.negotiation.mediaContentType,S.config.webrtcAllowedMediaContentType=this.negotiation.allowedMediaContentType,S.configProvider=f,S.diagnostics=this.context.diagnostics?.newNativeSession(!1),g?(S.config.isConference=!0,S.config.isPstnCall=!1):(S.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(S.config.webrtcIceGatheringTimeoutIncreased=!0));const v=new _WebRtcSession2(S,this.callId,this.callback);return this.useNullAudioStream&&v.useNullAudioStreamClient(),this.relayManagerProvider&&(v.relayManagerProvider=this.relayManagerProvider),v.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,v}async setCallConstraints(g,f){const S=this.configProvider.setCallConstraints(g);if(this.logger.safe.info(`[${f}] Setting call constraints ${JSON.stringify(S)}, enableDynamicCallConstraints: ${this.configProvider.config.enableDynamicCallConstraints}`),this.configProvider.config.enableDynamicCallConstraints)try{await this.streamSendersManager.applyCallConstraints(f),this.configProvider.addCallConstraintsTelemetryEvent(S,"applied")}catch(g){throw this.logger.safe.error(`Error while applying constraints: ${g}`),g}else this.configProvider.addCallConstraintsTelemetryEvent(S,"applied");return S}setInternals(g,f){this.logger.safe.info(`[${f}] Setting internals from previous session`),this.diagnostics.commitNativeSession(),g.subscriptionManager&&(this.subscriptionManager?.dispose(),this.subscriptionManager=g.subscriptionManager,this.subscriptionManager.setDiagnostics(this.diagnostics.newSubscriptionManagerDiagnostics()),this.subscriptionManager.setStreamProvider({getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:g=>this.streamsChangedListener=g}),this.subscriptionManager.setLogger(this.logger.createChild("subs")),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),g.audioRenderer&&(g.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=g.audioRenderer),g.remoteVideoManager?.moveRenderers(this.remoteVideoManager),g.rawIncomingAudioStreamManager&&this.rawIncomingAudioStreamManager.updateHandlers(g.rawIncomingAudioStreamManager.handlerMap),this.audioRenderer.getStream()&&this.rawIncomingAudioStreamManager.streamChanged(this.audioRenderer.getStream())}setSubsForDeviceManager(){const g=this.getVideoDeviceManager();this.configProvider.config.enablePlayVideoOnStreamUnmuteWorkaround&&this.deviceManagerSubs.push(g.on("onAudioStreamMuted",(f=>{f||(this.remoteVideoManager.playVideo(),g.getLocalVideoRenderers().forEach((g=>g.playVideo())))})))}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(g=>this.statsGatherer.setSubscribedTrackIds(g))),this.subscriptionManager.on("onTrackSsrcChanged",(g=>this.statsGatherer.setSubscribedTrackSsrc(g))),this.subscriptionManager.on("onSubscriptionChanged",((g,f,S,v,C,_)=>this.onSubscriptionChanged(g,f,S,v,C,_))),this.subscriptionManager.on("onSubscriptionFailed",((g,f,S,v,C)=>this.statsGatherer.addSubscriptionEvent(g,f,S,v,C)))]}onSubscriptionChanged(g,f,S,v,C,_){f===qt.MODALITY.video&&(2===g&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount()),3===g&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount())),this.statsGatherer.addSubscriptionEvent(g,f,S,v,null,C,_)}setSubsForStreamManagerEvents(){this.streamSendersManager.on("onSendStreamChanged",((g,f)=>{this.statsGatherer.updateSendStream(g,f),g?.hasAudio()&&this.diagnostics.setAudioSendStream(g,f),this.diagnostics.setPresentationAudioOnScreenSharing(g,f)})),this.streamSendersManager.on("onVideoCaptureFreeze",(g=>{this.transportStateProvider.isConnected&&!this.transportStateProvider.isWaitingAcceptProvisional&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",g?"Bad":"Good","Video")})),this.streamSendersManager.on("onMaxVideoSendCapabilitiesChanged",((g,f)=>this.onMaxVideoSendCapabilitiesChanged(g,f))),this.streamSendersManager.on("onBandwidthAllocationChanged",(g=>this.onSendBandwidthChanged(g)))}move(g,f){this.logger.safe.info(`[${f}] moving to new session`),g.setInternals({subscriptionManager:this.subscriptionManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager,rawIncomingAudioStreamManager:this.rawIncomingAudioStreamManager},f),g.muteHold(this.isMuteHold,f),this.isAudioInputMuted?g.muteInputAsync(f):g.unmuteInputAsync(f),this.isAudioOutputMuted?g.muteOutputAsync(f):g.unmuteOutputAsync(f),this.subscriptionManager=null,this.audioRenderer=null,this.rawIncomingAudioStreamManager=null,this.callbacks.onTerminated=null}setMute(g,f,S){this.logger.safe.info(`[${S}] call setMute for ${g} with mute state ${f}`),this.streamSendersManager.setMuted(g,f,S),this.processLegacyStats(this.statsGatherer.getLastStatistics())}getConfiguredModalities(){return this.negotiation.configuredModalities}getDisabledModalities(){return this.negotiation.disabledModalities}createAudioElement(g){this.configProvider.config.devices.setSinkImmediately&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),this.audioRenderer.assureAudioElement(g)}useNullAudioStreamClient(){this.useNullAudioStream=!0,this.streamSendersManager.useNullAudioStreamClient()}createRemoteRenderer(g){return this.remoteVideoManager.createRenderer(g,this.subscriptionManager,this.logger)}getStatsAsync(g){if(this.statsGatherer&&!this.statsGatherer.isDisposed){if(this.audioCodecManager){const g=this.audioCodecManager.getSessionEvents();this.statsGatherer.sessionInfo.setAudioCodecEvents(g),this.diagnostics.audioCodecEvents=g}this.statisticsReport=this.statisticsReport.then((()=>this.statsGatherer.getReport(g))).catch((g=>(this.logger.safe.error(`getting statistics should never fail: ${g.error}`),g.partialReport)))}return this.statisticsReport}getLastKnownStats(g){return this.statsGatherer.getReport(!1,g)}muteHold(g,f){this.logger.safe.info(`[${f}] set muteHold state ${g}`),this.isMuteHold=g;const S=[qt.MODALITY.audio,qt.MODALITY.video,qt.MODALITY.sharing].filter((g=>hasSendDirectionality(this.negotiation.negotiatedModalities[g])&&(g!==qt.MODALITY.audio||!this.isAudioInputMuted)));for(const v of S)this.setMute(modalityToMediaType(v),g,f)}async muteInputAsync(g){this.isAudioInputMuted=!0,this.setMute("Audio",!0,g)}async unmuteInputAsync(g){this.isAudioInputMuted=!1,this.setMute("Audio",!1,g)}async muteOutputAsync(g){return this.isAudioOutputMuted=!0,this.audioCodecManager.decoder?.disableStreamsMixer(!0),this.audioRenderer?.setMuted(!0,g)}async unmuteOutputAsync(g){return this.isAudioOutputMuted=!1,this.audioCodecManager.decoder?.disableStreamsMixer(!1),this.audioRenderer?.setMuted(!1,g)}async getSpeakerVolume(g){return this.audioRenderer?.getSpeakerVolume(g)||0}async setSpeakerVolume(g,f){return this.audioRenderer?.setSpeakerVolume(g,f)}sendDtmf(g){return this.dtmfSender.sendDtmf(this.peerConnection,g)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}onDeviceEvent(g){this.statsGatherer.onDeviceEvent(g)}deviceSelectionChanged(){this.peerConnection&&this.audioRenderer?.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId())}async terminate(g,f,S=!0){this.logger.safe.info(`[${g}] terminate`),this.statsGatherer.setTerminated(),this.diagnostics.terminate(),this.perfMonitorSubs.forEach((g=>g?.dispose())),this.performanceMonitor.dispose(),this.terminated=!0,this.negotiation.terminate(g),await(this.audioCodecManager.decoder?.storeApiRecording()),this.rawIncomingAudioStreamManager?.dispose(),this.remoteVideoManager.dispose(),this.dataChannel&&(this.dataChannel.dispose(),this.dataChannel=null),this.logger.safe.info(`[${g}] reset peer connection`),this.contributingSources?.dispose(),this.activeSpeakerManager.dispose(),this.qualityManager?.dispose(),this.qualityManager=null,this.audioRenderer?.dispose(),this.dtmfSender?.dispose(),this.dtmfSender=null,this.streamSendersManager?.dispose(),this.streamSendersManager=null,this.transceiverManager=null,this.encStreamsManager.dispose(),this.receiveStreamCollection.clear(),this.transportStateProvider?.dispose(),this.transportStateProvider=null,this.audioCodecManager.dispose(),this.mediaManager.reset(),this.mediaControlPlane?.dispose(),this.peerConnection?.close(),this.peerConnection=null,this.negotiation.negotiationEmulator.configure(null),this.peerConnectionPromise=null,this.subscriptionManagerSubs.forEach((g=>g.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.deviceManagerSubs.forEach((g=>g.dispose())),this.callDeviceManagerSub?.dispose(),this.clearIceDisconnectedTimer(),this.callbacks.onTerminated&&this.callbacks.onTerminated();try{S&&await this.getStatsAsync(!1)}catch(f){this.logger.safe.error(`[${g}] Error while gathering stats ${stringifyObject2(f)}`)}finally{this.statsGatherer.dispose()}}getIncomingRawAudioStream(g){this.logger.info("IRawStream for incoming audio stream requested");const f=this.audioRenderer.getStream();return this.rawIncomingAudioStreamManager.createIRawStreamClient(f,g)}getUnmixedAudioProvider(){return this.audioCodecManager.decoder?.getUnmixedAudioProvider()}configureSpatialAudio(g,f){this.configProvider.mediaConfig.spatialAudioEnabled=g,this.audioCodecManager.configureSpatialAudio(g,f)||this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable","Bad","Audio",!0,f)}setParticipantSpatialAudioPositions(g,f){if(!this.audioCodecManager?.decoder||!this.getUnmixedAudioProvider()?.configured)throw this.logger.safe.error(`[${f}] setParticipantSpatialAudioPositions is called while MUCH audio decoder is not created or not enabled`),"setParticipantSpatialAudioPositions not allowed";this.audioCodecManager.decoder?.setParticipantSpatialAudioPositions(g)}processNotification(g,f){"McpSourceRequestsAvailable"===g&&(this.subscriptionManager.mcpSourceRequestsAvailable(),this.notifyStreamsChanged()),"DominantSpeakerInfo"===g&&this.activeSpeakerManager.onDominantSpeakerHistoryChanged(f.previousDominantSpeakerHistory,"signaling"),"ControlVideoStreaming"===g&&this.streamConfigurationHandler.handleMessage(f),this.performanceMonitor.processNotification(g,f)}processStatsReport(g){try{if(this.remoteVideoManager.processStatsReport(g),this.configProvider.config.diagnostics.features.useNewNetworkUFD){this.networkQualityDiagnostics.processReport(g);const f=this.networkQualityDiagnostics.getInboundNetworkQuality();this.ufdManager.signalEvent("NetworkRecvQuality",f);const S=this.networkQualityDiagnostics.getOutboundNetworkQuality();this.ufdManager.signalEvent("NetworkSendQuality",this.isAudioInputMuted?"Good":S)}this.ufdManager.signalEvent("DeviceSpeakWhileMuted",this.speechDetectionDiagnostics.processReport(g)?"Bad":"Good"),this.streamSendersManager.onDiagnosticUpdated(g);for(const f of this.getVideoDeviceManager().getLocalVideoRenderers())f.onDiagnosticUpdated(g)}catch(g){this.logger.error("Failed to processes diagnostics update: "+g)}}processLegacyStats(g){g&&(this.remoteVideoManager.processLegacyStats(g),this.hwSilent!==g.audioHwSilent&&(this.hwSilent=g.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.configProvider.config.diagnostics.features.useNewNetworkUFD||(this.ufdManager.signalEvent("NetworkRecvQuality",g.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:g.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",this.isAudioInputMuted?"Good":g.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:g.networkSendLevel})),this.streamSendersManager.onStatisticsChanged(g))}assurePeerConnectionAsync(g,f){return this.peerConnectionPromise??(this.peerConnectionPromise=this.getPeerConnectionPromise(g,f)),this.peerConnectionPromise}async getPeerConnectionPromise(g,f){if(!this.relayManagerProvider)throw new Error("relay manager provider is not set!");this.logger.safe.info(`[${g}] fetching relay details from RelayManager...`);const S={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};f.mark("startQueryRelaysAsync");const v=await this.relayManagerProvider.getRelayManager().queryRelaysAsync(S);if(f.markAndMeasure("startQueryRelaysAsync","queryRelaysAsync"),this.terminated)throw new Error("session already disposed");const C={optional:[]},_=createIceServers(v,this.configProvider.config),T=this.negotiation.configureCrypto(C,this.context.config.isPstnCall);this.configureCpuThreshold(C),this.logger.safe.info("create peer connection");const I="unified-plan",b=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle";try{this.peerConnection=new Xs.window.RTCPeerConnection({iceServers:_,rtcpMuxPolicy:"require",iceTransportPolicy:this.configProvider.getIceTransportPolicy(),iceCandidatePoolSize:this.configProvider.config.iceCandidatePoolSize,bundlePolicy:b,sdpSemantics:I,audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===T,encodedInsertableStreams:!!this.configProvider.config.useInsertableStreams},C)}catch(g){throw g.code===DOMException.INVALID_STATE_ERR&&this.ufdManager.signalEvent("NoNetwork","Bad"),g}const A=this.peerConnection;this.negotiation.rollbackSupported=1===T&&this.context.configProvider.userAgentConfig.isBrowserRollbackSupported,this.negotiation.negotiationEmulator.configure(A),this.statsGatherer.initialize(A),this.statsGatherer.sessionInfo.setIceServers(_),this.statsGatherer.sessionInfo.setIceTransportPolicy(this.configProvider.getIceTransportPolicy()),this.statsGatherer.sessionInfo.setSdpSemantics(I),this.statsGatherer.sessionInfo.setBundlePolicy(b),this.diagnostics.iceServers=_,this.diagnostics.iceTransportPolicy=this.configProvider.getIceTransportPolicy(),this.diagnostics.sdpSemantics=I,this.diagnostics.bundlePolicy=b,await this.checkVideoCodecsSupport(),f.markAndMeasure("queryRelaysAsync","checkVideoCodecsSupport"),A.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${A.signalingState}`)},A.onicecandidateerror=g=>{const f=g,[S,v]=[f.address,f.port];if(this.logger.safe.warn(`On ICE candidate error ${f.url} | ${S}:${v}: code ${f.errorCode}: ${f.errorText}`),!this.transportStateProvider.isConnected||this.negotiation.iceCandidatesDefer.isPending){const g={address:S,port:+v,url:f.url,errorCode:f.errorCode,errorText:f.errorText};this.statsGatherer.addIceCandidateError(g),this.diagnostics.addIceCandidateError(g)}},A.onaddstream=g=>{this.logger.safe.info(`onaddstream stream: ${g.stream.id}`)};const processTrack=(g,f,S,v)=>{this.logger.safe.info(`ontrack processing ${g.kind}: ${f.id}`);let C=f.active;if(!f.active&&this.configProvider.config.useInactiveAudioTrack&&"audio"===g.kind&&(this.logger.safe.warn("ontrack override forcing to use inactive audio stream"),C=!0),!C||"stopped"===v?.currentDirection||v?.stopped)return void this.logger.safe.info("ontrack ignore non active stream");let _=this.mediaManager.getMediaEntityByRemoteStreamId(f.id);if(_||(this.logger.safe.info(`cannot find media entity with stream id ${f.id} trying to fallback`),f.getAudioTracks()[0]&&(_=this.mediaManager.getMediaEntitiesByModality(qt.MODALITY.audio)[0])),_){const v=this.createReceiveStream(f,S,g,_);_.setRemoteTrackId(g.id),this.addReceiveStreamTransforms(S,_.getModality()),this.receiveStreamCollection.add(v)}else this.logger.safe.error(`could not find media entity for an added stream: ${f.id}`)};A.ontrack=g=>{const{track:f,receiver:S,transceiver:v}=g,C=g.streams[0]??new MediaStream([f]),trackCallback=()=>processTrack(f,C,S,v);if((!this.configProvider.config.addAudioStreamBeforeConnection||qt.TRACK_KIND.audio!==f.kind)&&!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional)return this.logger.safe.info(`ontrack queueing to be run once connected ${f.kind}: ${C.id}`),void this.transportStateProvider.doOnConnected(trackCallback,"ontrack",!1);trackCallback()},A.onremovestream=g=>{this.logger.safe.info(`onremovestream ${g.stream.id}`),this.transportStateProvider.doOnConnected((()=>this.receiveStreamCollection.remove(g.stream.id)),"onremovestream")},A.onicecandidate=f=>{const S=f.candidate;if(S){const f=parseCandidateString(S.candidate);if(this.logger.safe.info(`[${g}] onicecandidate candidate: component:${f.component} protocol:${f.protocol} prio:${f.priority} type:${f.type} port:${f.port}`),this.logger.unsafe.info(`[${g}] candidate details: ${S.candidate}`),"1"!==f.component)return;if(this.negotiation.iceCandidateReceived=!0,this.statsGatherer.sessionInfo.setCandidateDetails(f),this.diagnostics.setCandidateDetails(f),!this.relayCandidateGathered&&S.candidate.indexOf("typ relay")>-1){const g={priority:S.priority?.toString()||f.priority,time:Date.now()-this.negotiation.iceRelayGatheringStartTime};this.statsGatherer.sessionInfo.setRelayCandidateInfo(g),this.diagnostics.relayCandidateInfo=g,this.relayCandidateGathered=!0}}else this.logger.safe.info(`[${g}] onicecandidate candidate: null`);if(!this.negotiation.iceCandidatesDefer.isPending)return;const v=!this.context.config.webrtcIceGatheringTimeoutIncreased||this.configProvider.config.emptyIceCandidateMarksGatheredAnswerer&&!this.negotiation.initiator,C=this.iceHostCandidateOnly||0===_.length;if(!S&&v||C){S&&this.logger.safe.info(`[${g}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${g}] Is connected:`,this.transportStateProvider.isConnected,this.transportStateProvider.iceConnectionState,this.transportStateProvider.signalingState);let f=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&S&&(f=this.negotiation.sessionDescription.createLocalOffer(A.localDescription.sdp).hasUnbundledIceCandidates()),f&&this.completeCandidateGathering(g)}else if(this.relayCandidateGathered){let f=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&(f=this.negotiation.sessionDescription.createLocalOffer(A.localDescription.sdp).hasUnbundledRelayIceCandidates()),f&&(this.statsGatherer.clearIceCandidateErrors(),this.diagnostics.clearIceCandidateErrors(),this.completeCandidateGathering(g))}},A.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${A.iceGatheringState}`)},this.transportStateProvider=new Nb(A,T,this.logger.createChild("TransportStateProvider"),this.configProvider,this.diagnostics.newTransportStateDiagnostics()),this.transportStateProvider.on("stateChanged",((S,v,C)=>{if(this.terminated)return;const _=this.wasConnected?C:g;if(this.statsGatherer.sessionInfo.setIceConnectionState(S),"connecting"===S&&f.mark("transportConnecting"),"connected"===S||"completed"===S)f.markAndMeasure("transportConnecting","transportConnected"),this.onTransportConnected(_);else if("failed"===S||"closed"===S&&"failed"!==v){if(this.negotiation.iceCandidatesDefer.isPending)return this.logger.safe.info(`[${_}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(_);this.raiseError({type:qt.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},_),this.configProvider.config.webrtcCloseAfterIceFailure&&A.close(),this.callbacks.onTransportFailed?.()}"disconnected"===S?(this.callbacks.onTransportDisconnected?.(g),this.startIceDisconnectedTimer(_)):this.clearIceDisconnectedTimer()})),this.transportStateProvider.on("signalingStateChanged",((f,S,v)=>{this.configProvider.config.reconnectOnPcClose&&!this.terminated&&"closed"===f&&this.transportStateProvider.isTransportConnected&&this.raiseError({type:qt.MEDIA_ERROR.unexpectedClose,detail:"PeerConnection is closed"},v),"have-remote-pranswer"===S&&"stable"===f&&this.configProvider.config.webrtcPranswerWaitFinalAnswer&&this.transportStateProvider.isTransportConnected&&(this.logger.safe.info(`[${v}] remote final answer, activating audio`),this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g))})),this.transceiverManager=new va(this.logger,this.peerConnection,this.mediaManager,this.context,this.reinvitelessContext),this.streamSendersManager.registerRtpSenderManager(this.transceiverManager),allowDataChannel(this.context)&&!this.dataChannel&&(this.dataChannel=new Rs(this.peerConnection,this.diagnostics,this.logger,this.configProvider),this.callback.onDataChannelUpdated?.(this.dataChannel),this.multiParty&&this.initializeMediaControlPlane(g)),this.sourceRequestSender=new JA(this.mediaControlPlane,this.context.sendWebRtcMediaNotificationAsyncCallback,this.logger.createChild("SourceRequestSender")),this.mediaMessageController=new Bb(this.logger.createChild("SourceRequester"),this.configProvider,this.sourceRequestSender,this.mediaControlPlane),this.negotiation.setInternals(this.transceiverManager,this.transportStateProvider,this.dataChannel),this.multiParty&&(this.contributingSources=new hb(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new ub(this.logger.createChild("ContributingSourcesProvider"),A,this.configProvider.config.diagnostics.features.logContributingSourcesError,this.diagnostics))),f.mark("startInitialize"),await this.encStreamsManager.initialize(),f.markAndMeasure("startInitialize","encStreamsManagerInitialize");const P=this.encStreamsManager.isWorkerLoaded();this.initAudioCodec(P),this.statsGatherer.sessionInfo.setEncodedStreamWorkerLoaded(P),this.diagnostics.encodedStreamWorker=P}configureCpuThreshold(g){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&g.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(g){this.negotiation.iceCandidatesDefer.isPending&&(this.logger.safe.info(`[${g}] ICE candidates gathered completely`),this.negotiation.iceCandidatesDefer.resolve())}detectVideoFeatures(){const g=this.videoFeatureManager.get("Video"),f=this.configProvider.config.specCompliantSimulcast;if(f?.enableSimulcastLayoutControlStrategy&&f?.video?.layerScaleFactors?.length>2&&g.toggleClient(0,!0),this.context.config.isTownHall){const f=this.configProvider.config.broadcastMode;(f?.prioritizeLayoutOnServer||f?.prioritizeLayoutOnClient)&&g.toggleClient(3,!0),f?.maxSessionBandwidthKbps&&(this.statsGatherer.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.diagnostics.maxSessionBandwidth=this.configProvider.mediaConfig.maxBandwidthInKbps)}const S=this.mediaManager.getMediaEntitiesByModality("video"),v=this.configProvider.config.preferredH264VideoSendProfile;v?.startsWith("64")&&S.length>0&&S[0].isSendProfileSupported("H264",v)&&g.toggleClient(1,!0)}onTransportConnected(g){if(this.statsGatherer.clearIceCandidateErrors(),this.diagnostics.clearIceCandidateErrors(),!this.terminated){if(this.transportStateProvider.isWaitingAcceptProvisional)return this.logger.safe.info(`[${g}] transport connected provisional`),this.configProvider.config.createProvisionalAnswer.audioState&&this.callbacks.onAudioStateChanged?.(this.configProvider.config.createProvisionalAnswer.audioState,g),void(this.configProvider.config.createProvisionalAnswer.connectTransport&&this.callbacks.onTransportConnected?.(g));this.logger.safe.info(`[${g}] audio transport connected`),this.wasConnected=!0,this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval&&"have-remote-pranswer"===this.transportStateProvider.signalingState?this.handleEarlyMediaAudioState(g):this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g),this.multiParty&&this.configProvider.config.enableVideoFeatureManager&&(this.videoFeatureManager.manageFeatureSupport((()=>{this.detectVideoFeatures()})),this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2&&this.videoFeatureManager.on("onVideoFeaturesChanged",(g=>{if("Video"===g.mediaType&&this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2){const f=this.mediaManager.getMediaEntitiesByModality("video");f.length>0&&this.mediaMessageController.sendMaxVideoSendCapabilitiesV2(f[0],g)}}))),this.callbacks.onTransportConnected?.(g)}}handleEarlyMediaAudioState(g){const f=this.peerConnection.getReceivers().filter((g=>"audio"===g.track.kind))[0];if(!f)return this.logger.safe.warn(`[${g}] Connected transport with provisional answer with no audio receiver`),void this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g);this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.started,g);const S=this.configProvider.config.webrtcPranswerMediaPollingTimeout,v=this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval;this.logger.safe.info(`[${g}] Starting polling for early media audio stats`);const pollStats=async()=>{try{if(!this.canPollAudioStats())return;let C;this.logger.safe.debug(`[${g}] Polling audio receiver stats to detect early media start`);const _=deferWithTimeout2(S,"Unable to get audio receiver stats report");f.getStats().then(_.resolve,_.reject);const T=await _.promise;this.diagnostics.registerEarlyMediaPoll();for(const g of T.values())if("inbound-rtp"===g.type){C=g;break}if(!this.canPollAudioStats())return void this.logger.safe.info(`[${g}] Finished polling early media audio stats, terminated: ${!this.terminated}`);if((this.configProvider.config.webrtcPranswerCheckAudioEnergy?C?.totalAudioEnergy:C?.bytesReceived)>this.configProvider.config.webrtcPranswerAudioThreshold)return this.logger.safe.info(`[${g}] Finished polling early media audio stats, activating audio`),void this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g);this.logger.safe.info(`[${g}] No audio data received yet, polling again in ${v}ms`),setTimeout(pollStats,v)}catch(f){const S=stringifyObject2(f);if(this.logger.safe.error(`[${g}] Error polling stats for pranswer: ${S}. Will stop polling: ${this.configProvider.config.webrtcPranswerStopPollingAfterError}`),this.diagnostics.addStatsError("WebrtcSession::earlyMediaPolling",S),this.configProvider.config.webrtcPranswerStopPollingAfterError)return void this.callbacks.onAudioStateChanged?.(qt.STREAMING_STATE.active,g);setTimeout(pollStats,v)}};setTimeout(pollStats,this.configProvider.config.webrtcPranswerWaitIntervalBeforePolling)}canPollAudioStats(){return!this.terminated&&"have-remote-pranswer"===this.transportStateProvider.signalingState}startIceDisconnectedTimer(g){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${g}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise ${qt.MEDIA_ERROR.iceConnectionError}`),this.raiseError({type:qt.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},g)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(g,f=generateCauseId()){this.logger.safe.error(`[${f}] Media error occurred type: ${g.type} detail: ${g.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(g,f)}notifyStreamsChanged(){this.streamsChangedNotificationScheduled||(this.logger.safe.info("Scheduling NotifyStreamsChanged"),this.streamsChangedNotificationScheduled=!0,this.negotiation.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.streamsChangedNotificationScheduled=!1,this.logger.safe.info("Executing NotifyStreamsChanged callback"),this.streamsChangedListener?.()})))}async streamAdded(g){if(qt.MODALITY.audio===g.getModality()&&(this.webrtcAudioRecvStream=g.getMediaStream(),await this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),await this.updateAudioRendererStream(this.webrtcAudioRecvStream)),this.configProvider.config.mapSsrcToTrackForStats){const f=this.mediaManager.getMediaEntityByRemoteStreamId(g.getMediaStream().id);this.statsGatherer.setSsrcTrackPair(f.getRemoteSsrc(),f.getRemoteTrackId())}this.notifyStreamsChanged()}async updateAudioRendererStream(g){await this.audioRenderer.play(g),this.rawIncomingAudioStreamManager.streamChanged(g)}streamRemoved(g){if(qt.MODALITY.audio===g.getModality())this.audioRenderer.getStream()===g.getMediaStream()&&(this.audioRenderer.stop(),this.rawIncomingAudioStreamManager.streamChanged(null)),this.webrtcAudioRecvStream=null;else if(qt.MODALITY.video===g.getModality()){const f=this.mediaManager.getMediaEntityByRemoteStreamId(g.getMediaStream().id);f?.getLocalRecvCapabilities()?.resetToInitial()}this.clearReceiveStreamTransforms(g.getReceiver()),g.dispose(),this.notifyStreamsChanged()}hasRelayCandidates(){return this.relayCandidateGathered}createReceiveStream(g,f,S,v){const C=this.configProvider.config.addFmtpToInitialSubscription?v.getLocalRecvCapabilities():null,_=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&v.getModality()!==qt.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null,T=new $y(g,f,v.getModality(),+v.getXSourceStreamId(),this,C,_,v.getSubstreamIndex());return new PA(T,S,this.receiveStreamCollection,this.logger.createChild("RecvStream"),this.configProvider.config)}async requestSource(g,f,S){if(!this.multiParty)return;const v=this.mediaManager.getMediaEntityByRemoteStreamId(g);if((this.isMuteHold||this.negotiation.negotiatedModalities[v.getModality()]===qt.MEDIA_STATE.inactive)&&-1!==f)return await delay(10),this.requestSource(g,f,S);if(this.negotiation.negotiationCompletedPromise.isPending)try{await this.negotiation.negotiationCompletedPromise.promise}catch(g){this.logger.safe.info("source request should be sent even if negotiation rejected",g)}if(!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional){this.logger.safe.info("requestSource is postponed till transport is connected");const g=new dt;this.transportStateProvider.doOnConnected((()=>g.resolve()),"requestSource"),await g.promise}return this.mediaMessageController.sendSourceRequest(v.getXSourceStreamId(),f,v?.getMid(),S,v.getSubstreamIndex())}async onReceiveCapabilitiesChanged(g,f,S){if(!this.streamSendersManager)return!1;try{return await this.streamSendersManager.applyCapabilities(f,g,S),!0}catch(g){return!1}}onOptimalVideoCountChanged(g,f){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(g),this.diagnostics.addOvcSubscriptionReport(g,this.subscriptionManager?.getSubscriptionsCount(),f)}async onSendBandwidthChanged(g){if(!this.transportStateProvider.isConnected||this.transportStateProvider.isWaitingAcceptProvisional||!this.mediaControlPlane.mcpFeaturesSupported("senderSideBandwidthEstimationEnabled"))return;const f=[],S=Object.keys(g);for(const v of S){const S=this.mediaManager.getMediaEntitiesByModality(mediaTypeToModality(v)).filter((g=>g.isEnabled()&&null!==g.getLocalTrackId()));if(0===S.length||0===g[v])return;f.push({streamMsid:S[0].getXSourceStreamId(),bw:g[v]})}await this.mediaMessageController.sendBandwidthInfo(f),this.diagnostics.reportedSendBandwidthLayouts(g)}onMaxVideoSendCapabilitiesChanged(g,f){("Video"===g&&this.configProvider.config.maxSendVideoCapabilities.enableForVideo||"ScreenShare"===g&&this.configProvider.config.maxSendVideoCapabilities.enableForSharing)&&this.transportStateProvider.doOnConnected((()=>this.notifyMaxVideoCapabilitiesChanged(g,f)),"maxCapabilities")}notifyMaxVideoCapabilitiesChanged(g,f){const S=mediaTypeToModality(g),v=this.mediaManager.getMediaEntitiesByModality(S)[0];if(!v)return;const C=v.getMid();"Video"===g&&this.configProvider.config.maxSendVideoCapabilities.enableForVideoV2?this.mediaMessageController.sendMaxVideoSendCapabilitiesV2(v,this.videoFeatureManager.get("Video"),f):this.mediaMessageController.sendMaxVideoSendCapabilities([C],f)}createAudioRenderer(){this.audioRenderer=new WC(this.logger.createChild("AudioRenderer"),this.configProvider,this.diagnostics.newAudioRendererDiagnostics()),this.ufdManager.signalDeviceEvent(1,"Good","Audio"),this.context.maContext.domOverrides.onMediaElementAdded&&this.audioRenderer.on("onAudioElementAdded",this.context.maContext.domOverrides.onMediaElementAdded),this.context.maContext.domOverrides.onMediaElementRemoved&&this.audioRenderer.on("onAudioElementRemoved",this.context.maContext.domOverrides.onMediaElementRemoved),this.audioRenderer.on("onAudioPlaybackError",((g,f,S)=>this.onAudioPlaybackError(g,f,S))),this.audioRenderer.on("onAudioStateChanged",((g,f)=>this.deviceManager.effectsManager.setAecRefStream(g,f)))}onAudioPlaybackError(g,f,S){const v={type:f,detail:S,isAudio:!0};this.ufdManager.signalDeviceEvent(1,"Bad","Audio"),this.deviceManager.raiseTelemetryEvent("reconnect_on_audio_playback_error",{error:g,mediaError:f,message:S}),this.context.reconnectRetry&&this.configProvider.config.audioRendererFailedRetryCodes?.includes(g)&&(this.logger.warn(`Reconnect required, attempt No: ${this.context.reconnectRetry}`),this.context.reconnectRetry--,this.raiseError(v))}getSessionConfig(){return this.configProvider}getLocalMediaTrackId(g){const f=this.mediaManager.getLocalTracksInfo(),S=mediaTypeToModality(g),v=f.find((g=>g.modality===S));return v?v.trackId:null}addReceiveStreamTransforms(g,f){const S=this.encStreamsManager.initTransformsCollection(g,"Receiver",modalityToMediaType(f));S&&f!==qt.MODALITY.audio&&this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&S.addTransform(new Wa(this.logger.createChild(`RecvStreamAnalyzer [${f}/${g.track.id}]`)))}clearReceiveStreamTransforms(g){this.encStreamsManager.clearTransformsCollection(g)}async checkVideoCodecsSupport(){try{const g=await this.capabilityGatherer.getCapabilities("video");this.statsGatherer.setH264AvailableProfiles(g);const f=nb.build({global:this.context.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround,!0),S=await f.getCapabilities("video"),v=nb.build({global:this.context.maContext},!1),C=await v.getCapabilities("video");this.statsGatherer.setSupportedH264Profiles(S,C);const _=await oa.isCodecsSupported(this.configProvider.config.hevcCodecs);this.diagnostics.videoCapabilities=g,this.diagnostics.setSupportedH264Profiles(S,C),this.diagnostics.isCodecsSupported=_;const T=new Set(g?.codecs?.map((g=>g.mimeType.toLocaleLowerCase()))||[]);for(const g of this.configProvider.config.requiredVideoCodecs)if(!T.has(g)){this.ufdManager.signalEvent("NoRequiredVideoCodecs","Bad","Video");break}}catch(g){this.logger.safe.error(`failed to get video capability ${stringifyObject2(g)}`)}}setBWSeed(g){if(!this.bandwidthCache)return;const f=this.bandwidthCache.getSeed();g.applyChannelParameters={multiChannelParameter:{mids:this.configProvider.config.bwSeedOptions.mids,mediaParameter:JSON.stringify({sendSideBWSeed:{seedValueBitsPerSec:f}})}},this.diagnostics.sentBWSeed=f}getSubscriptionManager(){return this.subscriptionManager}initAudioCodec(g){this.audioCodecManager.init(g,this.isAudioOutputMuted);const f=this.audioCodecManager.decoder;f&&(f.on("usedDecoderChanged",(g=>{this.updateAudioRendererStream(g?f.stream:this.webrtcAudioRecvStream),this.statsGatherer.setAudioDecoderStatsProvider(g?f.getStatsProvider():void 0),this.contributingSources?.useCustomCodec(g)})),f.on("contributingSourcesChanged",(g=>this.contributingSources?.updateContributingSources(g))),this.audioCodecManager.on("negotiationNeeded",(g=>this.negotiation.triggerRenegotiation(!0,g))))}onIncomingVideoQualityChanged(g,f){1===g&&this.remoteVideoResolutionManager.limitResolutionOnPoorPerformance(f)}getVideoDeviceManager(){return this.context.callDeviceManager.getDeviceManager("Video")}setupCallDeviceManagerSubs(){this.callDeviceManagerSub=this.context.callDeviceManager.on("onSelectedVirtualDevicesChanged",(()=>{this.logger.info("VirtualDevice changed, disposing deviceManager subscriptions"),this.deviceManagerSubs.forEach((g=>g.dispose())),this.logger.info("New subscriptions for deviceManager created"),this.setSubsForDeviceManager()}))}updateLocalMediaSources(){this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statsGatherer.updateStatsWithLocalSsrcTrackInfo();const g=this.streamSendersManager.getLocalMediaSources();this.qualityManager.updateRegisteredSources(g)}},XA={build:(g,f,S)=>new QA(g,f,S)};function makeReinvitelessContext(g,f){const S=(f?g?.maxReinvitelessMediaForVideoMultiparty:g?.maxReinvitelessMediaForVideo1on1)||0,v=(f?g?.maxReinvitelessMediaForVBSSMultiparty:g?.maxReinvitelessMediaForVBSS1on1)||0;return{enabled:S>0||v>0,maxStreamsForModality:{video:S,sharing:v}}}var ZA=class{constructor(g,f,S,v,C,_,T,I){this.logger=g,this.context=f,this.configProvider=S,this.diagnostics=v,this.ufdManager=C,this.deviceManager=_,this.capabilities=T,this.midCallTelemetry=I,this.activeSessions=[],this.pendingDeviceTelemetryEvents=[],this.pendingVideoEffectsTelemetryEvents=[],this.pendingAudioEffectsTelemetryEvents=[],this.callsCount=0,this.mediaConfig={},this.configProvider.on("configUpdated",(()=>this.configApplied())),this.deviceManager.on("onDeviceTelemetryEvent",(g=>this.onDeviceTelemetryEvent(g))),this.deviceManager.on("onVideoEffectsTelemetryEvent",(g=>this.onVideoEffectsTelemetryEvent(g))),this.deviceManager.on("onAudioEffectsTelemetryEvent",(g=>this.onAudioEffectsTelemetryEvent(g)))}createSession(g,f,S,v,C,_){const T=(0,sT.merge)({},this.mediaConfig,_);this.configProvider.setMediaConfiguration(T);const I=this.configProvider.getConfigView(S?.isConference),b=this.logger,A=f.correlationId,P=this.diagnostics.newSession(I,A,this.logger.createChild("sessionDiagnostics"));C?.setDiagnosticsReport(this.diagnostics.reportGenerator);const R={getLogger:()=>b,getUfdManager:()=>this.ufdManager,sendWebRtcMediaNotificationAsyncCallback:(g,S)=>f.sendWebRtcMediaNotificationAsync(g,S),maContext:this.context,config:S??{},configProvider:I,diagnostics:P.newNativeSessionDiag(),reconnectRetry:I.config.audioRendererFailedReconnectTimes,callDeviceManager:v,getSmallCallTelemetry:()=>C},M=(I.mediaConfig.simulcastSessionEnabled?XA:jb).build(R,A,g),w=new PT(I,++this.callsCount,P);w.setMediaQosEnabled(!!T.enableMediaQoS),w.setPortRangeConfigured(!!T.mediaPortRanges);const O=new ET(M,A,R,g,w,this.configProvider,P);for(O.on("onTerminated",(g=>this.onSessionTerminated(g))),this.activeSessions.push(O),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector=lT.getInstance(this.logger.createChild("WebRtcInternals"),I),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length);this.pendingDeviceTelemetryEvents.length>0;)O.registerDeviceTelemetryEvent(this.pendingDeviceTelemetryEvents.pop());for(;this.pendingVideoEffectsTelemetryEvents.length>0;)O.registerVideoEffectsTelemetryEvent(this.pendingVideoEffectsTelemetryEvents.pop());for(;this.pendingAudioEffectsTelemetryEvents.length>0;)O.registerAudioEffectsTelemetryEvent(this.pendingAudioEffectsTelemetryEvents.pop());return O}getDeviceManager(){return this.deviceManager}getCapabilities(){return this.capabilities}getScreenSharingManager(){return new hT(this.deviceManager)}updateConfig(g,f,S,v){this.configProvider.updateConfig(g,f,S,v)}getConfig(){return this.configProvider.config}getConfigProvider(){return this.configProvider}setMediaConfig(g){(0,sT.merge)(this.mediaConfig,g),this.diagnostics.mediaConfig=this.mediaConfig}getMediaLogs(){return this.webRtcInternalsCollector?this.webRtcInternalsCollector.collect():Promise.resolve("")}getDiagnosticsData(){return this.diagnostics.rootRef}dispose(g){return Promise.all([...this.activeSessions.map((async f=>{await f.terminate(g,{}).catch((()=>{})),f.dispose()}))]).then((()=>{}),(()=>{}))}handleSendMidCallTelemetry(g){this.midCallTelemetry?.on("sendMidCallTelemetry",g)}configApplied(){window&&(this.configProvider.config.enableDevtoolsAPI?window.webMA||this.injectDevtoolsAPI():window.webMA&&delete window.webMA)}injectDevtoolsAPI(){const g=[],f={config:{addOverride:(g,f)=>this.configProvider.setConsoleOverride(g,f),setOverrides:g=>this.configProvider.setConsoleOverrides(g),clearOverride:g=>this.configProvider.clearConsoleOverride(g),clearAllOverrides:()=>this.configProvider.clearAllConsoleOverrides(),setPlatformConstraints:g=>this.configProvider.setCallConstraints(g),setCallConstraints:g=>{this.activeSessions.length&&this.activeSessions[this.activeSessions.length-1].setCallConstraints(g,"webMA")},setRelayConfigOverride:g=>this.context.getRelayManager().setRelayOverride(g),manageVideoFeatures:f=>{g.push(f)}},diagnosticsReport:this.diagnostics.reportGenerator,initVideoFeatures:f=>{g.forEach((g=>{g(((g,S,v)=>{let C;const _=Lb[v];return void 0!==_&&(("video"===S||"sharing"===S)&&(C=f.get("Video")),void 0!==C)&&(g?(C.toggleServer(_,!0),!0):(C.toggleClient(_,!0),!0))}))}))},deviceManager:{setAudioProcessingFlags:g=>this.deviceManager.setAudioProcessingFlags(g)},ufdManager:{raiseUFD:(g,f="Bad",S="Video")=>this.ufdManager.signalEvent(g,f,S)}};window.webMA=f}onDeviceTelemetryEvent(g){this.activeSessions.length>0?this.activeSessions.forEach((f=>f.registerDeviceTelemetryEvent(g))):this.pendingDeviceTelemetryEvents.push(g)}onVideoEffectsTelemetryEvent(g){this.activeSessions.length>0?this.activeSessions.forEach((f=>f.registerVideoEffectsTelemetryEvent(g))):this.pendingVideoEffectsTelemetryEvents.push(g)}onAudioEffectsTelemetryEvent(g){this.activeSessions.length>0?this.activeSessions.forEach((f=>f.registerAudioEffectsTelemetryEvent(g))):this.pendingAudioEffectsTelemetryEvents.push(g)}onSessionTerminated(g){remove2(this.activeSessions,(f=>f===g)),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length),0===this.activeSessions.length&&this.ufdManager.reset()}},eP=class{static build(g,f,S,v,C,_,T,I){return new ZA(g,f,S,v,C,_,T,I)}};eP.constants=qt,eP.helper=aa;var tP=class{constructor(g,f,S){this.logger=g,this.callbacks=f,this.deviceManagerDiagnostics=S,this.createWasmCVWorker=()=>(this.logger.info("Creating wasmcv worker"),this.create({msg:"wasmcv"})),this.createEncodedStreamsWorker=()=>(this.logger.info("Creating encoded-stream worker"),this.create({msg:"encoded-stream"})),this.createTimerWorker=()=>(this.logger.info("Creating timer worker"),this.create({msg:"timer"})),this.getWasmVqeWorker=()=>(this.logger.info("Creating wasmvqe worker"),this.create({msg:"wasmvqe"}))}getWorkerFunction(g){if(this.logger.info(`getWorkerFunction, loaderName: ${g}`),!this.callbacks?.createGenericWebRTCWorker)switch(g){case"encoded-stream":return this.callbacks?.createEncodedStreamsWorker;case"wasmcv":return this.callbacks?.createWasmCVWorker;default:return}switch(g){case"encoded-stream":return this.createEncodedStreamsWorker;case"wasmcv":return this.createWasmCVWorker;case"timer":return this.createTimerWorker;default:return}}get audioWorklet(){return this.callbacks?.createGenericWebRTCWorker?{getWasmVqeWorker:this.getWasmVqeWorker,getWasmDnsWorklet:this.callbacks?.audioWorklet?.getWasmDnsWorklet,getWasmAecWorklet:this.callbacks?.audioWorklet?.getWasmAecWorklet,getWasmVqeWorklet:this.callbacks?.audioWorklet?.getWasmVqeWorklet}:this.callbacks?.audioWorklet}create(g){const f=this.callbacks.createGenericWebRTCWorker(),S=Date.now(),onError=S=>{this.logger.error(`Worker ${JSON.stringify(g)} error: ${S}`),this.deviceManagerDiagnostics?.registerWorkerEvent({timestamp:Date.now(),workerType:g.msg,msg:"generic-worker-error",payload:JSON.stringify(S)}),f.removeEventListener("error",onError)},onMessage=v=>{let C;"wasm-worker-loaded"===v?.data?.msg&&(this.logger.info(`Worker ${JSON.stringify(g)} event: ${JSON.stringify(v.data)}`),C={timestamp:Date.now(),workerType:g.msg,workerLoadTimeMs:Date.now()-S,msg:JSON.stringify(v?.data?.msg),payload:JSON.stringify(v?.data?.payload)},f.removeEventListener("message",onMessage)),"wasm-worker-load-error"===v?.data?.msg&&(this.logger.info(`Worker ${JSON.stringify(g)} error: ${JSON.stringify(v.data)}`),C={timestamp:Date.now(),workerType:g.msg,msg:"load-worker-error",payload:JSON.stringify(v?.data?.payload)}),C&&this.deviceManagerDiagnostics?.registerWorkerEvent(C)};return f.addEventListener("error",onError),f.addEventListener("message",onMessage),f.postMessage(g),f}},iP=class{constructor(g,f){this.wasmLoader=g,f&&f.getWorkerUrl().then((g=>{this.url=g}))}getWorker(g){try{g.safe.info("creating worker");const f=this.wasmLoader.getWorkerFunction("encoded-stream");return f?f():this.url?(g.safe.warn("WasmLoader didn't provide worker function, falling back to legacy worker provider"),new Worker(this.url)):(g.safe.error("no worker provider"),null)}catch(f){g.safe.error(`failed to create worker ${stringifyObject2(f)}`)}return null}},nP=class{constructor(g,f,S){this.mediaAgents=[],g.logger??(g.logger=new Mo),g.domOverrides??(g.domOverrides={}),this.config=g;const v=g.mediaSettings;setAgentPlatformInfo(g.clientInformation),this.logger=new rT(g.safeLogger?.createChild("MA",v.debug),g.logger.createChild("MA",v.debug)),this.configProvider=new By(this.logger.createChild("configProvider"),S,v);const C=new ay(this.configProvider);this.mediaAgentDiagnostics=new nT(this.configProvider,C),this.ufdManager=new Do(this.logger.createChild("UFD"),this.configProvider),this.wasmLoader=new tP(this.logger.createChild("WasmLoader"),g.createWasmWorkerCbs,C),this.deviceManager=new Oy(this.logger.createChild("DeviceManager"),this.configProvider,C,g.domOverrides,this.ufdManager,g.webcvProvider,g.wasmdnsProvider,g.wasmaecProvider,g.wasmVqeProvider,this.wasmLoader),this.capabilities=new wo(this.configProvider),ei.initialize(this.configProvider),f.on("OnECSChanged",(()=>{const g=f.getEcsConfig("SkypeWebMedia","mediaAgent");g?this.configProvider.updateConfig(g,f.ETag,f.getEcsConfig("ConfigIDs","SkypeWebMedia"),f.getEcsConfig("Headers","CountryCode")):this.logger.warn("No SkypeWebMedia.mediaAgent config.")}))}getDeviceManager(){return this.deviceManager}async buildAgent(g,f,S){if(!oa.hasMediaApi())throw[new rP(`${g} not supported by media agent provider`,"not_supported")];if(this.config?.detectH264Support&&!await oa.hasH264CodecSupport(this.config.logger))throw[new rP("H264 is not supported","not_supported")];const v=new iP(this.wasmLoader,this.config.encodedStreamsWorkerProvider),C={getRelayManager:()=>f.getOrCreateRelayManager(),getWebCVProvider:()=>this.config.webcvProvider,getWasmDnsProvider:()=>this.config.wasmdnsProvider,getWasmAecProvider:()=>this.config.wasmaecProvider,getWasmVqeProvider:()=>this.config.wasmVqeProvider,getEncodedStreamsWorkerProvider:()=>v,domOverrides:this.config.domOverrides,configProvider:this.configProvider};f.setConfigProvider(this.configProvider);const _=eP.build(this.logger,C,this.configProvider,this.mediaAgentDiagnostics,this.ufdManager,this.deviceManager,this.capabilities,S);return _.constants=eP.constants,this.mediaAgents.push(_),_}async dispose(g){return Promise.all([this.deviceManager.dispose(),this.ufdManager.dispose(),this.configProvider.dispose(),this.capabilities.dispose(),...this.mediaAgents.map((f=>f.dispose(g)))]).then((()=>{this.mediaAgents=[]}))}},rP=class extends Error{constructor(g,f="failure"){super(g),this.reason=f}},sP=class{constructor(){this.supportedPlatforms=new Map([["Chrome","59.0"],["EdgeAnaheim","79.0"],["Safari","13.1"],["Electron","3.0"],["Firefox","96.0"],["Maglev","1.0"]]),this.experimentalPlatforms=new Map}getPlatformSupportLevel(g){const f=et.getBrowserInfo(),S=this.supportedPlatforms.get(f.name);if(g&&S&&et.isVersionGreaterOrEqual(S))return 1;if(g&&!S){if(et.isEngine("Chromium","ChromiumAVD"))return 2;const g=this.experimentalPlatforms.get(f.name);if(g&&et.isVersionGreaterOrEqual(g))return 2}return 0}},aP=class extends Ke{constructor(g,f,S){super(),this.relayManagerProvider=g,this.configProvider=f,this.logger=S,this.currentInfo={},this.currentAreaContent={},this.isEnabled=!1,this.isEnabled=this.configProvider.config.enableE911,f.on("configUpdated",(()=>{const g=this.isEnabled;this.isEnabled=this.configProvider.config.enableE911,!this.isEnabled||g===this.isEnabled&&this.prober||(this.prober?.dispose(),this.prober=void 0,this.configProvider.config.probeE911OnInit&&this.probeForIP("config"))}))}get info(){return this.currentInfo}get areaContent(){return this.currentAreaContent}async getInfo(){return this.isEnabled&&!this.prober&&await this.probeForIP("publicGetInfo"),this.currentInfo}setClientInfo(g,f){if(this.isEnabled)switch(this.logger.info(`Client info for ${g} set`),g){case 3:this.mergeClientAreaInfo(JSON.parse(f));break;case 1:break;case 2:this.mergeClientNetworkInfo(JSON.parse(f))}}mergeClientAreaInfo(g){const f=JSON.stringify(this.currentAreaContent);this.currentAreaContent.geoCoordinates=g.geoCoordinates,removeUndefinedFields(this.currentAreaContent),JSON.stringify(this.currentAreaContent)!==f&&this.raiseChanged()}mergeClientNetworkInfo(g){if(0===Object.keys(g).length){const g=Object.keys(this.currentInfo).length+Object.keys(this.currentAreaContent).length;return this.currentInfo={},this.currentAreaContent={},void(g>0&&this.raiseChanged())}const f=this.currentInfo.bssid!==g.bssid||this.currentInfo.bssidv6!==g.bssidv6||this.currentInfo.mac!==g.mac||this.currentInfo.macv6!==g.macv6||this.currentInfo.subnetLengthIpv4!==g.subnetLengthIpv4||this.currentInfo.subnetLengthIpv6!==g.subnetLengthIpv6,S=this.currentInfo.e911;this.currentInfo.bssid=g.bssid,this.currentInfo.bssidv6=g.bssidv6,this.currentInfo.e911=g.e911,this.currentInfo.mac=g.mac,this.currentInfo.macv6=g.macv6,this.currentInfo.subnetLengthIpv4=g.subnetLengthIpv4,this.currentInfo.subnetLengthIpv6=g.subnetLengthIpv6,removeUndefinedFields(this.currentInfo),f?this.probeForIP("clientNetworkInfoChanged").then((g=>{g||this.raiseChanged()})):JSON.stringify(S)!==JSON.stringify(g.e911)&&this.raiseChanged()}async probeForIP(g){return this.probingPromise?(this.logger.info(`Probing already in progress, tried to start for: ${g}`),this.probingPromise):(this.probingPromise=this.probeForIPInternal(g),this.probingPromise.then((g=>(this.probingPromise=void 0,g))).catch((g=>(this.probingPromise=void 0,this.logger.error(`E911 probing failed: ${stringifyObject2(g)}`),!1))))}async probeForIPInternal(g){this.logger.info(`Probing for public IP address: ${g}`);const f=await this.ensureProber();if(await f.ensureOnline(),f.ipFromRelay){if((this.currentInfo.ipv4||this.currentInfo.ipv6)!==f.ipFromRelay)return delete this.currentInfo.ipv4,delete this.currentInfo.ipv6,this.currentInfo[la.test(f.ipFromRelay)?"ipv4":"ipv6"]=f.ipFromRelay,this.raiseChanged(),!0}else if(0!==Object.keys(this.currentInfo).length)return this.currentInfo={},this.raiseChanged(),!0;return!1}async ensureProber(){if(this.prober)return this.prober;const g=createProbeIceServers(await this.relayManagerProvider.getOrCreateRelayManager().queryRelaysAsync({relayType:"turn"}),this.configProvider.config);return this.prober=new ST(g,new rT(this.logger.createChild("Prober"),this.logger.createChild("ProberUnsafe"))),this.prober}},oP=class extends Ke{constructor(g){super(),this.ecsFilters=g,this.config=null}get ETag(){return this.etag}async setEcsConfig(g){this.config=JSON.parse(g.ecsBlob),this.etag=g.etag,this.event("OnECSChanged").raise()}async setUserEcsServerUrl(g,f){throw new Error("Not implemented")}async getUserEcsServerUrl(g){throw new Error("Not implemented")}async setActiveUserForEcs(g){throw new Error("Not implemented")}async getEcsQueryParameters(){const g={};g.CLRelease=getTsCallingVersion2();const f="_TS_BUILC_VERSION_".replace("C","D"),S=this.ecsFilters?.["UserInfo.Ring"]?.value,v=this.getTeamsExperience();g.CLRelease===f&&(g.CLRelease="9999.99"),S&&(g.audienceGroup=S,g.teamsRing=S),v&&(g.Experience=v),"vdi3"===this.ecsFilters?.vdi?.value&&(g.vdi="vdi3");const C=et.getBrowserInfo();return g.BrowserName=C.name,g.BrowserEngine=C.engine,g.BrowserVersion=C.version,g.FormFactor=C.formFactor,g.OsName=C.osName,g.OsVer=C.osVersion,oa.hardwareConcurrency&&(g.CPUCount=oa.hardwareConcurrency),JSON.stringify(g)}async ecsGetUserQueryParameters(g){return this.getEcsQueryParameters()}async shouldTriggerCQF(g,f,S){throw new Error("Not implemented")}getEcsConfig(g,f){const S=this.config?.[g];return f?S?.[f]:S}createEcsConfiguration(){return new class{constructor(g){this.provider=g}getBoolean(g,f){return this.provider.getEcsConfig(g,f)}getNumber(g,f){return this.provider.getEcsConfig(g,f)}getString(g,f){const S=this.provider.getEcsConfig(g,f);return JSON.stringify(S)}}(this)}getTeamsExperience(){return!0===this.ecsFilters?.isTeams2?.value?"teams2":!1===this.ecsFilters?.isTeams2?.value?"teams1":void 0}},lP=class{constructor(g){this._sharingSource=g}getId(){return this._sharingSource.getId()}getDeviceId(){return this._sharingSource.getDeviceId()}getType(){return this.mapSharingSourceType(this._sharingSource.getType())}getPreview(g,f,S){return Promise.reject("not implemented")}getPreviewAsync(g,f){return this._sharingSource.getPreviewAsync(g,f)}getDescription(){return this._sharingSource.getDescription()}getIcon(g,f){return this._sharingSource.getIcon(g,f)}getBounds(){}mapSharingSourceType(g){switch(g){case 1:return 1;case 2:return 2;case 3:return 3;default:throw new Error("Invalid sharing source type")}}},cP=class extends Ke{constructor(g){super(),this._screenSharingManager=g,this._screenSharingManager.onScreensChanged((()=>{this.event("screensChanged").raise()}))}enumerateScreensAsync(){return this._screenSharingManager.enumerateScreensAsync().then((g=>g.map((g=>new lP(g)))))}enumerateWindowsAsync(){return this._screenSharingManager.enumerateWindowsAsync().then((g=>g.map((g=>new lP(g)))))}enumerateCamerasAsync(){return this._screenSharingManager.enumerateCamerasAsync().then((g=>g.map((g=>new lP(g)))))}},dP=R,updateSignalingAgentConfig=(g,f)=>{if(!f)return g;const S={...g};if(f.ngIncoming&&f.ngOutgoing){const v=convertScreenSharingFlag(f.ngIncoming.isVBSSEnabled,f.ngOutgoing.isVBSSEnabled);S.cloudScreenSharingFlag=getParam(v,g.cloudScreenSharingFlag)}return f.ngOutgoing&&(S.emergencyCallCountry=convertEmergencyCallCountryFlag(f.ngOutgoing.isEmergencyCallingEnabled,g.emergencyCallCountry),S.isGVCOutgoingEnabled=getParam(f.ngOutgoing.isGVCEnabled,g.isGVCOutgoingEnabled),S.brokerEnabledOutgoing=getParam(f.ngOutgoing.isBrokerEnabled,g.brokerEnabledOutgoing)),f.ngIncoming&&(S.isGVCJoiningEnabled=getParam(f.ngIncoming.isGVCEnabled,g.isGVCJoiningEnabled),S.brokerEnabledIncoming=getParam(f.ngIncoming.isBrokerEnabled,g.brokerEnabledIncoming)),S.conversationServiceUrl=getUrl(f.conversationServiceUrl,g.conversationServiceUrl),S.uploadLogRequestUrl=getUrl(f.uploadLogRequestUrl,g.uploadLogRequestUrl),S.isConversationServiceUrlFromEcs=!!f.conversationServiceUrl,S.isUploadLogRequestUrlFromEcs=!!f.uploadLogRequestUrl,S.callingTokenLogicalUrl=getUrl(f.callingTokenLogicalUrl,g.callingTokenLogicalUrl),S.doHostlessCalling=getParam(f.allowHostlessCalls,g.doHostlessCalling),S.supportsCompressedServicePayload=getParam(f.supportCompressedTrouterPayload,g.supportsCompressedServicePayload),S.brokerRequestBatching=getParam(f.allowBrokerSubscribeBatching,g.brokerRequestBatching),S.brokerExclusively=getParam(f.brokerExclusively,g.brokerExclusively),S.handleMediaOfferFromPushNotification=getParam(f.handleMediaOfferFromPushNotification,g.handleMediaOfferFromPushNotification),S.handleNewOfferRequest=getParam(f.handleNewOfferRequest,g.handleNewOfferRequest),S.sendProgressFromCC=getParam(f.sendProgressFromCC,g.sendProgressFromCC),S.useInternalHttpDispatcher=getParam(f.webInternalHttpDispatcher,g.useInternalHttpDispatcher),(f.webInternalHttpDispatcherConfigNetworkRequest||g.requestTypeHttpDispatcherConfigMap)&&(f.webInternalHttpDispatcherConfigNetworkRequest=f.webInternalHttpDispatcherConfigNetworkRequest||{},g.requestTypeHttpDispatcherConfigMap=g.requestTypeHttpDispatcherConfigMap||{},S.requestTypeHttpDispatcherConfigMap={...g.requestTypeHttpDispatcherConfigMap,...f.webInternalHttpDispatcherConfigNetworkRequest}),(f.operationTypeHttpDispatcherConfigMap||g.operationTypeHttpDispatcherConfigMap)&&(f.operationTypeHttpDispatcherConfigMap=f.operationTypeHttpDispatcherConfigMap||{},g.operationTypeHttpDispatcherConfigMap=g.operationTypeHttpDispatcherConfigMap||{},S.operationTypeHttpDispatcherConfigMap={...g.operationTypeHttpDispatcherConfigMap,...f.operationTypeHttpDispatcherConfigMap}),(f.csaTimeoutConfiguration||g.csaTimeoutConfiguration)&&(f.csaTimeoutConfiguration=f.csaTimeoutConfiguration||{},g.csaTimeoutConfiguration=g.csaTimeoutConfiguration||{},S.csaTimeoutConfiguration={...g.csaTimeoutConfiguration,...f.csaTimeoutConfiguration}),S.autoJoinOnConflict=getParam(f.autoJoinOnConflict,g.autoJoinOnConflict),S.enableQuickSendAcceptanceAck=getParam(f.enableQuickSendAcceptanceAck,g.enableQuickSendAcceptanceAck),S.supportMediaRetargetWhileIncomingRenegotiation=getParam(f.supportMediaRetargetWhileIncomingRenegotiation,g.supportMediaRetargetWhileIncomingRenegotiation),S.enableCallEstablishmentTimeoutsForStartJoinCall=getParam(f.enableCallEstablishmentTimeoutsForStartJoinCall,g.enableCallEstablishmentTimeoutsForStartJoinCall),S.callingServiceSupportsCAETokens=getParam(f.callingServiceSupportsCAETokens,g.callingServiceSupportsCAETokens),S.callingServiceSupportsAADTokens=getParam(f.callingServiceSupportsAADTokens,g.callingServiceSupportsAADTokens),S.aadTokenExpirationTimeInSeconds=getParam(f.aadTokenExpirationTimeInSeconds,g.aadTokenExpirationTimeInSeconds),S.caeTokenExpirationTimeInSeconds=getParam(f.caeTokenExpirationTimeInSeconds,g.caeTokenExpirationTimeInSeconds),S.disableTokenMigrationHeader=getParam(f.disableTokenMigrationHeader,g.disableTokenMigrationHeader),S.enablePublishTokenTelemetry=getParam(f.enablePublishTokenTelemetry,g.enablePublishTokenTelemetry),S.refreshTimeBeforeTokenTimeoutInSeconds=getParam(f.refreshTimeBeforeTokenTimeoutInSeconds,g.refreshTimeBeforeTokenTimeoutInSeconds),S.forceClearExpiredTokens=getParam(f.forceClearExpiredTokens,g.forceClearExpiredTokens),S.enableRefreshToken=getParam(f.enableRefreshToken,g.enableRefreshToken),S.enableAsyncDisablePreheat=getParam(f.enableAsyncDisablePreheat,g.enableAsyncDisablePreheat),S.forceLowercaseHttpHeaders=getParam(f.forceLowercaseHttpHeaders,g.forceLowercaseHttpHeaders),S.enableResolveScreenSharingWhenNegotiationComplete=getParam(f.enableResolveScreenSharingWhenNegotiationComplete,g.enableResolveScreenSharingWhenNegotiationComplete),S.maxReinvitelessMediaForVideoForWeb=getParam(f.maxReinvitelessMediaForVideoForWeb,g.maxReinvitelessMediaForVideoForWeb),S.maxReinvitelessMediaForVBSSForWeb=getParam(f.maxReinvitelessMediaForVBSSForWeb,g.maxReinvitelessMediaForVBSSForWeb),S.enableRefreshTokenRetry=getParam(f.enableRefreshTokenRetry,g.enableRefreshTokenRetry),S.enableRefreshTokenRetryInSeconds=getParam(f.enableRefreshTokenRetryInSeconds,g.enableRefreshTokenRetryInSeconds),S.enableConversationTypeUpdateOnCallEnd=getParam(f.enableConversationTypeUpdateOnCallEnd,g.enableConversationTypeUpdateOnCallEnd),S.supportMissingTokenTypesInResponse=getParam(f.supportMissingTokenTypesInResponse,g.supportMissingTokenTypesInResponse),S.useSkypeTokenWhenNoAuthenticateHeader=getParam(f.useSkypeTokenWhenNoAuthenticateHeader,g.useSkypeTokenWhenNoAuthenticateHeader),S.enableAutoPromotion=getParam(f.enableAutoPromotion,g.enableAutoPromotion),S.enableTokenCache=getParam(f.enableTokenCache,g.enableTokenCache),S.enableBatchedSendMessageStatus=getParam(f.enableBatchedSendMessageStatus,g.enableBatchedSendMessageStatus),S.enableBatchedReceiveMessage=getParam(f.enableBatchedReceiveMessage,g.enableBatchedReceiveMessage),S.enableTokenCacheForGenericTokenAPI=getParam(f.enableTokenCacheForGenericTokenAPI,g.enableTokenCacheForGenericTokenAPI),S.disableRealTimeModeFromRoster=getParam(f.disableRealTimeModeFromRoster,g.disableRealTimeModeFromRoster),S.enableLongOutgoing1To1SetupTimeoutForWeb=getParam(f.enableLongOutgoing1To1SetupTimeoutForWeb,g.enableLongOutgoing1To1SetupTimeoutForWeb),S.checkAttendeeRoleInCreateContentSharing=getParam(f.checkAttendeeRoleInCreateContentSharing,g.checkAttendeeRoleInCreateContentSharing),S.enableSpecificErrorCodesForCallEnd=getParam(f.enableSpecificErrorCodesForCallEnd,g.enableSpecificErrorCodesForCallEnd),S.enableSplitConversationEndUrl=getParam(f.enableSplitConversationEndUrl,g.enableSplitConversationEndUrl),S.enableFetchRequestWithKeepAlive=getParam(f.enableFetchRequestWithKeepAlive,g.enableFetchRequestWithKeepAlive),S.enableFetchApi=getParam(f.enableFetchApi,g.enableFetchApi),S.enableFetchApiForBeacon=getParam(f.enableFetchApiForBeacon,g.enableFetchApiForBeacon),S};function getParam(g,f){return null==g?f:g}function getUrl(g,f){return g||f}function convertScreenSharingFlag(g,f){return f&&g?"enabled":g?"recvOnly":!1===g&&!1===f?"disabled":void 0}function convertEmergencyCallCountryFlag(g,f){return!1===g?"":f}var hP,uP="SkypeCalling",gP=class{constructor(g,f,S,v){this.signalingAgentConfig=g,this.ecsProvider=f,this.logger=S,this.telemetryLogger=v,this.ecsProvider.on("OnECSChanged",(()=>this.onEcsUpdate())),this.signalingAgentConfig.clientInformation+=`/TsCallingVersion=${getTsCallingVersion2()}/Ovb=${getOvb2()}`,this.signalingAgentConfig.piiScrubber={omit:dP.pii.Omit,mri:dP.pii.Mri},this.signalingAgent=new ir(this.getSignalingAgentConfig())}getSignalingAgent(){return this.signalingAgent}onEcsUpdate(){const g=this.ecsProvider.getEcsConfig(uP);this.logger.info(`onEcsUpdate, ecsTag=${this.ecsProvider.ETag||""}, ecsConfig=${JSON.stringify(g)}`),this.signalingAgentConfig=updateSignalingAgentConfig(this.signalingAgentConfig,g),this.signalingAgentConfig.ecsEtag=this.ecsProvider.ETag,this.signalingAgent.updateSignalingAgentConfig(this.getSignalingAgentConfig())}getSignalingAgentConfig(){return this.signalingAgentConfig.oneDsTelemetryLogger=this.telemetryLogger,this.signalingAgentConfig}},pP={build:(g,f,S,v)=>new gP(g,f,S,v)},mP=__toESM2(M),fP="toLowerCase",SP="blkVal",vP="length",CP="rdOnly",yP="notify",EP="warnToConsole",_P="throwInternal",TP="setDf",IP="watch",bP="logger",AP="apply",PP="push",RP="splice",MP="hdlr",wP="cancel",OP="initialize",DP="identifier",NP="isInitialized",kP="getPlugin",LP="name",FP="time",xP="processNext",UP="getProcessTelContext",VP="unload",BP="loggingLevelConsole",HP="createNew",$P="teardown",jP="messageId",GP="message",qP="isAsync",WP="diagLog",zP="_doTeardown",KP="update",JP="getNext",YP="setNextPlugin",QP="userAgent",XP="nodeType",ZP="replace",eR="logInternalMessage",tR="isChildEvt",iR="getCtx",nR="setCtx",rR="complete";function throwAggregationError22(g,f){hP||(hP=createCustomError2("AggregationError",(function(g,f){f[vP]>1&&(g.errors=f[1])})));var S=g||"One or more errors occurred.";throw arrForEach2(f,(function(g,f){S+="\n".concat(f," > ").concat(dumpObj2(g))})),new hP(S,f||[])}var sR=void 0,aR="",oR="core",lR="disabled",cR="extensionConfig",dR="processTelemetry",hR="priority",uR="getPerfMgr",gR="Not dynamic - ",pR=/-([a-z])/g,mR=/([^\w\d_$])/g,fR=/^(\d+[\w\d_$])/;function isNotNullOrUndefined22(g){return!isNullOrUndefined2(g)}function normalizeJsName22(g){var f=g;return f&&dl(f)&&(f=(f=(f=f[ZP](pR,(function(g,f){return f.toUpperCase()})))[ZP](mR,"_"))[ZP](fR,(function(g,f){return"_"+f}))),f}function strContains22(g,f){return!(!g||!f)&&-1!==oc(g,f)}function toISOString22(g){return g&&g.toISOString()||""}function _createProxyFunction22(g,f){var S=null,v=null;return hl(g)?S=g:v=g,function(){var g=arguments;if(S&&(v=S()),v)return v[f][AP](v,g)}}function proxyFunctionAs22(g,f,S,v,C){g&&f&&S&&(!1!==C||isUndefined4(g[f]))&&(g[f]=_createProxyFunction22(S,v))}var SR="console",vR="JSON",CR="crypto",yR="msCrypto",ER="msie",_R="trident/",TR=null,IR=null;function getConsole22(){return typeof console!==Fo?console:getInst2(SR)}function hasJSON22(){return Boolean(typeof JSON===Lo&&JSON||null!==getInst2(vR))}function getJSON22(){return hasJSON22()?JSON||getInst2(vR):null}function getCrypto22(){return getInst2(CR)}function getMsCrypto22(){return getInst2(yR)}function isIE22(){var g=Kl();if(g&&(g[QP]!==IR||null===TR)){var f=((IR=g[QP])||aR)[fP]();TR=strContains22(f,ER)||strContains22(f,_R)}return TR}var bR=4294967296,AR=4294967295,PR=123456789,RR=987654321,MR=!1,wR=PR,OR=RR;function _mwcSeed22(g){g<0&&(g>>>=0),wR=PR+g&AR,OR=RR-g&AR,MR=!0}function _autoSeedMwc22(){try{var g=2147483647&utcNow2();_mwcSeed22((Math.random()*bR^g)+g)}catch(g){}}function random3222(g){var f=0,S=getCrypto22()||getMsCrypto22();return S&&S.getRandomValues&&(f=S.getRandomValues(new Uint32Array(1))[0]&AR),0===f&&isIE22()&&(MR||_autoSeedMwc22(),f=mwcRandom3222()&AR),0===f&&(f=Math.floor(bR*Math.random()|0)),g||(f>>>=0),f}function mwcRandom3222(g){var f=((OR=36969*(65535&OR)+(OR>>16)&AR)<<16)+(65535&(wR=18e3*(65535&wR)+(wR>>16)&AR))>>>0&AR|0;return g||(f>>>=0),f}function newId22(g){void 0===g&&(g=22);for(var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S=random3222()>>>0,v=0,C=aR;C[vP]<g;)v++,C+=f.charAt(63&S),S>>>=6,5===v&&(S=(random3222()<<2&4294967295|3&S)>>>0,v=0);return C}var DR="3.3.1",NR="."+newId22(6),kR=0;function _canAcceptData22(g){return 1===g[XP]||9===g[XP]||!+g[XP]}function _getCache22(g,f){var S=f[g.id];if(!S){S={};try{_canAcceptData22(f)&&objDefine2(f,g.id,{e:!1,v:S})}catch(g){}}return S}function createUniqueNamespace22(g,f){return void 0===f&&(f=!1),normalizeJsName22(g+kR+++(f?"."+DR:aR)+NR)}function createElmNodeData22(g){var f={id:createUniqueNamespace22("_aiData-"+(g||aR)+"."+DR),accept:function(g){return _canAcceptData22(g)},get:function(g,S,v,C){var _=g[f.id];return _?_[normalizeJsName22(S)]:(C&&((_=_getCache22(f,g))[normalizeJsName22(S)]=v),v)},kill:function(g,f){if(g&&g[f])try{delete g[f]}catch(g){}}};return f}function _isConfigDefaults22(g){return g&&isObject3(g)&&(g.isVal||g.fb||vl(g,"v")||vl(g,"mrg")||vl(g,"ref")||g.set)}function _getDefault22(g,f,S){var v,C=S.dfVal||isDefined22;if(f&&S.fb){var _=S.fb;ul(_)||(_=[_]);for(var T=0;T<_[vP];T++){var I=_[T],b=f[I];if(C(b)?v=b:g&&(C(b=g.cfg[I])&&(v=b),g.set(g.cfg,_l(I),b)),C(v))break}}return!C(v)&&C(S.v)&&(v=S.v),v}function _resolveDefaultValue22(g,f,S){var v,C=S;return S&&_isConfigDefaults22(S)&&(C=_getDefault22(g,f,S)),C&&(_isConfigDefaults22(C)&&(C=_resolveDefaultValue22(g,f,C)),ul(C)?(v=[])[vP]=C[vP]:isPlainObject2(C)&&(v={}),v&&(objForEachKey2(C,(function(S,C){C&&_isConfigDefaults22(C)&&(C=_resolveDefaultValue22(g,f,C)),v[S]=C})),C=v)),C}function _applyDefaultValue22(g,f,S,v){var C,_,T,I,b,A,P,R,M=v;_isConfigDefaults22(M)?(C=M.isVal,_=M.set,A=M[CP],P=M[SP],I=M.mrg,!(b=M.ref)&&isUndefined4(b)&&(b=!!I),T=_getDefault22(g,f,M)):T=v,P&&g[SP](f,S);var w=!0,O=f[S];!O&&isNullOrUndefined2(O)||(R=O,w=!1,C&&R!==T&&!C(R)&&(R=T,w=!0),_&&(w=(R=_(R,T,f))===T)),w?R=T?_resolveDefaultValue22(g,f,T):T:(isPlainObject2(R)||ul(T))&&I&&T&&(isPlainObject2(T)||ul(T))&&objForEachKey2(T,(function(f,S){_applyDefaultValue22(g,R,f,S)})),g.set(f,S,R),b&&g.ref(f,S),A&&g[CP](f,S)}var LR=symbolFor2("[[ai_dynCfg_1]]"),FR=symbolFor2("[[ai_blkDynCfg_1]]"),xR=symbolFor2("[[ai_frcDynCfg_1]]");function _cfgDeepCopy22(g){var f;return g&&(ul(g)?(f=[])[vP]=g[vP]:isPlainObject2(g)&&(f={}),f)?(objForEachKey2(g,(function(g,S){f[g]=_cfgDeepCopy22(S)})),f):g}function getDynamicConfigHandler22(g){if(g){var f=g[LR]||g;if(f.cfg&&(f.cfg===g||f.cfg[LR]===f))return f}return null}function blockDynamicConversion22(g){if(g&&(isPlainObject2(g)||ul(g)))try{g[FR]=!0}catch(g){}return g}function _canMakeDynamic22(g,f,S){var v=!1;return S&&!g[f.blkVal]&&((v=S[xR])||S[FR]||(v=isPlainObject2(S)||ul(S))),v}function throwInvalidAccess22(g){throwTypeError2("InvalidAccess:"+g)}var UR=["push","pop","shift","unshift","splice"],_throwDynamicError22=function(g,f,S,v){g&&g[_P](3,108,"".concat(S," [").concat(f,"] failed - ")+dumpObj2(v))};function _patchArray22(g,f,S){ul(f)&&arrForEach2(UR,(function(v){var C=f[v];f[v]=function(){for(var v=[],_=0;_<arguments.length;_++)v[_]=arguments[_];var T=C[AP](this,v);return _makeDynamicObject22(g,f,S,"Patching"),T}}))}function _getOwnPropGetter22(g,f){var S=Sl(g,f);return S&&S.get}function _createDynamicProperty22(g,f,S,v){var C={n:S,h:[],trk:function(f){f&&f.fn&&(-1===Yl(C.h,f)&&C.h[PP](f),g.trk(f,C))},clr:function(g){var f=Yl(C.h,g);-1!==f&&C.h[RP](f,1)}},_=!0,T=!1;function _getProperty(){_&&(T=T||_canMakeDynamic22(_getProperty,g,v),v&&!v[LR]&&T&&(v=_makeDynamicObject22(g,v,S,"Converting")),_=!1);var f=g.act;return f&&C.trk(f),v}function _setProperty(I){if(v!==I){_getProperty[g.ro]&&!g.upd&&throwInvalidAccess22("["+S+"] is read-only:"+dumpObj2(f)),_&&(T=T||_canMakeDynamic22(_getProperty,g,v),_=!1);var b=T&&_getProperty[g.rf];if(T)if(b){objForEachKey2(v,(function(g){v[g]=I?I[g]:sR}));try{objForEachKey2(I,(function(f,S){_setDynamicProperty22(g,v,f,S)})),I=v}catch(f){_throwDynamicError22((g.hdlr||{})[bP],S,"Assigning",f),T=!1}}else v&&v[LR]&&objForEachKey2(v,(function(f){var S=_getOwnPropGetter22(v,f);if(S){var C=S[g.prop];C&&C.chng()}}));if(I!==v){var A=I&&_canMakeDynamic22(_getProperty,g,I);!b&&A&&(I=_makeDynamicObject22(g,I,S,"Converting")),v=I,T=A}g.add(C)}}_getProperty[g.prop]={chng:function(){g.add(C)}},objDefine2(f,C.n,{g:_getProperty,s:_setProperty})}function _setDynamicProperty22(g,f,S,v){if(f){var C=_getOwnPropGetter22(f,S);C&&C[g.prop]?f[S]=v:_createDynamicProperty22(g,f,S,v)}return f}function _setDynamicPropertyState22(g,f,S,v){if(f){var C=_getOwnPropGetter22(f,S),_=C&&!!C[g.prop],T=v&&v[0],I=v&&v[1],b=v&&v[2];if(!_){if(b)try{blockDynamicConversion22(f)}catch(f){_throwDynamicError22((g.hdlr||{})[bP],S,"Blocking",f)}try{_setDynamicProperty22(g,f,S,f[S]),C=_getOwnPropGetter22(f,S)}catch(f){_throwDynamicError22((g.hdlr||{})[bP],S,"State",f)}}T&&(C[g.rf]=T),I&&(C[g.ro]=I),b&&(C[g.blkVal]=!0)}return f}function _makeDynamicObject22(g,f,S,v){try{objForEachKey2(f,(function(S,v){_setDynamicProperty22(g,f,S,v)})),f[LR]||(yl(f,LR,{get:function(){return g[MP]}}),_patchArray22(g,f,S))}catch(f){_throwDynamicError22((g.hdlr||{})[bP],S,v,f)}return f}var VR="[[ai_",BR="]]";function _createState22(g){var f,S,v=newSymbol2(VR+"get"+g.uid+BR),C=newSymbol2(VR+"ro"+g.uid+BR),_=newSymbol2(VR+"rf"+g.uid+BR),T=newSymbol2(VR+"blkVal"+g.uid+BR),I=newSymbol2(VR+"dtl"+g.uid+BR),b=null,A=null;function _useHandler(f,v){var C=S.act;try{S.act=f,f&&f[I]&&(arrForEach2(f[I],(function(g){g.clr(f)})),f[I]=[]),v({cfg:g.cfg,set:g.set.bind(g),setDf:g[TP].bind(g),ref:g.ref.bind(g),rdOnly:g[CP].bind(g)})}catch(f){var _=g[bP];throw _&&_[_P](1,107,dumpObj2(f)),f}finally{S.act=C||null}}function _notifyWatchers(){if(b){var g=b;b=null,A&&A[wP](),A=null;var f=[];if(arrForEach2(g,(function(g){if(g&&(g[I]&&(arrForEach2(g[I],(function(f){f.clr(g)})),g[I]=null),g.fn))try{_useHandler(g,g.fn)}catch(g){f[PP](g)}})),b)try{_notifyWatchers()}catch(g){f[PP](g)}f[vP]>0&&throwAggregationError22("Watcher error(s): ",f)}}function _addWatcher(g){if(g&&g.h[vP]>0){b||(b=[]),A||(A=scheduleTimeout2((function(){A=null,_notifyWatchers()}),0));for(var f=0;f<g.h[vP];f++){var S=g.h[f];S&&-1===Yl(b,S)&&b[PP](S)}}}function _trackHandler(g,f){if(g){var S=g[I]=g[I]||[];-1===Yl(S,f)&&S[PP](f)}}return(f={prop:v,ro:C,rf:_})[SP]=T,f[MP]=g,f.add=_addWatcher,f[yP]=_notifyWatchers,f.use=_useHandler,f.trk=_trackHandler,S=f}function _createAndUseHandler22(g,f){var S={fn:f,rm:function(){S.fn=null,g=null,f=null}};return objDefine2(S,"toJSON",{v:function(){return"WatcherHandler"+(S.fn?"":"[X]")}}),g.use(S,f),S}function _createDynamicHandler22(g,f,S){var v,C=getDynamicConfigHandler22(f);if(C)return C;var _,T=createUniqueNamespace22("dyncfg",!0),I=f&&!1!==S?f:_cfgDeepCopy22(f);function _notifyWatchers(){_[yP]()}function _setValue(f,S,v){try{f=_setDynamicProperty22(_,f,S,v)}catch(f){_throwDynamicError22(g,S,"Setting value",f)}return f[S]}function _watch(g){return _createAndUseHandler22(_,g)}function _block(g,f){_.use(null,(function(S){var v=_.upd;try{isUndefined4(f)||(_.upd=f),g(S)}finally{_.upd=v}}))}function _ref(g,f){var S;return _setDynamicPropertyState22(_,g,f,(S={},S[0]=!0,S))[f]}function _rdOnly(g,f){var S;return _setDynamicPropertyState22(_,g,f,(S={},S[1]=!0,S))[f]}function _blkPropValue(g,f){var S;return _setDynamicPropertyState22(_,g,f,(S={},S[2]=!0,S))[f]}function _applyDefaults(g,f){return f&&objForEachKey2(f,(function(f,S){_applyDefaultValue22(b,g,f,S)})),g}var b=((v={uid:null,cfg:I})[bP]=g,v[yP]=_notifyWatchers,v.set=_setValue,v[TP]=_applyDefaults,v[IP]=_watch,v.ref=_ref,v[CP]=_rdOnly,v[SP]=_blkPropValue,v._block=_block,v);return objDefine2(b,"uid",{c:!1,e:!1,w:!1,v:T}),_makeDynamicObject22(_=_createState22(b),I,"config","Creating"),b}function _logInvalidAccess22(g,f){g?(g[EP](f),g[_P](2,108,f)):throwInvalidAccess22(f)}function createDynamicConfig22(g,f,S,v){var C=_createDynamicHandler22(S,g||{},v);return f&&C[TP](C.cfg,f),C}function onConfigChange22(g,f,S){var v=g[LR]||g;return!v.cfg||v.cfg!==g&&v.cfg[LR]!==v?(_logInvalidAccess22(S,gR+dumpObj2(g)),createDynamicConfig22(g,null,S)[IP](f)):v[IP](f)}var HR,$R=null;function _getExtensionNamespace22(){var g=getInst2("Microsoft");return g&&($R=g.ApplicationInsights),$R}function getDebugExt22(g){var f=$R;return f||!0===g.disableDbgExt||(f=$R||_getExtensionNamespace22()),f?f.ChromeDbgExt:null}var jR="warnToConsole",GR="AI (Internal): ",qR="AI: ",WR="AITR_",zR={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},KR=((HR={})[0]=null,HR[1]="errorToConsole",HR[2]=jR,HR[3]="debugToConsole",HR);function _sanitizeDiagnosticText22(g){return g?'"'+g[ZP](/\"/g,aR)+'"':aR}function _logToConsole22(g,f){var S=getConsole22();if(S){var v="log";S[g]&&(v=g),hl(S[v])&&S[v](f)}}var JR=function(){function _InternalLogMessage3(g,f,S,v){void 0===S&&(S=!1);var C=this;C[jP]=g,C[GP]=(S?qR:GR)+g;var _=aR;hasJSON22()&&(_=getJSON22().stringify(v));var T=(f?" message:"+_sanitizeDiagnosticText22(f):aR)+(v?" props:"+_sanitizeDiagnosticText22(_):aR);C[GP]+=T}return _InternalLogMessage3.dataType="MessageData",_InternalLogMessage3}();function safeGetLogger22(g,f){return(g||{})[bP]||new YR(f)}var YR=function(){function DiagnosticLogger3(g){this.identifier="DiagnosticLogger",this.queue=[];var f,S,v,C,_,T=0,I={};dynamicProto2(DiagnosticLogger3,this,(function(b){function _logInternalMessage3(g,f){if(!_areInternalMessagesThrottled()){var C=!0,_=WR+f[jP];if(I[_]?C=!1:I[_]=!0,C&&(g<=S&&(b.queue[PP](f),T++,_debugExtMsg(1===g?"error":"warn",f)),T===v)){var A="Internal events throttle limit per PageView reached for this app.",P=new JR(23,A,!1);b.queue[PP](P),1===g?b.errorToConsole(A):b[EP](A)}}}function _setDefaultsFromConfig(g){return onConfigChange22(createDynamicConfig22(g,zR,b).cfg,(function(g){var _=g.cfg;f=_[BP],S=_.loggingLevelTelemetry,v=_.maxMessageLimit,C=_.enableDebug}))}function _areInternalMessagesThrottled(){return T>=v}function _debugExtMsg(f,S){var v=getDebugExt22(g||{});v&&v[WP]&&v[WP](f,S)}_=_setDefaultsFromConfig(g||{}),b.consoleLoggingLevel=function(){return f},b[_P]=function(g,S,v,_,T){void 0===T&&(T=!1);var A=new JR(S,v,T,_);if(C)throw dumpObj2(A);var P=KR[g]||jR;if(isUndefined4(A[GP]))_debugExtMsg("throw"+(1===g?"Critical":"Warning"),A);else{if(T){var R=+A[jP];!I[R]&&f>=g&&(b[P](A[GP]),I[R]=!0)}else f>=g&&b[P](A[GP]);_logInternalMessage3(g,A)}},b.debugToConsole=function(g){_logToConsole22("debug",g),_debugExtMsg("warning",g)},b[EP]=function(g){_logToConsole22("warn",g),_debugExtMsg("warning",g)},b.errorToConsole=function(g){_logToConsole22("error",g),_debugExtMsg("error",g)},b.resetInternalMessageCount=function(){T=0,I={}},b[eR]=_logInternalMessage3,b[VP]=function(g){_&&_.rm(),_=null}}))}return DiagnosticLogger3.__ieDyn=1,DiagnosticLogger3}();function _getLogger22(g){return g||new YR}function _throwInternal22(g,f,S,v,C,_){void 0===_&&(_=!1),_getLogger22(g)[_P](f,S,v,C,_)}var QR="ctx",XR="ParentContextKey",ZR="ChildrenContextKey",eM=function(){function PerfEvent3(g,f,S){var v,C=this;C.start=utcNow2(),C[LP]=g,C[qP]=S,C[tR]=function(){return!1},hl(f)&&objDefine2(C,"payload",{g:function(){return!v&&hl(f)&&(v=f(),f=null),v}}),C[iR]=function(g){return g?g===PerfEvent3[XR]||g===PerfEvent3[ZR]?C[g]:(C[QR]||{})[g]:null},C[nR]=function(g,f){g&&(g===PerfEvent3[XR]?(C[g]||(C[tR]=function(){return!0}),C[g]=f):g===PerfEvent3[ZR]?C[g]=f:(C[QR]=C[QR]||{})[g]=f)},C[rR]=function(){var g=0,f=C[iR](PerfEvent3[ZR]);if(ul(f))for(var S=0;S<f[vP];S++){var v=f[S];v&&(g+=v[FP])}C[FP]=utcNow2()-C.start,C.exTime=C[FP]-g,C[rR]=function(){}}}return PerfEvent3.ParentContextKey="parent",PerfEvent3.ChildrenContextKey="childEvts",PerfEvent3}(),tM="CoreUtils.doPerf";function doPerf22(g,f,S,v,C){if(g){var _=g;if(_[uR]&&(_=_[uR]()),_){var T=void 0,I=_[iR](tM);try{if(T=_.create(f(),v,C)){if(I&&T[nR]&&(T[nR](eM[XR],I),I[iR]&&I[nR])){var b=I[iR](eM[ZR]);b||(b=[],I[nR](eM[ZR],b)),b[PP](T)}return _[nR](tM,T),S(T)}}catch(g){T&&T[nR]&&T[nR]("exception",g)}finally{T&&_.fire(T),_[nR](tM,I)}}}return S()}function newGuid3(){var g=generateW3CId22();return Ll(g,0,8)+"-"+Ll(g,8,12)+"-"+Ll(g,12,16)+"-"+Ll(g,16,20)+"-"+Ll(g,20)}function generateW3CId22(){for(var g,f=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],S=aR,v=0;v<4;v++)S+=f[15&(g=random3222())]+f[g>>4&15]+f[g>>8&15]+f[g>>12&15]+f[g>>16&15]+f[g>>20&15]+f[g>>24&15]+f[g>>28&15];var C=f[8+(3&random3222())|0];return Fl(S,0,8)+Fl(S,9,4)+"4"+Fl(S,13,3)+C+Fl(S,16,3)+Fl(S,19,12)}var iM=createElmNodeData22("plugin");function _getPluginState22(g){return iM.get(g,"state",{},!0)}var nM,rM="TelemetryPluginChain",sM="_hasRun",aM="_getTelCtx",oM=0;function _getNextProxyStart22(g,f,S){for(;g;){if(g[kP]()===S)return g;g=g[JP]()}return createTelemetryProxyChain22([S],f.config||{},f)}function _createInternalContext22(g,f,S,v){var C=null,_=[];f||(f=createDynamicConfig22({},null,S[bP])),null!==v&&(C=v?_getNextProxyStart22(g,S,v):g);var T={_next:_moveNext,ctx:{core:function(){return S},diagLog:function(){return safeGetLogger22(S,f.cfg)},getCfg:function(){return f.cfg},getExtCfg:_resolveExtCfg,getConfig:_getConfig,hasNext:function(){return!!C},getNext:function(){return C},setNext:function(g){C=g},iterate:_iterateChain,onComplete:_addOnComplete}};function _addOnComplete(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];g&&_[PP]({func:g,self:isUndefined4(f)?T.ctx:f,args:S})}function _moveNext(){var g=C;if(C=g?g[JP]():null,!g){var f=_;f&&f[vP]>0&&(arrForEach2(f,(function(g){try{g.func.call(g.self,g.args)}catch(g){_throwInternal22(S[bP],2,73,"Unexpected Exception during onComplete - "+dumpObj2(g))}})),_=[])}return g}function _getExtCfg(g,S){var v=null,C=f.cfg;if(C&&g){var _=C[cR];!_&&S&&(_={}),C[cR]=_,(_=f.ref(C,cR))&&(!(v=_[g])&&S&&(v={}),_[g]=v,v=f.ref(_,g))}return v}function _resolveExtCfg(g,S){var v=_getExtCfg(g,!0);return S&&objForEachKey2(S,(function(g,S){if(isNullOrUndefined2(v[g])){var C=f.cfg[g];!C&&isNullOrUndefined2(C)||(v[g]=C)}_applyDefaultValue22(f,v,g,S)})),f[TP](v,S)}function _getConfig(g,S,v){var C;void 0===v&&(v=!1);var _=_getExtCfg(g,!1),T=f.cfg;return!_||!_[S]&&isNullOrUndefined2(_[S])?!T[S]&&isNullOrUndefined2(T[S])||(C=T[S]):C=_[S],C||!isNullOrUndefined2(C)?C:v}function _iterateChain(g){for(var f;f=T._next();){var S=f[kP]();S&&g(S)}}return T}function createProcessTelemetryContext22(g,f,S,v){var C=createDynamicConfig22(f),_=_createInternalContext22(g,C,S,v),T=_.ctx;function _processNext(g){var f=_._next();return f&&f[dR](g,T),!f}function _createNew(g,f){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain22(g,C.cfg,S,f)),createProcessTelemetryContext22(g||T[JP](),C.cfg,S,f)}return T[xP]=_processNext,T[HP]=_createNew,T}function createProcessTelemetryUnloadContext22(g,f,S){var v=createDynamicConfig22(f.config),C=_createInternalContext22(g,v,f,S),_=C.ctx;function _processNext(g){var f=C._next();return f&&f[VP](_,g),!f}function _createNew(g,S){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain22(g,v.cfg,f,S)),createProcessTelemetryUnloadContext22(g||_[JP](),f,S)}return _[xP]=_processNext,_[HP]=_createNew,_}function createProcessTelemetryUpdateContext22(g,f,S){var v=createDynamicConfig22(f.config),C=_createInternalContext22(g,v,f,S).ctx;function _processNext(g){return C.iterate((function(f){hl(f[KP])&&f[KP](C,g)}))}function _createNew(g,S){return void 0===g&&(g=null),ul(g)&&(g=createTelemetryProxyChain22(g,v.cfg,f,S)),createProcessTelemetryUpdateContext22(g||C[JP](),f,S)}return C[xP]=_processNext,C[HP]=_createNew,C}function createTelemetryProxyChain22(g,f,S,v){var C=null,_=!v;if(ul(g)&&g[vP]>0){var T=null;arrForEach2(g,(function(g){if(_||v!==g||(_=!0),_&&g&&hl(g[dR])){var I=createTelemetryPluginProxy22(g,f,S);C||(C=I),T&&T._setNext(I),T=I}}))}return v&&!C?createTelemetryProxyChain22([v],f,S):C}function createTelemetryPluginProxy22(g,f,S){var v,C=null,_=hl(g[dR]),T=hl(g[YP]),I={getPlugin:function(){return g},getNext:function(){return C},processTelemetry:_processTelemetry,unload:_unloadPlugin,update:_updatePlugin,_id:v=g?g[DP]+"-"+g[hR]+"-"+oM++:"Unknown-0-"+oM++,_setNext:function(g){C=g}};function _getTelCtx(){var v;return g&&hl(g[aM])&&(v=g[aM]()),v||(v=createProcessTelemetryContext22(I,f,S)),v}function _processChain(f,S,_,T,I){var b=!1,A=g?g[DP]:rM,P=f[sM];return P||(P=f[sM]={}),f.setNext(C),g&&doPerf22(f[oR](),(function(){return A+":"+_}),(function(){P[v]=!0;try{var g=C?C._id:aR;g&&(P[g]=!1),b=S(f)}catch(g){var T=!C||P[C._id];T&&(b=!0),C&&T||_throwInternal22(f[WP](),1,73,"Plugin ["+A+"] failed during "+_+" - "+dumpObj2(g)+", run flags: "+dumpObj2(P))}}),T,I),b}function _processTelemetry(f,S){function _callProcessTelemetry(S){if(!g||!_)return!1;var v=_getPluginState22(g);return!v[$P]&&!v[lR]&&(T&&g[YP](C),g[dR](f,S),!0)}_processChain(S=S||_getTelCtx(),_callProcessTelemetry,"processTelemetry",(function(){return{item:f}}),!f.sync)||S[xP](f)}function _unloadPlugin(f,S){function _callTeardown(){var v=!1;if(g){var C=_getPluginState22(g),_=g[oR]||C[oR];!g||_&&_!==f.core()||C[$P]||(C[oR]=null,C[$P]=!0,C[NP]=!1,g[$P]&&!0===g[$P](f,S)&&(v=!0))}return v}_processChain(f,_callTeardown,"unload",(function(){}),S[qP])||f[xP](S)}function _updatePlugin(f,S){function _callUpdate(){var v=!1;if(g){var C=_getPluginState22(g),_=g[oR]||C[oR];!g||_&&_!==f.core()||C[$P]||g[KP]&&!0===g[KP](f,S)&&(v=!0)}return v}_processChain(f,_callUpdate,"update",(function(){}),!1)||f[xP](S)}return Pl(I)}function createUnloadHandlerContainer22(){var g=[];function _addHandler(f){f&&g[PP](f)}function _runHandlers(f,S){arrForEach2(g,(function(g){try{g(f,S)}catch(g){_throwInternal22(f[WP](),2,73,"Unexpected error calling unload handler - "+dumpObj2(g))}})),g=[]}return{add:_addHandler,run:_runHandlers}}function createUnloadHookContainer22(){var g=[];function _doUnload(f){var S=g;g=[],arrForEach2(S,(function(g){try{(g.rm||g.remove).call(g)}catch(g){_throwInternal22(f,2,73,"Unloading:"+dumpObj2(g))}}))}function _addHook(f){f&&arrAppend2(g,f)}return{run:_doUnload,add:_addHook}}var lM,cM="getPlugin",dM=((nM={})[cR]={isVal:isNotNullOrUndefined22,v:{}},nM),hM=function(){function BaseTelemetryPlugin3(){var g,f,S,v,C,_=this;function _getTelCtx(g){void 0===g&&(g=null);var v=g;if(!v){var C=f||createProcessTelemetryContext22(null,{},_[oR]);v=S&&S[cM]?C[HP](null,S[cM]):C[HP](null,S)}return v}function _setDefaults(g,v,C){createDynamicConfig22(g,dM,safeGetLogger22(v)),!C&&v&&(C=v[UP]()[JP]());var T=S;S&&S[cM]&&(T=S[cM]()),_[oR]=v,f=createProcessTelemetryContext22(C,g,v,T)}function _initDefaults(){g=!1,_[oR]=null,f=null,S=null,C=createUnloadHookContainer22(),v=createUnloadHandlerContainer22()}_initDefaults(),dynamicProto2(BaseTelemetryPlugin3,_,(function(f){f[OP]=function(f,S,v,C){_setDefaults(f,S,C),g=!0},f[$P]=function(g,_){var T,I=f[oR];if(I&&(!g||I===g[oR]())){var b,A=!1,P=g||createProcessTelemetryUnloadContext22(null,I,S&&S[cM]?S[cM]():S),R=_||((T={reason:0})[qP]=!1,T);return f[zP]&&!0===f[zP](P,R,_unloadCallback)?b=!0:_unloadCallback(),b}function _unloadCallback(){A||(A=!0,v.run(P,_),C.run(P[WP]()),!0===b&&P[xP](R),_initDefaults())}},f[KP]=function(g,v){var C=f[oR];if(C&&(!g||C===g[oR]())){var _,T=!1,I=g||createProcessTelemetryUpdateContext22(null,C,S&&S[cM]?S[cM]():S),b=v||{reason:0};return f._doUpdate&&!0===f._doUpdate(I,b,_updateCallback)?_=!0:_updateCallback(),_}function _updateCallback(){T||(T=!0,_setDefaults(I.getCfg(),I.core(),I[JP]()))}},proxyFunctionAs22(f,"_addUnloadCb",(function(){return v}),"add"),proxyFunctionAs22(f,"_addHook",(function(){return C}),"add"),objDefine2(f,"_unloadHooks",{g:function(){return C}})})),_[WP]=function(g){return _getTelCtx(g)[WP]()},_[NP]=function(){return g},_.setInitialized=function(f){g=f},_[YP]=function(g){S=g},_[xP]=function(g,f){f?f[xP](g):S&&hl(S[dR])&&S[dR](g,null)},_._getTelCtx=_getTelCtx}return BaseTelemetryPlugin3.__ieDyn=1,BaseTelemetryPlugin3}(),uM="",gM="timings",pM="processTelemetryStart";function getTenantId22(g){if(g){var f=oc(g,"-");if(f>-1)return strLeft2(g,f)}return uM}(lM={})[0]=0,lM[2]=6,lM[1]=1,lM[3]=7,lM[4098]=6,lM[4097]=1,lM[4099]=7;var mM,fM,SM=perfNow2;function setProcessTelemetryTimings22(g,f){var S=g;S[gM]=S[gM]||{},S[gM][pM]=S[gM][pM]||{},S[gM][pM][f]=SM()}function isGreaterThanZero22(g){return g>0}function isValidPersistenceLevel(g){return pl(g)&&g>=1&&g<=2}(fM=mM||(mM={}))[fM.LocalStorage=1]="LocalStorage",fM[fM.SessionStorage=2]="SessionStorage",fM[fM.IndexedDb=3]="IndexedDb";var vM="readwrite",CM="result",yM="DBError: Unable to open database",EM="Database is not open",_M="DBError: Failed to Open Cursor",TM="DBError: Failed to delete the database",IM="DBError: Database does not exist",bM="DBError: Database upgrade required",AM="DBError: Feature not supported",PM=["indexedDB"],RM=hl,MM=dl,wM=0;function _getDbFactory(){var g=getGlobal2()||{},f=null;if(g)try{for(var S=0;S<PM.length;S++)if((f=g[PM[S]])&&RM(f.open))return f}catch(g){f=null}return f||null}function _debugLog(g,f){getInst2("QUnit")&&console&&console.log("  ["+toISOString22(new Date)+"]: IndexedDbHelper ["+g+"] "+f)}function _warnLog(g,f,S){g&&g.warnToConsole("IndexedDbHelper ["+f+"] "+S)}function _eventReject(g,f,S,v){return function(C){S(new Error(f)),_debugLog(g,"["+v+"] event rejected")}}var OM=[];function _getDbContext(g,f){for(var S=null,v=0;v<OM.length;v++)if((S=OM[v]).name===g)return S;return S={name:g,sch:createTaskScheduler(createAsyncPromise2,"IndexedDbHelper["+g+"]"),dbHdl:[],add:function(f){S.dbHdl.push(f),_debugLog(g,"- dbOpened (add) -- hdls ["+S.dbHdl.length+"]")},remove:function(f){for(var v=S.dbHdl,C=0;C<v.length;C++)if(v[C]===f){v.splice(C,1);break}_debugLog(g,"- dbClosed (remove) -- hdls ["+S.dbHdl.length+"]")},isOpen:function(){return S.dbHdl.length>0},openHdl:function(){return S.dbHdl.length>0?S.dbHdl[0]:null}},OM.push(S),S}var DM=function(){function IndexedDbHelper2(g){var f=wM++,S=0;dynamicProto2(IndexedDbHelper2,this,(function(v){var C=_getDbFactory()||null;function _createStoreContext(v,C,_){var T=v.db,I=S++;_debugLog(v.dbName,"["+f+":"+I+"] txn.open - "+C+" -- "+_);var b=T.transaction(C,vM);return b.onabort=function(){_warnLog(g,v.dbName,"["+f+":"+I+"] txn.onabort - "+C+" -- "+_+" -- "+dumpObj2(b.error))},b.onerror=function(){_warnLog(g,v.dbName,"["+f+":"+I+"] txn.onerror - "+C+" -- "+_)},b.oncomplete=function(){_debugLog(v.dbName,"["+f+":"+I+"] txn.oncomplete - "+C+" -- "+_)},{db:v,store:b.objectStore(C),tx:b,tbl:C,openCursor:function(g,f){return _openCursor(v,C,g,f)},newTransaction:function(g){return _openStore(v,C,g)}}}function _openStore(g,f,S){if(!g||!g.db)return mh(new Error(EM));try{var v=S(_createStoreContext(g,f,"openStore"));return isPromiseLike22(v)?v:ph(v)}catch(g){return mh(g)}}function _openCursor(g,f,S,v){if(!g||!g.db)return mh(new Error(EM));var C=null;return S&&MM(S)?C=new NM(S):S&&S.isMatch&&(C=S),createAsyncPromise2((function(S,_){var T=[],I=null,b=null;C&&C.keyRange&&(b=C.keyRange());var A=_createStoreContext(g,f,"openCursor");(I=b?A.store.openCursor(b):A.store.openCursor()).onerror=_eventReject(A.db.dbName,_M,_,"openCursor"),I.onsuccess=function(g){var f=g.target[CM];if(f){var I={store:A,cursor:f,continue:function(){f.continue()},done:function(){S(T)}},b=f.value;if(!C||C.isMatch(b))if(v)try{switch(v(I,b,T)){case 2:S(T);break;case 1:break;default:I.continue()}}catch(g){_(g)}else T.push(b),I.continue();else I.continue()}else S(T)}}))}function _scheduleEvent(g,f,S,v){return _getDbContext(g).sch.queue(S,f,v)}v.isAvailable=function(){return!!C},v.openDb=function(f,S,v,_){return _scheduleEvent(f,"openDb",(function(T){return createAsyncPromise2((function(I,b){var A=!1;function _createDbCtx(g,v,C,_,T){var I={db:v,dbName:f,dbVersion:S,ctx:null,isNew:_,txn:C?C.transaction:null};return T||(I.openStore=function(g,f){return _openStore(I,g,f)},I.openCursor=function(g,f,S){return _openCursor(I,g,f,S)}),I}function _databaseUpgrade(g,f){var S=_createDbCtx(null,g,f,!0,!0);if(_)A=!0,doAwaitResponse2(_(S),(function(g){if(g.rejected)try{f.transaction&&f.transaction.abort()}finally{b(g.reason)}else S.txn||(S.txn=f.transaction)}));else try{f.transaction&&f.transaction.abort()}finally{b(new Error(bM))}}function _databaseOpen(S,C){var _=_getDbContext(f);_.add(S),S.onabort=function(v){_warnLog(g,f,"onabort -- closing the Db"),_.remove(S)},S.onerror=function(v){_warnLog(g,f,"onerror -- closing the Db"),_.remove(S)},S.onclose=function(v){_warnLog(g,f,"onclose -- closing the Db"),_.remove(S)},S.onversionchange=function(v){_warnLog(g,f,"onversionchange -- force closing the Db"),S.close(),_.remove(S)};var T=null,P=null;_.dbHdl.length>0&&(P=_.dbHdl[0]),T=_createDbCtx(_,P,C,A);try{doAwait2(v(T),I,b)}catch(g){b(g)}}var P=_getDbContext(f);if(null==C)b(new Error("No available storage factory"));else if(P.isOpen()){var R=_createDbCtx(P,P.openHdl(),null,!1);doAwait2(v(R),I,b)}else{var M=C.open(f,S);M.onblocked=function(S){_warnLog(g,f,"Db Open Blocked event ["+T+"] - "+(M.error||"")),b(new Error(yM))},M.onerror=function(S){_warnLog(g,f,"Db Open Error event ["+T+"] - "+(M.error||"")),b(new Error(yM))},M.onupgradeneeded=function(g){_debugLog(f,"Db Open Create/Upgrade needed event ["+T+"]");try{var S=g.target[CM];if(!S)return void b(new Error(yM));_databaseUpgrade(S,M)}catch(g){_eventReject(f,yM,b,T)(g)}},M.onsuccess=function(g){var f=g.target[CM];f?_databaseOpen(f,M):b(new Error(yM))}}}))}))},v.closeDb=function(g){_scheduleEvent(g,"closeDb",(function(f){var S=_getDbContext(g),v=S.dbHdl,C=v.length;if(C>0){for(var _=0;_<C;_++)v[_].close();S.dbHdl=[]}return 1})).catch((function(g){}))},v.deleteDb=function(f){return null!=C&&_scheduleEvent(f,"deleteDb",(function(S){var v=_getDbContext(f),_=v.dbHdl,T=_.length;if(T>0){_warnLog(g,f,"Db is open ["+T+"] force closing");for(var I=0;I<T;I++)_[I].close();v.dbHdl=[]}return createAsyncPromise2((function(v,_){setTimeout((function(){try{_debugLog(f,"["+S+"] starting");var T=C.deleteDatabase(f);T.onerror=function(v){_warnLog(g,f,"["+S+"] error!!"),_(new Error(TM))},T.onblocked=function(v){_warnLog(g,f,"["+S+"] blocked!!"),_(new Error(TM))},T.onupgradeneeded=function(v){_warnLog(g,f,"["+S+"] upgrade needed!!"),_(new Error(TM))},T.onsuccess=function(g){_debugLog(f,"["+S+"] complete"),v(!0)},_debugLog(f,"["+S+"] started")}catch(v){_warnLog(g,f,"["+S+"] threw - "+v),_(new Error(TM+" - "+v))}}),0)}))}))},v.getDbDetails=function(g){return _scheduleEvent(g,"getDbDetails",(function(f){return null!=C&&C.databases?createAsyncPromise2((function(f,S){C.databases().then((function(v){for(var C=0;C<v.length;C++)if(v[C].name===g)return void f(v[C]);S(new Error(IM))}),S)})):mh(new Error(AM))}),2e3)}}))}return IndexedDbHelper2.__ieDyn=1,IndexedDbHelper2}(),NM=function(){function SimpleQuery2(g){var f=[],S=null;dynamicProto2(SimpleQuery2,this,(function(v){v.keyRange=function(){return S},v.parseQuery=function(g){if(f=[],g)for(var C=g.split(";"),_=0;_<C.length;_++){var T=C[_],I=T.indexOf("=");if(-1!==I){var b=T.substring(0,I),A=T.substring(I+1);0===b.indexOf("#")&&(b=b.substring(1),S||(S=IDBKeyRange.bound(A,A+""))),v.startsWith(b,A)}}},v.startsWith=function(g,S){f.push({name:g,value:S,type:0})},v.contains=function(g,S){f.push({name:g,value:S,type:1})},v.isMatch=function(g){if(!f||0===f.length)return!0;if(!g)return!1;for(var S=0;S<f.length;S++){var v=f[S],C=g[v.name];if(C)if(0===v.type){if(0!==C.indexOf(v.value))return!1}else if(1===v.type&&-1===C.indexOf(v.value))return!1}return!0},g&&v.parseQuery(g)}))}return SimpleQuery2.__ieDyn=1,SimpleQuery2}(),kM=10,LM=1,FM=6e5,xM=6048e5,UM="Unknown",VM=-1,BM="DBError: Unable to add event",HM="DBError: Unable to update iKey",$M=1,jM="Evts",GM="iKey",qM=isValidPersistenceLevel;function _getTime(){return(new Date).getTime()}function _eventReject2(g,f){return function(S){return f(new Error(g))}}function _createDb(g){g.objectStoreNames.contains(jM)||g.createObjectStore(jM,{keyPath:"key"}).createIndex("EvntId","key",{unique:!1}),g.objectStoreNames.contains(GM)||g.createObjectStore(GM,{keyPath:"iKey"}).createIndex("iKey","iKey",{unique:!0})}function _updateiKey(g){return g.openStore(GM,(function(f){return createAsyncPromise2((function(S,v){var C={iKey:g.ctx.iKey,tm:_getTime()},_=f.store.put(C);_.onsuccess=function(g){S(_.result.toString())},_.onerror=function(g){v(new Error(BM))},_.onerror=_eventReject2(HM,v)}))}))}function _orderEventsByPriority(g){for(var f=[],S=2;S>=1;S--)for(var v=0;v<g.length;v++){var C=g[v];C&&C.evt.persistence===S&&f.push(C.evt)}return f}function _addEventByTime(g,f){for(var S=0;S<g.length;S++)if(f.tm<g[S].tm)return void g.splice(S,0,f);g.push(f)}function _getKeyIndex(g,f){for(var S=f.length,v=0;v<S;v++)if(g===f[v].id)return v;return-1}function _isOldItem(g,f){var S=g.tm;return _getTime()-S>f}function _cursorContinueEvent(g){return function(f){return g.continue()}}function _cursorDeleteAndContinue(g){var f=g.cursor.delete();return f.onerror=_cursorContinueEvent(g),f.onsuccess=_cursorContinueEvent(g),1}function _getAllEventsForiKey(g,f){return g.openCursor(jM,f,(function(g,f,S){return S.push(f),0}))}function _deleteEvents(g,f,S){return g.openCursor(jM,f,(function(g,f,v){return S(f)?(v.push(f),_cursorDeleteAndContinue(g)):0}))}function _deleteOrphanedEvents(g){return createAsyncPromise2((function(f,S){var v=!1;g.openCursor(GM,null,(function(g,f,S){var C=f.tm;return _getTime()-C<xM?0:(v=!0,2)})).then((function(){if(v){var C={};_deleteEvents(g,null,(function(g){if(!g||!g.evt||!g.evt.iKey)return!0;var f=g.tm;return _getTime()-f>xM||(C[g.evt.iKey]=1,!1)})).then((function(){var v=[];g.openCursor(GM,null,(function(g,f,S){var _=f.tm;return _getTime()-_<xM||C[f.iKey]?0:(v.push(f),_cursorDeleteAndContinue(g))})).then((function(){f(v)}),S)}),S)}else f([])}),S)}))}function _moveOldEventsToCurrentStore(g,f){return g.openCursor(jM,"#key="+g.ctx.iKeyPrefix(),(function(S,v){var C=v.key;if(0===C.indexOf(g.ctx.iKeyPrefix())&&-1===C.indexOf(g.ctx.evtKeyPrefix())&&_isOldItem(v,f)){v.key=g.ctx.evtKeyPrefix()+v.id;var _=S.store.store.put(v);return _.onerror=_cursorContinueEvent(S),_.onsuccess=function(g){try{_cursorDeleteAndContinue(S)}catch(g){S.continue()}},1}return 0}))}function _checkVersionAndMoveEventsToCurrentStorage(g,f){return createAsyncPromise2((function(S,v){_deleteOrphanedEvents(g).then((function(){_moveOldEventsToCurrentStore(g,f).then(S,S)}),v)}))}function _dropEventsUpToPersistence(g,f){return createAsyncPromise2((function(S,v){var C=0,_=g.ctx.evtKeyPrefix();function _resolveWithDroppedEvents(){S(C)}function _dropEvent(g,f){return createAsyncPromise2((function(S){var v=g.store.delete(f.key);v.onsuccess=function(g){C++,S()},v.onerror=function(g){S()}}))}function _processCandidates(f){0!==f.length?g.openStore(jM,(function(g){for(var S=[],v=0;v<f.length;v++)S.push(_dropEvent(g,f[v]));return gh(S).then(_resolveWithDroppedEvents,_resolveWithDroppedEvents)})):_resolveWithDroppedEvents()}g.openCursor(jM,"#key="+_,(function(g,S,v){return S.evt.persistence<=f&&0===S.key.indexOf(_)&&(_addEventByTime(v,S),v.length>kM&&v.splice(v.length-1,1)),0})).then(_processCandidates,(function(){S(0)}))}))}var WM=function(){function IndexedDbProvider2(g,f){dynamicProto2(IndexedDbProvider2,this,(function(S){var v=null,C=null,_=UM,T=null,I=null,b=null,A=VM,P=0,R=FM;function _openDb(g){function _handleDbUpgrade(g){return createAsyncPromise2((function(f,S){_createDb(g.db),f()}))}function _handleDbOpen(f){return createAsyncPromise2((function(S,v){var C={iKey:_,storageId:T,iKeyPrefix:function(){return I},evtKeyPrefix:function(){return b}};f.ctx=C,doAwait2(_updateiKey(f),(function(){doAwait2(g(f),S,v)}),v)}))}return v.openDb(C,$M,_handleDbOpen,_handleDbUpgrade)}function _addDbEvent(g,f,S){return createAsyncPromise2((function(v,C){function dropEvents(f,S){_dropEventsUpToPersistence(g,f).then((function(g){g>0&&(P-=g),S(g)}),(function(g){S(0)}))}function resolveAddEvent(g){v(f.evt)}function _insertNewEvent(){g.openStore(jM,(function(_){var T=_.store.put(f);T.onsuccess=function(C){S&&_updateiKey(g).then(resolveAddEvent,resolveAddEvent),P++,v(f.evt)},T.onerror=function(_){function _retryAddEvent(S){0===S&&C(new Error(BM)),_addDbEvent(g,f,!1).then((function(g){v(f.evt)}),(function(){C(new Error(BM))}))}S?dropEvents(1,(function(g){g>0?_retryAddEvent(g):f.evt.persistence>=2?dropEvents(2,(function(g){_retryAddEvent(g)})):C(new Error(BM))})):C(new Error(BM))}}))}A>0&&P>=A?dropEvents(1,(function(g){0===g?f.evt.persistence>=2?dropEvents(2,(function(g){_insertNewEvent()})):C(new Error(BM)):_insertNewEvent()})):_insertNewEvent()}))}S.id=g,S.initialize=function(g){var P=g.itemCtx.diagLog();if(!(v=new DM(P)).isAvailable())return v=null,!1;var M=g.itemCtx.getCfg(),w=g.storageConfig;_=M.instrumentationKey||_,T=S.id||g.id||newGuid3(),b=(I=_+"::")+T+"::",R=w.accessThresholdInMs||R;var O=onConfigChange22(w,(function(){A=w.maxStorageItems;var g=w.indexedDbName;C&&g!==C&&C&&doAwaitResponse2(S.clear(),(function(f){C=g,_openDb((function(g){return g.isNew?[]:_checkVersionAndMoveEventsToCurrentStorage(g,R)})).then((function(g){}),(function(g){P.warnToConsole("IndexedDbProvider failed to initialize - "+(g||"<unknown>")),v=null}))})),C=g}));return f&&f.add(O),_openDb((function(g){return g.isNew?[]:_checkVersionAndMoveEventsToCurrentStorage(g,R)})).then((function(g){}),(function(g){P.warnToConsole("IndexedDbProvider failed to initialize - "+(g||"<unknown>")),v=null})),!0},S._getDbgPlgTargets=function(){return[C]},S.supportsSyncRequests=function(){return!1},S.getAllEvents=function(){return null!=v&&v.isAvailable()?_openDb((function(g){return createAsyncPromise2((function(f,S){_getAllEventsForiKey(g,"#key="+g.ctx.evtKeyPrefix()).then((function(g){P=g.length,f(_orderEventsByPriority(g))}),S)}))})):[]},S.addEvent=function(g,f,S){return null!=v&&v.isAvailable()?(f.id=f.id||newGuid3(),qM(f.persistence)||(f.persistence=1),_openDb((function(S){var v=g||f.id,C={key:S.ctx.evtKeyPrefix()+v,id:v,evt:f,tm:_getTime(),v:LM};return _addDbEvent(S,C,!0)}))):f},S.removeEvents=function(g){if(null==v||!v.isAvailable())return[];var f=[];return createAsyncPromise2((function(S,v){_openDb((function(S){return S.openCursor(jM,"#key="+S.ctx.iKey,(function(S,v,C){if(-1!==_getKeyIndex(v.id,g)){var _=S.cursor.delete();return _.onerror=_cursorContinueEvent(S),_.onsuccess=function(){f.push(v.evt),S.continue()},1}return 0}))})).then((function(g){P-=f.length,S(f)}),(function(g){P-=f.length,S(f)}))}))},S.clear=function(){return null!=v&&v.isAvailable()?createAsyncPromise2((function(g,f){_openDb((function(g){return _deleteEvents(g,"#key="+g.ctx.evtKeyPrefix(),(function(f){return 0===f.key.indexOf(g.ctx.evtKeyPrefix())}))})).then((function(f){P=0,g(_orderEventsByPriority(f))}),f)})):[]},S.moveStaleEvents=function(){_openDb((function(g){return _checkVersionAndMoveEventsToCurrentStorage(g,R)}))},S.teardown=function(){v&&v.closeDb(C)}}))}return IndexedDbProvider2.__ieDyn=1,IndexedDbProvider2}(),zM=10,KM="3",JM="Version",YM="AWTEvents",QM=5e6;function _isQuotaExceeded(g,f){var S=!1;return f instanceof DOMException&&(22!==f.code&&"QuotaExceededError"!==f.name&&1014!==f.code&&"NS_ERROR_DOM_QUOTA_REACHED"!==f.name||g&&0!==g.length&&(S=!0)),S}function _getAvailableStorage(g){var f=getGlobal2()||{},S=null;try{if(S=f[g]){var v="__storage_test__";S.setItem(v,v),S.removeItem(v)}}catch(g){_isQuotaExceeded(S,g)||(S=null)}return S}function _forEachMap(g,f){if(g)for(var S=Al(g),v=0;v<S.length;v++){var C=S[v];if(!f(g[C],C))break}}function _isMapEmpty(g){var f=!0;return _forEachMap(g,(function(g,S){return g&&(f=!1),f})),f}function _dropEventsUpToPersistence2(g,f){for(var S=1,v=0,_loop_1=function(){var g=[],C=f[S];if(_forEachMap(C,(function(f,S){return g.push(S),++v<zM})),v>0){for(var _=0;_<g.length;_++)delete C[g[_]];return{value:!0}}S++};S<=g&&v<zM;){var C=_loop_1();if("object"==typeof C)return C.value}return v>0}var XM=isValidPersistenceLevel,ZM=function(){function WebStorageProvider2(g,f,S){dynamicProto2(WebStorageProvider2,this,(function(v){var C=null,_=YM,T=null,I=KM,b=null,A=null,P=QM,R=6e5,M=null,w=null;function _newStore(g,f){return{key:g,db:f}}function _fetchStoredDb(g,f){void 0===f&&(f=!0);var S=null;if(C){var v=C.getItem(g);if(v)try{S=JSON.parse(v)}catch(f){C.removeItem(g)}}return f&&!S&&(S={events:{1:{},2:{},3:{}},lastAccessTime:0}),_newStore(g,S)}function _updateStoredDb(g,f){void 0===f&&(f=!0);var S=!0,v=g.db;if(v){f&&(v.lastAccessTime=(new Date).getTime());for(var _=1;_<=2;_++)if(!_isMapEmpty(v.events[_])){S=!1;break}}try{if(S)C&&C.removeItem(g.key);else{var T=JSON.stringify(v);if(T.length>P)return!1;C&&C.setItem(g.key,T)}}catch(g){return!1}return!0}function _clearDatabase(g){var f=[],S=_fetchStoredDb(g,!1),v=S.db;if(v){var _=v.events;try{for(var T=1;T<=2;T++)_forEachMap(_[T],(function(g,S){return g&&f.push(g),!0}))}catch(g){}C&&C.removeItem(S.key)}return f}function _checkVersionAndMoveEventsToCurrentStorage2(){if(C){for(var g=C.getItem(M),f=[],S=_fetchStoredDb(w),v=!1,T=0;T<C.length;T++){var b=C.key(T);if(0===b.indexOf(_)&&b!==M){if(g!==KM){f.push(_newStore(b,null));continue}var P=_fetchStoredDb(b,!1),O=P.db;if(O){if((new Date).getTime()-O.lastAccessTime>R){for(var D=1,_loop_3=function(){var g=O.events[D],f=S.db.events[D];_forEachMap(g,(function(S,v){return(getTenantId22(S.iKey)||S.iKey)===A&&(f[v]=S,delete g[v]),!0})),D++};D<=2;)_loop_3();v=!0,f.push(P)}}else f.push(_newStore(b,null))}}for(T=0;T<f.length;T++)_updateStoredDb(f[T],!1);v&&_updateStoredDb(S),C.setItem(M,I)}}v.id=f,C=_getAvailableStorage(g)||null,v._getDbgPlgTargets=function(){return[_,P]},v.initialize=function(g){if(!C)return!1;var f=g.storageConfig;T=v.id||g.id||newGuid3(),b=g.itemCtx.getCfg().instrumentationKey,A=getTenantId22(b)||b,R=f.accessThresholdInMs?f.accessThresholdInMs:R;var I=onConfigChange22(f,(function(){P=f.maxStorageSizeInBytes;var g=f.storageKey;_&&g!==_&&doAwaitResponse2(v.clear(),(function(f){w=(_=g)+"."+T,M=_+JM,_checkVersionAndMoveEventsToCurrentStorage2()}))}));return S&&S.add(I),_=f.storageKey,w=_+"."+T,M=_+JM,_checkVersionAndMoveEventsToCurrentStorage2(),!0},v.supportsSyncRequests=function(){return!0},v.getAllEvents=function(){try{var g=[],f=_fetchStoredDb(w,!1).db;if(f)for(var S=f.events,v=2;v>=1;v--)_forEachMap(S[v],(function(f){return f&&(getTenantId22(f.iKey)||f.iKey)===A&&g.push(f),!0}));return g}catch(g){return mh(g)}},v.addEvent=function(g,f,S){try{var v=_fetchStoredDb(w);f.id=f.id||newGuid3(),XM(f.persistence)||(f.persistence=1);for(var C=f.persistence,_=f.id,T=v.db.events;;){if(T[C][_]=f,_updateStoredDb(v))return f;if(delete T[C][_],!_dropEventsUpToPersistence2(C,T))return mh(new Error("Unable to free up event space"))}}catch(g){return mh(g)}},v.removeEvents=function(g){try{var f=_fetchStoredDb(w,!1),S=f.db;if(S){var v=S.events;try{for(var C=0;C<g.length;++C){var _=g[C];delete v[_.persistence][_.id]}if(_updateStoredDb(f))return g}catch(g){}g=_clearDatabase(f.key)}return g}catch(g){return mh(g)}},v.clear=function(){try{var g=[],f=_fetchStoredDb(w,!1),S=f.db;if(S){for(var v=S.events,_loop_2=function(f){var S=v[f];_forEachMap(S,(function(f){return f&&(getTenantId22(f.iKey)||f.iKey)===A&&(delete S[f.id],g.push(f)),!0}))},C=2;C>=1;C--)_loop_2(C);_updateStoredDb(f)}return g}catch(g){return mh(g)}},v.teardown=function(){try{var g=_fetchStoredDb(w,!1),f=g.db;f&&(f.lastAccessTime=0,_updateStoredDb(g,!1))}catch(g){}},v.moveStaleEvents=function(){_checkVersionAndMoveEventsToCurrentStorage2()}}))}return WebStorageProvider2.__ieDyn=1,WebStorageProvider2}(),ew="4.3.1",tw="LocalStorage",iw=5,nw=isValidPersistenceLevel,rw=void 0,sw="AppInsightEvents.1",aw=objDeepFreeze2({maxStorageSizeInBytes:{isVal:isGreaterThanZero22,v:5e6},storageKey:"AWTEvents",minPersistenceLevel:{isVal:nw,v:1},providers:[mM.LocalStorage,mM.IndexedDb],indexedDbName:sw,maxStorageItems:{isVal:isGreaterThanZero22,v:rw}}),ow=function(g){function LocalStorageChannel2(){var f=g.call(this)||this;return f.identifier=tw,f.priority=1009,f.version=ew,dynamicProto2(LocalStorageChannel2,f,(function(g,f){var S,v,C,_;function _initDefaults(){S=!1,v=!1,C=null,_=[]}function _queueStorageEvent(g,f){C||(C=createTaskScheduler(createAsyncPromise2,"LocalStorage")),C.queue((function(g){return f(g)}),g).catch((function(g){}))}function _sendStoredEventsToNextPlugin(f){doPerf22(g.core,(function(){return"LocalStorageChannel:_sendStoredEventsToNextPlugin"}),(function(){_queueStorageEvent("sendToNext",(function(S){return doAwaitResponse2(f.provider.getAllEvents(),(function(S){for(var v=S.value||[],C=0;C<v.length;C++)try{var _=v[C];(getTenantId22(_.iKey)||_.iKey)===f.tenantId&&g.processNext(_,f.coreRootCtx.createNew())}catch(g){}}))}))}),(function(){return{iKeyConfig:f}}))}function _removeEvents(f,S){doPerf22(g.core,(function(){return"LocalStorageChannel:_removeEvents"}),(function(){_queueStorageEvent("removeEvents",(function(g){var v=[];if(arrForEach2(S,(function(g){(getTenantId22(g.iKey)||g.iKey)===f.tenantId&&v.push(g)})),v.length>0)return doAwaitResponse2(f.provider.removeEvents(v),(function(g){}))}))}),(function(){return{iKeyConfig:f,events:S}}))}function _shouldCacheEvent(g,f){return!(f.sync||f.persistence<g.minPersistenceCacheLevel)}function _tryGetIndexedDbProvider(f){var S=new WM(void 0,g._unloadHooks);return S.initialize(f)||(S=null),S}function _tryGetWebStorageProvider(f,S){var v=new ZM(f,void 0,g._unloadHooks);return v.initialize(S)||(v=null),v}function _initializeProvider(g){for(var f=g.storageConfig.providers,S=null,v=0;!S&&v<f.length&&v<iw;)switch(f[v++]){case mM.LocalStorage:S=_tryGetWebStorageProvider("localStorage",g);break;case mM.SessionStorage:S=_tryGetWebStorageProvider("sessionStorage",g);break;case mM.IndexedDb:S=_tryGetIndexedDbProvider(g)}return S}function _compareProviders(g,f){if(g.length!==f.length)return!1;var S=!0;return arrForEach2(g,(function(g,v){if(g!==f[v])return S=!1,-1})),S}function _getCoreItemCtx(f,S,v,C){f&&(f.extensionConfig=f.extensionConfig||[]),!C&&S&&(C=S.getProcessTelContext().getNext());var _=null,T=g._getTelCtx().getNext();return T&&(_=T.getPlugin()),createProcessTelemetryContext22(C,f,S,_)}function _createIkeyConfig(f,S,v,C){var T=!1;if(arrForEach2(_,(function(g){if(g.iKey===f.instrumentationKey)return T=!0,-1})),!T){var I=null;g._addHook(onConfigChange22(f,(function(v){var C=createProcessTelemetryContext22(null,v.cfg,S);I=C.getExtCfg(g.identifier,aw);var T=!1,b=null,A=f.instrumentationKey;if(arrForEach2(_,(function(g){if(g.iKey===A)return T=!0,b=g,-1})),T&&b){var R=I.providers,M=b.preProviders;_compareProviders(R,M)||doAwaitResponse2(P.clear(),(function(g){if(!g.rejected)try{var f=_.indexOf(b);-1!==f&&_.splice(f,1);var v=_initializeProvider(b.providerContext);b.provider=v,b.preProviders=R.slice();var C=b.preListener;C&&S.removeNotificationListener(C);var T={eventsSent:function(g){_removeEvents(b,g)},eventsDiscarded:function(g,f){_removeEvents(b,g)}};b.preListener=T,_.push(b),S.addNotificationListener(T),_sendStoredEventsToNextPlugin(b)}catch(g){}}))}})));var b=_getCoreItemCtx(f,S,v,C),A={itemCtx:b,storageConfig:I,id:g.id};if(!dl(f.instrumentationKey))return;var P=_initializeProvider(A),R={iKey:f.instrumentationKey,tenantId:getTenantId22(f.instrumentationKey)||f.instrumentationKey,minPersistenceCacheLevel:1,coreRootCtx:b,providerContext:A,provider:P,preProviders:I.providers.slice()};if(P){nw(I.minPersistenceLevel||-1)&&(R.minPersistenceCacheLevel=I.minPersistenceLevel);var M={eventsSent:function(g){_removeEvents(R,g)},eventsDiscarded:function(g,f){_removeEvents(R,g)}};R.preListener=M,_.push(R),S.addNotificationListener(M),_sendStoredEventsToNextPlugin(R)}else _.push(R)}}_initDefaults(),g.initialize=function(g,v,_,T){doPerf22(v,(function(){return"LocalStorageChannel.initialize"}),(function(){S||(f.initialize(g,v,_),f.setInitialized(!1),S=!0,C=createTaskScheduler(createAsyncPromise2,"LocalStorage")),_createIkeyConfig(g,v,_,T)}),(function(){return{coreConfig:g,core:v,extensions:_,pluginChain:T}}))},g.processTelemetry=function(f,C){var T=f;if(S&&!v){C=g._getTelCtx(C),setProcessTelemetryTimings22(f,g.identifier);var I=null;arrForEach2(_,(function(g){g.iKey===f.iKey&&(I=g)}));var b=I?I.provider:null;if(T.sync||!b)return void g.processNext(T,C);T.id=T.id||newGuid3(),isValidPersistenceLevel(T.persistence)||(T.persistence=1),_shouldCacheEvent(I,T)&&_queueStorageEvent("processTelemetry",(function(g){return b.addEvent(T.id,T,C)}))}g.processNext(T,C)},g.pause=function(){v=!0},g.resume=function(){doPerf22(g.core,(function(){return"LocalStorageChannel:resume"}),(function(){v=!1,arrForEach2(_,(function(g){g.provider&&_sendStoredEventsToNextPlugin(g)}))}))},g._doTeardown=function(g,f){arrForEach2(_,(function(g){var f=g.provider;f&&f.teardown()})),_initDefaults()},g.flush=function(g,f,S){},g._getDbgPlgTargets=function(){return[_]},g._sendStale=function(g){arrForEach2(_,(function(f){if(f&&f.iKey===g&&f.provider)return f.provider.moveStaleEvents(),_sendStoredEventsToNextPlugin(f),-1}))}})),f}return __extendsFn2(LocalStorageChannel2,g),LocalStorageChannel2.__ieDyn=1,LocalStorageChannel2}(hM),lw="LocalStorage",cw=class{constructor(g,f,S,v,C,_){this.logger=g,this.configProvider=f,this.clientInfo=S,this.contextProvider=v,this.accountCollectorURL=C,this.envOverride=_,this.manager=new Ov,this.managerConfig=this.createConfigForManager(),this.currentTransmitProfile=qt.REPORTING_PROFILE.RT_PROFILE,this.initManager(),this.uiVersion=this.getUiVersion(),this.configProvider.on("configUpdated",(()=>this.updateChannelConfig()))}createLogger(g,f){return new dw(g,this.manager,this.logger,this.configProvider,this.uiVersion,f,this.contextProvider,this.envOverride)}createConfigForManager(){return{channels:[],extensionConfig:{},propertyConfiguration:{populateBrowserInfo:!0,populateOperatingSystemInfo:!0},channelConfiguration:{eventsLimitInMem:this.configProvider.config.eventsLimitInMem,disableFetchKeepAlive:this.configProvider.config.oneDSDisableFetchKeepAlive,useSendBeacon:this.configProvider.config.oneDSUseSendBeacon},endpointUrl:this.accountCollectorURL,enableCompoundKey:this.configProvider.config.enableCompoundKey,disablePageUnloadEvents:this.configProvider.config.oneDSDisabledPageUnloadEvents}}getUiVersion(){const g=this.clientInfo.match(/^.*?\/(\d+\/)(.*?)\/.*$/);return g?g[1]+g[2]:this.clientInfo}updateChannelConfig(){this.configProvider.config.eventsLimitInMem!==this.managerConfig.channelConfiguration.eventsLimitInMem&&this.manager.getPostChannel().setEventQueueLimits(this.configProvider.config.eventsLimitInMem),this.setTransmitProfile()}initManager(){this.initLocalStorageChannel(),this.manager.create(this.managerConfig,[]),this.manager.getNotifyMgr().addNotificationListener({eventsDiscarded:(g,f)=>this.logDiscardedEvents(g,f),eventsSent:g=>this.logSentEvents(g)}),this.setTransmitProfile()}initLocalStorageChannel(){if(!this.configProvider.config.useLocalStorageForOneDs)return;const g=new ow;this.managerConfig.channels.push([g]);const f={storageKey:"TsCalling",accessThresholdInMs:this.configProvider.config.oneDSLocalStorage.accessThresholdInMs??6e5};this.managerConfig.extensionConfig[lw]=f}logDiscardedEvents(g,f){let S="discarded events:";g.forEach((g=>S=`${S+g.name};`)),this.logger.info(`${S} reason:${f}`)}logSentEvents(g){let f=`sent events: ${g[0]?.data?.CorrelationId&&getFrom("value",g[0].data.CorrelationId)}:`;g.forEach((g=>{f=`${f+g.name};`})),this.logger.info(`${f}`)}setTransmitProfile(){this.configProvider.config.transmitProfileTimings.length&&this.manager.getPostChannel()._loadTransmitProfiles({[this.configProvider.config.transmitProfileName]:this.configProvider.config.transmitProfileTimings}),this.configProvider.config.transmitProfileName!==this.currentTransmitProfile&&this.manager.getPostChannel()._setTransmitProfile(this.configProvider.config.transmitProfileName),this.currentTransmitProfile=this.configProvider.config.transmitProfileName}},dw=class{constructor(g,f,S,v,C,_,T,I){this.tenant=g,this.manager=f,this.logger=S,this.configProvider=v,this.uiVersion=C,this.eventLatency=_,this.contextProvider=T,this.envOverride=I,this.instanceConfig={extensions:[],extensionConfig:{}};const{oneDSLocalStorage:b,oneDSNotificationManager:A}=this.configProvider.config;A.blockEventsDiscardedNotifications&&this.blockEventsDiscarded(),A.blockNotificationsOnPageUnload&&this.blockNotificationListenersOnPageUnload(),b.sendStaleEvents&&this.sendStaleEvents()}sendEvent(g){this.setEnvPropertiesToEveryEvent();const f=g.props,S={};switch(this.logger.info(`preparing event for delivery: ${g.props?.CorrelationId??""}/${g.eventName}`),this.tenant){case"signaling":f.SkypeId&&(S.user_id={value:f.SkypeId,kind:10},S.Skype_InitiatingUser_Username={value:f.SkypeId,kind:10},S.SkypeId={value:f.SkypeId,kind:10},delete f.SkypeId),this.uiVersion&&(S.ui_version={value:this.uiVersion,kind:0});break;case"media":case"tlePlayer":this.uiVersion&&(S.uiVersion={value:this.uiVersion,kind:0});break;case"realtimeMedia":this.uiVersion&&(S["AppInfo.Version"]={value:this.uiVersion,kind:0})}for(const g of Object.keys(f)){const v=f[g];S[g]={value:v?.value??v,kind:v?.piiKind??0}}const v={name:g.eventName,data:S,latency:this.eventLatency,persistence:_p.Normal,sync:this.configProvider.config.oneDSEventSendType};this.configProvider.config.smallCallTelemetry.enable&&"mdsc_webrtc_call_session"===v.name&&(v.sync=this.configProvider.config.smallCallTelemetry.eventSendType),this.logger.info(`about to send event ${JSON.stringify(mP.omit(v,["LocalUser","TargetUser"]))}`),this.applicationInsights.track(v)}sendStaleEvents(){this.logger.info("preparing to send stalled telemetry events");const g=this.applicationInsights.getPlugin(lw).plugin;g._sendStale&&g._sendStale(this.tenantToken)}get applicationInsights(){return this.manager.getInst(this.tenantToken)??this.manager.newInst(this.tenantToken,this.instanceConfig,[])}get tenantToken(){return this.configProvider.config.telemetryTenants[this.tenant]}blockNotificationListenersOnPageUnload(){let g=!1;const setPageUnloading=()=>{g=!0},resetPageUnloading=()=>{g=!1};window.addEventListener("beforeunload",setPageUnloading),window.addEventListener("unload",setPageUnloading),window.addEventListener("pagehide",setPageUnloading),window.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?setPageUnloading():resetPageUnloading()})),this.applicationInsights.getNotifyMgr().listeners.forEach((f=>{const{eventsSent:S,eventsDiscarded:v}=f;S&&(f.eventsSent=f=>{g?this.logger.info("1DS eventSent was not raised due to page unload"):S(f)}),v&&(f.eventsDiscarded=(f,S)=>{g?this.logger.log("1DS eventsDiscarded was not raised due to page unload"):v(f,S)})}))}blockEventsDiscarded(){this.applicationInsights.getNotifyMgr().listeners.forEach((g=>{g.eventsDiscarded=(g,f)=>{this.logger.log(`1DS eventsDiscarded with reason ${f} was not raised due to configuration`)}}))}setEnvPropertiesToEveryEvent(){const g=this.contextProvider?.();if(!deepEqual(this.ctx,g)&&(this.ctx=g,this.ctx))if(this.envOverride){for(const g of Object.keys(this.envOverride||{}))if(this.ctx[g]){const f=this.ctx[g].piiKind??0,S=convertContextProperty(this.ctx[g].value);this.manager.getPropertyManager().setProperty(this.envOverride[g],{value:S,kind:f})}}else for(const g of Object.keys(this.ctx)){const f=this.ctx[g].piiKind??0,S=convertContextProperty(this.ctx[g].value);this.manager.getPropertyManager().setProperty(g,{value:S,kind:f})}}},hw=class extends Error{constructor(g,f=1){super(g),this.callSupport=f}};function createTelemetryLoggersFromConfig(g){let f={};return g.telemetryLoggers?f=g.telemetryLoggers:g.telemetryService?.getGenericTelemetryLogger&&g.telemetryTenants?Object.keys(g.telemetryTenants).forEach((S=>f[S]=g.telemetryService.getGenericTelemetryLogger(g.telemetryTenants[S]))):g.telemetryService&&(g.telemetryService.sendEvents||g.telemetryService.getCallingAdapter)&&(g.telemetryService.sendEvents&&(f.media={sendEvent(f){f.eventName&&(f.eventName=f.eventName.replace(/^(mdsc_)/,"")),g.telemetryService.sendEvents([f])}},f.tlePlayer={sendEvent(f){f.eventName&&(f.eventName=f.eventName.replace(/^(mdsc_)/,"")),g.telemetryService.sendEvents([f])}}),g.telemetryService?.sendRealTimeEvents&&(f.realtimeMedia={sendEvent(f){f.eventName&&(f.eventName=f.eventName.replace(/^(mdsc_)/,"")),g.telemetryService.sendRealTimeEvents([f])}}),g.telemetryService.getCallingAdapter&&(f.signaling={sendEvent(f){g.telemetryService.getCallingAdapter().sendEvent(f.eventName,f.props)}})),f}function createTelemetryLoggersForOneDs(g,f,S,v,C,_){const T={signaling:[],media:[],tlePlayer:[],realtimeMedia:[]};let I={signaling:{sendEvent:g=>T.signaling.push(g)},media:{sendEvent:g=>T.media.push(g)},tlePlayer:{sendEvent:g=>T.tlePlayer.push(g)},realtimeMedia:{sendEvent:g=>T.realtimeMedia.push(g)},gtcAudit:{sendEvent:g=>T.realtimeMedia.push(g)}};return f.getConfigReceivedOrTimeout().then((async()=>{let b=(await C)?.serviceUrls?.OneDsCollectorUrl;if(b=b??f.config.collectorUrl,b){const C=new cw(g,f,S,v,b);I.signaling=C.createLogger("signaling",f.config.eventLatency),I.media=C.createLogger("media",f.config.eventLatency),I.tlePlayer=C.createLogger("tlePlayer",f.config.eventLatency),I.gtcAudit=C.createLogger("gtcAudit",Ep.Immediate);const _=new cw(g,f,S,v,b,{"UserInfo.Ring":"Ring","UserInfo.TenantId":"TenantId","AppInfo.ClientType":"client_type","UserInfo.ETag":"AppInfo.EcsEtag",appversion:"First/Second Client VDI Desktop Version",vdiMode:"First/Second Client VDI Mode",vdiConnectedState:"First/Second Client VDI Connected State",vdiShimVersion:"First/Second Client VDI Shim Version",vdiProvider:"First/Second Client VDI Provider Version"});I.realtimeMedia=_.createLogger("realtimeMedia",f.config.eventLatencyRealTime)}else I=createTelemetryLoggersFromConfig(_);for(const[g,f]of Object.entries(T))for(const S of f)I[g].sendEvent(S)})),I}var uw=class _PluginlessStack extends Ke{constructor(g,f){super(),this._config=g,this._ecsProvider=f,this.callRegistries=[],this._logger=new Ge(this._config.logger).createChild("PluginlessStack"),this._platformManager=new sP,this._waitForAccountConfiguration=new dt,this.platformCallConstraintsProvider=new ii(this._logger.createChild("PlatformConstraintsProvider"))}async initializeMediaAgent(g){if(this._mediaAgent)throw new hw("Media agent is already initialized");let f,S=null;if(!this._mediaAgentProvider)throw new hw("PluginlessStack initialize MediaAgent error, Media Stack not initialized",S);try{this._relayManagerProvider=new pi(g,this._signalingAgentProvider,this._ecsProvider,this._logger),f=await this._mediaAgentProvider.buildAgent(this._config.platformType,this._relayManagerProvider,this._midCallTelemetry)}catch(g){const f=g.some((g=>"incompatible_version"===g.reason));S=f?2:1}if(!this._config.usePlatformSupportApi&&!this._config.callSettings?.useLwjForAllCalls){if(S)throw new hw("PluginlessStack initialization failed",S);{const g=(new sP).getPlatformSupportLevel(!0);if(1!==g&&2!==g)throw new hw("PluginlessStack initialization failed",1)}}f?(this._screenSharingManager=new cP(f.getScreenSharingManager()),this._waitForAccountConfigurationTimeout=window.setTimeout((()=>{this._waitForAccountConfiguration.resolve(void 0),this._waitForAccountConfigurationTimeout=void 0}),3e4),this._oneDsTelemetryLoggers=createTelemetryLoggersForOneDs(this._logger.createChild("OneDsLogger"),f.getConfigProvider(),g.clientInformation,this._config.telemetryContextProvider,this._waitForAccountConfiguration.promise,this._config),f.getConfigProvider().config.useOneDsLogger&&(this.signalingLoggerAdapter={sendEvent:(g,f)=>{const S={eventName:g,props:f};this._oneDsTelemetryLoggers.signaling.sendEvent(S)}}),this._mediaAgent=f,this._e911=new aP(this._relayManagerProvider,this._mediaAgent.getConfigProvider(),this._logger.createChild("E911")),this._e911?.changed((()=>{this.event("e911InfoChanged").raise(this._e911?.info,this._e911?.areaContent)}))):this._deviceManager=new xt}async initializeSignalingAgentProvider(g){this._trouterService=g.trouterService,this._signalingAgentProvider=pP.build(g.signalingAgentConfig,this._ecsProvider,this._config.logger,this.signalingLoggerAdapter)}static async build(g,f,S){try{const v=new _PluginlessStack({detectH264Support:g.mediaAgentFactoryConfig.detectH264Support,domOverrides:g.mediaAgentFactoryConfig.domOverrides,mediaSettings:g.mediaAgentFactoryConfig.settings,logger:g.logger,telemetryLoggers:g.telemetryLoggers,telemetryService:g.telemetryService,telemetryTenants:g.telemetryTenants,telemetryContextProvider:g.telemetryContextProvider,platformType:g.platformType,callSettings:g.callSettings,usePlatformSupportApi:g.usePlatformSupportApi,clientInformation:g.signalingAgentConfig.clientInformation,vdi3diagnostics:g.vdi3diagnostics},f);return v.initializeMediaProvider({detectH264Support:g.mediaAgentFactoryConfig.detectH264Support,domOverrides:g.mediaAgentFactoryConfig.domOverrides,mediaSettings:g.mediaAgentFactoryConfig.settings,logger:g.mediaAgentFactoryConfig.logger,safeLogger:g.mediaAgentFactoryConfig.safeLogger,webcvProvider:g.mediaAgentFactoryConfig.webcvProvider,wasmdnsProvider:g.mediaAgentFactoryConfig.wasmdnsProvider,wasmaecProvider:g.mediaAgentFactoryConfig.wasmaecProvider,wasmVqeProvider:g.mediaAgentFactoryConfig.wasmVqeProvider,createWasmWorkerCbs:g.mediaAgentFactoryConfig.createWasmWorkerCbs,encodedStreamsWorkerProvider:g.mediaAgentFactoryConfig.encodedStreamsWorkerProvider,clientInformation:g.signalingAgentConfig.clientInformation}),v.setMidCallTelemetry(S),v.initializeSignalingAgentProvider({signalingAgentConfig:g.signalingAgentConfig,trouterService:g.trouterService}),await v.initializeMediaAgent({httpRequestDispatcher:g.mediaAgentFactoryConfig.httpRequestDispatcher,tokenProvider:g.mediaAgentFactoryConfig.tokenProvider,configProvider:g.mediaAgentFactoryConfig.configProvider,appStateProvider:g.mediaAgentFactoryConfig.appStateProvider,clientInformation:g.signalingAgentConfig.clientInformation,trapTokenCredentialsProvider:g.mediaAgentFactoryConfig.trapTokenCredentialsProvider,relayManager:g.mediaAgentFactoryConfig.relayManager}),v}catch(g){throw g instanceof hw?g:new hw(`${g}`)}}static async buildBaseStack(g,f){const S=new _PluginlessStack(g,f);return S.initializeMediaProvider({detectH264Support:g.detectH264Support,domOverrides:g.domOverrides,mediaSettings:g.mediaSettings,logger:g.logger,safeLogger:g.safeLogger,webcvProvider:g.webcvProvider,wasmdnsProvider:g.wasmdnsProvider,wasmaecProvider:g.wasmaecProvider,wasmVqeProvider:g.wasmVqeProvider,createWasmWorkerCbs:g.createWasmWorkerCbs,encodedStreamsWorkerProvider:g.encodedStreamsWorkerProvider,clientInformation:g.clientInformation}),S}async init(){}async dispose(g=generateCauseId()){const f=this._logger.createFnLogger("dispose",g);f.info("Dispose"),this._ecsProvider.dispose(),this._e911?.dispose();const handleDisposeError=g=>{f.warn("Failed:",g)},S=this.callRegistries.map((f=>f.dispose(g).catch(handleDisposeError)));await Promise.all(S),await this._mediaAgentProvider.dispose(g),f.info("media agent is disposed"),this.callRegistries=[],f.info("call registries are disposed"),this._screenSharingManager&&(this._screenSharingManager.dispose(g),this._screenSharingManager=void 0,f.info("screensharing manager is disposed")),this._deviceManager=void 0,super.dispose()}getCallRegistry(){return this._logger.info("returning default callRegistry"),this.callRegistries[0]?this.callRegistries[0]:this._createCallRegistry()}async createCallRegistry(g,f=generateCauseId()){const S=g?mriOrId(g.id):void 0,v=this._logger.createFnLogger(`createCallRegistry[identity=${S}]`,f),C=this.callRegistries.find((f=>f.identity===g.id));return C&&!C.isDisposing?(v.info(`callRegistry already exists for ${mriOrId(g.id)}`),C):(C?.isDisposing&&await C.disposePromise,this._createCallRegistry(g))}createCompositor(g){throw new Error("Method not implemented.")}_createCallRegistry(g){if(!this._trouterService)throw new hw("Unable to create call registry, trouter service undefined");if(!this._mediaAgent)throw new hw("Unable to create call registry, media agent undefined");if(!this._signalingAgentProvider)throw new hw("Unable to create call registry, signaling agent undefined");const f=new po(this._trouterService,this._signalingAgentProvider,this._mediaAgent,this._logger,createTelemetryLoggersFromConfig(this._config),this._ecsProvider,g,this._oneDsTelemetryLoggers,this._config.vdi3diagnostics);return f.on("disposed",(()=>{this.callRegistries.splice(this.callRegistries.indexOf(f),1)})),f.on("accountConfigurationReceived",(g=>{this._waitForAccountConfiguration.isPending&&(this._waitForAccountConfiguration.resolve(g),window.clearTimeout(this._waitForAccountConfigurationTimeout)),this._relayManagerProvider.getOrCreateRelayManager().setDefaultRelayConfig(g.relayConfig),this._relayManagerProvider.getOrCreateRelayManager().setClientSupportsGenericTokenApi(g.clientSupportsGenericTokenAPI)})),f.on("locationInfoSet",((g,f)=>{this._e911?.setClientInfo(g,f)})),this._relayManagerProvider.getOrCreateRelayManager(),this.callRegistries.push(f),f}initializeMediaProvider(g){const f=(0,je.assign)({},g);this._mediaAgentProvider=new nP(f,this._ecsProvider,this.platformCallConstraintsProvider),this._deviceManager=new vo(this._mediaAgentProvider.getDeviceManager())}setMidCallTelemetry(g){this._midCallTelemetry=g}getDeviceManager(){return this._deviceManager}async getDeviceManagerAsync(){return this._deviceManager}createDeviceManager(g){return this._deviceManager}getScreenSharingManager(){return this._screenSharingManager}getSetup(){}getEcsProvider(){return this._ecsProvider}async getEcsProviderAsync(){return this._ecsProvider}getCallFeedback(){return null}getAiMdp(){return null}fireIntent(g,f){}getVersion(){return{build:getTsCallingVersion2(),ovb:getOvb2()}}async getVersionAsync(){return{build:getTsCallingVersion2(),ovb:getOvb2()}}getMediaStatus(){return null}getVideoCapabilityLimits(){return null}async setMediaConfig(g){this._mediaAgent.setMediaConfig(g)}async getE911Info(){return this._e911?.getInfo()}setPlatformCallConstraints(g){this.platformCallConstraintsProvider.setConstraints(g)}getPlatformSupportLevel(){return this._platformManager.getPlatformSupportLevel(!!this._mediaAgent)}async getPlatformSupportLevelAsync(){return this.getPlatformSupportLevel()}getLiveStreamClient(){const getTelemetryLogger=()=>createTelemetryLoggersFromConfig(this._config).tlePlayer;return new Ft(this._ecsProvider.createEcsConfiguration(),this._logger.createChild("LiveStreamClient"),getTelemetryLogger)}createVoipCallCoordinator(){}async setLogFileName(g,f,S){throw new Error("not supported")}aggregateDiagnosticLogs(g){return Promise.reject("not supported")}submitBrbReport(g,f){return Promise.reject("not supported")}extendBrbFeedback(g,f){return Promise.reject("not supported")}async addOcclusion(g,f,S,v,C,_){}async removeOcclusion(g,f,S,v){}async flushLogs(){throw new Error("not supported")}getDebugDump(){return this._mediaAgent&&maskSensitiveData(JSON.stringify(this._mediaAgent.getDiagnosticsData()),'"(redacted)",')}async getStageCapability(){throw new Error("not supported")}async getAiCameraCapability(){throw new Error("not supported")}createAiCameraManager(){throw new Error("not supported")}async disposeMediaAgent(g=generateCauseId()){if(!this._mediaAgent)throw new hw("_mediaAgent is not initialized");await(this._mediaAgent?.dispose(g)),this._mediaAgent=null}async updateSignalingAgentProviderConfig(g){if(!this._signalingAgentProvider)throw new hw("_signalingAgentProvider not initialized");this._trouterService=g.trouterService,this._signalingAgentProvider.getSignalingAgent().updateSignalingAgentConfig(g.signalingAgentConfig)}},gw={build(g,f=!0){const S=g.telemetryContextProvider?.(),v=new oP(S),C=new Ao;return f&&initLogger(g,v,C),uw.build(g,v,C)},buildBaseStack(g){const f=g.telemetryContextProvider?.(),S=new oP(f);return uw.buildBaseStack(g,S)},getVersion:()=>({build:getTsCallingVersion2(),ovb:getOvb2()})},pw=[{className:lo,props:["callId","endpointId","participantId","callMode","spamRiskLevel","spamStirAttestation","groupId","threadId","messageId","backroomThreadId","lobbyThreadId","streamThreadId","callType","conversationType","calleeAlternateId","callerMri","acceptedElsewhereBy","state","terminatedReason","failureType","callEndDiagnosticsInfo","transferDiagnosticsInfo","capabilities","transferState","parkState","origin","isPreheatEnabled","publishedStates","participants","dominantSpeakerInfo","slowedDownActiveTalkerInfo","callStartedAt","callHeldAt","participantCounts","conversationStartTime","isAudioStreamConnected","isVideoOn","isScreenSharingOn","isIncomingOneOnOneVideoCall","localMediaStreams","mediaStreams","isMuted","isServerMuted","isSpeakerMuted","conversationId","isEmergency","isCast","isHuddleGroupCall","label","isHostless","endpoints","meetingDetails","meetingStates","role","meetingRole","advancedMeetingRole","meetingRoles","participantType","tenantId","transferorMri","transferorDisplayName","transferorType","consultativeCallId","callQueueInfo","incomingCallType","invitationData","customHeaderContext","clientTransferContext","onBehalfOfMri","onBehalfOfUserDisplayName","callPhoneLineType","forwardingDestinationType","optimalVideoCount","maxIncomingVideoCount","maxIncomingVbssCount","contentSharingSessions","screenSharingControl","ptzHandler","broadcastMeeting","broadcastMetadata","dataChannelAdapter","meetingData","meetingInfo","region","meetingGroupDetails","breakoutDetails","videoLayout","callLimits","redirectionProperties","fromApplicationType","maskedIdentityDetails","complianceRecordingContent","bannerContent","callQueueSupervisorContent","supervisorCallQueueMri","meetingLayoutDetails","compositionServiceDetails","joinAsStreamingUser","otpIdentity","enableCaptcha","groupKeyManagerMri","sendSignalLevel","displayNameSource","getIncomingRawAudioStream","getUnmixedAudioProvider","init","initAsync","setDeviceManager","forceUpdate","join","joinCallWithoutCallModality","start","startCallToVoicemail","startCallWithNudge","startWithMeetingData","joinWithMeetingData","subscribeWithMeetingData","startAndUnpark","unpark","joinPreheatedCall","park","updateMeetingRoles","acknowledge","accept","reject","admitParticipant","admit","addParticipant","nudgeParticipants","updateParticipantsProperties","callMeBack","removeParticipant","stop","cancelNudge","mute","unmute","muteParticipants","muteSpeaker","unmuteSpeaker","getSpeakerVolume","setSpeakerVolume","hold","unhold","updateEndpointMetadata","sendDtmfTone","setMaxVideoChannels","setMaxVbssChannels","startVideo","stopVideo","startAudio","stopAudio","startScreenSharing","changeCropRegion","stopScreenSharing","isRecordingLocally","startLocalRecording","stopLocalRecording","includeSystemAudioInLocalRecording","startDataChannel","stopDataChannel","sendUserEvents","shareSystemSound","startFaceStream","stopFaceStream","startInRoomFaceAtrribution","stopInRoomFaceAtrribution","startMultichannelAudioDevice","stopMultichannelAudioDevice","transferCall","callBlindTransfer","callSafeTransfer","transferCallToVoicemail","callConsultativeTransfer","consultativeTransferWithPickupCode","callRedirect","assimilate","merge","getServerHoldLocation","getJoinBlob","getTechnicalInformationJson","createContentSharingSession","setAudioUsageMode","setAudioMidcallConfig","setAudioMidcallConfigJson","setParticipantSpatialAudioPositions","reconnect","provideCallQualityFeedback","dumpVideoSourceImages","addGroupModality","addParticipants","addBroadcastModality","mergeWithPickupCode","publishState","publishStatesForEveryone","removeState","removeStatesForEveryone","updateMeetingSettings","updateMeetingGroups","updateMeetingLiveState","updateParticipantInterpretationState","joinMeetingGroup","leaveMeetingGroup","mergeParticipants","sendMessages","setMeetingLayout","updateMonitorSession","updateMeetingStates","showCQFInfo","isCqfRendered","provideCallQualityFeedbackEx","searchParticipants","getAllParticipants","getMediaTelemetry","getMediaSessionStats","getMediaSessionStatsAsync","getMediaLogs","setVideoMidcallConfigJson","pictureInPicture","setPlatformCallConstraints","setCallConstraints","switchInterpreterGroup","setLiveInterpretationAttributes","selectDevices","getSelectDevices","createStage","setAudioStreamConnectedAsync","setSpamRiskLevelAsync","setSpamStirAttestationAsync","setDominantSpeakerInfoAsync","setSlowedDownActiveTalkerInfoAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:po,props:["calls","identity","setConfiguration","updateDisplayName","updateSkypeToken","updateToken","fireIntent","getSetup","getEcsConfig","dispose","createCallAsync","getCall","getCallState","debugInformation","setLocationInfo","createDownloader","getUnassembledLocalRecordingSessions","submitBrbReport","extendBrbFeedback","initialize","logout","init","uninit","login","createCall","createCallWithGroupId","createCallWithMeetingData","deleteCall","deleteCallAsync","enableWindowUninitEventHandler","disableWindowUninitEventHandler","enableWindowUninitEventHandlerAsync","disableWindowUninitEventHandlerAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:hs,props:["id","displayName","role","tenantId","voiceLevel","isServerMuted","state","stateReason","streams","participantCapabilities","acceptedBy","endpoints","contentSharingRole","callEndDiagnosticsInfo","balanceUpdates","meetingRole","advancedMeetingRole","meetingRoles","participantType","otpIdentity","getSourceIdForMediaType","getDiagnosticData","getDiagnosticDataAsync","isIdentityMasked","nonMaskedId","nonMaskedDisplayName","nonMaskedObjectId","maskedIdSeqNumber","version","propertyBag","dispose","disposeAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:vo,props:["getPermissionState","getPermissionStateAsync","isAudioOutputSelectionSupported","askDevicePermission","enumerateDevicesAsync","getPreferredCamera","selectDevices","getSelectedDevices","createPreview","createPreviewRenderer","createScreenSharingPreviewRenderer","getDeviceNameAsync","getSpeakerDeviceDomIdAsync","setDeviceEffectsAsync","getDeviceEffectsCapabilityAsync","setBackgroundImageAsync","getImagePropertyAsync","transformImageAsync","sendMessageDeviceVideoEffectsAsync","sendMessageDeviceVideoExtensibilityAsync","setVideoCaptureConfigAsync","captureVideoFrameWithoutEffectsAsync","enableSignLanguageDetectionAsync","downloadAiModel","setAudioProcessingFlags","getSpeakerVolume","getSpeakerSystemVolume","setSpeakerVolume","setSpeakerSystemVolume","unmuteMicrophone","unmuteSpeaker","getNrgLevelsForDeviceTuner","getNrgLevelPollerForDeviceTuner","setAudioEffectsAsync","getAudioFeatureCapability","getMicrophoneVolume","setMicrophoneVolume","setDeviceTelemetryData","getSourceFormats","enableShellSharing","disableShellSharing","enableParticipantCameras","registerDerivedSource","unregisterDerivedSource","getMicrophoneGeometryArrayInfoAsync","startAudioLoopbackDevice","getRawDeviceMediaStream","setRawMediaStream","unsetRawMediaStream","createAudioRenderer","getPersonalizedNoiseSuppression","getRtcAudioManager","dispose","registerCompositeVideoDevice","unregisterCompositeVideoDevice","createAudioPlayer","mapBrowserDevices","setAudioProcessingFlagsAsync","selectDevicesAsync","getSelectedDevicesAsync","getAudioFeatureProviderName","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:oP,props:["setEcsConfig","setUserEcsServerUrl","getUserEcsServerUrl","setActiveUserForEcs","getEcsQueryParameters","ecsGetUserQueryParameters","shouldTriggerCQF"]},{className:sa,props:["controlState","role","enableScreenSharingControl","setScreenSharingControlFeatureFlag","isScreenSharingControlEnabled","initControlForSharer","initControlForViewer","shutdownControlForSharer","shutdownControlForViewer","sendRemoteControlEvent","setRenderer","setPointerImage","setLocalPointerImage","setRemotePointerImage","startPointerMode","stopPointerMode","requestControl","acceptControlRequest","denyControlRequest","grantControl","terminateControl","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:us,props:["contentSharingState","contentSharingStatus","contentSharingTerminationReason","contentSharingIdentity","contentSharingGuid","startContentSharing","joinContentSharing","updateContentSharingSessionState","takeContentSharingControl","updateContentSharingParticipantStateToViewer","stopContentSharing","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:Ms,props:["addHandler","removeHandler","updateNegotiationTag"]},{className:rs,props:["id","type","rank","label","mediaSourceId","dynamicVirtualParticipantId","deviceCapabilities","ordinal","getRawStream","start","stop","selectVideoTrack","setVideoStreamConfig","getDiagnosticData","getStats","isAvailable","isStreaming","participantId","endpointId","negotiationTag","isActive","dispose","disposeAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:ns,props:["id","type","rank","label","mediaSourceId","dynamicVirtualParticipantId","deviceCapabilities","ordinal","getRawStream","start","stop","selectVideoTrack","setVideoStreamConfig","getDiagnosticData","getStats","isAvailable","isStreaming","participantId","endpointId","negotiationTag","isActive","dispose","disposeAsync","changed","on","once","changedAsync","onAsync","onceAsync"]},{className:uw,props:["init","getCallRegistry","createCallRegistry","callRegistries","cancelOperation","getDeviceManager","createDeviceManager","getScreenSharingManager","getSetup","getEcsProvider","getCallFeedback","getAiMdp","getVersion","getMediaStatus","getVideoCapabilityLimits","setMediaConfig","fireIntent","getE911Info","getLocationInfo","setAllowPrivacySensitiveApis","getGeolocationCapabilityState","getLiveStreamClient","getUmsStream","createVoipCallCoordinator","setLogFileName","aggregateDiagnosticLogs","addOcclusion","removeOcclusion","extendBrbFeedback","getDebugDump","flushLogs","getStageCapability","getAiCameraCapability","createAiCameraManager","dispose","getVersionAsync","getDeviceManagerAsync","getEcsProviderAsync","changed","on","once","changedAsync","onAsync","onceAsync"].concat(["getPlatformSupportLevel","setPlatformCallConstraints","createCompositor","initializeMediaAgent","initializeSignalingAgentProvider","disposeMediaAgent","updateSignalingAgentProviderConfig","getPlatformSupportLevelAsync"])}];if("object"==typeof v.exports&&"object"==typeof S){var __cp=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let C of Object.getOwnPropertyNames(f))Object.prototype.hasOwnProperty.call(g,C)||C===S||Object.defineProperty(g,C,{get:()=>f[C],enumerable:!(v=Object.getOwnPropertyDescriptor(f,C))||v.enumerable});return g};v.exports=__cp(v.exports,S)}return v.exports},"object"==typeof g&&"object"==typeof f?f.exports=v(R,M):"object"==typeof g?g["skype-calling-pluginless"]=v(R,M):S["skype-calling-pluginless"]=v(S["@skype/rt-js-bindings"],S.lodash)}}),D={};__export(D,{ShellTrouter:()=>Hh,monitor:()=>ih,stackFactory:()=>Bh,tsCallingChannel:()=>tsCallingChannel}),C.exports=__toCommonJS(D);var N="transportConfig",uuidv4=()=>{const g=new Array(36);for(let f=0;f<g.length;f++)g[f]=Math.floor(16*Math.random());return g[14]=4,g[19]=g[19]&=-5,g[19]=g[19]|=8,g[8]=g[13]=g[18]=g[23]="-",g.map((g=>g.toString(16))).join("")},k="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid=(g=21)=>{let f="";const S=crypto.getRandomValues(new Uint8Array(g));for(let v=0;v<g;v++)f+=k[63&S[v]];return f},L=class{constructor(g,f){this.logger=g,this.transportConfig=f,this._state=3,this.listeners=new Map}get state(){return this._state}get config(){return this.transportConfig||{}}addEventListener(g,f){this.logger.log(`Event listener added, type: ${g}`);const S=this.listeners.get(g)||new Set;S.add(f),this.listeners.set(g,S)}removeEventListener(g,f){this.logger.log(`Event listener removed, type: ${g}`),this.listeners.get(g)?.delete(f),0===this.listeners.get(g)?.size&&this.listeners.delete(g)}handleMessage(g){const f=JSON.parse(g),S=f.type;this.listeners.get(S)?.forEach((g=>{g(f)}))}},F=class extends L{constructor(g,f){if(super(g,f),this.logger=g,!window.chrome?.webview)throw new Error("chrome.webview is undefined");this._state=1,window.chrome.webview.addEventListener("message",this.handleEvent.bind(this))}dispatchEvent(g){window.chrome.webview.postMessage(g)}handleEvent(g){const f=g.data;f&&super.handleMessage(JSON.stringify(f))}},x=class extends L{constructor(g,f){super(g,f),this.updateTransportState()}get tsCallingChannel(){return navigator.mediaDevices?.tsCallingChannel}dispatchEvent(g){this.tsCallingChannel?this.tsCallingChannel.sendTsCallingMessage(JSON.stringify(g)):this.logger.error("tsCallingChannel is not available.")}updateTransportState(){this.tsCallingChannel?(clearInterval(this.stateCheckTimerId),this.initTsCallingChannel(),this.tsCallingChannel.addEventListener("messagerecv",this.handleEvent.bind(this)),this._state=1):this.stateCheckTimerId=setInterval(this.updateTransportState.bind(this),500)}handleEvent(g){g.detail?.message&&super.handleMessage(g.detail.message)}initTsCallingChannel(){if(this.config.tsCallingChannel?.connectionUrl){const g=new URL(this.config.tsCallingChannel.connectionUrl);g.searchParams.set(N,JSON.stringify(this.config)),this.logger.log(`connectionUrl: ${g}`),this.dispatchEvent({WebViewRemotingControlChannel:{url:g.toString()}})}else this.logger.warn("tsCallingLoaderUrl was not passed in config.")}},getRPCTransport=(g,f,S={})=>{if("WebView"===g)return new F(f,S);if("TsCallingChannel"===g)return new x(f,S);throw new Error(`Transport type: ${g} not valid`)},U=M;function stringifyObject(g){if(!g)return`${g}`;if(g instanceof Map)return mapToString(g);const f=g.toString();return f.endsWith("[object Object]")?JSON.stringify(g):f}function mapToString(g){const f={};return g.forEach(((g,S)=>{f[S.toString()]=g})),JSON.stringify(f)}function limitArraySize(g,f,S=0){return g&&void 0!==f&&f>-1&&g.length>f&&g.splice(S,g.length-f),g}function arrayLimitedPush(g,f,S,v=0){limitArraySize(g,0===S?0:S-1,v),0!==S&&g.push(f)}var getMessageSize=g=>{try{return(new TextEncoder).encode(g).length/1024}catch(f){return g.length/1024}},V=class{constructor(g){this.eventLogger=g,this.subscriptions=[]}subscribe(g){return new B(this.subscriptions,g)}dispose(g){this.subscriptions=[]}raiseEvents(g){this.subscriptions.slice().forEach((f=>{try{void 0!==f.eventHandler&&g(f.eventHandler)}catch(g){this.eventLogger?.warn?.("Event handler exception caught!",stringifyObject(g))}}))}},B=class{constructor(g,f){this.subscriptions=g,this.eventHandler=f,this.subscriptions.push(this)}dispose(){(0,U.remove)(this.subscriptions,(g=>g===this)),this.eventHandler=void 0}},H=class extends V{constructor(g){super(g)}changed(g,f){return this.subscribe({changed:{skipEventConfig:f,handler:g},on:void 0})}on(g,f){return this.subscribe({changed:void 0,on:{name:String(g),handler:this._toEventCallback(f)}})}once(g,f,S){let v;const onceSubscription=(...g)=>{v.dispose(S),this._toEventCallback(f)(...g)};return v=this.on(g,this._fromEventCallback(onceSubscription)),v}raiseChanged(g){this.raiseEvents((f=>{if(!f.changed)return;const{skipEventConfig:S,handler:v}=f.changed;!this.getShouldSkipChangedEvent(g,S)&&v()}))}event(g){return{raise:this._fromEventCallback(((...f)=>this._raiseEventImpl(String(g),...f)))}}_raiseEventImpl(g,...f){this.raiseEvents((S=>S.on&&S.on.name===g&&S.on.handler(...f)))}_toEventCallback(g){return g}_fromEventCallback(g){return g}getShouldSkipChangedEvent(g,f){return g?.skipDominantSpeakerUpdatesOnCall?!!f?.skipDominantSpeakerUpdatesOnCall:!!g?.skipParticipantsUpdatesOnCall&&!!f?.skipParticipantsUpdatesOnCall}async onAsync(g,f){return this.on(g,f)}async onceAsync(g,f,S){return this.once(g,f,S)}async changedAsync(g,f){return this.changed(g,f)}async disposeAsync(g){this.dispose(g)}},$=class{constructor(){this.isPendingInt=!0,this.promiseInt=new Promise(((g,f)=>{this.resolveInt=g,this.rejectInt=f}))}get resolve(){return g=>{this.isPendingInt=!1,this.resolveInt(g),this.clearTimeout()}}get reject(){return g=>{this.isPendingInt=!1,this.rejectInt(g),this.clearTimeout()}}get promise(){return this.promiseInt}get isPending(){return this.isPendingInt}setTimeout(g,f=`deferred timed out after ${g}ms`){this.isPendingInt&&(this.timeoutId=setTimeout((()=>{this.reject(f)}),g))}clearTimeout(){this.timeoutId&&clearTimeout(this.timeoutId)}};function deferWithTimeout(g,f=`deferred timed out after ${g}ms`){const S=new $;return S.setTimeout(g,f),S}var j=class{constructor(){this.rttStat=[],this.transportEventStat=[],this.channel=new Map,this.historyLength=100}registerRtt(g){arrayLimitedPush(this.rttStat,{rtt:g,timestamp:Date.now()},this.historyLength)}markEvent(g,f){arrayLimitedPush(this.transportEventStat,{eventName:g,timestamp:Date.now(),payload:f},this.historyLength)}setLastPingReceived(){this.lastPingReceived=Date.now()}setLastPingSent(){this.lastPingSent=Date.now()}reportChannelAdded(g){this.channel.set(g,{channelId:g,createdAt:Date.now()})}reportChannelTerminated(g){const f=this.channel.get(g);f&&(f.terminatedAt=Date.now())}getStats(g){let f=this.rttStat,S=this.transportEventStat;return g&&(f=this.rttStat.filter((f=>f.timestamp>=g)),S=this.transportEventStat.filter((f=>f.timestamp>=g))),{rttStat:f,transportEventStat:S,lastPingReceived:this.lastPingReceived,lastPingSent:this.lastPingSent,channelStat:Array.from(this.channel.values())}}clear(){this.rttStat=[],this.transportEventStat=[]}},G=class{constructor(g){this.statManager=g}getReport(g){const{rttStat:f,transportEventStat:S,lastPingSent:v,lastPingReceived:C,channelStat:_}=this.statManager.getStats(g);return{Transport_rttStat:JSON.stringify(f),Transport_transportEventStat:JSON.stringify(S),Transport_lastPingSent:v,Transport_lastPingReceived:C,Transport_channelStat:JSON.stringify(_)}}},q={handshake:{timeout:3e4,retryCount:3},transportMonitor:{connectionTimeout:3e4,monitorInterval:1e3},transportStats:{historyLength:100},telemetry:{eventsLimitInMem:200,tenantToken:"1cae5691997646c98b01d15beddae7a3-ce16e198-bc32-420f-ac64-42bb916111af-6865",onedsCollectorURL:"https://ic3.events.data.microsoft.com/OneCollector/1.0/",realTimeTelemetryInterval:3e4}},W={IN_PROGRESS:"Handshake in progress",TIMEOUT:"Request timedout"},z=class{constructor(g,f,S){this.transport=g,this.statManager=f,this.logger=S,this.onConnectionCallbackPool=new Set,this.handShakeReqAck=new Map,this.CONNECTION_TIMEOUT=q.handshake.timeout,this.CONNECTION_RETRY_COUNT=q.handshake.retryCount,this.synEvetListener=async g=>{if(this.onConnectionCallbackPool.has(g.reqId))this.logger.log(`Callback for ${g.reqId} already processed`);else{this.onConnectionCallbackPool.add(g.reqId);try{await(this.onSynCallback?.(g))}catch(g){this.logger.log("Callback errored.",g)}finally{this.onConnectionCallbackPool.delete(g.reqId)}}},this.ackEvetListener=g=>{this.onAckCallback?.(g)},this.transport.addEventListener("syn",this.synEvetListener),this.transport.addEventListener("ack",this.ackEvetListener)}async establish(g){const f=Date.now();this.statManager.markEvent("handShakeInitiated",g);const{resolve:S,promise:v}=deferWithTimeout(this.CONNECTION_TIMEOUT,W.TIMEOUT),C=uuidv4();this.handShakeReqAck.set(C,S),this.transport.dispatchEvent({type:"syn",payload:g,reqId:C});const _=globalThis.setInterval((()=>{this.transport.dispatchEvent({type:"syn",payload:g,reqId:C})}),this.CONNECTION_TIMEOUT/this.CONNECTION_RETRY_COUNT);return this.onAckCallback=g=>{const S=Date.now();this.statManager.markEvent("handShakeSuccess",{duration:S-f}),this.handShakeReqAck.get(g.reqId)?.(),this.handShakeReqAck.delete(g.reqId)},this.establishPromise=v.finally((()=>{globalThis.clearInterval(_),this.establishPromise=void 0})),this.establishPromise}onConnection(g){const f=Date.now();this.onSynCallback=async S=>{await g(S.payload),this.transport.dispatchEvent({type:"ack",reqId:S.reqId});const v=Date.now();this.statManager.markEvent("handShakeSuccess",{duration:v-f,handshakePayload:S.payload})}}dispose(){this.transport.removeEventListener("syn",this.synEvetListener),this.transport.removeEventListener("ack",this.ackEvetListener),this.handShakeReqAck.clear(),this.onConnectionCallbackPool.clear()}},K=class{constructor(g){this.logger=g}start(g,f){if(this.intervalWorker=new J(this.logger.createChild("WorkerBasedTimer")),!this.intervalWorker)throw new Error("Failed to initialize worker");this.intervalWorker.setInterval(g,f)}stop(){this.intervalWorker?.clearInterval(),this.intervalWorker?.disposeTimerWorker?.()}},J=class{constructor(g){this.logger=g,this.timerId=nanoid(),this.workerMessageHandler=g=>{if("ping"===g.data.type)return this.onPing();this.logger.debug(`Msg from worker: ${JSON.stringify(g)}`)},this.workerErrorHandler=g=>{this.logger.error(`Error from worker: ${JSON.stringify(g)}`)},this.createWorker()}setInterval(g,f){this.logger.debug(`Starting id: ${this.timerId}`),this.callback=g,this.timeout=f,this.doWork?.postMessage({id:this.timerId,ms:this.timeout})}clearInterval(){this.logger.debug(`Stopping id: ${this.timerId}`),this.doWork?.postMessage({stop:!0,id:this.timerId})}disposeTimerWorker(){this.doWork?(this.callback=void 0,this.doWork.removeEventListener("message",this.workerMessageHandler),this.doWork.removeEventListener("error",this.workerErrorHandler),this.doWork.terminate(),this.doWork=void 0):this.logger.error("Worker is already terminated")}onPing(){this.doWork?.postMessage({id:this.timerId,ms:this.timeout}),this.callback?.()}createWorker(){this.logger.debug("Creating worker");try{const g=new Blob(["'use strict';\n                        var internalId;\n                        var externalId;\n                        (function () {\n                            onmessage = function (event) {\n                                if (event.data.stop) {\n                                    if (event.data.id === externalId) {\n                                        clearTimeout(internalId);\n                                    }\n                                    postMessage({ type: 'clearTimeoutCompleted', id: externalId });\n                                }else {\n                                    clearTimeout(internalId);\n                                    externalId = event.data.id;\n                                    internalId = setTimeout(function () {\n                                        postMessage({ type: 'ping', id: externalId });\n                                    }, event.data.ms);\n                                }\n                            };\n                        })();"],{type:"text/javascript"});this.doWork=new window.Worker(window.URL.createObjectURL(g)),this.doWork.addEventListener("message",this.workerMessageHandler),this.doWork.addEventListener("error",this.workerErrorHandler),this.logger.debug("Initialized")}catch(g){throw this.logger.debug(`Worker creation failed: ${JSON.stringify(g)}`),g}}},Y=class extends H{constructor(g,f=q.transportMonitor.connectionTimeout,S){super(),this.transport=g,this.transportTimeout=f,this.logger=S,this.heartbeats=new Map,this.monitorInterval=q.transportMonitor.monitorInterval,this.scheduler=new K(this.logger),this.start(),g.addEventListener("ping",(g=>{this.handleTransportPing(g)})),g.addEventListener("pong",(g=>{this.handleTransportPong(g)}))}async waitForTransport(){if(1===this.transport.state)return Promise.resolve();const{resolve:g,promise:f}=deferWithTimeout(this.transportTimeout,`Unable to establish transport in ${this.transportTimeout}s`),S=globalThis.setInterval((()=>{1===this.transport.state&&g()}),200);return f.finally((()=>{globalThis.clearInterval(S)}))}stop(){this.logger.log("Stopping transport health check"),this.heartbeats.clear(),globalThis.clearInterval(this.monitorIntervalId),this.scheduler.stop(),this.monitorIntervalId=void 0}start(){this.logger.log("Starting transport health check");const healthCheckFn=()=>{this.sendHeartbeat(),this.checkTransportState()};try{this.scheduler.start(healthCheckFn,this.monitorInterval)}catch(g){this.logger.error(g),this.logger.log("Fallback to setInterval"),this.monitorIntervalId=globalThis.setInterval(healthCheckFn,this.monitorInterval)}}sendHeartbeat(){const g=Math.random();this.heartbeats.set(g,Date.now()),this.transport.dispatchEvent({type:"ping",eventId:g})}handleTransportPing({eventId:g}){this.transport.dispatchEvent({type:"pong",eventId:g})}handleTransportPong({eventId:g}){void 0!==this.heartbeats.get(g)&&(this.heartbeats.delete(g),this.lastAckTime=Date.now())}checkTransportState(){this.lastAckTime&&Date.now()-this.lastAckTime>this.transportTimeout&&(this.stop(),this.event("connectionTerminated").raise())}},Q=class extends Y{constructor(g,f,S=3e4,v){super(f,S,v),this.statManager=g,this.statManager.markEvent("monitorInitialized")}async waitForTransport(){await super.waitForTransport(),this.statManager.markEvent("transportOpen")}stop(){super.stop(),this.statManager.markEvent("transportTerminated")}sendHeartbeat(){super.sendHeartbeat(),this.statManager.setLastPingSent()}handleTransportPong(g){const f=this.heartbeats.get(g.eventId);void 0!==f&&(super.handleTransportPong(g),this.statManager.registerRtt(Date.now()-f),this.statManager.setLastPingReceived())}},X=class{constructor(g){this.modifiers=g,this.hasModifier=this.modifiers.length>0}transform(g){if(!this.hasModifier)return[{chunk:g,index:0}];const f=this.modifiers.reduce(((g,f)=>f.modify(g)),g);return Array.isArray(f)?f.map(((g,f)=>({chunk:g,index:f}))):[{chunk:f,index:0}]}rebuild(g){if(!this.hasModifier)return g[0].chunk;const f=[];g.forEach((({index:g,chunk:S})=>{f[g]=S}));return this.modifiers.slice().reverse().reduce(((g,f)=>f.reconstruct(g)),f)}},Z=class{constructor(g,f){if(this.config=f,!(f.chunkSize&&f.chunkSize>0))throw new Error(`Invalid chunkSize given: ${f.chunkSize}`);g.warn(`chunkSize set to ${f.chunkSize} bytes`)}modify(g){const f=g.length,S=this.config.chunkSize,v=Math.ceil(f/S),C=[];for(let f=0;f<v;f++){const v=g.substring(f*S,(f+1)*S);C.push(v)}return C}reconstruct(g){return g.reduce(((g,f)=>g+f),"")}},ee=class{constructor(g,f){this.logger=g,this.config=f,this.reconstructionBuffers=new Map,this.receivedIndexes=new Map,this.messageTransformer=new X(this.config.chunkSize?[new Z(this.logger,this.config)]:[])}dispatchMessage(g,f){const S=g.type,v=uuidv4(),C=this.messageTransformer.transform(JSON.stringify(g)),_=C.length;C.forEach((g=>f({type:S,messageId:v,totalChunks:_,message:g})))}onMessageReceived(g){const f=g.messageId,S=g.totalChunks;this.reconstructionBuffers.has(f)||(this.reconstructionBuffers.set(f,[]),this.receivedIndexes.set(f,new Set));const v=this.reconstructionBuffers.get(f),C=this.receivedIndexes.get(f);if(C.has(g.message.index)||(C.add(g.message.index),v.push(g.message)),v.filter((g=>!!g)).length===S){const g=this.messageTransformer.rebuild(v);return this.reconstructionBuffers.delete(f),this.receivedIndexes.delete(f),g}return null}},te=class extends L{constructor(g,f){super(f,g.config),this.transport=g,this.logger=f,this.handleTransportEvent=this.handleEvent.bind(this),this.messageTransformHandler=new ee(f.createChild("MessageTransformHandler"),this.config.messageConfig||{})}dispatchEvent(g){this.messageTransformHandler.dispatchMessage(g,this.transport.dispatchEvent.bind(this.transport))}get state(){return this.transport.state}addEventListener(g,f){this.listeners.has(g)||this.transport.addEventListener(g,this.handleTransportEvent),super.addEventListener(g,f)}removeEventListener(g,f){super.removeEventListener(g,f),this.listeners.has(g)&&0!==this.listeners.get(g)?.size||this.transport.removeEventListener(g,this.handleTransportEvent)}handleEvent(g){const f=this.messageTransformHandler.onMessageReceived(g);f&&super.handleMessage(f)}dispose(){this.listeners.forEach(((g,f)=>{g.forEach((g=>this.transport.removeEventListener(f,g)))})),this.listeners.clear()}},ie=class extends L{constructor(g,f,S){super(S,f.config),this.channelId=g,this.transport=f,this.handleTransportEvent=this.handleEvent.bind(this)}get state(){return this.transport.state}dispatchEvent(g){this.transport.dispatchEvent({...g,$$channelId:this.channelId})}addEventListener(g,f){this.listeners.has(g)||this.transport.addEventListener(g,this.handleTransportEvent),super.addEventListener(g,f)}removeEventListener(g,f){super.removeEventListener(g,f),this.listeners.has(g)&&0!==this.listeners.get(g)?.size||this.transport.removeEventListener(g,this.handleTransportEvent)}handleEvent(g){if(g.$$channelId===this.channelId){delete g.$$channelId;const f=g.type;this.listeners.get(f)?.forEach((f=>{f(g)}))}}dispose(){this.listeners.forEach(((g,f)=>{this.transport.removeEventListener(f,this.handleTransportEvent)})),this.listeners.clear()}},ne=class extends H{constructor(g,f){super(),this.transportExt=g,this.logger=f,this.statManager=new j,this.transportTelemetryProvider=new G(this.statManager),this.channels=new Map,this.transport=new te(this.transportExt,this.logger),this.handShakeService=new z(this.transport,this.statManager,this.logger),this.transportHealthCheck=new Q(this.statManager,this.transport,this.transport.config?.transportConnectionTimeout,this.logger),this.transportHealthCheck.on("connectionTerminated",(()=>{this.event("connectionTerminated").raise()}))}get rpcTransport(){return this.transport}async initiateConnection(g){await this.handShakeService.establish(g),this.logger.log("connection established")}async onConnection(g){this.handShakeService.onConnection(g),this.logger.log("new connection callback set")}createChannel(g){const f=this.logger.createChild(`Channel:${g}`),S=new ie(g,this.transport,f);this.statManager.reportChannelAdded(g);return new Y(S,this.transport.config?.transportConnectionTimeout,f.createChild("ChannelHealthCheck")).on("connectionTerminated",(()=>{this.statManager.reportChannelTerminated(g),this.logger.log(`Connection terminated, channelId: ${g}`),this.channels.delete(g),S.dispose(),this.event("connectionTerminated").raise(g)})),this.channels.set(g,S),S}get telemetryProvider(){return this.transportTelemetryProvider}dispose(){this.transport.dispose(),this.handShakeService.dispose(),this.channels.forEach((g=>g.dispose())),this.logger.info("Dispose: Transport Manager")}},re="function",se="object",ae="undefined",oe="prototype",le=Object,ce=le[oe];function _pureAssign(g,f){return g||f}function _pureRef(g,f){return g[f]}var de,he=void 0,ue=null,ge="",pe="function",me="object",fe="prototype",Se="__proto__",ve="undefined",Ce="constructor",ye="Symbol",Ee="_polyfill",_e="length",Te="name",Ie="call",be="toString",Ae=_pureAssign(Object),Pe=_pureRef(Ae,fe),Re=_pureAssign(String),Me=_pureRef(Re,fe),we=_pureAssign(Math),Oe=_pureAssign(Array),De=_pureRef(Oe,fe),Ne=_pureRef(De,"slice");function safe(g,f){try{return{v:g.apply(this,f)}}catch(g){return{e:g}}}function safeGet(g,f){var S=safe(g);return S.e?f:S.v}function _createIs(g){return function(f){return typeof f===g}}function _createObjIs(g){var f="[object "+g+"]";return function(g){return!(!g||objToString(g)!==f)}}function objToString(g){return Pe[be].call(g)}function isUndefined(g){return typeof g===ve||g===ve}function isNullOrUndefined(g){return g===ue||isUndefined(g)}function isStrictNullOrUndefined(g){return g===ue||!isDefined(g)}function isDefined(g){return!!g||g!==he}function isPrimitive(g){return g===ue||isPrimitiveType(typeof g)}function isPrimitiveType(g){return!de&&(de=["string","number","boolean",ve,"symbol","bigint"]),g!==me&&-1!==de.indexOf(g)}var ke=_createIs("string"),Le=_createIs(pe);function isObject(g){return!(!g&&isNullOrUndefined(g))&&(!!g&&typeof g===me)}var Fe=_pureRef(Oe,"isArray"),xe=_createObjIs("Date"),Ue=_createIs("number"),Ve=_createIs("boolean"),Be=_createObjIs("Error");function isPromiseLike(g){return!!(g&&g.then&&Le(g.then))}function isTruthy(g){return!(!g||safeGet((function(){return!(g&&0+g)}),!g))}var He=_pureRef(Ae,"getOwnPropertyDescriptor");function objHasOwnProperty(g,f){return!!g&&Pe.hasOwnProperty[Ie](g,f)}var $e=_pureAssign(_pureRef(Ae,"hasOwn"),polyObjHasOwn);function polyObjHasOwn(g,f){return objHasOwnProperty(g,f)||!!He(g,f)}function objForEachKey(g,f,S){if(g&&isObject(g))for(var v in g)if($e(g,v)&&-1===f[Ie](S||g,v,g[v]))break}var je={e:"enumerable",c:"configurable",v:"value",w:"writable",g:"get",s:"set"};function _createProp(g){var f={};if(f[je.c]=!0,f[je.e]=!0,g.l){f.get=function(){return g.l.v};var S=He(g.l,"v");S&&S.set&&(f.set=function(f){g.l.v=f})}return objForEachKey(g,(function(g,S){f[je[g]]=isUndefined(S)?f[je[g]]:S})),f}var Ge=_pureRef(Ae,"defineProperty"),qe=_pureRef(Ae,"defineProperties");function objDefine(g,f,S){return Ge(g,f,_createProp(S))}function objDefineProps(g,f){var S={};return objForEachKey(f,(function(g,f){S[g]=_createProp(f)})),qe(g,S)}function _createKeyValueMap(g,f,S,v,C){var _={};return objForEachKey(g,(function(g,v){_assignMapValue(_,g,f?v:g,C),_assignMapValue(_,v,S?v:g,C)})),v?v(_):_}function _assignMapValue(g,f,S,v){Ge(g,f,{value:S,enumerable:!0,writable:!!v})}var We=_pureAssign(Re),ze="[object Error]";function dumpObj(g,f){var S=ge,v=Pe[be][Ie](g);v===ze&&(g={stack:We(g.stack),message:We(g.message),name:We(g.name)});try{S=(S=JSON.stringify(g,ue,f?"number"==typeof f?f:4:he))&&S.replace(/"(\w+)"\s*:\s{0,1}/g,"$1: ")||We(g)}catch(g){S=" - "+dumpObj(g,f)}return v+": "+S}function throwError(g){throw new Error(g)}function throwTypeError(g){throw new TypeError(g)}var Ke=_pureRef(Ae,"freeze");function _doNothing(g){return g}function _getProto(g){return g[Se]||ue}var Je=_pureRef(Ae,"assign"),Ye=_pureRef(Ae,"keys");function objDeepFreeze(g){return Ke&&objForEachKey(g,(function(g,f){(Fe(f)||isObject(f))&&objDeepFreeze(f)})),Qe(g)}var Qe=_pureAssign(Ke,_doNothing),Xe=_pureAssign(_pureRef(Ae,"getPrototypeOf"),_getProto);function createEnum(g){return _createKeyValueMap(g,1,0,Qe)}function createEnumKeyMap(g){return _createKeyValueMap(g,0,0,Qe)}function createSimpleMap(g){var f={};return objForEachKey(g,(function(g,S){_assignMapValue(f,g,S[1]),_assignMapValue(f,S[0],S[1])})),Qe(f)}function createTypeMap(g){return createSimpleMap(g)}var Ze,et=createEnumKeyMap({asyncIterator:0,hasInstance:1,isConcatSpreadable:2,iterator:3,match:4,matchAll:5,replace:6,search:7,species:8,split:9,toPrimitive:10,toStringTag:11,unscopables:12}),tt="__tsUtils$gblCfg";function _getGlobalValue(){var g;return typeof globalThis!==ve&&(g=globalThis),g||typeof self===ve||(g=self),g||typeof window===ve||(g=window),g||typeof S===ve||(g=S),g}function _getGlobalConfig(){if(!Ze){var g=safe(_getGlobalValue).v||{};Ze=g[tt]=g[tt]||{}}return Ze}var it=_unwrapFunctionWithPoly;function _unwrapFunctionWithPoly(g,f,S){var v=f&&f[g];return function(f){var C=f&&f[g]||v;if(C||S){var _=arguments;return(C||S).apply(f,C?Ne[Ie](_,1):_)}throwTypeError('"'+We(g)+'" not defined for '+dumpObj(f))}}function _unwrapProp(g){return function(f){return f[g]}}var nt=_pureRef(we,"max"),rt=it("slice",Me),st=it("substring",Me),at=_unwrapFunctionWithPoly("substr",Me,polyStrSubstr);function polyStrSubstr(g,f,S){return isNullOrUndefined(g)&&throwTypeError("Invalid "+dumpObj(g)),S<0?ge:((f=f||0)<0&&(f=nt(f+g[_e],0)),isUndefined(S)?rt(g,f):rt(g,f,f+S))}function strLeft(g,f){return st(g,0,f)}var ot,lt,ct,dt="_urid";function _globalSymbolRegistry(){if(!ot){var g=_getGlobalConfig();ot=g.gblSym=g.gblSym||{k:{},s:{}}}return ot}function polyNewSymbol(g){var f={description:We(g),toString:function(){return ye+"("+g+")"}};return f[Ee]=!0,f}function polySymbolFor(g){var f=_globalSymbolRegistry();if(!$e(f.k,g)){var S=polyNewSymbol(g),v=Ye(f.s).length;S[dt]=function(){return v+"_"+S[be]()},f.k[g]=S,f.s[S[dt]()]=We(g)}return f.k[g]}function polyGetKnownSymbol(g){var f;!lt&&(lt={});var S=et[g];return S&&(f=lt[S]=lt[S]||polyNewSymbol(ye+"."+S)),f}function _initTestHooks(){ct=_getGlobalConfig()}function getLazy(g){var f={};return!ct&&_initTestHooks(),f.b=ct.lzy,Ge(f,"v",{configurable:!0,get:function(){var S=g();return ct.lzy||Ge(f,"v",{value:S}),f.b=ct.lzy,S}}),f}function createCachedValue(g){return Ge({toJSON:function(){return g}},"v",{value:g})}var ht,ut="window";function _getGlobalInstFn(g,f){var S;return function(){return!ct&&_initTestHooks(),(!S||ct.lzy)&&(S=createCachedValue(safe(g,f).v)),S.v}}function getGlobal(g){return!ct&&_initTestHooks(),(!ht||!1===g||ct.lzy)&&(ht=createCachedValue(safe(_getGlobalValue).v||ue)),ht.v}function getInst(g,f){var S=ht&&!1!==f?ht.v:getGlobal(f);return S&&S[g]?S[g]:g===ut?pt():ue}function hasDocument(){return!!gt()}var gt=_getGlobalInstFn(getInst,["document"]);function hasWindow(){return!!pt()}var pt=_getGlobalInstFn(getInst,[ut]);function hasNavigator(){return!!vt()}var mt,ft,St,vt=_getGlobalInstFn(getInst,["navigator"]),Ct=_getGlobalInstFn((function(){return!!safe((function(){return process&&(process.versions||{}).node})).v}));function _initSymbol(){return mt=createCachedValue(safe(getInst,[ye]).v)}function _getSymbolKey(g){var f=(ct.lzy?0:mt)||_initSymbol();return f.v?f.v[g]:he}function hasSymbol(){return!!getSymbol()}function getSymbol(){return!ct&&_initTestHooks(),((ct.lzy?0:mt)||_initSymbol()).v}function getKnownSymbol(g,f){var S=et[g];!ct&&_initTestHooks();var v=(ct.lzy?0:mt)||_initSymbol();return v.v?v.v[S||g]:f?he:polyGetKnownSymbol(g)}function newSymbol(g,f){!ct&&_initTestHooks();var S=(ct.lzy?0:mt)||_initSymbol();return S.v?S.v(g):f?ue:polyNewSymbol(g)}function symbolFor(g){return!ct&&_initTestHooks(),((ft=(ct.lzy?0:ft)||createCachedValue(safe(_getSymbolKey,["for"]).v)).v||polySymbolFor)(g)}function isIterator(g){return!!g&&Le(g.next)}function isIterable(g){return!isStrictNullOrUndefined(g)&&Le(g[getKnownSymbol(3)])}function iterForOf(g,f,S){if(g&&(isIterator(g)||(!St&&(St=createCachedValue(getKnownSymbol(3))),g=g[St.v]?g[St.v]():null),isIterator(g))){var v=he,C=he;try{for(var _=0;!(C=g.next()).done&&-1!==f[Ie](S||g,C.value,_,g);)_++}catch(f){v={e:f},g.throw&&(C=ue,g.throw(v))}finally{try{C&&!C.done&&g.return&&g.return(C)}finally{if(v)throw v.e}}}}function fnApply(g,f,S){return g.apply(f,S)}function arrAppend(g,f){return!isUndefined(f)&&g&&(Fe(f)?fnApply(g.push,g,f):isIterator(f)||isIterable(f)?iterForOf(f,(function(f){g.push(f)})):g.push(f)),g}function arrForEach(g,f,S){if(g)for(var v=g[_e]>>>0,C=0;C<v&&(!(C in g)||-1!==f[Ie](S||g,g[C],C,g));C++);}var yt=it("indexOf",De);function arrSlice(g,f,S){return(g&&g.slice||Ne).apply(g,Ne[Ie](arguments,1))}function polyArrIncludes(g,f,S){return-1!==yt(g,f,S)}var Et,_t=_unwrapFunctionWithPoly("includes",De,polyArrIncludes),Tt=_pureAssign(_pureRef(Ae,"create"),polyObjCreate);function polyObjCreate(g){if(!g)return{};var f=typeof g;function tempFunc(){}return f!==me&&f!==pe&&throwTypeError("Prototype must be an Object or function: "+dumpObj(g)),tempFunc[fe]=g,new tempFunc}function objSetPrototypeOf(g,f){return(Ae.setPrototypeOf||function(g,f){var S;!Et&&(Et=createCachedValue(((S={})[Se]=[],S instanceof Array))),Et.v?g[Se]=f:objForEachKey(f,(function(f,S){return g[f]=S}))})(g,f)}function _createCustomError(g,f,S){function __(){this[Ce]=f,safe(objDefine,[this,Te,{v:g,c:!0,e:!1}])}return safe(objDefine,[f,Te,{v:g,c:!0,e:!1}]),(f=objSetPrototypeOf(f,S))[fe]=S===ue?Tt(S):(__[fe]=S[fe],new __),f}function _setName(g,f){f&&(g[Te]=f)}function createCustomError(g,f,S){var v=S||Error,C=v[fe][Te],_=Error.captureStackTrace;return _createCustomError(g,(function(){var S=this,T=arguments;try{safe(_setName,[v,g]);var I=fnApply(v,S,Ne[Ie](T))||S;if(I!==S){var b=Xe(S);b!==Xe(I)&&objSetPrototypeOf(I,b)}return _&&_(I,S[Ce]),f&&f(I,T),I}finally{safe(_setName,[v,C])}}),v)}function utcNow(){return(Date.now||polyUtcNow)()}function polyUtcNow(){return(new Date).getTime()}function _createTrimFn(g){return function _doTrim(f){return isNullOrUndefined(f)&&throwTypeError("strTrim called ["+dumpObj(f)+"]"),f&&f.replace&&(f=f.replace(g,ge)),f}}var It,bt,At,Pt=_unwrapFunctionWithPoly("trim",Me,_createTrimFn(/^\s+|(?=\s)\s+$/g));function isPlainObject(g){if(!g||typeof g!==me)return!1;At||(At=!hasWindow()||pt());var f=!1;if(g!==At){bt||(It=Function[fe][be],bt=It[Ie](Ae));try{var S=Xe(g);(f=!S)||(objHasOwnProperty(S,Ce)&&(S=S[Ce]),f=S&&typeof S===pe&&It[Ie](S)===bt)}catch(g){}}return f}function _defaultDeepCopyHandler(g){return g.value&&plainObjDeepCopyHandler(g),!0}var Rt=[arrayDeepCopyHandler,plainObjDeepCopyHandler,functionDeepCopyHandler,dateDeepCopyHandler];function _getSetVisited(g,f,S,v){var C;return arrForEach(g,(function(g){if(g.k===f)return C=g,-1})),C||(C={k:f,v:f},g.push(C),v(C)),C.v}function _deepCopy(g,f,S,v){var C=S.handler,_=S.path?v?S.path.concat(v):S.path:[],T={handler:S.handler,src:S.src,path:_},I=typeof f,b=!1,A=!1;f&&I===me?b=isPlainObject(f):A=f===ue||isPrimitiveType(I);var P={type:I,isPrim:A,isPlain:b,value:f,result:f,path:_,origin:S.src,copy:function(f,v){return _deepCopy(g,f,v?T:S,v)},copyTo:function(f,S){return _copyProps(g,f,S,T)}};return P.isPrim?C&&C[Ie](S,P)?P.result:f:_getSetVisited(g,f,_,(function(g){objDefine(P,"result",{g:function(){return g.v},s:function(f){g.v=f}});for(var f=0,v=C;!(v||(f<Rt.length?Rt[f++]:_defaultDeepCopyHandler))[Ie](S,P);)v=ue}))}function _copyProps(g,f,S,v){if(!isNullOrUndefined(S))for(var C in S)f[C]=_deepCopy(g,S[C],v,C);return f}function objCopyProps(g,f,S){return _copyProps([],g,f,{handler:S,src:f,path:[]})}function objDeepCopy(g,f){return _deepCopy([],g,{handler:f,src:g})}function arrayDeepCopyHandler(g){var f=g.value;if(Fe(f)){var S=g.result=[];return S.length=f.length,g.copyTo(S,f),!0}return!1}function dateDeepCopyHandler(g){var f=g.value;return!!xe(f)&&(g.result=new Date(f.getTime()),!0)}function functionDeepCopyHandler(g){return g.type===pe}function plainObjDeepCopyHandler(g){var f=g.value;if(f&&g.isPlain){var S=g.result={};return g.copyTo(S,f),!0}return!1}function _doExtend(g,f){return arrForEach(f,(function(f){objCopyProps(g,f)})),g}function deepExtend(g,f,S,v,C,_,T){return _doExtend(objDeepCopy(g)||{},Ne[Ie](arguments))}var Mt=_unwrapProp(_e);function perfNow(){return utcNow()}var wt=_unwrapFunctionWithPoly("endsWith",Me,polyStrEndsWith);function polyStrEndsWith(g,f,S){ke(g)||throwTypeError("'"+dumpObj(g)+"' is not a string");var v=ke(f)?f:We(f),C=!isUndefined(S)&&S<g[_e]?S:g[_e];return st(g,C-v[_e],C)===v}var Ot=it("indexOf",Me),Dt=_unwrapFunctionWithPoly("startsWith",Me,polyStrStartsWith);function polyStrStartsWith(g,f,S){ke(g)||throwTypeError("'"+dumpObj(g)+"' is not a string");var v=ke(f)?f:We(f),C=S>0?S:0;return st(g,C,C+v[_e])===v}var Nt="ref",kt="unref",Lt="hasRef",Ft="enabled";function _createTimerHandler(g,f,S){var v,C=!0,_=g?f(ue):ue;function _unref(){return C=!1,_&&_[kt]&&_[kt](),v}function _cancel(){_&&S(_),_=ue}function _refresh(){return _=f(_),C||_unref(),v}function _setEnabled(g){!g&&_&&_cancel(),g&&!_&&_refresh()}return(v={cancel:_cancel,refresh:_refresh})[Lt]=function(){return _&&_[Lt]?_[Lt]():C},v[Nt]=function(){return C=!0,_&&_[Nt]&&_[Nt](),v},v[kt]=_unref,{h:v=Ge(v,Ft,{get:function(){return!!_},set:_setEnabled}),dn:function(){_=ue}}}function _createTimeoutWith(g,f,S){var v=Fe(f),C=v?f.length:0,_=(C>0?f[0]:v?he:f)||setTimeout,T=(C>1?f[1]:he)||clearTimeout,I=S[0];S[0]=function(){b.dn(),fnApply(I,he,Ne[Ie](arguments))};var b=_createTimerHandler(g,(function(g){if(g){if(g.refresh)return g.refresh(),g;fnApply(T,he,[g])}return fnApply(_,he,S)}),(function(g){fnApply(T,he,[g])}));return b.h}function scheduleTimeout(g,f){return _createTimeoutWith(!0,he,Ne[Ie](arguments))}function scheduleTimeoutWith(g,f,S){return _createTimeoutWith(!0,g,Ne[Ie](arguments,1))}function createTimeout(g,f){return _createTimeoutWith(!1,he,Ne[Ie](arguments))}(getGlobal()||{}).Symbol,(getGlobal()||{}).Reflect;var xt,Ut="hasOwnProperty",extendStaticsFn=function(g,f){return(extendStaticsFn=le.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f[Ut](S)&&(g[S]=f[S])})(g,f)};function __extendsFn(g,f){function __(){this.constructor=g}typeof f!==re&&null!==f&&throwTypeError("Class extends value "+String(f)+" is not a constructor or null"),extendStaticsFn(g,f),g[oe]=null===f?Tt(f):(__[oe]=f[oe],new __)}function __spreadArrayFn(g,f){for(var S=0,v=f.length,C=g.length;S<v;S++,C++)g[C]=f[S];return g}var Vt="constructor",Bt="prototype",Ht="function",$t="_dynInstFuncs",jt="_isDynProxy",Gt="_dynClass",qt="_dynCls$",Wt="_dynInstChk",zt=Wt,Kt="_dfOpts",Jt="_unknown_",Yt="__proto__",Qt="_dyn"+Yt,Xt="__dynProto$Gbl",Zt="_dynInstProto",ei="useBaseInst",ti="setInstFuncs",ii=Object,ni=ii.getPrototypeOf,ri=ii.getOwnPropertyNames,si=getGlobal(),ai=si[Xt]||(si[Xt]={o:(xt={},xt[ti]=!0,xt[ei]=!0,xt),n:1e3});function _isObjectOrArrayPrototype(g){return g&&(g===ii[Bt]||g===Array[Bt])}function _isObjectArrayOrFunctionPrototype(g){return _isObjectOrArrayPrototype(g)||g===Function[Bt]}function _getObjProto(g){var f;if(g){if(ni)return ni(g);var S=g[Yt]||g[Bt]||(g[Vt]?g[Vt][Bt]:null);f=g[Qt]||S,objHasOwnProperty(g,Qt)||(delete g[Zt],f=g[Qt]=g[Zt]||g[Qt],g[Zt]=S)}return f}function _forEachProp(g,f){var S=[];if(ri)S=ri(g);else for(var v in g)"string"==typeof v&&objHasOwnProperty(g,v)&&S.push(v);if(S&&S.length>0)for(var C=0;C<S.length;C++)f(S[C])}function _isDynamicCandidate(g,f,S){return f!==Vt&&typeof g[f]===Ht&&(S||objHasOwnProperty(g,f))&&f!==Yt&&f!==Bt}function _throwTypeError(g){throwTypeError("DynamicProto: "+g)}function _getInstanceFuncs(g){var f=Tt(null);return _forEachProp(g,(function(S){!f[S]&&_isDynamicCandidate(g,S,!1)&&(f[S]=g[S])})),f}function _hasVisited(g,f){for(var S=g.length-1;S>=0;S--)if(g[S]===f)return!0;return!1}function _getBaseFuncs(g,f,S,v){function _instFuncProxy(g,f,S){var C=f[S];if(C[jt]&&v){var _=g[$t]||{};!1!==_[zt]&&(C=(_[f[Gt]]||{})[S]||C)}return function(){return C.apply(g,arguments)}}var C=Tt(null);_forEachProp(S,(function(g){C[g]=_instFuncProxy(f,S,g)}));for(var _=_getObjProto(g),T=[];_&&!_isObjectArrayOrFunctionPrototype(_)&&!_hasVisited(T,_);)_forEachProp(_,(function(g){!C[g]&&_isDynamicCandidate(_,g,!ni)&&(C[g]=_instFuncProxy(f,_,g))})),T.push(_),_=_getObjProto(_);return C}function _getInstFunc(g,f,S,v){var C=null;if(g&&objHasOwnProperty(S,Gt)){var _=g[$t]||Tt(null);if((C=(_[S[Gt]]||Tt(null))[f])||_throwTypeError("Missing ["+f+"] "+Ht),!C[Wt]&&!1!==_[zt]){for(var T=!objHasOwnProperty(g,f),I=_getObjProto(g),b=[];T&&I&&!_isObjectArrayOrFunctionPrototype(I)&&!_hasVisited(b,I);){var A=I[f];if(A){T=A===v;break}b.push(I),I=_getObjProto(I)}try{T&&(g[f]=C),C[Wt]=1}catch(g){_[zt]=!1}}}return C}function _getProtoFunc(g,f,S){var v=f[g];return v===S&&(v=_getObjProto(f)[g]),typeof v!==Ht&&_throwTypeError("["+g+"] is not a "+Ht),v}function _populatePrototype(g,f,S,v,C){function _createDynamicPrototype(g,f){var dynProtoProxy=function(){return(_getInstFunc(this,f,g,dynProtoProxy)||_getProtoFunc(f,g,dynProtoProxy)).apply(this,arguments)};return dynProtoProxy[jt]=1,dynProtoProxy}if(!_isObjectOrArrayPrototype(g)){var _=S[$t]=S[$t]||Tt(null);if(!_isObjectOrArrayPrototype(_)){var T=_[f]=_[f]||Tt(null);!1!==_[zt]&&(_[zt]=!!C),_isObjectOrArrayPrototype(T)||_forEachProp(S,(function(f){_isDynamicCandidate(S,f,!1)&&S[f]!==v[f]&&(T[f]=S[f],delete S[f],(!objHasOwnProperty(g,f)||g[f]&&!g[f][jt])&&(g[f]=_createDynamicPrototype(g,f)))}))}}}function _checkPrototype(g,f){if(ni){for(var S=[],v=_getObjProto(f);v&&!_isObjectArrayOrFunctionPrototype(v)&&!_hasVisited(S,v);){if(v===g)return!0;S.push(v),v=_getObjProto(v)}return!1}return!0}function _getObjName(g,f){return objHasOwnProperty(g,Bt)?g.name||f||Jt:((g||{})[Vt]||{}).name||f||Jt}function dynamicProto(g,f,S,v){objHasOwnProperty(g,Bt)||_throwTypeError("theClass is an invalid class definition.");var C=g[Bt];_checkPrototype(C,f)||_throwTypeError("["+_getObjName(g)+"] not in hierarchy of ["+_getObjName(f)+"]");var _=null;objHasOwnProperty(C,Gt)?_=C[Gt]:(_=qt+_getObjName(g,"_")+"$"+ai.n,ai.n++,C[Gt]=_);var T=dynamicProto[Kt],I=!!T[ei];I&&v&&void 0!==v[ei]&&(I=!!v[ei]);var b=_getInstanceFuncs(f);S(f,_getBaseFuncs(C,f,b,I));var A=!!ni&&!!T[ti];A&&v&&(A=!!v[ti]),_populatePrototype(C,_,f,b,!1!==A)}dynamicProto[Kt]=ai.o;var oi,li=createEnum,ci=createTypeMap,di=li({Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5}),hi="toLowerCase",ui="blkVal",gi="length",pi="rdOnly",mi="notify",fi="warnToConsole",Si="throwInternal",vi="setDf",Ci="watch",yi="logger",Ei="apply",_i="push",Ti="splice",Ii="hdlr",bi="cancel",Ai="initialize",Pi="identifier",Ri="removeNotificationListener",Mi="addNotificationListener",wi="isInitialized",Oi="getNotifyMgr",Di="getPlugin",Ni="pollInternalLogs",ki="name",Li="time",Fi="processNext",xi="getProcessTelContext",Ui="enabled",Vi="stopPollingInternalLogs",Bi="unload",Hi="onComplete",$i="version",ji="loggingLevelConsole",Gi="createNew",qi="teardown",Wi="messageId",zi="message",Ki="isAsync",Ji="diagLog",Yi="_doTeardown",Qi="update",Xi="getNext",Zi="setNextPlugin",en="protocol",tn="userAgent",nn="split",rn="nodeType",sn="replace",an="logInternalMessage",on="type",ln="handler",cn="status",dn="getResponseHeader",hn="getAllResponseHeaders",un="isChildEvt",gn="data",pn="getCtx",mn="setCtx",fn="complete",Sn="urlString",vn="sendPOST",Cn="headers",yn="timeout",En="setRequestHeader",_n="traceId",Tn="spanId",In="traceFlags";function throwAggregationError(g,f){oi||(oi=createCustomError("AggregationError",(function(g,f){f[gi]>1&&(g.errors=f[1])})));var S=g||"One or more errors occurred.";throw arrForEach(f,(function(g,f){S+="\n".concat(f," > ").concat(dumpObj(g))})),new oi(S,f||[])}var bn="Promise",An="rejected";function doAwaitResponse(g,f){return doAwait(g,(function(g){return f?f({status:"fulfilled",rejected:!1,value:g}):g}),(function(g){return f?f({status:An,rejected:!0,reason:g}):g}))}function doAwait(g,f,S,v){var C=g;try{if(isPromiseLike(g))(f||S)&&(C=g.then(f,S));else try{f&&(C=f(g))}catch(g){if(!S)throw g;C=S(g)}}finally{v&&doFinally(C,v)}return C}function doFinally(g,f){var S=g;return f&&(isPromiseLike(g)?S=g.finally?g.finally(f):g.then((function(g){return f(),g}),(function(g){throw f(),g})):f()),S}var Pn,Rn=["pending","resolving","resolved",An],Mn="dispatchEvent";function _hasInitEventFn(g){var f;return g&&g.createEvent&&(f=g.createEvent("Event")),!!f&&f.initEvent}function emitEvent(g,f,S,v){var C=gt();!Pn&&(Pn=createCachedValue(!!safe(_hasInitEventFn,[C]).v));var _=Pn.v?C.createEvent("Event"):v?new Event(f):{};if(S&&S(_),Pn.v&&_.initEvent(f,!1,!0),_&&g[Mn])g[Mn](_);else{var T=g["on"+f];if(T)T(_);else{var I=getInst("console");I&&(I.error||I.log)(f,dumpObj(_))}}}var wn,On,Dn,Nn="unhandledRejection",kn=Nn.toLowerCase(),Ln=[],Fn=0,xn=10;function dumpFnObj(g){return Le(g)?g.toString():dumpObj(g)}function _createPromise(g,f,S){var v,C,_=arrSlice(arguments,3),T=0,I=!1,b=[],A=Fn++,P=!1,R=null;function _then(f,S){try{return Ln.push(A),P=!0,R&&R.cancel(),R=null,g((function(g,C){b.push((function(){try{var _=2===T?f:S,I=isUndefined(_)?v:Le(_)?_(v):_;isPromiseLike(I)?I.then(g,C):_?g(I):3===T?C(I):g(I)}catch(g){C(g)}})),I&&_processQueue()}),_)}finally{Ln.pop()}}function _catch(g){return _then(void 0,g)}function _finally(g){var f=g,S=g;return Le(g)&&(f=function(f){return g&&g(),f},S=function(f){throw g&&g(),f}),_then(f,S)}function _strState(){return Rn[T]}function _processQueue(){if(b.length>0){var g=b.slice();b=[],P=!0,R&&R.cancel(),R=null,f(g)}}function _createSettleIfFn(g,f){return function(S){if(T===f){if(2===g&&isPromiseLike(S))return T=1,void S.then(_createSettleIfFn(2,1),_createSettleIfFn(3,1));T=g,I=!0,v=S,_processQueue(),P||3!==g||R||(R=scheduleTimeout(_notifyUnhandledRejection,xn))}}}function _notifyUnhandledRejection(){if(!P)if(P=!0,Ct())process.emit(Nn,v,C);else{var g=pt()||getGlobal();!wn&&(wn=createCachedValue(safe(getInst,[bn+"RejectionEvent"]).v)),emitEvent(g,kn,(function(g){return objDefine(g,"promise",{g:function(){return C}}),g.reason=v,g}),!!wn.v)}}function _toString(){return"IPromise "+_strState()+(I?" - "+dumpFnObj(v):"")}return Ge(C={then:_then,catch:_catch,finally:_finally},"state",{get:_strState}),hasSymbol()&&(C[getKnownSymbol(11)]="IPromise"),C.toString=_toString,function _initialize(){Le(S)||throwTypeError(bn+": executor is not a function - "+dumpFnObj(S));var g=_createSettleIfFn(3,0);try{S.call(C,_createSettleIfFn(2,0),g)}catch(f){g(f)}}(),C}function _createAllPromise(g){return function(f){var S=arrSlice(arguments,1);return g((function(g,S){try{var v=[],C=1;iterForOf(f,(function(f,_){f&&(C++,doAwait(f,(function(f){v[_]=f,0==--C&&g(v)}),S))})),0===--C&&g(v)}catch(g){S(g)}}),S)}}function syncItemProcessor(g){arrForEach(g,(function(g){try{g()}catch(g){}}))}function timeoutItemProcessor(g){var f=Ue(g)?g:0;return function(g){scheduleTimeout((function(){syncItemProcessor(g)}),f)}}function createAsyncPromise(g,f){return _createPromise(createAsyncPromise,timeoutItemProcessor(f),g,f)}function createNativePromise(g,f){!On&&(On=createCachedValue(safe(getInst,[bn]).v||null));var S=On.v;if(!S)return createAsyncPromise(g);Le(g)||throwTypeError(bn+": executor is not a function - "+dumpObj(g));var v=0;function _strState(){return Rn[v]}var C=new S((function(f,S){function _resolve(g){v=2,f(g)}function _reject(g){v=3,S(g)}g(_resolve,_reject)}));return Ge(C,"state",{get:_strState}),C}function createPromise(g,f){return!Dn&&(Dn=createCachedValue(createNativePromise)),Dn.v.call(this,g,f)}var Un=_createAllPromise(createPromise),Vn=(getKnownSymbol(11),void 0),Bn="",Hn="channels",$n="core",jn="createPerfMgr",Gn="disabled",qn="extensionConfig",Wn="extensions",zn="processTelemetry",Kn="priority",Jn="eventsSent",Yn="eventsDiscarded",Qn="eventsSendRequest",Xn="perfEvent",Zn="offlineEventsStored",er="offlineBatchSent",tr="offlineBatchDrop",ir="getPerfMgr",nr="domain",rr="path",sr="Not dynamic - ",ar=/-([a-z])/g,or=/([^\w\d_$])/g,lr=/^(\d+[\w\d_$])/;function isNotNullOrUndefined(g){return!isNullOrUndefined(g)}function normalizeJsName(g){var f=g;return f&&ke(f)&&(f=(f=(f=f[sn](ar,(function(g,f){return f.toUpperCase()})))[sn](or,"_"))[sn](lr,(function(g,f){return"_"+f}))),f}function strContains(g,f){return!(!g||!f)&&-1!==Ot(g,f)}function toISOString(g){return g&&g.toISOString()||""}function getExceptionName(g){return Be(g)?g[ki]:Bn}function setValue(g,f,S,v,C){var _=S;return g&&((_=g[f])===S||C&&!C(_)||v&&!v(S)||(_=S,g[f]=_)),_}function getSetValue(g,f,S){var v;return g?!(v=g[f])&&isNullOrUndefined(v)&&(v=isUndefined(S)?{}:S,g[f]=v):v=isUndefined(S)?{}:S,v}function _createProxyFunction(g,f){var S=null,v=null;return Le(g)?S=g:v=g,function(){var g=arguments;if(S&&(v=S()),v)return v[f][Ei](v,g)}}function proxyFunctionAs(g,f,S,v,C){g&&f&&S&&(!1!==C||isUndefined(g[f]))&&(g[f]=_createProxyFunction(S,v))}function proxyFunctions(g,f,S,v){return g&&f&&isObject(g)&&Fe(S)&&arrForEach(S,(function(S){ke(S)&&proxyFunctionAs(g,S,f,S,v)})),g}function optimizeObject(g){return g&&Je&&(g=le(Je({},g))),g}function objExtend(g,f,S,v,C,_){var T=arguments,I=T[0]||{},b=T[gi],A=!1,P=1;for(b>0&&Ve(I)&&(A=I,I=T[P]||{},P++),isObject(I)||(I={});P<b;P++){var R=T[P],M=Fe(R),w=isObject(R);for(var O in R){if(M&&O in R||w&&$e(R,O)){var D=R[O],N=void 0;if(A&&D&&((N=Fe(D))||isPlainObject(D))){var k=I[O];N?Fe(k)||(k=[]):isPlainObject(k)||(k={}),D=objExtend(A,k,D)}void 0!==D&&(I[O]=D)}}}return I}function getResponseText(g){try{return g.responseText}catch(g){}return null}function formatErrorMessageXdr(g,f){return g?"XDomainRequest,Response:"+getResponseText(g)||"":f}function formatErrorMessageXhr(g,f){return g?"XMLHttpRequest,Status:"+g[cn]+",Response:"+getResponseText(g)||g.response||"":f}function prependTransports(g,f){return f&&(Ue(f)?g=[f].concat(g):Fe(f)&&(g=f.concat(g))),g}var cr="Microsoft_ApplicationInsights_BypassAjaxInstrumentation",dr="withCredentials",hr="timeout";function openXhr(g,f,S,v,C,_){function _wrapSetXhrProp(g,f,S){try{g[f]=S}catch(g){}}void 0===v&&(v=!1),void 0===C&&(C=!1);var T=new XMLHttpRequest;return v&&_wrapSetXhrProp(T,cr,v),S&&_wrapSetXhrProp(T,dr,S),T.open(g,f,!C),S&&_wrapSetXhrProp(T,dr,S),!C&&_&&_wrapSetXhrProp(T,hr,_),T}function convertAllHeadersToMap(g){var f={};ke(g)&&arrForEach(Pt(g)[nn](/[\r\n]+/),(function(g){if(g){var S=g.indexOf(": ");if(-1!==S){var v=Pt(g.substring(0,S))[hi](),C=Pt(g.substring(S+1));f[v]=C}else f[Pt(g)]=1}}));return f}function _appendHeader(g,f,S){if(!g[S]&&f&&f[dn]){var v=f[dn](S);v&&(g[S]=Pt(v))}return g}var ur="kill-duration",gr="kill-duration-seconds",pr="time-delta-millis";function _getAllResponseHeaders(g,f){var S={};return g[hn]?S=convertAllHeadersToMap(g[hn]()):f&&(S=_appendHeader(S,g,pr),S=_appendHeader(S,g,ur),S=_appendHeader(S,g,gr)),S}var mr="location",fr="console",Sr="JSON",vr="crypto",Cr="msCrypto",yr="ReactNative",Er="msie",_r="trident/",Tr="XMLHttpRequest",Ir=null,br=null,Ar=!1,Pr=null,Rr=null;function _hasProperty(g,f){var S=!1;if(g){try{if(!(S=f in g)){var v=g[oe];v&&(S=f in v)}}catch(g){}if(!S)try{S=!isUndefined((new g)[f])}catch(g){}}return S}function getLocation(g){if(g&&Ar){var f=getInst("__mockLocation");if(f)return f}return typeof location===se&&location?location:getInst(mr)}function getConsole(){return typeof console!==ae?console:getInst(fr)}function hasJSON(){return Boolean(typeof JSON===se&&JSON||null!==getInst(Sr))}function getJSON(){return hasJSON()?JSON||getInst(Sr):null}function getCrypto(){return getInst(vr)}function getMsCrypto(){return getInst(Cr)}function isReactNative(){var g=vt();return!(!g||!g.product)&&g.product===yr}function isIE(){var g=vt();if(g&&(g[tn]!==br||null===Ir)){var f=((br=g[tn])||Bn)[hi]();Ir=strContains(f,Er)||strContains(f,_r)}return Ir}function isBeaconsSupported(g){return null!==Rr&&!1!==g||(Rr=hasNavigator()&&Boolean(vt().sendBeacon)),Rr}function isFetchSupported(g){var f=!1;try{f=!!getInst("fetch");var S=getInst("Request");f&&g&&S&&(f=_hasProperty(S,"keepalive"))}catch(g){}return f}function useXDomainRequest(){return null===Pr&&(Pr=typeof XDomainRequest!==ae)&&isXhrSupported()&&(Pr=Pr&&!_hasProperty(getInst(Tr),"withCredentials")),Pr}function isXhrSupported(){var g=!1;try{g=!!getInst(Tr)}catch(g){}return g}var Mr=4294967296,wr=4294967295,Or=123456789,Dr=987654321,Nr=!1,kr=Or,Lr=Dr;function _mwcSeed(g){g<0&&(g>>>=0),kr=Or+g&wr,Lr=Dr-g&wr,Nr=!0}function _autoSeedMwc(){try{var g=2147483647&utcNow();_mwcSeed((Math.random()*Mr^g)+g)}catch(g){}}function random32(g){var f=0,S=getCrypto()||getMsCrypto();return S&&S.getRandomValues&&(f=S.getRandomValues(new Uint32Array(1))[0]&wr),0===f&&isIE()&&(Nr||_autoSeedMwc(),f=mwcRandom32()&wr),0===f&&(f=Math.floor(Mr*Math.random()|0)),g||(f>>>=0),f}function mwcRandom32(g){var f=((Lr=36969*(65535&Lr)+(Lr>>16)&wr)<<16)+(65535&(kr=18e3*(65535&kr)+(kr>>16)&wr))>>>0&wr|0;return g||(f>>>=0),f}function newId(g){void 0===g&&(g=22);for(var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S=random32()>>>0,v=0,C=Bn;C[gi]<g;)v++,C+=f.charAt(63&S),S>>>=6,5===v&&(S=(random32()<<2&4294967295|3&S)>>>0,v=0);return C}var Fr="3.2.1",xr="."+newId(6),Ur=0;function _canAcceptData(g){return 1===g[rn]||9===g[rn]||!+g[rn]}function _getCache(g,f){var S=f[g.id];if(!S){S={};try{_canAcceptData(f)&&objDefine(f,g.id,{e:!1,v:S})}catch(g){}}return S}function createUniqueNamespace(g,f){return void 0===f&&(f=!1),normalizeJsName(g+Ur+++(f?"."+Fr:Bn)+xr)}function createElmNodeData(g){var f={id:createUniqueNamespace("_aiData-"+(g||Bn)+"."+Fr),accept:function(g){return _canAcceptData(g)},get:function(g,S,v,C){var _=g[f.id];return _?_[normalizeJsName(S)]:(C&&((_=_getCache(f,g))[normalizeJsName(S)]=v),v)},kill:function(g,f){if(g&&g[f])try{delete g[f]}catch(g){}}};return f}function _isConfigDefaults(g){return g&&isObject(g)&&(g.isVal||g.fb||$e(g,"v")||$e(g,"mrg")||$e(g,"ref")||g.set)}function _getDefault(g,f,S){var v,C=S.dfVal||isDefined;if(f&&S.fb){var _=S.fb;Fe(_)||(_=[_]);for(var T=0;T<_[gi];T++){var I=_[T],b=f[I];if(C(b)?v=b:g&&(C(b=g.cfg[I])&&(v=b),g.set(g.cfg,We(I),b)),C(v))break}}return!C(v)&&C(S.v)&&(v=S.v),v}function _resolveDefaultValue(g,f,S){var v,C=S;(S&&_isConfigDefaults(S)&&(C=_getDefault(g,f,S)),C)&&(_isConfigDefaults(C)&&(C=_resolveDefaultValue(g,f,C)),Fe(C)?(v=[])[gi]=C[gi]:isPlainObject(C)&&(v={}),v&&(objForEachKey(C,(function(S,C){C&&_isConfigDefaults(C)&&(C=_resolveDefaultValue(g,f,C)),v[S]=C})),C=v));return C}function _applyDefaultValue(g,f,S,v){var C,_,T,I,b,A,P,R,M=v;_isConfigDefaults(M)?(C=M.isVal,_=M.set,A=M[pi],P=M[ui],I=M.mrg,!(b=M.ref)&&isUndefined(b)&&(b=!!I),T=_getDefault(g,f,M)):T=v,P&&g[ui](f,S);var w=!0,O=f[S];!O&&isNullOrUndefined(O)||(R=O,w=!1,C&&R!==T&&!C(R)&&(R=T,w=!0),_&&(w=(R=_(R,T,f))===T)),w?R=T?_resolveDefaultValue(g,f,T):T:(isPlainObject(R)||Fe(T))&&I&&T&&(isPlainObject(T)||Fe(T))&&objForEachKey(T,(function(f,S){_applyDefaultValue(g,R,f,S)})),g.set(f,S,R),b&&g.ref(f,S),A&&g[pi](f,S)}var Vr=symbolFor("[[ai_dynCfg_1]]"),Br=symbolFor("[[ai_blkDynCfg_1]]"),Hr=symbolFor("[[ai_frcDynCfg_1]]");function _cfgDeepCopy(g){var f;if(g&&(Fe(g)?(f=[])[gi]=g[gi]:isPlainObject(g)&&(f={}),f))return objForEachKey(g,(function(g,S){f[g]=_cfgDeepCopy(S)})),f;return g}function getDynamicConfigHandler(g){if(g){var f=g[Vr]||g;if(f.cfg&&(f.cfg===g||f.cfg[Vr]===f))return f}return null}function blockDynamicConversion(g){if(g&&(isPlainObject(g)||Fe(g)))try{g[Br]=!0}catch(g){}return g}function _canMakeDynamic(g,f,S){var v=!1;return S&&!g[f.blkVal]&&((v=S[Hr])||S[Br]||(v=isPlainObject(S)||Fe(S))),v}function throwInvalidAccess(g){throwTypeError("InvalidAccess:"+g)}var $r=["push","pop","shift","unshift","splice"],_throwDynamicError=function(g,f,S,v){g&&g[Si](3,108,"".concat(S," [").concat(f,"] failed - ")+dumpObj(v))};function _patchArray(g,f,S){Fe(f)&&arrForEach($r,(function(v){var C=f[v];f[v]=function(){for(var v=[],_=0;_<arguments.length;_++)v[_]=arguments[_];var T=C[Ei](this,v);return _makeDynamicObject(g,f,S,"Patching"),T}}))}function _getOwnPropGetter(g,f){var S=He(g,f);return S&&S.get}function _createDynamicProperty(g,f,S,v){var C={n:S,h:[],trk:function(f){f&&f.fn&&(-1===yt(C.h,f)&&C.h[_i](f),g.trk(f,C))},clr:function(g){var f=yt(C.h,g);-1!==f&&C.h[Ti](f,1)}},_=!0,T=!1;function _getProperty(){_&&(T=T||_canMakeDynamic(_getProperty,g,v),v&&!v[Vr]&&T&&(v=_makeDynamicObject(g,v,S,"Converting")),_=!1);var f=g.act;return f&&C.trk(f),v}function _setProperty(I){if(v!==I){_getProperty[g.ro]&&!g.upd&&throwInvalidAccess("["+S+"] is read-only:"+dumpObj(f)),_&&(T=T||_canMakeDynamic(_getProperty,g,v),_=!1);var b=T&&_getProperty[g.rf];if(T)if(b){objForEachKey(v,(function(g){v[g]=I?I[g]:Vn}));try{objForEachKey(I,(function(f,S){_setDynamicProperty(g,v,f,S)})),I=v}catch(f){_throwDynamicError((g.hdlr||{})[yi],S,"Assigning",f),T=!1}}else v&&v[Vr]&&objForEachKey(v,(function(f){var S=_getOwnPropGetter(v,f);if(S){var C=S[g.prop];C&&C.chng()}}));if(I!==v){var A=I&&_canMakeDynamic(_getProperty,g,I);!b&&A&&(I=_makeDynamicObject(g,I,S,"Converting")),v=I,T=A}g.add(C)}}_getProperty[g.prop]={chng:function(){g.add(C)}},objDefine(f,C.n,{g:_getProperty,s:_setProperty})}function _setDynamicProperty(g,f,S,v){if(f){var C=_getOwnPropGetter(f,S);C&&!!C[g.prop]?f[S]=v:_createDynamicProperty(g,f,S,v)}return f}function _setDynamicPropertyState(g,f,S,v){if(f){var C=_getOwnPropGetter(f,S),_=C&&!!C[g.prop],T=v&&v[0],I=v&&v[1],b=v&&v[2];if(!_){if(b)try{blockDynamicConversion(f)}catch(f){_throwDynamicError((g.hdlr||{})[yi],S,"Blocking",f)}try{_setDynamicProperty(g,f,S,f[S]),C=_getOwnPropGetter(f,S)}catch(f){_throwDynamicError((g.hdlr||{})[yi],S,"State",f)}}T&&(C[g.rf]=T),I&&(C[g.ro]=I),b&&(C[g.blkVal]=!0)}return f}function _makeDynamicObject(g,f,S,v){try{objForEachKey(f,(function(S,v){_setDynamicProperty(g,f,S,v)})),f[Vr]||(Ge(f,Vr,{get:function(){return g[Ii]}}),_patchArray(g,f,S))}catch(f){_throwDynamicError((g.hdlr||{})[yi],S,v,f)}return f}var jr="[[ai_",Gr="]]";function _createState(g){var f,S,v=newSymbol(jr+"get"+g.uid+Gr),C=newSymbol(jr+"ro"+g.uid+Gr),_=newSymbol(jr+"rf"+g.uid+Gr),T=newSymbol(jr+"blkVal"+g.uid+Gr),I=newSymbol(jr+"dtl"+g.uid+Gr),b=null,A=null;function _useHandler(f,v){var C=S.act;try{S.act=f,f&&f[I]&&(arrForEach(f[I],(function(g){g.clr(f)})),f[I]=[]),v({cfg:g.cfg,set:g.set.bind(g),setDf:g[vi].bind(g),ref:g.ref.bind(g),rdOnly:g[pi].bind(g)})}catch(f){var _=g[yi];throw _&&_[Si](1,107,dumpObj(f)),f}finally{S.act=C||null}}function _notifyWatchers(){if(b){var g=b;b=null,A&&A[bi](),A=null;var f=[];if(arrForEach(g,(function(g){if(g&&(g[I]&&(arrForEach(g[I],(function(f){f.clr(g)})),g[I]=null),g.fn))try{_useHandler(g,g.fn)}catch(g){f[_i](g)}})),b)try{_notifyWatchers()}catch(g){f[_i](g)}f[gi]>0&&throwAggregationError("Watcher error(s): ",f)}}function _addWatcher(g){if(g&&g.h[gi]>0){b||(b=[]),A||(A=scheduleTimeout((function(){A=null,_notifyWatchers()}),0));for(var f=0;f<g.h[gi];f++){var S=g.h[f];S&&-1===yt(b,S)&&b[_i](S)}}}function _trackHandler(g,f){if(g){var S=g[I]=g[I]||[];-1===yt(S,f)&&S[_i](f)}}return(f={prop:v,ro:C,rf:_})[ui]=T,f[Ii]=g,f.add=_addWatcher,f[mi]=_notifyWatchers,f.use=_useHandler,f.trk=_trackHandler,S=f}function _createAndUseHandler(g,f){var S={fn:f,rm:function(){S.fn=null,g=null,f=null}};return objDefine(S,"toJSON",{v:function(){return"WatcherHandler"+(S.fn?"":"[X]")}}),g.use(S,f),S}function _createDynamicHandler(g,f,S){var v,C=getDynamicConfigHandler(f);if(C)return C;var _,T=createUniqueNamespace("dyncfg",!0),I=f&&!1!==S?f:_cfgDeepCopy(f);function _notifyWatchers(){_[mi]()}function _setValue(f,S,v){try{f=_setDynamicProperty(_,f,S,v)}catch(f){_throwDynamicError(g,S,"Setting value",f)}return f[S]}function _watch(g){return _createAndUseHandler(_,g)}function _block(g,f){_.use(null,(function(S){var v=_.upd;try{isUndefined(f)||(_.upd=f),g(S)}finally{_.upd=v}}))}function _ref(g,f){var S;return _setDynamicPropertyState(_,g,f,(S={},S[0]=!0,S))[f]}function _rdOnly(g,f){var S;return _setDynamicPropertyState(_,g,f,(S={},S[1]=!0,S))[f]}function _blkPropValue(g,f){var S;return _setDynamicPropertyState(_,g,f,(S={},S[2]=!0,S))[f]}function _applyDefaults(g,f){return f&&objForEachKey(f,(function(f,S){_applyDefaultValue(b,g,f,S)})),g}var b=((v={uid:null,cfg:I})[yi]=g,v[mi]=_notifyWatchers,v.set=_setValue,v[vi]=_applyDefaults,v[Ci]=_watch,v.ref=_ref,v[pi]=_rdOnly,v[ui]=_blkPropValue,v._block=_block,v);return objDefine(b,"uid",{c:!1,e:!1,w:!1,v:T}),_makeDynamicObject(_=_createState(b),I,"config","Creating"),b}function _logInvalidAccess(g,f){g?(g[fi](f),g[Si](2,108,f)):throwInvalidAccess(f)}function createDynamicConfig(g,f,S,v){var C=_createDynamicHandler(S,g||{},v);return f&&C[vi](C.cfg,f),C}function onConfigChange(g,f,S){var v=g[Vr]||g;return!v.cfg||v.cfg!==g&&v.cfg[Vr]!==v?(_logInvalidAccess(S,sr+dumpObj(g)),createDynamicConfig(g,null,S)[Ci](f)):v[Ci](f)}function runTargetUnload(g,f){if(g&&g[Bi])return g[Bi](f)}function doUnloadAll(g,f,S){var v;return S||(v=createPromise((function(g){S=g}))),g&&Mt(g)>0?doAwaitResponse(runTargetUnload(g[0],f),(function(){doUnloadAll(arrSlice(g,1),f,S)})):S(),v}var qr=500,Wr="Microsoft_ApplicationInsights_BypassAjaxInstrumentation";function cfgDfMerge(g){return{mrg:!0,v:g}}function cfgDfString(g){return{isVal:ke,v:We(g||Bn)}}var zr,Kr,Jr=[Jn,Yn,Qn,Xn],Yr=null;function _listenerProxyFunc(g,f){return function(){var S=arguments,v=getDebugExt(f);if(v){var C=v.listener;C&&C[g]&&C[g][Ei](C,S)}}}function _getExtensionNamespace(){var g=getInst("Microsoft");return g&&(Yr=g.ApplicationInsights),Yr}function getDebugExt(g){var f=Yr;return f||!0===g.disableDbgExt||(f=Yr||_getExtensionNamespace()),f?f.ChromeDbgExt:null}function getDebugListener(g){if(!zr){zr={};for(var f=0;f<Jr[gi];f++)zr[Jr[f]]=_listenerProxyFunc(Jr[f],g)}return zr}var Qr="warnToConsole",Xr="AI (Internal): ",Zr="AI: ",es="AITR_",ts={loggingLevelConsole:0,loggingLevelTelemetry:1,maxMessageLimit:25,enableDebug:!1},is=((Kr={})[0]=null,Kr[1]="errorToConsole",Kr[2]=Qr,Kr[3]="debugToConsole",Kr);function _sanitizeDiagnosticText(g){return g?'"'+g[sn](/\"/g,Bn)+'"':Bn}function _logToConsole(g,f){var S=getConsole();if(S){var v="log";S[g]&&(v=g),Le(S[v])&&S[v](f)}}var ns=function(){function _InternalLogMessage2(g,f,S,v){void 0===S&&(S=!1);var C=this;C[Wi]=g,C[zi]=(S?Zr:Xr)+g;var _=Bn;hasJSON()&&(_=getJSON().stringify(v));var T=(f?" message:"+_sanitizeDiagnosticText(f):Bn)+(v?" props:"+_sanitizeDiagnosticText(_):Bn);C[zi]+=T}return _InternalLogMessage2.dataType="MessageData",_InternalLogMessage2}();function safeGetLogger(g,f){return(g||{})[yi]||new as(f)}var rs,ss,as=function(){function DiagnosticLogger2(g){this.identifier="DiagnosticLogger",this.queue=[];var f,S,v,C,_,T=0,I={};dynamicProto(DiagnosticLogger2,this,(function(b){function _logInternalMessage2(g,f){if(!_areInternalMessagesThrottled()){var C=!0,_=es+f[Wi];if(I[_]?C=!1:I[_]=!0,C&&(g<=S&&(b.queue[_i](f),T++,_debugExtMsg(1===g?"error":"warn",f)),T===v)){var A="Internal events throttle limit per PageView reached for this app.",P=new ns(23,A,!1);b.queue[_i](P),1===g?b.errorToConsole(A):b[fi](A)}}}function _setDefaultsFromConfig(g){return onConfigChange(createDynamicConfig(g,ts,b).cfg,(function(g){var _=g.cfg;f=_[ji],S=_.loggingLevelTelemetry,v=_.maxMessageLimit,C=_.enableDebug}))}function _areInternalMessagesThrottled(){return T>=v}function _debugExtMsg(f,S){var v=getDebugExt(g||{});v&&v[Ji]&&v[Ji](f,S)}_=_setDefaultsFromConfig(g||{}),b.consoleLoggingLevel=function(){return f},b[Si]=function(g,S,v,_,T){void 0===T&&(T=!1);var A=new ns(S,v,T,_);if(C)throw dumpObj(A);var P=is[g]||Qr;if(isUndefined(A[zi]))_debugExtMsg("throw"+(1===g?"Critical":"Warning"),A);else{if(T){var R=+A[Wi];!I[R]&&f>=g&&(b[P](A[zi]),I[R]=!0)}else f>=g&&b[P](A[zi]);_logInternalMessage2(g,A)}},b.debugToConsole=function(g){_logToConsole("debug",g),_debugExtMsg("warning",g)},b[fi]=function(g){_logToConsole("warn",g),_debugExtMsg("warning",g)},b.errorToConsole=function(g){_logToConsole("error",g),_debugExtMsg("error",g)},b.resetInternalMessageCount=function(){T=0,I={}},b[an]=_logInternalMessage2,b[Bi]=function(g){_&&_.rm(),_=null}}))}return DiagnosticLogger2.__ieDyn=1,DiagnosticLogger2}();function _getLogger(g){return g||new as}function _throwInternal(g,f,S,v,C,_){void 0===_&&(_=!1),_getLogger(g)[Si](f,S,v,C,_)}function _warnToConsole(g,f){_getLogger(g)[fi](f)}var os,ls="toGMTString",cs="toUTCString",ds="cookie",hs="expires",us="isCookieUseDisabled",gs="disableCookiesUsage",ps="_ckMgr",ms=null,fs=null,Ss=null,vs={},Cs={},ys=((rs={cookieCfg:cfgDfMerge((ss={},ss[nr]={fb:"cookieDomain",dfVal:isNotNullOrUndefined},ss.path={fb:"cookiePath",dfVal:isNotNullOrUndefined},ss.enabled=Vn,ss.ignoreCookies=Vn,ss.blockedCookies=Vn,ss)),cookieDomain:Vn,cookiePath:Vn})[gs]=Vn,rs);function _getDoc(){!os&&(os=getLazy((function(){return gt()})))}function _gblCookieMgr(g,f){var S=createCookieMgr[ps]||Cs[ps];return S||(S=createCookieMgr[ps]=createCookieMgr(g,f),Cs[ps]=S),S}function _isMgrEnabled(g){return!g||g.isEnabled()}function _isIgnoredCookie(g,f){return!!(f&&g&&Fe(g.ignoreCookies))&&-1!==yt(g.ignoreCookies,f)}function _isBlockedCookie(g,f){return!!(f&&g&&Fe(g.blockedCookies)&&-1!==yt(g.blockedCookies,f))||_isIgnoredCookie(g,f)}function _isCfgEnabled(g,f){var S=f[Ui];if(isNullOrUndefined(S)){var v=void 0;isUndefined(g[us])||(v=!g[us]),isUndefined(g[gs])||(v=!g[gs]),S=v}return S}function safeGetCookieMgr(g,f){var S;if(g)S=g.getCookieMgr();else if(f){var v=f.cookieCfg;S=v&&v[ps]?v[ps]:createCookieMgr(f)}return S||(S=_gblCookieMgr(f,(g||{})[yi])),S}function createCookieMgr(g,f){var S,v,C,_,T,I,b,A,P;g=createDynamicConfig(g||Cs,null,f).cfg,T=onConfigChange(g,(function(f){f[vi](f.cfg,ys),v=f.ref(f.cfg,"cookieCfg"),C=v[rr]||"/",_=v[nr],I=!1!==_isCfgEnabled(g,v),b=v.getCookie||_getCookieValue,A=v.setCookie||_setCookieValue,P=v.delCookie||_setCookieValue}),f);var R=((S={isEnabled:function(){var S=!1!==_isCfgEnabled(g,v)&&I&&areCookiesSupported(f),C=Cs[ps];return S&&C&&R!==C&&(S=_isMgrEnabled(C)),S},setEnabled:function(g){I=!1!==g,v[Ui]=g},set:function(g,f,S,T,I){var b=!1;if(_isMgrEnabled(R)&&!_isBlockedCookie(v,g)){var P={},M=Pt(f||Bn),w=Ot(M,";");if(-1!==w&&(M=Pt(strLeft(f,w)),P=_extractParts(st(f,w+1))),setValue(P,nr,T||_,isTruthy,isUndefined),!isNullOrUndefined(S)){var O=isIE();if(isUndefined(P[hs])){var D=utcNow()+1e3*S;if(D>0){var N=new Date;N.setTime(D),setValue(P,hs,_formatDate(N,O?ls:cs)||_formatDate(N,O?ls:cs)||Bn,isTruthy)}}O||setValue(P,"max-age",Bn+S,null,isUndefined)}var k=getLocation();k&&"https:"===k[en]&&(setValue(P,"secure",null,null,isUndefined),null===fs&&(fs=!uaDisallowsSameSiteNone((vt()||{})[tn])),fs&&setValue(P,"SameSite","None",null,isUndefined)),setValue(P,rr,I||C,null,isUndefined),A(g,_formatCookieValue(M,P)),b=!0}return b},get:function(g){var f=Bn;return _isMgrEnabled(R)&&!_isIgnoredCookie(v,g)&&(f=b(g)),f},del:function(g,f){var S=!1;return _isMgrEnabled(R)&&(S=R.purge(g,f)),S},purge:function(g,S){var v,C=!1;if(areCookiesSupported(f)){var _=((v={})[rr]=S||"/",v[hs]="Thu, 01 Jan 1970 00:00:01 GMT",v);isIE()||(_["max-age"]="0"),P(g,_formatCookieValue(Bn,_)),C=!0}return C}})[Bi]=function(g){T&&T.rm(),T=null},S);return R[ps]=R,R}function areCookiesSupported(g){if(null===ms){ms=!1,!os&&_getDoc();try{var f=os.v||{};ms=void 0!==f[ds]}catch(f){_throwInternal(g,2,68,"Cannot access document.cookie - "+getExceptionName(f),{exception:dumpObj(f)})}}return ms}function _extractParts(g){var f={};g&&g[gi]&&arrForEach(Pt(g)[nn](";"),(function(g){if(g=Pt(g||Bn)){var S=Ot(g,"=");-1===S?f[g]=null:f[Pt(strLeft(g,S))]=Pt(st(g,S+1))}}));return f}function _formatDate(g,f){return Le(g[f])?g[f]():null}function _formatCookieValue(g,f){var S=g||Bn;return objForEachKey(f,(function(g,f){S+="; "+g+(isNullOrUndefined(f)?Bn:"="+f)})),S}function _getCookieValue(g){var f=Bn;if(!os&&_getDoc(),os.v){var S=os.v[ds]||Bn;Ss!==S&&(vs=_extractParts(S),Ss=S),f=Pt(vs[g]||Bn)}return f}function _setCookieValue(g,f){!os&&_getDoc(),os.v&&(os.v[ds]=g+"="+f)}function uaDisallowsSameSiteNone(g){return!!ke(g)&&(!(!strContains(g,"CPU iPhone OS 12")&&!strContains(g,"iPad; CPU OS 12"))||(!!(strContains(g,"Macintosh; Intel Mac OS X 10_14")&&strContains(g,"Version/")&&strContains(g,"Safari"))||(!(!strContains(g,"Macintosh; Intel Mac OS X 10_14")||!wt(g,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))||(!(!strContains(g,"Chrome/5")&&!strContains(g,"Chrome/6"))||(!(!strContains(g,"UnrealEngine")||strContains(g,"Chrome"))||!(!strContains(g,"UCBrowser/12")&&!strContains(g,"UCBrowser/11")))))))}var Es={perfEvtsSendAll:!1};function _runScheduledListeners(g){g.h=null;var f=g.cb;g.cb=[],arrForEach(f,(function(g){safe(g.fn,[g.arg])}))}function _runListeners(g,f,S,v){arrForEach(g,(function(g){g&&g[f]&&(S?(S.cb[_i]({fn:v,arg:g}),S.h=S.h||scheduleTimeout(_runScheduledListeners,0,S)):safe(v,[g]))}))}var _s=function(){function NotificationManager2(g){var f,S;this.listeners=[];var v=[],C={h:null,cb:[]},_=createDynamicConfig(g,Es);S=_[Ci]((function(g){f=!!g.cfg.perfEvtsSendAll})),dynamicProto(NotificationManager2,this,(function(g){objDefine(g,"listeners",{g:function(){return v}}),g[Mi]=function(g){v[_i](g)},g[Ri]=function(g){for(var f=yt(v,g);f>-1;)v[Ti](f,1),f=yt(v,g)},g[Jn]=function(g){_runListeners(v,Jn,C,(function(f){f[Jn](g)}))},g[Yn]=function(g,f){_runListeners(v,Yn,C,(function(S){S[Yn](g,f)}))},g[Qn]=function(g,f){_runListeners(v,Qn,f?C:null,(function(S){S[Qn](g,f)}))},g[Xn]=function(g){g&&(!f&&g[un]()||_runListeners(v,Xn,null,(function(f){g[Ki]?scheduleTimeout((function(){return f[Xn](g)}),0):f[Xn](g)})))},g[Zn]=function(g){g&&g[gi]&&_runListeners(v,Zn,C,(function(f){f[Zn](g)}))},g[er]=function(g){g&&g[gn]&&_runListeners(v,er,C,(function(f){f[er](g)}))},g[tr]=function(g,f){if(g>0){var S=f||0;_runListeners(v,tr,C,(function(f){f[tr](g,S)}))}},g[Bi]=function(g){var f,_finishUnload=function(){S&&S.rm(),S=null,v=[],C.h&&C.h[bi](),C.h=null,C.cb=[]};if(_runListeners(v,"unload",null,(function(S){var v=S[Bi](g);v&&(f||(f=[]),f[_i](v))})),f)return createPromise((function(g){return doAwaitResponse(Un(f),(function(){_finishUnload(),g()}))}));_finishUnload()}}))}return NotificationManager2.__ieDyn=1,NotificationManager2}(),Ts="ctx",Is="ParentContextKey",bs="ChildrenContextKey",As=null,Ps=function(){function PerfEvent2(g,f,S){var v,C=this;(C.start=utcNow(),C[ki]=g,C[Ki]=S,C[un]=function(){return!1},Le(f))&&objDefine(C,"payload",{g:function(){return!v&&Le(f)&&(v=f(),f=null),v}});C[pn]=function(g){return g?g===PerfEvent2[Is]||g===PerfEvent2[bs]?C[g]:(C[Ts]||{})[g]:null},C[mn]=function(g,f){if(g)if(g===PerfEvent2[Is])C[g]||(C[un]=function(){return!0}),C[g]=f;else if(g===PerfEvent2[bs])C[g]=f;else{(C[Ts]=C[Ts]||{})[g]=f}},C[fn]=function(){var g=0,f=C[pn](PerfEvent2[bs]);if(Fe(f))for(var S=0;S<f[gi];S++){var v=f[S];v&&(g+=v[Li])}C[Li]=utcNow()-C.start,C.exTime=C[Li]-g,C[fn]=function(){}}}return PerfEvent2.ParentContextKey="parent",PerfEvent2.ChildrenContextKey="childEvts",PerfEvent2}(),Rs=function(){function PerfManager2(g){this.ctx={},dynamicProto(PerfManager2,this,(function(f){f.create=function(g,f,S){return new Ps(g,f,S)},f.fire=function(f){f&&(f[fn](),g&&Le(g[Xn])&&g[Xn](f))},f[mn]=function(g,S){g&&((f[Ts]=f[Ts]||{})[g]=S)},f[pn]=function(g){return(f[Ts]||{})[g]}}))}return PerfManager2.__ieDyn=1,PerfManager2}(),Ms="CoreUtils.doPerf";function doPerf(g,f,S,v,C){if(g){var _=g;if(_[ir]&&(_=_[ir]()),_){var T=void 0,I=_[pn](Ms);try{if(T=_.create(f(),v,C)){if(I&&T[mn]&&(T[mn](Ps[Is],I),I[pn]&&I[mn])){var b=I[pn](Ps[bs]);b||(b=[],I[mn](Ps[bs],b)),b[_i](T)}return _[mn](Ms,T),S(T)}}catch(g){T&&T[mn]&&T[mn]("exception",g)}finally{T&&_.fire(T),_[mn](Ms,I)}}}return S()}function getGblPerfMgr(){return As}function newGuid(){var g=generateW3CId();return st(g,0,8)+"-"+st(g,8,12)+"-"+st(g,12,16)+"-"+st(g,16,20)+"-"+st(g,20)}function generateW3CId(){for(var g,f=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],S=Bn,v=0;v<4;v++)S+=f[15&(g=random32())]+f[g>>4&15]+f[g>>8&15]+f[g>>12&15]+f[g>>16&15]+f[g>>20&15]+f[g>>24&15]+f[g>>28&15];var C=f[8+(3&random32())|0];return at(S,0,8)+at(S,9,4)+"4"+at(S,13,3)+C+at(S,16,3)+at(S,19,12)}var ws="00000000000000000000000000000000",Os="0000000000000000";function _isValid(g,f,S){return!(!g||g[gi]!==f||g===S)&&!!g.match(/^[\da-f]*$/i)}function isValidTraceId(g){return _isValid(g,32,ws)}function isValidSpanId(g){return _isValid(g,16,Os)}var Ds=createElmNodeData("plugin");function _getPluginState(g){return Ds.get(g,"state",{},!0)}function initializePlugins(g,f){for(var S,v=[],C=null,_=g[Xi]();_;){var T=_[Di]();if(T){C&&C[Zi]&&T[zn]&&C[Zi](T);var I=!!(S=_getPluginState(T))[wi];T[wi]&&(I=T[wi]()),I||v[_i](T),C=T,_=_[Xi]()}}arrForEach(v,(function(v){var C=g[$n]();v[Ai](g.getCfg(),C,f,g[Xi]()),S=_getPluginState(v),v[$n]||S[$n]||(S[$n]=C),S[wi]=!0,delete S[qi]}))}function sortPlugins(g){return g.sort((function(g,f){var S=0;if(f){var v=f[zn];g[zn]?S=v?g[Kn]-f[Kn]:1:v&&(S=-1)}else S=g?1:-1;return S}))}function createDistributedTraceContext(g){var f={};return{getName:function(){return f[ki]},setName:function(S){g&&g.setName(S),f[ki]=S},getTraceId:function(){return f[_n]},setTraceId:function(S){g&&g.setTraceId(S),isValidTraceId(S)&&(f[_n]=S)},getSpanId:function(){return f[Tn]},setSpanId:function(S){g&&g.setSpanId(S),isValidSpanId(S)&&(f[Tn]=S)},getTraceFlags:function(){return f[In]},setTraceFlags:function(S){g&&g.setTraceFlags(S),f[In]=S}}}var Ns,ks="TelemetryPluginChain",Ls="_hasRun",Fs="_getTelCtx",xs=0;function _getNextProxyStart(g,f,S){for(;g;){if(g[Di]()===S)return g;g=g[Xi]()}return createTelemetryProxyChain([S],f.config||{},f)}function _createInternalContext(g,f,S,v){var C=null,_=[];f||(f=createDynamicConfig({},null,S[yi])),null!==v&&(C=v?_getNextProxyStart(g,S,v):g);var T={_next:_moveNext,ctx:{core:function(){return S},diagLog:function(){return safeGetLogger(S,f.cfg)},getCfg:function(){return f.cfg},getExtCfg:_resolveExtCfg,getConfig:_getConfig,hasNext:function(){return!!C},getNext:function(){return C},setNext:function(g){C=g},iterate:_iterateChain,onComplete:_addOnComplete}};function _addOnComplete(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];g&&_[_i]({func:g,self:isUndefined(f)?T.ctx:f,args:S})}function _moveNext(){var g=C;if(C=g?g[Xi]():null,!g){var f=_;f&&f[gi]>0&&(arrForEach(f,(function(g){try{g.func.call(g.self,g.args)}catch(g){_throwInternal(S[yi],2,73,"Unexpected Exception during onComplete - "+dumpObj(g))}})),_=[])}return g}function _getExtCfg(g,S){var v=null,C=f.cfg;if(C&&g){var _=C[qn];!_&&S&&(_={}),C[qn]=_,(_=f.ref(C,qn))&&(!(v=_[g])&&S&&(v={}),_[g]=v,v=f.ref(_,g))}return v}function _resolveExtCfg(g,S){var v=_getExtCfg(g,!0);return S&&objForEachKey(S,(function(g,S){if(isNullOrUndefined(v[g])){var C=f.cfg[g];!C&&isNullOrUndefined(C)||(v[g]=C)}_applyDefaultValue(f,v,g,S)})),f[vi](v,S)}function _getConfig(g,S,v){var C;void 0===v&&(v=!1);var _=_getExtCfg(g,!1),T=f.cfg;return!_||!_[S]&&isNullOrUndefined(_[S])?!T[S]&&isNullOrUndefined(T[S])||(C=T[S]):C=_[S],C||!isNullOrUndefined(C)?C:v}function _iterateChain(g){for(var f;f=T._next();){var S=f[Di]();S&&g(S)}}return T}function createProcessTelemetryContext(g,f,S,v){var C=createDynamicConfig(f),_=_createInternalContext(g,C,S,v),T=_.ctx;function _processNext(g){var f=_._next();return f&&f[zn](g,T),!f}function _createNew(g,f){return void 0===g&&(g=null),Fe(g)&&(g=createTelemetryProxyChain(g,C.cfg,S,f)),createProcessTelemetryContext(g||T[Xi](),C.cfg,S,f)}return T[Fi]=_processNext,T[Gi]=_createNew,T}function createProcessTelemetryUnloadContext(g,f,S){var v=createDynamicConfig(f.config),C=_createInternalContext(g,v,f,S),_=C.ctx;function _processNext(g){var f=C._next();return f&&f[Bi](_,g),!f}function _createNew(g,S){return void 0===g&&(g=null),Fe(g)&&(g=createTelemetryProxyChain(g,v.cfg,f,S)),createProcessTelemetryUnloadContext(g||_[Xi](),f,S)}return _[Fi]=_processNext,_[Gi]=_createNew,_}function createProcessTelemetryUpdateContext(g,f,S){var v=createDynamicConfig(f.config),C=_createInternalContext(g,v,f,S).ctx;function _processNext(g){return C.iterate((function(f){Le(f[Qi])&&f[Qi](C,g)}))}function _createNew(g,S){return void 0===g&&(g=null),Fe(g)&&(g=createTelemetryProxyChain(g,v.cfg,f,S)),createProcessTelemetryUpdateContext(g||C[Xi](),f,S)}return C[Fi]=_processNext,C[Gi]=_createNew,C}function createTelemetryProxyChain(g,f,S,v){var C=null,_=!v;if(Fe(g)&&g[gi]>0){var T=null;arrForEach(g,(function(g){if(_||v!==g||(_=!0),_&&g&&Le(g[zn])){var I=createTelemetryPluginProxy(g,f,S);C||(C=I),T&&T._setNext(I),T=I}}))}return v&&!C?createTelemetryProxyChain([v],f,S):C}function createTelemetryPluginProxy(g,f,S){var v,C=null,_=Le(g[zn]),T=Le(g[Zi]),I={getPlugin:function(){return g},getNext:function(){return C},processTelemetry:_processTelemetry,unload:_unloadPlugin,update:_updatePlugin,_id:v=g?g[Pi]+"-"+g[Kn]+"-"+xs++:"Unknown-0-"+xs++,_setNext:function(g){C=g}};function _getTelCtx(){var v;return g&&Le(g[Fs])&&(v=g[Fs]()),v||(v=createProcessTelemetryContext(I,f,S)),v}function _processChain(f,S,_,T,I){var b=!1,A=g?g[Pi]:ks,P=f[Ls];return P||(P=f[Ls]={}),f.setNext(C),g&&doPerf(f[$n](),(function(){return A+":"+_}),(function(){P[v]=!0;try{var g=C?C._id:Bn;g&&(P[g]=!1),b=S(f)}catch(g){var T=!C||P[C._id];T&&(b=!0),C&&T||_throwInternal(f[Ji](),1,73,"Plugin ["+A+"] failed during "+_+" - "+dumpObj(g)+", run flags: "+dumpObj(P))}}),T,I),b}function _processTelemetry(f,S){function _callProcessTelemetry(S){if(!g||!_)return!1;var v=_getPluginState(g);return!v[qi]&&!v[Gn]&&(T&&g[Zi](C),g[zn](f,S),!0)}_processChain(S=S||_getTelCtx(),_callProcessTelemetry,"processTelemetry",(function(){return{item:f}}),!f.sync)||S[Fi](f)}function _unloadPlugin(f,S){function _callTeardown(){var v=!1;if(g){var C=_getPluginState(g),_=g[$n]||C[$n];!g||_&&_!==f.core()||C[qi]||(C[$n]=null,C[qi]=!0,C[wi]=!1,g[qi]&&!0===g[qi](f,S)&&(v=!0))}return v}_processChain(f,_callTeardown,"unload",(function(){}),S[Ki])||f[Fi](S)}function _updatePlugin(f,S){function _callUpdate(){var v=!1;if(g){var C=_getPluginState(g),_=g[$n]||C[$n];!g||_&&_!==f.core()||C[qi]||g[Qi]&&!0===g[Qi](f,S)&&(v=!0)}return v}_processChain(f,_callUpdate,"update",(function(){}),!1)||f[Fi](S)}return Qe(I)}function createUnloadHandlerContainer(){var g=[];function _addHandler(f){f&&g[_i](f)}function _runHandlers(f,S){arrForEach(g,(function(g){try{g(f,S)}catch(g){_throwInternal(f[Ji](),2,73,"Unexpected error calling unload handler - "+dumpObj(g))}})),g=[]}return{add:_addHandler,run:_runHandlers}}function createUnloadHookContainer(){var g=[];function _doUnload(f){var S=g;g=[],arrForEach(S,(function(g){try{(g.rm||g.remove).call(g)}catch(g){_throwInternal(f,2,73,"Unloading:"+dumpObj(g))}}))}function _addHook(f){f&&arrAppend(g,f)}return{run:_doUnload,add:_addHook}}var Us="getPlugin",Vs=((Ns={})[qn]={isVal:isNotNullOrUndefined,v:{}},Ns),Bs=function(){function BaseTelemetryPlugin2(){var g,f,S,v,C,_=this;function _getTelCtx(g){void 0===g&&(g=null);var v=g;if(!v){var C=f||createProcessTelemetryContext(null,{},_[$n]);v=S&&S[Us]?C[Gi](null,S[Us]):C[Gi](null,S)}return v}function _setDefaults(g,v,C){createDynamicConfig(g,Vs,safeGetLogger(v)),!C&&v&&(C=v[xi]()[Xi]());var T=S;S&&S[Us]&&(T=S[Us]()),_[$n]=v,f=createProcessTelemetryContext(C,g,v,T)}function _initDefaults(){g=!1,_[$n]=null,f=null,S=null,C=createUnloadHookContainer(),v=createUnloadHandlerContainer()}_initDefaults(),dynamicProto(BaseTelemetryPlugin2,_,(function(f){f[Ai]=function(f,S,v,C){_setDefaults(f,S,C),g=!0},f[qi]=function(g,_){var T,I=f[$n];if(I&&(!g||I===g[$n]())){var b,A=!1,P=g||createProcessTelemetryUnloadContext(null,I,S&&S[Us]?S[Us]():S),R=_||((T={reason:0})[Ki]=!1,T);return f[Yi]&&!0===f[Yi](P,R,_unloadCallback)?b=!0:_unloadCallback(),b}function _unloadCallback(){A||(A=!0,v.run(P,_),C.run(P[Ji]()),!0===b&&P[Fi](R),_initDefaults())}},f[Qi]=function(g,v){var C=f[$n];if(C&&(!g||C===g[$n]())){var _,T=!1,I=g||createProcessTelemetryUpdateContext(null,C,S&&S[Us]?S[Us]():S),b=v||{reason:0};return f._doUpdate&&!0===f._doUpdate(I,b,_updateCallback)?_=!0:_updateCallback(),_}function _updateCallback(){T||(T=!0,_setDefaults(I.getCfg(),I.core(),I[Xi]()))}},proxyFunctionAs(f,"_addUnloadCb",(function(){return v}),"add"),proxyFunctionAs(f,"_addHook",(function(){return C}),"add"),objDefine(f,"_unloadHooks",{g:function(){return C}})})),_[Ji]=function(g){return _getTelCtx(g)[Ji]()},_[wi]=function(){return g},_.setInitialized=function(f){g=f},_[Zi]=function(g){S=g},_[Fi]=function(g,f){f?f[Fi](g):S&&Le(S[zn])&&S[zn](g,null)},_._getTelCtx=_getTelCtx}return BaseTelemetryPlugin2.__ieDyn=1,BaseTelemetryPlugin2}();function _addInitializer(g,f,S){var v={id:f,fn:S};return arrAppend(g,v),{remove:function(){arrForEach(g,(function(f,S){if(f.id===v.id)return g[Ti](S,1),-1}))}}}function _runInitializers(g,f,S){for(var v=!1,C=g[gi],_=0;_<C;++_){var T=g[_];if(T)try{if(!1===T.fn[Ei](null,[f])){v=!0;break}}catch(g){_throwInternal(S,2,64,"Telemetry initializer failed: "+getExceptionName(g),{exception:dumpObj(g)},!0)}}return!v}var Hs,$s=function(g){function TelemetryInitializerPlugin2(){var f,S,v=g.call(this)||this;function _initDefaults(){f=0,S=[]}return v.identifier="TelemetryInitializerPlugin",v.priority=199,_initDefaults(),dynamicProto(TelemetryInitializerPlugin2,v,(function(g,v){g.addTelemetryInitializer=function(g){return _addInitializer(S,f++,g)},g[zn]=function(f,v){_runInitializers(S,f,v?v[Ji]():g[Ji]())&&g[Fi](f,v)},g[Yi]=function(){_initDefaults()}})),v}return __extendsFn(TelemetryInitializerPlugin2,g),TelemetryInitializerPlugin2.__ieDyn=1,TelemetryInitializerPlugin2}(Bs),js="Plugins must provide initialize method",Gs="_notificationManager",qs="SDK is still unloading...",Ws="SDK is not initialized",zs=objDeepFreeze(((Hs={cookieCfg:{}})[Wn]={rdOnly:!0,ref:!0,v:[]},Hs[Hn]={rdOnly:!0,ref:!0,v:[]},Hs[qn]={ref:!0,v:{}},Hs[jn]=Vn,Hs.loggingLevelConsole=0,Hs.diagnosticLogInterval=Vn,Hs));function _createPerfManager(g,f){return new Rs(f)}function _validateExtensions(g,f,S){var v,C=[],_=[],T={};return arrForEach(S,(function(S){(isNullOrUndefined(S)||isNullOrUndefined(S[Ai]))&&throwError(js);var v=S[Kn],I=S[Pi];S&&v&&(isNullOrUndefined(T[v])?T[v]=I:_warnToConsole(g,"Two extensions have same priority #"+v+" - "+T[v]+", "+I)),!v||v<f?C[_i](S):_[_i](S)})),(v={})[$n]=C,v[Hn]=_,v}function _isPluginPresent(g,f){var S=!1;return arrForEach(f,(function(f){if(f===g)return S=!0,-1})),S}function _deepMergeConfig(g,f,S,v){S&&objForEachKey(S,(function(S,C){v&&isPlainObject(C)&&isPlainObject(f[S])&&_deepMergeConfig(g,f[S],C,v),v&&isPlainObject(C)&&isPlainObject(f[S])?_deepMergeConfig(g,f[S],C,v):g.set(f,S,C)}))}function _findWatcher(g,f){var S=null,v=-1;return arrForEach(g,(function(g,C){if(g.w===f)return S=g,v=C,-1})),{i:v,l:S}}function _addDelayedCfgListener(g,f){var S=_findWatcher(g,f).l;return S||(S={w:f,rm:function(){var S=_findWatcher(g,f);-1!==S.i&&g[Ti](S.i,1)}},g[_i](S)),S}function _registerDelayedCfgListener(g,f,S){arrForEach(f,(function(f){var v=onConfigChange(g,f.w,S);delete f.w,f.rm=function(){v.rm()}}))}function _initDebugListener(g,f,S,v){return f.add(g[Ci]((function(g){var f=g.cfg.disableDbgExt;!0===f&&v&&(S[Ri](v),v=null),S&&!v&&!0!==f&&(v=getDebugListener(g.cfg),S[Mi](v))}))),v}function _createUnloadHook(g){return objDefine({rm:function(){g.rm()}},"toJSON",{v:function(){return"aicore::onCfgChange<"+JSON.stringify(g)+">"}})}var Ks=function(){function AppInsightsCore3(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G;dynamicProto(AppInsightsCore3,this,(function(q){function _startLogPoller(f){$&&$[Ui]||G||(f||S&&S.queue[gi]>0)&&(j||(j=!0,_addUnloadHook(g[Ci]((function(g){var f=g.cfg.diagnosticLogInterval;f&&f>0||(f=1e4);var S=!1;$&&(S=$[Ui],$[bi]()),($=createTimeout(_flushInternalLogs,f)).unref(),$[Ui]=S})))),$[Ui]=!0);return $}function _setPluginVersions(){var g={};B=[];var _addPluginVersions=function(f){f&&arrForEach(f,(function(f){if(f[Pi]&&f[$i]&&!g[f.identifier]){var S=f[Pi]+"="+f[$i];B[_i](S),g[f.identifier]=f}}))};_addPluginVersions(R),P&&arrForEach(P,(function(g){_addPluginVersions(g)})),_addPluginVersions(A)}function _initDefaults(){f=!1,(g=createDynamicConfig({},zs,q[yi])).cfg[ji]=1,objDefine(q,"config",{g:function(){return g.cfg},s:function(g){q.updateCfg(g,!1)}}),objDefine(q,"pluginVersionStringArr",{g:function(){return B||_setPluginVersions(),B}}),objDefine(q,"pluginVersionString",{g:function(){return H||(B||_setPluginVersions(),H=B.join(";")),H||Bn}}),objDefine(q,"logger",{g:function(){return S||(S=new as(g.cfg),g[yi]=S),S},s:function(f){g[yi]=f,S!==f&&(runTargetUnload(S,!1),S=f)}}),q[yi]=new as(g.cfg),V=[];var L=q.config[Wn]||[];L.splice(0,L[gi]),arrAppend(L,V),w=new $s,v=[],runTargetUnload(C,!1),C=null,_=null,T=null,runTargetUnload(I,!1),I=null,b=null,A=[],P=null,R=null,M=!1,O=null,D=createUniqueNamespace("AIBaseCore",!0),N=createUnloadHandlerContainer(),F=null,x=null,k=createUnloadHookContainer(),U=[],H=null,B=null,G=!1,$=null,j=!1}function _createTelCtx(){var f=createProcessTelemetryContext(_getPluginChain(),g.cfg,q);return f[Hi](_startLogPoller),f}function _initPluginChain(g){var f=_validateExtensions(q[yi],qr,A);b=null,H=null,B=null,R=sortPlugins(arrAppend(R=(P||[])[0]||[],f[Hn]));var S=arrAppend(sortPlugins(f[$n]),R);V=Qe(S);var v=q.config[Wn]||[];v.splice(0,v[gi]),arrAppend(v,V);var C=_createTelCtx();R&&R[gi]>0&&initializePlugins(C[Gi](R),S),initializePlugins(C,S),g&&_doUpdate(g)}function _getPlugin(g){var f=null,S=null,v=[];return arrForEach(V,(function(f){if(f[Pi]===g&&f!==w)return S=f,-1;f.getChannel&&v[_i](f)})),!S&&v[gi]>0&&arrForEach(v,(function(f){if(!(S=f.getChannel(g)))return-1})),S&&(f={plugin:S,setEnabled:function(g){_getPluginState(S)[Gn]=!g},isEnabled:function(){var g=_getPluginState(S);return!g[qi]&&!g[Gn]},remove:function(g,f){var v;void 0===g&&(g=!0);var C=[S],_=((v={reason:1})[Ki]=g,v);_removePlugins(C,_,(function(g){g&&_initPluginChain({reason:32,removed:C}),f&&f(g)}))}}),f}function _getPluginChain(){if(!b){var f=(V||[]).slice();-1===yt(f,w)&&f[_i](w),b=createTelemetryProxyChain(sortPlugins(f),g.cfg,q)}return b}function _removePlugins(f,S,v){if(f&&f[gi]>0){var C=createProcessTelemetryUnloadContext(createTelemetryProxyChain(f,g.cfg,q),q);C[Hi]((function(){var g=!1,S=[];arrForEach(A,(function(v,C){_isPluginPresent(v,f)?g=!0:S[_i](v)})),A=S,H=null,B=null;var C=[];P&&(arrForEach(P,(function(S,v){var _=[];arrForEach(S,(function(S){_isPluginPresent(S,f)?g=!0:_[_i](S)})),C[_i](_)})),P=C),v&&v(g),_startLogPoller()})),C[Fi](S)}else v(!1)}function _flushInternalLogs(){if(S&&S.queue){var g=S.queue.slice(0);S.queue[gi]=0,arrForEach(g,(function(g){var f,S=((f={})[ki]=O||"InternalMessageId: "+g[Wi],f.iKey=x,f[Li]=toISOString(new Date),f.baseType=ns.dataType,f.baseData={message:g[zi]},f);q.track(S)}))}}function _flushChannels(g,f,S,v){var C=1,_=!1,T=null;function doCallback(){C--,_&&0===C&&(T&&T[bi](),T=null,f&&f(_),f=null)}(v=v||5e3,R&&R[gi]>0)&&_createTelCtx()[Gi](R).iterate((function(f){if(f.flush){C++;var _=!1;f.flush(g,(function(){_=!0,doCallback()}),S)||_||(g&&null==T?T=scheduleTimeout((function(){T=null,doCallback()}),v):doCallback())}}));return _=!0,doCallback(),!0}function _initPerfManager(){var f;_addUnloadHook(g[Ci]((function(g){if(g.cfg.enablePerfMgr){var S=g.cfg[jn];f!==S&&(S||(S=_createPerfManager),getSetValue(g.cfg,jn,S),f=S,T=null),_||T||!Le(S)||(T=S(q,q[Oi]()))}else T=null,f=null})))}function _doUpdate(g){var f=createProcessTelemetryUpdateContext(_getPluginChain(),q);f[Hi](_startLogPoller),q._updateHook&&!0===q._updateHook(f,g)||f[Fi](g)}function _logOrThrowError(g){var f=q[yi];f?(_throwInternal(f,2,73,g),_startLogPoller()):throwError(g)}function _notifyInvalidEvent(g){var f=q[Oi]();f&&f[Yn]([g],2)}function _addUnloadHook(g){k.add(g)}_initDefaults(),q._getDbgPlgTargets=function(){return[V]},q[wi]=function(){return f},q[Ai]=function(v,_,T,I){M&&throwError(qs),q[wi]()&&throwError("Core cannot be initialized more than once"),v=(g=createDynamicConfig(v,zs,T||q[yi],!1)).cfg,_addUnloadHook(g[Ci]((function(g){x=g.cfg.instrumentationKey;var f=g.ref(g.cfg,qn);objForEachKey(f,(function(S){g.ref(f,S)})),isNullOrUndefined(x)&&throwError("Please provide instrumentation key")}))),L=_initDebugListener(g,k,(C=I)&&q[Oi](),L),_initPerfManager(),q[yi]=T;var b=v[Wn];if((A=[])[_i].apply(A,__spreadArrayFn(__spreadArrayFn([],_,!1),b)),P=v[Hn],_initPluginChain(null),R&&0!==R[gi]||throwError("No "+Hn+" available"),P&&P[gi]>1){var w=q[Di]("TeeChannelController");w&&w.plugin||_throwInternal(S,1,28,"TeeChannel required")}_registerDelayedCfgListener(v,U,S),U=null,f=!0,q.releaseQueue(),q[Ni]()},q.getChannels=function(){var g=[];return R&&arrForEach(R,(function(f){g[_i](f)})),Qe(g)},q.track=function(g){doPerf(q[ir](),(function(){return"AppInsightsCore:track"}),(function(){null===g&&(_notifyInvalidEvent(g),throwError("Invalid telemetry item")),!g[ki]&&isNullOrUndefined(g[ki])&&(_notifyInvalidEvent(g),throwError("telemetry name required")),g.iKey=g.iKey||x,g[Li]=g[Li]||toISOString(new Date),g.ver=g.ver||"4.0",!M&&q[wi]()?_createTelCtx()[Fi](g):v[_i](g)}),(function(){return{item:g}}),!g.sync)},q[xi]=_createTelCtx,q[Oi]=function(){return C||(C=new _s(g.cfg),q[Gs]=C),C},q[Mi]=function(g){q.getNotifyMgr()[Mi](g)},q[Ri]=function(g){C&&C[Ri](g)},q.getCookieMgr=function(){return I||(I=createCookieMgr(g.cfg,q[yi])),I},q.setCookieMgr=function(g){I!==g&&(runTargetUnload(I,!1),I=g)},q[ir]=function(){return _||T||getGblPerfMgr()},q.setPerfMgr=function(g){_=g},q.eventCnt=function(){return v[gi]},q.releaseQueue=function(){if(f&&v[gi]>0){var g=v;v=[],arrForEach(g,(function(g){_createTelCtx()[Fi](g)}))}},q[Ni]=function(g){return O=g||null,G=!1,$&&$[bi](),_startLogPoller(!0)},q[Vi]=function(){G=!0,$&&$[bi](),_flushInternalLogs()},proxyFunctions(q,(function(){return w}),["addTelemetryInitializer"]),q[Bi]=function(g,v,_){var T;void 0===g&&(g=!0),f||throwError(Ws),M&&throwError(qs);var b,A=((T={reason:50})[Ki]=g,T.flushComplete=!1,T);g&&!v&&(b=createPromise((function(g){v=g})));var P=createProcessTelemetryUnloadContext(_getPluginChain(),q);function _doUnload(g){A.flushComplete=g,M=!0,N.run(P,A),q[Vi](),P[Fi](A)}return P[Hi]((function(){k.run(q[yi]),doUnloadAll([I,C,S],g,(function(){_initDefaults(),v&&v(A)}))}),q),_flushInternalLogs(),_flushChannels(g,_doUnload,6,_),b},q[Di]=_getPlugin,q.addPlugin=function(g,f,S,v){if(!g)return v&&v(!1),void _logOrThrowError(js);var C=_getPlugin(g[Pi]);if(C&&!f)return v&&v(!1),void _logOrThrowError("Plugin ["+g[Pi]+"] is already loaded!");var _={reason:16};function _addPlugin(f){A[_i](g),_.added=[g],_initPluginChain(_),v&&v(!0)}if(C){var T=[C.plugin];_removePlugins(T,{reason:2,isAsync:!!S},(function(g){g?(_.removed=T,_.reason|=32,_addPlugin()):v&&v(!1)}))}else _addPlugin()},q.updateCfg=function(f,S){var v;if(void 0===S&&(S=!0),q[wi]()){v={reason:1,cfg:g.cfg,oldCfg:deepExtend({},g.cfg),newConfig:deepExtend({},f),merge:S},f=v.newConfig;var C=g.cfg;f[Wn]=C[Wn],f[Hn]=C[Hn]}g._block((function(g){var v=g.cfg;_deepMergeConfig(g,v,f,S),S||objForEachKey(v,(function(S){$e(f,S)||g.set(v,S,Vn)})),g[vi](v,zs)}),!0),g[mi](),v&&_doUpdate(v)},q.evtNamespace=function(){return D},q.flush=_flushChannels,q.getTraceCtx=function(g){return F||(F=createDistributedTraceContext()),F},q.setTraceCtx=function(g){F=g||null},q.addUnloadHook=_addUnloadHook,proxyFunctionAs(q,"addUnloadCb",(function(){return N}),"add"),q.onCfgChange=function(S){return _createUnloadHook(f?onConfigChange(g.cfg,S,q[yi]):_addDelayedCfgListener(U,S))},q.getWParam=function(){return hasDocument()||g.cfg.enableWParam?0:-1}}))}return AppInsightsCore3.__ieDyn=1,AppInsightsCore3}(),Js="",Ys="&"+"NoResponseBody"+"=true",Qs="POST",Xs=function(){function SenderPostManager2(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w=0;dynamicProto(SenderPostManager2,this,(function(O,D){var N=!0;function _onSuccess(g,f){_doOnComplete(f,200,{},g)}function _onError(g,f){_throwInternal(S,2,26,"Failed to send telemetry.",{message:g}),_doOnComplete(f,400,{})}function _onNoPayloadUrl(g){_onError("No endpoint url is provided for the batch",g)}function _getSenderInterface(g,f){for(var S,v=0,C=null,_=0;null==C&&_<g[gi];)v=g[_],I||1!==v?2!==v||!isFetchSupported(f)||f&&P?3!==v||!isBeaconsSupported()||(f?A:b)||(C=_beaconSender):C=_doFetchSender:useXDomainRequest()?C=_xdrSender:isXhrSupported()&&(C=_xhrSender),_++;return C?((S={_transport:v,_isSync:f})[vn]=C,S):null}function _doOnComplete(g,f,S,v){try{g&&g(f,S,v)}catch(g){}}function _doBeaconSend(g,f){var S=vt(),C=g[Sn];if(!C)return _onNoPayloadUrl(f),!0;C=g[Sn]+(R?Ys:Js);var _=g[gn],T=v?_:new Blob([_],{type:"text/plain;charset=UTF-8"});return S.sendBeacon(C,T)}function _beaconSender(g,f,_){var I=g[gn];try{if(I)if(_doBeaconSend(g,f))_onSuccess(Js,f);else{var b=C&&C.beaconOnRetry;b&&Le(b)?b(g,f,_doBeaconSend):(T&&T[vn](g,f,!0),_throwInternal(S,2,40,". Failed to send telemetry with Beacon API, retried with normal sender."))}}catch(g){v&&_warnToConsole(S,"Failed to send telemetry using sendBeacon API. Ex:"+dumpObj(g)),_doOnComplete(f,v?0:400,{},Js)}}function _xhrSender(f,S,_){var T,I,b,A=f[Cn]||{};!_&&g&&(T=createPromise((function(g,f){I=g,b=f}))),v&&_&&f.disableXhrSync&&(_=!1);var P=f[Sn];if(!P)return _onNoPayloadUrl(S),void(I&&I(!1));var R=openXhr(Qs,P,N,!0,_,f[yn]);function _doOnReadyFunc(g){var _=C&&C.xhrOnComplete;if(_&&Le(_))_(g,S,f);else{var T=getResponseText(g);_doOnComplete(S,g[cn],_getAllResponseHeaders(g,v),T)}}return v||R[En]("Content-type","application/json"),arrForEach(Ye(A),(function(g){R[En](g,A[g])})),R.onreadystatechange=function(){v||(_doOnReadyFunc(R),4===R.readyState&&I&&I(!0))},R.onload=function(){v&&_doOnReadyFunc(R)},R.onerror=function(g){_doOnComplete(S,v?R[cn]:400,_getAllResponseHeaders(R,v),v?Js:formatErrorMessageXhr(R)),b&&b(g)},R.ontimeout=function(){_doOnComplete(S,v?R[cn]:500,_getAllResponseHeaders(R,v),v?Js:formatErrorMessageXhr(R)),I&&I(!1)},R.send(f[gn]),T}function _doFetchSender(f,S,_){var T,I,b,A,P=f[Sn],O=f[gn],D=v?O:new Blob([O],{type:"application/json"}),k=new Headers,L=O[gi],F=!1,x=!1,U=f[Cn]||{},V=((T={method:Qs,body:D})[Wr]=!0,T);f.headers&&Ye(f.headers)[gi]>0&&(arrForEach(Ye(U),(function(g){k.append(g,U[g])})),V[Cn]=k),N&&v&&(V.credentials="include"),_&&(V.keepalive=!0,w+=L,v?2===f._sendReason&&(F=!0,R&&(P+=Ys)):F=!0);var B=new Request(P,V);try{B[Wr]=!0}catch(g){}if(!_&&g&&(I=createPromise((function(g,f){b=g,A=f}))),!P)return _onNoPayloadUrl(S),void(b&&b(!1));function _handleError(g){_doOnComplete(S,v?0:400,{},v?Js:g)}function _onFetchComplete(g,f,v){var _=g[cn],T=C.fetchOnComplete;T&&Le(T)?T(g,S,v||Js,f):_doOnComplete(S,_,{},v||Js)}try{doAwaitResponse(fetch(v?P:B,v?V:null),(function(g){if(_&&(w-=L,L=0),!x)if(x=!0,g.rejected)_handleError(g.reason&&g.reason[zi]),A&&A(g.reason);else{var S=g.value;try{v||S.ok?v&&!S.body?(_onFetchComplete(S,null,Js),b&&b(!0)):doAwaitResponse(S.text(),(function(g){_onFetchComplete(S,f,g.value),b&&b(!0)})):(_handleError(S.statusText),b&&b(!1))}catch(g){_handleError(dumpObj(g)),A&&A(g)}}}))}catch(g){x||(_handleError(dumpObj(g)),A&&A(g))}return F&&!x&&(x=!0,_doOnComplete(S,200,{}),b&&b(!0)),v&&!x&&f[yn]>0&&M&&M.set((function(){x||(x=!0,_doOnComplete(S,500,{}),b&&b(!0))}),f[yn]),I}function _xdrSender(g,f,_){var T=pt(),I=new XDomainRequest,b=g[gn];I.onload=function(){var S=getResponseText(I),v=C&&C.xdrOnComplete;v&&Le(v)?v(I,f,g):_doOnComplete(f,200,{},S)},I.onerror=function(){_doOnComplete(f,400,{},v?Js:formatErrorMessageXdr(I))},I.ontimeout=function(){_doOnComplete(f,500,{})},I.onprogress=function(){};var A=T&&T.location&&T.location[en]||"",P=g[Sn];if(P){if(!v&&0!==P.lastIndexOf(A,0)){var R="Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.";return _throwInternal(S,2,40,". "+R),void _onError(R,f)}var w=v?P:P[sn](/^(https?:)/,"");I.open(Qs,w),g[yn]&&(I[yn]=g[yn]),I.send(b),v&&_?M&&M.set((function(){I.send(b)}),0):I.send(b)}else _onNoPayloadUrl(f)}function _initDefaults(){w=0,f=!1,g=!1,S=null,v=null,C=null,_=null,T=null,I=!1,b=!1,A=!1,P=!1,R=!1,M=null}_initDefaults(),O[Ai]=function(g,v){S=v,f&&_throwInternal(S,1,28,"Sender is already initialized"),O.SetConfig(g),f=!0},O._getDbgPlgTargets=function(){return[f,v,_,g]},O.SetConfig=function(f){try{if(C=f.senderOnCompleteCallBack||{},_=!!f.disableCredentials,v=!!f.isOneDs,g=!!f.enableSendPromise,I=!!f.disableXhr,b=!!f.disableBeacon,A=!!f.disableBeaconSync,M=f.timeWrapper,R=!!f.addNoResponse,P=!!f.disableFetchKeepAlive,T={sendPOST:_xhrSender},v||(N=!1),_){var S=getLocation();S&&S.protocol&&"file:"===S.protocol[hi]()&&(N=!1)}return!0}catch(g){}return!1},O.getSyncFetchPayload=function(){return w},O.getSenderInst=function(g,f){return g&&g[gi]?_getSenderInterface(g,f):null},O.getFallbackInst=function(){return T},O[Yi]=function(g,f){_initDefaults()}}))}return SenderPostManager2.__ieDyn=1,SenderPostManager2}(),Zs="on",ea="attachEvent",ta="addEventListener",ia="detachEvent",na="removeEventListener",ra="events",sa="visibilitychange",aa="pagehide",oa="pageshow",la="unload",ca="beforeunload",da=createUniqueNamespace("aiEvtPageHide"),ha=createUniqueNamespace("aiEvtPageShow"),ua=/\.[\.]+/g,ga=/[\.]+$/,pa=1,ma=createElmNodeData("events"),fa=/^([^.]*)(?:\.(.+)|)/;function _normalizeNamespace(g){return g&&g[sn]?g[sn](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g,Bn):g}function _getEvtNamespace(g,f){var S;if(f){var v=Bn;Fe(f)?(v=Bn,arrForEach(f,(function(g){(g=_normalizeNamespace(g))&&("."!==g[0]&&(g="."+g),v+=g)}))):v=_normalizeNamespace(f),v&&("."!==v[0]&&(v="."+v),g=(g||Bn)+v)}var C=fa.exec(g||Bn)||[];return(S={})[on]=C[1],S.ns=(C[2]||Bn).replace(ua,".").replace(ga,Bn)[nn](".").sort().join("."),S}function _getRegisteredEvents(g,f,S){void 0===S&&(S=!0);var v=ma.get(g,ra,{},S),C=v[f];return C||(C=v[f]=[]),C}function _doDetach(g,f,S,v){g&&f&&f[on]&&(g[na]?g[na](f[on],S,v):g[ia]&&g[ia](Zs+f[on],S))}function _doAttach(g,f,S,v){var C=!1;return g&&f&&f[on]&&S&&(g[ta]?(g[ta](f[on],S,v),C=!0):g[ea]&&(g[ea](Zs+f[on],S),C=!0)),C}function _doUnregister(g,f,S,v){for(var C=f[gi];C--;){var _=f[C];_&&(S.ns&&S.ns!==_.evtName.ns||v&&!v(_)||(_doDetach(g,_.evtName,_[ln],_.capture),f[Ti](C,1)))}}function _unregisterEvents(g,f,S){if(f[on])_doUnregister(g,_getRegisteredEvents(g,f[on]),f,S);else{var v=ma.get(g,ra,{});objForEachKey(v,(function(v,C){_doUnregister(g,C,f,S)})),0===Ye(v)[gi]&&ma.kill(g,ra)}}function mergeEvtNamespace(g,f){return f?_getEvtNamespace("xx",Fe(f)?[g].concat(f):[g,f]).ns[nn]("."):g}function eventOn(g,f,S,v,C){var _;void 0===C&&(C=!1);var T=!1;if(g)try{var I=_getEvtNamespace(f,v);if((T=_doAttach(g,I,S,C))&&ma.accept(g)){var b=((_={guid:pa++,evtName:I})[ln]=S,_.capture=C,_);_getRegisteredEvents(g,I.type)[_i](b)}}catch(g){}return T}function eventOff(g,f,S,v,C){if(void 0===C&&(C=!1),g)try{var _=_getEvtNamespace(f,v),T=!1;_unregisterEvents(g,_,(function(g){return!((!_.ns||S)&&g[ln]!==S)&&(T=!0,!0)})),T||_doDetach(g,_,S,C)}catch(g){}}function addEventHandler(g,f,S){var v=!1,C=pt();C&&(v=eventOn(C,g,f,S),v=eventOn(C.body,g,f,S)||v);var _=gt();return _&&(v=eventOn(_,g,f,S)||v),v}function removeEventHandler(g,f,S){var v=pt();v&&(eventOff(v,g,f,S),eventOff(v.body,g,f,S));var C=gt();C&&eventOff(C,g,f,S)}function _addEventListeners(g,f,S,v){var C=!1;return f&&g&&g[gi]>0&&arrForEach(g,(function(g){g&&(S&&-1!==yt(S,g)||(C=addEventHandler(g,f,v)||C))})),C}function addEventListeners(g,f,S,v){var C=!1;return f&&g&&Fe(g)&&!(C=_addEventListeners(g,f,S,v))&&S&&S[gi]>0&&(C=_addEventListeners(g,f,null,v)),C}function removeEventListeners(g,f,S){g&&Fe(g)&&arrForEach(g,(function(g){g&&removeEventHandler(g,f,S)}))}function addPageUnloadEventListener(g,f,S){return addEventListeners([ca,la,aa],g,f,S)}function removePageUnloadEventListener(g,f){removeEventListeners([ca,la,aa],g,f)}function addPageHideEventListener(g,f,S){function _handlePageVisibility(f){var S=gt();g&&S&&"hidden"===S.visibilityState&&g(f)}var v=mergeEvtNamespace(da,S),C=_addEventListeners([aa],g,f,v);return f&&-1!==yt(f,sa)||(C=_addEventListeners([sa],_handlePageVisibility,f,v)||C),!C&&f&&(C=addPageHideEventListener(g,null,S)),C}function removePageHideEventListener(g,f){var S=mergeEvtNamespace(da,f);removeEventListeners([aa],g,S),removeEventListeners([sa],null,S)}function addPageShowEventListener(g,f,S){function _handlePageVisibility(f){var S=gt();g&&S&&"visible"===S.visibilityState&&g(f)}var v=mergeEvtNamespace(ha,S),C=_addEventListeners([oa],g,f,v);return!(C=_addEventListeners([sa],_handlePageVisibility,f,v)||C)&&f&&(C=addPageShowEventListener(g,null,S)),C}function removePageShowEventListener(g,f){var S=mergeEvtNamespace(ha,f);removeEventListeners([oa],g,S),removeEventListeners([sa],null,S)}var Sa,va="",Ca="https://browser.events.data.microsoft.com/OneCollector/1.0/",ya="version",Ea="properties",_a="initialize",Ta="logger",Ia="indexOf",ba="timings",Aa="pollInternalLogs",Pa="value",Ra="kind",Ma="length",wa="processTelemetryStart",Oa="1DS-Web-JS-"+"4.2.1",Da=ce.hasOwnProperty,Na=((Sa={})[0]=0,Sa[2]=6,Sa[1]=1,Sa[3]=7,Sa[4098]=6,Sa[4097]=1,Sa[4099]=7,Sa);function isValueAssigned(g){return!(g===va||isNullOrUndefined(g))}function getTenantId(g){if(g){var f=Ot(g,"-");if(f>-1)return strLeft(g,f)}return va}function isLatency(g){return!!(g&&Ue(g)&&g>=1&&g<=4)}function sanitizeProperty(g,f,S){if(!f&&!isValueAssigned(f)||"string"!=typeof g)return null;var v=typeof f;if("string"===v||"number"===v||"boolean"===v||Fe(f))f={value:f};else if("object"!==v||Da.call(f,"value")){if(isNullOrUndefined(f[Pa])||f[Pa]===va||!ke(f[Pa])&&!Ue(f[Pa])&&!Ve(f[Pa])&&!Fe(f[Pa]))return null}else f={value:S?JSON.stringify(f):f};if(Fe(f[Pa])&&!isArrayValid(f[Pa]))return null;if(!isNullOrUndefined(f[Ra])){if(Fe(f[Pa])||!isValueKind(f[Ra]))return null;f[Pa]=f[Pa].toString()}return f}function getCommonSchemaMetaData(g,f,S){var v=-1;if(!isUndefined(g))if(f>0&&(32===f?v=8192:f<=13&&(v=f<<5)),isDataType(S))-1===v&&(v=0),v|=S;else{var C=Na[getFieldValueType(g)]||-1;-1!==v&&-1!==C?v|=C:6===C&&(v=C)}return v}function getCookieValue(g,f,S){var v;return void 0===S&&(S=!0),g&&(v=g.get(f),S&&v&&decodeURIComponent&&(v=decodeURIComponent(v))),v||va}function createGuid(g){void 0===g&&(g="D");var f=newGuid();return"B"===g?f="{"+f+"}":"P"===g?f="("+f+")":"N"===g&&(f=f.replace(/-/g,va)),f}function extend(g,f,S,v,C){var _={},T=!1,I=0,b=arguments[Ma],A=arguments;for(Ve(A[0])&&(T=A[0],I++);I<b;I++){objForEachKey(A[I],(function(g,f){T&&f&&isObject(f)?Fe(f)?(_[g]=_[g]||[],arrForEach(f,(function(f,S){f&&isObject(f)?_[g][S]=extend(!0,_[g][S],f):_[g][S]=f}))):_[g]=extend(!0,_[g],f):_[g]=f}))}return _}var ka=perfNow;function isValueKind(g){return 0===g||g>0&&g<=13||32===g}function isDataType(g){return g>=0&&g<=9}function isArrayValid(g){return g[Ma]>0}function setProcessTelemetryTimings(g,f){var S=g;S[ba]=S[ba]||{},S[ba][wa]=S[ba][wa]||{},S[ba][wa][f]=ka()}function getFieldValueType(g){var f=0;if(null!=g){var S=typeof g;"string"===S?f=1:"number"===S?f=2:"boolean"===S?f=3:S===se&&(f=4,Fe(g)?(f=4096,g[Ma]>0&&(f|=getFieldValueType(g[0]))):Da.call(g,"value")&&(f=8192|getFieldValueType(g[Pa])))}return f}function isChromium(){return!!getInst("chrome")}function isGreaterThanZero(g){return g>0}var La=objDeepFreeze({endpointUrl:Ca,propertyStorageOverride:{isVal:_chkPropOverride}});function _chkPropOverride(g){return!g||g.getProperty&&g.setProperty||throwError("Invalid property storage override passed."),!0}var Fa=function(g){function AppInsightsCore3(){var f=g.call(this)||this;return dynamicProto(AppInsightsCore3,f,(function(g,f){g[_a]=function(S,v,C,_){doPerf(g,(function(){return"AppInsightsCore.initialize"}),(function(){try{f[_a](createDynamicConfig(S,La,C||g[Ta],!1).cfg,v,C,_)}catch(f){var T=g[Ta],I=dumpObj(f);-1!==I[Ia]("channels")&&(I+="\n - Channels must be provided through config.channels only!"),_throwInternal(T,1,514,"SDK Initialization Failed - no telemetry will be sent: "+I)}}),(function(){return{config:S,extensions:v,logger:C,notificationManager:_}}))},g.track=function(S){doPerf(g,(function(){return"AppInsightsCore.track"}),(function(){var v=S;if(v){v[ba]=v[ba]||{},v[ba].trackStart=ka(),isLatency(v.latency)||(v.latency=1);var C=v.ext=v.ext||{};C.sdk=C.sdk||{},C.sdk.ver=Oa;var _=v.baseData=v.baseData||{};_[Ea]=_[Ea]||{};var T=_[Ea];T[ya]=T[ya]||g.pluginVersionString||va}f.track(v)}),(function(){return{item:S}}),!S.sync)},g[Aa]=function(g){return f[Aa](g||"InternalLog")}})),f}return __extendsFn(AppInsightsCore3,g),AppInsightsCore3.__ieDyn=1,AppInsightsCore3}(Ks),xa=li({Normal:1,CostDeferred:2,RealTime:3,Immediate:4}),Ua=li({Normal:1,Critical:2}),Va="REAL_TIME",Ba="NEAR_REAL_TIME",Ha="BEST_EFFORT",$a="",ja="drop",Ga="send",qa="requeue",Wa="rspFail",za="oth",Ka="no-cache, no-store",Ja="application/x-json-stream",Ya="cache-control",Qa="content-type",Xa="kill-tokens",Za="kill-duration",eo="time-delta-millis",to="client-version",io="client-id",no="time-delta-to-apply-millis",ro="upload-time",so="apikey",ao="AuthMsaDeviceTicket",oo="WebAuthToken",lo="AuthXToken",co="NoResponseBody",ho="msfpc",uo="trace",go="user",po="allowRequestSending",mo="firstRequestSent",fo="shouldAddClockSkewHeaders",So="getClockSkewHeaderValue",vo="setClockSkew",Co="length",yo="concat",Eo="iKey",_o="count",To="events",Io="push",bo="split",Ao="splice",Po="toLowerCase",Ro="hdrs",Mo="useHdrs",wo="initialize",Oo="setTimeoutOverride",Do="clearTimeoutOverride",No="payloadPreprocessor",ko="overrideEndpointUrl",Lo="avoidOptions",Fo="disableEventTimings",xo="stringifyObjects",Uo="enableCompoundKey",Vo="disableXhrSync",Bo="disableFetchKeepAlive",Ho="addNoResponse",$o="excludeCsMetaData",jo="useSendBeacon",Go="alwaysUseXhrOverride",qo="unloadTransports",Wo="serializeOfflineEvt",zo="getOfflineRequestDetails",Ko="createPayload",Jo="createOneDSPayload",Yo="payloadBlob",Qo="headers",Xo="_thePayload",Zo="urlString",el="batches",tl="sendType",il="addHeader",nl="canSendRequest",rl="sendQueuedRequests",sl="isCompletelyIdle",al="setUnloading",ol="isTenantKilled",ll="sendSynchronousBatch",cl="_transport",dl="getWParam",hl="isBeacon",ul="timings",gl="isTeardown",pl="isSync",ml="data",fl="timeout",Sl="_sendReason",vl="setKillSwitchTenants",Cl="_backOffTransmission",yl="identifier",El="disableOptimizeObj",_l="ignoreMc1Ms0CookieProcessing",Tl="eventsLimitInMem",Il="autoFlushEventsLimit",bl="disableAutoBatchFlushLimit",Al="overrideInstrumentationKey",Pl="disableTelemetry",Rl="baseData",Ml="sendAttempt",wl="latency",Ol="sync";function _getEventMsfpc(g){var f=(g.ext||{}).intweb;return f&&isValueAssigned(f[ho])?f[ho]:null}function _getMsfpc(g){for(var f=null,S=0;null===f&&S<g[Co];S++)f=_getEventMsfpc(g[S]);return f}var Dl=function(){function EventBatch2(g,f){var S=f?[][yo](f):[],v=this,C=_getMsfpc(S);v[Eo]=function(){return g},v.Msfpc=function(){return C||$a},v[_o]=function(){return S[Co]},v[To]=function(){return S},v.addEvent=function(g){return!!g&&(S[Io](g),C||(C=_getEventMsfpc(g)),!0)},v[bo]=function(f,v){var _;if(f<S[Co]){var T=S[Co]-f;isNullOrUndefined(v)||(T=v<T?v:T),_=S[Ao](f,T),C=_getMsfpc(S)}return new EventBatch2(g,_)}}return EventBatch2.create=function(g,f){return new EventBatch2(g,f)},EventBatch2}(),Nl=function(){function ClockSkewManager2(){var g=!0,f=!0,S=!0,v="use-collector-delta",C=!1;dynamicProto(ClockSkewManager2,this,(function(_){_[po]=function(){return g},_[mo]=function(){S&&(S=!1,C||(g=!1))},_[fo]=function(){return f},_[So]=function(){return v},_[vo]=function(S){C||(S?(v=S,f=!0,C=!0):f=!1,g=!0)}}))}return ClockSkewManager2.__ieDyn=1,ClockSkewManager2}(),kl=1e3,Ll=function(){function KillSwitch2(){var g={};function _normalizeTenants(g){var f=[];return g&&arrForEach(g,(function(g){f[Io](Pt(g))})),f}dynamicProto(KillSwitch2,this,(function(f){f[vl]=function(f,S){if(f&&S)try{var v=_normalizeTenants(f[bo](","));if("this-request-only"===S)return v;for(var C=parseInt(S,10)*kl,_=0;_<v[Co];++_)g[v[_]]=utcNow()+C}catch(g){return[]}return[]},f[ol]=function(f){var S=g,v=Pt(f);return void 0!==S[v]&&S[v]>utcNow()||(delete S[v],!1)}}))}return KillSwitch2.__ieDyn=1,KillSwitch2}(),Fl=.8,xl=1.2,Ul=3e3,Vl=6e5;function retryPolicyShouldRetryForStatus(g){return!(g>=300&&g<500&&429!=g||501==g||505==g)}function retryPolicyGetMillisToBackoffForRetry(g){var f=0,S=Ul*Fl,v=Ul*xl,C=Math.floor(Math.random()*(v-S))+S;return f=Math.pow(2,g)*C,Math.min(f,Vl)}var Bl,Hl=20,$l=3984588,jl=65e3,Gl=2e6,ql=Math.min(Gl,jl),Wl="metadata",zl="f",Kl=/\./,Jl=function(){function Serializer2(g,f,S,v,C,_){var T="data",I="baseData",b="ext",A=!!v,P=!0,R=f,M={},w=!!_,O=C||getCommonSchemaMetaData;dynamicProto(Serializer2,this,(function(f){function _isReservedField(g,f){var S=M[g];return void 0===S&&(g.length>=7&&(S=Dt(g,"ext.metadata")||Dt(g,"ext.web")),M[g]=S),S}function _processPathKeys(g,f,v,C,_,T,I){objForEachKey(g,(function(g,b){var P=null;if(b||isValueAssigned(b)){var M=v,w=g,O=_,D=f;if(A&&!C&&Kl.test(g)){var N=g.split("."),k=N.length;if(k>1){O&&(O=O.slice());for(var L=0;L<k-1;L++){var F=N[L];D=D[F]=D[F]||{},M+="."+F,O&&O.push(F)}w=N[k-1]}}if(P=!(C&&_isReservedField(M))&&R&&R.handleField(M,w)?R.value(M,w,b,S):sanitizeProperty(w,b,S)){var x=P.value;if(D[w]=x,T&&T(O,w,P),I&&"object"==typeof x&&!Fe(x)){var U=O;U&&(U=U.slice()).push(w),_processPathKeys(b,x,M+"."+w,C,U,T,I)}}}}))}f.createPayload=function(g,f,S,v,C,_){return{apiKeys:[],payloadBlob:$a,overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:g,isTeardown:f,isSync:S,isBeacon:v,sendType:_,sendReason:C}},f.appendPayload=function(S,v,C){var _=S&&v&&!S.overflow;return _&&doPerf(g,(function(){return"Serializer:appendPayload"}),(function(){for(var g=v.events(),_=S.payloadBlob,T=S.numEvents,I=!1,b=[],A=[],P=S.isBeacon,R=P?jl:$l,M=P?ql:Gl,w=0,O=0;w<g.length;){var D=g[w];if(D){if(T>=C){S.overflow=v.split(w);break}var N=f.getEventBlob(D);if(N&&N.length<=M){var k=N.length;if(_.length+k>R){S.overflow=v.split(w);break}_&&(_+="\n"),_+=N,++O>Hl&&(at(_,0,1),O=0),I=!0,T++}else N?b.push(D):A.push(D),g.splice(w,1),w--}w++}if(b.length>0&&S.sizeExceed.push(Dl.create(v.iKey(),b)),A.length>0&&S.failedEvts.push(Dl.create(v.iKey(),A)),I){S.batches.push(v),S.payloadBlob=_,S.numEvents=T;var L=v.iKey();-1===yt(S.apiKeys,L)&&S.apiKeys.push(L)}}),(function(){return{payload:S,theBatch:{iKey:v.iKey(),evts:v.events()},max:C}})),_},f.getEventBlob=function(f){try{return doPerf(g,(function(){return"Serializer.getEventBlob"}),(function(){var g={};g.name=f.name,g.time=f.time,g.ver=f.ver,g.iKey="o:"+getTenantId(f.iKey);var S,v={};w||(S=function(g,f,S){_addJSONPropertyMetaData(O,v,g,f,S)});var C=f[b];C&&(g[b]=v,objForEachKey(C,(function(g,f){_processPathKeys(f,v[g]={},"ext."+g,!0,null,null,!0)})));var _=g[T]={};_.baseType=f.baseType;var A=_[I]={};return _processPathKeys(f.baseData,A,I,!1,[I],S,P),_processPathKeys(f.data,_,T,!1,[],S,P),JSON.stringify(g)}),(function(){return{item:f}}))}catch(g){return null}}}))}return Serializer2.__ieDyn=1,Serializer2}();function _addJSONPropertyMetaData(g,f,S,v,C){if(C&&f){var _=g(C.value,C.kind,C.propertyType);if(_>-1){var T=f[Wl];T||(T=f[Wl]={f:{}});var I=T[zl];if(I||(I=T[zl]={}),S)for(var b=0;b<S.length;b++){var A=S[b];I[A]||(I[A]={f:{}});var P=I[A][zl];P||(P=I[A][zl]={}),I=P}I=I[v]={},Fe(C.value)?I.a={t:_}:I.t=_}}}function createTimeoutWrapper(g,f){return{set:function(S,v){for(var C=[],_=2;_<arguments.length;_++)C[_-2]=arguments[_];return scheduleTimeoutWith([g,f],S,v,C)}}}var Yl="sendAttempt",Ql="&"+co+"=true",Xl="?cors=true&"+Qa[Po]()+"="+Ja,Zl=((Bl={})[1]=qa,Bl[100]=qa,Bl[200]="sent",Bl[8004]=ja,Bl[8003]=ja,Bl),ec={},tc={};function _addCollectorHeaderQsMapping(g,f,S){ec[g]=f,!1!==S&&(tc[f]=g)}function _hasHeader(g,f){var S=!1;if(g&&f){var v=Ye(g);if(v&&v[Co]>0)for(var C=f[Po](),_=0;_<v[Co];_++){var T=v[_];if(T&&objHasOwnProperty(f,T)&&T[Po]()===C){S=!0;break}}}return S}function _addRequestDetails(g,f,S,v){f&&S&&S[Co]>0&&(v&&ec[f]?(g[Ro][ec[f]]=S,g[Mo]=!0):g.url+="&"+f+"="+S)}function _addQueryStringParameter(g,f,S){for(var v=0;v<g[Co];v++)if(g[v].name===f)return void(g[v].value=S);g[Io]({name:f,value:S})}function _removeQueryStringParameter(g,f){for(var S=0;S<g[Co];S++)if(g[S].name===f)return void g[Ao](S,1)}_addCollectorHeaderQsMapping(ao,ao,!1),_addCollectorHeaderQsMapping(to,to),_addCollectorHeaderQsMapping(io,"Client-Id"),_addCollectorHeaderQsMapping(so,so),_addCollectorHeaderQsMapping(no,no),_addCollectorHeaderQsMapping(ro,ro),_addCollectorHeaderQsMapping(lo,lo);var ic=function(){function HttpManager2(g,f,S,v){var C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q,W,z,K,J,Y,Q,X=!1;dynamicProto(HttpManager2,this,(function(Z){_initDefaults();var ee=!0;function _getSenderInterface(g,f){try{return Q&&Q.getSenderInst(g,f)}catch(g){}return null}function _getSendPostMgrConfig(){try{return{enableSendPromise:!1,isOneDs:!0,disableCredentials:!ee,disableXhr:!1,disableBeacon:!X,disableBeaconSync:!X,disableFetchKeepAlive:H,timeWrapper:J,addNoResponse:j,senderOnCompleteCallBack:{xdrOnComplete:_xdrOncomplete,fetchOnComplete:_fetchOnComplete,xhrOnComplete:_xhrOnComplete,beaconOnRetry:_onBeaconRetry}}}catch(g){}return null}function _xdrOncomplete(g,f,S){var v=getResponseText(g);_doOnComplete(f,200,{},v),_handleCollectorResponse(v)}function _initDefaults(){var g;C=null,_=new Ll,T=!1,I=new Nl,X=!1,b=0,A=null,P=null,R=null,M=null,w=!0,O=[],D={},N=[],k=null,L=!1,F=null,x=!1,U=!1,V=g,B=g,H=g,$=g,j=g,G=[],q=g,W=g,z=[],K=!1,J=createTimeoutWrapper(),Y=!1,Q=null}function _fetchOnComplete(g,f,S,v){var handleResponse=function(g,S,v){_doOnComplete(f,g,S,v),_handleCollectorResponse(v)},C={},_=g[Qo];_&&_.forEach((function(g,f){C[f]=g})),handleResponse(g.status,C,S||$a)}function _xhrOnComplete(g,f,S){var v=getResponseText(g);_doOnComplete(f,g.status,_getAllResponseHeaders(g,!0),v),_handleCollectorResponse(v)}function _doOnComplete(g,f,S,v){try{g(f,S,v)}catch(g){_throwInternal(P,2,518,dumpObj(g))}}function _onBeaconRetry(g,f,S){var v=200,C=g[Xo],_=g[Zo]+(j?Ql:$a);try{var T=vt();if(C){var I=!!M.getPlugin("LocalStorage"),b=[],A=[];arrForEach(C[el],(function(g){if(b&&g&&g[_o]()>0)for(var f=g[To](),S=0;S<f[Co];S++){if(!T.sendBeacon(_,k.getEventBlob(f[S]))){b[Io](g[bo](S));break}A[Io](g[S])}else b[Io](g[bo](0))})),A[Co]>0&&(C.sentEvts=A),I||_sendBatchesNotification(b,8003,C[tl],!0)}else v=0}catch(g){_warnToConsole(P,"Failed to send telemetry using sendBeacon API. Ex:"+dumpObj(g)),v=0}finally{_doOnComplete(f,v,{},$a)}}function _isBeaconPayload(g){return 2===g||3===g}function _adjustSendType(g){return x&&_isBeaconPayload(g)&&(g=2),g}function _hasIdleConnection(){return!T&&b<f}function _clearQueue(){var g=N;return N=[],g}function _canSendPayload(g,f,S){var v=!1;return g&&g[Co]>0&&!T&&R[f]&&k&&(v=0!==f||_hasIdleConnection()&&(S>0||I[po]())),v}function _createDebugBatches(g){var f={};return g&&arrForEach(g,(function(g,S){f[S]={iKey:g[Eo](),evts:g[To]()}})),f}function _sendBatches(f,S,v,C,I){if(f&&0!==f[Co])if(T)_sendBatchesNotification(f,1,C);else{C=_adjustSendType(C);try{var b=f,A=0!==C;doPerf(M,(function(){return"HttpManager:_sendBatches"}),(function(T){T&&(f=f.slice(0));for(var b=[],P=null,M=ka(),w=R[C]||(A?R[1]:R[0]),O=w&&w[cl],D=$&&(x||_isBeaconPayload(C)||3===O||w._isSync&&2===O);_canSendPayload(f,C,S);){var L=f.shift();L&&L[_o]()>0&&(_.isTenantKilled(L[Eo]())?b[Io](L):(P=P||k[Ko](S,v,A,D,I,C),k.appendPayload(P,L,g)?null!==P.overflow&&(f=[P.overflow][yo](f),P.overflow=null,_doPayloadSend(P,M,ka(),I),M=ka(),P=null):(_doPayloadSend(P,M,ka(),I),M=ka(),f=[L][yo](f),P=null)))}P&&_doPayloadSend(P,M,ka(),I),f[Co]>0&&(N=f[yo](N)),_sendBatchesNotification(b,8004,C)}),(function(){return{batches:_createDebugBatches(b),retryCount:S,isTeardown:v,isSynchronous:A,sendReason:I,useSendBeacon:_isBeaconPayload(C),sendType:C}}),!A)}catch(g){_throwInternal(P,2,48,"Unexpected Exception sending batch: "+dumpObj(g))}}}function _buildRequestDetails(g,f){var S={url:C,hdrs:{},useHdrs:!1};f?(S[Ro]=extend(S[Ro],D),S.useHdrs=Ye(S.hdrs)[Co]>0):objForEachKey(D,(function(g,f){tc[g]?_addRequestDetails(S,tc[g],f,!1):(S[Ro][g]=f,S[Mo]=!0)})),_addRequestDetails(S,io,"NO_AUTH",f),_addRequestDetails(S,to,Oa,f);var v=$a;arrForEach(g.apiKeys,(function(g){v[Co]>0&&(v+=","),v+=g})),_addRequestDetails(S,so,v,f),_addRequestDetails(S,ro,utcNow().toString(),f);var _=_getMsfpc3(g);if(isValueAssigned(_)&&(S.url+="&ext.intweb.msfpc="+_),I[fo]()&&_addRequestDetails(S,no,I[So](),f),M[dl]){var T=M[dl]();T>=0&&(S.url+="&w="+T)}for(var b=0;b<O[Co];b++)S.url+="&"+O[b].name+"="+O[b].value;return S}function _setTimingValue(g,f,S){g[f]=g[f]||{},g[f][A.identifier]=S}function _doPayloadSend(g,f,S,v){if(g&&g.payloadBlob&&g.payloadBlob[Co]>0){var C=!!q,_=R[g.sendType];!_isBeaconPayload(g[tl])&&g[hl]&&2===g.sendReason&&(_=R[2]||R[3]||_);var T=U;(g.isBeacon||3===_[cl])&&(T=!1);var A=_buildRequestDetails(g,T);T=T||A[Mo];var O=ka();doPerf(M,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var R=0;R<g.batches[Co];R++)for(var D=g[el][R][To](),N=0;N<D[Co];N++){var k=D[N];if(L){var F=k[ul]=k[ul]||{};_setTimingValue(F,"sendEventStart",O),_setTimingValue(F,"serializationStart",f),_setTimingValue(F,"serializationCompleted",S)}k[Yl]>0?k[Yl]++:k[Yl]=1}_sendBatchesNotification(g[el],1e3+(v||0),g[tl],!0);var x={data:g[Yo],urlString:A.url,headers:A[Ro],_thePayload:g,_sendReason:v,timeout:V,disableXhrSync:B,disableFetchKeepAlive:H};T&&(_hasHeader(x[Qo],Ya)||(x[Qo][Ya]=Ka),_hasHeader(x[Qo],Qa)||(x[Qo][Qa]=Ja));var U=null;_&&(U=function(f){I[mo]();var onComplete=function(f,S){_retryRequestIfNeeded(f,S,g,v)},S=g[gl]||g[pl];try{_.sendPOST(f,onComplete,S),W&&W(x,f,S,g[hl])}catch(g){_warnToConsole(P,"Unexpected exception sending payload. Ex:"+dumpObj(g)),_doOnComplete(onComplete,0,{})}}),doPerf(M,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(U)if(0===g[tl]&&b++,C&&!g.isBeacon&&3!==_[cl]){var f={data:x[ml],urlString:x[Zo],headers:extend({},x[Qo]),timeout:x[fl],disableXhrSync:x[Vo],disableFetchKeepAlive:x[Bo]},S=!1;doPerf(M,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{q(f,(function(g){S=!0,w||g[Xo]||(g[Xo]=g[Xo]||x[Xo],g[Sl]=g[Sl]||x[Sl]),U(g)}),g.isSync||g[gl])}catch(g){S||U(x)}}))}else U(x)}))}),(function(){return{thePayload:g,serializationStart:f,serializationCompleted:S,sendReason:v}}),g[pl])}g.sizeExceed&&g.sizeExceed[Co]>0&&_sendBatchesNotification(g.sizeExceed,8003,g[tl]),g.failedEvts&&g.failedEvts[Co]>0&&_sendBatchesNotification(g.failedEvts,8002,g[tl])}function _addEventCompletedTimings(g,f){L&&arrForEach(g,(function(g){_setTimingValue(g[ul]=g[ul]||{},"sendEventCompleted",f)}))}function _retryRequestIfNeeded(g,f,v,C){var T=9e3,A=null,P=!1,R=!1;try{var M=!0;if(typeof g!==ae){if(f){I[vo](f[eo]);var w=f[Za]||f["kill-duration-seconds"];arrForEach(_[vl](f[Xa],w),(function(g){arrForEach(v[el],(function(f){if(f[Eo]()===g){A=A||[];var S=f[bo](0);v.numEvents-=S[_o](),A[Io](S)}}))}))}if(200==g||204==g)return void(T=200);(!retryPolicyShouldRetryForStatus(g)||v.numEvents<=0)&&(M=!1),T=9e3+g%1e3}if(M){T=100;var O=v.retryCnt;0===v[tl]&&(O<S?(P=!0,_doAction((function(){0===v[tl]&&b--,_sendBatches(v[el],O+1,v[gl],x?2:v[tl],5)}),x,retryPolicyGetMillisToBackoffForRetry(O))):(R=!0,x&&(T=8001)))}}finally{P||(I[vo](),_handleRequestFinished(v,T,C,R)),_sendBatchesNotification(A,8004,v[tl])}}function _handleRequestFinished(g,f,S,v){try{v&&A[Cl]();var C=g[el];200===f&&(C=g.sentEvts||g[el],v||g[pl]||A._clearBackOff(),_addCompleteTimings(C)),_sendBatchesNotification(C,f,g[tl],!0)}finally{0===g[tl]&&(b--,5!==S&&Z.sendQueuedRequests(g[tl],S))}}function _addCompleteTimings(g){if(L){var f=ka();arrForEach(g,(function(g){g&&g[_o]()>0&&_addEventCompletedTimings(g[To](),f)}))}}function _doAction(g,f,S){f?g():J.set(g,S)}function _getMsfpc3(g){for(var f=0;f<g.batches[Co];f++){var S=g[el][f].Msfpc();if(S)return encodeURIComponent(S)}return $a}function _handleCollectorResponse(g){var f=z;try{for(var S=0;S<f[Co];S++)try{f[S](g)}catch(g){_throwInternal(P,1,519,"Response handler failed: "+g)}if(g){var v=JSON.parse(g);isValueAssigned(v.webResult)&&isValueAssigned(v.webResult[ho])&&F.set("MSFPC",v.webResult[ho],31536e3)}}catch(g){}}function _sendBatchesNotification(g,f,S,C){if(g&&g[Co]>0&&v){var _=v[_getNotificationAction(f)];if(_){var T=0!==S;doPerf(M,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){_doAction((function(){try{_.call(v,g,f,T,S)}catch(g){_throwInternal(P,1,74,"send request notification failed: "+g)}}),C||T,0)}),(function(){return{batches:_createDebugBatches(g),reason:f,isSync:T,sendSync:C,sendType:S}}),!T)}}}function _getNotificationAction(g){var f=Zl[g];return isValueAssigned(f)||(f=za,g>=9e3&&g<=9999?f=Wa:g>=8e3&&g<=8999?f=ja:g>=1e3&&g<=1999&&(f=Ga)),f}Z[wo]=function(g,f,S){K||(M=f,F=f.getCookieMgr(),P=(A=S).diagLog(),arrAppend(G,onConfigChange(g,(function(g){var v,_=g.cfg,T=g.cfg.extensionConfig[S.identifier];J=createTimeoutWrapper(T[Oo],T[Do]),isValueAssigned(_.anonCookieName)?_addQueryStringParameter(O,"anoncknm",_.anonCookieName):_removeQueryStringParameter(O,"anoncknm"),q=T[No],W=T.payloadListener;var I=T.httpXHROverride,b=T[ko]?T[ko]:_.endpointUrl;C=b+Xl,U=!!isUndefined(T[Lo])||!T[Lo],L=!T[Fo];var A=T.valueSanitizer,D=T[xo],N=!!_[Uo];isUndefined(T[Uo])||(N=!!T[Uo]),V=T.xhrTimeout,B=!!T[Vo],H=!!T[Bo],j=!1!==T[Ho],Y=!!T[$o],f.getPlugin("LocalStorage")&&(H=!0),X=!isReactNative(),k=new Jl(M,A,D,N,getCommonSchemaMetaData,Y),isNullOrUndefined(T[jo])||(X=!!T[jo]);var F=_getSendPostMgrConfig();Q?Q.SetConfig(F):(Q=new Xs)[wo](F,P);var x=I,G=T[Go]?I:null,z=T[Go]?I:null,K=[3,2];if(!I){w=!1;var Z=[];isReactNative()?(Z=[2,1],K=[2,1,3]):Z=[1,2,3],(I=_getSenderInterface(Z=prependTransports(Z,T.transports),!1))||_warnToConsole(P,"No available transport to send events"),x=_getSenderInterface(Z,!0)}G||(G=_getSenderInterface(K=prependTransports(K,T[qo]),!0)),$=!w&&(X&&isBeaconsSupported()||!H&&isFetchSupported(!0)),(v={})[0]=I,v[1]=x||_getSenderInterface([1,2,3],!0),v[2]=G||x||_getSenderInterface([1],!0),v[3]=z||_getSenderInterface([2,3],!0)||x||_getSenderInterface([1],!0),R=v}))),K=!0)},Z.addResponseHandler=function(g){return z[Io](g),{rm:function(){var f=z.indexOf(g);f>=0&&z[Ao](f,1)}}},Z[Wo]=function(g){try{if(k)return k.getEventBlob(g)}catch(g){}return $a},Z[zo]=function(){try{return _buildRequestDetails(k&&k[Ko](0,!1,!1,!1,1,0),U)}catch(g){}return null},Z[Jo]=function(f,S){try{var v=[];arrForEach(f,(function(g){S&&(g=optimizeObject(g));var f=Dl.create(g[Eo],[g]);v[Io](f)}));for(var C=null;v[Co]>0&&k;){var _=v.shift();_&&_[_o]()>0&&(C=C||k[Ko](0,!1,!1,!1,1,0),k.appendPayload(C,_,g))}var T=_buildRequestDetails(C,U),I={data:C[Yo],urlString:T.url,headers:T[Ro],timeout:V,disableXhrSync:B,disableFetchKeepAlive:H};return U&&(_hasHeader(I[Qo],Ya)||(I[Qo][Ya]=Ka),_hasHeader(I[Qo],Qa)||(I[Qo][Qa]=Ja)),I}catch(g){}return null},Z._getDbgPlgTargets=function(){return[R[0],_,k,R]},Z[il]=function(g,f){D[g]=f},Z.removeHeader=function(g){delete D[g]},Z[nl]=function(){return _hasIdleConnection()&&I[po]()},Z[rl]=function(g,f){isUndefined(g)&&(g=0),x&&(g=_adjustSendType(g),f=2),_canSendPayload(N,g,0)&&_sendBatches(_clearQueue(),0,!1,g,f||0)},Z[sl]=function(){return!T&&0===b&&0===N[Co]},Z[al]=function(g){x=g},Z.addBatch=function(g){if(g&&g[_o]()>0){if(_.isTenantKilled(g[Eo]()))return!1;N[Io](g)}return!0},Z.teardown=function(){N[Co]>0&&_sendBatches(_clearQueue(),0,!0,2,2),arrForEach(G,(function(g){g&&g.rm&&g.rm()})),G=[]},Z.pause=function(){T=!0},Z.resume=function(){T=!1,Z[rl](0,4)},Z[ll]=function(g,f,S){g&&g[_o]()>0&&(isNullOrUndefined(f)&&(f=1),x&&(f=_adjustSendType(f),S=2),_sendBatches([g],0,!1,f,S||0))}}))}return HttpManager2.__ieDyn=1,HttpManager2}(),nc=.25,rc=500,sc=20,ac=6,oc=2,lc=4,cc=2,dc=1,hc=1e4,uc="eventsDiscarded",gc="",pc=void 0,mc=objDeepFreeze({eventsLimitInMem:{isVal:isGreaterThanZero,v:hc},immediateEventLimit:{isVal:isGreaterThanZero,v:500},autoFlushEventsLimit:{isVal:isGreaterThanZero,v:0},disableAutoBatchFlushLimit:!1,httpXHROverride:{isVal:isOverrideFn,v:pc},overrideInstrumentationKey:pc,overrideEndpointUrl:pc,disableTelemetry:!1,ignoreMc1Ms0CookieProcessing:!1,setTimeoutOverride:pc,clearTimeoutOverride:pc,payloadPreprocessor:pc,payloadListener:pc,disableEventTimings:pc,valueSanitizer:pc,stringifyObjects:pc,enableCompoundKey:pc,disableOptimizeObj:!1,transports:pc,unloadTransports:pc,useSendBeacon:pc,disableFetchKeepAlive:pc,avoidOptions:!1,xhrTimeout:pc,disableXhrSync:pc,alwaysUseXhrOverride:!1,maxEventRetryAttempts:{isVal:Ue,v:ac},maxUnloadEventRetryAttempts:{isVal:Ue,v:oc},addNoResponse:pc,excludeCsMetaData:pc});function isOverrideFn(g){return g&&g.sendPOST}var fc,Sc=function(g){function PostChannel2(){var f,S=g.call(this)||this;S.identifier="PostChannel",S.priority=1011,S.version="4.2.1";var v,C,_,T,I,b,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B,H,$,j,G,q=!1,W=[],z=!1,K=0,J=0,Y={},Q=Va;return dynamicProto(PostChannel2,S,(function(g,S){function _removeUnloadHandlers(){removePageUnloadEventListener(null,x),removePageHideEventListener(null,x),removePageShowEventListener(null,x)}function _hookWParam(g){var f=g[dl];g[dl]=function(){var S=0;return V&&(S|=2),S|f.call(g)}}function _batch(g){var f=gc;return g&&g[Co]&&arrForEach(g,(function(g){f&&(f+="\n"),f+=g})),f}function _serialize(g){var f=gc;try{_cleanEvent(g),f=P[Wo](g)}catch(g){}return f}function _handleUnloadEvents(g){"beforeunload"!==(g||pt().event).type&&(k=!0,P[al](k)),_releaseAllQueues(2,2)}function _handleShowEvents(g){k=!1,P[al](k)}function _cleanEvent(g){g.ext&&g.ext[uo]&&delete g.ext[uo],g.ext&&g.ext[go]&&g.ext[go].id&&delete g.ext[go].id,N&&(g.ext=optimizeObject(g.ext),g[Rl]&&(g[Rl]=optimizeObject(g[Rl])),g[ml]&&(g[ml]=optimizeObject(g[ml])))}function _addEventToQueues(g,f){if(g[Ml]||(g[Ml]=0),g[wl]||(g[wl]=1),_cleanEvent(g),g[Ol])if(b||z)g[wl]=3,g[Ol]=!1;else if(P)return N&&(g=optimizeObject(g)),void P[ll](Dl.create(g[Eo],[g]),!0===g[Ol]?1:g[Ol],3);var S=g[wl],v=J,T=_;4===S&&(v=K,T=C);var I=!1;if(v<T)I=!_addEventToProperQueue(g,f);else{var A=1,R=sc;4===S&&(A=4,R=1),I=!0,_dropEventWithLatencyOrLess(g[Eo],g[wl],A,R)&&(I=!_addEventToProperQueue(g,f))}I&&_notifyEvents(uc,[g],di.QueueFull)}function _sendEventsForLatencyAndAbove(g,f,S){var v=_queueBatches(g,f,S);return P[rl](f,S),v}function _hasEvents(){return J>0}function _scheduleTimer(){if(O>=0&&_queueBatches(O,0,D)&&P[rl](0,D),K>0&&!I&&!z){var g=Y[Q][2];g>=0&&(I=_createTimer((function(){I=null,_sendEventsForLatencyAndAbove(4,0,1),_scheduleTimer()}),g))}var f=Y[Q][1];!T&&!v&&f>=0&&!z&&(_hasEvents()?T=_createTimer((function(){T=null,_sendEventsForLatencyAndAbove(0===A?3:1,0,1),A++,A%=2,_scheduleTimer()}),f):A=0)}function _initDefaults(){f=null,q=!1,W=[],v=null,z=!1,K=0,C=500,J=0,_=hc,Y={},Q=Va,T=null,I=null,b=0,A=0,R={},M=0,$=!1,w=0,O=-1,D=null,N=!0,k=!1,L=ac,F=oc,x=null,j=null,G=!1,U=createTimeoutWrapper(),P=new ic(rc,cc,dc,{requeue:_requeueEvents,send:_sendingEvent,sent:_eventsSentEvent,drop:_eventsDropped,rspFail:_eventsResponseFail,oth:_otherEvent}),_initializeProfiles(),_clearQueues(),_setAutoLimits()}function _createTimer(g,f){0===f&&b&&(f=1);var S=1e3;return b&&(S=retryPolicyGetMillisToBackoffForRetry(b-1)),U.set(g,f*S)}function _clearScheduledTimer(){return null!==T&&(T.cancel(),T=null,A=0,!0)}function _releaseAllQueues(g,f){_clearScheduledTimer(),v&&(v.cancel(),v=null),z||_sendEventsForLatencyAndAbove(1,g,f)}function _clearQueues(){R[4]={batches:[],iKeyMap:{}},R[3]={batches:[],iKeyMap:{}},R[2]={batches:[],iKeyMap:{}},R[1]={batches:[],iKeyMap:{}}}function _getEventBatch(g,f,S){var v=R[f];v||(v=R[f=1]);var C=v.iKeyMap[g];return!C&&S&&(C=Dl.create(g),v.batches[Io](C),v.iKeyMap[g]=C),C}function _performAutoFlush(f,S){P[nl]()&&!b&&(M>0&&J>M&&(S=!0),S&&null==v&&g.flush(f,(function(){}),20))}function _addEventToProperQueue(g,f){N&&(g=optimizeObject(g));var S=g[wl],v=_getEventBatch(g[Eo],S,!0);return!!v.addEvent(g)&&(4!==S?(J++,f&&0===g[Ml]&&_performAutoFlush(!g.sync,w>0&&v[_o]()>=w)):K++,!0)}function _dropEventWithLatencyOrLess(g,f,S,v){for(;S<=f;){var C=_getEventBatch(g,f,!0);if(C&&C[_o]()>0){var _=C[bo](0,v),T=_[_o]();if(T>0)return 4===S?K-=T:J-=T,_notifyBatchEvents(uc,[_],di.QueueFull),!0}S++}return _resetQueueCounts(),!1}function _resetQueueCounts(){for(var g=0,f=0,_loop_1=function(S){var v=R[S];v&&v[el]&&arrForEach(v[el],(function(v){4===S?g+=v[_o]():f+=v[_o]()}))},S=1;S<=4;S++)_loop_1(S);J=f,K=g}function _queueBatches(f,S,v){var C=!1,_=0===S;return!_||P[nl]()?doPerf(g.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var g=[],S=4;S>=f;){var v=R[S];v&&v.batches&&v.batches[Co]>0&&(arrForEach(v[el],(function(f){P.addBatch(f)?C=C||f&&f[_o]()>0:g=g[yo](f[To]()),4===S?K-=f[_o]():J-=f[_o]()})),v[el]=[],v.iKeyMap={}),S--}g[Co]>0&&_notifyEvents(uc,g,di.KillSwitch),C&&O>=f&&(O=-1,D=0)}),(function(){return{latency:f,sendType:S,sendReason:v}}),!_):(O=O>=0?Math.min(O,f):f,D=Math.max(D,v)),C}function _flushImpl(g,f){_sendEventsForLatencyAndAbove(1,0,f),_resetQueueCounts(),_waitForIdleManager((function(){g&&g(),W[Co]>0?v=_createTimer((function(){v=null,_flushImpl(W.shift(),f)}),0):(v=null,_scheduleTimer())}))}function _waitForIdleManager(g){P[sl]()?g():v=_createTimer((function(){v=null,_waitForIdleManager(g)}),nc)}function _resetTransmitProfiles(){_clearScheduledTimer(),_initializeProfiles(),Q=Va,_scheduleTimer()}function _initializeProfiles(){(Y={})[Va]=[2,1,0],Y[Ba]=[6,3,0],Y[Ha]=[18,9,0]}function _requeueEvents(f,S){var v=[],C=L;k&&(C=F),arrForEach(f,(function(f){f&&f[_o]()>0&&arrForEach(f[To](),(function(f){f&&(f[Ol]&&(f[wl]=4,f[Ol]=!1),f[Ml]<C?(setProcessTelemetryTimings(f,g[yl]),_addEventToQueues(f,!1)):v[Io](f))}))})),v[Co]>0&&_notifyEvents(uc,v,di.NonRetryableStatus),k&&_releaseAllQueues(2,2)}function _callNotification(f,S){var v=H||{},C=v[f];if(C)try{C.apply(v,S)}catch(S){_throwInternal(g.diagLog(),1,74,f+" notification failed: "+S)}}function _notifyEvents(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];f&&f[Co]>0&&_callNotification(g,[f][yo](S))}function _notifyBatchEvents(g,f){for(var S=[],v=2;v<arguments.length;v++)S[v-2]=arguments[v];f&&f[Co]>0&&arrForEach(f,(function(f){f&&f[_o]()>0&&_callNotification(g,[f.events()][yo](S))}))}function _sendingEvent(g,f,S){g&&g[Co]>0&&_callNotification("eventsSendRequest",[f>=1e3&&f<=1999?f-1e3:0,!0!==S])}function _eventsSentEvent(g,f){_notifyBatchEvents("eventsSent",g,f),_scheduleTimer()}function _eventsDropped(g,f){_notifyBatchEvents(uc,g,f>=8e3&&f<=8999?f-8e3:di.Unknown)}function _eventsResponseFail(g){_notifyBatchEvents(uc,g,di.NonRetryableStatus),_scheduleTimer()}function _otherEvent(g,f){_notifyBatchEvents(uc,g,di.Unknown),_scheduleTimer()}function _setAutoLimits(){w=B?0:Math.max(rc*(cc+1),_/6)}_initDefaults(),g._getDbgPlgTargets=function(){return[P,f]},g[wo]=function(v,T,I){doPerf(T,(function(){return"PostChannel:initialize"}),(function(){S[wo](v,T,I),H=T.getNotifyMgr();try{x=mergeEvtNamespace(createUniqueNamespace(g[yl]),T.evtNamespace&&T.evtNamespace()),g._addHook(onConfigChange(v,(function(S){var v=S.cfg,I=createProcessTelemetryContext(null,v,T);f=I.getExtCfg(g[yl],mc),U=createTimeoutWrapper(f[Oo],f[Do]),N=!f[El]&&isChromium(),V=f[_l],_hookWParam(T),_=f[Tl],C=f.immediateEventLimit,M=f[Il],L=f.maxEventRetryAttempts,F=f.maxUnloadEventRetryAttempts,B=f[bl],_setAutoLimits(),j=f[Al],G=!!f[Pl],$&&_removeUnloadHandlers();var b=v.disablePageUnloadEvents||[];$=addPageUnloadEventListener(_handleUnloadEvents,b,x),$=addPageHideEventListener(_handleUnloadEvents,b,x)||$,$=addPageShowEventListener(_handleShowEvents,v.disablePageShowEvents,x)||$}))),P[wo](v,g.core,g)}catch(f){throw g.setInitialized(!1),f}}),(function(){return{theConfig:v,core:T,extensions:I}}))},g.processTelemetry=function(f,S){setProcessTelemetryTimings(f,g[yl]),S=S||g._getTelCtx(S);var v=f;G||q||(j&&(v[Eo]=j),_addEventToQueues(v,!0),k?_releaseAllQueues(2,2):_scheduleTimer()),g.processNext(v,S)},g.getOfflineSupport=function(){try{var g=P&&P[zo]();if(P)return{getUrl:function(){return g?g.url:null},serialize:_serialize,batch:_batch,shouldProcess:function(g){return!G},createPayload:function(g){return null},createOneDSPayload:function(g){if(P[Jo])return P[Jo](g,N)}}}catch(g){}return null},g._doTeardown=function(g,f){_releaseAllQueues(2,2),q=!0,P.teardown(),_removeUnloadHandlers(),_initDefaults()},g.setEventQueueLimits=function(g,S){f[Tl]=_=isGreaterThanZero(g)?g:hc,f[Il]=M=isGreaterThanZero(S)?S:0,_setAutoLimits();var v=J>g;if(!v&&w>0)for(var C=1;!v&&C<=3;C++){var T=R[C];T&&T[el]&&arrForEach(T[el],(function(g){g&&g[_o]()>=w&&(v=!0)}))}_performAutoFlush(!0,v)},g.pause=function(){_clearScheduledTimer(),z=!0,P.pause()},g.resume=function(){z=!1,P.resume(),_scheduleTimer()},g._loadTransmitProfiles=function(g){_resetTransmitProfiles(),objForEachKey(g,(function(g,f){var S=f[Co];if(S>=2){var v=S>2?f[2]:0;if(f[Ao](0,S-2),f[1]<0&&(f[0]=-1),f[1]>0&&f[0]>0){var C=f[0]/f[1];f[0]=Math.ceil(C)*f[1]}v>=0&&f[1]>=0&&v>f[1]&&(v=f[1]),f[Io](v),Y[g]=f}}))},g.flush=function(g,f,S){var C;if(void 0===g&&(g=!0),!z)if(S=S||1,g)f||(C=createPromise((function(g){f=g}))),null==v?(_clearScheduledTimer(),_queueBatches(1,0,S),v=_createTimer((function(){v=null,_flushImpl(f,S)}),0)):W[Io](f);else{var _=_clearScheduledTimer();_sendEventsForLatencyAndAbove(1,1,S),f&&f(),_&&_scheduleTimer()}return C},g.setMsaAuthTicket=function(g){P[il](ao,g)},g.setAuthPluginHeader=function(g){P[il](oo,g)},g.removeAuthPluginHeader=function(){P.removeHeader(oo)},g.hasEvents=_hasEvents,g._setTransmitProfile=function(g){Q!==g&&void 0!==Y[g]&&(_clearScheduledTimer(),Q=g,_scheduleTimer())},proxyFunctions(g,(function(){return P}),["addResponseHandler"]),g[Cl]=function(){b<lc&&(b++,_clearScheduledTimer(),_scheduleTimer())},g._clearBackOff=function(){b&&(b=0,_clearScheduledTimer(),_scheduleTimer())}})),S}return __extendsFn(PostChannel2,g),PostChannel2.__ieDyn=1,PostChannel2}(Bs),vc="locale",Cc="ver",yc="browser",Ec="browserVer",_c="popSample",Tc="eventFlags",Ic="name",bc="serviceName",Ac=ci({UserExt:[0,"user"],DeviceExt:[1,"device"],TraceExt:[2,"trace"],WebExt:[3,"web"],AppExt:[4,"app"],OSExt:[5,"os"],SdkExt:[6,"sdk"],IntWebExt:[7,"intweb"],UtcExt:[8,"utc"],LocExt:[9,"loc"],CloudExt:[10,"cloud"],DtExt:[11,"dt"]}),Pc=ci({id:[0,"id"],ver:[1,Cc],appName:[2,Ic],locale:[3,vc],expId:[4,"expId"],env:[5,"env"]}),Rc=ci({domain:[0,"domain"],browser:[1,yc],browserVer:[2,Ec],screenRes:[3,"screenRes"],userConsent:[4,"userConsent"],consentDetails:[5,"consentDetails"]}),Mc=ci({locale:[0,vc],localId:[1,"localId"],id:[2,"id"]}),wc=ci({osName:[0,Ic],ver:[1,Cc]}),Oc=ci({ver:[0,Cc],seq:[1,"seq"],installId:[2,"installId"],epoch:[3,"epoch"]}),Dc=ci({msfpc:[0,"msfpc"],anid:[1,"anid"],serviceName:[2,bc]}),Nc=ci({popSample:[0,_c],eventFlags:[1,Tc]}),kc=ci({tz:[0,"tz"]}),Lc=ci({sessionId:[0,"sesId"]}),Fc=ci({localId:[0,"localId"],deviceClass:[1,"deviceClass"],make:[2,"make"],model:[3,"model"]}),xc=ci({role:[0,"role"],roleInstance:[1,"roleInstance"],roleVer:[2,"roleVer"]}),Uc=ci({traceId:[0,"traceID"],traceName:[1,Ic],parentId:[2,"parentID"]}),Vc=ci({traceId:[0,"traceId"],spanId:[1,"spanId"],traceFlags:[2,"traceFlags"]});function canUseLocalStorage(){return void 0===fc&&(fc=!!_getVerifiedStorageObject(0)),fc}function _getLocalStorageObject(){return canUseLocalStorage()?_getVerifiedStorageObject(0):null}function _getVerifiedStorageObject(g){var f,S,v=null;try{var C=getGlobal();if(!C)return null;S=new Date,(v=0===g?C.localStorage:C.sessionStorage)&&Le(v.setItem)&&(v.setItem(S,S),f=v.getItem(S)!==S,v.removeItem(S),f&&(v=null))}catch(g){v=null}return v}function setStorage(g,f,S){var v=_getLocalStorageObject();if(null!==v)try{return v.setItem(f,S),!0}catch(f){fc=!1,_throwInternal(g,1,504,"Browser failed write to local storage. "+f)}return!1}function getStorage(g,f){var S=_getLocalStorageObject();if(null!==S)try{return S.getItem(f)}catch(f){fc=!1,_throwInternal(g,1,503,"Browser failed read of local storage. "+f)}return null}function _getId(){return this.getId()}function _setId(g){this.setId(g)}var Bc=function(){function Session2(){dynamicProto(Session2,this,(function(g){g.setId=function(f){g.customId=f},g.getId=function(){return ke(g.customId)?g.customId:g.automaticId}}))}return Session2._staticInit=void objDefine(Session2.prototype,"id",{g:_getId,s:_setId}),Session2}(),Hc="ai_session",$c=function(){function SessionManager2(g,f,S){var v,C,_,T=safeGetLogger(g),I=safeGetCookieMgr(g);dynamicProto(SessionManager2,this,(function(g){var b=onConfigChange(f,(function(){_=f,g.config=_}));function _initializeAutomaticSession(){var f=I.get(C());if(f&&Le(f.split))_initializeAutomaticSessionWithData(f);else{var S=getStorage(T,C());S&&_initializeAutomaticSessionWithData(S)}g.automaticSession.getId()||_renew()}function _initializeAutomaticSessionWithData(f){var S=g.automaticSession,v=f.split("|");v.length>0&&S.setId(v[0]);try{if(v.length>1){var C=+v[1];S.acquisitionDate=+new Date(C),S.acquisitionDate=S.acquisitionDate>0?S.acquisitionDate:0}if(v.length>2){var _=+v[2];S.renewalDate=+new Date(_),S.renewalDate=S.renewalDate>0?S.renewalDate:0}}catch(g){_throwInternal(T,1,510,"Error parsing ai_session cookie, session will be reset: "+g)}0===S.renewalDate&&_throwInternal(T,2,517,"AI session renewal date is 0, session will be reset.")}function _renew(){var f=g.automaticSession,S=(new Date).getTime(),v=g.config.sessionAsGuid;!isUndefined(v)&&v?Ve(v)?f.setId(createGuid()):f.setId(createGuid(v)):f.setId(newId(_.idLength||22)),f.acquisitionDate=S,f.renewalDate=S,_setCookie(f.getId(),f.acquisitionDate,f.renewalDate),canUseLocalStorage()||_throwInternal(T,2,505,"Browser does not support local storage. Session durations will be inaccurate.")}function _setCookie(f,S,_){var T=S+g.config.sessionExpirationMs,b=_+g.config.sessionRenewalMs,A=new Date,P=[f,S,_];T<b?A.setTime(T):A.setTime(b);var R=g.config.cookieDomain||null;I.set(C(),P.join("|")+";expires="+A.toUTCString(),null,R),v=(new Date).getTime()}function _setStorage(g,f,S){setStorage(T,C(),[g,f,S].join("|"))}S&&S.add(b),C=function(){return g.config.namePrefix?Hc+g.config.namePrefix:Hc},g.automaticSession=new Bc,g.update=function(){g.automaticSession.getId()||_initializeAutomaticSession();var f=g.automaticSession,S=g.config,C=(new Date).getTime(),_=C-f.acquisitionDate>S.sessionExpirationMs,T=C-f.renewalDate>S.sessionRenewalMs;if(_||T)_renew();else{(!v||C-v>SessionManager2.cookieUpdateInterval)&&(f.renewalDate=C,_setCookie(f.getId(),f.acquisitionDate,f.renewalDate))}},g.backup=function(){var f=g.automaticSession;_setStorage(f.getId(),f.acquisitionDate,f.renewalDate)}}))}return SessionManager2.cookieUpdateInterval=6e4,SessionManager2}(),jc=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function _validateAppExpId(g,f){void 0===f&&(f=jc);var S=null;if(g)for(var v=g.split(","),C=0;C<v.length;C++)_isValidAppFlightId(v[C],f)&&(S?S+=","+v[C]:S=v[C]);return S}function _isValidAppFlightId(g,f){if(void 0===f&&(f=jc),!g||g.length<4)return!1;for(var S=!1,v=256,C=g.substring(0,3).toString().toUpperCase(),_=0;_<f.length;_++)if(f[_]+":"===C&&g.length<=v){S=!0;break}return S}function _getExpId(){return this.getExpId()}var Gc=function(){function Application2(g,f,S){var v,C=null,_=jc.slice(0),T="Treatments",I=null;dynamicProto(Application2,this,(function(b){if(_populateDefaults(g),hasDocument()){var A=gt().documentElement;A&&(b.locale=A.lang)}function _getMetaDataFromDOM(g){var f,S={},v=gt();if(v){f=v&&v.querySelectorAll("meta");for(var C=0;C<f.length;C++){var _=f[C];if(_.name)if(0===_.name.toLowerCase().indexOf(g))S[_.name.replace(g,"")]=_.content}}return S}function _setAppExpId(g){g!==C&&(C=_validateAppExpId(g,_))}function _readExpIdFromCookie(){return _setAppExpId(getCookieValue(v,T)),C}function _readExpIdFromCoreData(g){return _setAppExpId(g),C}function _populateDefaults(g){var C=onConfigChange(g,(function(){v=f&&f.getCookieMgr(),I=g||{},b.env=I.env||_getMetaDataFromDOM("awa-").env}));S&&S.add(C)}b.getExpId=function(){return I.expId?_readExpIdFromCoreData(I.expId):_readExpIdFromCookie()}}))}return Application2.validateAppExpId=_validateAppExpId,Application2._staticInit=void objDefine(Application2.prototype,"expId",{g:_getExpId}),Application2}(),qc=function(){function Cloud2(){}return Cloud2}(),Wc=function(){function Device2(){}return Device2}();function _getMsfpc2(){return this.getMsfpc()}function _getAnid(){return this.getAnid()}var zc=function(){function IntWeb2(g,f,S){var v;dynamicProto(IntWeb2,this,(function(C){function _populateDefaults(g){var _=onConfigChange(g,(function(){v=f&&f.getCookieMgr();var S=g||{};S.serviceName&&(C.serviceName=S.serviceName)}));S&&S.add(_)}_populateDefaults(g),C.getMsfpc=function(){return getCookieValue(v,"MSFPC")},C.getAnid=function(){return getCookieValue(v,"ANON").slice(0,34)}}))}var g;return IntWeb2._staticInit=(objDefine(g=IntWeb2.prototype,"msfpc",{g:_getMsfpc2}),void objDefine(g,"anid",{g:_getAnid})),IntWeb2}(),Kc=function(){function Loc2(){var g=(new Date).getTimezoneOffset(),f=g%60,S=(g-f)/60,v="+";S>0&&(v="-"),S=Math.abs(S),f=Math.abs(f),this.tz=v+(S<10?"0"+S:S.toString())+":"+(f<10?"0"+f:f.toString())}return Loc2}(),Jc={WIN:/(windows|win32)/i,WINRT:/ arm;/i,WINPHONE:/windows\sphone\s\d+\.\d+/i,OSX:/(macintosh|mac os x)/i,IOS:/(ipad|iphone|ipod)(?=.*like mac os x)/i,LINUX:/(linux|joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)/i,ANDROID:/android/i,CROS:/CrOS/i},Yc={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},Qc="([\\d,.]+)",Xc="([\\d,_,.]+)",Zc="Unknown",ed=[{r:Jc.WINPHONE,os:"Windows Phone"},{r:Jc.WINRT,os:"Windows RT"},{r:Jc.WIN,os:"Windows"},{r:Jc.IOS,os:"iOS"},{r:Jc.ANDROID,os:"Android"},{r:Jc.LINUX,os:"Linux"},{r:Jc.CROS,os:"Chrome OS"},{s:"x11",os:"Unix"},{s:"blackberry",os:"BlackBerry"},{s:"symbian",os:"Symbian"},{s:"nokia",os:"Nokia"},{r:Jc.OSX,os:"Mac OS X"}];function _getOsName(g){for(var f=0;f<ed.length;f++){var S=ed[f];if(S.r&&g.match(S.r))return S.os;if(S.s&&-1!==g.indexOf(S.s))return S.os}return Zc}function _getOsVersion(g,f){return"Windows"===f?_getGenericOsVersion(g,"Windows NT"):"Android"===f?_getGenericOsVersion(g,f):"Mac OS X"===f?_getMacOsxVersion(g):"iOS"===f?_getIosVersion(g):Zc}function _getGenericOsVersion(g,f){var S=g.match(new RegExp(f+" "+Qc));return S?Yc[S[1]]?Yc[S[1]]:S[1]:Zc}function _getMacOsxVersion(g){var f=g.match(new RegExp("Mac OS X "+Xc));if(f){var S=f[1].replace(/_/g,".");if(S){var v=_getDelimiter(S);return v?S.split(v)[0]:S}}return Zc}function _getIosVersion(g){var f=g.match(new RegExp("OS "+Xc));if(f){var S=f[1].replace(/_/g,".");if(S){var v=_getDelimiter(S);return v?S.split(v)[0]:S}}return Zc}function _getDelimiter(g){return g.indexOf(".")>-1?".":g.indexOf("_")>-1?"_":null}var td=function(){function OperatingSystem2(g,f){var S=this,v=null,C=null,_=null,T=null,_setSysName=function(g){_=g},_setSysVer=function(g){T=g},_getSysName=function(){return _||v},_getSysVer=function(){return T||C},I=onConfigChange(g,(function(){if((g||{}).populateOperatingSystemInfo){var f=vt()||{},S=g.userAgent||f.userAgent||"",_=(g.userAgentData||{}).platform||(f.userAgentData||{}).platform;if(S){var T=_getOsName(S.toLowerCase());v=T,C=_getOsVersion(S,T)}v&&v!==Zc||!ke(_)||(v=_)}}));f&&f.add(I),objDefine(S,"name",{s:_setSysName,g:_getSysName}),objDefine(S,"ver",{s:_setSysVer,g:_getSysVer})}return OperatingSystem2}(),id="MicrosoftApplicationsTelemetryDeviceId";function _saveData(g,f,S,v){f?f.setProperty(S,v):g.set(S,v,31536e3)}function _getData(g,f,S){return f?f.getProperty(S)||"":getCookieValue(g,S)}var nd=function(){function Sdk2(g,f,S){var v,C=0;dynamicProto(Sdk2,this,(function(_){_.seq=C,_.epoch=random32(!1).toString(),_.getSequenceId=function(){return++C};var T=onConfigChange(g,(function(g){v=f&&f.getCookieMgr();var S=g.cfg.propertyStorageOverride;if(v.isEnabled()||S){var C=_getData(v,S,id);C||(C=newGuid()),_saveData(v,S,id,C),_.installId=C}else v.purge(id)}));S&&S.add(T)}))}return Sdk2.__ieDyn=1,Sdk2}(),rd=function(){function Trace2(g,f,S,v,C){var _=this;_.traceId=f||generateW3CId();var T=onConfigChange(g,(function(){var f=g;if(f.enableDistributedTracing&&!S&&(S=generateW3CId().substring(0,16)),_.parentId=_.parentId||S,f.enableApplicationInsightsTrace&&!v){var C=getLocation();C&&C.pathname&&(v=C.pathname)}_.name=_.name||v}));C&&C.add(T)}return Trace2}(),sd="setLocalId";function _getLocalId(){return this.getLocalId()}function _setLocalId(g){this[sd](g)}var ad=function(){function User2(g,f,S,v){var C,_,T;dynamicProto(User2,this,(function(I){if(_populateDefaults(f),"undefined"!=typeof navigator){var b=navigator;I.locale=b.userLanguage||b.language}function _populateMuidFromCookie(){if(!C.hashIdentifiers&&!C.dropIdentifiers){var g=getCookieValue(T,"MUID");g&&(_="t:"+g)}return _}function _populateDefaults(f){var b=onConfigChange(f,(function(){if(T=S&&S.getCookieMgr(),C=f,_=null,T&&T.isEnabled()&&(_populateMuidFromCookie(),C.enableApplicationInsightsUser)){var v=getCookieValue(T,User2.userCookieName);if(v){var b=v.split(User2.cookieSeparator);b.length>0&&(I.id=b[0])}if(!I.id){I.id=newId(g&&!isUndefined(g.idLength)?g.idLength:22);var A=toISOString(new Date);I.accountAcquisitionDate=A;var P=[I.id,A],R=C.cookieDomain?C.cookieDomain:void 0;T.set(User2.userCookieName,P.join(User2.cookieSeparator),31536e3,R)}}}));v&&v.add(b)}I.getLocalId=function(){return _||_populateMuidFromCookie()},I[sd]=function(g){_=g}}))}return User2.cookieSeparator="|",User2.userCookieName="ai_user",User2._staticInit=void objDefine(User2.prototype,"localId",{g:_getLocalId,s:_setLocalId}),User2}(),od=1048576,ld=2097152,cd=4194304,dd=function(){function Utc2(g,f){var S=this;S.popSample=100;var v=onConfigChange(g,(function(){S.eventFlags=0,g.hashIdentifiers&&(S.eventFlags=S.eventFlags|od),g.dropIdentifiers&&(S.eventFlags=S.eventFlags|ld),g.scrubIpOnly&&(S.eventFlags=S.eventFlags|cd)}));f&&f.add(v)}return Utc2}(),hd=["Required","Analytics","SocialMedia","Advertising"],ud="([\\d,.]+)",gd="Unknown",pd="Edg/",md=[{ua:"OPR/",b:"Opera"},{ua:"PhantomJS",b:"PhantomJS"},{ua:"Edge",b:"Edge"},{ua:pd,b:"Edge"},{ua:"Electron",b:"Electron"},{ua:"Chrome",b:"Chrome"},{ua:"Trident",b:"MSIE"},{ua:"MSIE ",b:"MSIE"},{ua:"Firefox",b:"Firefox"},{ua:"Safari",b:"Safari"},{ua:"SkypeShell",b:"SkypeShell"}],fd=[{br:"Microsoft Edge",b:"Edge"},{br:"Google Chrome",b:"Chrome"},{br:"Opera",b:"Opera"}];function _userAgentContainsString(g,f){return f.indexOf(g)>-1}function _getBrandVersion(g,f){for(var S=0;S<f.length;S++)if(g==f[S].brand)return f[S].version;return null}function _getBrowserName(g){if(g)for(var f=0;f<md.length;f++){if(_userAgentContainsString(md[f].ua,g))return md[f].b}return gd}function _getBrowserVersion(g,f){return"MSIE"===f?_getIeVersion(g):_getOtherVersion(f,g)}function _getIeVersion(g){var f=g.match(new RegExp("MSIE "+ud));if(f)return f[1];var S=g.match(new RegExp("rv:"+ud));return S?S[1]:void 0}function _getOtherVersion(g,f){"Safari"===g?g="Version":"Edge"===g&&_userAgentContainsString(pd,f)&&(g="Edg");var S=f.match(new RegExp(g+"/"+ud));return S||"Opera"===g&&(S=f.match(new RegExp("OPR/"+ud)))?S[1]:gd}function _getScreenResolution(){var g={h:0,w:0},f=pt();return f&&f.screen&&(g.h=screen.height,g.w=screen.width),g}function _getUserConsent(){return this.getUserConsent()}var Sd=function(){function Web2(g,f,S){var v=safeGetCookieMgr(f),C=g||{},_=null,T=null,I=null,b=null,A=null,P=null,R=null;dynamicProto(Web2,this,(function(f){_populateDefaults(g);var M=getLocation();if(M){var w=M.hostname;w&&(f.domain="file:"===M.protocol?"local":w)}var O=_getScreenResolution();function _parseUserAgent(g,f){if(Fe(f))try{for(var S=0;S<fd.length;S++){var v=_getBrandVersion(fd[S].br,f);if(v)return A=fd[S].b,void(P=v)}}catch(g){}if(g){var C=_getBrowserName(g);A=C,P=_getBrowserVersion(g,C)}}function _setBrowser(g){I=g}function _setBrowserVer(g){b=g}function _getBrowser(){return I||A}function _getBrowserVer(){return b||P}f.screenRes=O.w+"X"+O.h,f.getUserConsent=function(){return C.userConsented||!!getCookieValue(v,C.userConsentCookieName||"MSCC")},f.getUserConsentDetails=function(){var g=null;try{var f=C.callback;if(f&&f.userConsentDetails){var S=f.userConsentDetails();if(S){g=C.disableConsentDetailsSanitize?S:{};for(var v=0;v<hd.length;v++){var _=hd[v];g[_]=S[_]||!1}}}return null!==R&&((g=g||{}).GPC_DataSharingOptIn=!!R),g?JSON.stringify(g):null}catch(g){}};var _getGpcDataSharing=function(){return R},_setGpcDataSharing=function(g){R=Ve(g)?g:null,C.gpcDataSharingOptIn=R};function _populateDefaults(g){var f=onConfigChange(g,(function(){if((C=g).populateBrowserInfo){var f=C.userAgent,S=(C.userAgentData||{}).brands;if(f!==_||S!==T){if(!f||!S||0===S.length){var v=vt();v&&(f=f||v.userAgent||"",S=S||(v.userAgentData||{}).brands)}_parseUserAgent(f,S),_=f,T=S}}R=Ve(C.gpcDataSharingOptIn)?C.gpcDataSharingOptIn:null}));S&&S.add(f)}objDefineProps(f,{userConsent:{g:f.getUserConsent},browser:{s:_setBrowser,g:_getBrowser},browserVer:{s:_setBrowserVer,g:_getBrowserVer},gpcDataSharingOptIn:{g:_getGpcDataSharing,s:_setGpcDataSharing}})}))}return Web2._staticInit=void objDefine(Web2.prototype,"userConsent",{g:_getUserConsent}),Web2}();function _applyExtValues(g,f,S,v,C){var _=f.ext[Ac[g]];if(_)try{objForEachKey(v,(function(g,f){if(ke(f)||Ue(f)||Ve(f)){var v=_[S[g]];!C&&(v||ke(v)||Ue(v)||Ve(v))&&(f=v),_[S[g]]=f}}))}catch(g){}return _}var vd,Cd=function(){function TelemetryContext2(g,f,S,v){dynamicProto(TelemetryContext2,this,(function(C){C.app=new Gc(f,S,v),C.cloud=new qc,C.user=new ad(g,f,S,v),C.os=new td(f,v),C.web=new Sd(f,S,v);var _=new nd(g,S,v),T=new zc(f,S,v),I=new dd(f,v);C.loc=new Kc,C.device=new Wc;var b=new $c(S,f,v);C.session=new Bc;var A=void 0,P=createDistributedTraceContextFromTraceCtx(new rd(f,A,A,A,v),_getTraceCtx()),R=!(f||{}).eventContainExtFields;function _getSessionId(){var g=C.session;if(g&&ke(g.customId))return g.customId;b.update();var f=b.automaticSession;if(f){var S=f.getId();S&&ke(S)&&(g.automaticId=S)}return g.automaticId}function _getTraceCtx(){var g=P;return S&&S.getTraceCtx&&(g=S.getTraceCtx(!1)||P),g}C.getTraceCtx=function(){return P},C.getSessionId=_getSessionId,C.applyApplicationContext=function(g){var f,S=C.app;_applyExtValues(4,g,Pc,((f={})[0]=S.id,f[1]=S.ver,f[2]=S.name,f[3]=S.locale,f[4]=S.getExpId(),f[5]=S.env,f),R)},C.applyUserContext=function(g){var f,S=C.user;_applyExtValues(0,g,Mc,((f={})[1]=S.getLocalId(),f[0]=S.locale,f[2]=S.id,f),R)},C.applyWebContext=function(g){var f,S=C.web;_applyExtValues(3,g,Rc,((f={})[0]=S.domain,f[1]=S.browser,f[2]=S.browserVer,f[3]=S.screenRes,f[5]=S.getUserConsentDetails(),f[4]=S.getUserConsent(),f),R)},C.applyOsContext=function(g){var f,S=C.os;_applyExtValues(5,g,wc,((f={})[0]=S.name,f[1]=S.ver,f),R)},C.applySdkContext=function(g){var f;_applyExtValues(6,g,Oc,((f={})[2]=_.installId,f[1]=_.getSequenceId(),f[3]=_.epoch,f),R)},C.applyIntWebContext=function(g){var f;_applyExtValues(7,g,Dc,((f={})[0]=T.getMsfpc(),f[1]=T.getAnid(),f[2]=T.serviceName,f),R)},C.applyUtcContext=function(g){var f,S=((f={})[0]=I.popSample,f);I.eventFlags>0&&(S[1]=I.eventFlags),_applyExtValues(8,g,Nc,S,R)},C.applyLocContext=function(g){var f;_applyExtValues(9,g,kc,((f={})[0]=C.loc.tz,f),R)},C.applySessionContext=function(g){var f;_applyExtValues(4,g,Lc,((f={})[0]=_getSessionId(),f),R)},C.applyDeviceContext=function(g){var f,S=C.device;_applyExtValues(1,g,Fc,((f={})[0]=S.localId,f[2]=S.make,f[3]=S.model,f[1]=S.deviceClass,f),R)},C.applyCloudContext=function(g){var f,S=C.cloud;_applyExtValues(10,g,xc,((f={})[0]=S.role,f[1]=S.roleInstance,f[2]=S.roleVer,f),R)},C.applyAITraceContext=function(g){var S;if(f.enableApplicationInsightsTrace){var v=_getTraceCtx();v&&_applyExtValues(2,g,Uc,((S={})[0]=v.getTraceId(),S[1]=v.getName(),S[2]=v.getSpanId(),S),!1)}},C.applyDistributedTraceContext=function(g){var f,S=_getTraceCtx();if(S){var v=((f={})[0]=S.getTraceId(),f[1]=S.getSpanId(),f),C=S.getTraceFlags();isNullOrUndefined(C)||(v[2]=C),_applyExtValues(11,g,Vc,v,!1)}}}))}return TelemetryContext2.__ieDyn=1,TelemetryContext2}();function createDistributedTraceContextFromTraceCtx(g,f){var S=g||{};return{getName:function(){return S.name},setName:function(g){f&&f.setName(g),S.name=g},getTraceId:function(){return S.traceId},setTraceId:function(g){f&&f.setTraceId(g),isValidTraceId(g)&&(S.traceId=g)},getSpanId:function(){return S.parentId},setSpanId:function(g){f&&f.setSpanId(g),isValidSpanId(g)&&(S.parentId=g)},getTraceFlags:function(){return S.traceFlags},setTraceFlags:function(g){f&&f.setTraceFlags(g),S.traceFlags=g}}}var yd=[Ac[4],Ac[0],Ac[3],Ac[5],Ac[6],Ac[7],Ac[8],Ac[9],Ac[1],Ac[2],Ac[11],Ac[10]],Ed=objDeepFreeze({populateBrowserInfo:!1,populateOperatingSystemInfo:!1,userAgent:cfgDfString(),userAgentData:cfgDfMerge({brands:vd,mobile:vd,platform:vd}),userConsentCookieName:cfgDfString(),userConsented:!1,serviceName:cfgDfString(),env:cfgDfString(),expId:cfgDfString(),sessionRenewalMs:18e5,sessionExpirationMs:864e5,sessionAsGuid:null,cookieDomain:cfgDfString(),namePrefix:cfgDfString(),enableApplicationInsightsTrace:!1,enableApplicationInsightsUser:!1,hashIdentifiers:!1,dropIdentifiers:!1,scrubIpOnly:!1,callback:cfgDfMerge({userConsentDetails:null}),gpcDataSharingOptIn:vd,idLength:22,enableDistributedTracing:!1,eventContainExtFields:!1}),_d=function(g){function PropertiesPlugin2(){var f,S,v,C=g.call(this)||this;return C.identifier="SystemPropertiesCollector",C.priority=3,C.version="4.2.1",dynamicProto(PropertiesPlugin2,C,(function(g,C){function _initDefaults(){f=null,S={}}function _populateDefaults(S){var C=g.identifier,_=g.core;g._addHook(onConfigChange(S,(function(){var g=createProcessTelemetryContext(null,S,_);v=g.getExtCfg(C,Ed)}))),f=new Cd(S,v,_,g._unloadHooks),_&&_.setTraceCtx&&_.setTraceCtx(f.getTraceCtx())}function _addPropertiesIfAbsent(g,f){g&&objForEachKey(g,(function(g,S){f[g]||(f[g]=S)}))}_initDefaults(),g.initialize=function(g,f,S){C.initialize(g,f,S),_populateDefaults(g)},g.processTelemetry=function(C,_){setProcessTelemetryTimings(C,g.identifier),_=g._getTelCtx(_);var T=C.ext=C.ext?C.ext:{};C.data=C.data?C.data:{},arrForEach(yd,(function(g){T[g]=T[g]||{}})),f&&(f.applyUtcContext(C),f.applyApplicationContext(C),f.applyUserContext(C),f.applyWebContext(C),f.applyOsContext(C),f.applySdkContext(C),f.applyIntWebContext(C),f.applyLocContext(C),f.applySessionContext(C),f.applyDeviceContext(C),v.enableApplicationInsightsTrace&&f.applyAITraceContext(C),v.enableDistributedTracing&&f.applyDistributedTraceContext(C),f.applyCloudContext(C)),arrForEach(Ye(T),(function(g){0===Ye(T[g]).length&&delete T[g]})),_addPropertiesIfAbsent(S,C.data),g.processNext(C,_)},g.getPropertiesContext=function(){return f},g.setProperty=function(g,f){S[g]=f},g._doTeardown=function(g,S){var v=(g||{}).core();if(v&&v.getTraceCtx&&f){var C=v.getTraceCtx(!1);C&&C===f.getTraceCtx()&&v.setTraceCtx(null)}_initDefaults()},g._getDbgPlgTargets=function(){return[v]}})),C}return __extendsFn(PropertiesPlugin2,g),PropertiesPlugin2.__ieDyn=1,PropertiesPlugin2}(Bs),Td=function(){function BaseContext2(g){this._setOverride=function(f,S){g.setOverride(f,S)},this._getOverride=function(f){return g.getOverride(f)}}return BaseContext2}(),Id=function(g){function ApplicationContext2(f,S,v){var C=g.call(this,f)||this,_=C;_.setId=function(g){_._setOverride(Pc.id,g)},_.getId=function(){return _._getOverride(Pc.id)},_.setVer=function(g){_._setOverride(Pc.ver,g)},_.getVer=function(){return _._getOverride(Pc.ver)},_.setName=function(g){_._setOverride(Pc.appName,g)},_.getName=function(){return _._getOverride(Pc.appName)},_.setLocale=function(g){_._setOverride(Pc.locale,g)},_.getLocale=function(){return _._getOverride(Pc.locale)},_.setEnv=function(g){_._setOverride(Pc.env,g)},_.getEnv=function(){return _._getOverride(Pc.env)},_.setExpId=function(g){_._setOverride(Pc.expId,Gc.validateAppExpId(g))},_.getExpId=function(){return _._getOverride(Pc.expId)};var T=onConfigChange(S,(function(){S&&(isUndefined(S.env)||_.setEnv(S.env),isNullOrUndefined(S.expId)||_.setExpId(S.expId))}));return v&&v.add(T),C}return __extendsFn(ApplicationContext2,g),ApplicationContext2}(Td),bd=function(g){function CloudContext2(f){var S=g.call(this,f)||this,v=S;return v.setRole=function(g){v._setOverride(xc.role,g)},v.getRole=function(){return v._getOverride(xc.role)},v.setRoleInstance=function(g){v._setOverride(xc.roleInstance,g)},v.getRoleInstance=function(){return v._getOverride(xc.roleInstance)},v.setRoleVer=function(g){v._setOverride(xc.roleVer,g)},v.getRoleVer=function(){return v._getOverride(xc.roleVer)},S}return __extendsFn(CloudContext2,g),CloudContext2}(Td),Ad=function(g){function DataContext2(f){var S=g.call(this,f)||this,v=S;return v.setProperty=function(g,f){v._setOverride(g,f)},v.getProperty=function(g){return v._getOverride(g)},S}return __extendsFn(DataContext2,g),DataContext2}(Td),Pd=function(g){function DeviceContext2(f){var S=g.call(this,f)||this,v=S;return v.setLocalId=function(g){v._setOverride(Fc.localId,g)},v.getLocalId=function(){return v._getOverride(Fc.localId)},v.setDeviceClass=function(g){v._setOverride(Fc.deviceClass,g)},v.getDeviceClass=function(){return v._getOverride(Fc.deviceClass)},v.setMake=function(g){v._setOverride(Fc.make,g)},v.getMake=function(){return v._getOverride(Fc.make)},v.setModel=function(g){v._setOverride(Fc.model,g)},v.getModel=function(){return v._getOverride(Fc.model)},S}return __extendsFn(DeviceContext2,g),DeviceContext2}(Td),Rd=function(g){function LocContext2(f){var S=g.call(this,f)||this,v=S;return v.setTz=function(g){v._setOverride(kc.tz,g)},v.getTz=function(){return v._getOverride(kc.tz)},S}return __extendsFn(LocContext2,g),LocContext2}(Td),Md=function(g){function OperatingSystemContext2(f,S,v){var C=g.call(this,f)||this,_=C,T=null;_.setOsName=function(g){_._setOverride(wc.osName,g)},_.getOsName=function(){return _._getOverride(wc.osName)},_.setVer=function(g){_._setOverride(wc.ver,g)},_.getVer=function(){return _._getOverride(wc.ver)};var I=onConfigChange(S,(function(){!T&&S.userAgent&&S.populateOperatingSystemInfo&&(T=new td(S,v)),T&&(_.setOsName(T.name),_.setVer(T.ver))}));return v&&v.add(I),C}return __extendsFn(OperatingSystemContext2,g),OperatingSystemContext2}(Td);function _getEventRoot(g,f){if(g)for(var S=0;S<f.length;S++){var v=f[S];isNullOrUndefined(g[v])&&(g[v]={}),g=g[v]}return g}function _setOverride(g,f,S){if(g&&f){var v=f.split("."),C=v[v.length-1];v.length>1&&(g=_getEventRoot(g,v.slice(0,-1))),isNullOrUndefined(S)?isUndefined(g[C])||delete g[C]:g[C]=S}}var wd,Od,Dd=function(){function OverrideContainer2(g){var f=this,S=[];f.setOverride=function(g,f){g&&S.push({key:g,value:f})},f.hasOverride=function(g){var f=!1;return arrForEach(S,(function(S){S.key===g&&(f=!0)})),f},f.getOverride=function(g){var f;return arrForEach(S,(function(S){S.key===g&&(f=S.value)})),f},f.applyOverrides=function(f,v){if(S.length>0)try{var C=_getEventRoot(f,g);arrForEach(S,(function(g){_setOverride(C,g.key,g.value)}))}catch(g){}}}return OverrideContainer2}(),Nd=function(g){function UserContext2(f){var S=g.call(this,f)||this,v=S;return v.setLocalId=function(g){v._setOverride(Mc.localId,g)},v.getLocalId=function(){return v._getOverride(Mc.localId)},v.setLocale=function(g){v._setOverride(Mc.locale,g)},v.getLocale=function(){return v._getOverride(Mc.locale)},v.setId=function(g){v._setOverride(Mc.id,g)},v.getId=function(){return v._getOverride(Mc.id)},S}return __extendsFn(UserContext2,g),UserContext2}(Td),kd=function(g){function WebContext2(f,S,v){var C=g.call(this,f)||this,_=C;_.setDomain=function(g){_._setOverride(Rc.domain,g)},_.getDomain=function(){return _._getOverride(Rc.domain)},_.setBrowser=function(g){_._setOverride(Rc.browser,g)},_.getBrowser=function(){return _._getOverride(Rc.browser)},_.setBrowserVer=function(g){_._setOverride(Rc.browserVer,g)},_.getBrowserVer=function(){return _._getOverride(Rc.browserVer)},_.setScreenRes=function(g){_._setOverride(Rc.screenRes,g)},_.getScreenRes=function(){return _._getOverride(Rc.screenRes)},_.setUserConsent=function(g){_._setOverride(Rc.userConsent,g)},_.getUserContext=function(){return _._getOverride(Rc.userConsent)};var T=onConfigChange(S,(function(){S&&(isUndefined(S.userConsented)||_.setUserConsent(S.userConsented))}));return v&&v.add(T),C}return __extendsFn(WebContext2,g),WebContext2}(Td),Ld="ext",Fd="data",xd=function(){function OverrideContext2(g,f,S,v){var C=this,_={};function _getContainer(g){for(var f="",S=0;S<g.length;S++)f&&(f+="_"),f+=g[S];return isUndefined(_[f])&&(_[f]=new Dd(g)),f?_[f]:null}C.data=new Ad(_getContainer([Fd])),C.app=new Id(_getContainer([Ld,Ac.AppExt]),f,v),C.user=new Nd(_getContainer([Ld,Ac.UserExt])),C.os=new Md(_getContainer([Ld,Ac.OSExt]),f,v),C.web=new kd(_getContainer([Ld,Ac.WebExt]),f,v),C.device=new Pd(_getContainer([Ld,Ac.DeviceExt])),C.loc=new Rd(_getContainer([Ld,Ac.LocExt])),C.cloud=new bd(_getContainer([Ld,Ac.CloudExt])),C.applyOverrides=function(g,f){var S=Ye(_);S&&S.length>0&&arrForEach(S,(function(S){_[S].applyOverrides(g,f)}))}}return OverrideContext2}(),Ud=void 0,Vd=objDeepFreeze({env:Ud,expId:Ud,populateOperatingSystemInfo:!1,userAgent:Ud,userAgentData:cfgDfMerge({brands:Ud,mobile:Ud,platform:Ud}),userConsented:Ud}),Bd="OverridePropertiesPlugin",Hd=function(g){function OverridePropertiesPlugin2(){var f=g.call(this)||this;f.identifier=Bd,f.priority=4,f.version="4.2.1";var S=null;return dynamicProto(OverridePropertiesPlugin2,f,(function(g,v){g.initialize=function(f,S,C){v.initialize(f,S,C),g._baseInit(f,S,C)},g.processTelemetry=function(S,v){setProcessTelemetryTimings(S,f.identifier),v=g._getTelCtx(v);var C=g.getOverrideContext();C&&C.applyOverrides(S,v),g.processNext(S,v)},g._baseInit=function(v,C,_){S=new xd(v,f._getTelCtx().getExtCfg(f.identifier,Vd),C,g._unloadHooks)},g.setProperty=function(g,f){S&&S.data.setProperty(g,f)},g.getOverrideContext=function(){return S}})),f}return __extendsFn(OverridePropertiesPlugin2,g),OverridePropertiesPlugin2.__ieDyn=1,OverridePropertiesPlugin2}(Bs),$d="_dropInst",jd=["channelConfiguration","propertyStorageOverride"];function _fixupExtensionConfig(g){if(g&&Fe(g.extensionConfig)){var f=g.extensionConfig,S={};objForEachKey(f,(function(g,f){Le(f)||Dt(g,"Symbol(")||(S[g]=f)})),g.extensionConfig=S}return g}function _copyObjProperties(g,f){if(f)for(var S=Ye(f),v=0;v<S.length;v++){var C=S[v];$e(g,C)||Dt(C,"Symbol(")||(g[C]=f[C])}}function _proxyReadonlyProperty(g,f,S){var v;return objDefine(g,f,{g:function(){return isPrimitive(S)?S:(Fe(S)?(Fe(v)||(v=[]),v.length=S.length):isObject(v)||(v={}),objForEachKey(S,(function(g,f){Dt(g,"Symbol(")||_proxyReadonlyProperty(v,g,f)})),v)}})}function _isChannel(g){return g.pause&&g.teardown&&g.flush}function _getEndpointUrl(g,f){var S=null;if(f){f.endpointUrl&&(S=f.endpointUrl);var v=(f.extensionConfig||{})[g]||{};v.overrideEndpointUrl&&(S=v.overrideEndpointUrl)}return S}var Gd=objDeepFreeze({cookieCfg:{},channelConfiguration:cfgDfMerge({}),propertyConfiguration:cfgDfMerge({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:cfgDfMerge({}),createPerfMgr:Od,loggingLevelConsole:0}),qd=objDeepFreeze({propertyConfiguration:cfgDfMerge({}),cookieCfg:cfgDfMerge({}),extensions:{rdOnly:!0,ref:!0,v:[],blkVal:!0},channels:{rdOnly:!0,ref:!0,v:[],blkVal:!0},extensionConfig:cfgDfMerge((wd={},wd[Bd]=cfgDfMerge({}),wd)),createPerfMgr:Od,loggingLevelConsole:0}),Wd=function(g){function ChildNotificationManager2(f,S){var v=g.call(this)||this;return dynamicProto(ChildNotificationManager2,v,(function(g,v){function _getEvents(g){var S=[];return g&&arrForEach(g,(function(g){g.iKey===f&&S.push(g)})),S}function _hasListeners(f){if(g[f]&&g.listeners)for(var S=0;S<g.listeners.length;S++){var v=g.listeners[S];if(v&&v[f])return!0}return!1}var C={eventsSent:function(f){if(_hasListeners("eventsSent")){var S=_getEvents(f);S.length>0&&g.eventsSent(S)}},eventsDiscarded:function(f,S){if(_hasListeners("eventsDiscarded")){var v=_getEvents(f);v.length>0&&g.eventsDiscarded(v,S)}},eventsSendRequest:function(f,S){_hasListeners("eventsSendRequest")&&g.eventsSendRequest(f,S)},perfEvent:function(f){_hasListeners("perfEvent")&&g.perfEvent(f)}};S.addNotificationListener(C)})),v}return __extendsFn(ChildNotificationManager2,g),ChildNotificationManager2.__ieDyn=1,ChildNotificationManager2}(_s),zd=function(){function ApplicationInsightsManager2(){var g,f,S,v,C,_,T,I,b,A,P,R,M,w,O=null,D=null;dynamicProto(ApplicationInsightsManager2,this,(function(N){function _initDefaults(){g=createDynamicConfig({},Gd,null),f=[],S=null,v=null,C=[],_=[],T={},I=null,b=null,A=null,R=null,M=null,w=!1,g.cfg.loggingLevelConsole=1,P=new as(g.cfg),objDefine(N,"sharedConfig",{g:function(){return w&&_initializeSharedInstance(),g.cfg}})}function _registerPlugin(f,S){var v;if(void 0===S&&(S=null),f){(_isChannel(f)?_:C).push(f);var T=f.identifier,I=g.cfg.extensionConfig;g.setDf(I,((v={})[T]={ref:!0,v:S||{}},v))}return f}function _initializeSharedChannels(){var f=g.cfg,S=f.channels,v=new Sc,C=v.identifier,_=!1;b=null,A=null,arrForEach(S,(function(g){_||arrForEach(g,(function(g){if(!Le(g)&&(_registerPlugin(g),g.identifier===C))return b=g,_=!0,-1}))})),_||(b=_registerPlugin(v,f.channelConfiguration),S.length>0?arrAppend(S[0],b):f.channels.push([b]))}function _initializeSharedExtensions(S){var v=g.cfg;f=[],I=_registerPlugin(new _d,v.propertyConfiguration),f.push(I),v.extensions&&arrForEach(v.extensions,(function(g){Le(g)||_registerPlugin(g)})),S&&arrForEach(S,(function(g){g&&!Le(g)&&f.push(_registerPlugin(g))}))}function _initializeSharedInstance(){S||(w||_throwInternal(N.diagLog(),2,520,"The Shared Manager is not yet created, the returned shared instance will be overwritten"),g.cfg.instrumentationKey=g.cfg.instrumentationKey||"_not_defined_",v=new _s,(S=new Kd(N,N.diagLog(),v)).initialize(g.cfg,f),S.isInitialized()&&(objDefineProps((g=getDynamicConfigHandler(S.config)).cfg,{channelConfiguration:{g:function(){return g.cfg.extensionConfig[b.identifier]}},propertyConfiguration:{g:function(){return g.cfg.extensionConfig[I.identifier]}}}),b&&(A=_getEndpointUrl(b.identifier,g.cfg))),O&&S.setCookieMgr(O))}function _createInstanceConfig(f,S){var v=[],C=g.cfg,_={};if(objForEachKey(C.extensionConfig,(function(g,f){g===b.identifier||g===I.identifier||Dt(g,"Symbol(")||(g!==Bd?_proxyReadonlyProperty(_,g,f):(_[g]={},_copyObjProperties(_[g],f)))})),S){S.extensions&&S.extensions.length>0&&(v=arrAppend(v,S.extensions));var T=S.extensionConfig;T&&($e(T,b.identifier)&&Ye(T).length>0&&_throwInternal(N.diagLog(),2,511,"Instances cannot override the shared Post channel configuration, the shared will be used!"),_copyObjProperties(_,T))}var A={instrumentationKey:f,channels:_createMergedChannels(S),extensions:v,extensionConfig:_};return _copyObjProperties(A,S),A}function _createMergedChannels(f){var S=g.cfg,v=[[]];return S.channels&&arrForEach(S.channels,(function(g,f){Le(g)||(v[f]=v[f]||[],v[f]=v[f].concat(g))})),f&&f.channels&&arrForEach(f.channels,(function(g,f){Le(g)||(v[f]=v[f]||[],v[f]=v[f].concat(g))})),v}function _createMergedExtensions(g){var S=[];return f&&f.length>0&&(S=S.concat(f)),g&&g.length>0&&(S=S.concat(g)),S}function _unloadInstance(g,f,S,v){var C=T[g];C&&(C.inst&&C.inst.isInitialized()?C.inst.unload(f,(function(f){S&&S(g,f)}),v):S&&S(g,{reason:50,isAsync:f,flushComplete:!1}))}_initDefaults(),N.diagLog=function(){return P||(P=new as(g.cfg)),P},N.getCookieMgr=function(){return _initializeSharedInstance(),O||S.getCookieMgr()},N.setCookieMgr=function(g){O=g,S&&S.setCookieMgr(g)},N.getPerfMgr=function(){return M||g&&g.cfg.enablePerfMgr&&(M=D||new Rs(N.getNotifyMgr())),M},N.setPerfMgr=function(g){D=g,M=g},N.create=function(f,v){w?_throwInternal(N.diagLog(),2,514,"Shared Manager has already been initialized."):(g=createDynamicConfig(_fixupExtensionConfig(f?objExtend({},f):{}),Gd,null),S=null,_initializeSharedChannels(),_initializeSharedExtensions(v),w=!0)},N.getInst=function(g){return(T[g]||{}).inst},N.newInst=function(f,C,_){var I=N.getInst(f);if(I)return _throwInternal(N.diagLog(),2,514,"Instance already exists for ["+f+"]"),I;if(_initializeSharedInstance(),S.isInitialized()){var P=_createInstanceConfig(f,C);if(b){var R=_getEndpointUrl(b.identifier,P);A&&R&&A!==R&&_throwInternal(N.diagLog(),2,511,"The endpointUrl mismatch, shared Url ["+A+"] is different from configured ["+R+"] shared will be used!")}var M=new Wd(f,v);if(I=new Kd(N,N.diagLog(),M),T[f]={iKey:f,inst:I,notifyMgr:M},I.setPerfMgr(N.getPerfMgr()),I.initialize(P,_createMergedExtensions(_)),I.isInitialized()){var w=I.config;objDefineProps(w,{propertyConfiguration:{g:function(){return w.extensionConfig[Bd]}}});try{delete w.endpointUrl,delete w.channelConfiguration,delete w.propertyStorageOverride}catch(g){_throwInternal(N.diagLog(),2,108,"Failed to remove unused defaults!")}objForEachKey(g.cfg,(function(g,f){$e(w,g)||Dt(g,"Symbol(")||_t(jd,g)||_proxyReadonlyProperty(w,g,f)}))}else _throwInternal(N.diagLog(),2,520,"Failed to initialize new instance!"),I=null,delete T[f]}return I},N.getSharedPlugin=function(g){_initializeSharedInstance();var f=null,v=S.getPlugin(g);return v&&(f=v.plugin),f},N.getPropertyManager=function(){return _initializeSharedInstance(),I},N.getPostChannel=function(){return _initializeSharedInstance(),b},N.getNotifyMgr=function(){return R||(R=new _s),R},N.unload=function(g,f,v){var C,_=Ye(T),I=_.length+1,b={reason:50,isAsync:g,flushComplete:!1};function _doUnload(g,S){0===--I&&(_initDefaults(),f&&f(S))}return g&&!f&&(C=createPromise((function(g){f=g}))),S&&(arrForEach(_,(function(f){_unloadInstance(f,g,(function(g,f){_doUnload(g,f)}),v)})),S.isInitialized()&&(S.unload(g,(function(g){_doUnload(null,b=g)}),v),S=null)),_doUnload(null,b),C},N.addUnloadHook=function(g){_initializeSharedInstance(),S.addUnloadHook(g)},N.addSharedPlugin=function(g,f,v,C){return _initializeSharedInstance(),S.addPlugin(g,f,v,C)},N.updateCfg=function(g,f){return _initializeSharedInstance(),S.updateCfg(g,f)},N.evtNamespace=function(){return _initializeSharedInstance(),S.evtNamespace()},N.addUnloadCb=function(g){_initializeSharedInstance(),S.addUnloadCb(g)},N.onCfgChange=function(g){return _initializeSharedInstance(),S.onCfgChange(g)},N[$d]=function(g){g&&T.iKey&&delete T[g]}}))}return ApplicationInsightsManager2.__ieDyn=1,ApplicationInsightsManager2}(),Kd=function(g){function ApplicationInsights3(f,S,v){var C,_=g.call(this)||this,T=f;return dynamicProto(ApplicationInsights3,_,(function(g,f){g.getSharedPropertyManager=function(){return T.getPropertyManager()},g.getSharedPostChannel=function(){return T.getPostChannel()},g.getOverridePropertyManager=function(){return C},g.initialize=function(_,T){doPerf(g,(function(){return"ApplicationInsights:initialize"}),(function(){var I=[C=new Hd];T&&(I=I.concat(T));var b=_.propertyConfiguration||{};if(_.propertyConfiguration)try{delete _.propertyConfiguration}catch(g){_.propertyConfiguration={}}_.extensionConfig=_.extensionConfig||{},_.extensionConfig[C.identifier]=b,_=createDynamicConfig(_,qd,S||g.logger,!1).cfg;try{f.initialize(_,I,S,v)}catch(f){_throwInternal(g.logger,1,514,"Failed to initialize SDK."+dumpObj(f))}}),(function(){return{config:_,extensions:T}}))},g.unload=function(S,v,C){return T[$d]&&T[$d]((g.config||{}).instrumentationKey),f.unload(S,v,C)}})),_}return __extendsFn(ApplicationInsights3,g),ApplicationInsights3.__ieDyn=1,ApplicationInsights3}(Fa),Jd=class{constructor(g=q.telemetry.tenantToken,f=q.telemetry.onedsCollectorURL,S=q.telemetry.eventsLimitInMem){this.tenantToken=g,this.onedsCollectorURL=f,this.eventsLimitInMem=S,this.DB_NAME="mdsc_vdi3_sessions",this.DB_NAME_REALTIME="mdsc_vdi3_sessions_realtime",this.DB_NAME_TERMINATED="mdsc_vdi3_sessions_terminated",this.manager=new zd,this.initManager()}sendEvent(g,f){const S=this.manager.getInst(this.tenantToken)??this.manager.newInst(this.tenantToken),v={};for(const f of Object.keys(g))v[f]={value:g[f]};const C={name:f||this.DB_NAME,data:v,latency:xa.Normal,persistence:Ua.Normal};S.track(C)}sendRealTimeEvent(g){this.sendEvent(g,this.DB_NAME_REALTIME)}sendTerminatedTelemetrEvent(g){this.sendEvent(g,this.DB_NAME_TERMINATED)}initManager(){const g={propertyConfiguration:{populateBrowserInfo:!0,populateOperatingSystemInfo:!0},channelConfiguration:{eventsLimitInMem:this.eventsLimitInMem},endpointUrl:this.onedsCollectorURL,enableCompoundKey:!0};this.manager.create(g,[])}},Yd=class{constructor(g){this.logger=g,this.realTimeTelemetryStarted=!1,this.telemetryLogger=new Jd,this.sessionStat=new Map,this.realTimeTelemetryInterval=q.telemetry.realTimeTelemetryInterval}setConfig(g,f,S,v){this.logger.log(`Setting telemetry config:\n            tenantToken: ${g?"****":"undefined"},\n            onedsCollectorURL: ${f}, \n            eventsLimitInMem: ${S}, \n            realTimeTelemetryInterval: ${v}`),this.realTimeTelemetryInterval=v??this.realTimeTelemetryInterval,this.telemetryLogger=new Jd(g,f,S)}addSession(g){this.sessionStat.has(g.id)||this.sessionStat.set(g.id,g)}getSession(g){return this.sessionStat.get(g)}sendTelemetry(g){if(!this.sessionStat.has(g))return void this.logger.log(`Invalid session if ${g}`);const f=this.sessionStat.get(g);this.telemetryLogger.sendEvent(f.getReport())}startRealtimeTelemetry(){this.realTimeTelemetryStarted||(this.realTimeTelemetryStarted=!0,this.sendRealTimeTelemetry())}stopRealtimeTelemetry(){this.realTimeTelemetryStarted=!1}sendLastGatheredTelemetry(g){if(g){const f=this.sessionStat.get(g);f&&this.telemetryLogger.sendTerminatedTelemetrEvent(f.getReport())}else this.sessionStat.forEach((g=>{this.telemetryLogger.sendTerminatedTelemetrEvent(g.getReport())}))}removeSession(g){this.sessionStat.delete(g)}clear(){this.sessionStat.clear()}sendRealTimeTelemetry(){this.realTimeTelemetryStarted&&(this.logger.info("Sending real time telemetry"),this.sessionStat.forEach((g=>{this.telemetryLogger.sendRealTimeEvent(g.getReportForRealTime())})),setTimeout((()=>{this.sendRealTimeTelemetry()}),q.telemetry.realTimeTelemetryInterval))}},Qd=class{constructor(g,f,S,v){this.id=g,this.logger=f,this.getRpcTelemetry=S,this.getTransportTelemetry=v,this.metricsMap=new Map,this.startTime=Date.now(),this.stacksCreatedAt=[],this.connectionTerminatedAt=void 0}startTimer(g){const f=this.metricsMap.get(g)??new Xd(this.logger);f.start(),this.metricsMap.has(g)||this.metricsMap.set(g,f)}stopTimer(g){this.metricsMap.get(g)?.stop()}setTsCallingVersion(g){this.tsCallingVersion=g}addStack(){arrayLimitedPush(this.stacksCreatedAt,Date.now(),10)}setConnectionTerminatedAt(){this.connectionTerminatedAt=Date.now()}},Xd=class{constructor(g){this.logger=g}start(){if(this.endTime||this.startTime)throw new Error("Already used.");this.startTime=Date.now()}stop(){this.endTime&&this.logger.error("Already stopped."),this.endTime=Date.now()}getReport(){return{startTime:this.startTime,endTime:this.endTime,duration:this.endTime&&this.startTime&&this.endTime-this.startTime||void 0}}},Zd=class{constructor(){this.onConnectionTerminatedCallbacks=new Set}onConnectionTerminated(g){this.onConnectionTerminatedCallbacks.add(g)}setChannel(g){this.channelId=g}addTransportManager(g){this.sessionInitializedAt=Date.now(),this.transportEvent?.dispose(),this.transportEvent=g.on("connectionTerminated",(g=>{this.channelId&&g!==this.channelId||(this.lastSesstionTerminatedAt=Date.now(),this.onConnectionTerminatedCallbacks.forEach((g=>g())))}))}getStat(){return{lastSesstionTerminatedAt:this.lastSesstionTerminatedAt,sessionInitializedAt:this.sessionInitializedAt}}},eh=class{constructor(g){this.remoteStackHealthCheck=g}onConnectionTerminated(g){this.remoteStackHealthCheck.onConnectionTerminated(g)}getStat(){return this.remoteStackHealthCheck.getStat()}},th=new Zd,ih=new eh(th);function shellify(g,f){return g.shellify(f)}var nh="$$marshalled",rh="$$ref",createMarshalled=(g,f)=>({[nh]:{type:g,properties:f}}),isMarshalled=g=>nh in g,isMarshalledOfType=(g,f)=>!("object"!=typeof f||null===f||!isMarshalled(f))&&f[nh].type===g,getMarshalledProperties=g=>g[nh].properties,createReferenced=g=>({[rh]:g}),isReferenced=g=>"object"==typeof g&&null!==g&&rh in g,getRefIdFromReferenced=g=>g[rh],sh=class{constructor(g){this.marshallers=g}pack(g){const f=this.findMarshaller(g);return f?createMarshalled(f.type,f.marshall(g)):g}unpack(g){const f=this.findUnmarshaller(g);return f?f.unmarshall(getMarshalledProperties(g)):g}findMarshaller(g){return this.marshallers.find((f=>f.canMarshall(g)))}findUnmarshaller(g){return this.marshallers.find((f=>f.canUnmarshall(g)))}},ah=class{constructor(g,f,S){this.logger=g,this.uniqueIdFactory=f,this.config=S,this.finalizationRegistry=new FinalizationRegistry((g=>{this.logger.info("Reference garbage collected",g),this.refIdToRef.delete(g)})),this.refIdToRef=new Map,this.refToRefId=this.config.disableWeakRefs?new Map:new WeakMap,this.shellRefs=new WeakSet}dispose(){this.refIdToRef.clear(),this.refToRefId instanceof Map&&this.refToRefId.clear()}getRefs(){return this.refIdToRef.entries()}saveRef(g,f=this.uniqueIdFactory.getNextRefId()){if(void 0!==g){if(this.hasByRef(g))return this.getRefId(g);try{return this.refIdToRef.set(f,new WeakRef(g)),this.refToRefId.set(g,f),this.finalizationRegistry.register(g,f),f}catch(f){return void this.logger.error("Error when saving a reference",g,f)}}}getRef(g){if(void 0!==g)return this.refIdToRef.get(g)?.deref()}getRefId(g){return this.refToRefId.get(g)}hasByRef(g){return this.refToRefId.has(g)}hasByRefId(g){return!!this.refIdToRef.has(g)&&void 0!==this.getRef(g)}removeByRefId(g){const f=this.refIdToRef.get(g)?.deref();this.refIdToRef.delete(g),f&&this.refToRefId.delete(f)}removeByRef(g){const f=this.refToRefId.get(g);this.refToRefId.delete(g),f&&this.refIdToRef.delete(f)}saveShellRef(g){this.shellRefs.add(g)}isShellByRef(g){return this.shellRefs.has(g)}isShellByRefId(g){const f=this.getRef(g);return void 0!==f&&this.shellRefs.has(f)}toReferenced(g){return this.hasByRef(g)?createReferenced(this.getRefId(g)):g}fromReferenced(g){return isReferenced(g)?this.getRef(getRefIdFromReferenced(g)):g}},oh=class{getNextExecutionId(){return nanoid(8)}getNextRefId(){return nanoid(10)}},lh={timeout:5e4},ch=class{constructor(g,f,S){this.logger=g,this.uniqueIdFactory=f,this.pool=new Map,this.timeout=S.timeout}setTimeout(g){this.logger.info(`timeout set to, ${g}`),this.timeout=g}create(){const g=this.uniqueIdFactory.getNextExecutionId(),{promise:f,resolve:S,reject:v}=deferWithTimeout(this.timeout,JSON.stringify("timeout"));return this.pool.set(g,[S,v]),[g,f.finally((()=>{this.logger.debug(`removing execution ${g} from pool`),this.pool.delete(g)}))]}getExecutionHandlers(g){const f=this.pool.get(g);if(!f)throw this.logger.error(`no execution with id ${g} is waiting for result.`),new Error(`no execution with id ${g} is waiting for result.`);return f}dispose(){this.pool.forEach((([,g])=>g(new Error("Transport closed")))),this.pool.clear()}},dh=class{canUnmarshall(g){return isMarshalledOfType(this.type,g)}},hh=class extends dh{constructor(g,f){super(),this.logger=g,this.referenceManager=f}ensureRefSaved(g){this.referenceManager.hasByRef(g)||(this.logger.warn("Value not saved before marshalling, saving"),this.referenceManager.saveRef(g))}ensureRefExists(g){if(!this.referenceManager.hasByRefId(g.refId)){this.logger.info("Value does not exist, creating shell");const f=this.createShellRef(g);this.referenceManager.saveRef(f,g.refId),this.referenceManager.saveShellRef(f)}}},uh=class extends hh{marshall(g){this.ensureRefSaved(g);return{refId:this.referenceManager.getRefId(g),entries:this.marshallEntries(g)}}unmarshall(g){this.ensureRefExists(g);const f=this.referenceManager.getRef(g.refId);return this.unmarshallEntries(f,g.entries),f}},gh=class extends dh{constructor(){super(...arguments),this.type="error"}marshall(g){return{message:g.message,stack:g.stack,name:g.name,cause:g.cause}}unmarshall(g){const f=new Error(g.message);return f.stack=g.stack,f.name=g.name,f.cause=g.cause,f}canMarshall(g){return g instanceof Error}},ph=class extends uh{constructor(){super(...arguments),this.type="array"}canMarshall(g){return Array.isArray(g)}createShellRef(){return new Array}marshallEntries(g){return g.map(((g,f)=>[f,this.referenceManager.toReferenced(g)]))}unmarshallEntries(g,f){g.length=0;for(const[S,v]of f)g[S]=this.referenceManager.fromReferenced(v);return g}},mh=class extends hh{constructor(g,f,S){super(g,f),this.execute=S,this.type="function"}marshall(g){return this.ensureRefSaved(g),{refId:this.referenceManager.getRefId(g)}}unmarshall(g){return this.ensureRefExists(g),this.referenceManager.getRef(g.refId)}canMarshall(g){return"function"==typeof g}createShellRef(){const g=this.execute,funfunfun=function(...f){return g(funfunfun,f,this)};return funfunfun}},tryReadProperty=(g,f,S)=>{try{return g.value??g.get?.call(f)}catch(g){return void S?.warn("Failed to read property value",g)}},fh=Object.getPrototypeOf({});function*collectDescriptors(g,f){let S=g;const{allowedObjectNames:v,deniedNames:C,deniedValues:_}=f,T=new Set(C),isNotAllowedInstance=g=>Array.from(f.deniedInstances).some((f=>g instanceof f)),I=S?v.get(S)??v.get(S.constructor):void 0;do{if(0!==I?.size){for(const f of Object.getOwnPropertyNames(S)){if(T.has(f))continue;if(I&&!I.has(f))continue;const v=Object.getOwnPropertyDescriptor(S,f),C=tryReadProperty(v,g);isNotAllowedInstance(C)||(_.has(C)||(T.add(f),yield[f,v]))}S=Reflect.getPrototypeOf(S)}else S=Reflect.getPrototypeOf(S)}while(S&&S!==fh)}var Sh=class extends hh{constructor(g,f,S){super(g,f),this.propertyCollectionConfig=S,this.type="object"}marshall(g){this.ensureRefSaved(g);const f=this.referenceManager.getRefId(g),S=Object.create(null);for(const[f,v]of collectDescriptors(g,this.propertyCollectionConfig))S[f]=this.referenceManager.toReferenced(tryReadProperty(v,g,this.logger));return{refId:f,properties:S}}unmarshall(g){const{refId:f,properties:S}=g;this.ensureRefExists(g);const v=this.referenceManager.getRef(f);if(void 0===v&&this.logger.warn("reference lost. refId=",f),void 0===S)return this.logger.info("no properties to be applied. refId=",f),v;for(const[g,f]of collectDescriptors(v,this.propertyCollectionConfig)){const v=S[g];void 0!==v&&(isReferenced(v)&&this.referenceManager.saveRef(f.value,getRefIdFromReferenced(v)))}for(const[g,f]of Object.entries(S))Reflect.defineProperty(v,g,{value:this.referenceManager.fromReferenced(f),enumerable:!0,writable:!0,configurable:!0});return v}canMarshall(g){return"object"==typeof g&&null!==g}createShellRef(){return{}}},vh=class{constructor(g,f,S,v){this.logger=g,this.referenceManager=f,this.propertyCollectionConfig=S,this.worldRootRef=v}ingestRefs(g){const f=new Set(g);f.add(this.worldRootRef);for(const[,g]of this.referenceManager.getRefs())this.referenceManager.isShellByRef(g)||f.add(g.deref());f.delete(void 0);const S=Array.from(f);if(0===S.length)return void this.logger.info("nothing to ingest");this.logger.info("ingesting references");const v=new Set;for(;S.length;){const g=S.pop();if(null!==g&&!("object"!=typeof g&&"function"!=typeof g||this.isNotAllowedByPropertyCollectionConfig(g)||v.has(g)||(v.add(g),this.referenceManager.saveRef(g),"function"==typeof g)))if(g instanceof Map)for(const[f,v]of g.entries())S.push(f,v);else if(g instanceof Set||Array.isArray(g))S.push(...g.values());else for(const[,f]of collectDescriptors(g,this.propertyCollectionConfig)){const v=tryReadProperty(f,g,this.logger);v&&S.push(v)}}}isNotAllowedByPropertyCollectionConfig(g){if(this.propertyCollectionConfig.deniedValues.has(g))return!0;for(const f of this.propertyCollectionConfig.deniedInstances)if(g instanceof f)return!0;return!1}},Ch=class{constructor(){this.requests=[],this.historyLength=100}registerStat(g){arrayLimitedPush(this.requests,g,this.historyLength)}getStats(g){let f=this.requests;return g&&(f=this.requests.filter((({timestamp:f})=>f>=g))),{requests:f,avgRtt:this.getAverage(f,"rtt"),avgRequestSize:this.getAverage(f,"requestSize"),avgResponseSize:this.getAverage(f,"responseSize"),medianRtt:this.getMedian(f,"rtt"),medianRequestSize:this.getMedian(f,"requestSize"),medianResponseSize:this.getMedian(f,"responseSize")}}clear(){this.requests=[]}getMedian(g,f){const S=g.map((g=>g[f])),v=g.length;if(0===v)return 0;const C=[...S].sort(),_=Math.floor(v/2);return v%2==0?(C[_-1]+C[_])/2:C[_]}getAverage(g,f){if(0===g.length)return 0;return g.reduce(((g,S)=>g+S[f]),0)/g.length}},yh=class{constructor(g){this.rpcStatsManager=g}getReport(g){const{requests:f,avgRtt:S,avgRequestSize:v,avgResponseSize:C,medianRtt:_,medianRequestSize:T,medianResponseSize:I}=this.rpcStatsManager.getStats(g);return{RPC_requests:JSON.stringify(f),RPC_avgRtt:S,RPC_avgRequestSize:v,RPC_avgResponseSize:C,RPC_medianRtt:_,RPC_medianRequestSize:T,RPC_medianResponseSize:I}}},Eh=class{constructor(){this.failed=!1,this.steps=new Map,this.startTime=Date.now()}startStep(g){this.steps.set(g,{start:Date.now(),end:void 0})}endStep(g){const f=this.steps.get(g);if(!f)return;const S=f.start;this.steps.set(g,{start:S,end:Date.now()})}setRequestBody(g){this.requestBody=JSON.stringify(g)}setResponseBody(g){this.responseBody=JSON.stringify(g)}markFailed(){this.failed=!0}getStat(){return{timestamp:this.startTime,rtt:Date.now()-this.startTime,requestSize:getMessageSize(this.requestBody||""),responseSize:getMessageSize(this.responseBody||""),steps:Array.from(this.steps).map((([g,{start:f,end:S}])=>({name:g,duration:S?S-f:void 0}))),failed:this.failed}}},createRequestSynchronizeStateEvent=()=>({type:"sync-state-request"}),createSynchronizeStateEvent=(g,f)=>({type:"sync-state",executionId:g,payload:{snapshot:f}}),createSynchronizeStateResultEvent=g=>({type:"sync-state-result",executionId:g}),_h=class{constructor(g,f,S,v,C){this.logger=g,this.transport=f,this.remoteExecutionStorage=S,this.snapshotManager=v,this.referenceExtractor=C,this.synchronized=new $,this.transport.addEventListener("sync-state",(g=>{this.handleSynchronizeState(g)})),this.transport.addEventListener("sync-state-result",(g=>{this.handleSynchronizeStateResult(g)})),this.transport.addEventListener("sync-state-request",(g=>{this.handleSynchronizeStateRequest(g)}))}async waitForSynchronization(){return this.logger.info("waiting for remote sync to be completed"),this.transport.dispatchEvent(createRequestSynchronizeStateEvent()),this.synchronized.promise}async synchronize(g=[]){this.logger.info("writing remote state"),this.referenceExtractor.ingestRefs(g);const f=this.snapshotManager.create(),[S,v]=this.remoteExecutionStorage.create();this.transport.dispatchEvent(createSynchronizeStateEvent(S,f)),this.logger.info(`Execution[${S}]: waiting to be resolved`),await v}handleSynchronizeState(g){this.logger.info("updating state from remote");const f=g.payload.snapshot;this.snapshotManager.apply(f),this.transport.dispatchEvent(createSynchronizeStateResultEvent(g.executionId)),this.synchronized.resolve()}handleSynchronizeStateResult(g){this.logger.info("remote state updated");const[f]=this.remoteExecutionStorage.getExecutionHandlers(g.executionId);f()}handleSynchronizeStateRequest(g){this.logger.info("received request to update remote"),this.synchronize()}},createRemoteExecuteByRefEvent=(g,f,S,v,C,_=!1)=>({type:"remote-execute-by-ref",executionId:g,queued:_,payload:{target:f,args:v,context:S,snapshot:C}}),createRemoteExecuteResultSuccessEvent=({executionId:g},f,S)=>({type:"remote-execute-result",executionId:g,payload:{result:f,snapshot:S}}),createRemoteExecuteResultErrorEvent=({executionId:g},f,S)=>({type:"remote-execute-result",executionId:g,payload:{error:f instanceof Error?f.message:f,snapshot:S}}),Th=class{constructor(g,f,S,v,C,_,T,I){this.logger=g,this.transport=f,this.remoteExecutionStorage=S,this.snapshotManager=v,this.payloadManager=C,this.referenceManager=_,this.referenceExtractor=T,this.statManager=I,this.executionTelemetry=new Map,this.transport.addEventListener("remote-execute-by-ref",(g=>{this.handleExecuteByRefRequest(g)})),this.transport.addEventListener("remote-execute-result",(g=>{this.handleExecuteResult(g)}))}async executeByRef(g,f,S){const[v,C]=this.remoteExecutionStorage.create(),_=new Eh;this.executionTelemetry.set(v,_),this.logger.info(`[${v}]: start execution by reference`);const T=this.referenceManager.saveRef(g),I=this.referenceManager.saveRef(f),b=this.referenceManager.saveRef(S);this.logger.info(`[${v}]: creating event: target[${T}]="${g.name}"; args=[${I}]; context[${b}];`),_.startStep("ReferenceUpdate"),this.referenceExtractor.ingestRefs([g,f,S]),_.endStep("ReferenceUpdate"),_.startStep("SnapshotCreated");const A=this.snapshotManager.create();_.endStep("SnapshotCreated"),this.logger.info(`[${v}]: snapshot created`);const P=createRemoteExecuteByRefEvent(v,T,b,I,A);_.setRequestBody(P),this.transport.dispatchEvent(P);try{this.logger.info(`[${v}]: waiting to be resolved`),_.startStep("RemoteExecution");const g=await C;if(_.endStep("RemoteExecution"),this.logger.info(`[${v}]: remote execution resolved`),void 0===g)return void this.logger.info(`[${v}]: skip unpacking, as response is undefined`);_.startStep("ReponseUnpack");const f=this.payloadManager.unpack(g);return _.endStep("ReponseUnpack"),this.logger.info(`[${v}]: response unpacked`),f}catch(g){if(_.markFailed(),g instanceof Error)throw this.logger.error(`[${v}]: internal error:`,g),g;_.startStep("ReponseUnpack");const f=this.payloadManager.unpack(g);throw _.endStep("ReponseUnpack"),this.logger.error(`[${v}]: remote error:`,f),f}finally{queueMicrotask((()=>{this.statManager.registerStat(_.getStat()),this.executionTelemetry.delete(v)}))}}async handleExecuteByRefRequest(g){const f=g.executionId,{target:S,args:v,context:C,snapshot:_}=g.payload;try{this.logger.info(`[${f}]: local execute start`),this.snapshotManager.apply(_);const T=this.referenceManager.getRef(S);if(!T)throw this.logger.error(`[${f}]: unknown local target[${S}]`),new Error("Unknown execution target");const I=this.referenceManager.getRef(C),b=this.referenceManager.getRef(v)??[];this.logger.info(`[${f}]: executing on local target[${S}]="${T.name}" with context[${C}] and arguments[${v}]`);const A=await Reflect.apply(T,I,b);this.logger.info(`[${f}]: local result:`,A),this.referenceExtractor.ingestRefs([b,I,A]),this.transport.dispatchEvent(createRemoteExecuteResultSuccessEvent(g,this.payloadManager.pack(A),this.snapshotManager.create()))}catch(S){this.logger.error(`[${f}]: local failed with error:`,S),this.referenceExtractor.ingestRefs([S]),this.transport.dispatchEvent(createRemoteExecuteResultErrorEvent(g,this.payloadManager.pack(S),this.snapshotManager.create()))}}handleExecuteResult(g){const{executionId:f,payload:S}=g;this.executionTelemetry.get(f)?.setResponseBody(S);const v=g.payload.snapshot;this.logger.info(`[${f}]: handling execution result`),this.snapshotManager.apply(v);const[C,_]=this.remoteExecutionStorage.getExecutionHandlers(f);"error"in S?_(S.error):C(S.result)}},Ih=class extends uh{constructor(){super(...arguments),this.type="map"}canMarshall(g){return g instanceof Map}createShellRef(){return new Map}marshallEntries(g){return Array.from(g.entries()).map((([g,f])=>[this.referenceManager.toReferenced(g),this.referenceManager.toReferenced(f)]))}unmarshallEntries(g,f){g.clear();for(const[S,v]of f)g.set(this.referenceManager.fromReferenced(S),this.referenceManager.fromReferenced(v));return g}},bh=class extends uh{constructor(){super(...arguments),this.type="set"}canMarshall(g){return g instanceof Set}createShellRef(){return new Set}marshallEntries(g){return Array.from(g.values()).map((g=>this.referenceManager.toReferenced(g)))}unmarshallEntries(g,f){g.clear();for(const S of f)g.add(this.referenceManager.fromReferenced(S));return g}},Ah=class{constructor(g,f,S){this.logger=g,this.referenceManager=f,this.payloadManager=S}getReferences(){const g=[];for(const[f,S]of this.referenceManager.getRefs()){const v=S.deref();void 0!==v?this.referenceManager.isShellByRef(v)||g.push([f,this.payloadManager.pack(v)]):this.logger.warn("Reference garbage collected. refId=",f)}return g}applyReferences(g){for(const[f,S]of g)this.referenceManager.saveRef(this.payloadManager.unpack(S),f);for(const[f,S]of g)this.referenceManager.saveRef(this.payloadManager.unpack(S),f)}},Ph=class extends Ah{constructor(g,f,S){super(g,f,S),this.lastSentReferences=[],this.lastRecvReferences=[]}create(){this.logger.info("creating snapshot");const g=this.getReferences();if(!this.lastSentReferences.length){this.logger.info("no previous snapshot available, creating full snapshot"),this.lastSentReferences=g;const f={"+":g};return this.logger.info("delta snapshot ready"),this.logger.debug(JSON.stringify(f)),f}this.logger.info("previous snapshot available, creating delta snapshot");const f=new Map(this.lastSentReferences),S=new Map(g),v={"-":[],"+":[],"*":[]};for(const g of new Set([...f.keys(),...S.keys()]))this.referenceManager.isShellByRefId(g)||(!f.has(g)||S.has(g)?f.has(g)||!S.has(g)?f.has(g)&&S.has(g)&&JSON.stringify(f.get(g))!==JSON.stringify(S.get(g))&&v["*"].push([g,S.get(g)]):v["+"].push([g,S.get(g)]):v["-"].push(g));return this.logger.info("delta snapshot ready"),this.logger.debug(JSON.stringify(v)),this.lastSentReferences=g,v}apply(g){this.logger.info("applying snapshot"),this.logger.debug(JSON.stringify(g)),this.lastRecvReferences.length?this.logger.info("previous snapshot available, applying delta to it"):this.logger.info("no previous snapshot available, delta should contain full snapshot");const f=new Map(this.lastRecvReferences);for(const S of g["-"]??[])this.referenceManager.removeByRefId(S),f.delete(S);for(const[S,v]of g["+"]??[])f.set(S,v);for(const[S,v]of g["*"]??[])f.set(S,v);this.lastRecvReferences=Array.from(f.entries()),this.logger.info("delta snapshot ready"),this.logger.debug(JSON.stringify(this.lastRecvReferences)),this.applyReferences(this.lastRecvReferences)}},Rh=class extends dh{constructor(g,f){super(),this.type=g,this.value=f}marshall(g){}unmarshall(){return this.value}canMarshall(g){return g===this.value}},isBigTypedArray=g=>"BigInt64Array"===g[Symbol.toStringTag]||"BigUint64Array"===g[Symbol.toStringTag],Mh=class _TypedArrayMarshaller extends hh{constructor(){super(...arguments),this.type="typedArray"}marshall(g){this.ensureRefSaved(g);return{refId:this.referenceManager.getRefId(g),type:g[Symbol.toStringTag],values:isBigTypedArray(g)?Array.from(g).map((g=>g.toString())):Array.from(g),byteOffset:g.byteOffset,bufferType:g.buffer[Symbol.toStringTag],bufferByteLength:g.buffer.byteLength}}unmarshall(g){this.ensureRefExists(g);const f=this.referenceManager.getRef(g.refId),S=isBigTypedArray(f)?BigInt:Number;for(const[v,C]of g.values.entries())f[v]=S(C);return f}createShellRef(g){if(!_TypedArrayMarshaller.TYPED_ARRAY_CONSTRUCTOR.has(g.type))throw new Error(`Unknown typed array type: ${g.type}`);const f=_TypedArrayMarshaller.TYPED_ARRAY_CONSTRUCTOR.get(g.type);return"SharedArrayBuffer"===g.bufferType&&this.logger.error("SharedArrayBuffers are mostly disabled, consider using ArrayBuffer instead"),new f(new ArrayBuffer(g.bufferByteLength),g.byteOffset)}canMarshall(g){if("object"!=typeof g||null===g)return!1;if(Symbol.toStringTag in g){const f=g[Symbol.toStringTag];return"string"==typeof f&&_TypedArrayMarshaller.TYPED_ARRAY_CONSTRUCTOR.has(f)}return!1}};Mh.TYPED_ARRAY_CONSTRUCTOR=new Map([["Int8Array",Int8Array],["Uint8Array",Uint8Array],["Uint8ClampedArray",Uint8ClampedArray],["Int16Array",Int16Array],["Uint16Array",Uint16Array],["Int32Array",Int32Array],["Uint32Array",Uint32Array],["Float32Array",Float32Array],["Float64Array",Float64Array],["BigInt64Array",BigInt64Array],["BigUint64Array",BigUint64Array]]);var wh=Mh,Oh={allowedObjectNames:new WeakMap,deniedNames:new Set(["constructor","prototype","arguments","caller"]),deniedValues:new Set([globalThis,document,null]),deniedInstances:new Set([Boolean,Number,String,Date,RegExp,EventTarget,HTMLElement])},Dh=class{constructor(g,f,S,v=new oh){this.transport=g,this.logger=f,this.config=S,this.uniqueIdFactory=v,this.statManager=new Ch,this.rpcTelemetryProvider=new yh(this.statManager),this.propertyCollectionConfig={...Oh,...this.config?.propertyCollectionConfig},this.referenceManager=new ah(this.logger.createChild("ReferenceManager"),this.uniqueIdFactory,{disableWeakRefs:this.config?.disableWeakRefs}),this.referenceExtractor=new vh(this.logger.createChild("ReferenceExtractor"),this.referenceManager,this.propertyCollectionConfig,this.config?.worldRootRef),this.payloadManager=new sh([new gh,new Rh("globalThis",globalThis),new Rh("document",document),new Ih(this.logger.createChild("MapMarshaller"),this.referenceManager),new bh(this.logger.createChild("SetMarshaller"),this.referenceManager),new ph(this.logger.createChild("ArrayMarshaller"),this.referenceManager),new wh(this.logger.createChild("TypedArrayMarshaller"),this.referenceManager),new mh(this.logger.createChild("FunctionMarshaller"),this.referenceManager,((g,f,S)=>this.executeByRef(g,f,S))),new Sh(this.logger.createChild("ObjectMarshaller"),this.referenceManager,this.propertyCollectionConfig)]),this.snapshotManager=new Ph(this.logger.createChild("SnapshotManager"),this.referenceManager,this.payloadManager),this.remoteExecutionStorage=new ch(this.logger.createChild("RemoteExecutionStorage"),this.uniqueIdFactory,{...lh,timeout:this.config?.remoteExecutionTimeout??lh.timeout}),this.remoteExecutionService=new Th(this.logger.createChild("RemoteExecutionService"),this.transport,this.remoteExecutionStorage,this.snapshotManager,this.payloadManager,this.referenceManager,this.referenceExtractor,this.statManager),this.synchronizer=new _h(this.logger.createChild("StateSynchronizer"),this.transport,this.remoteExecutionStorage,this.snapshotManager,this.referenceExtractor)}get telemetryProvider(){return this.rpcTelemetryProvider}waitForSynchronization(){return this.synchronizer.waitForSynchronization()}synchronize(...g){return this.synchronizer.synchronize(g)}setRequestTimeout(g){this.remoteExecutionStorage.setTimeout(g)}getPropertyCollectionConfig(){return this.propertyCollectionConfig}saveRef(g,f){return this.referenceManager.saveRef(f,g),f}shellify(g){if("object"==typeof g){this.referenceManager.saveShellRef(g);for(const[f,S]of collectDescriptors(g,this.getPropertyCollectionConfig()))"function"==typeof S.value&&(Reflect.defineProperty(g,f,{value:new Proxy(S.value,{apply:(S,v,C)=>this.executeByRef(Reflect.get(g,f),C,v)})}),this.referenceManager.saveShellRef(Reflect.get(g,f))),S.get;return g}if("function"==typeof g){const f=new Proxy(g,{apply:(g,S,v)=>this.executeByRef(f,v,S)});return f}throw new Error("Unsupported type")}async executeByRef(g,f,S){return this.remoteExecutionService.executeByRef(g,f,S)}dispose(){this.logger.info("Disposing RPCService"),this.remoteExecutionStorage.dispose(),this.referenceManager.dispose(),this.statManager.clear()}},Nh=class extends Qd{constructor(){super(...arguments),this.namespace="Shell"}getReport(){const g=this.metricsMap.get("TimeToEstablishConnection")?.getReport();return{NameSpace:this.namespace,SessionId:this.id,TsCallingVersion:this.tsCallingVersion,Session_StartTime:this.startTime,EstablishConnection_StartTime:g?.startTime,EstablishConnection_Duration:g?.duration,...this.getRpcTelemetry(),...this.getTransportTelemetry()}}getReportForRealTime(){return{NameSpace:this.namespace,...this.getRpcTelemetry(),...this.getTransportTelemetry()}}},kh=R,Lh=M,Fh=class _TsCallingLogger{constructor(g,f,S=""){this.ulLogComponent=g,this.ulSafeComponent=f,this._getPrefix=(0,Lh.isFunction)(S)?S:()=>S,this.logComponent=kh.LogFactory.instance().component(this.ulLogComponent),kh.LogFactory.instance().declareComponentSafe(this.ulLogComponent,f)}createChild(g){const f=(0,Lh.isFunction)(g)?g:()=>g;return new _TsCallingLogger(this.ulLogComponent,this.ulSafeComponent,(()=>this._getPrefix()?`${this._getPrefix()}/${f()}`:f()))}log(...g){this._apply((g=>this.logComponent.debug2(null,g)),g)}debug(...g){this._apply((g=>this.logComponent.debug4(null,g)),g)}info(...g){this._apply((g=>this.logComponent.debug1(null,g)),g)}warn(...g){this._apply((g=>this.logComponent.warn(null,g)),g)}error(...g){this._apply((g=>this.logComponent.error(null,g)),g)}_apply(g,f=[]){this._addPrefix(f);g(f.map((g=>g instanceof DOMException?g.toString():g)).map((g=>(0,Lh.isObject)(g)?JSON.stringify(g):g)).join(", "))}_addPrefix(g){if(g&&g[0]){const f=`${this._getPrefix()} ${g[0]}`;g[0]=f}}};function getTsCallingVersion(){return"2025.03.01.41"}function getOvb(){return"cba3e05218cf5c9f3c5c1009bd560650dc7383a5"}var xh=__toESM(w()),Uh=class{constructor(){this.fallbackLogger=new Fh("RemoteStackFactory",!0),this.telemetry=new Yd(this.logger),this.healthCheck=th}async build(g){return this.callingLogger??(this.callingLogger=g.logger.createChild("RemoteStackFactory")),this.remoteStackFactory??(this.remoteStackFactory=await this.getFactory(g.vdi3Config)),this.remoteStackFactory.build(this.getRemoteStackConfig(g))}async buildBaseStack(g){return this.callingLogger??(this.callingLogger=g.logger.createChild("RemoteStackFactory")),this.remoteStackFactory??(this.remoteStackFactory=await this.getFactory(g.vdi3Config)),this.remoteStackFactory.buildBaseStack(this.getRemoteBaseStackConfig(g))}getVersion(){return{build:getTsCallingVersion(),ovb:getOvb()}}async getFactory(g){const{transport:f,telemetryConfig:S,pluginlessUrl:v,cdnUrl:C}=g;if(!f)throw new Error("transport is required for remote stack");const _=uuidv4(),T=this.logger.createChild(`Channel:${_}`);this.transportManager??(this.transportManager=new ne(f,this.logger.createChild("TransportManager"))),this.healthCheck.addTransportManager(this.transportManager),this.transportManager.on("connectionTerminated",(()=>{T.log("Connection terminated, disposing."),this.dispose()})),this.healthCheck.setChannel(_),S&&this.telemetry.setConfig(S.tenantToken,S.onedsCollectorURL,S.eventsLimitInMem,S.realTimeTelemetryInterval);const I=new Nh(_,T.createChild("Telemetry"),(()=>this.rpcSession?.telemetryProvider.getReport()),(()=>this.transportManager?.telemetryProvider.getReport()));this.telemetry.addSession(I);const b={tsCallingVersion:this.getVersion().build,channelId:_,pluginlessUrl:v,cdnUrl:C,telemetryConfig:S};T.log(`Initiating connection with payload: ${JSON.stringify(b)}`),I.startTimer("TimeToEstablishConnection"),await this.transportManager.initiateConnection(b),I.stopTimer("TimeToEstablishConnection");const A=new Dh(this.transportManager.createChannel(_),T.createChild("RPCService"),{remoteExecutionTimeout:f.config?.remoteExecutionTimeout,disableWeakRefs:!0});this.rpcSession=A,g.shellTrouter&&A.saveRef("shell-trouter",shellify(A,g.shellTrouter)),A.saveRef("remote-telemetry-provider",{getReport:async g=>({transport:this.transportManager.telemetryProvider.getReport(g),rpc:A.telemetryProvider.getReport(g)})});const P=A.saveRef("pluginless-stack",shellify(A,{build:g=>{throw new Error("Should be executed rmotely")},buildBaseStack:g=>{throw new Error("Should be executed rmotely")}}));return await A.waitForSynchronization(),this.telemetry.sendTelemetry(_),this.telemetry.startRealtimeTelemetry(),P}getRemoteStackConfig(g){const f=g.logger,{vdi3Config:{trouterSettings:S},stackType:v,...C}=g;if(!S)throw new Error("Trouter setting is required for remoteStack");const _=(0,xh.default)(C);this.removeHttpDispatcher(_),this.removeLogger(_),this.removeTrouterService(_),this.sanitizeTelemetryConfig(_.telemetryService,f),this.removeEffectConfigProvider(_.mediaAgentFactoryConfig);const T={..._,trouterSettings:S};return f.log(`RemoteStackConfig: ${JSON.stringify(T)}`),T}getRemoteBaseStackConfig(g){const f=g.logger,{vdi3Config:S,stackType:v,...C}=g,_=(0,xh.default)(C);return this.removeHttpDispatcher(_),this.removeLogger(_),this.sanitizeTelemetryConfig(_.telemetryService,f),f.log(`baseStackConfig: ${JSON.stringify(_)}`),_}sanitizeTelemetryConfig(g,f){g.getCallingAdapter&&(delete g.getCallingAdapter,f.warn("getCallingAdapter not supported")),g.getGenericTelemetryLogger&&(delete g.getGenericTelemetryLogger,f.warn("getGenericTelemetryLogger not supported"))}removeLogger(g){delete g.logger;const f=g;delete f.signalingAgentConfig?.logger,delete f.mediaAgentFactoryConfig?.logger,delete f.mediaAgentFactoryConfig?.safeLogger,delete f.imageRendererConfig?.callingLogger}removeHttpDispatcher(g){delete g.imageRendererConfig?.httpRequestDispatcher;const f=g;delete f.signalingAgentConfig?.httpRequestDispatcher,delete f.mediaAgentFactoryConfig?.httpRequestDispatcher}removeTrouterService(g){delete g.trouterService,delete g.signalingAgentConfig.trouterServiceProvider}removeEffectConfigProvider(g){delete g.wasmVqeProvider,delete g.webcvProvider,delete g.createWasmWorkerCbs}dispose(){this.logger.info("Dispose: RemoteStackFactory, TransportManager and RPCSessions"),this.telemetry?.sendLastGatheredTelemetry(),this.telemetry?.stopRealtimeTelemetry(),this.telemetry?.clear(),this.rpcSession.dispose(),this.transportManager?.dispose(),this.remoteStackFactory=null,this.transportManager=null}get logger(){return this.callingLogger??this.fallbackLogger}},Vh=__toESM(O()),Bh=new class{constructor(){this.remotedPluginlessStackFactory=new Uh}async build(g){return this.getStackFactory(g.stackType).build(g)}async buildBaseStack(g){return this.getStackFactory(g.stackType).buildBaseStack(g)}getStackFactory(g){return 1===g?this.remotedPluginlessStackFactory:Vh.pluginlessStackFactory}getVersion(){return Vh.pluginlessStackFactory.getVersion()}},Hh=class{async state(){throw new Error("Should be executed remotely")}async onStateChanged(g){throw new Error("Should be executed remotely")}async offStateChanged(g){throw new Error("Should be executed remotely")}async getTrouterUrlAsync(){throw new Error("Should be executed remotely")}},tsCallingChannel=(g,f)=>getRPCTransport("TsCallingChannel",f,g)
/*! Bundled license information:

	@nevware21/ts-utils/dist/es5/mod/ts-utils.js:
	  (*! https://github.com/nevware21/ts-utils v0.11.3 *)

	@nevware21/ts-async/dist/es5/mod/ts-async.js:
	  (*!
	   * NevWare21 Solutions LLC - ts-async, 0.5.2
	   * https://github.com/nevware21/ts-async
	   * Copyright (c) NevWare21 Solutions LLC and contributors. All rights reserved.
	   * Licensed under the MIT license.
	   *)
	*/
/*! Bundled license information:

	@nevware21/ts-utils/dist/es5/mod/ts-utils.js:
	  (*! https://github.com/nevware21/ts-utils v0.11.3 *)

	@nevware21/ts-async/dist/es5/mod/ts-async.js:
	  (*!
	   * NevWare21 Solutions LLC - ts-async, 0.5.2
	   * https://github.com/nevware21/ts-async
	   * Copyright (c) NevWare21 Solutions LLC and contributors. All rights reserved.
	   * Licensed under the MIT license.
	   *)
	*/;if("object"==typeof C.exports&&"object"==typeof v){var __cp=(g,f,S,v)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let C of Object.getOwnPropertyNames(f))Object.prototype.hasOwnProperty.call(g,C)||C===S||Object.defineProperty(g,C,{get:()=>f[C],enumerable:!(v=Object.getOwnPropertyDescriptor(f,C))||v.enumerable});return g};C.exports=__cp(C.exports,v)}return C.exports}))}));class EcsProvider{constructor(g,f,S){this._configIds={AcsCallingSDKWeb:"",SkypeWebMedia:""},this.setConfigOrDefault=(g,f)=>{g&&Object.keys(g).forEach((S=>{void 0!==g[S]&&(f[S]=g[S])}))},this._logger=g,this.sdkDiagnosticInformation=f,this._acsProxy=S;const v=getAcsEcsConfig().calling.applicationSettingsUrls;this._trouterSettings={version:`${getPlatformId()}/${getSdkInternalVersion()}`,productName:"AcsWeb",trouterServiceUrl:v.Public_TrouterServiceUrl,registrarServiceUrl:v.Public_RegistrarServiceUrl,maxRegistrationTimeInMs:36e5,pnhAppId:"AcsWeb",pnhTemplate:"AcsWeb_2.0",environment:"Prod",platform:getPlatformName()},this._JsCsaConfig={languageCode:"en",emergencyCallCountry:"",autoResolveConflictedCall:!1,handleRosterFromCreateAndJoin:!0,conversationServiceUrl:S.proxyfyUrl(v.Public_ConversationServiceUrl),useInternalHttpDispatcher:!0,supportsHostlessGroupCalls:!0,doHostlessCalling:!0,shouldServiceSendCallEventMessages:!0,shouldServiceSendNGCUpgradeMessages:!0,supportsCompressedServicePayload:!0,handleNewOfferRequest:!0,handleMediaOfferFromPushNotification:!0,isWebRtcEnabled:!0,supportsSynchronousTrouterResponse:!0,autoJoinOnConflict:!0,brokerEnabledOutgoing:!0,brokerEnabledIncoming:!0,brokerExclusively:!1,brokerRequestBatching:!0,isGVCOutgoingEnabled:!0,isGVCJoiningEnabled:!0,enableTokenCache:!1},this._JamaSettingsMobile={webrtcCameraOpenFs:900,webrtcMultipartyMaxScalingFs:900,webrtcMaxScalingFs:900},this._JamaSettings={debug:!1,numVideoChannelsGvc:6,webcv:null,maxNumberOfPinnedVideos:2},this._MDNTrapSettings={Service:{url:S.proxyfyUrl(v.Public_MdnTrapServiceUrl),tokenUrl:S.proxyfyUrl(v.Public_MdnTrapServiceTokenUrl)},Relay:{Skype:{addresses:[],fqdns:[v.Public_MdnTrapRelaySkypeFqdns],tcpPort:443,udpPort:3478},Turn:{addresses:[],fqdns:[v.Public_MdnTrapRelayTurnFqdns],tcpPort:443,udpPort:3478,url:v.Public_MdnTrapRelayTurnUrl}},Http:{connectionTimeout:30,requestTimeout:60},Token:{earlyRefreshMinutes:1080,earlyRefreshPercentage:25}},this._TrouterJScriptClient={TelemetryEnabled:!1,ClientTelemetryEventEnabled:{trouter_js_client_connected:!1,trouter_js_client_disconnected:!1,trouter_js_client_error:!1,trouter_js_client_progress:!1,trouter_js_client_response:!1,trouter_js_client_check_connection:!1,trouter_js_client_registration:!1,trouter_js_client_unregistration:!1,logHealthCheckError:!1,logSendPingError:!1,numberOfStepsToMaintain:0,sendProgressTimeoutSecs:0}};const C=getSdkInternalVersion();C.includes("alpha")||C.includes("alpharc")||C.includes("beta")||C.includes("betarc")||(C.includes("stable")||C.includes("stablerc"))&&(this._JamaSettings.maxNumberOfPinnedVideos=1)}getTrouterTelemetryConfig(){return{enabled:this._TrouterJScriptClient.TelemetryEnabled,...this._TrouterJScriptClient.ClientTelemetryEventEnabled}}getJamaSettings(){const g=getBrowserInfo();let f=this._JamaSettings;return"Mobile"==g.formFactor&&(f={...f,...this._JamaSettingsMobile}),f}getClientInformation(){const g=getAcsEcsConfig().telemetry.reportSdkUaToService,f=getAcsEcsConfig().telemetry.reportEnvToService;return`ACSWeb(${getPlatformId()}/${getSdkInternalVersion()})`+(f?`/${getInternalEnvInfo()}`:"")+(g?`/(${this.sdkDiagnosticInformation})`:"")}getJsCsaConfig(){return this._JsCsaConfig.useInternalHttpDispatcher=!(this._acsProxy.hasProxyUrl()||getAcsEcsConfig().telemetry.sendNetworkInfo),{...this._JsCsaConfig,clientInformation:this.getClientInformation()}}getMdnTrapSettings(){return this._MDNTrapSettings}getTrouterSettings(){return this._trouterSettings}setConfig(g,f){this._logger.info("Update ECS settings");const S=getAcsEcsConfig().calling.applicationSettingsUrls,v=getAcsEcsConfig().calling.applicationSettingsEudbUrls,C=g&&isEudbConfigurationsApplicable(g.identityType,g.region);if(g?.identityType==lm.Enterprise)C?(this._trouterSettings.trouterServiceUrl=v.Enterprise_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(v.Enterprise_RegistrarServiceUrl_EUDB)):(this._trouterSettings.trouterServiceUrl=S.Enterprise_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(S.Enterprise_RegistrarServiceUrl));else switch(g?.cloudType){case tm.Public:C&&(this._trouterSettings.trouterServiceUrl=v.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(v.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(v.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(v.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(v.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[v.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[v.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=v.Public_MdnTrapRelayTurnUrl_EUDB);break;case tm.GccHigh:this._trouterSettings.trouterServiceUrl=S.GccHigh_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(S.GccHigh_RegistrarServiceUrl);break;case tm.Dod:this._trouterSettings.trouterServiceUrl=S.Dod_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(S.Dod_RegistrarServiceUrl);break;case tm.AirGap08:this._trouterSettings.trouterServiceUrl=S.AirGap08_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(S.AirGap08_RegistrarServiceUrl);break;case tm.AirGap09:this._trouterSettings.trouterServiceUrl=S.AirGap09_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(S.AirGap09_RegistrarServiceUrl)}if(f)this._configIds={AcsCallingSDKWeb:f?.ConfigIDs?.AcsCallingSDKWeb||"",SkypeWebMedia:f?.ConfigIDs?.SkypeWebMedia||""},this.setConfigOrDefault(f?.SkypeCalling,this._JsCsaConfig),this.setConfigOrDefault(f?.MDN_TRAP,this._MDNTrapSettings),this.setConfigOrDefault(f?.SkypeWebMedia?.mediaAgent,this._JamaSettings),this.setConfigOrDefault(f?.TrouterJScriptClient,this._TrouterJScriptClient);else if(g?.identityType===lm.Enterprise)C?(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(v.Enterprise_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(v.Enterprise_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(v.Enterprise_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[v.Enterprise_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[v.Enterprise_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=v.Enterprise_MdnTrapRelayTurnUrl_EUDB):(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(S.Enterprise_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(S.Enterprise_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(S.Enterprise_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[S.Enterprise_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[S.Enterprise_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=S.Enterprise_MdnTrapRelayTurnUrl);else switch(g?.cloudType){case tm.Public:C&&(this._trouterSettings.trouterServiceUrl=v.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(v.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(v.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(v.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(v.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[v.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[v.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=v.Public_MdnTrapRelayTurnUrl_EUDB);break;case tm.GccHigh:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(S.GccHigh_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(S.GccHigh_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(S.GccHigh_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[S.GccHigh_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[S.GccHigh_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=S.GccHigh_MdnTrapRelayTurnUrl;break;case tm.Dod:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(S.Dod_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(S.Dod_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(S.Dod_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[S.Dod_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[S.Dod_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=S.Dod_MdnTrapRelayTurnUrl;break;case tm.AirGap08:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(S.AirGap08_ConversationServiceUrl);break;case tm.AirGap09:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(S.AirGap09_ConversationServiceUrl)}}getConfigIds(){return this._configIds}assertConfigs(g){const f="SkypeCalling",S="MDN_TRAP",v="SkypeWebMedia",C="SkypeWebMedia.mediaAgent",_="TrouterJScriptClient";let T=[];if(g?.SkypeCalling||T.push(f),g?.MDN_TRAP||T.push(S),g?.SkypeWebMedia?g?.SkypeWebMedia?.mediaAgent||T.push(C):T.push(v),g?.TrouterJScriptClient||T.push(_),T.length>0){const g=new CallingCommunicationError({defaultError:D.CALL_STACK.FOUND_UNDEFINED_CONFIGS,defaultErrorMessageArgs:[T.join(", ")]});throw this._logger.error(g.message),g}}}var dA=createCommonjsModule((function(g,f){var S;S=function(){return function(g){function e(S){if(f[S])return f[S].exports;var v=f[S]={i:S,l:!1,exports:{}};return g[S].call(v.exports,v,v.exports,e),v.l=!0,v.exports}var f={};return e.m=g,e.c=f,e.i=function(g){return g},e.d=function(g,f,S){e.o(g,f)||Object.defineProperty(g,f,{configurable:!1,enumerable:!0,get:S})},e.n=function(g){var f=g&&g.__esModule?function(){return g.default}:function(){return g};return e.d(f,"a",f),f},e.o=function(g,f){return Object.prototype.hasOwnProperty.call(g,f)},e.p="",e(e.s=1)}([function(g,f,S){function n(g,f){var S,v=new Promise((function(f,v){fetch(g).then((function(g){void 0!==S&&clearTimeout(S),f(g)})).catch((function(g){void 0!==S&&clearTimeout(S),v(g)}))}));if(0!==f){var C=new Promise((function(v,C){S=setTimeout(C,f,new Error("Fetch for '".concat(g.url,"' timed out")))}));return Promise.race([v,C])}return v}function o(g){try{return JSON.stringify(g)}catch(f){return"Unable to serialize object of type ".concat(typeof g)}}Object.defineProperty(f,"__esModule",{value:!0}),f.Timespan=f.toJson=f.fetchWithTimeout=void 0,f.fetchWithTimeout=n,f.toJson=o;var v=function(){function t(){this.start=Date.now()}return Object.defineProperty(t.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),t.prototype.reset=function(){this.start=Date.now()},t}();f.Timespan=v},function(g,f,S){function n(g,f,S){return new R(g,f,S)}var v=this&&this.__extends||function(){var t=function(g,f){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)Object.prototype.hasOwnProperty.call(f,S)&&(g[S]=f[S])})(g,f)};return function(g,f){function n(){this.constructor=g}if("function"!=typeof f&&null!==f)throw new TypeError("Class extends value "+String(f)+" is not a constructor or null");t(g,f),g.prototype=null===f?Object.create(f):(n.prototype=f.prototype,new n)}}(),C=this&&this.__assign||function(){return C=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},C.apply(this,arguments)},_=this&&this.__awaiter||function(g,f,S,v){function o(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function s(g){try{c(v.next(g))}catch(g){C(g)}}function a(g){try{c(v.throw(g))}catch(g){C(g)}}function c(g){g.done?S(g.value):o(g.value).then(s,a)}c((v=v.apply(g,f||[])).next())}))},T=this&&this.__generator||function(g,f){function r(g){return function(f){return n([g,f])}}function n(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!(C=(C=T.trys).length>0&&C[C.length-1])&&(6===I[0]||2===I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:r(0),throw:r(1),return:r(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_};Object.defineProperty(f,"__esModule",{value:!0}),f.createRegistrarClient=f.RegistrarClient=void 0;var I=S(0),b=["skype","aad","cae"],A=function(g){function e(f){var S=g.call(this,f)||this;return S.name="CancelationError",S}return v(e,g),e}(Error),P=function(){function t(g,f,S){this.logger=g,this.maxBackoffInMs=f,this.initialDelay=S,this.backoffCount=0,this.id=++t.idCounter}return t.prototype.delay=function(g){var f=this;if(void 0!==this.timerHandle)throw new Error("Retry sequence logical failure");if(-1===this.backoffCount)return new Promise((function(g,f){f(new A("Cancelled"))}));var S=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info("[RegistrarClient] Backing off ".concat(g," for ").concat(S," milliseconds with ID ").concat(this.id)),new Promise((function(v,C){f.cancelFunc=C,f.timerHandle=setTimeout((function(){f.logger.info("[RegistrarClient] Back off for ".concat(g," with ID ").concat(f.id," complete")),f.timerHandle=void 0,v()}),S)}))},t.prototype.cancel=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off"),clearTimeout(this.timerHandle),void 0!==this.cancelFunc&&this.cancelFunc(new A("Cancelled"))),this.backoffCount=-1},t.prototype.calculateNextBackoffMs=function(){var g=1+.4*(Math.random()-.5),f=this.initialDelay*Math.pow(2,this.backoffCount)*g;return f=Math.round(f),Math.min(this.maxBackoffInMs,f)},t.idCounter=0,t}(),R=function(){function t(g,f,S){var v;this.logger=g,this.tokenProvider=f,this.options=S,this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN=15,this.DEFAULT_MAX_BACKOFF_TIME_IN_MS=3e5,this.backoffs={},this.maxBackOffTime=this.options.maxRetryDelayMs>0?this.options.maxRetryDelayMs:this.DEFAULT_MAX_BACKOFF_TIME_IN_MS,this.maxRetriesForGetToken=void 0===S.maxRetriesForGetToken||null===S.maxRetriesForGetToken?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:S.maxRetriesForGetToken,this.proxyUrlRewrite=null!==(v=S.proxyUrlRewrite)&&void 0!==v?v:function(g){return g}}return t.prototype.setTelemetryLogger=function(g){this.eventLogger=g},t.prototype.register=function(g,f){return _(this,void 0,void 0,(function(){return T(this,(function(S){switch(S.label){case 0:return[4,this.performRegistration(g,f,"pr_set_registration")];case 1:return S.sent(),this.cachedRegistrationParams=[g,f],[2]}}))}))},t.prototype.unregister=function(){return _(this,void 0,void 0,(function(){var g;return T(this,(function(f){switch(f.label){case 0:return this.logger.info("[RegistrarClient] sending unregister request"),g=new Request(this.proxyUrlRewrite("".concat(this.options.registrarUrl,"/").concat(this.options.registrationId)),{method:"DELETE",mode:"cors",headers:new Headers(C(C({},this.options.extraRegistrationHeaders),{accept:"application/json, text/javascript"}))}),[4,this.callRegistrar(g,"pr_delete_registration")];case 1:return f.sent(),[2]}}))}))},t.prototype.cancelPendingRequests=function(){var g=this;Object.keys(this.backoffs).forEach((function(f){g.backoffs[f].cancel()})),this.backoffs={}},t.prototype.resendRegistration=function(){return _(this,void 0,void 0,(function(){return T(this,(function(g){switch(g.label){case 0:if(!this.cachedRegistrationParams)throw new Error("Re-registration failed because there is no registration parameters cached");return[4,this.performRegistration(this.cachedRegistrationParams[0],this.cachedRegistrationParams[1],"pr_resend_registration")];case 1:return g.sent(),[2]}}))}))},t.prototype.performRegistration=function(g,f,S){return _(this,void 0,void 0,(function(){var v,_;return T(this,(function(T){switch(T.label){case 0:return this.logger.info("[RegistrarClient] Sending register request"),v={clientDescription:g,registrationId:this.options.registrationId,nodeId:"",transports:f},_=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:"POST",mode:"cors",headers:new Headers(C(C({},this.options.extraRegistrationHeaders),{"content-type":"application/json",accept:"application/json, text/javascript"})),body:(0,I.toJson)(v)}),[4,this.callRegistrar(_,S)];case 1:return T.sent(),[2]}}))}))},t.prototype.startBackoff=function(){var g=new P(this.logger,this.maxBackOffTime,this.options.initialRetryDelayMs);return this.backoffs[g.id]=g,g},t.prototype.stopBackoff=function(g){g.cancel(),delete this.backoffs[g.id]},t.prototype.getToken=function(g){return _(this,void 0,void 0,(function(){var f,S,v,C,_,I,A;return T(this,(function(T){switch(T.label){case 0:f=this.startBackoff(),S=0,T.label=1;case 1:return T.trys.push([1,3,,8]),this.logger.info("[RegistrarClient] Asking for a new token"),[4,this.tokenProvider({needFresh:!0,supportedTokenTypes:b,wwwAuthenticateHeader:g,purpose:"registrar"})];case 2:return v=T.sent(),this.stopBackoff(f),[2,v];case 3:C=T.sent(),T.label=4;case 4:return T.trys.push([4,6,,7]),S++,_=JSON.stringify(C),S>this.maxRetriesForGetToken?(I="[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ".concat(_),this.logger.error(I),this.stopBackoff(f),[2,Promise.reject(I)]):(this.logger.warn("[RegistrarClient] Retrying for a new token. Retry Count: ".concat(S," Error: ").concat(_)),[4,f.delay("Fetching a new token")]);case 5:return T.sent(),[3,8];case 6:throw A=T.sent(),this.stopBackoff(f),A;case 7:return[3,8];case 8:return[3,1];case 9:return[2]}}))}))},t.prototype.callRegistrar=function(g,f){var S,v,C;return _(this,void 0,void 0,(function(){var _,A,P,R,M,w,O,D,N,k,L,F,x,U,V,B;return T(this,(function(T){switch(T.label){case 0:return _=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:b,wwwAuthenticateHeader:void 0,purpose:"registrar"})];case 1:A=T.sent(),this.setTokenHeader(g,A),P=new I.Timespan,R=0,T.label=2;case 2:M=void 0,T.label=3;case 3:return T.trys.push([3,10,15,16]),w=g.clone(),[4,(0,I.fetchWithTimeout)(w,this.options.requestTimeoutMs)];case 4:return 401!==(M=T.sent()).status?[3,8]:++R>this.maxRetriesForGetToken?(O="[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '".concat(g.url,"' failed with ").concat(M.status," ").concat(M.statusText),this.logger.error(O),this.stopBackoff(_),[2,Promise.reject(O)]):(this.logger.warn("[RegistrarClient] Retry Count ".concat(R,". Request '").concat(g.url,"' failed with ").concat(M.status," ").concat(M.statusText)),D=null!==(v=null===(S=M.headers)||void 0===S?void 0:S.get("www-authenticate"))&&void 0!==v?v:void 0,N=this.setTokenHeader,k=[g],[4,this.getToken(D)]);case 5:return N.apply(this,k.concat([T.sent()])),R>1?[4,_.delay("Registrar call retry after 401")]:[3,7];case 6:T.sent(),T.label=7;case 7:return[3,22];case 8:if(M.status>=500&&M.status<600)throw new Error("Fetch for '".concat(g.url,"' failed with ").concat(M.status," ").concat(M.statusText));T.label=9;case 9:return[3,16];case 10:L=T.sent(),this.logger.error("[RegistrarClient] Request failed with ".concat(L)),T.label=11;case 11:return T.trys.push([11,13,,14]),[4,_.delay("Registrar call retry")];case 12:return T.sent(),[3,22];case 13:throw F=T.sent(),this.logger.error("[RegistrarClient] Request cancelled"),this.stopBackoff(_),F;case 14:return[3,16];case 15:return this.sendTelemetryEvent(f,g,M,P),[7];case 16:return this.stopBackoff(_),M.ok?[2,M]:[3,17];case 17:x=void 0,T.label=18;case 18:return T.trys.push([18,20,,21]),V=(U=JSON).stringify,[4,M.json()];case 19:return x=V.apply(U,[T.sent()]),[3,21];case 20:return T.sent(),x="no details",[3,21];case 21:throw B="Fetch for '".concat(g.url,"' failed with ").concat(M.status," ").concat(M.statusText," (").concat(x,", MS-CV: ").concat(null===(C=M.headers)||void 0===C?void 0:C.get("MS-CV"),")"),this.logger.error("[RegistrarClient] ".concat(B)),new Error(B);case 22:return[3,2];case 23:return[2]}}))}))},t.prototype.setTokenHeader=function(g,f){switch(g.headers.delete("X-Skypetoken"),g.headers.delete("Authorization"),g.headers.delete("X-MS-Migration"),f.tokenType.toLowerCase()){case"skype":g.headers.set("X-Skypetoken",f.token);break;case"aad":case"cae":g.headers.set("Authorization","Bearer ".concat(f.token));break;default:throw new Error("unsupported token type: ".concat(f.tokenType))}!1===this.options.usingLegacyTokenApi&&g.headers.set("X-MS-Migration","True")},t.prototype.sendTelemetryEvent=function(g,f,S,v){if(void 0!==this.eventLogger){var C={name:g,properties:{url:{value:f.url},result_code:{value:void 0!==S?S.status:0},begin_timestamp:{value:v.startTime},elapsed:{value:v.duration}}};this.eventLogger.logEvent(C)}},t}();f.RegistrarClient=R,f.createRegistrarClient=n}])},g.exports=S()})),hA=createCommonjsModule((function(g,f){var S;S=function(g){return function(g){function e(S){if(f[S])return f[S].exports;var v=f[S]={i:S,l:!1,exports:{}};return g[S].call(v.exports,v,v.exports,e),v.l=!0,v.exports}var f={};return e.m=g,e.c=f,e.i=function(g){return g},e.d=function(g,f,S){e.o(g,f)||Object.defineProperty(g,f,{configurable:!1,enumerable:!0,get:S})},e.n=function(g){var f=g&&g.__esModule?function(){return g.default}:function(){return g};return e.d(f,"a",f),f},e.o=function(g,f){return Object.prototype.hasOwnProperty.call(g,f)},e.p="",e(e.s=20)}([function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.Logger=void 0;var v=function(){function t(g,f){this.name=g,this.logger=f}return t.prototype.debug=function(g){this.logger.debug("[".concat(this.name,"] ").concat(g))},t.prototype.info=function(g){this.logger.info("[".concat(this.name,"] ").concat(g))},t.prototype.warn=function(g){this.logger.warn("[".concat(this.name,"] ").concat(g))},t.prototype.error=function(g){this.logger.error("[".concat(this.name,"] ").concat(g))},t}();f.Logger=v},function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.USER_AUTHENTICATE_EVENT_NAME=f.SUPPORTED_TOKEN_TYPES=f.FAILED_MESSAGE_ACK=f.UNHANDLED_MESSAGE_ACK=f.HANDLED_MESSAGE_ACK=f.CLIENT_VERSION=f.constants=void 0,f.constants={TROUTER_INIT:"trouterinit",TROUTER_READY_EVENT:"trouterReadyEvent",TROUTER_READY_TIMEOUT:"trouterReadyTimeout",TROUTER_TOKEN_REQUEST:"trouterTokenRequest",TROUTER_TOKEN_GET_SUCCEEDED:"trouterTokenGetSucceeded",TROUTER_TOKEN_GET_FAILED:"trouterTokenGetFailed",TROUTER_RECONNECTING:"trouterReconnecting",RENEWAL:"renewal",NEW_CONNECTION:"newConnection",ENDPOINT_REGISTRATION_FAILED:"endpointRegistrationFailed"},f.CLIENT_VERSION="2025.03.01.34",f.HANDLED_MESSAGE_ACK=200,f.UNHANDLED_MESSAGE_ACK=404,f.FAILED_MESSAGE_ACK=500,f.SUPPORTED_TOKEN_TYPES=["skype","aad","cae"],f.USER_AUTHENTICATE_EVENT_NAME="user.authenticate"},function(g,f,S){var v,C;Object.defineProperty(f,"__esModule",{value:!0}),f.TrouterState=f.UserActivityState=void 0,function(g){g[g.Unknown=0]="Unknown",g[g.Active=1]="Active",g[g.Inactive=2]="Inactive"}(v||(f.UserActivityState=v={})),function(g){g[g.Unknown=0]="Unknown",g[g.Connected=2]="Connected",g[g.Disconnected=3]="Disconnected",g[g.Switching=9]="Switching"}(C||(f.TrouterState=C={}))},function(g,f,S){function o(g){try{return JSON.stringify(g)}catch(f){return"Unable to serialize object of type ".concat(typeof g)}}function i(g){var f=Math.round((new Date).getTime()/1e3);return void 0!==g&&g>f?g-f:0}function r(g){return Math.round((new Date).getTime()/1e3)+g}function s(g,f){return v(this,void 0,void 0,(function(){var S,v,_;return C(this,(function(C){return v=new Promise((function(f,v){fetch(g).then((function(g){clearTimeout(S),f(g)})).catch((function(g){clearTimeout(S),v(g)}))})),0!==f?(_=new Promise((function(v,C){var _=new URL(g.url),T=new Error("".concat(g.method," ").concat(_.origin).concat(_.pathname," timed out"));S=setTimeout(C,f,T)})),[2,Promise.race([v,_])]):[2,v]}))}))}var v=this&&this.__awaiter||function(g,f,S,v){function i(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function s(g){try{a(v.next(g))}catch(g){C(g)}}function c(g){try{a(v.throw(g))}catch(g){C(g)}}function a(g){g.done?S(g.value):i(g.value).then(s,c)}a((v=v.apply(g,f||[])).next())}))},C=this&&this.__generator||function(g,f){function n(g){return function(f){return o([g,f])}}function o(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!(C=(C=T.trys).length>0&&C[C.length-1])&&(6===I[0]||2===I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_};Object.defineProperty(f,"__esModule",{value:!0}),f.Timespan=f.CorrelationVector=f.fetchWithTimeout=f.calculateExpireTsInSec=f.calculateTtlInSec=f.toJson=void 0,f.toJson=o,f.calculateTtlInSec=i,f.calculateExpireTsInSec=r,f.fetchWithTimeout=s;var _=function(){function t(g){this.base=void 0!==g?g:this.createCorrelationVectorBase(),this.extension=0}return t.extend=function(g){return new t(g)},t.prototype.increase=function(){this.extension++},t.prototype.value=function(){return"".concat(this.base,".").concat(this.extension)},t.prototype.createCorrelationVectorBase=function(){for(var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0987654321/+",f="AQgw",S="",v=0;v<21;v++)S+=g.charAt(Math.floor(Math.random()*g.length));return S+f.charAt(Math.floor(Math.random()*f.length))},t}();f.CorrelationVector=_;var T=function(){function t(){this.start=Date.now()}return Object.defineProperty(t.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),t.prototype.reset=function(){this.start=Date.now()},t}();f.Timespan=T},function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.TrouterManagerState=f.UserActivityEventReason=f.ServerState=void 0;var v,C,_=S(3),T=function(){function t(g,f,S,v,C,_){this.connectionId=g,this.connectedClientId=f,this.domId=S,this.url=v,this.c2cUrlBase=C,this.expirationTsSec=_}return t.prototype.getRemainingTtlInSec=function(){return(0,_.calculateTtlInSec)(this.expirationTsSec)},t}();f.ServerState=T,function(g){g[g.Unknown=0]="Unknown",g[g.Modified=1]="Modified",g[g.Snapshot=2]="Snapshot",g[g.Connected=3]="Connected"}(v||(f.UserActivityEventReason=v={})),function(g){g[g.Unknown=0]="Unknown",g[g.Connected=2]="Connected",g[g.Disconnected=3]="Disconnected",g[g.Switching=9]="Switching",g[g.TerminalError=10]="TerminalError"}(C||(f.TrouterManagerState=C={}))},function(g,f,S){function o(g,f){return"skype"===g&&"1"!==i(null==f?void 0:f.scae)?"v4a":"v4c"}function i(g){return"string"==typeof g?g:"number"==typeof g?g.toString():void 0}function r(g,f){return"v4c-websocket-failure"===(null==f?void 0:f.kind)?"v4a":g}function s(g){return Object.prototype.hasOwnProperty.call(g,"connectparams")}function c(g,f){return"v4a"===f?g.replace(/\/v4\/c\b/,"/v4/a").replace("wss://","https://").replace("ws://","http://"):g.replace(/\/v4\/a\b/,"/v4/c").replace("https://","wss://").replace("http://","ws://")}function a(g){if(void 0!==g)return v(v({},g),{reconnectUrl:void 0,serviceUrl:void 0})}function u(g){return"string"==typeof g?parseInt(g,10):g}function h(g){if("redirect"===(null==g?void 0:g.kind)&&void 0!==g.host){var f=g.host;return f.endsWith("/")&&(f=f.substring(0,f.length-1)),f.endsWith("/v4/c")||f.endsWith("/v4/a")||(f+="/v4/c"),f}}var v=this&&this.__assign||function(){return v=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},v.apply(this,arguments)};Object.defineProperty(f,"__esModule",{value:!0}),f.redirectUrlIfPresent=f.ensureNumber=f.reconnectParamsWithoutUrls=f.adaptUrl=f.isV4ConnectEvent=f.usedProtocolAfterFallback=f.usedProtocol=void 0,f.usedProtocol=o,f.usedProtocolAfterFallback=r,f.isV4ConnectEvent=s,f.adaptUrl=c,f.reconnectParamsWithoutUrls=a,f.ensureNumber=u,f.redirectUrlIfPresent=h},function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.TrouterFsm=f.State=void 0;var v,C,_=S(4),T=S(0),I=S(5);!function(g){g[g.Initial=0]="Initial",g[g.RetrievingToken=1]="RetrievingToken",g[g.Allocating=2]="Allocating",g[g.Handshaking=3]="Handshaking",g[g.Connecting=4]="Connecting",g[g.AnonymousConnecting=5]="AnonymousConnecting",g[g.WebsocketAuthenticating=6]="WebsocketAuthenticating",g[g.Connected=7]="Connected",g[g.Unregistering=8]="Unregistering",g[g.TerminalError=9]="TerminalError"}(v||(f.State=v={})),function(g){g[g.Initial=0]="Initial",g[g.Registering=1]="Registering",g[g.RegisteringButResendPending=2]="RegisteringButResendPending",g[g.Retrying=3]="Retrying",g[g.Registered=4]="Registered",g[g.RegistrationDisabled=5]="RegistrationDisabled"}(C||(C={}));var b=function(){function t(g,f,S,_){this.worker=f,this.incallModeEnabled=S,this.protocolSelector=_,this.state=v.Initial,this.autoReconnect=!0,this.logger=new T.Logger("ConnectionFsm",g),this.registrationState=C.Initial}return t.prototype.getState=function(){return this.state},t.prototype.isActive=function(){return this.state===v.Allocating||this.state===v.Connected||this.state===v.Handshaking||this.state===v.Connecting||this.state===v.RetrievingToken||this.state===v.AnonymousConnecting||this.state===v.WebsocketAuthenticating},t.prototype.isConnecting=function(){return this.state===v.Allocating||this.state===v.Handshaking||this.state===v.Connecting||this.state===v.AnonymousConnecting},t.prototype.start=function(){return this.state===v.Initial?(this.setState(v.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored("start"),!1)},t.prototype.stop=function(g,f){g&&(this.registrationState=C.Initial),this.worker.isIncallMode()&&this.worker.exitIncallMode(),this.worker.resetTokenBackoff(),this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.state===v.Connected&&this.worker.sendDisconnectTelemetryEvent("connection stopped"),this.registrationState!==C.Registered&&this.registrationState!==C.Registering&&this.registrationState!==C.RegisteringButResendPending||this.state===v.Unregistering?f?(this.setState(v.TerminalError),this.worker.dispatchTerminalError()):(this.setState(v.Initial),this.worker.dispatchDisconnected()):(this.registrationState=C.Initial,this.setState(v.Unregistering),this.worker.sendUnregisterRequest())},t.prototype.onTokenReceived=function(g,f,S){this.state===v.RetrievingToken?"v4c"===(0,I.usedProtocolAfterFallback)(this.protocolSelector(g.tokenType,S),f)?(this.setState(v.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(g,f)):(this.setState(v.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(g)):this.showIgnored("onTokenReceived")},t.prototype.checkConnection=function(g){g&&this.onPingInterval()},t.prototype.onAllocationSucceed=function(g){return this.state===v.Allocating&&this.registrationState===C.Registered&&this.worker.dispatchUnregistered(),this.state===v.Allocating?(this.setState(v.Handshaking),this.registrationState=C.Initial,this.worker.startSocketIo(g),!0):(this.showIgnored("onAllocationSucceed"),!1)},t.prototype.onAllocationFailed=function(g,f){this.state===v.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!g,claimsChallenge:f}):this.showIgnored("onAllocationFailed")},t.prototype.onV4cConnectivityCheckFailed=function(){this.state===v.AnonymousConnecting?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0}):this.showIgnored("onV4cConnectivityCheckFailed")},t.prototype.onV4cException=function(){this.state!==v.AnonymousConnecting&&this.state!==v.WebsocketAuthenticating||(this.logger.error("v4c exception, falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}}))},t.prototype.onConnectingTimeout=function(){this.state===v.Allocating||this.state===v.Connecting||this.state===v.Handshaking||this.state===v.AnonymousConnecting||this.state===v.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored("onConnectingTimeout")},t.prototype.onConnecting=function(){this.state===v.Handshaking?this.setState(v.Connecting):this.showIgnored("onConnecting")},t.prototype.onSocketConnect=function(g){this.state===v.AnonymousConnecting?(this.setState(v.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(g)):this.showIgnored("onSocketConnect")},t.prototype.onConnectingFailed=function(){this.state===v.Connecting?this.onConnectingTimeout():this.state===v.Handshaking?(this.logger.error("Unexpected error in Socket.io - no valid transports"),this.onConnectingTimeout()):this.state===v.AnonymousConnecting||this.state===v.WebsocketAuthenticating?(this.logger.info("/v4/c falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}})):this.showIgnored("onConnectingFailed")},t.prototype.onSocketDisconnect=function(g){this.state===v.Handshaking||this.state===v.Connected||this.state===v.WebsocketAuthenticating?(this.state===v.Connected&&this.worker.sendDisconnectTelemetryEvent(null==g?void 0:g.toTelemetryString()),this.state===v.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),"skypetoken-deprecated"===(null==g?void 0:g.reason)?(this.logger.error("Skypetoken deprecated response, not retrying any further"),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==v.Connected&&"dup"!==(null==g?void 0:g.reason),allowCachedToken:"unauthorized"!==(null==g?void 0:g.reason),claimsChallenge:null==g?void 0:g.claims})):this.showIgnored("onSocketDisconnect")},t.prototype.onTrouterConnected=function(){this.state===v.Connecting||this.state===v.WebsocketAuthenticating?(this.setState(v.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(_.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=C.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=C.Registering,this.worker.sendRegisterRequest())):this.showIgnored("onTrouterConnected")},t.prototype.onReconnectRequired=function(g,f,S){this.state===v.AnonymousConnecting||this.state===v.WebsocketAuthenticating?void 0===S||"host"!==S.target||void 0===S.url||""===S.url?(this.logger.error("unexpected reconnect arguments: ".concat(null==S?void 0:S.target," ").concat(null==S?void 0:S.url,", reconnecting without cache")),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"redirect-no-host"}})):this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"redirect",host:S.url}}):this.worker.dispatchReconnectIsRequired(g,f)},t.prototype.disableAutoReconnect=function(){this.autoReconnect=!1},t.prototype.onDownstreamRequest=function(g){this.state===v.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(g)):this.showIgnored("onDownstreamRequest")},t.prototype.onTrouterMessageLost=function(g){this.state===v.Connected?this.worker.dispatchTrouterMessageLost(g):this.showIgnored("onTrouterMessageLost")},t.prototype.onPingInterval=function(){this.state===v.Connected?this.worker.sendPingRequest():this.showIgnored("onPingInterval")},t.prototype.onPingResponseTimeout=function(){this.onMissedResponse("onPingResponseTimeout")},t.prototype.onPingResponse=function(){this.state===v.Connected||this.showIgnored("onPingResponse")},t.prototype.onRegistrationFailed=function(){this.state===v.Connected&&this.registrationState===C.Registering?(this.worker.dispatchUnregistered(),this.registrationState=C.Retrying,this.worker.startRegistrationRetryTimer()):this.state===v.Connected&&this.registrationState===C.RegisteringButResendPending?(this.registrationState=C.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationFailed")},t.prototype.onRetryRegistration=function(){this.state===v.Connected&&this.registrationState===C.Retrying?(this.registrationState=C.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRetryRegistration")},t.prototype.onRegistrationSucceeded=function(){this.state===v.Connected&&this.registrationState===C.Registering?(this.registrationState=C.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===v.Connected&&this.registrationState===C.RegisteringButResendPending?(this.registrationState=C.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationSucceeded")},t.prototype.onRegistrationNearExpiry=function(){this.state===v.Connected&&this.registrationState===C.Registered?(this.registrationState=C.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationNearExpiry")},t.prototype.onUnregistrationDone=function(){this.state===v.Unregistering?(this.setState(v.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored("onUnregistrationDone")},t.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===v.Connected&&this.registrationState===C.Registered?(this.registrationState=C.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===v.Connected&&this.registrationState===C.Registering&&(this.registrationState=C.RegisteringButResendPending)},t.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===v.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored("onIncallModeTimer")},t.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(_.UserActivityEventReason.Modified,this.state===v.Connected)},t.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse("onActivityStateResponseTimeout")},t.prototype.forceReconnect=function(g){this.state===v.Connected&&this.worker.sendDisconnectTelemetryEvent(g),this.worker.resetTokenBackoff(),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})},t.prototype.onTerminalError=function(){this.logger.error("Cannot proceed, reached terminal state. Switching from state '".concat(v[this.state],"' to ").concat(v[v.TerminalError])),this.stop(!0,!0),this.setState(v.TerminalError)},t.prototype.onMissedResponse=function(g){this.state===v.Connected?(this.worker.sendDisconnectTelemetryEvent(g),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})):this.showIgnored(g)},t.prototype.showIgnored=function(g){this.logger.debug("Ignoring event '".concat(g,"' in state '").concat(v[this.state],"'"))},t.prototype.setState=function(g){this.logger.info("Switching from state '".concat(v[this.state],"' to state '").concat(v[g],"'")),this.state!==g?this.state=g:this.logger.error("Attempt to switch to the current state '".concat(v[g],"'"))},t.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer())},t.prototype.cleanUpAndInitiateReconnect=function(g){if(!this.autoReconnect)return this.logger.info("Automatic reconnect is disabled, stopping this connection"),void this.stop(!0);this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.setState(v.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(g.allowCachedToken,g.backoff,g.claimsChallenge,g.fallbackReason)},t}();f.TrouterFsm=b},function(g,f,S){function o(g,f){var S=f?void 0:{"X-MS-Migration":"True"};switch(g.tokenType.toLowerCase()){case"skype":return v({"X-Skypetoken":g.token},S);case"aad":case"cae":return v({Authorization:"Bearer ".concat(g.token)},S);default:throw new Error("unsupported token type: ".concat(g.tokenType))}}function i(g){return null!=g&&"function"==typeof g.toString?g.toString():"[".concat(typeof g,"]")}function r(g){return"object"==typeof g&&null!==g&&void 0!==g.stack?(0,b.toJson)(g.stack):'"(no error.stack)"'}function s(g){return"object"==typeof g&&null!==g&&"string"==typeof g.message?g.message:"(no error.message)"}var v=this&&this.__assign||function(){return v=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},v.apply(this,arguments)},C=this&&this.__awaiter||function(g,f,S,v){function i(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function s(g){try{a(v.next(g))}catch(g){C(g)}}function c(g){try{a(v.throw(g))}catch(g){C(g)}}function a(g){g.done?S(g.value):i(g.value).then(s,c)}a((v=v.apply(g,f||[])).next())}))},_=this&&this.__generator||function(g,f){function n(g){return function(f){return o([g,f])}}function o(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!(C=(C=T.trys).length>0&&C[C.length-1])&&(6===I[0]||2===I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_};Object.defineProperty(f,"__esModule",{value:!0}),f.TrouterConnection=f.ReconnectReason=void 0;var T,I=S(21),b=S(3),A=S(15),P=S(1),R=S(16),M=S(17),w=S(2),O=S(4),D=S(0),N=S(5),k=S(6),L=S(12),F=function(){function t(){this.cv=P.CLIENT_VERSION,this.ua="",this.hr="",this.v=""}return t}(),x=function(){function t(){this["force new connection"]=!0,this.reconnect=!1,this.query="",this.ackTimeoutMs=5e3}return t.prototype.rewriteUrlForProxy=function(g){return g},t}(),U="MS-CV",V=function(){function t(g,f){this.logger=f,this.cvCounter=0;var S=JSON.parse(g);this.startTS=this.safeJsonNumber(S,"startTS",0),this.url=this.safeJsonString(S,"url",""),this.shortUrl=this.safeJsonString(S,"shortUrl",""),this.body=this.safeJsonString(S,"body",""),this.headers=this.safeJsonRecord(S,"headers",{}),this.id=this.safeJsonNumber(S,"id",-1),this.method=this.safeJsonString(S,"method",""),this.replied=!1,this.timedout=!1,this.receivedCv=this.headers[U],this.updateCvHeader()}return Object.defineProperty(t.prototype,"correlationVector",{get:function(){return this.receivedCv?"".concat(this.receivedCv,".").concat(this.cvCounter):""},enumerable:!1,configurable:!0}),t.prototype.on=function(g,f){"data"===g?this.dataCallback=f:"end"===g&&("function"==typeof this.dataCallback&&this.dataCallback(this.body),f())},t.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader()},t.prototype.updateCvHeader=function(){var g=this.correlationVector;g&&(this.headers[U]=g)},t.prototype.safeJsonNumber=function(g,f,S){var v;if(null!=g&&Object.prototype.hasOwnProperty.call(g,f)){var C=g;if("number"==typeof C[f])return C[f];if("string"==typeof C[f])return parseFloat(C[f]);null===(v=this.logger)||void 0===v||v.warn("unexpected type of '".concat(f,"': ").concat(typeof C[f]))}return S},t.prototype.safeJsonString=function(g,f,S){var v;if(null!=g&&Object.prototype.hasOwnProperty.call(g,f)){var C=g;if("string"==typeof C[f])return C[f];null===(v=this.logger)||void 0===v||v.warn("unexpected type of '".concat(f,"': ").concat(typeof C[f]))}return S},t.prototype.safeJsonRecord=function(g,f,S){var v;if(null!=g&&Object.prototype.hasOwnProperty.call(g,f)){var C=g;if("object"==typeof C[f])return C[f];null===(v=this.logger)||void 0===v||v.warn("unexpected type of '".concat(f,"': ").concat(typeof C[f]))}return S},t}(),B=function(){function t(g,f,S){this.request=g,this.responseData=f,this.sendResponse=S}return t.prototype.writeHead=function(g,f){this.responseData.status=g,this.responseData.headers=f},t.prototype.write=function(g){this.responseData.body+=g},t.prototype.end=function(g){return g&&(this.responseData.body+=g),this.sendResponse(this.request,this.responseData)},t}(),H=function(){function t(g){this.name=g,this.args={},this.timeoutTimerId=0}return t}();!function(g){g[g.Configuration=0]="Configuration",g[g.ServerInitiated=1]="ServerInitiated"}(T||(f.ReconnectReason=T={}));var $=function(){function t(g,f,S,v,C,_,T,b){var R,w=this;this.options=f,this.manager=S,this.tokenProvider=v,this.usingLegacyTokenApi=C,this.protocolSelector=T,this.audienceSubscriptionState=b,this.WEBSOCKET_TRANSPORT_NAME="websocket",this.XHR_POLLING_TRANSPORT_NAME="xhr-polling",this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR="Error",this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED="Unsubscribed",this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT="Timeout",this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST="BadRequest",this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX=/&audienceSubscriptionState=[^&]*|^audienceSubscriptionState=[^&]*&?/,this.USER_ACTIVITY_QUERY_PARAM_REGEX=/userActivity=[^&]*/,this.connectionId="",this.inIncallMode=!1,this.connectionAttempt=0,this.connectedClientId="",this.isNavigatorOnline=!0,this.onNavigatorOnlineStatusUpdateBound=this.onNavigatorOnlineStatusUpdate.bind(this),this.c2cUrlBase="",this.connectingErrorsInRow=0,this.connectivityCheckFailuresInARow=0,this.unauthorizedErrorCount=0,this.pendingSentEventTimers={},this.lastDisconnectReason="",this.UNKNOWN_TRANSPORT="unknown_transport",this.connectingErrorsThreshold=3,this.pendingAudienceSubscription=void 0,this.logger=new D.Logger("Connection",g),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff=new M.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),"undefined"!=typeof window&&window.location&&(this.domId=window.location.hostname);var O=new F;O.cv=P.CLIENT_VERSION,O.ua="",(null===(R=this.options)||void 0===R?void 0:R.clientInfo)&&(O.ua=this.safeString(this.options.clientInfo.ua),O.v=this.safeString(this.options.clientInfo.v)),this.clientInfo=O,this.connectionTracker=new A.ConnectionTracker(g,this.clientID,this.clientInfo,(function(){return w.getServerState()}),this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(f);var N=this.options.incallModeTimeoutMs>0;if(this.fsm=new k.TrouterFsm(g,this,N,this.protocolSelector),f.registration){var L={registrarUrl:f.registration.registrarUrl,proxyUrlRewrite:f.rewriteUrlForProxy,registrationId:f.registration.registrationId,requestTimeoutMs:f.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:f.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:f.retryLimitOnTokenFetch,extraRegistrationHeaders:f.extraConnectionHeaders};this.registrarClient=(0,I.createRegistrarClient)(g,this.tokenProvider,L)}this.userActivityState=_}return t.prototype.start=function(g){this.logger.info("Starting"),this.reconnectParams=g,"undefined"!=typeof window&&window.navigator&&window.addEventListener?(this.isNavigatorOnline=window.navigator.onLine,window.addEventListener("online",this.onNavigatorOnlineStatusUpdateBound),window.addEventListener("offline",this.onNavigatorOnlineStatusUpdateBound),this.logger.debug("Registered for browser online notifications - current state: ".concat(this.isNavigatorOnline))):this.isNavigatorOnline=!0,this.fsm.start()},t.prototype.stop=function(g){this.logger.info("Stopping"),"undefined"!=typeof window&&window.navigator&&(window.removeEventListener("online",this.onNavigatorOnlineStatusUpdateBound),window.removeEventListener("offline",this.onNavigatorOnlineStatusUpdateBound)),this.fsm.stop(g),this.connectionTracker.close()},t.prototype.configure=function(g){var f=this.options.trouterUrl!==g.trouterUrl;this.options=g,this.applyConnectionTrackerOptions(g),f&&(this.logger.info("Configuration changed. Reconnection required."),this.fsm.onReconnectRequired(!1,T.Configuration))},t.prototype.checkConnection=function(g){this.logger.info("checkConnection called with ".concat(g)),this.fsm.checkConnection(g),g&&this.connectionTracker.sendTelemetry(A.ClientEventName.CheckConnection,{disconnectDetected:g},[])},t.prototype.disableRegistrationsAndAutoReconnect=function(){this.stopRegistrationTimer(),this.cancelPendingRegistrationRequests(),this.fsm.disableAutoReconnect()},t.prototype.getServerState=function(){return new O.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:"",this.allocateResult?this.allocateResult.surl:"",this.c2cUrlBase,this.connectionExpireTimestampInSecs)},t.prototype.getState=function(){return this.fsm.getState()},t.prototype.getToken=function(g,f,S,v,C){var _=this;void 0===C&&(C=0),this.logger.info("Getting token ".concat(f?"with backoff":"without backoff"));var s=function(){_.connectionTracker.trackStart("token");var f={needFresh:!g,wwwAuthenticateHeader:S,supportedTokenTypes:P.SUPPORTED_TOKEN_TYPES,purpose:"trouter"};_.logger.info("Requesting token: needFresh=".concat(f.needFresh," ")+"types=[".concat(P.SUPPORTED_TOKEN_TYPES,"], ")+"wwwAuthenticateHeader is ".concat(f.wwwAuthenticateHeader?"non empty":"empty")),_.tokenProvider(f).then((function(g){_.logger.debug("".concat(g.tokenType," token is received")),_.connectionTracker.trackEnd("token"),_.fsm.onTokenReceived(g,v,_.reconnectParams)})).catch((function(f){var T=(0,b.toJson)(f.stack);if(_.logger.error("Getting token failed, will retry after timeout. Error: ".concat(T)),_.connectionTracker.trackError("token",T),!_.canRetryTokenFetchRequest(C+_.unauthorizedErrorCount))return _.connectionTracker.trackError("token","getToken retry limit hit, reached terminal error state"),_.resetTokenBackoff(),void _.fsm.onTerminalError();_.getToken(g,!0,S,v,C+1)}))};f?this.tokenBackoff.backoff("getting token",s):(this.resetTokenBackoff(),s())},t.prototype.startConnectionTimer=function(){var g=this;this.stopConnectionTimer(),this.logger.debug("Starting connection timeout for ".concat(this.timeoutOptions.connectionTimeoutMs," ms")),this.connectionTimeoutId=setTimeout((function(){g.logger.info("Connection timeout is fired"),g.fsm.onConnectingTimeout()}),this.timeoutOptions.connectionTimeoutMs)},t.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&(this.logger.debug("Stopping connection timeout"),clearTimeout(this.connectionTimeoutId),this.connectionTimeoutId=void 0)},t.prototype.startPingTimer=function(){var g=this;"websocket"===this.transportTypeName?(this.logger.debug("Starting ping timeout for ".concat(this.timeoutOptions.pingTimeoutMs," ms")),this.pingTimerId=setInterval((function(){g.logger.info("Ping interval fired"),g.fsm.onPingInterval()}),this.timeoutOptions.pingTimeoutMs)):this.logger.debug("Not starting ping for transport ".concat(this.transportTypeName))},t.prototype.stopPingTimer=function(){this.pingTimerId&&(this.logger.debug("Stopping ping timeout"),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),this.pingTimerId=void 0)},t.prototype.shouldSkipRegistration=function(){return void 0===this.options.registration},t.prototype.hasCustomRegistrationTtl=function(){var g,f;return void 0!==(null===(g=this.options.registration)||void 0===g?void 0:g.registrarTtlSec)&&0!==(null===(f=this.options.registration)||void 0===f?void 0:f.registrarTtlSec)},t.prototype.startRegistrationTimer=function(){var g=this;this.stopRegistrationTimer();var f=this.getRegistrationTtl(),S=f[0],v=f[1];if(S<=30||!v)return this.logger.debug("Starting registration expiration timer (TTL ".concat(S," sec)")),void(this.registrationTimerId=setTimeout((function(){g.registrationTimerId=void 0,g.logger.warn("Registration expired but the connection is still alive. Should never happen"),g.dispatchUnregistered()}),1e3*S));var C=S-30;this.logger.debug("Starting registration extension timer for ".concat(C," sec")),this.registrationTimerId=setTimeout((function(){g.logger.info("Registration extension timer fired"),g.registrationTimerId=setTimeout((function(){g.registrationTimerId=void 0,g.logger.debug("Registration extension did not happen in time"),g.dispatchUnregistered()}),3e4),g.fsm.onRegistrationNearExpiry()}),1e3*C)},t.prototype.startRegistrationRetryTimer=function(){var g=this;this.stopRegistrationTimer(),this.registrationTimerId=setTimeout((function(){g.registrationTimerId=void 0,g.fsm.onRetryRegistration()}),123e3)},t.prototype.stopRegistrationTimer=function(){this.registrationTimerId&&(this.logger.debug("Stopping registration timeout"),clearTimeout(this.registrationTimerId),this.registrationTimerId=void 0)},t.prototype.resendRegistration=function(){if(!this.registrarClient)throw new Error("Trouter Client not configured to handle registrations");return this.fsm.onResendRegistration(),Promise.resolve()},t.prototype.buildSocketIoUrlParams=function(g,f){if(!this.allocateResult)throw new Error("Allocate result is undefined in buildSocketIoUrlParams()");for(var S={},v=this.allocateResult.connectparams,C=0,_=Object.keys(v);C<_.length;C++){var T=_[C];if(void 0!==v[T]){var I=v[T];"string"==typeof I||"number"==typeof I?S[T]=I:this.logger.error("signatureData[".concat(T,"] has unsupported type ").concat(typeof I))}}return S.v="v4",S.tc=encodeURI((0,b.toJson)(this.clientInfo)),S.timeout=this.timeoutOptions.pingTimeoutMs/1e3,S.auth="true",this.options.endpointId&&(S.epid=this.options.endpointId),g&&(S.userActivity=encodeURIComponent((0,b.toJson)(g))),f&&(S.audienceSubscriptionState=encodeURIComponent((0,b.toJson)(f))),this.appendConnectedClientIds(this.buildQuery(S),!0)},t.prototype.startSocketIo=function(g){var f,S;if(this.logger.debug("Starting socket io"),this.connectionTracker.trackStart("connectSocket"),!this.allocateResult)throw new Error("Allocate result is undefined in startSocketIo()");var C=this.options.ioOptions?v({},this.options.ioOptions):new x,_=this.userActivityState.state!==w.UserActivityState.Unknown?this.userActivityState.increaseCvAndGetEventObject():void 0,T=null===(f=this.audienceSubscriptionState)||void 0===f?void 0:f.increaseCvAndGetEventObject();if(C["force new connection"]=!0,C.reconnect=!1,C.rewriteUrlForProxy=this.options.rewriteUrlForProxy,C.requestHeaders=v(v({},this.options.extraConnectionHeaders),o(g,this.usingLegacyTokenApi)),C.query=this.buildSocketIoUrlParams(_,T),this.logger.info("connecting to ".concat(this.allocateResult.socketio)),this.stopSocketIo(),this.socket=(null!==(S=this.options.io)&&void 0!==S?S:L).connect(this.allocateResult.socketio,C),void 0===this.socket)throw new Error("Can't create Socket.io object");this.attachSocketIoHandlers(this.socket,g,_,T)},t.prototype.stopSocketIo=function(){if(this.socket){this.logger.debug("clearing socket.io");try{for(var g=0,f=["connecting","connect","connect_failed","close_during_connecting","disconnect","reconnect","reconnect_failed","reconnecting","error","message","trouter.connected","trouter.reconnect","trouter.message_loss"];g<f.length;g++){var S=f[g];this.socket.removeAllListeners(S)}this.socket.disconnect(),this.logger.debug("cleared socket"),this.socket=void 0}catch(g){this.logger.error("exception in disconnecting previous socket. Error: ".concat(r(g)))}}},t.prototype.dispatchConnected=function(){this.logger.info("dispatching connected"),this.manager.onConnected(this)},t.prototype.dispatchRegistered=function(){this.logger.info("dispatching registered"),this.manager.onRegistered(this)},t.prototype.dispatchUnregistered=function(){this.logger.info("dispatching unregistered"),this.manager.onUnregistered(this)},t.prototype.dispatchDownstreamRequest=function(g){var f=this;this.logger.debug("dispatching downstream request");try{var S=new B(g,new A.ResponseData(g.id),(function(g,S){return f.logger.debug("sending response to downstream"),f.sendResponse(g,S)}));this.manager.onDownstreamRequest(this,g,S)}catch(g){this.logger.error("exception in socket.on message. Error : ".concat(r(g)))}},t.prototype.dispatchReconnecting=function(){this.logger.info("dispatching reconnecting"),this.manager.onReconnecting(this)},t.prototype.dispatchReconnectIsRequired=function(g,f){this.logger.info("dispatching reconnect is required by server"),this.manager.onReconnectIsRequired(this,g,f)},t.prototype.dispatchDisconnected=function(){this.logger.info("dispatching disconnected"),this.manager.onDisconnected(this)},t.prototype.dispatchTerminalError=function(){this.logger.info("dispatching terminal error"),this.manager.onTerminalError(this)},t.prototype.dispatchTrouterMessageLost=function(g){this.logger.info("dispatching trouter message lost"),this.manager.onTrouterMessageLost(g)},t.prototype.countDisconnectBeforeConnectionEstablishment=function(){this.logger.warn("counting disconnect before connection was fully established as a connection failure"),++this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()},t.prototype.sendProcessedDroppedIndicators=function(g){var f=this;try{this.logger.debug("emitting processed flow tags to the server");var S=new H("trouter.processed_message_loss");S.args={droppedIndicators:g},this.sendDownstreamEvent(S,(function(){f.logger.info("emitted processed flow tags to the server")}))}catch(g){var v=r(g);this.logger.error("unable to send processed message loss event. Error: ".concat(v)),this.connectionTracker.trackError("trouter.processed_message_loss",v,!1)}},t.prototype.sendAllocateRequest=function(g){var f=this;this.connectionAttempt++,this.connectionTracker.trackNewConnection();var S,C=this.options.trouterUrl,_=this.reconnectParams,T="string"==typeof(null==_?void 0:_.se)?parseInt(_.se,10):"number"==typeof(null==_?void 0:_.se)?_.se:void 0;T&&T<=Date.now()+36e5&&(this.logger.warn("Dropping expired cached connection parameters: ".concat(new Date(T))),this.reconnectParams=_=void 0),_&&_.serviceUrl!==C&&(this.logger.warn("Dropping cached connection parameters for a different environment (".concat(_.serviceUrl,", now ").concat(C,")")),this.reconnectParams=_=void 0),(null==_?void 0:_.reconnectUrl)&&(C=_.reconnectUrl),S=_?v(v({},_),{serviceUrl:void 0,reconnectUrl:void 0}):null,C=(0,N.adaptUrl)(C,"v4a"),C=this.appendCorrelationIds(C,!1);var I=C=this.appendEndpointId(C,!1);S&&(C+="&".concat(this.buildQuery(S)),S.v||(C+="&v=".concat("v4"))),C=this.options.rewriteUrlForProxy(C);var A=new Request(C,{method:"POST",mode:"cors",headers:new Headers(v(v({"Content-Type":"text/plain"},this.options.extraConnectionHeaders),o(g,this.usingLegacyTokenApi)))});this.logger.info("sendAllocateRequest: POST ".concat(this.options.rewriteUrlForProxy(I)," (connectparams redacted)}")),this.connectionTracker.trackStart("allocation");var P,R=Date.now(),M=-1,w=!1;(0,b.fetchWithTimeout)(A,this.timeoutOptions.fetchTimeoutMs).then((function(g){var S;if(M=g.status,!g.ok)throw P=null!==(S=g.headers.get("www-authenticate"))&&void 0!==S?S:void 0,w="1"===g.headers.get("x-trouter-skypetoken-deprecated"),f.logger.warn("Allocation request got response status ".concat(g.status,", www-authenticate header was ").concat(P?"not empty":"empty")),new Error(g.statusText);var v=g.headers.get("content-type");if(!v||"application/json"!==v&&!v.startsWith("application/json;"))throw new Error("Content-type '".concat(v,"' is unexpected"));return f.connectionTracker.trackEnd("allocation"),g.json()})).then((function(S){f.unauthorizedErrorCount=0,f.onAllocationResponse(S,g)})).catch((function(g){f.connectingErrorsInRow++;var S="".concat(g).concat(M>=0?", status code ".concat(M):"");if(f.logger.error("".concat(f.connectingErrorsInRow," failed connecting attempt(s) in a row. ").concat(S)),f.connectionTracker.trackError("allocation",S),w){var v="Skypetoken deprecated response, not retrying any further";return f.logger.error(v),f.connectionTracker.trackError("allocation",v),void f.fsm.onTerminalError()}if(401===M&&f.unauthorizedErrorCount++,!f.canRetryTokenFetchRequest(f.unauthorizedErrorCount))return v="getToken retry limit hit, reached terminal error state",f.connectionTracker.trackError("allocation",v),void f.fsm.onTerminalError();if(-1!==M||f.isNavigatorOnline){if(f.reconnectParams&&f.connectingErrorsInRow>=f.connectingErrorsThreshold)if(M>=400&&M<=599)f.resetReconnectParamsOnErrorThreshold();else if(f.reconnectParams.reconnectUrl&&f.connectingErrorsInRow%3==0){f.logger.warn("".concat(f.connectingErrorsInRow," connection attempts, testing nominal service URL"));var C=Math.min(f.timeoutOptions.connectionTimeoutMs-(Date.now()-R)-500,f.timeoutOptions.fetchTimeoutMs);return void f.testNominalUrlConnectivity(C).then((function(g){f.connectionTracker.trackProgress("nomcheck",g?"ok":"failed"),g?(f.logger.warn("Nominal service URL is reachable, erasing cached reconnect URL"),f.reconnectParams&&delete f.reconnectParams.reconnectUrl):f.logger.warn("Nominal service URL is not reachable either, keeping cached reconnect URL"),f.fsm.onAllocationFailed(!1,void 0)}),(function(){f.fsm.onAllocationFailed(!1,void 0)}))}}else f.logger.info("Expected failure, the browser says it is not online at the moment");f.fsm.onAllocationFailed(401===M,P)}))},t.prototype.testNominalUrlConnectivity=function(g){var f,S=this;if(g<1e3)return this.logger.warn("There is no time left to reasonably perform the nominal service URL connectivity check (".concat(g," ms), falling back to assuming that the connectivity is fine")),Promise.resolve(!0);try{var v=new URL(this.options.trouterUrl);v.pathname=v.pathname.replace(/\/v4\/.*/,"/"),v.search="?"+this.buildQuery({check:Date.now(),cor_id:encodeURIComponent(this.options.clientCorrelationID),epid:encodeURIComponent(this.options.endpointId?this.options.endpointId:""),tc:encodeURIComponent((0,b.toJson)(this.clientInfo))}),f=new Request(this.options.rewriteUrlForProxy(v.toString()),{method:"GET",headers:{Accept:"text/plain"}})}catch(g){return this.logger.warn("Nominal service URL connectivity test request could not be created (".concat(g,"), falling back to assuming that the connectivity is fine")),Promise.resolve(!0)}return(0,b.fetchWithTimeout)(f,g).then((function(g){if(200!==g.status)throw new Error("Not 200 OK: ".concat(g.status," ").concat(g.statusText));return g.text()})).then((function(g){if("Trouter"!==g)throw new Error('Not "Trouter": '.concat(g.substring(0,16)).concat(g.length>16?"...":""));return!0})).catch((function(g){return S.logger.error("Nominal service URL connectivity test failed: ".concat(g)),!1}))},t.prototype.sendPingRequest=function(){var g=this;if(this.socket&&void 0===this.pingResponseTimerId)try{this.logger.debug("emitting ping event");var f=!1;this.socket.emit("ping",(function(){!0!==f&&g.onPingResponse()})),this.pingResponseTimerId=setTimeout((function(){g.logger.error("Ping response timeout is fired"),f=!0,g.clearPingResponseTimer(),g.fsm.onPingResponseTimeout()}),this.timeoutOptions.pongTimeoutMs)}catch(g){var S=r(g);this.logger.error("unable to send ping. Error: ".concat(S)),this.connectionTracker.trackError("ping",S,!1)}},t.prototype.connectV4c=function(g,f){var S,T,I,b,A,P;return C(this,void 0,void 0,(function(){var C,R,M,w;return _(this,(function(_){switch(_.label){case 0:return[4,this.performV4cInitialConnectivityCheck()];case 1:if(!1===_.sent())return[2];(C=this.options.ioOptions?v({},this.options.ioOptions):new x)["force new connection"]=!0,C.reconnect=!1,(null===(S=this.reconnectParams)||void 0===S?void 0:S.serviceUrl)&&(0,N.adaptUrl)(this.reconnectParams.serviceUrl,"v4c")!==(0,N.adaptUrl)(this.options.trouterUrl,"v4c")&&(this.logger.warn("Dropping cached connection parameters for a different environment (".concat(this.reconnectParams.serviceUrl,", now ").concat(this.options.trouterUrl,")")),this.reconnectParams=void 0),R=null!==(b=null!==(T=(0,N.redirectUrlIfPresent)(f))&&void 0!==T?T:"redirect-no-host"!==(null==f?void 0:f.kind)?null===(I=this.reconnectParams)||void 0===I?void 0:I.reconnectUrl:void 0)&&void 0!==b?b:this.options.trouterUrl,M=(0,N.adaptUrl)(R,"v4c"),C["skipped handshake data"]={timeout:70,websocketUrl:M},C.query=this.buildV4cUrlParams(),C.rewriteUrlForProxy=this.options.rewriteUrlForProxy;try{if(this.stopSocketIo(),this.transportTypeName="websocket",this.socket=(null!==(A=this.options.io)&&void 0!==A?A:L).connect(this.options.trouterUrl,C),void 0===this.socket)throw new Error("failed to create Socket.io object");w=null===(P=this.audienceSubscriptionState)||void 0===P?void 0:P.increaseCvAndGetEventObject(),this.attachSocketIoHandlers(this.socket,g,void 0,w)}catch(g){this.logger.error("".concat(g)),this.connectionTracker.trackError("v4c","".concat(g)),this.fsm.onV4cException()}return[2]}}))}))},t.prototype.performV4cInitialConnectivityCheck=function(){return C(this,void 0,void 0,(function(){return _(this,(function(g){switch(g.label){case 0:return this.options.initialConnectivityCheck?(this.logger.info("checking connectivity to configured URL (go URL) before a connection attempt"),[4,this.testNominalUrlConnectivity(3e3)]):[2,!0];case 1:return g.sent()?(this.connectivityCheckFailuresInARow=0,[2,!0]):this.connectivityCheckFailuresInARow>=3?(this.connectivityCheckFailuresInARow=0,this.logger.error("three connectivity checks failed in a row, will attempt with the fallback protocol"),this.fsm.onV4cException(),[2,!1]):(this.logger.warn("connectivity check failed, will retry after backoff"),this.connectivityCheckFailuresInARow++,this.fsm.onV4cConnectivityCheckFailed(),[2,!1])}}))}))},t.prototype.sendV4cAuthenticationEvent=function(g){var f,S={headers:v(v({},this.options.extraConnectionHeaders),o(g,this.usingLegacyTokenApi)),connectparams:(0,N.reconnectParamsWithoutUrls)(this.reconnectParams)};null===(f=this.socket)||void 0===f||f.emit(P.USER_AUTHENTICATE_EVENT_NAME,S)},t.prototype.setUserActivityState=function(g){var f=g.state!==this.userActivityState.state;this.userActivityState=g,f?(this.logger.info("Changing user activity state to '".concat(g.toEventJSON(),"'")),this.fsm.onSetNewUserActivityState()):(this.logger.debug("Not changing the same user activity state '".concat(g.toEventJSON(),"'")),this.manager.onUserActivityStateAccepted(g.correlationVector.value()))},t.prototype.sendUserActivityState=function(g,f){if(this.userActivityState.state!==w.UserActivityState.Unknown){if(this.options.updateUserActivityDuringConnectionAttempt&&this.socket){var S=this.userActivityState.toEventObject(),v=this.socket.socket.options.query;if(v){var C="userActivity=".concat(encodeURIComponent((0,b.toJson)(S)));-1==v.search(this.USER_ACTIVITY_QUERY_PARAM_REGEX)?this.socket.socket.options.query=v.concat("&",C):this.socket.socket.options.query=v.replace(this.USER_ACTIVITY_QUERY_PARAM_REGEX,C)}}"websocket"===this.transportTypeName&&f?g===O.UserActivityEventReason.Connected?this.sendUserActivityStateMultiple(2):this.sendUserActivityStateMultiple(1):"xhr-polling"===this.transportTypeName&&g===O.UserActivityEventReason.Modified&&this.fsm.forceReconnect("user activity/force reconnect")}},t.prototype.setAudienceSubscriptionsAsync=function(g,f){var S=this.audienceSubscriptionState;if(this.audienceSubscriptionState=g,this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME)return this.setAudienceSubscriptionsInternalAsync(g.increaseCvAndGetEventObject(),f);if(this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var v=this.setAudienceSubscriptionsLongpollInternalAsync(g.increaseCvAndGetEventObject(),f,S);return this.fsm.forceReconnect("set audience subscription force reconnect"),v}throw new Error("set audience subscription executed on an unknown transport")},t.prototype.setAudienceSubscriptionsUnsafeAsync=function(g){if(g)return this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?this.setAudienceSubscriptionsInternalAsync(g,15e3):void 0},t.prototype.setAudienceSubscriptionsInternalAsync=function(g,f){return C(this,void 0,void 0,(function(){var S,v,C=this;return _(this,(function(_){switch(_.label){case 0:return this.logger.info("[WebSocket] Audience subscription set requested."),(S=new H("audience.subscribe")).args=g,[4,new Promise((function(v){var _=!1,T=setTimeout((function(){return _=!0,v(C.buildAudienceSubscriptionsTimeoutResponse(g))}),f);C.sendDownstreamEvent(S,(function(g,f){_||(clearTimeout(T),C.logger.debug("[Websocket] Audience subscription response: ".concat(f)),C.pendingAudienceSubscription&&C.onAudienceSubscriptionResult(f),v(f))}))}))];case 1:return v=_.sent(),this.manager.onAudiencesSetResolved(v,g.cv),[2,v]}}))}))},t.prototype.setAudienceSubscriptionsLongpollInternalAsync=function(g,f,S){var v;return C(this,void 0,void 0,(function(){var C,T,I,b,A,P,R=this;return _(this,(function(_){switch(_.label){case 0:return this.logger.info("[XHR Polling] Audience subscription set requested."),this.pendingAudienceSubscription&&(this.logger.error("Racing audience subscriptions occured. This situation resolves into undefined scenario and/or nasal demons."),clearTimeout(this.pendingAudienceSubscription.timeoutId)),0===g.audiences.length?[2,this.handleAudienceUnsubscribeLongpoll(g.cv,S)]:[4,new Promise((function(S){var v=setTimeout((function(){return R.pendingAudienceSubscription=void 0,S(R.buildAudienceSubscriptionsTimeoutResponse(g))}),f);R.pendingAudienceSubscription={audienceSetResolve:S,timeoutId:v}}))];case 1:return C=_.sent(),this.manager.getState()===w.TrouterState.Unknown||this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?[2,C]:(null==(T=C.responses[0])?void 0:T.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST?(this.clearAudienceSubscriptionStateQueryParam(),this.manager.onAudiencesSetResolved(C,g.cv),[2,C]):(I=C.responses.find((function(f){return f.audienceId===g.audiences[0].id})),(null==I?void 0:I.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR?(this.clearAudienceSubscriptionStateQueryParam(),this.manager.onAudiencesSetResolved(C,g.cv),[2,C]):(b=(null===(v=null==S?void 0:S.audienceSubscriptionModel.audienceSubscriptions[0])||void 0===v?void 0:v.id)!==(null==T?void 0:T.audienceId),S&&b&&(A=this.mapToSyntheticAudienceSubscriptionResponses(S.audienceSubscriptionModel.audienceSubscriptions,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200),(P=C.responses).push.apply(P,A)),this.manager.onAudiencesSetResolved(C,g.cv),[2,C]))}}))}))},t.prototype.clearAudienceSubscriptionStateQueryParam=function(){var g,f,S;(null===(S=null===(f=null===(g=this.socket)||void 0===g?void 0:g.socket)||void 0===f?void 0:f.options)||void 0===S?void 0:S.query)&&(this.socket.socket.options.query=this.socket.socket.options.query.replace(this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX,""))},t.prototype.handleAudienceUnsubscribeLongpoll=function(g,f){var S;this.audienceSubscriptionState=void 0;var v={responses:[]};if(f){var C=this.mapToSyntheticAudienceSubscriptionResponses(f.audienceSubscriptionModel.audienceSubscriptions,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200);(S=v.responses).push.apply(S,C)}return this.manager.onAudiencesSetResolved(v,g),v},t.prototype.buildAudienceSubscriptionsTimeoutResponse=function(g){return this.logger.error("Audience subscription attempt has timed out."),{responses:this.mapToSyntheticAudienceSubscriptionResponses(g.audiences,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT)}},t.prototype.mapToSyntheticAudienceSubscriptionResponses=function(g,f,S){return g.map((function(g){return{audienceId:g.id,result:{audienceSubscriptionState:f,responseStatus:S}}}))},t.prototype.expediteBackoff=function(){this.tokenBackoff.expediteIfPending()},t.prototype.sendRegisterRequest=function(){var g=this;if(!this.options.registration||!this.registrarClient)throw new Error("Internal error - options.registration is undefined");if(!this.allocateResult)throw new Error("Allocate result is undefined in sendRegisterRequest()");this.logger.info("sending register request");var f=new b.Timespan;this.connectionTracker.trackStart("registration");var S=this.getRegistrationTtl()[0];this.registrarClient.register({appId:this.options.registration.pnhAppId,aesKey:"",languageId:"en-US",platform:this.options.registration.platform,templateKey:this.options.registration.pnhTemplateKey,platformUIVersion:this.options.registration.platformUIVersion,productContext:this.options.registration.productContext},{TROUTER:[{context:this.options.registration.context,path:this.allocateResult.surl,ttl:S}]}).then((function(){g.logger.info("Register request successful"),g.connectionTracker.trackEnd("registration"),g.fsm.onRegistrationSucceeded(),g.connectionTracker.sendTelemetry(A.ClientEventName.Registration,{duration:f.duration},[])})).catch((function(S){g.logger.error("Register request failed. Error: ".concat(S)),g.connectionTracker.trackError("registration",s(S)),g.fsm.onRegistrationFailed(),g.connectionTracker.sendTelemetry(A.ClientEventName.Registration,{duration:f.duration},[])}))},t.prototype.sendUnregisterRequest=function(){var g=this;this.logger.info("sending unregister request");var f=new b.Timespan;if(!this.options.registration||!this.registrarClient)throw new Error("Internal error - options.registration is undefined");this.connectionTracker.trackStart("unregistration"),this.registrarClient.unregister().then((function(){g.logger.info("Unregister request successful"),g.connectionTracker.trackEnd("unregistration"),g.fsm.onUnregistrationDone(),g.connectionTracker.sendTelemetry(A.ClientEventName.Unregistration,{duration:f.duration},[])})).catch((function(S){g.logger.error("Unregister request failed. Error: ".concat(S)),g.connectionTracker.trackError("unregistration",s(S)),g.fsm.onUnregistrationDone(),g.connectionTracker.sendTelemetry(A.ClientEventName.Unregistration,{duration:f.duration},[])}))},t.prototype.resetTokenBackoff=function(){this.tokenBackoff.reset()},t.prototype.cancelPendingRegistrationRequests=function(){this.registrarClient&&this.registrarClient.cancelPendingRequests()},t.prototype.clearSentEventTimers=function(){var g=Object.keys(this.pendingSentEventTimers);if(g.length>0){this.logger.debug("Clearing all pending downstream events related timers");for(var f=0,S=g;f<S.length;f++){var v=S[f];this.clearSentEventTimer(Number(v))}}},t.prototype.restartIncallModeTimer=function(){var g=this;this.clearIncallModeTimerId(),this.logger.debug("Restarting incall mode timer"),this.incallModeTimerId=setTimeout((function(){g.logger.info("Call mode timer fired"),g.fsm.onIncallModeTimer()}),this.options.incallModeTimeoutMs)},t.prototype.enterIncallMode=function(){this.logger.info("Entering incall mode"),this.timeoutOptions=this.options.incallTimeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!0},t.prototype.exitIncallMode=function(){this.logger.info("Exiting incall mode"),this.clearIncallModeTimerId(),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!1},t.prototype.isIncallMode=function(){return this.inIncallMode},t.prototype.sendDisconnectTelemetryEvent=function(g){var f={reason:g,serverClosed:!this.fsm.isActive()};this.connectionTracker.trackDisconnected(f),this.connectionTracker.clearConnectedInfo()},t.prototype.forceReconnectDueToNoRegistration=function(){this.fsm.forceReconnect("force reconnect due to no registration")},t.prototype.resetReconnectParamsOnErrorThreshold=function(){this.logger.warn("".concat(this.connectingErrorsInRow," connection attempts, server-side failure: erasing cached connection parameters")),this.reconnectParams=void 0},t.prototype.onSocketConnecting=function(g){this.logger.info("onSocketConnecting(".concat(g,")")),this.transportTypeName=g,this.connectionTracker.trackProgress("connecting",this.transportTypeName),this.fsm.onConnecting()},t.prototype.onSocketConnect=function(g){this.logger.info("onSocketConnect"),this.fsm.onSocketConnect(g)},t.prototype.onSocketConnectFailed=function(g){this.logger.error("onSocketConnectFailed"),this.connectionTracker.trackError("connect_failed",g,!0,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onConnectingFailed()},t.prototype.onSocketDisconnect=function(g){var f=this.connectionTracker.getSessionLength()||0,S=R.DisconnectReason.fromRawReason(g);this.logger.error("onSocketDisconnect, reason: ".concat(S.reason)),"dup"===S.reason&&"dup"===this.lastDisconnectReason&&f<this.options.duplicateDisconnectThresholdMs&&(this.logger.warn("Socket was closed by server as Duplicate for the second time in a row "+"after ".concat(f," ms which is below the threshold of ")+"".concat(this.options.duplicateDisconnectThresholdMs," ms. Resetting cached ")+"connection parameters and making a new allocation."),this.reconnectParams=void 0),this.lastDisconnectReason=S.reason,this.fsm.onSocketDisconnect(S),this.connectionExpireTimestampInSecs=void 0},t.prototype.onSocketReconnect=function(){this.logger.error("onSocketReconnect"),this.fsm.onTrouterConnected()},t.prototype.onSocketReconnectFailed=function(g){this.logger.error("onSocketReconnectFailed with '".concat(g,"'")),this.fsm.onSocketDisconnect(R.DisconnectReason.fromSocketIoEventData("reconnecterror",g))},t.prototype.onSocketReconnecting=function(){this.logger.error("onSocketReconnecting")},t.prototype.onSocketError=function(g){this.logger.error("onSocketError with '".concat((0,b.toJson)(g),"'")),this.fsm.isConnecting()&&++this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold(),this.connectionTracker.trackError("connectSocket",i(g)),this.fsm.onSocketDisconnect(R.DisconnectReason.fromSocketIoEventData("socketerror",g))},t.prototype.onSocketMessage=function(g){var f,S,v=this;this.logger.debug("onSocketMessage");try{var C=null===(f=(S=new V(g,this.logger)).headers)||void 0===f?void 0:f["X-Microsoft-Skype-Chain-ID"],_=C?" Chain-Id ".concat(C):"";this.logger.info("Received request N ".concat(S.id).concat(_," CV ").concat(S.correlationVector," to '").concat(S.url,"'")),S.startTS=Date.now(),S.url&&this.urlPath&&S.url.startsWith(this.urlPath)&&(S.shortUrl=S.url.substring(this.urlPath.length))}catch(g){var T=r(g);return this.logger.error("unable to parse request. Error: ".concat(T)),this.connectionTracker.trackRequest(void 0,T),void this.connectionTracker.sendResponseError("unable to parse request, error: ".concat(g))}S.timeoutTimerId=setTimeout((function(){if(!S.replied){v.logger.error("Request ".concat(S.id," timed out"));var g=new A.ResponseData(S.id);g.status=504,g.headers={"Trouter-Responder":"ClientLib"},v.sendResponse(S,g),S.timedout=!0}}),this.timeoutOptions.requestTimeoutMs);try{this.connectionTracker.trackRequest(S),this.fsm.onDownstreamRequest(S)}catch(g){this.logger.error("exception in socket.on message. Error: ".concat(r(g))),this.connectionTracker.sendResponseError(s(g),S,void 0)}},t.prototype.onTrouterConnected=function(g,f,S){var C,_,T,I,A,P=this;if((0,N.isV4ConnectEvent)(g)){var R=g;this.allocateResult=v(v({},R),{ttl:g.ttl.toString()}),this.populateAndCacheReconnectParams(R,R.reconnectUrl),this.populateConnectionStateFields(R)}else if(!this.allocateResult)return void this.logger.error("Invalid internal state - received onTrouterConnected while allocateResult is not set");this.connectingErrorsInRow=0,this.logger.info("onTrouterConnected: ".concat(this.allocateResult.surl)),this.options.updateUserActivityDuringConnectionAttempt?"xhr-polling"===this.transportTypeName&&((null!==(C=null==f?void 0:f.state)&&void 0!==C?C:"unknown")!==this.userActivityState.getStateString()?(this.logger.info("XHR user activity changed during connection attempt, from '".concat((0,b.toJson)(f),"' to '").concat(this.userActivityState.toEventJSON(),"', updating")),this.sendUserActivityStateIgnoreResponse()):f&&this.manager.onUserActivityStateAccepted(f.cv)):"xhr-polling"===this.transportTypeName&&f&&this.manager.onUserActivityStateAccepted(f.cv),(null===(I=null===(T=null===(_=this.socket)||void 0===_?void 0:_.socket)||void 0===T?void 0:T.options)||void 0===I?void 0:I.query)&&(this.socket.socket.options.query+="&connected=true"),this.urlPath=this.allocateResult.surl.replace(/https?:\/\/([A-z0-9\:\$\-\_\.\+\!\*\"\(\)\,]*)\//,"/");var M=this.connectedUrl!==this.allocateResult.surl;this.connectedUrl=this.allocateResult.surl,this.connectionExpireTimestampInSecs=(0,b.calculateExpireTsInSec)((0,N.ensureNumber)(g.ttl)),this.connectionTracker.trackEnd("connectSocket"),this.connectionTracker.trackConnected(M,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),null===(A=this.setAudienceSubscriptionsUnsafeAsync(S))||void 0===A||A.catch((function(g){return P.logger.error("Re-subscribe to audiences has failed with ".concat(g))})),this.fsm.onTrouterConnected()},t.prototype.onTrouterReconnect=function(g){var f=g.target;this.logger.info("onTrouterReconnect target: ".concat(f)),"self"===f?this.fsm.onReconnectRequired(!0,T.ServerInitiated):this.fsm.onReconnectRequired(!1,T.ServerInitiated,g)},t.prototype.onTrouterMessageLoss=function(g){this.logger.debug("onTrouterMessageLoss"),this.fsm.onTrouterMessageLost(g.droppedIndicators)},t.prototype.onAudienceSubscriptionResult=function(g){this.logger.info("onAudienceSubscriptionResult"),this.pendingAudienceSubscription&&(clearTimeout(this.pendingAudienceSubscription.timeoutId),this.pendingAudienceSubscription.audienceSetResolve(g),this.pendingAudienceSubscription=void 0)},t.prototype.buildV4cUrlParams=function(){var g={};return g.tc=encodeURI((0,b.toJson)(this.clientInfo)),g.timeout=Math.floor(this.timeoutOptions.pingTimeoutMs/1e3),this.options.endpointId&&(g.epid=this.options.endpointId),this.appendConnectedClientIds(this.buildQuery(g),!0)},t.prototype.attachSocketIoHandlers=function(g,f,S,v){var C=this;g.on("connecting",(function(g){C.onSocketConnecting(g)})),g.on("connect",(function(){C.onSocketConnect(f)})),g.on("connect_failed",(function(g){C.onSocketConnectFailed(g)})),g.on("close_during_connecting",(function(g){C.onSocketConnectFailed(g)})),g.on("disconnect",(function(g){C.onSocketDisconnect(g)})),g.on("reconnect",(function(){C.onSocketReconnect()})),g.on("reconnect_failed",(function(g){C.onSocketReconnectFailed(g)})),g.on("reconnecting",(function(){C.onSocketReconnecting()})),g.on("error",(function(g){C.onSocketError(g)})),g.on("message",(function(g){C.onSocketMessage(g)})),g.on("trouter.connected",(function(g){C.onTrouterConnected(g,S,v)})),g.on("trouter.reconnect",(function(g){C.onTrouterReconnect(g)})),g.on("trouter.message_loss",(function(g){C.onTrouterMessageLoss(g)})),g.on("audience.subscriptionresult",(function(g,f){C.onAudienceSubscriptionResult(f)}))},t.prototype.onNavigatorOnlineStatusUpdate=function(){var g=window.navigator.onLine;this.logger.debug("Browser online status update - new state: ".concat(g,", previously: ").concat(this.isNavigatorOnline)),g&&!this.isNavigatorOnline?(this.isNavigatorOnline=!0,this.tokenBackoff.expediteIfPending(),this.connectionTracker.trackProgress("browserNet","online")):!g&&this.isNavigatorOnline&&(this.isNavigatorOnline=!1,this.connectionTracker.trackProgress("browserNet","offline"))},t.prototype.onAllocationResponse=function(g,f){this.logger.info("Received allocation response ".concat(JSON.stringify(v(v({},g),{connectparams:void 0}))," (connectparams redacted)")),this.allocateResult=g,this.populateAndCacheReconnectParams(this.allocateResult,"".concat(this.allocateResult.socketio,"v4/a")),this.populateConnectionStateFields(this.allocateResult),this.fsm.onAllocationSucceed(f)},t.prototype.populateAndCacheReconnectParams=function(g,f){this.reconnectParams=v({serviceUrl:this.options.trouterUrl,reconnectUrl:f},g.connectparams),this.manager.onConnectionParametersUpdated(this.reconnectParams)},t.prototype.populateConnectionStateFields=function(g){var f,S,v="string"==typeof g.ttl?parseInt(g.ttl,10):g.ttl;if(this.connectionExpireTimestampInSecs=(0,b.calculateExpireTsInSec)(v),this.connectionId=null!==(f=g.id)&&void 0!==f?f:"",this.connectedClientId=g.ccid,this.logger.debug("connected client id set {connectedClientId:".concat(this.connectedClientId,"}")),this.c2cUrlBase=null!==(S=g.curlb)&&void 0!==S?S:"",""===this.c2cUrlBase){var C=g.surl.indexOf("://");C>=0&&(C=g.surl.indexOf("/",C+3))>=5&&":3443"===g.surl.substr(C-5,5)&&(this.c2cUrlBase=g.surl.substr(0,C-5))}},t.prototype.onPingResponse=function(){this.logger.debug("onPingResponse"),this.connectionTracker.increasePingResponseCount(),this.clearPingResponseTimer(),this.fsm.onPingResponse()},t.prototype.clearPingResponseTimer=function(){void 0!==this.pingResponseTimerId&&(clearTimeout(this.pingResponseTimerId),this.pingResponseTimerId=void 0)},t.prototype.buildQuery=function(g){for(var f=[],S=0,v=Object.keys(g);S<v.length;S++){var C=v[S];void 0!==g[C]&&f.push("".concat(C,"=").concat(g[C]))}return f.join("&")},t.prototype.appendConnectedClientIds=function(g,f){var S="";g.includes("ccid=")||(S="ccid=".concat(this.connectedClientId,"&")),this.domId&&(S+="dom=".concat(this.domId,"&")),S.length>0&&(S=S.slice(0,-1));var v=f||g.includes("?")?"&":"?";return this.appendCorrelationIds(g+v+S,f)},t.prototype.appendEndpointId=function(g,f){var S=f||g.includes("?")?"&":"?";return!g.includes("epid")&&this.options.endpointId?"".concat(g).concat(S,"epid=").concat(this.options.endpointId):g},t.prototype.appendCorrelationIds=function(g,f){var S=f||g.includes("?")?"&":"?";return g.includes("cor_id")?g:"".concat(g).concat(S,"cor_id=").concat(this.options.clientCorrelationID)+"&con_num=".concat(this.clientID,"_").concat(this.connectionAttempt)},t.prototype.safeString=function(g){return"string"==typeof g?g:""},t.prototype.sendResponse=function(g,f){var S,v,C;if(g.timedout)return this.logger.error("Request ".concat(g.id," already timed out")),1;if(g.replied)return this.logger.error("Response for request ".concat(g.id," already sent")),2;clearTimeout(g.timeoutTimerId),g.timeoutTimerId=void 0,g.replied=!0,f.headers=null!==(S=f.headers)&&void 0!==S?S:{};var _=g.correlationVector;this.logger.info("Sending response N ".concat(g.id," CV ").concat(_," with status ").concat(f.status)),_&&(f.headers[U]=_),(null===(v=g.headers)||void 0===v?void 0:v["trouter-request"])&&(f.headers["trouter-request"]=g.headers["trouter-request"]);var T=Date.now()-g.startTS;if(f.headers["trouter-client"]=(0,b.toJson)({cd:T}),(null===(C=g.headers)||void 0===C?void 0:C["trouter-is-broadcast"])&&(f.headers["trouter-is-broadcast"]=g.headers["trouter-is-broadcast"]),!this.socket)return this.connectionTracker.sendResponseError("no socket",g,f),4;try{return this.socket.send((0,b.toJson)(f)),f.sentTS=Date.now(),g.incrementCorrelationVector(),this.connectionTracker.trackResponse(g,T,f),"websocket"===this.transportTypeName&&this.sendPingRequest(),0}catch(S){var I="unable to send data on response.end. Error: ".concat(r(S));return this.logger.error(I),this.connectionTracker.sendResponseError(I,g,f),4}},t.prototype.sendUserActivityStateMultiple=function(g){var f=this,S=new H("user.activity"),v=this.userActivityState.increaseCvAndGetEventObject();S.args=v,this.logger.debug("Sending user activity '".concat(this.userActivityState.toEventJSON(),"', remaining ").concat(g-1));var C=!1;this.sendDownstreamEvent(S,(function(){if(!0!==C&&(f.logger.info("User activity state: ".concat(v.state,", cv: ").concat(v.cv," accepted")),f.manager.onUserActivityStateAccepted(v.cv),f.clearSentEventTimer(S.timeoutTimerId),g>1)){var _=setTimeout((function(){f.clearSentEventTimer(_),f.sendUserActivityStateMultiple(g-1)}),f.options.userActivitySecondResendDelayMs);f.registerSentEventTimer(_,"user.activity/resend")}})),S.timeoutTimerId=setTimeout((function(){f.logger.error("Activity state response timeout is fired"),C=!0,f.fsm.onActivityStateResponseTimeout(),f.clearSentEventTimer(S.timeoutTimerId)}),this.timeoutOptions.userActivityResponseTimeoutMs),this.registerSentEventTimer(S.timeoutTimerId,"user.activity/response")},t.prototype.sendUserActivityStateIgnoreResponse=function(){var g=new H("user.activity"),f=this.userActivityState.toEventObject();g.args=f,this.socket&&(this.logger.info("Sending user activity after XHR connect, ".concat(f.state,", cv: ").concat(f.cv,", treating it as accepted")),this.socket.emit(g.name,g.args),this.manager.onUserActivityStateAccepted(f.cv))},t.prototype.sendDownstreamEvent=function(g,f){this.logger.debug("Sending downstream event ".concat(g.name)),this.socket&&this.socket.emit(g.name,g.args,f)},t.prototype.registerSentEventTimer=function(g,f){this.logger.debug("registering timer ".concat(g," -> ").concat(f)),this.pendingSentEventTimers[g]=f},t.prototype.clearSentEventTimer=function(g){var f=this.pendingSentEventTimers[g];this.logger.debug("clearing timer ".concat(g," -> ").concat(f)),delete this.pendingSentEventTimers[g],clearTimeout(g)},t.prototype.getRegistrationTtl=function(){var g,f,S=(0,b.calculateTtlInSec)(this.connectionExpireTimestampInSecs);if(this.logger.debug("Current connectionID will expire in ".concat(S," seconds")),(null===(g=this.options.registration)||void 0===g?void 0:g.registrarTtlSec)&&S>0){var v=this.options.registration.registrarTtlSec<S;return[Math.min(this.options.registration.registrarTtlSec,S),v]}return(null===(f=this.options.registration)||void 0===f?void 0:f.registrarTtlSec)?[this.options.registration.registrarTtlSec,!1]:S>0?[S,!1]:[3600,!1]},t.prototype.clearIncallModeTimerId=function(){void 0!==this.incallModeTimerId&&(this.logger.debug("Clearing in-call mode timer"),clearTimeout(this.incallModeTimerId),this.incallModeTimerId=void 0)},t.prototype.applyConnectionTrackerOptions=function(g){try{g.eventLogger&&"function"==typeof g.eventLogger.logEvent?(this.connectionTracker.mergeSettings(g.telemetrySettings),this.connectionTracker.enable(g.eventLogger)):this.logger.warn("Trouter client event logging disabled due to invalid configuration.")}catch(g){this.logger.warn("Trouter client event logging disabled. Error: ".concat(r(g))),this.connectionTracker.disable()}},t.prototype.canRetryTokenFetchRequest=function(g){var f=this.options.retryLimitOnTokenFetch;return null==f||g<f||(this.logger.warn("Reached limit on maximum number of token fetch request. Current count: ".concat(g,", retry limit: ").concat(f)),!1)},t}();f.TrouterConnection=$},function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.MessageHandlerRegistry=void 0;var v=S(1),C=S(0),_=function(){function t(g){this.messageHandlers=[],this.logger=new C.Logger("MessageHandlers",g)}return t.prototype.register=function(g){if(this.messageHandlers.some((function(f){return f===g})))throw new Error("Registering the same handler twice is not allowed");this.messageHandlers.push(g)},t.prototype.clear=function(){this.logger.debug("Clearing message handlers"),this.messageHandlers=[]},t.prototype.active=function(){return this.messageHandlers.length>0},t.prototype.handleMessage=function(g){for(var f={resultCode:v.UNHANDLED_MESSAGE_ACK,isHandled:!1},S=0,C=this.messageHandlers;S<C.length;S++){var _=C[S],T=this.safeExecuteHandle(_,g);if(void 0!==T&&(void 0===T.isHandled||T.isHandled))return void 0===T.resultCode&&(T.resultCode=v.HANDLED_MESSAGE_ACK),T}return f},t.prototype.safeExecuteHandle=function(g,f){try{return g.handleMessage(f)}catch(g){return void this.logger.warn("Trouter message handler threw an exception: ".concat(g))}},t}();f.MessageHandlerRegistry=_},function(g,f,S){function o(g){var f,S=this;return function(_){return v(S,void 0,void 0,(function(){return C(this,(function(S){return _&&(f=void 0),[2,new Promise((function(S,v){g(_).then((function(g){f=g,S(g)})).catch((function(g){void 0!==f&&f.length>0&&S(f),v(g)}))}))]}))}))}}var v=this&&this.__awaiter||function(g,f,S,v){function i(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function s(g){try{a(v.next(g))}catch(g){C(g)}}function c(g){try{a(v.throw(g))}catch(g){C(g)}}function a(g){g.done?S(g.value):i(g.value).then(s,c)}a((v=v.apply(g,f||[])).next())}))},C=this&&this.__generator||function(g,f){function n(g){return function(f){return o([g,f])}}function o(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!(C=(C=T.trys).length>0&&C[C.length-1])&&(6===I[0]||2===I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_};Object.defineProperty(f,"__esModule",{value:!0}),f.addCacheAsBackupTo=void 0,f.addCacheAsBackupTo=o},function(g,f,S){var v=this&&this.__awaiter||function(g,f,S,v){function i(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function s(g){try{a(v.next(g))}catch(g){C(g)}}function c(g){try{a(v.throw(g))}catch(g){C(g)}}function a(g){g.done?S(g.value):i(g.value).then(s,c)}a((v=v.apply(g,f||[])).next())}))},C=this&&this.__generator||function(g,f){function n(g){return function(f){return o([g,f])}}function o(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!(C=(C=T.trys).length>0&&C[C.length-1])&&(6===I[0]||2===I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_};Object.defineProperty(f,"__esModule",{value:!0}),f.TrouterManager=f.AudienceSubscriptionState=f.UserActivityObject=void 0;var _=S(3),T=S(2),I=S(4),b=S(0),A=S(5),P=S(18),R=S(7),M=S(6),w=S(19),O=function(){function t(g,f){this.state=g,this.correlationVector=void 0!==f?f:_.CorrelationVector.extend()}return t.prototype.getStateString=function(){switch(this.state){case T.UserActivityState.Active:return"active";case T.UserActivityState.Inactive:return"inactive";case T.UserActivityState.Unknown:return"unknown";default:return"undefined"}},t.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},t.prototype.toEventObject=function(){return{state:this.getStateString(),cv:this.correlationVector.value()}},t.prototype.toEventJSON=function(){return(0,_.toJson)(this.toEventObject())},t}();f.UserActivityObject=O;var D=function(){function t(g,f){void 0===f&&(f=_.CorrelationVector.extend()),this.audienceSubscriptionModel=g,this.correlationVector=f}return t.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},t.prototype.toEventObject=function(){return{audiences:this.audienceSubscriptionModel.audienceSubscriptions,cv:this.correlationVector.value()}},t.prototype.toEventJSON=function(){return(0,_.toJson)(this.toEventObject())},t}();f.AudienceSubscriptionState=D;var N=function(){function t(g,f,S,v,C,I){var P=this;this.logFunc=g,this.options=f,this.tokenProvider=S,this.usingLegacyTokenApi=v,this.listener=C,this.tokenTypeProtocolSelector=function(g,f){return P.options.forceV4aProtocol?"v4a":(0,A.usedProtocol)(g,f)},this.logger=new b.Logger("Manager",g),this.logger.info("Created TrouterManager with options ".concat((0,_.toJson)(this.options))),this.fsm=new w.TrouterManagerFsm(g,this),this.baseEndpointUrl="",this.processedMessageLoss={},this.userActivityObject=new O(T.UserActivityState.Unknown),this.protocolSelector=null!=I?I:this.tokenTypeProtocolSelector.bind(this)}return t.prototype.start=function(){this.fsm.start()},t.prototype.stop=function(g){this.fsm.stop(g)},t.prototype.configure=function(g){this.options=g,void 0!==this.firstConnection&&this.firstConnection.configure(g),void 0!==this.secondConnection&&this.secondConnection.configure(g),this.logger.info("Reconfigured TrouterManager with options ".concat((0,_.toJson)(this.options)))},t.prototype.checkConnection=function(g){void 0!==this.firstConnection&&this.firstConnection.checkConnection(g),void 0!==this.secondConnection&&this.secondConnection.checkConnection(g)},t.prototype.resendRegistration=function(){return v(this,void 0,void 0,(function(){return C(this,(function(g){return void 0!==this.secondConnection?(this.logger.info("Resending registration on the second/new connection"),[2,this.secondConnection.resendRegistration()]):void 0!==this.firstConnection?(this.logger.info("Resending registration on the first/current connection"),[2,this.firstConnection.resendRegistration()]):(this.logger.info("No connection to resend registration on, will be done upon (re)connect"),[2])}))}))},t.prototype.getServerState=function(){if(void 0!==this.firstConnection)return this.firstConnection.getServerState()},t.prototype.getState=function(){return this.fsm.getState()},t.prototype.isInTerminalState=function(){return this.fsm.getInternalState()===I.TrouterManagerState.TerminalError},t.prototype.reportStateInfo=function(){var g=this.firstConnection?M.State[this.firstConnection.getState()]:"Unknown",f=I.TrouterManagerState[this.fsm.getInternalState()];if(this.secondConnection){var S=M.State[this.secondConnection.getState()];return"Manager ".concat(f,"; 1st ").concat(g,"; 2nd ").concat(S)}return"Manager ".concat(f,"; Connection ").concat(g)},t.prototype.startFirstConnection=function(){var g=new R.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.firstConnection=g,this.getConnectionCache().then((function(f){g.start(f)})).catch((function(){}))},t.prototype.startSecondConnection=function(g){var f=new R.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.secondConnection=f,void 0!==this.firstConnection&&this.firstConnection.disableRegistrationsAndAutoReconnect(),g?this.getConnectionCache().then((function(g){f.start(g)})).catch((function(){})):f.start()},t.prototype.stopFirstConnection=function(g){void 0!==this.firstConnection&&(this.storedFirstConnection=this.firstConnection,this.firstConnection.stop(g),this.firstConnection=void 0)},t.prototype.stopSecondConnection=function(g){void 0!==this.secondConnection&&(this.secondConnection.stop(g),this.secondConnection=void 0)},t.prototype.stopSecondConnectionDelayed=function(){if(void 0!==this.secondConnection){var g=this.secondConnection;this.secondConnection=void 0,this.logger.info("Closing an inactive connection in ".concat(Math.round(this.options.lingeringConnectionDelayMs/1e3),"s")),setTimeout((function(){g.stop(!0)}),this.options.lingeringConnectionDelayMs)}},t.prototype.forceStopLingeringConnection=function(){this.storedFirstConnection&&(this.storedFirstConnection.stop(!1),this.storedFirstConnection=void 0)},t.prototype.switchConnections=function(){var g=this.firstConnection;this.firstConnection=this.secondConnection,this.secondConnection=g},t.prototype.doesSecondConnectionExist=function(){return void 0!==this.secondConnection},t.prototype.dispatchConnected=function(){if(void 0!==this.firstConnection){var g=this.firstConnection.getServerState(),f=g.url.endsWith("/")?g.url.slice(0,-1):g.url,S={baseEndpointUrl:f,newEndpointUrl:f!==this.baseEndpointUrl,c2cUrlBase:g.c2cUrlBase,clientId:g.connectedClientId,connectionId:g.connectionId,connectionTtlSec:g.getRemainingTtlInSec()};this.baseEndpointUrl=f,this.listener.onTrouterConnected(g.url,S)}},t.prototype.dispatchDisconnected=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},t.prototype.dispatchTerminalError=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},t.prototype.dispatchRegistrationState=function(g){this.options.registrationStateCallback&&this.options.registrationStateCallback(g)},t.prototype.expediteBackoffOnConnections=function(){var g;void 0!==this.lastExpediteBackoffCallAt&&Date.now()-this.lastExpediteBackoffCallAt<(null!==(g=this.options.expediteBackoffOnStartMinimumDelayMs)&&void 0!==g?g:1e4)?this.logger.info("Expedite backoff due to start() too frequent, skipping"):(this.lastExpediteBackoffCallAt=Date.now(),void 0!==this.firstConnection&&this.firstConnection.expediteBackoff(),void 0!==this.secondConnection&&this.secondConnection.expediteBackoff())},t.prototype.onDownstreamRequest=function(g,f,S){var v={id:f.id,method:f.method,path:"/".concat(f.shortUrl),body:f.body,headers:f.headers},C={id:f.id,status:0,headers:{},body:"",send:function(){return C.status<=100||C.status>=999?3:(S.writeHead(C.status,C.headers),S.end(C.body))}};this.listener.onTrouterRequest(v,C)},t.prototype.onConnected=function(g){this.fsm.onConnected(g===this.firstConnection)},t.prototype.onRegistered=function(g){this.fsm.onRegistered(g===this.firstConnection)},t.prototype.onUnregistered=function(g){this.fsm.onUnregistered(g===this.firstConnection||g===this.storedFirstConnection)},t.prototype.onReconnecting=function(g){this.fsm.onReconnecting(g===this.firstConnection)},t.prototype.onReconnectIsRequired=function(g,f,S){this.fsm.onReconnectionRequired(g===this.firstConnection,f,S)},t.prototype.onDisconnected=function(g){this.fsm.onDisconnected(g===this.firstConnection||g==this.storedFirstConnection),this.storedFirstConnection=void 0},t.prototype.onTerminalError=function(){this.fsm.onTerminalError(),this.storedFirstConnection=void 0},t.prototype.onUserActivityStateAccepted=function(g){this.listener.onTrouterUserActivityStateAccepted&&this.listener.onTrouterUserActivityStateAccepted(g)},t.prototype.onAudiencesSetResolved=function(g,f){var S,v;null===(v=(S=this.listener).onAudiencesSetResolved)||void 0===v||v.call(S,g,f)},t.prototype.onConnectionParametersUpdated=function(g){this.setConnectionCache(g)},t.prototype.setUserActivityState=function(g,f){return this.userActivityObject=new O(g,_.CorrelationVector.extend(f)),void 0!==this.secondConnection?(this.logger.info("Setting user activity ".concat(this.userActivityObject.toEventJSON()," on the second/new connection")),void this.secondConnection.setUserActivityState(this.userActivityObject)):void 0!==this.firstConnection?(this.logger.info("Setting user activity ".concat(this.userActivityObject.toEventJSON()," on the first/current connection")),void this.firstConnection.setUserActivityState(this.userActivityObject)):void 0},t.prototype.setAudienceSubscriptionsAsync=function(g,f,S){if(this.audienceSubscriptionState=new D(g,_.CorrelationVector.extend(S)),this.secondConnection)return this.logger.info("Setting audience subscriptions ".concat(this.audienceSubscriptionState.toEventJSON()," on second/new connection")),this.secondConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,f);if(this.firstConnection)return this.logger.info("Setting audience subscriptions ".concat(this.audienceSubscriptionState.toEventJSON()," on first/current connection")),this.firstConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,f);throw new Error("No connection found")},t.prototype.onTrouterMessageLost=function(g){var f=this;if(this.listener.onTrouterMessageLoss)if(null==g?void 0:g.length){var S=g.filter((function(g){return void 0!==f.processedMessageLoss["".concat(g.tag,"-").concat(g.etag)]}));if(S.length&&(this.logger.info("onTrouterMessageLoss - immediately acknowledging ".concat(S.length," seen dropped indicators")),this.sendProcessedDroppedIndicators(S),!(g=g.filter((function(g){return void 0===f.processedMessageLoss["".concat(g.tag,"-").concat(g.etag)]}))).length))return void this.logger.info("onTrouterMessageLoss - all declared dropped indicators have been seen before");if(!this.listener.onTrouterMessageLoss(g.map((function(g){return g.tag}))))return void this.logger.warn("onTrouterMessageLoss - some flow tag(s) have not been processed by listeners");g.forEach((function(g){f.processedMessageLoss["".concat(g.tag,"-").concat(g.etag)]=""})),this.sendProcessedDroppedIndicators(g)}else this.logger.warn("onTrouterMessageLoss - no flow tags have been provided")},t.prototype.getConnectionCache=function(){var g=this;return this.options.connectionCache?(this.logger.debug("Querying host's connection cache"),this.options.connectionCache.onGetTrouterConnectionCache().then((function(g){var f=g?JSON.parse(g):void 0;return"object"==typeof f?f:void 0})).catch((function(f){return g.logger.warn("Invalid connection cache content provided: ".concat(f)),g.connectionCache}))):Promise.resolve(this.connectionCache)},t.prototype.setConnectionCache=function(g){if(this.connectionCache=g,this.options.connectionCache)try{this.options.connectionCache.onSetTrouterConnectionCache(JSON.stringify(g))}catch(g){this.logger.warn("Error setting external connection cache: ".concat(g))}},t.prototype.sendProcessedDroppedIndicators=function(g){return void 0!==this.firstConnection?void this.firstConnection.sendProcessedDroppedIndicators(g):void 0!==this.secondConnection?void this.secondConnection.sendProcessedDroppedIndicators(g):void 0},t.prototype.configuredTrouterManager=function(){return new P.RegistrationEnforcer(this,this.options.connectionDependsOnRegistration,this.options.delayEventsUntilRegistered)},t}();f.TrouterManager=N},function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.TrouterUrlPromise=void 0;var v=S(0),C=function(){function t(g){this.logger=new v.Logger("UrlPromise",g)}return t.prototype.getPromise=function(){var g=this;return void 0!==this.url?(this.logger.debug("returning previously resolved url: ".concat(this.url)),Promise.resolve(this.url)):(void 0===this.pendingPromise?(this.logger.debug("creating and returning promise"),this.pendingPromise=new Promise((function(f,S){g.pendingPromiseResolveRef=f,g.pendingPromiseRejectRef=S}))):this.logger.debug("returning existing promise"),this.pendingPromise)},t.prototype.resolveUrl=function(g){this.url=g,this.logger.debug("got url: ".concat(this.url));var f=this.pendingPromiseResolveRef;this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==f&&(this.logger.debug("resolving promise"),f(g))},t.prototype.rejectUrl=function(g){this.logger.debug("aborting");var f=this.pendingPromiseRejectRef;this.url=void 0,this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==f&&(this.logger.debug("rejecting promise"),f(g))},t.prototype.resetUrl=function(){this.logger.debug("resetting url"),this.url=void 0},t}();f.TrouterUrlPromise=C},function(g,f,S){(function(g,S){!function(g,f){var S=g;S.version="0.9.6",S.protocol=1,S.transports=[],S.j=[],S.sockets={},S.connect=function(g,v){var C,_,T=S.util.parseUri(g);f&&f.location&&(T.protocol=T.protocol||f.location.protocol.slice(0,-1),T.host=T.host||(f.document?f.document.domain:f.location.hostname),T.port=T.port||f.location.port),C=S.util.uniqueUri(T);var I={host:T.host,secure:"https"==T.protocol,port:T.port||("https"==T.protocol?443:80),query:T.query||""};return S.util.merge(I,v),!I["force new connection"]&&S.sockets[C]||(_=new S.Socket(I)),!I["force new connection"]&&_&&(S.sockets[C]=_),_=_||S.sockets[C],I["skipped handshake data"]?_.of(""):_.of(T.path.length>1?T.path:"")}}(S.exports,void 0===g?window:g);var v=S.exports;!function(g,f){var S=g.util={},v=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,C=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];S.parseUri=function(g){for(var f=v.exec(g||""),S={},_=14;_--;)S[C[_]]=f[_]||"";return S},S.uniqueUri=function(g){var S=g.protocol,v=g.host,C=g.port;return"document"in f?(v=v||document.domain,C=C||("https"==S&&"https:"!==document.location.protocol?443:document.location.port)):(v=v||"localhost",C||"https"!=S||(C=443)),(S||"http")+"://"+v+":"+(C||80)},S.query=function(g,f){var v=S.chunkQuery(g||""),C=[];for(var _ in S.merge(v,S.chunkQuery(f||"")),v)v.hasOwnProperty(_)&&C.push(_+"="+v[_]);return C.length?"?"+C.join("&"):""},S.chunkQuery=function(g){for(var f,S={},v=g.split("&"),C=0,_=v.length;C<_;++C)(f=v[C].split("="))[0]&&(S[f[0]]=f[1]);return S};var _=!1;S.load=function(g){if("document"in f&&"complete"===document.readyState||_)return g();S.on(f,"load",g,!1)},S.on=function(g,f,S,v){g.attachEvent?g.attachEvent("on"+f,S):g.addEventListener&&g.addEventListener(f,S,v)},S.request=function(g){if(g&&"undefined"!=typeof XDomainRequest)return new XDomainRequest;if("undefined"!=typeof XMLHttpRequest&&(!g||S.ua.hasCORS))return new XMLHttpRequest;if(!g)try{return new(window[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(g){}return null},"undefined"!=typeof window&&S.load((function(){_=!0})),S.defer=function(g){if(!S.ua.webkit||"undefined"!=typeof importScripts)return g();S.load((function(){setTimeout(g,100)}))},S.merge=function(g,f,v,C){var _,T=C||[],I=void 0===v?2:v;for(_ in f)f.hasOwnProperty(_)&&S.indexOf(T,_)<0&&("object"==typeof g[_]&&I?S.merge(g[_],f[_],I-1,T):(g[_]=f[_],T.push(f[_])));return g},S.mixin=function(g,f){S.merge(g.prototype,f.prototype)},S.inherit=function(g,f){function n(){}n.prototype=f.prototype,g.prototype=new n},S.isArray=Array.isArray||function(g){return"[object Array]"===Object.prototype.toString.call(g)},S.intersect=function(g,f){for(var v=[],C=g.length>f.length?g:f,_=g.length>f.length?f:g,T=0,I=_.length;T<I;T++)~S.indexOf(C,_[T])&&v.push(_[T]);return v},S.indexOf=function(g,f,S){var v=g.length;for(S=S<0?S+v<0?0:S+v:S||0;S<v&&g[S]!==f;S++);return v<=S?-1:S},S.toArray=function(g){for(var f=[],S=0,v=g.length;S<v;S++)f.push(g[S]);return f},S.ua={},S.ua.hasCORS="undefined"!=typeof XMLHttpRequest&&function(){try{var g=new XMLHttpRequest}catch(g){return!1}return null!=g.withCredentials}(),S.ua.webkit="undefined"!=typeof navigator&&/webkit/i.test(navigator.userAgent)}(void 0!==v?v:S.exports,void 0===g?window:g),function(g,f){function n(){}g.EventEmitter=n,n.prototype.on=function(g,S){return this.$events||(this.$events={}),this.$events[g]?f.util.isArray(this.$events[g])?this.$events[g].push(S):this.$events[g]=[this.$events[g],S]:this.$events[g]=S,this},n.prototype.addListener=n.prototype.on,n.prototype.once=function(g,f){function n(){S.removeListener(g,n),f.apply(this,arguments)}var S=this;return n.listener=f,this.on(g,n),this},n.prototype.removeListener=function(g,S){if(this.$events&&this.$events[g]){var v=this.$events[g];if(f.util.isArray(v)){for(var C=-1,_=0,T=v.length;_<T;_++)if(v[_]===S||v[_].listener&&v[_].listener===S){C=_;break}if(C<0)return this;v.splice(C,1),v.length||delete this.$events[g]}else(v===S||v.listener&&v.listener===S)&&delete this.$events[g]}return this},n.prototype.removeAllListeners=function(g){return this.$events&&this.$events[g]&&(this.$events[g]=null),this},n.prototype.listeners=function(g){return this.$events||(this.$events={}),this.$events[g]||(this.$events[g]=[]),f.util.isArray(this.$events[g])||(this.$events[g]=[this.$events[g]]),this.$events[g]},n.prototype.emit=function(g){if(!this.$events)return!1;var S=this.$events[g];if(!S)return!1;var v=Array.prototype.slice.call(arguments,1);if("function"==typeof S)S.apply(this,v);else{if(!f.util.isArray(S))return!1;for(var C=S.slice(),_=0,T=C.length;_<T;_++)C[_].apply(this,v)}return!0}}(void 0!==v?v:S.exports,void 0!==v?v:S.parent.exports),function(g,f){if(f&&f.parse)return g.JSON={parse:f.parse,stringify:f.stringify};throw new Error("JSON not available")}(void 0!==v?v:S.exports,"undefined"!=typeof JSON?JSON:void 0),function(g,f){var S=g.parser={},v=S.packets=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],C=S.reasons=["transport not supported","client not handshaken","unauthorized"],_=S.advice=["reconnect"],T=f.JSON,I=f.util.indexOf;S.encodePacket=function(g){var f=I(v,g.type),S=g.id||"",b=g.endpoint||"",A=g.ack,P=null;switch(g.type){case"error":var R=g.reason?I(C,g.reason):"",M=g.advice?I(_,g.advice):"";""===R&&""===M||(P=R+(""!==M?"+"+M:""));break;case"message":""!==g.data&&(P=g.data);break;case"event":var w={name:g.name};g.args&&g.args.length&&(w.args=g.args),P=T.stringify(w);break;case"json":P=T.stringify(g.data);break;case"connect":g.qs&&(P=g.qs);break;case"ack":P=g.ackId+(g.args&&g.args.length?"+"+T.stringify(g.args):"")}var O=[f,S+("data"==A?"+":""),b];return null!=P&&O.push(P),O.join(":")},S.encodePayload=function(g){var f="";if(1==g.length)return g[0];for(var S=0,v=g.length;S<v;S++)f+="�"+g[S].length+"�"+g[S];return f};var b=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;S.decodePacket=function(g){if(!(I=g.match(b)))return{};var f=I[2]||"",S=(g=I[5]||"",{type:v[I[1]],endpoint:I[4]||""});switch(f&&(S.id=f,I[3]?S.ack="data":S.ack=!0),S.type){case"error":var I=g.split("+");S.reason=C[I[0]]||"",S.advice=_[I[1]]||"";break;case"message":S.data=g||"";break;case"event":try{var A=T.parse(g);S.name=A.name,S.args=A.args}catch(g){}S.args=S.args||[];break;case"json":try{S.data=T.parse(g)}catch(g){}break;case"connect":S.qs=g||"";break;case"ack":if((I=g.match(/^([0-9]+)(\+)?(.*)/))&&(S.ackId=I[1],S.args=[],I[3]))try{S.args=I[3]?T.parse(I[3]):[]}catch(g){}break;case"disconnect":S.reason=g}return S},S.decodePayload=function(g){if("�"==g.charAt(0)){for(var f=[],v=1,C="";v<g.length;v++)"�"==g.charAt(v)?(f.push(S.decodePacket(g.substr(v+1).substr(0,C))),v+=Number(C)+1,C=""):C+=g.charAt(v);return f}return[S.decodePacket(g)]}}(void 0!==v?v:S.exports,void 0!==v?v:S.parent.exports),function(g,f){function n(g,f){this.socket=g,this.sessid=f,this.connectErrorCallback=void 0,this.isOpened=!1}g.Transport=n,f.util.mixin(n,f.EventEmitter),n.prototype.onData=function(g){if(this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout(),""!==g){var S=f.parser.decodePayload(g);if(S&&S.length)for(var v=0,C=S.length;v<C;v++)this.onPacket(S[v])}return this},n.prototype.onPacket=function(g){return this.socket.setHeartbeatTimeout(),"heartbeat"==g.type?this.onHeartbeat():("connect"==g.type&&""==g.endpoint&&this.onConnect(),"error"==g.type&&"reconnect"==g.advice&&(this.isOpened=!1),this.socket.onPacket(g),this)},n.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var g=this;this.closeTimeout=setTimeout((function(){g.onDisconnect()}),this.socket.closeTimeout)}},n.prototype.onDisconnect=function(){return this.close&&this.isOpened&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},n.prototype.onConnect=function(){return this.socket.onConnect(),this.connectErrorCallback=void 0,this},n.prototype.clearCloseTimeout=function(){this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null)},n.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},n.prototype.packet=function(g){this.send(f.parser.encodePacket(g))},n.prototype.onHeartbeat=function(g){this.packet({type:"heartbeat"})},n.prototype.onOpen=function(){this.isOpened=!0,this.clearCloseTimeout(),this.socket.onOpen()},n.prototype.onClose=function(){this.isOpened=!1,this.socket.onClose(),this.onDisconnect()},n.prototype.prepareUrl=function(g){var S=this.socket.options;if(S["skipped handshake data"])return S.rewriteUrlForProxy(S["skipped handshake data"].websocketUrl+(g||""));var v=this.scheme()+"://"+S.host+":"+S.port+"/"+S.resource+"/"+f.protocol+"/"+this.name+"/"+this.sessid+(g||"");return S.rewriteUrlForProxy(v)},n.prototype.ready=function(g,f){f.call(this)},n.prototype.clearEventHandlers=function(){return this}}(void 0!==v?v:S.exports,void 0!==v?v:S.parent.exports),function(g,f,S){function o(g){if(this.options={port:80,secure:!1,document:"document"in S&&document,resource:"socket.io",transports:f.transports.slice(),"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":1/0,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!0,"auto connect":!0,"flash policy port":10843},f.util.merge(this.options,g),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1,this.disconnected=!1,this.options["sync disconnect on unload"]&&(!this.isXDomain()||f.util.ua.hasCORS)){var v=this;f.util.on(S,"unload",(function(){v.disconnectSync()}),!1)}this.options["auto connect"]&&this.connect()}function i(){}g.Socket=o,f.util.mixin(o,f.EventEmitter),o.prototype.of=function(g){return this.namespaces[g]||(this.namespaces[g]=new f.SocketNamespace(this,g),""!==g&&this.namespaces[g].packet({type:"connect"})),this.namespaces[g]},o.prototype.publish=function(){var g;for(var f in this.emit.apply(this,arguments),this.namespaces)this.namespaces.hasOwnProperty(f)&&(g=this.of(f)).$emit.apply(g,arguments)},o.prototype.handshake=function(g){function n(f){f instanceof Error?S.onError(f.message):g.apply(null,f.split(":"))}var S=this,v=this.options;if(!S.disconnected){var C=v.rewriteUrlForProxy(["http"+(v.secure?"s":"")+":/",v.host+":"+v.port,v.resource,f.protocol,f.util.query(this.options.query,"t="+ +new Date)].join("/"));if(this.isXDomain()&&!f.util.ua.hasCORS){var _=document.getElementsByTagName("script")[0],T=document.createElement("script");T.src=C+"&jsonp="+f.j.length,_.parentNode.insertBefore(T,_),f.j.push((function(g){n(g),T.parentNode.removeChild(T)}))}else{var I=f.util.request();I.open("GET",C,!0);var b=this.options.requestHeaders;void 0!==b&&Object.keys(b).forEach((function(g){I.setRequestHeader(g,b[g])})),I.onreadystatechange=function(){4==I.readyState&&(I.onreadystatechange=i,200==I.status?n(I.responseText):!S.reconnecting&&S.onError(I.responseText))},I.send(null)}}},o.prototype.getTransport=function(g){for(var S,v=g||this.transports,C=0;S=v[C];C++)if(f.Transport[S]&&f.Transport[S].check(this)&&(!this.isXDomain()||f.Transport[S].xdomainCheck()))return new f.Transport[S](this,this.sessionid);return null},o.prototype.connect=function(g){if(this.connecting||this.disconnected)return this;var S=this,o=function(v,C,_,T){function c(){if(!S.connected&&!S.disconnected)if(S.connecting=!1,clearTimeout(S.connectTimeoutTimer),S.options["try multiple transports"]){for(;S.remainingTransports.length>0&&S.remainingTransports.splice(0,1)[0]!=S.transport.name;);S.remainingTransports.length?a(S.remainingTransports):S.publish("connect_failed")}else S.publish("connect_failed")}function a(g){if(S.transport&&(S.transport.clearTimeouts(),S.transport.clearEventHandlers()),S.transport=S.getTransport(g),!S.transport||S.disconnected)return S.publish("connect_failed");S.transport.ready(S,(function(){S.connecting=!0,S.publish("connecting",S.transport.name),S.transport.open(c),S.options["connect timeout"]&&(S.connectTimeoutTimer=setTimeout((function(){c()}),S.options["connect timeout"]))}))}S.sessionid=v,S.closeTimeout=1e3*_+2e3,S.heartbeatTimeout=1e3*C+2e3,S.transports=T?f.util.intersect(T.split(","),S.options.transports):S.options.transports,S.setHeartbeatTimeout(),S.remainingTransports=S.transports.slice(0),a(S.transports),S.once("connect",(function(){clearTimeout(S.connectTimeoutTimer),g&&"function"==typeof g&&g()}))};if(this.options["skipped handshake data"]){var v=this.options["skipped handshake data"];o("v4c-"+(new Date).getTime(),v.timeout,v.timeout,"websocket")}else this.handshake(o);return this},o.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);var g=this;this.heartbeatTimeoutTimer=setTimeout((function(){g.transport.onClose()}),this.heartbeatTimeout)},o.prototype.packet=function(g){return this.connected&&!this.doBuffer?this.transport.packet(g):this.buffer.push(g),this},o.prototype.setBuffer=function(g){this.doBuffer=g,!g&&this.connected&&this.buffer.length&&(this.transport.payload(this.buffer),this.buffer=[])},o.prototype.disconnect=function(){return(this.connected||this.connecting)&&(this.open&&this.of("").packet({type:"disconnect"}),this.onDisconnect("booted")),this.disconnected=!0,this},o.prototype.disconnectSync=function(){var g=f.util.request(),S=this.resource+"/"+f.protocol+"/"+this.sessionid;g.open("GET",S,!0),this.onDisconnect("booted")},o.prototype.isXDomain=function(){var g=S.location.port||("https:"==S.location.protocol?443:80);return this.options.host!==S.location.hostname||this.options.port!=g},o.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit("connect"))},o.prototype.onOpen=function(){this.open=!0},o.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},o.prototype.onPacket=function(g){this.of(g.endpoint).onPacket(g)},o.prototype.onError=function(g){g&&g.advice&&"reconnect"===g.advice&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish("error",g&&g.reason?g.reason:g)},o.prototype.onDisconnect=function(g){var f=this.connected,S=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1,(f||S)&&(this.transport.close(),this.transport.clearTimeouts(),f?(this.publish("disconnect",g),"booted"!=g&&this.options.reconnect&&!this.reconnecting&&this.reconnect()):this.publish("close_during_connecting",g))},o.prototype.reconnect=function(){function t(){if(g.connected){for(var f in g.namespaces)g.namespaces.hasOwnProperty(f)&&""!==f&&g.namespaces[f].packet({type:"connect"});g.publish("reconnect",g.transport.name,g.reconnectionAttempts)}clearTimeout(g.reconnectionTimer),g.removeListener("connect_failed",e),g.removeListener("connect",e),g.reconnecting=!1,delete g.reconnectionAttempts,delete g.reconnectionDelay,delete g.reconnectionTimer,delete g.redoTransports,g.options["try multiple transports"]=S}function e(){if(g.reconnecting)return g.connected?t():g.connecting&&g.reconnecting?g.reconnectionTimer=setTimeout(e,1e3):void(g.reconnectionAttempts++>=f?g.redoTransports?(g.publish("reconnect_failed"),t()):(g.on("connect_failed",e),g.options["try multiple transports"]=!0,g.transport=g.getTransport(),g.redoTransports=!0,g.connect()):(g.reconnectionDelay<v&&(g.reconnectionDelay*=2),g.connect(),g.publish("reconnecting",g.reconnectionDelay,g.reconnectionAttempts),g.reconnectionTimer=setTimeout(e,g.reconnectionDelay)))}this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options["reconnection delay"];var g=this,f=this.options["max reconnection attempts"],S=this.options["try multiple transports"],v=this.options["reconnection limit"];this.options["try multiple transports"]=!1,this.reconnectionTimer=setTimeout(e,this.reconnectionDelay),this.on("connect",e)}}(void 0!==v?v:S.exports,void 0!==v?v:S.parent.exports,void 0===g?window:g),function(g,f){function n(g,f){this.socket=g,this.name=f||"",this.flags={},this.json=new o(this,"json"),this.ackPackets=0,this.acks={}}function o(g,f){this.namespace=g,this.name=f}g.SocketNamespace=n,f.util.mixin(n,f.EventEmitter),n.prototype.$emit=f.EventEmitter.prototype.emit,n.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},n.prototype.packet=function(g){return g.endpoint=this.name,this.socket.packet(g),this.flags={},this},n.prototype.send=function(g,f){var S={type:this.flags.json?"json":"message",data:g};return"function"==typeof f&&(S.id=++this.ackPackets,S.ack=!0,this.acks[S.id]=f),this.packet(S)},n.prototype.emit=function(g){var f=Array.prototype.slice.call(arguments,1),S=f[f.length-1],v={type:"event",name:g};return"function"==typeof S&&(v.id=++this.ackPackets,v.ack="data",this.acks[v.id]=S,f=f.slice(0,f.length-1)),v.args=f,this.packet(v)},n.prototype.disconnect=function(){return""===this.name?this.socket.disconnect():(this.packet({type:"disconnect"}),this.$emit("disconnect")),this},n.prototype.onPacket=function(g){function n(){S.packet({type:"ack",args:f.util.toArray(arguments),ackId:g.id})}var S=this;switch(g.type){case"connect":this.$emit("connect");break;case"disconnect":""===this.name?this.socket.onDisconnect(g.reason||"booted"):this.$emit("disconnect",g.reason||"");break;case"message":case"json":var v=["message",g.data];"data"==g.ack?v.push(n):g.ack&&this.packet({type:"ack",ackId:g.id}),this.$emit.apply(this,v);break;case"event":v=[g.name].concat(g.args),"data"==g.ack&&v.push(n),this.$emit.apply(this,v);break;case"ack":this.acks[g.ackId]&&(this.acks[g.ackId].apply(this,g.args),delete this.acks[g.ackId]);break;case"error":g.advice?this.socket.onError(g):"unauthorized"==g.reason?this.$emit("connect_failed",g.reason):this.$emit("error",g.reason)}},o.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},o.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}(void 0!==v?v:S.exports,void 0!==v?v:S.parent.exports),function(g,f,S){function o(g){f.Transport.apply(this,arguments)}function i(){}g.websocket=o,f.util.inherit(o,f.Transport),o.prototype.name="websocket",o.prototype.open=function(g){var v,C=f.util.query(this.socket.options.query),_=this;return this.connectErrorCallback=g,v||(v=S.MozWebSocket||S.WebSocket),this.websocket=new v(this.prepareUrl(C)),this.websocket.onopen=function(){_.onOpen(),_.socket.setBuffer(!1)},this.websocket.onmessage=function(g){_.onData(g.data)},this.websocket.onclose=function(){_.onClose(),_.socket.setBuffer(!0)},this.websocket.onerror=function(g){_.onError(g)},this},o.prototype.send=function(g){return this.websocket.send(g),this},o.prototype.payload=function(g){for(var f=0,S=g.length;f<S;f++)this.packet(g[f]);return this},o.prototype.close=function(){return this.websocket.close(),this},o.prototype.onError=function(g){void 0!==this.connectErrorCallback&&(this.connectErrorCallback(),this.connectErrorCallback=void 0),this.socket.onError(g)},o.prototype.scheme=function(){return this.socket.options.secure?"wss":"ws"},o.check=function(){return"WebSocket"in S&&!("__addTask"in WebSocket)||"MozWebSocket"in S},o.xdomainCheck=function(){return!0},o.prototype.clearEventHandlers=function(){return this.websocket&&(this.websocket.onopen=this.websocket.onmessage=this.websocket.onclose=this.websocket.onerror=i),this},f.transports.push("websocket")}(void 0!==v?v.Transport:S.exports,void 0!==v?v:S.parent.exports,void 0===g?window:g),function(g,f,S){function o(g){g&&f.Transport.apply(this,arguments)}function i(){}g.XHR=o,f.util.inherit(o,f.Transport),o.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},o.prototype.payload=function(g){for(var S=[],v=0,C=g.length;v<C;v++)S.push(f.parser.encodePacket(g[v]));this.send(f.parser.encodePayload(S))},o.prototype.send=function(g){return this.post(g),this},o.prototype.post=function(g){function e(){4==this.readyState&&(this.onreadystatechange=i,200==this.status?(clearTimeout(this.ackTimeoutTimer),f.socket.setBuffer(!1)):f.onClose())}function o(){this.onload=i,f.socket.setBuffer(!1)}var f=this;this.socket.setBuffer(!0),this.sendXHR=this.request("POST"),S.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=o:this.sendXHR.onreadystatechange=e,this.sendXHR.send(g),f.sendXHR.ackTimeoutTimer=setTimeout((function(){f.onClose()}),f.socket.options.ackTimeoutMs)},o.prototype.close=function(){return this.onClose(),this},o.prototype.request=function(g){var S=f.util.request(this.socket.isXDomain()),v=f.util.query(this.socket.options.query,"t="+ +new Date);S.open(g||"GET",this.prepareUrl(v),!0);var C=this.socket.options.requestHeaders;if(void 0!==C&&Object.keys(C).forEach((function(g){S.setRequestHeader(g,C[g])})),"POST"==g)try{S.setRequestHeader?S.setRequestHeader("Content-type","text/plain;charset=UTF-8"):S.contentType="text/plain"}catch(g){}return S},o.prototype.scheme=function(){return this.socket.options.secure?"https":"http"},o.check=function(g,v){try{var C=f.util.request(v),_=S.XDomainRequest&&C instanceof XDomainRequest,T=(g&&g.options&&g.options.secure?"https:":"http:")!=S.location.protocol;if(C&&(!_||!T))return!0}catch(g){}return!1},o.xdomainCheck=function(){return o.check(null,!0)},o.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXHR.onreadystatechange=this.sendXHR.onload=i),this}}(void 0!==v?v.Transport:S.exports,void 0!==v?v:S.parent.exports,void 0===g?window:g),function(g,f,S){function o(){f.Transport.XHR.apply(this,arguments)}function i(){}g["xhr-polling"]=o,f.util.inherit(o,f.Transport.XHR),f.util.merge(o,f.Transport.XHR),o.prototype.name="xhr-polling",o.prototype.open=function(g){var S=this;return S.connectErrorCallback=g,f.Transport.XHR.prototype.open.call(S),!1},o.prototype.get=function(){function t(){4==this.readyState&&(this.onreadystatechange=i,200==this.status?(g.connectErrorCallback=void 0,g.onData(this.responseText),g.get()):(g.onClose(),void 0!==g.connectErrorCallback&&(g.connectErrorCallback(),g.connectErrorCallback=void 0)))}function e(){g.connectErrorCallback=void 0,this.onload=i,this.onerror=i,g.onData(this.responseText),g.get()}function o(){g.onClose(),void 0!==g.connectErrorCallback&&(g.connectErrorCallback(),g.connectErrorCallback=void 0)}if(this.isOpened){var g=this;this.xhr=this.request(),S.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=e,this.xhr.onerror=o):this.xhr.onreadystatechange=t,this.xhr.send(null)}},o.prototype.onClose=function(){if(f.Transport.XHR.prototype.onClose.call(this),this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i;try{this.xhr.abort()}catch(g){}this.xhr=null}},o.prototype.ready=function(g,S){var v=this;f.util.defer((function(){S.call(v)}))},o.prototype.clearEventHandlers=function(){return f.Transport.XHR.prototype.clearEventHandlers.call(this),this.xhr&&(this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i),this},f.transports.push("xhr-polling")}(void 0!==v?v.Transport:S.exports,void 0!==v?v:S.parent.exports,void 0===g?window:g),f.io=v}).call(f,S(13),S(14)(g))},function(g,f){var S;S=function(){return this}();try{S=S||Function("return this")()||(0,eval)("this")}catch(g){"object"==typeof window&&(S=window)}g.exports=S},function(g,f){g.exports=function(g){return g.webpackPolyfill||(g.deprecate=function(){},g.paths=[],g.children||(g.children=[]),Object.defineProperty(g,"loaded",{enumerable:!0,get:function(){return g.l}}),Object.defineProperty(g,"id",{enumerable:!0,get:function(){return g.i}}),g.webpackPolyfill=1),g}},function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.ConnectionTracker=f.Properties=f.TrackerStep=f.ClientEventName=f.ResponseData=void 0;var v,C=S(3),_=S(1),T=S(0),I=function(){function t(g){this.id=g,this.status=200,this.headers={},this.body=""}return t}();f.ResponseData=I,function(g){g.Connected="trouter_js_client_connected",g.Disconnected="trouter_js_client_disconnected",g.Error="trouter_js_client_error",g.Progress="trouter_js_client_progress",g.Response="trouter_js_client_response",g.Request="trouter_js_client_request",g.CheckConnection="trouter_js_client_check_connection",g.Registration="trouter_js_client_registration",g.Unregistration="trouter_js_client_unregistration"}(v||(f.ClientEventName=v={}));var b=function(){function t(g,f,S,v,C){this.stepName=g,this.operation=f,this.delta=S,this.ts=v,this.error=C}return t}();f.TrackerStep=b;var A=function(){function t(){}return t}();f.Properties=A;var P=function(){function t(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType="",this.connectionNumber=0}return t}(),R=function(){function t(){this.enabled=!1,this.numberOfStepsToMaintain=40,this.logHealthCheckError=!1,this.sendProgressTimeoutSecs=55,this.logSendPingError=!1,this.maxBackoffInMs=12e4,this.trouter_js_client_connected=!1,this.trouter_js_client_disconnected=!1,this.trouter_js_client_error=!1,this.trouter_js_client_progress=!1,this.trouter_js_client_response=!1,this.trouter_js_client_request=!1,this.trouter_js_client_registration=!1,this.trouter_js_client_unregistration=!1,this.trouter_js_client_check_connection=!0}return t}(),M=function(){function t(g,f,S,v,_,I,b){this.clientId=f,this.clientInfo=S,this.getServerState=v,this.endpointId=_,this.clientCorrelationID=I,this.environment=b,this.logger=new T.Logger("ConnectionTracker",g),this.clientCorrelationID=void 0!==I?I:"",this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new C.Timespan,this.eventLogSettings=new R,this.connectedInfo=new P}return t.prototype.enable=function(g){this.eventLogSettings.enabled=!0,this.eventLogger=g},t.prototype.disable=function(){this.eventLogSettings.enabled=!1},t.prototype.sendProgress=function(g){this.steps.length>0&&this.sendTelemetry(v.Progress,g,this.steps)},t.prototype.cancelProgressTimer=function(){void 0!==this.progressTimeout&&(clearTimeout(this.progressTimeout),this.progressTimeout=void 0)},t.prototype.resetProgressSendTimer=function(){var g=this;this.cancelProgressTimer(),void 0!==this.eventLogSettings.sendProgressTimeoutSecs&&this.eventLogSettings.sendProgressTimeoutSecs>0&&(this.progressTimeout=setTimeout((function(){g.sendProgress({reason:"timeout",timeoutSecs:g.eventLogSettings.sendProgressTimeoutSecs})}),1e3*this.eventLogSettings.sendProgressTimeoutSecs))},t.prototype.setConnectedInfo=function(g,f){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=Date.now(),this.connectedInfo.isNewUrl=g,this.connectedInfo.transportType=f,++this.connectedInfo.connectionNumber},t.prototype.clearConnectedInfo=function(){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=0,this.connectedInfo.isNewUrl=!0,this.connectedInfo.transportType=""},t.prototype.copyProperties=function(g,f){for(var S=0,v=Object.keys(f);S<v.length;S++){var C=v[S];void 0!==f[C]&&(g[C.replace(/-/g,"_")]={value:f[C]})}},t.prototype.increasePingResponseCount=function(){++this.connectedInfo.numberOfPingReplies},t.prototype.sendTelemetry=function(g,f,S){try{if(!0===this.eventLogSettings.enabled&&!0===this.eventLogSettings[g]&&void 0!==this.eventLogger){var v=this.getServerState(),T={name:g,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:(0,C.toJson)(S)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:_.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:v.connectionId},connectedClientId:{value:v.connectedClientId},domId:{value:v.domId},url:{value:v.url},ttlInSecs:{value:v.getRemainingTtlInSec()},numberOfPingReplies:{value:this.connectedInfo.numberOfPingReplies},connectedTimestamp:{value:this.connectedInfo.connectedTimestamp},isNewUrl:{value:this.connectedInfo.isNewUrl},transportType:{value:this.connectedInfo.transportType},connectionNumber:{value:this.connectedInfo.connectionNumber}}};this.copyProperties(T.properties,f),this.eventLogger.logEvent(T)}}catch(f){this.logger.warn("error in sending event ".concat(g,": ").concat((0,C.toJson)(f)))}},t.prototype.createStep=function(g,f,S){return new b(g,f,this.beginTimestamp.duration,Date.now(),S)},t.prototype.addStep=function(g,f,S){if(!1!==this.eventLogSettings.enabled&&(0===this.steps.length&&this.beginTimestamp.reset(),this.steps.push(this.createStep(g,f,S)),++this.totalStepCount,void 0!==this.eventLogSettings.numberOfStepsToMaintain&&this.steps.length>this.eventLogSettings.numberOfStepsToMaintain)){var C=this.steps.slice(0);this.steps.length=0,this.sendTelemetry(v.Progress,{reason:"flush"},C)}},t.prototype.trackStart=function(g){this.addStep(g,"start")},t.prototype.trackEnd=function(g){this.addStep(g,"end")},t.prototype.trackError=function(g,f,S,C){void 0===S&&(S=!0),"health"===g&&!0!==this.eventLogSettings.logHealthCheckError||"ping"===g&&!1===this.eventLogSettings.logSendPingError||(void 0===C&&(C="error"),!0===S&&this.addStep(g,C,f),this.sendTelemetry(v.Error,{},[this.createStep(g,C,f)]))},t.prototype.trackProgress=function(g,f){this.addStep(g,f)},t.prototype.trackConnected=function(g,f){this.setConnectedInfo(g,f);var S=this.steps.slice(0),C=this.totalStepCount,_=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(v.Connected,{stepCount:S.length,totalStepCount:C,connectionEstablishmentMs_Total:_},S),this.cancelProgressTimer()},t.prototype.getSessionLength=function(){return Date.now()-this.connectedInfo.connectedTimestamp},t.prototype.trackDisconnected=function(g){g.sessionLengthMS=this.getSessionLength(),this.sendTelemetry(v.Disconnected,g,[]),this.resetProgressSendTimer()},t.prototype.trackNewConnection=function(){++this.connectionAttempt},t.prototype.trackRequest=function(g,f){var S={};void 0!==f&&(S.hasError=!0,S.error=f);try{if(g){S.requestID=g.id,S.httpMethod=g.method,S.url=g.url,S.bodyLength=g.body.length,S.shortUrl=g.shortUrl,S.requestTimeStamp=g.startTS,S.correlationVector=g.correlationVector;for(var _=g.headers,T=0,I=Object.keys(_);T<I.length;T++){var b=I[T];S[b]=_[b]}}}catch(g){S.hasError=!0,S.error="".concat(S.error," error creating request context ").concat((0,C.toJson)(g))}this.sendTelemetry(v.Request,S,[])},t.prototype.trackResponse=function(g,f,S,_){var T={};void 0!==_&&(T.hasError=!0,T.error=_);try{if(T.responseTimestamp=void 0!==S?S.sentTS:Date.now(),g){T.requestID=g.id,T.httpMethod=g.method,T.shortUrl=g.shortUrl,T.correlationVector=g.correlationVector;for(var I=g.headers,b=0,A=Object.keys(I);b<A.length;b++){var P=A[b];T[P]=I[P]}}S&&(T.latencyMS=f,T.responseCode=S.status,T.responseLength=S.body.length)}catch(g){T.hasError=!0,T.error="".concat(T.error," error creating response context ").concat((0,C.toJson)(g))}this.sendTelemetry(v.Response,T,[])},t.prototype.sendResponseError=function(g,f,S){this.trackResponse(f,void 0,S,g)},t.prototype.close=function(){this.sendProgress({reason:"closed"}),this.steps.length=0,this.cancelProgressTimer()},t.prototype.mergeSettings=function(g){if(g){this.eventLogSettings.numberOfStepsToMaintain=Math.min(40,Math.max(10,void 0!==g.numberOfStepsToMaintain?g.numberOfStepsToMaintain:0));var f=Math.min(3600,Math.max(55,void 0!==g.sendProgressTimeoutSecs?g.sendProgressTimeoutSecs:0));this.eventLogSettings.logHealthCheckError=g.logHealthCheckError,this.eventLogSettings.logSendPingError=g.logSendPingError;for(var S=0,C=Object.keys(v).map((function(g){return v[g]}));S<C.length;S++){var _=C[S];void 0!==g[_]&&(this.eventLogSettings[_]=g[_])}this.eventLogSettings.sendProgressTimeoutSecs!==f&&(this.eventLogSettings.sendProgressTimeoutSecs=f,this.resetProgressSendTimer())}},t}();f.ConnectionTracker=M},function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.DisconnectReason=void 0;var v=function(){function t(g,f,S){this.reason=g,this.claims=f,this.details=S}return t.fromRawReason=function(g,f){if(""===g||"dup"===g)return new t(g);try{var S=JSON.parse(g);return"object"!=typeof S||void 0===S.reason?(null==f||f.error("invalid disconnect reason format"),new t("unknown",void 0,g)):new t(S.reason,S.claims,S.details)}catch(f){return new t("disconnect",void 0,g)}},t.fromSocketIoEventData=function(g,f){return"string"==typeof f?new t(g,void 0,f):void 0},t.prototype.toTelemetryString=function(){return"socketerror"===this.reason||"reconnecterror"===this.reason||"disconnect"===this.reason?this.details:this.reason},t}();f.DisconnectReason=v},function(g,f,S){function o(g,f,S){if(void 0===g||void 0===f)return!1;var v=Date.now()-g;return v>f*S.tolerance&&v>S.minimumWaitMs}Object.defineProperty(f,"__esModule",{value:!0}),f.ExponentialBackoff=void 0;var v=function(){function t(g,f,S){void 0===S&&(S={tolerance:2,minimumWaitMs:1e4}),this.logger=g,this.maxBackoffInMs=f,this.gapDetectionSettings=S,this.backoffId=0,this.backoffCount=0}return t.calculateNextBackoffMs=function(g,f){var S=1+.4*(Math.random()-.5),v=1e3*Math.pow(2,g)*S;return v=Math.round(v),Math.min(f,v)},t.prototype.setMaxBackoffMs=function(g){this.maxBackoffInMs=g},t.prototype.backoff=function(g,f){var S=this;if(void 0!==this.timerHandle&&(this.logger.debug("Clearing current back off"),clearTimeout(this.timerHandle),this.timerHandle=void 0),void 0!==this.previousCompleteTime){var v=Date.now()-this.previousCompleteTime;v>this.maxBackoffInMs*this.gapDetectionSettings.tolerance&&v>this.gapDetectionSettings.minimumWaitMs&&(this.logger.info("Back off for ".concat(g," with ID ").concat(this.backoffId," will be reset due to a lot of time having passed since the previous backoff (").concat(v," ms)")),this.backoffCount=0,this.previousCompleteTime=void 0)}var C=t.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info("Backing off ".concat(g," for ").concat(C," milliseconds with ID ").concat(this.backoffId)),this.callback=function(v,C){o(v,C,S.gapDetectionSettings)&&(S.logger.info("Back off for ".concat(g," with ID ").concat(S.backoffId," will be reset due to the wait (").concat(Date.now()-(null!=v?v:0)," ms) being longer than expected (").concat(C," ms)")),S.backoffCount=0),S.logger.info("Back off for ".concat(g," with ID ").concat(S.backoffId," complete, invoking handler")),S.timerHandle=void 0,S.callback=void 0,S.previousCompleteTime=Date.now(),f()};var _=Date.now();this.timerHandle=setTimeout((function(){var g;return null===(g=S.callback)||void 0===g?void 0:g.call(S,_,C)}),C)},t.prototype.reset=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off with ID ".concat(this.backoffId)),clearTimeout(this.timerHandle),this.timerHandle=void 0,this.callback=void 0),this.backoffCount=0},t.prototype.expediteIfPending=function(){if(this.backoffCount=0,void 0!==this.timerHandle){this.logger.debug("Expediting back off with ID ".concat(this.backoffId)),clearTimeout(this.timerHandle),this.timerHandle=void 0;var g=this.callback;this.callback=void 0,g&&g()}},t}();f.ExponentialBackoff=v},function(g,f,S){var v=this&&this.__spreadArray||function(g,f,S){if(S||2===arguments.length)for(var v,C=0,_=f.length;C<_;C++)!v&&C in f||(v||(v=Array.prototype.slice.call(f,0,C)),v[C]=f[C]);return g.concat(v||Array.prototype.slice.call(f))};Object.defineProperty(f,"__esModule",{value:!0}),f.LoggingManagerConsumer=f.RegistrationEnforcer=void 0;var C=S(6),_=function(){function t(g,f,S){this.wrapped=g,this.shouldConnectionDependOnRegistration=f,this.shouldHoldBackEvents=S,this.isRegistered=!1,this.heldBackEvents=[]}return t.prototype.onDownstreamRequest=function(g,f,S){this.passIfRegisteredOrNotNeeded("onDownstreamRequest",g,f,S)},t.prototype.onConnected=function(g){this.passIfRegisteredOrNotNeeded("onConnected",g)},t.prototype.onRegistered=function(g){this.isRegistered=!0,this.wrapped.onRegistered(g),this.fireHeldBackEvents()},t.prototype.onUnregistered=function(g){var f=this.isRegistered;this.isRegistered=!1,this.wrapped.onUnregistered(g),f&&g.getState()===C.State.Connected&&this.shouldConnectionDependOnRegistration()&&g.forceReconnectDueToNoRegistration()},t.prototype.onReconnecting=function(g){this.wrapped.onReconnecting(g)},t.prototype.onReconnectIsRequired=function(g,f,S){this.wrapped.onReconnectIsRequired(g,f,S)},t.prototype.onDisconnected=function(g){this.isRegistered=!1,this.dropHeldBackEvents(),this.wrapped.onDisconnected(g)},t.prototype.onTerminalError=function(g){this.wrapped.onTerminalError(g)},t.prototype.onConnectionParametersUpdated=function(g){this.wrapped.onConnectionParametersUpdated(g)},t.prototype.onTrouterMessageLost=function(g){this.passIfRegisteredOrNotNeeded("onTrouterMessageLost",g)},t.prototype.onUserActivityStateAccepted=function(g){this.passIfRegisteredOrNotNeeded("onUserActivityStateAccepted",g)},t.prototype.onAudiencesSetResolved=function(g,f){this.passIfRegisteredOrNotNeeded("onAudiencesSetResolved",g,f)},t.prototype.getState=function(){return this.wrapped.getState()},t.prototype.holdBackEvent=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];this.heldBackEvents.push({kind:g,args:f})},t.prototype.passIfRegisteredOrNotNeeded=function(g){for(var f,S=[],C=1;C<arguments.length;C++)S[C-1]=arguments[C];var _=this.shouldConnectionDependOnRegistration(),T=this.shouldHoldBackEvents();_&&T||this.fireHeldBackEvents(_?function(g){return"onConnected"!==g.kind}:void 0),this.isRegistered||!_||!1===T&&"onConnected"!==g?(f=this.wrapped)[g].apply(f,S):this.holdBackEvent.apply(this,v([g],S,!1))},t.prototype.fireHeldBackEvents=function(g){for(var f,S=0,v=this.heldBackEvents;S<v.length;S++){var C=v[S];(void 0===g||g(C))&&(f=this.wrapped)[C.kind].apply(f,C.args)}this.heldBackEvents=void 0===g?[]:this.heldBackEvents.filter((function(f){return!g(f)}))},t.prototype.dropHeldBackEvents=function(){this.heldBackEvents=[]},t}();f.RegistrationEnforcer=_;var T=function(){function t(g,f,S,v){this.wrapped=g,this.prefix=f,this.logger=S,this.onEventAction=v}return t.prototype.onEvent=function(g,f){var S;void 0!==this.onEventAction?this.onEventAction(g,f):(null!==(S=this.logger)&&void 0!==S?S:console).log("".concat(this.prefix," TracingEnforcer: ").concat(g,"(").concat(f,")"))},t.prototype.onDownstreamRequest=function(g,f,S){this.onEvent("onDownstreamRequest",JSON.stringify({request:f,response:S})),this.wrapped.onDownstreamRequest(g,f,S)},t.prototype.onConnected=function(g){this.onEvent("onConnected",g.getState().toString()),this.wrapped.onConnected(g)},t.prototype.onRegistered=function(g){this.onEvent("onRegistered",g.getState().toString()),this.wrapped.onRegistered(g)},t.prototype.onUnregistered=function(g){this.onEvent("onUnregistered",g.getState().toString()),this.wrapped.onUnregistered(g)},t.prototype.onReconnecting=function(g){this.onEvent("onReconnecting",g.getState().toString()),this.wrapped.onReconnecting(g)},t.prototype.onReconnectIsRequired=function(g,f,S){this.onEvent("onReconnectIsRequired",JSON.stringify({connection:g.getState().toString(),useConnectParamsFromCache:f,reason:S})),this.wrapped.onReconnectIsRequired(g,f,S)},t.prototype.onDisconnected=function(g){this.onEvent("onDisconnected",g.getState().toString()),this.wrapped.onDisconnected(g)},t.prototype.onTerminalError=function(g){this.onEvent("onTerminalError",JSON.stringify({connection:g})),this.wrapped.onTerminalError(g)},t.prototype.onConnectionParametersUpdated=function(g){this.onEvent("onConnectionParametersUpdated",JSON.stringify({connectParams:g})),this.wrapped.onConnectionParametersUpdated(g)},t.prototype.onTrouterMessageLost=function(g){this.onEvent("onTrouterMessageLost",JSON.stringify({flowTags:g})),this.wrapped.onTrouterMessageLost(g)},t.prototype.onUserActivityStateAccepted=function(g){this.onEvent("onUserActivityStateAccepted",JSON.stringify({cv:g})),this.wrapped.onUserActivityStateAccepted(g)},t.prototype.onAudiencesSetResolved=function(g,f){this.onEvent("onAudiencesSetResolved",JSON.stringify({audienceSubscriptionsResponse:g,cv:f})),this.wrapped.onAudiencesSetResolved(g,f)},t.prototype.getState=function(){return this.wrapped.getState()},t}();f.LoggingManagerConsumer=T},function(g,f,S){Object.defineProperty(f,"__esModule",{value:!0}),f.TrouterManagerFsm=void 0;var v=S(2),C=S(4),_=S(0),T=S(7),I=function(){function t(g,f){this.worker=f,this.state=C.TrouterManagerState.Unknown,this.logger=new _.Logger("ManagerFsm",g)}return t.prototype.start=function(){this.state===C.TrouterManagerState.Unknown?(this.setState(C.TrouterManagerState.Disconnected),this.worker.forceStopLingeringConnection(),this.worker.startFirstConnection()):(this.logger.info("start called in state '".concat(C.TrouterManagerState[this.state],"', expediting pending backoffs, if any")),this.worker.expediteBackoffOnConnections())},t.prototype.stop=function(g){this.state!==C.TrouterManagerState.Unknown?(this.setState(C.TrouterManagerState.Unknown),this.worker.stopFirstConnection(!0===g),this.worker.stopSecondConnection(!0===g)):this.showIgnored("stop")},t.prototype.getState=function(){switch(this.state){case C.TrouterManagerState.Unknown:case C.TrouterManagerState.Connected:case C.TrouterManagerState.Disconnected:case C.TrouterManagerState.Switching:return this.state;case C.TrouterManagerState.TerminalError:return v.TrouterState.Disconnected}},t.prototype.getInternalState=function(){return this.state},t.prototype.onConnected=function(g){this.state===C.TrouterManagerState.Disconnected&&g?this.worker.doesSecondConnectionExist()?this.setState(C.TrouterManagerState.Switching):(this.setState(C.TrouterManagerState.Connected),this.worker.dispatchConnected()):this.showIgnored("onConnected(".concat(g,")"))},t.prototype.onRegistered=function(g){this.state!==C.TrouterManagerState.Disconnected||g?this.state!==C.TrouterManagerState.Switching||g?this.state===C.TrouterManagerState.Disconnected&&g&&(this.setState(C.TrouterManagerState.Connected),this.worker.dispatchConnected()):(this.setState(C.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnectionDelayed(),this.worker.dispatchConnected()):(this.setState(C.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnection(!0),this.worker.dispatchConnected()),this.worker.dispatchRegistrationState(!0)},t.prototype.onUnregistered=function(g){g&&this.worker.dispatchRegistrationState(!1)},t.prototype.onReconnecting=function(g){this.state!==C.TrouterManagerState.Connected&&this.state!==C.TrouterManagerState.Switching||!g?this.showIgnored("onReconnecting(".concat(g,")")):(this.setState(C.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected())},t.prototype.onReconnectionRequired=function(g,f,S){this.state===C.TrouterManagerState.Connected&&g?(this.setState(C.TrouterManagerState.Switching),this.worker.startSecondConnection(f)):this.state===C.TrouterManagerState.Disconnected&&g?this.worker.startSecondConnection(f):this.state===C.TrouterManagerState.Switching&&g&&S===T.ReconnectReason.Configuration?(this.logger.debug("onReconnectionRequired: switch requested while already in Switching state"),this.worker.stopSecondConnection(!0),this.worker.startSecondConnection(f)):this.showIgnored("onReconnectionRequired(".concat(g,")"))},t.prototype.onDisconnected=function(g){this.state==C.TrouterManagerState.Unknown&&g?this.worker.dispatchDisconnected():this.state==C.TrouterManagerState.Switching&&g?(this.worker.switchConnections(),this.worker.stopSecondConnection(!1),this.setState(C.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected()):this.showIgnored("onDisconnected(".concat(g,")"))},t.prototype.onTerminalError=function(){this.setState(C.TrouterManagerState.TerminalError),this.worker.dispatchTerminalError()},t.prototype.showIgnored=function(g){this.logger.info("Ignoring event '".concat(g,"' in state '").concat(C.TrouterManagerState[this.state],"'"))},t.prototype.setState=function(g){this.logger.info("Switching from state '".concat(C.TrouterManagerState[this.state],"' to state '").concat(C.TrouterManagerState[g],"'")),this.state!==g?this.state=g:this.logger.error("Attempt to switch to the current state '".concat(C.TrouterManagerState[g],"'"))},t}();f.TrouterManagerFsm=I},function(g,f,S){function o(g,f){if(!f)return g;var S=v(v({},g),{enabled:f.TelemetryEnabled});return void 0!==f.ClientTelemetryEventEnabled&&(S=v(v({},S),f.ClientTelemetryEventEnabled)),S}function i(g,f,S){var C,_,T,I,b,A,P,R,M,w,O,D,m=function(S){return g.proxyUrlRewrite?(f.info("Using rewritten URL for proxy"),g.proxyUrlRewrite(S)):S};return{clientInfo:{ua:g.trouterSettings.productName,v:g.trouterSettings.version},ioOptions:{ackTimeoutMs:5e3,rewriteUrlForProxy:m},clientCorrelationID:g.trouterSettings.sessionId,environment:g.trouterSettings.environment,telemetrySettings:o(g.telemetryConfig.settings,S),eventLogger:g.telemetryConfig.eventLogger,endpointId:g.trouterSettings.registrationId,trouterUrl:(null==S?void 0:S.TrouterConnectionUrl)||g.trouterSettings.trouterServiceUrl,registration:g.trouterSettings.registrarServiceUrl?{registrarUrl:g.trouterSettings.registrarServiceUrl,registrationId:null!==(C=g.trouterSettings.registrationId)&&void 0!==C?C:"",pnhAppId:null!==(_=g.trouterSettings.pnhAppId)&&void 0!==_?_:"",platform:null!==(T=g.trouterSettings.platform)&&void 0!==T?T:"",pnhTemplateKey:null!==(I=g.trouterSettings.pnhTemplate)&&void 0!==I?I:"",platformUIVersion:null!==(b=g.trouterSettings.platformUIVersion)&&void 0!==b?b:"",productContext:g.trouterSettings.pnhProductContext||void 0,context:null!==(A=g.trouterSettings.pnhContext)&&void 0!==A?A:"",registrarTtlSec:(null!==(P=g.trouterSettings.maxRegistrationTimeInMs)&&void 0!==P?P:0)/1e3}:void 0,connectionDependsOnRegistration:void 0===g.trouterSettings.registrarServiceUrl?function(){return!1}:null!==(R=g.trouterSettings.connectionDependsOnRegistration)&&void 0!==R?R:function(){return!1},delayEventsUntilRegistered:null!==(M=g.trouterSettings.delayEventsUntilRegistered)&&void 0!==M?M:function(){return!1},timeoutOptions:v({connectionTimeoutMs:g.trouterSettings.trouterConnectTimeoutInMs||3e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:"TeamsCDL"===g.trouterSettings.productName?3e5:3e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},g.trouterSettings.timeoutOptions),incallTimeoutOptions:v({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:"TeamsCDL"===g.trouterSettings.productName?3e5:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},g.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:null!==(w=g.trouterSettings.incallModeTimeoutMs)&&void 0!==w?w:0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:g.trouterSettings.userActivitySecondResendDelayMs||1e4,duplicateDisconnectThresholdMs:1e4,connectionCache:g.connectionCache,registrationStateCallback:g.registrationStateCallbackForAcsDoNotUse,rewriteUrlForProxy:m,retryLimitOnTokenFetch:g.trouterSettings.retryLimitOnTokenFetch,extraConnectionHeaders:g.trouterSettings.extraConnectionHeaders,expediteBackoffOnStartMinimumDelayMs:1e4,updateUserActivityDuringConnectionAttempt:null===(O=g.trouterSettings.updateUserActivityDuringConnectionAttempt)||void 0===O||O,initialConnectivityCheck:null===(D=g.trouterSettings.initialConnectivityCheck)||void 0===D||D,toJSON:function(){return v(v({},this),{connectionCache:this.connectionCache?{}:this.connectionCache})}}}function r(g){return new w(g)}function s(){return T.CLIENT_VERSION}function c(g,f){var S=g.indexOf("://");if(S>=0){var v=g.indexOf("/",S+3);if(v>=0)return f+g.substr(v)}return""}function a(g){var f=this;return function(S){return C(f,void 0,void 0,(function(){var f;return _(this,(function(v){switch(v.label){case 0:return f={},[4,g(S.needFresh)];case 1:return[2,(f.token=v.sent(),f.tokenType="skype",f)]}}))}))}}function u(g,f){var S,v=this;return function(T){return C(v,void 0,void 0,(function(){var v,C,I;return _(this,(function(_){switch(_.label){case 0:v=new Date,C=setInterval((function(){var f=Math.round((Date.now()-v.getTime())/6e4);g.warn("Note: Trouter auth token request promise from ".concat(v.toISOString()," has not been resolved for ").concat(f," minutes. The client is blocked from operating properly"))}),3e5),_.label=1;case 1:return _.trys.push([1,,3,4]),[4,f(T)];case 2:return I=_.sent(),T.needFresh&&I.token===S&&g.error("API violation: Trouter auth token provider got a request with needRefresh=true, but returned the same token as last time anyway. Please fix the host app"),S=I.token,[2,I];case 3:return clearInterval(C),[7];case 4:return[2]}}))}))}}var v=this&&this.__assign||function(){return v=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},v.apply(this,arguments)},C=this&&this.__awaiter||function(g,f,S,v){function i(g){return g instanceof S?g:new S((function(f){f(g)}))}return new(S||(S=Promise))((function(S,C){function s(g){try{a(v.next(g))}catch(g){C(g)}}function c(g){try{a(v.throw(g))}catch(g){C(g)}}function a(g){g.done?S(g.value):i(g.value).then(s,c)}a((v=v.apply(g,f||[])).next())}))},_=this&&this.__generator||function(g,f){function n(g){return function(f){return o([g,f])}}function o(I){if(S)throw new TypeError("Generator is already executing.");for(;_&&(_=0,I[0]&&(T=0)),T;)try{if(S=1,v&&(C=2&I[0]?v.return:I[0]?v.throw||((C=v.return)&&C.call(v),0):v.next)&&!(C=C.call(v,I[1])).done)return C;switch(v=0,C&&(I=[2&I[0],C.value]),I[0]){case 0:case 1:C=I;break;case 4:return T.label++,{value:I[1],done:!1};case 5:T.label++,v=I[1],I=[0];continue;case 7:I=T.ops.pop(),T.trys.pop();continue;default:if(!(C=(C=T.trys).length>0&&C[C.length-1])&&(6===I[0]||2===I[0])){T=0;continue}if(3===I[0]&&(!C||I[1]>C[0]&&I[1]<C[3])){T.label=I[1];break}if(6===I[0]&&T.label<C[1]){T.label=C[1],C=I;break}if(C&&T.label<C[2]){T.label=C[2],T.ops.push(I);break}C[2]&&T.ops.pop(),T.trys.pop();continue}I=f.call(g,T)}catch(g){I=[6,g],v=0}finally{S=C=0}if(5&I[0])throw I[1];return{value:I[0]?I[1]:void 0,done:!0}}var S,v,C,_,T={label:0,sent:function(){if(1&C[0])throw C[1];return C[1]},trys:[],ops:[]};return _={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(_[Symbol.iterator]=function(){return this}),_};Object.defineProperty(f,"__esModule",{value:!0}),f.replaceTrouterUrlBase=f.getTrouterServiceVersion=f.createTrouterService=f.TrouterService=f.UserActivityState=f.TrouterState=void 0;var T=S(1),I=S(2);Object.defineProperty(f,"TrouterState",{enumerable:!0,get:function(){return I.TrouterState}}),Object.defineProperty(f,"UserActivityState",{enumerable:!0,get:function(){return I.UserActivityState}});var b=S(0),A=S(8),P=S(9),R=S(10),M=S(11),w=function(){function t(g){this.logProvider=g,this.stateChangedListeners=[],this.logger=new b.Logger("Trouter",g),this.trouterUrlPromise=new M.TrouterUrlPromise(g),this.messageHandlers=new A.MessageHandlerRegistry(g),this.listeners={},this.connectionInfo=null,this.logger.info("Created TrouterService version ".concat(T.CLIENT_VERSION))}return t.prototype.start=function(g){var f;if(this.logger.info("Start"),!g.skypeTokenProvider&&!g.authTokenProvider)throw new Error("no token provider has been configured, either skypeTokenProvider or authTokenProvider must be populated");g.skypeTokenProvider&&!g.trouterSettings.disableInternalSkypeTokenCache&&(g.skypeTokenProvider=(0,P.addCacheAsBackupTo)(g.skypeTokenProvider)),this.trouterCfg=g;var S=i(g,this.logger,this.ecsCfg);!1===g.internalEnableV4cProtocol&&(S.forceV4aProtocol=!0);var v=u(this.logger,null!==(f=g.authTokenProvider)&&void 0!==f?f:a(g.skypeTokenProvider));void 0===this.trouterServer&&(this.trouterServer=new R.TrouterManager(this.logProvider,S,v,void 0===g.authTokenProvider,this)),void 0!==this.pendingActivityState&&(this.trouterServer.setUserActivityState(this.pendingActivityState[0],this.pendingActivityState[1]),this.pendingActivityState=void 0),this.trouterServer.start()},t.prototype.stop=function(g){this.logger.info("close connection"),this.trouterUrlPromise.rejectUrl(new Error("TrouterService is stopped")),void 0!==this.trouterServer&&this.trouterServer.stop(g)},t.prototype.setEcsConfig=function(g){return C(this,void 0,void 0,(function(){var f=this;return _(this,(function(S){return[2,new Promise((function(S){if(f.ecsCfg=g.TrouterJScriptClient,f.logger.info("Setting ECS configuration to ".concat(JSON.stringify(f.ecsCfg))),void 0!==f.trouterServer&&void 0!==f.trouterCfg){var v=i(f.trouterCfg,f.logger,f.ecsCfg);f.trouterServer.configure(v)}S()}))]}))}))},t.prototype.checkConnection=function(g){void 0!==this.trouterServer&&this.trouterServer.checkConnection(null!=g&&g)},t.prototype.resendRegistration=function(){return C(this,void 0,void 0,(function(){return _(this,(function(g){if(!this.trouterServer)throw new Error("resendRegistration called too early");return[2,this.trouterServer.resendRegistration()]}))}))},t.prototype.registerListener=function(g,f){return""===f||!f.startsWith("/")||f.includes("?")||f.includes("#")?(this.logger.error("Listener path '".concat(f,"' is not valid")),!1):this.listeners[f]?(this.logger.error("Another listener is already registered for path '".concat(f,"'")),!1):(this.listeners[f]=g,this.logger.debug("Listener for path '".concat(f,"' registered")),this.connectionInfo&&g.onTrouterConnected(this.connectionInfo.baseEndpointUrl+f,this.connectionInfo),!0)},t.prototype.unregisterListener=function(g){for(var f=[],S=0,v=Object.keys(this.listeners);S<v.length;S++){var C=v[S];this.listeners[C]===g&&f.push(C)}if(0===f.length)return!1;for(var _=0,T=f;_<T.length;_++)C=T[_],delete this.listeners[C];return this.logger.debug("Listener for path(s) '".concat(f.join("', '"),"' unregistered")),!0},t.prototype.onTrouterConnected=function(g,f){this.logger.debug("Trouter is now connected");for(var S=0,v=Object.keys(this.listeners);S<v.length;S++){var C=v[S];try{this.listeners[C].onTrouterConnected(f.baseEndpointUrl+C,f)}catch(g){this.logger.error("Listener '".concat(C,"' threw an exception from onTrouterConnected(): ").concat(g))}}this.connectionInfo=f,this.trouterUrlPromise.resolveUrl(g),this.notifyStateChanged(I.TrouterState.Connected,{url:g,getRemainingTtlInSec:function(){return f.connectionTtlSec}})},t.prototype.onTrouterDisconnected=function(){this.logger.debug("Trouter is now disconnected"),this.connectionInfo=null;for(var g=0,f=Object.keys(this.listeners);g<f.length;g++){var S=f[g],v=this.listeners[S];if(v.onTrouterDisconnected)try{v.onTrouterDisconnected()}catch(g){this.logger.error("Listener '".concat(S,"' threw an exception from onTrouterDisconnected(): ").concat(g))}}this.notifyStateChanged(I.TrouterState.Disconnected)},t.prototype.onTrouterRequest=function(g,f){for(var S="",v=0,C=Object.keys(this.listeners);v<C.length;v++){var _=C[v];g.path.startsWith(_)&&_.length>S.length&&(S=_)}if(""===S)this.tryMessageHandlers(g,f)||(f.status=404,f.headers={"Trouter-Responder":"ClientLib"},f.send());else try{this.listeners[S].onTrouterRequest(g,f)}catch(g){this.logger.error("Listener '".concat(S,"' threw an exception from onTrouterRequest(): ").concat(g)),f.status=500,f.headers={"Trouter-Responder":"ClientLib"},f.send()}},t.prototype.onTrouterMessageLoss=function(g){this.logger.info("onTrouterMessageLoss called with tags [".concat(g,"]"));for(var f=!0,S=0,v=Object.keys(this.listeners);S<v.length;S++){var C=v[S],_=this.listeners[C];if(_.onTrouterMessageLoss)try{void 0===(f=_.onTrouterMessageLoss(g)&&f)&&(this.logger.error("Listener '".concat(C,"' did not return a boolean value from onTrouterMessageLoss()")),f=!1)}catch(g){this.logger.error("Listener '".concat(C,"' threw an exception from onTrouterMessageLoss(): ").concat(g)),f=!1}}return f},t.prototype.onTrouterUserActivityStateAccepted=function(g){this.logger.debug("onTrouterUserActivityStateAccepted cv: ".concat(g));for(var f=0,S=Object.keys(this.listeners);f<S.length;f++){var v=S[f],C=this.listeners[v];if(C.onTrouterUserActivityStateAccepted)try{C.onTrouterUserActivityStateAccepted(g)}catch(g){this.logger.error("Listener '".concat(v,"' threw an exception from onTrouterUserActivityStateAccepted(): ").concat(g))}}},t.prototype.onAudiencesSetResolved=function(g,f){this.logger.debug("onAudiencesSetResolved cv: ".concat(f));for(var S=0,v=Object.keys(this.listeners);S<v.length;S++){var C=v[S],_=this.listeners[C];if(_.onAudiencesSetResolved)try{_.onAudiencesSetResolved(g,f)}catch(g){this.logger.error("Listener '".concat(C,"' threw an exception from onAudienceSubscribed(): ").concat(g))}}},t.prototype.setUserActivityState=function(g,f){if(g!==I.UserActivityState.Active&&g!==I.UserActivityState.Inactive)throw new Error("setUserActivityState called with unsupported value ".concat(g));this.logger.info("setUserActivityState called with value ".concat(I.UserActivityState[g])),this.trouterServer&&this.state()!==I.TrouterState.Unknown?this.trouterServer.setUserActivityState(g,f):(this.pendingActivityState=[g,f],this.logger.warn("setUserActivityState called before start() or after stop()"))},t.prototype.setAudienceSubscriptions=function(g,f){if(g.audienceSubscriptions.length>1)throw new Error("Only singular audience subscription is supported");if(this.trouterServer&&this.state()!==I.TrouterState.Unknown)return this.trouterServer.setAudienceSubscriptionsAsync(g,15e3,f);throw new Error("audience subscribe called before start() or after stop()")},t.prototype.state=function(){return void 0!==this.trouterServer?this.trouterServer.getState():I.TrouterState.Unknown},t.prototype.isInTerminalState=function(){return void 0!==this.trouterServer&&this.trouterServer.isInTerminalState()},t.prototype.reportStateInfo=function(){return void 0===this.trouterServer?"":this.trouterServer.reportStateInfo()},t.prototype.getServerState=function(){if(void 0!==this.trouterServer)return this.trouterServer.getServerState()},t.prototype.getTrouterUrlAsync=function(){return void 0!==this.trouterServer?this.trouterUrlPromise.getPromise():Promise.reject(new Error("TrouterService has not been started"))},t.prototype.onStateChanged=function(g){if(this.logger.info("onStateChanged called"),void 0===g)this.stateChangedListeners=this.stateChangedListeners.filter((function(g){return void 0===g.wrappedCallback}));else{this.offStateChanged(g);var e=function(f,S){g(f,S?S.url:"")};e.wrappedCallback=g,this.stateChangedListeners.push(e)}},t.prototype.offStateChanged=function(g){this.logger.info("offStateChanged called");var f=this.stateChangedListeners.length;return this.stateChangedListeners=this.stateChangedListeners.filter((function(f){return f.wrappedCallback!==g})),f>this.stateChangedListeners.length},t.prototype.addCallback=function(g){this.logger.info("addListener called"),-1===this.stateChangedListeners.indexOf(g,0)&&void 0!==g&&this.stateChangedListeners.push(g)},t.prototype.removeCallback=function(g){this.logger.info("removeListener called");var f=this.stateChangedListeners.indexOf(g,0);return f>-1&&(this.stateChangedListeners.splice(f,1),!0)},t.prototype.registerMessageHandler=function(g){this.logger.info("registerMessageHandler is called"),this.messageHandlers.register(g)},t.prototype.clearMessageHandlers=function(){this.logger.info("clearMessageHandlers is called"),this.messageHandlers.clear()},t.prototype.notifyStateChanged=function(g,f){var S=this;this.logger.info("notifyStateChanged called, will forward to ".concat(this.stateChangedListeners.length," listeners")),this.stateChangedListeners.forEach((function(v){try{v(g,f)}catch(g){S.logger.error("Error in callback ".concat(g))}}))},t.prototype.tryMessageHandlers=function(g,f){if(!this.messageHandlers.active())return!1;var S,v=null;try{v=(S=JSON.parse(g.body))&&(S.evt||S.eventId)||null}catch(g){}var C={eventId:v,url:(this.connectionInfo?this.connectionInfo.baseEndpointUrl:"")+g.path,body:S,rawBody:g.body,headers:g.headers},_=this.messageHandlers.handleMessage(C);return!!_.isHandled&&(f.status=_.resultCode,_.responseHeaders&&(f.headers=_.responseHeaders),_.responseBody&&(f.body=_.responseBody),f.send(),!0)},t}();f.TrouterService=w,f.createTrouterService=r,f.getTrouterServiceVersion=s,f.replaceTrouterUrlBase=c},function(f,S){f.exports=g}])},g.exports=S(dA)}));class TelemetrySender{constructor(g,f){this.logEvent=g=>{this._logger.debug(g),this._telemetryLogManager.sendEvent({name:g.name,tenant:af,properties:{...g.properties}})},this._logger=g.createChild("TelemetrySender"),this._telemetryLogManager=f}}class Trouter{constructor(g,f,S,v,C){this._ecsProvider=f,this._tokenProvider=S,this._isRegistered=!1,this._registeredChangedListeners=[],this._logger=g.createChild("Trouter"),this._logger.info("init"),this._initialRegistrationCompleteDefer=defer$1(),this._telemetryLogManager=v,this._acsProxy=C}async start(g){let f;if(this._trouterService)throw this._logger.error("Trouterservice already initialized"),new CallingCommunicationError({defaultError:D.CALL_STACK.SIGNALING_SERVICE_ALREADY_INITIALIZED});{const S=new Promise((async(f,S)=>{try{if(this._logger.info("Trouterservice start"),this._trouterService=hA.createTrouterService(this._logger),!this._trouterService)throw this._logger.error("Failed to create trouter service"),new CallingCommunicationError({defaultError:D.CALL_STACK.SIGNALING_SERVICE_CREATE_FAIL});this._options=this._getTrouterConfig(this._logger,this._tokenProvider),g&&(this._options.trouterSettings.environment=g.environment||"",this._options.trouterSettings.sessionId=g.sessionId);let S,v,C=+new Date;this._trouterService.start(this._options),this._trouterService.onStateChanged(((g,f)=>{g===hA.TrouterState.Connected&&(S=+new Date)})),await this._initialRegistrationCompleteDefer.promise;const _=+new Date;S=S??+new Date,v=S,f({trouterRequestCompletionTimeDeltaMs:Math.max(0,S-C),registrarRequestCompletionTimeDeltaMs:Math.max(0,_-v)})}catch(g){S(g)}}));try{const g=wait((()=>S),Am);f=await g}catch(g){throw 408===g.code?(this._logger.error("Signaling init timeout"),new CallingCommunicationError({defaultError:D.CALL_STACK.SIGNALING_SERVICE_CREATE_TIMEOUT,defaultErrorMessageArgs:[Am]})):(this._logger.error("Signaling init failed"),new CallingCommunicationError({defaultError:D.CALL_STACK.SIGNALING_INIT_FAIL}))}}return f}isRegistered(){return this._isRegistered}onRegisteredChanged(g){this._logger.info("TrouterService onRegisteredChanged"),this._registeredChangedListeners.push(g)}offRegisteredChanged(g){const f=this._registeredChangedListeners.indexOf(g);this._logger.info(`TrouterService offRegisteredChanged: ${f}`),f>-1&&this._registeredChangedListeners.splice(f,1)}stop(g){this._logger.info("Trouterservice stop"),this._trouterService?(this._trouterService.onStateChanged(void 0),this._trouterService.stop(g),this._trouterService=void 0):this._logger.error("Trouterservice not inited")}registerMessageHandler(g){this._logger.info("Trouterservice registerMessageHandler"),this._trouterService&&this._trouterService.registerMessageHandler(g)}clearMessageHandlers(){this._trouterService&&this._trouterService.clearMessageHandlers()}checkConnection(){this._trouterService&&this._trouterService.checkConnection()}state(){return this._logger.info("Trouterservice state"),this._trouterService?this._trouterService.state():hA.TrouterState.Unknown}onStateChanged(g){this._logger.info("Trouterservice onStateChanged"),this._trouterService&&this._trouterService.onStateChanged(g)}offStateChanged(g){this._logger.info("Trouterservice offStateChanged"),this._trouterService&&this._trouterService.offStateChanged(g)}getTrouterUrlAsync(){return this._trouterService?(this._logger.info("getTrouterUrlAsync called"),this._trouterService.getTrouterUrlAsync()):Promise.reject("Trouterservice not started yet")}getTrouterSettings(){return this._options.trouterSettings}_getSettings(){return{registrationId:generateGuid(),registrarServiceUrl:this._ecsProvider.getTrouterSettings().registrarServiceUrl,registrarTtlInSeconds:this._ecsProvider.getTrouterSettings().registrarTtlInSeconds,maxRegistrationTimeInMs:this._ecsProvider.getTrouterSettings().maxRegistrationTimeInMs,registrarRefreshTimeoutInMs:this._ecsProvider.getTrouterSettings().registrarRefreshTimeoutInMs,pnhAppId:this._ecsProvider.getTrouterSettings().pnhAppId,pnhTemplate:this._ecsProvider.getTrouterSettings().pnhTemplate,platform:this._ecsProvider.getTrouterSettings().platform,platformUIVersion:this._ecsProvider.getTrouterSettings().version,trouterServiceUrl:this._ecsProvider.getTrouterSettings().trouterServiceUrl,version:this._ecsProvider.getTrouterSettings().version,trouterConnectTimeoutInMs:this._ecsProvider.getTrouterSettings().trouterConnectTimeoutInMs,productName:this._ecsProvider.getTrouterSettings().productName,sessionId:generateGuid(),environment:this._ecsProvider.getTrouterSettings().environment,timeoutOptions:this._ecsProvider.getTrouterSettings().timeoutOptions}}_createTrouterTelemetryConfig(g){return{eventLogger:new TelemetrySender(g.createChild("TrouterTelemetry"),this._telemetryLogManager),settings:{enabled:this._ecsProvider.getTrouterTelemetryConfig().enabled,logHealthCheckError:this._ecsProvider.getTrouterTelemetryConfig().logHealthCheckError,trouter_js_client_connected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_connected,trouter_js_client_disconnected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_disconnected,trouter_js_client_error:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_error,trouter_js_client_progress:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_progress,trouter_js_client_response:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_response,numberOfStepsToMaintain:this._ecsProvider.getTrouterTelemetryConfig().numberOfStepsToMaintain,sendProgressTimeoutSecs:this._ecsProvider.getTrouterTelemetryConfig().sendProgressTimeoutSecs}}}_getTrouterConfig(g,f){return{trouterSettings:this._getSettings(),proxyUrlRewrite:this._acsProxy.hasProxyUrl()?g=>this._acsProxy.proxyfyUrl(g):void 0,skypeTokenProvider:f,telemetryConfig:this._createTrouterTelemetryConfig(g),registrationStateCallbackForAcsDoNotUse:g=>{this._logger.info(`TrouterService registrationStateCallbackForAcs: ${g}`),this._isRegistered=g,this._initialRegistrationCompleteDefer.isPending()&&this._isRegistered?this._initialRegistrationCompleteDefer.resolve():this._isRegistered?this._logger.info("Signaling service is currently registered"):this._logger.error("Signaling service is currently not registered. Unable to receive incoming calls"),this._onRegisteredChanged(g)}}}_onRegisteredChanged(g){this._logger.info(`TrouterService onRegisteredChanged: ${g}`),this._registeredChangedListeners.forEach((f=>{f(g)}))}}class TelemetryService{constructor(g){this._eventToTenantId={skypecosi_concore_web_csa_conversation_httprequest:nf,skypecosi_concore_web_ts_calling_in_call_session:nf,skypecosi_concore_web_ts_calling_call_setup_session:nf,skypecosi_concore_native_ts_calling_in_call_session:nf,skypecosi_concore_native_ts_calling_call_setup_session:nf,skypecosi_concore_web_pluginless_call_session:nf,skypecosi_concore_web_pluginless_modality_session:nf,skypecosi_concore_web_csa_conversation_callmodality:nf,skypecosi_concore_web_ts_calling_registry:nf,mdsc_webrtc_session:rf,mdsc_webrtc_session_initial:rf,live_events:sf,mdsc_ortc_reports:rf,mdsc_ortc_reports_initial:rf,mdsc_rt_log:rf},this.getTenant=g=>this._eventToTenantId[g]?this._eventToTenantId[g]:"",this.getCallingAdapter=()=>({sendEvent:(g,f)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(g),name:g,properties:f})}}),this.getGenericTelemetryLogger=g=>({sendEvent:g=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(g.eventName),name:g.eventName,properties:g.props})}}),this.getMediaAdapter=()=>({sendEvent:(g,f)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(g),name:g,properties:f})}}),this.sendEvents=g=>(g.forEach((g=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(g.eventName),name:g.eventName,properties:g.props})})),Promise.resolve()),this._telemetryLogManager=g}}class WebCVProvider{constructor(){this._timedVideoEffectProviderPromise=timedDefer(H),this._timedModelConfigPromise=timedDefer(H)}get videoEffectProviderDeferredPromise(){return this._timedVideoEffectProviderPromise.deferredPromise}get modelConfigDeferredPromise(){return this._timedModelConfigPromise.deferredPromise}async getVideoEffectProvider(){return this._timedVideoEffectProviderPromise.timerStart(),this._timedVideoEffectProviderPromise.deferredPromise.promise}async getModelConfig(){return this._timedModelConfigPromise.deferredPromise.resolve({modelUrl:"",weightPathPrefix:""}),this._timedModelConfigPromise.deferredPromise.promise}}class EncodedStreamsWorkerProvider{constructor(g){this._encodedStreamsJsPath=g}async getWorkerUrl(){return this._encodedStreamsJsPath}}class HttpRequestDispatcher{constructor(g,f){f||"function"!=typeof g.createChild?this.logger=g:this.logger=g.createChild("JS.TsCalling.RequestDispatcher"),this.proxy=f}getRequestOptions(g,f,S,v,C){return{headers:f||{},timeout:v,payload:S||null,responseType:C}}getAsync(g,f){return this.sendRequest(this.proxy?this.proxy.proxyfyUrl(g):g,f,"GET")}postAsync(g,f){return this.sendRequest(this.proxy?this.proxy.proxyfyUrl(g):g,f,"POST")}putAsync(g,f){return this.sendRequest(this.proxy?this.proxy.proxyfyUrl(g):g,f,"PUT")}removeAsync(g,f){return this.sendRequest(this.proxy?this.proxy.proxyfyUrl(g):g,f,"DELETE")}async sendRequest(g,f={headers:{}},S){const v=this.logger.createChild(`[${f.causeId||generateGuid()}][Request]`);v.info(`sending, ${S}-${g}`);const C=Date.now();let _;f.headers=f.headers||{},f.headers["content-type"]||(f.headers["content-type"]=f.contentType||"application/json");let T={url:g,start:new Date(C).toISOString(),end:"",statusCode:0,deltaTimeInMs:0,causeId:""};const I=getAcsEcsConfig().telemetry.apiCauseIdHeader;try{const b=TI.request({url:g,method:S,headers:f.headers||{},timeout:"number"==typeof f.timeout?f.timeout:45e3,data:f.payload||"",responseType:f.responseType||f.dataType||"json",withCredentials:valueOrDefault(f.withCredentials,!1),cancelToken:new TI.CancelToken((g=>{_=g}))});isPromiseLike$1(f.timeout)&&f.timeout.then((()=>{v.info("Aborting pending request"),_()}),(()=>{v.info("Timeout promise rejected, ignoring")}));const A=await b;if(v.info(`success, status=${A.status}`),f.headers[I]){const g=f.headers[I].split("-")[0];B_.getRemoveCauseIdToNetworkInfo(g)&&(T={...T,end:(new Date).toISOString(),statusCode:A.status,deltaTimeInMs:Date.now()-C,causeId:g},B_.setCauseIdToNetworkInfo(g,T))}return{response:A.data,request:A.request,duration:Date.now()-C}}catch(g){if(v.info("failed"),f.headers[I]){const S=f.headers[I].split("-")[0];B_.ifCauseIdExistsRemoveNetworkInfo(S)&&(T={...T,end:(new Date).toISOString(),statusCode:g.code,deltaTimeInMs:Date.now()-C,causeId:S},B_.setCauseIdToNetworkInfo(S,T))}if(TI.isCancel(g))throw v.info(`response=${safeJsonStringify(g.message)}`),{aborted:!0};throw g.response?v.info(`response=${safeJsonStringify(g.response)}`):g.request?v.info(`no response, request=${safeJsonStringify(g.request)}`):v.info(`request not made, error=${safeJsonStringify(g)}`),g||new Error("Request failed")}}}class VideoEffectsStatusManager{constructor(){this._activeEffects=[],this.eventEmitter=new LE.EventEmitter}on(g,f){if("statusChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}off(g,f){if("statusChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.off(g,f)}getActiveEffects(){return this._activeEffects}setActiveEffects(g){const f=this._activeEffects;this._activeEffects=g,this.eventEmitter.emit("statusChanged",f,this._activeEffects)}}class AudioEffectsStatusManager{constructor(){this._activeEffects={echoCancellation:[],noiseSuppression:[],autoGainControl:[]},this.eventEmitter=new LE.EventEmitter}on(g,f){if("statusChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.on(g,f)}off(g,f){if("statusChanged"!==g)throw new CallingCommunicationError({defaultError:D.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this.eventEmitter.off(g,f)}getActiveEffects(){return this._activeEffects}setActiveEffects(g,f){const S={...this._activeEffects};this._activeEffects={...g},this.eventEmitter.emit("statusChanged",S,this._activeEffects,f)}}class WasmVqeProvider{get providerValue(){return this._providerValue}set providerValue(g){this._providerValue=g}async getAudioEffectProvider(){return this.providerValue}}var uA,gA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0});var S=function(){function AllowBackgroundFetchData(){this._isAllowed=!1}return AllowBackgroundFetchData.prototype.putBackgroundFetchAllowed=function(g){if(this._isAllowed=g,this.isBackgroundFetchAllowed()&&this._isAllowedDeferral){var f=this._isAllowedDeferral;this._isAllowedDeferral=void 0,f.resolve(void 0)}},AllowBackgroundFetchData.prototype.isBackgroundFetchAllowed=function(){return this._isAllowed},AllowBackgroundFetchData.prototype.waitForBackgroundFetchAllowed=function(){return this.isBackgroundFetchAllowed()?I.Resolved():(this._isAllowedDeferral||(this._isAllowedDeferral=I.Defer()),this._isAllowedDeferral.promise())},AllowBackgroundFetchData}();f.default=S})),pA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0});var S=function(){function AppActiveData(){this._isActive=!1}return AppActiveData.prototype.putAppActive=function(g){if(this._isActive=g,this.isAppActive()&&this._appActiveDeferral){var f=this._appActiveDeferral;this._appActiveDeferral=void 0,f.resolve(void 0)}},AppActiveData.prototype.isAppActive=function(){return this._isActive},AppActiveData.prototype.waitForAppActive=function(){return this.isAppActive()?I.Resolved():(this._appActiveDeferral||(this._appActiveDeferral=I.Defer()),this._appActiveDeferral.promise())},AppActiveData}();f.default=S})),mA=function(){function SubscriptionToken(g,f){this._event=g,this._callback=f}return SubscriptionToken.prototype.unsubscribe=function(){this._event.unsubscribe(this._callback)},SubscriptionToken}(),fA=function(){function SubscribableEvent(g){void 0===g&&(g=!1);var f=this;this._allowStopPropagation=g,this.fire=function(){for(var g=[],S=0;S<arguments.length;S++)g[S]=arguments[S];for(var v=f._subscribers,C=v.length-1;C>=0;C--){var _=v[C].apply(null,g);if(f._allowStopPropagation&&_)return!0}return!1},this._subscribers=[]}return SubscribableEvent.prototype.dispose=function(){this._subscribers=[]},SubscribableEvent.prototype.subscribe=function(g){return this._subscribers=this._subscribers.concat(g),new mA(this,g)},SubscribableEvent.prototype.unsubscribe=function(g){this._subscribers=this._subscribers.filter((function(f){return f!==g}))},SubscribableEvent}(),SA=Object.freeze({__proto__:null,SubscriptionToken:mA,default:fA}),vA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),function(g){g[g.Default=0]="Default",g[g.User=1]="User"}(f.EcsConfigType||(f.EcsConfigType={}))})),CA=getAugmentedNamespace(SA),yA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0});var S=function(){function Cache(g){this._config=g,this.configUpdated=new CA.default,this._cachedConfigs={}}return Cache.prototype.initialize=function(){return this.updateConfigsToFetch()},Cache.prototype.updateConfigsToFetch=function(){var g=this,f=this._config.getConfig(),S=f.databaseInterface,v=f.configsToFetch;if(!S)return I.Resolved();for(var C=[],_loop_1=function(f){if(_._cachedConfigs[f])return"continue";C.push(S.getData(f).then((function(S){S&&(g._cachedConfigs[f]=S)})).catch((function(){return I.Resolved()})))},_=this,T=0,b=v;T<b.length;T++){_loop_1(b[T])}return I.all(C).then((function(){C.length>0&&g.configUpdated.fire()}))},Cache.prototype.getEcsConfig=function(){return this._cachedConfigs[vA.EcsConfigType.User]||this._cachedConfigs[vA.EcsConfigType.Default]},Cache.prototype.getEcsConfigByType=function(g){return this._cachedConfigs[g]},Cache.prototype.putConfig=function(g){var f=this.getEcsConfig();this._cachedConfigs[g.configType]=g;var S=this.getEcsConfig();(S&&S.configType===g.configType||f&&S&&f.configType!==S.configType)&&this.configUpdated.fire();var v=this._config.getConfig().databaseInterface;return v?v.putData(g.configType,g):I.Resolved()},Cache}();f.default=S})),EA=createCommonjsModule((function(g,f){var S=C&&C.__assign||function(){return S=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},S.apply(this,arguments)};Object.defineProperty(f,"__esModule",{value:!0});var v=function(){function Config(){}return Config.prototype.initialize=function(g){if(this._config)throw new Error("ECS Configuration already initialized");this._config=g},Config.prototype.getConfig=function(){if(!this._config)throw new Error("ECS Configuration not yet initialized");return this._config},Config.prototype.setConfigsToFetch=function(g){if(!this._config)throw new Error("ECS Configuration not yet initialized");this._config=S(S({},this._config),{configsToFetch:g})},Config.prototype.setFetchTimeout=function(g){if(!this._config)throw new Error("ECS Configuration not yet initialized");this._config=S(S({},this._config),{fetchTimeout:g})},Config}();f.default=v})),_A=createCommonjsModule((function(g,f){var S=C&&C.__assign||function(){return S=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},S.apply(this,arguments)};Object.defineProperty(f,"__esModule",{value:!0}),f.assert=function(g,f){if(!g)throw new Error(f)},f.isObject=function(g){return null!==g&&"object"==typeof g},f.isString=function(g){return"string"==typeof g},f.attempt=function(g){for(var f=[],S=1;S<arguments.length;S++)f[S-1]=arguments[S];try{return g.apply(void 0,f)}catch(g){return new Error(g)}},f.remove=function(g,f){for(var S=g.length-1;S>=0;S--)g[S]===f&&g.splice(S,1)},f.clone=function(g){return Array.isArray(g)?g.map(f.clone):f.isObject(g)?Object.keys(g).reduce((function(v,C){var _;return S(S({},v),((_={})[C]=f.clone(g[C]),_))}),{}):g}})),TA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.DEFAULT_TIME_GROW_FACTOR=2.718281828459045,f.DEFAULT_TIME_JITTER=.11962656472;var S=function(){function ExponentialTime(g,S,v,C){void 0===v&&(v=f.DEFAULT_TIME_GROW_FACTOR),void 0===C&&(C=f.DEFAULT_TIME_JITTER),this._initialTime=g,this._maxTime=S,this._growFactor=v,this._jitterFactor=C,_A.assert(this._initialTime>0,"Initial delay must be positive"),_A.assert(this._maxTime>0,"Delay upper bound must be positive"),_A.assert(this._growFactor>=0,"Ratio must be non-negative"),_A.assert(this._jitterFactor>=0,"Jitter factor must be non-negative"),this.reset()}return ExponentialTime.prototype.reset=function(){this._incrementCount=0,this._currentTime=Math.round(this._initialTime*(1+Math.random()*this._jitterFactor))},ExponentialTime.prototype.getTime=function(){return this._currentTime},ExponentialTime.prototype.getIncrementCount=function(){return this._incrementCount},ExponentialTime.prototype.calculateNext=function(){var g=this._currentTime*this._growFactor;return g>this._maxTime&&(g=this._maxTime),this._jitterFactor<1e-5?this._currentTime=g:this._currentTime=Math.round(Math.random()*g*this._jitterFactor+g),this._currentTime<this._initialTime&&(this._currentTime=this._initialTime),this._currentTime>this._maxTime&&(this._currentTime=this._maxTime),this._incrementCount++,this._currentTime},ExponentialTime.prototype.getTimeAndCalculateNext=function(){var g=this.getTime();return this.calculateNext(),g},ExponentialTime}();f.ExponentialTime=S})),IA=createCommonjsModule((function(g,f){var S,v,_,T=C&&C.__extends||(S=function(g,f){return S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f.hasOwnProperty(S)&&(g[S]=f[S])},S(g,f)},function(g,f){function __(){this.constructor=g}S(g,f),g.prototype=null===f?Object.create(f):(__.prototype=f.prototype,new __)}),b=C&&C.__assign||function(){return b=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},b.apply(this,arguments)};function isJsonContentType(g){return!!g&&0===g.indexOf("application/json")}function isFormContentType(g){return!!g&&0===g.indexOf("application/x-www-form-urlencoded")}function isFormDataContentType(g){return!!g&&0===g.indexOf("multipart/form-data")}function DefaultErrorHandler(g,f){return f.canceled||!f.statusCode||f.statusCode>=400&&f.statusCode<600?_.DoNotRetry:_.RetryCountedWithBackoff}Object.defineProperty(f,"__esModule",{value:!0}),function(g){g[g.DontCare=0]="DontCare",g[g.Low=1]="Low",g[g.Normal=2]="Normal",g[g.High=3]="High",g[g.Critical=4]="Critical"}(v=f.WebRequestPriority||(f.WebRequestPriority={})),function(g){g[g.DoNotRetry=0]="DoNotRetry",g[g.RetryUncountedImmediately=1]="RetryUncountedImmediately",g[g.RetryUncountedWithBackoff=2]="RetryUncountedWithBackoff",g[g.RetryCountedWithBackoff=3]="RetryCountedWithBackoff",g[g.PauseUntilResumed=4]="PauseUntilResumed"}(_=f.ErrorHandlingType||(f.ErrorHandlingType={})),f.DefaultOptions={priority:v.Normal},f.SimpleWebRequestOptions={MaxSimultaneousRequests:5,HungRequestCleanupIntervalMs:1e4,setTimeout:function(g,f){return setTimeout(g,f)},clearTimeout:function(g){return clearTimeout(g)}},f.DefaultErrorHandler=DefaultErrorHandler;var A,P=[],R=[],M=[],w=0,O=0,D=function(){function SimpleWebRequestBase(g,S,v,C,_){this._action=g,this._url=S,this.options=v,this._getHeaders=C,this._blockRequestUntil=_,this._aborted=!1,this._timedOut=!1,this._paused=!1,this._created=Date.now(),this._finishHandled=!1,this._retryExponentialTime=new TA.ExponentialTime(1e3,3e5),this._options=b(b({},f.DefaultOptions),v)}return SimpleWebRequestBase.prototype.getPriority=function(){return this._options.priority||v.DontCare},SimpleWebRequestBase.checkQueueProcessing=function(){for(var _loop_1=function(){var g=P.shift();R.push(g),(g._blockRequestUntil&&g._blockRequestUntil()||I.Resolved()).finally((function(){_A.remove(R,g)})).then((function(){M.length<f.SimpleWebRequestOptions.MaxSimultaneousRequests&&!g._aborted?(M.push(g),N._scheduleHungRequestCleanupIfNeeded(),g._fire()):g._enqueue()}),(function(f){g._respond("_blockRequestUntil rejected: "+f)}))};P.length>0&&M.length<f.SimpleWebRequestOptions.MaxSimultaneousRequests;)_loop_1()},SimpleWebRequestBase._scheduleHungRequestCleanupIfNeeded=function(){M.length>0&&void 0===A?A=f.SimpleWebRequestOptions.setTimeout(this._hungRequestCleanupTimerCallback,f.SimpleWebRequestOptions.HungRequestCleanupIntervalMs):0===M.length&&A&&(f.SimpleWebRequestOptions.clearTimeout(A),A=void 0)},SimpleWebRequestBase.prototype._removeFromQueue=function(){_A.remove(M,this),_A.remove(P,this)},SimpleWebRequestBase.prototype._assertAndClean=function(g,f){g||(this._removeFromQueue(),console.error(f),_A.assert(g,f))},SimpleWebRequestBase.prototype._fire=function(){var g=this;this._xhr=new XMLHttpRequest,this._xhrRequestHeaders={};var S=_A.attempt((function(){g._xhr.open(g._action,g._url,!0)}));if(S)this._respond(S.toString());else{if(this._options.timeout){var v=O;3!==v&&(this._assertAndClean(!this._requestTimeoutTimer,"Double-fired requestTimeoutTimer"),this._requestTimeoutTimer=f.SimpleWebRequestOptions.setTimeout((function(){g._requestTimeoutTimer=void 0,g._timedOut=!0,g.abort()}),this._options.timeout)),(3===v||v<=1)&&(this._xhr.timeout=this._options.timeout,this._xhr.ontimeout=function(){O=3,3===v&&(g._timedOut=!0,g._aborted=!0,g._respond("TimedOut"))})}var C=w;3!==C?(0===C&&(w=1),this._xhr.onreadystatechange=function(){g._xhr&&(3!==g._xhr.readyState||!g._options.streamingDownloadProgress||g._aborted?4===g._xhr.readyState&&(0===C&&1===w&&f.SimpleWebRequestOptions.setTimeout((function(){3!==w&&(w=2)}),1e4),g._respond()):g._options.streamingDownloadProgress(g._xhr.responseText))}):this._options.streamingDownloadProgress&&(this._xhr.onreadystatechange=function(){g._xhr&&3===g._xhr.readyState&&g._options.streamingDownloadProgress&&!g._aborted&&g._options.streamingDownloadProgress(g._xhr.responseText)}),2!==C&&(this._xhr.onload=function(){w=3,3===C&&g._respond()},this._xhr.onerror=function(){w=3,3===C&&g._respond()}),this._xhr.onabort=function(){g._aborted=!0,g._respond("Aborted")},this._xhr.upload&&this._options.onProgress&&(this._xhr.upload.onprogress=this._options.onProgress);var _=this._options.acceptType||"json",T=this._options.customResponseType||SimpleWebRequestBase._getResponseType(_),I=_A.attempt((function(){g._xhr.responseType=T}));if(I&&"json"!==T)throw I;N._setRequestHeader(this._xhr,this._xhrRequestHeaders,"Accept",SimpleWebRequestBase.mapContentType(_)),this._xhr.withCredentials=!!this._options.withCredentials;var b=this.getRequestHeaders(),A={};if(Object.keys(b).forEach((function(f){var S=b[f],v=f.toLowerCase();"content-type"!==v?"accept"!==v?(g._assertAndClean(!A[v],"Setting duplicate header key: "+A[v]+" and "+f),null!=S?(A[v]=!0,N._setRequestHeader(g._xhr,g._xhrRequestHeaders,f,S)):console.warn('Tried to set header "'+f+'" on request with "'+S+'" value, header will be dropped')):g._assertAndClean(!1,"Don't set Accept with options.headers -- use it with the options.acceptType property"):g._assertAndClean(!1,"Don't set Content-Type with options.headers -- use it with the options.contentType property")})),this._options.sendData){var P=SimpleWebRequestBase.mapContentType(this._options.contentType||"json");N._setRequestHeader(this._xhr,this._xhrRequestHeaders,"Content-Type",P);var R=SimpleWebRequestBase.mapBody(this._options.sendData,P);this._xhr.send(R)}else this._xhr.send()}},SimpleWebRequestBase._setRequestHeader=function(g,f,S,v){g.setRequestHeader(S,v),f[S]=v},SimpleWebRequestBase.mapContentType=function(g){return"json"===g?"application/json":"form"===g?"application/x-www-form-urlencoded":g},SimpleWebRequestBase.mapBody=function(g,f){if(isJsonContentType(f)){if(!_A.isString(g))return JSON.stringify(g)}else if(isFormContentType(f)){if(!_A.isString(g)&&_A.isObject(g)){var S=g;return Object.keys(S).map((function(g){return encodeURIComponent(g)+(S[g]?"="+encodeURIComponent(S[g].toString()):"")})).join("&")}}else if(isFormDataContentType(f)){if(_A.isObject(g)){var v=new FormData,C=g;return Object.keys(C).forEach((function(g){return v.append(g,C[g])})),v}_A.assert(!1,"contentType multipart/form-data must include an object as sendData")}return g},SimpleWebRequestBase.prototype.setUrl=function(g){this._url=g},SimpleWebRequestBase.prototype.setHeader=function(g,f){this._options.augmentHeaders||(this._options.augmentHeaders={}),f?this._options.augmentHeaders[g]=f:delete this._options.augmentHeaders[g]},SimpleWebRequestBase.prototype.getRequestHeaders=function(){var g={};return!this._getHeaders||this._options.overrideGetHeaders||this._options.headers||(g=b(b({},g),this._getHeaders())),this._options.overrideGetHeaders&&(g=b(b({},g),this._options.overrideGetHeaders)),this._options.headers&&(g=b(b({},g),this._options.headers)),this._options.augmentHeaders&&(g=b(b({},g),this._options.augmentHeaders)),g},SimpleWebRequestBase.prototype.getOptions=function(){return _A.clone(this._options)},SimpleWebRequestBase.prototype.setPriority=function(g){this._options.priority!==g&&(this._options.priority=g,this._paused||this._xhr||(_A.remove(P,this),this._enqueue()))},SimpleWebRequestBase.prototype.resumeRetrying=function(){this._paused?(this._paused=!1,this._enqueue()):_A.assert(!1,"resumeRetrying() called but not paused!")},SimpleWebRequestBase.prototype._enqueue=function(){var g=this;if(!this._aborted&&!(M.indexOf(this)>=0||R.indexOf(this)>=0||P.indexOf(this)>=0)){var f=P.findIndex((function(f){return f.getPriority()===g.getPriority()&&f._created>g._created||f.getPriority()<g.getPriority()}));f>-1?P.splice(f,0,this):P.push(this),SimpleWebRequestBase.checkQueueProcessing()}},SimpleWebRequestBase._getResponseType=function(g){return"blob"===g?"arraybuffer":"text/xml"===g||"application/xml"===g?"document":"text/plain"===g?"text":"json"},SimpleWebRequestBase._hungRequestCleanupTimerCallback=function(){A=void 0,M.filter((function(g){return!(!g._xhr||4!==g._xhr.readyState)&&(console.warn("SimpleWebRequests found a completed XHR that hasn't invoked it's callback functions, manually responding"),!0)})).forEach((function(g){g._respond()})),N._scheduleHungRequestCleanupIfNeeded()},SimpleWebRequestBase}();f.SimpleWebRequestBase=D;var N=function(g){function SimpleWebRequest(f,S,v,C,_){return g.call(this,f,S,v,C,_)||this}return T(SimpleWebRequest,g),SimpleWebRequest.prototype.abort=function(){this._aborted?_A.assert(!1,"Already aborted "+this._action+" request to "+this._url):(this._aborted=!0,this._retryTimer&&(f.SimpleWebRequestOptions.clearTimeout(this._retryTimer),this._retryTimer=void 0),this._requestTimeoutTimer&&(f.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),this._requestTimeoutTimer=void 0),this._deferred?(this._respond("Aborted"),this._xhr&&this._xhr.abort()):_A.assert(!1,"Haven't even fired start() yet -- can't abort"))},SimpleWebRequest.prototype.start=function(){var g=this;return this._deferred?(_A.assert(!1,"WebRequest already started"),I.Rejected("WebRequest already started")):(this._deferred=I.Defer(),this._deferred.onCancel((function(){g.abort()})),this._enqueue(),this._deferred.promise())},SimpleWebRequest.prototype._respond=function(g){var S=this;if(!this._finishHandled){this._finishHandled=!0,this._removeFromQueue(),this._retryTimer&&(f.SimpleWebRequestOptions.clearTimeout(this._retryTimer),this._retryTimer=void 0),this._requestTimeoutTimer&&(f.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),this._requestTimeoutTimer=void 0);var v,C=0;if(this._xhr)try{C=this._xhr.status,v=this._xhr.statusText||g}catch(g){}else v=g||"Browser Error - Possible CORS or Connectivity Issue";var T,I,b={};if(this._xhr){if((this._xhr.getAllResponseHeaders()||"").split(/\r?\n/).forEach((function(g){if(0!==g.length){var f=g.indexOf(":");-1===f?b[g]="":b[g.substr(0,f).toLowerCase()]=g.substr(f+1).trim()}})),!b["content-type"]){var A=this._xhr.getResponseHeader("content-type");A&&(b["content-type"]=A)}if(T=this._xhr.response,b["content-type"]&&isJsonContentType(b["content-type"])&&(!T||!_A.isObject(T))&&("text"===this._xhr.responseType||""===this._xhr.responseType)&&this._xhr.responseText)try{T=JSON.parse(this._xhr.responseText)}catch(g){I=g,console.warn("Failed to parse XHR JSON response")}}if(this._xhr&&4===this._xhr.readyState&&(C>=200&&C<300||304===C)){var P={url:this._xhr.responseURL||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:C,statusText:v,headers:b,body:T,responseParsingException:I};this._deferred.resolve(P)}else{var R={url:(this._xhr?this._xhr.responseURL:void 0)||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:C,statusText:v,headers:b,body:T,canceled:this._aborted,timedOut:this._timedOut,responseParsingException:I};this._options.augmentErrorResponse&&this._options.augmentErrorResponse(R);var M=this._options.customErrorHandler?this._options.customErrorHandler(this,R):DefaultErrorHandler(this,R);M!==_.DoNotRetry&&(this._options.retries&&this._options.retries>0||M===_.PauseUntilResumed||M===_.RetryUncountedImmediately||M===_.RetryUncountedWithBackoff)?(M===_.RetryCountedWithBackoff&&this._options.retries--,this._requestTimeoutTimer&&(f.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),this._requestTimeoutTimer=void 0),this._aborted=!1,this._timedOut=!1,this._finishHandled=!1,this._xhr&&(this._xhr.onabort=null,this._xhr.onerror=null,this._xhr.onload=null,this._xhr.onprogress=null,this._xhr.onreadystatechange=null,this._xhr.ontimeout=null,this._xhr=void 0,this._xhrRequestHeaders=void 0),M===_.PauseUntilResumed?this._paused=!0:M===_.RetryUncountedImmediately?this._enqueue():this._retryTimer=f.SimpleWebRequestOptions.setTimeout((function(){S._retryTimer=void 0,S._enqueue()}),this._retryExponentialTime.getTimeAndCalculateNext())):this._deferred.reject(R)}D.checkQueueProcessing()}},SimpleWebRequest}(D);f.SimpleWebRequest=N})),bA=createCommonjsModule((function(g,f){var S=C&&C.__assign||function(){return S=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},S.apply(this,arguments)};Object.defineProperty(f,"__esModule",{value:!0});var v=function(){function GenericRestClient(g){this._defaultOptions={excludeEndpointUrl:!1,withCredentials:!1,retries:0},this._endpointUrl=g}return GenericRestClient.prototype._performApiCall=function(g,f,v,C){var _=this;void 0===C&&(C={});var T=S(S({},this._defaultOptions),C);v&&(T.sendData=v),T.eTag&&(T.augmentHeaders||(T.augmentHeaders={}),T.augmentHeaders["If-None-Match"]=T.eTag),T.contentType||(T.contentType=_A.isString(T.sendData)?"form":"json");var I=T.excludeEndpointUrl?g:this._endpointUrl+g;return new IA.SimpleWebRequest(f,I,T,(function(){return _._getHeaders(T)}),(function(){return _._blockRequestUntil(T)})).start().then((function(g){return _._processSuccessResponse(g),g}))},GenericRestClient.prototype._getHeaders=function(g){return{}},GenericRestClient.prototype._blockRequestUntil=function(g){},GenericRestClient.prototype._processSuccessResponse=function(g){},GenericRestClient.prototype.performApiGet=function(g,f){return this.performApiGetDetailed(g,f).then((function(g){return g.body}))},GenericRestClient.prototype.performApiGetDetailed=function(g,f){return this._performApiCall(g,"GET",void 0,f)},GenericRestClient.prototype.performApiPost=function(g,f,S){return this.performApiPostDetailed(g,f,S).then((function(g){return g.body}))},GenericRestClient.prototype.performApiPostDetailed=function(g,f,S){return this._performApiCall(g,"POST",f,S)},GenericRestClient.prototype.performApiPatch=function(g,f,S){return this.performApiPatchDetailed(g,f,S).then((function(g){return g.body}))},GenericRestClient.prototype.performApiPatchDetailed=function(g,f,S){return this._performApiCall(g,"PATCH",f,S)},GenericRestClient.prototype.performApiPut=function(g,f,S){return this.performApiPutDetailed(g,f,S).then((function(g){return g.body}))},GenericRestClient.prototype.performApiPutDetailed=function(g,f,S){return this._performApiCall(g,"PUT",f,S)},GenericRestClient.prototype.performApiDelete=function(g,f,S){return this.performApiDeleteDetailed(g,f,S).then((function(g){return g.body}))},GenericRestClient.prototype.performApiDeleteDetailed=function(g,f,S){return this._performApiCall(g,"DELETE",f,S)},GenericRestClient}();f.GenericRestClient=v})),AA=createCommonjsModule((function(g,f){function __export(g){for(var S in g)f.hasOwnProperty(S)||(f[S]=g[S])}Object.defineProperty(f,"__esModule",{value:!0}),__export(TA),__export(bA),__export(IA)})),PA=AA,RA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0});var S=function(){function TelemetryEventBase(){}return TelemetryEventBase.prototype.getAttributes=function(){return{Source:"ecs_client"}},TelemetryEventBase}();f.TelemetryEventBase=S})),MA=createCommonjsModule((function(g,f){var S,v=C&&C.__extends||(S=function(g,f){return S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f.hasOwnProperty(S)&&(g[S]=f[S])},S(g,f)},function(g,f){function __(){this.constructor=g}S(g,f),g.prototype=null===f?Object.create(f):(__.prototype=f.prototype,new __)});Object.defineProperty(f,"__esModule",{value:!0});var _=function(g){function EcsConfigFetchResponse(f,S,v,C,_,T,I,b,A,P,R,M,w,O,D,N,k){var L=g.call(this)||this;return L._responseTime=f,L._responseCode=S,L._fetchAttempts=v,L._hasValidToken=C,L._serverEndpoint=_,L._fetchDurationValid=T,L._cacheAvailable=I,L._responseSize=b,L._configAge=A,L._configExpired=P,L._fetchStart=R,L._fetchEnd=M,L._isUserConfig=w,L._etag=O,L._timedOut=D,L._responseParsingException=N,L._errorMessage=k,L}return v(EcsConfigFetchResponse,g),EcsConfigFetchResponse.prototype.getEventName=function(){return"ecs_tsclient_fetch_config"},EcsConfigFetchResponse.prototype.getAttributes=function(){var f=g.prototype.getAttributes.call(this);return f.fetch_delay_ms=this._responseTime,f.fetch_response_code=this._responseCode,f.fetch_attempts=this._fetchAttempts,f.authenticated_user=this._hasValidToken,f.url=this._serverEndpoint,f.fetch_duration_valid=this._fetchDurationValid,f.cache_available=this._cacheAvailable,f.response_size=this._responseSize,f.config_age=this._configAge,f.config_expired=this._configExpired,f.fetch_start=this._fetchStart,f.fetch_end=this._fetchEnd,f.is_user_config=this._isUserConfig,this._etag&&(f.fetched_etag=this._etag),void 0!==this._timedOut&&(f.fetch_timed_out=this._timedOut),this._responseParsingException&&(f.fetch_response_parsing_error=this._responseParsingException.message),this._errorMessage&&(f.fetch_error_message=this._errorMessage),f},EcsConfigFetchResponse}(RA.TelemetryEventBase);f.EcsConfigFetchResponse=_})),wA=createCommonjsModule((function(g,f){var S,v=C&&C.__extends||(S=function(g,f){return S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,f){g.__proto__=f}||function(g,f){for(var S in f)f.hasOwnProperty(S)&&(g[S]=f[S])},S(g,f)},function(g,f){function __(){this.constructor=g}S(g,f),g.prototype=null===f?Object.create(f):(__.prototype=f.prototype,new __)}),_=C&&C.__assign||function(){return _=Object.assign||function(g){for(var f,S=1,v=arguments.length;S<v;S++)for(var C in f=arguments[S])Object.prototype.hasOwnProperty.call(f,C)&&(g[C]=f[C]);return g},_.apply(this,arguments)};Object.defineProperty(f,"__esModule",{value:!0});var T,b,A=1728e5,P=18e5,R=31536e6,M=3e4,w=function(g){function EcsFetcher(f,S,v,C,_,T,I,b){var A=g.call(this,f)||this;A._config=S,A._skypeTokenData=v,A._appActiveData=C,A._allowBackgroundFetchData=_,A._etag=T,A._getUserConfig=I;var P=A._config.getConfig();if(A._apiPath=P.clientTeam?"/config/v1/"+P.clientName+"/"+P.clientVersion+"/"+P.clientTeam:"/config/v1/"+P.clientName+"/"+P.clientVersion,b){var R=Object.keys(b).map((function(g){return encodeURIComponent(g)+"="+encodeURIComponent(b[g].toString())}));R&&(A._apiPath+="?"+R.join("&"))}return A}return v(EcsFetcher,g),EcsFetcher.prototype._blockRequestUntil=function(g){var f=this;if(this._getUserConfig&&!this._skypeTokenData.isSkypeTokenValid()&&console.log("ECS - Delaying User config fetch until we have a valid SkypeToken"),!this._appActiveData.isAppActive()&&!this._allowBackgroundFetchData.isBackgroundFetchAllowed()){var S=this._getUserConfig?"User config":"config";console.log("ECS - Delaying "+S+" fetch until the app is active (or background fetch is allowed)")}return I.race([this._appActiveData.waitForAppActive(),this._allowBackgroundFetchData.waitForBackgroundFetchAllowed()]).then((function(){if(f._getUserConfig)return f._skypeTokenData.waitForValidSkypeToken()})).then((function(){b=Date.now()}))},EcsFetcher.prototype._getHeaders=function(){var g={};return this._etag&&(g["If-None-Match"]=this._etag),this._getUserConfig&&(g.Authorization=this._skypeTokenData.getSkypeToken()),g},EcsFetcher.prototype.getConfig=function(){var f=this._config.getConfig().fetchTimeout;return void 0!==f&&(f<0?f=0:f>0&&f<M&&(f=M)),g.prototype.performApiGetDetailed.call(this,this._apiPath,{timeout:f})},EcsFetcher}(PA.GenericRestClient),O=function(){function EcsClient(g,f,S,v,C){this._config=g,this._skypeTokenData=f,this._appActiveData=S,this._allowBackgroundFetchData=v,this._telemetryManager=C,this._ecsFailureBackoffTimer=new PA.ExponentialTime(1e3,3e5),this._cacheMaxAgeRegex=/.*max-age=(\d+).*/gi,this._serverIndex=NaN}return EcsClient.prototype.getConfig=function(g,f,S){var v=this,C=this._config.getConfig().hosts;if((isNaN(this._serverIndex)||this._serverIndex>C.length-1)&&(this._serverIndex=Math.floor(Math.random()*C.length)),!C||!C.length)return I.Rejected(new Error("no configuration service endpoint"));var T=I.Defer(),A=0,callConfigServer=function(){var P=g&&g.eTag?g.eTag:void 0,R=new w(C[v._serverIndex],v._config,v._skypeTokenData,v._appActiveData,v._allowBackgroundFetchData,P,f,S);A++,R.getConfig().then((function(S){var R=S.headers.etag,M=S.headers.expires;S.body&&S.body.Headers&&(R||(R=S.body.Headers.ETag),M||(M=S.body.Headers.Expires));var w=v._calculateResponseTimeInfo(g);if(!R||!M)return console.warn("ECS - Service returned an empty ETag or Expiration header: "+JSON.stringify(S)),I.Rejected({timedOut:!1,responseParsingException:new Error("ECS Service returned empty ETag or Expiration header"),responseCode:S.statusCode});var O,D=new Date(v._calculateExpirationDate(S.headers)).getTime();if(304===S.statusCode&&g)(O=_({},g)).configType=f?vA.EcsConfigType.User:vA.EcsConfigType.Default,O.eTag=R,O.expiration=D,O.cacheUpdateTime=w.lastResponseTime,O.lastFetchTokenHash=v._skypeTokenData.getSkypeTokenHash(S.requestHeaders.Authorization);else{if("object"!=typeof S.body)return console.warn("ECS - Service returned invalid response "+JSON.stringify(S)),I.Rejected({timedOut:!1,responseParsingException:new Error("ECS Service returned invalid response body"),responseCode:S.statusCode});O={config:S.body,configType:f?vA.EcsConfigType.User:vA.EcsConfigType.Default,eTag:R,expiration:D,cacheUpdateTime:b,lastFetchTokenHash:v._skypeTokenData.getSkypeTokenHash(S.requestHeaders.Authorization),appVersion:v._config.getConfig().clientVersion}}v._telemetryManager.sendTelemetryEvent(new MA.EcsConfigFetchResponse(w.fetchDelayMs,S.statusCode,A,v._skypeTokenData.isSkypeTokenValid(),C[v._serverIndex],w.fetchDurationValid,!!P,JSON.stringify(S).length,w.cacheAge,!(g&&g.expiration-Date.now()>0),b,w.lastResponseTime,f,R)),v._ecsFailureBackoffTimer.reset(),T.resolve(O)})).catch((function(S){var _={timedOut:S&&S.timedOut||!1,responseParseError:S&&S.responseParsingException,responseCode:S&&S.statusCode||0,message:v._getErrorMessage(S)};console.error("ECS - Service request failed to return a response (timedOut: "+_.timedOut+", responseParseError: "+_.responseParseError+")");var T=v._calculateResponseTimeInfo(g);v._telemetryManager.sendTelemetryEvent(new MA.EcsConfigFetchResponse(T.fetchDelayMs,_.responseCode,A,v._skypeTokenData.isSkypeTokenValid(),C[v._serverIndex],T.fetchDurationValid,!!P,0,T.cacheAge,!(g&&g.expiration-Date.now()>0),b,T.lastResponseTime,f,void 0,_.timedOut,_.responseParseError,_.message));var I=v._config.getConfig().fetchAttemptMax;I&&A>I||setTimeout((function(){callConfigServer()}),v._ecsFailureBackoffTimer.getTimeAndCalculateNext())}))};return callConfigServer(),T.promise()},EcsClient.prototype._calculateExpirationDate=function(g){var f=Date.now()+A;if(g.date&&g.expires){var S=new Date(g.date).getTime(),v=Date.now()-S,C=new Date(g.expires).getTime();return isNaN(C)?f:Math.min(f,C+v)}var _=this._cacheMaxAgeRegex.exec(g["cache-control"]);return this._cacheMaxAgeRegex.lastIndex=0,_&&2===_.length?Math.min(f,Date.now()+1e3*Number(_[1])):Date.now()+P},EcsClient.prototype._calculateResponseTimeInfo=function(g){var f=(T=Date.now())-b;return{lastResponseTime:T,fetchDelayMs:f,fetchDurationValid:!(f<0||f>R),cacheAge:g?T-g.cacheUpdateTime:0}},EcsClient.prototype._getErrorMessage=function(g){if(g)return"string"==typeof g?g:"object"==typeof g&&(g.statusText||g.message)?g.statusText||g.message:void 0},EcsClient}();f.default=O})),OA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0});var S=function(){function Scheduler(g,f,S,v,C,_){var T=this;this._config=g,this._skypeTokenData=f,this._cache=S,this._isFetchingSettings={},this._pendingFetch={},this._pendingTimers={},this._subscriptionToken=null,this._paused=!1,this._fetchEcsSettingsIfNeeded=function(g){var f,S=T._config.getConfig(),v=T._cache.getEcsConfigByType(g);if(-1!==S.configsToFetch.indexOf(g)&&!T._isFetchingSettings[g])if(v||!T._pendingFetch[g]){var C=v?v.expiration-Date.now():-1;C<=0||v&&g===vA.EcsConfigType.User&&T._skypeTokenData.isSkypeTokenValid()&&v.lastFetchTokenHash!==T._skypeTokenData.getSkypeTokenHash(T._skypeTokenData.getSkypeToken())?T._fetchSkypeEcsSettings(g):(null===(f=S.Killswitches)||void 0===f?void 0:f.isSkypeTokenDataLeakFixEnabled)?(T._pendingTimers[g]>0&&clearTimeout(T._pendingTimers[g]),T._pendingTimers[g]=window.setTimeout((function(){return T._fetchEcsSettingsIfNeeded(g)}),C)):window.setTimeout((function(){return T._fetchEcsSettingsIfNeeded(g)}),C)}else T._fetchSkypeEcsSettings(g)},this._fetchSkypeEcsSettings=function(g,f){(void 0===f&&(f=!1),T._isFetchingSettings[g]||T._paused&&!f)?T._pendingFetch[g]=!0:(T._pendingFetch[g]=!1,T._isFetchingSettings[g]=!0,T._config.getConfig().getEcsParameters().catch((function(){return console.warn("ECS - Failed to fetch ECS fetching parameters"),{}})).then((function(f){return T._ecsClient.getConfig(T._cache.getEcsConfig(),g===vA.EcsConfigType.User,f)})).then((function(f){console.log("ECS - Config fetch complete"),T._isFetchingSettings[g]=!1,T._cache.putConfig(f),T._fetchEcsSettingsIfNeeded(g)})))},this._ecsClient=new wA.default(this._config,this._skypeTokenData,v,C,_)}return Scheduler.prototype.initialize=function(){var g=this;this.updateConfigsToFetch(),this._subscriptionToken=this._skypeTokenData.skypeTokenChanged.subscribe((function(){return g._fetchEcsSettingsIfNeeded(vA.EcsConfigType.User)}))},Scheduler.prototype.dispose=function(){var g,f,S=this._config.getConfig();if(null===(g=S.Killswitches)||void 0===g?void 0:g.isSkypeTokenDataLeakFixEnabled){for(var v=0,C=S.configsToFetch;v<C.length;v++){var _=C[v];clearTimeout(this._pendingTimers[_]),this._pendingTimers[_]=0}null===(f=this._subscriptionToken)||void 0===f||f.unsubscribe(),this._subscriptionToken=null,this._skypeTokenData.skypeTokenChanged.dispose()}},Scheduler.prototype.updateConfigsToFetch=function(){for(var g=this._config.getConfig(),f=0,S=g.configsToFetch;f<S.length;f++){(_=S[f])in this._isFetchingSettings||(this._isFetchingSettings[_]=!1),_ in this._isFetchingSettings||(this._pendingFetch[_]=!1)}for(var v=0,C=g.configsToFetch;v<C.length;v++){var _=C[v],T=this._cache.getEcsConfigByType(_);!T||T.appVersion&&T.appVersion!==g.clientVersion?this._fetchSkypeEcsSettings(_,!0):this._fetchEcsSettingsIfNeeded(_)}},Scheduler.prototype.requestUpdate=function(){for(var g=0,f=this._config.getConfig().configsToFetch;g<f.length;g++){var S=f[g];this._fetchSkypeEcsSettings(S)}},Scheduler.prototype.pause=function(){this._paused=!0},Scheduler.prototype.resume=function(){this._paused=!1;for(var g=0,f=this._config.getConfig().configsToFetch;g<f.length;g++){var S=f[g];this._fetchEcsSettingsIfNeeded(S)}},Scheduler}();f.default=S})),DA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0});var S=function(){function SkypeTokenData(){this.skypeTokenChanged=new CA.default}return SkypeTokenData.prototype.putSkypeTokenData=function(g){if(this._data=g,this.isSkypeTokenValid()&&this.skypeTokenChanged.fire(),this.isSkypeTokenValid()&&this._validSkypeTokenDeferral){var f=this._validSkypeTokenDeferral;this._validSkypeTokenDeferral=void 0,f.resolve(void 0)}},SkypeTokenData.prototype.isSkypeTokenValid=function(){var g=this._data;return!!g&&!!g.skypeToken&&g.skypeTokenExpiration>Date.now()},SkypeTokenData.prototype.getSkypeToken=function(){var g=this._data;if(!g||!g.skypeToken)throw new Error("No Skype Token provided");return g.skypeToken},SkypeTokenData.prototype.getSkypeTokenHash=function(g){return void 0===g?0:g.split("").reduce((function(g,f){return(101*g+f.charCodeAt(0))%999727999}),g.length)},SkypeTokenData.prototype.waitForValidSkypeToken=function(){return this.isSkypeTokenValid()?I.Resolved():(this._validSkypeTokenDeferral||(this._validSkypeTokenDeferral=I.Defer()),this._validSkypeTokenDeferral.promise())},SkypeTokenData}();f.default=S})),NA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0});var S=function(){function TelemetryManager(g){this._cache=g,this.telemetryEventAdded=new CA.default}return TelemetryManager.prototype.sendTelemetryEvent=function(g){var f=g.getEventName(),S=g.getAttributes(),v=!1,C=this._cache.getEcsConfig();if(C){if(TelemetryManager._containsEcsClientTelemetryConfig(C.config)){var _=C.config.ECSCONFIG;_&&_.ecsClientTelemetry&&(v=!!_.ecsClientTelemetry[f])}}else console.warn("No previously cached ECS telemetry config exists - fallback to sending event"),v=!0;v&&this.telemetryEventAdded.fire(f,S)},TelemetryManager._containsEcsClientTelemetryConfig=function(g){return!!g&&!!g.ECSCONFIG&&!!g.ECSCONFIG.ecsClientTelemetry},TelemetryManager}();f.default=S})),kA=createCommonjsModule((function(g,f){Object.defineProperty(f,"__esModule",{value:!0}),f.Models=vA;var S=function(){function EcsClient(){this._allowBackgroundFetchData=new gA.default,this._appActiveData=new pA.default,this._config=new EA.default,this._cache=new yA.default(this._config),this._skypeTokenData=new DA.default,this._telemetryManager=new NA.default(this._cache),this._scheduler=new OA.default(this._config,this._skypeTokenData,this._cache,this._appActiveData,this._allowBackgroundFetchData,this._telemetryManager),this.telemetryEventAdded=this._telemetryManager.telemetryEventAdded,this.configUpdated=this._cache.configUpdated}return EcsClient.prototype.initialize=function(g){var f=this;return this._config.initialize(g),this._skypeTokenData.putSkypeTokenData(g.initialSkypeTokenData),this._appActiveData.putAppActive(g.initialAppActiveState),this._cache.initialize().then((function(){f._scheduler.initialize()}))},EcsClient.prototype.dispose=function(){var g;(null===(g=this._config.getConfig().Killswitches)||void 0===g?void 0:g.isSkypeTokenDataLeakFixEnabled)&&this._scheduler.dispose()},EcsClient.prototype.getConfig=function(){return this._cache.getEcsConfig()},EcsClient.prototype.getConfigType=function(){var g=this._cache.getEcsConfig();if(g)return g.configType},EcsClient.prototype.requestUpdate=function(){this._scheduler.requestUpdate()},EcsClient.prototype.pause=function(){this._scheduler.pause()},EcsClient.prototype.resume=function(){this._scheduler.resume()},EcsClient.prototype.setAllowBackgroundFetch=function(g){this._allowBackgroundFetchData.putBackgroundFetchAllowed(g)},EcsClient.prototype.useSkypeToken=function(g,f){this._skypeTokenData.putSkypeTokenData({skypeToken:g,skypeTokenExpiration:f})},EcsClient.prototype.setAppActive=function(g){this._appActiveData.putAppActive(g)},EcsClient.prototype.setConfigsToFetch=function(g){var f=this;return this._config.setConfigsToFetch(g),this._cache.updateConfigsToFetch().then((function(){f._scheduler.updateConfigsToFetch()}))},EcsClient.prototype.setFetchTimeout=function(g){this._config.setFetchTimeout(g)},EcsClient}();f.default=S})),LA=getDefaultExportFromCjs(kA);function getEcsHostUrl(g,f){const S={[tm.Public]:am.Public_EcsServer_Url,[tm.Dod]:am.Dod_EcsServer_Url,[tm.GccHigh]:am.GccHigh_EcsServer_Url,[tm.AirGap08]:am.AirGap08_EcsServer_Url,[tm.AirGap09]:am.AirGap09_EcsServer_Url};let v=am.Public_EcsServer_Url;return f&&(v=f.identityType===lm.Enterprise?am.Enterprise_Ecs_ServerUrl:S[f.cloudType]??am.Public_EcsServer_Url),g?.proxyfyUrl(v)??v}!function(g){g.Default="Default",g.User="User"}(uA||(uA={}));class EcsFetchClient{constructor(g,f){this._acsProxy=f,this._throttlingTimeoutHandle=0,this._eventEmitter=new LE.EventEmitter,this._logger=g.createChild("EcsClient")}_resetThrottlingTimeout(){this._throttlingTimeoutHandle&&(window.clearTimeout(this._throttlingTimeoutHandle),this._throttlingTimeoutHandle=0)}_resetEcsClient(){this._ecsClient&&(this._ecsClient.configUpdated.dispose(),this._ecsClient=void 0)}async _fetchConfig(g){this._resetEcsClient(),this._resetThrottlingTimeout();const f=new LA,S=defer$1();try{await f.initialize(g);let v=[],C=!1,_=0;f.configUpdated.subscribe((()=>{if(S.isPending())S.resolve();else{v.push(Date.now());const g=f.getConfig();if(g?.config){const f=g?.configType===kA.Models.EcsConfigType.User?uA.User:uA.Default;this._cachedConfig=g,this._eventEmitter.emit("configUpdated",{config:g?.config,fetchType:f})}const S=getAcsEcsConfig().ecsClient.throttling;v.length>S.triggerCount&&(v=v.slice(v.length-S.triggerCount));const T=v[v.length-1]-v[0];C?(v.length<S.triggerCount||T>=S.coolDownDuration)&&(C=!1,_=0,v=[],this._resetThrottlingTimeout()):v.length===S.triggerCount&&T<S.triggerDuration&&(C=!0),C&&(_=0===_?S.startingDelay:Math.min(Math.ceil(_*S.delayFactor),S.maxDelay),f.pause(),this._throttlingTimeoutHandle=window.setTimeout((()=>{this._throttlingTimeoutHandle=0,f.resume()}),_))}})),this._ecsClient=f,await wait((()=>S.promise),of);const T=f.getConfig();if(!T?.config)throw new CallingCommunicationError({defaultError:D.INTERNAL.ECS_CONFIG_EMPTY});return this._cachedConfig=T,T.config}catch(g){throw S.reject(g),this._logger.error(`${g}`),g}}async fetchDefaultConfig(g,f){const S=`${getPlatformId()}_${getSdkInternalVersion()}`,v={hosts:[getEcsHostUrl(this._acsProxy,f)],clientName:Zp,clientVersion:S,configsToFetch:[kA.Models.EcsConfigType.Default],getEcsParameters:()=>I.Resolved(g),initialAppActiveState:!0};return this._fetchConfig(v)}async fetchUserConfig(g,f,S){const v=`${getPlatformId()}_${getSdkInternalVersion()}`,C=await S(),_=1e3*parseJWT(C).exp,T={hosts:[getEcsHostUrl(this._acsProxy,f)],clientName:Zp,clientVersion:v,configsToFetch:[kA.Models.EcsConfigType.User],getEcsParameters:()=>I.Resolved(g),initialAppActiveState:!0,initialSkypeTokenData:{skypeToken:C,skypeTokenExpiration:_}};return this._fetchConfig(T)}getETag(){return this._cachedConfig?.eTag??""}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}dispose(){this._eventEmitter.removeAllListeners(),this._resetThrottlingTimeout(),this._resetEcsClient()}}class EcsTelemetryLogger{constructor(g){this._telemetryLogManager=g,this._seq=0}sendAttemptEvent(g,f,S){this._seq++,this._telemetryLogManager.sendEvent({name:uE.acs_calling_config_fetched_attempt,tenant:tf,properties:{attemptTimestamp:g,ecsFetchType:f,correlationId:S,eventSeq:this._seq}})}sendSuccessEvent(g,f,S,v){const C=Date.now();this._seq++;const _=void 0!==g?C-g:0;this._telemetryLogManager.sendEvent({name:uE.acs_calling_config_fetched_success,tenant:tf,properties:{...void 0!==g?{attemptTimestamp:g}:void 0,successTimestamp:C,deltaTimeInMs:_,ecsFetchType:f,correlationId:S,eventSeq:this._seq,ecsConfigIds_AcsCallingSDKWeb:v?.AcsCallingSDKWeb||"",ecsConfigIds_SkypeWebMedia:v?.SkypeWebMedia||""}})}sendFailureEvent(g,f,S,v){const C=Date.now();this._seq++;const _=void 0!==g?C-g:0,T=v.message,I=extractCommunicationServicesErrorForTelemetry(v);this._telemetryLogManager.sendEvent({name:uE.acs_calling_config_fetched_failure,tenant:tf,properties:{...void 0!==g?{attemptTimestamp:g}:void 0,failureTimestamp:C,deltaTimeInMs:_,ecsFetchType:f,correlationId:S,eventSeq:this._seq,failureReason:T,additionalDetails:{...I}}})}}var __decorate$q=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$q=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class CallStack{constructor(g,f,S,v,C,_,T){if(this._disposed=!1,this._trouterStateChangedListenersRegistered=new Map,this.clientId=f,this.sdkDiagnosticInformation=v,this.logger=g.createChild("CallStack"),this._telemetryLogManager=S,this._acsProxy=C,this._acsCustomRelayManager=_,this._webcvProvider=new WebCVProvider,this._wasmvqeProvider=new WasmVqeProvider,"https:"!==location.protocol&&"file:"!==location.protocol&&"localhost"!==location.hostname)throw new CallingCommunicationError({defaultError:D.CALL_STACK.BAD_PROTOCOL});this._telemetryService=new TelemetryService(this._telemetryLogManager),this._ecsTelemetryLogger=new EcsTelemetryLogger(S),this._ecsProvider=new EcsProvider(this.logger,this.sdkDiagnosticInformation,this._acsProxy),this._ecsClient=new EcsFetchClient(this.logger,this._acsProxy),this._ecsClient.on("configUpdated",(async g=>{try{await this.updateConfig(g.config,this.caConfigBag),this._ecsTelemetryLogger.sendSuccessEvent(void 0,g.fetchType,"",this._ecsProvider.getConfigIds());try{this._ecsProvider.assertConfigs(g.config)}catch(f){this._ecsTelemetryLogger.sendFailureEvent(void 0,g.fetchType,"",f)}}catch(f){const S=new CallingCommunicationError({defaultError:D.CALL_STACK.PARSE_CONFIG,originalError:f});this._ecsTelemetryLogger.sendFailureEvent(void 0,g.fetchType,"",S)}})),this._videoEffectsStatusManager=new VideoEffectsStatusManager,this._audioEffectsStatusManager=new AudioEffectsStatusManager,void 0!==T&&(this._encodedStreamsWorkerProvider=new EncodedStreamsWorkerProvider(T))}getClientId(){return this.clientId}getTrouterState(){const g=this?._trouterService?.state();return this.mapTsTrouterState(g)}getEcsConfigIds(){return this._ecsProvider.getConfigIds()}isRegistered(){return this._trouterService?.isRegistered()??!1}onRegisteredChanged(g){this._trouterService?.onRegisteredChanged(g)}offRegisteredChanged(g){this._trouterService?.offRegisteredChanged(g)}onTrouterStateChanged(g){const tsTrouterStateChangedListener=(f,S)=>{g(this.mapTsTrouterState(f))};return this._trouterService?.onStateChanged(tsTrouterStateChangedListener),this._trouterStateChangedListenersRegistered.set(g,tsTrouterStateChangedListener),{listener:g,tsTrouterStateChangedListener:tsTrouterStateChangedListener}}offTrouterStateChanged(g){const f=this._trouterStateChangedListenersRegistered.get(g);if(f)return this._trouterService?.offStateChanged(f),this._trouterStateChangedListenersRegistered.delete(g),{listener:g,tsTrouterStateChangedListener:f}}mapTsTrouterState(g){let f="Uninitialized";if(void 0!==g)switch(g){case 0:f="Unknown";break;case 2:f="Connected";break;case 3:f="Disconnected";break;case 9:f="Switching"}return f}get webcvProvider(){return this._webcvProvider}get wasmvqeProvider(){return this._wasmvqeProvider}get videoEffectsStatusManager(){return this._videoEffectsStatusManager}get audioEffectsStatusManager(){return this._audioEffectsStatusManager}async createStackBase(g){if(this._createStackBaseWaitPromise)return this._createStackBaseWaitPromise;const f=new Promise((async(f,S)=>{try{const S=this._getBaseStackConfig();this._tsStack=await cA.stackFactory.buildBaseStack({...S,stackType:0}),await this.initializeEcsBase(g),f(this._tsStack)}catch(g){S(g)}}));try{this._createStackBaseWaitPromise=wait((()=>f),Im);const g=await this._createStackBaseWaitPromise;return this.logger.log("Base stack init success"),g}catch(g){throw await this.dispose(),g.code===L?new CallingCommunicationError({defaultError:D.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new CallingCommunicationError({defaultError:D.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:g})}}async initializeStackForUser(g,f){if(this.caConfigBag=f,this._initializeStackForUserWaitPromise)return this._initializeStackForUserWaitPromise;this._tsStack=await this.createStackBase(f),this._disposed=!1;const S=new Promise((async(S,v)=>{try{this._tsStack?(this._telemetryService=new TelemetryService(this._telemetryLogManager),this._ecsProvider=new EcsProvider(this.logger,this.sdkDiagnosticInformation,this._acsProxy),await this.initializeEcsBase(f),await this.initializeEcsForUser(f,g),DefaultLogger.overrideDefaultLogDump(),getAcsEcsConfig().calling.doNotWaitForTrouter?this._initTrouter(g).catch((()=>{this.logger.warn(D.CALL_STACK.SIGNALING_UNINITIALIZED.message)})):await this._initTrouter(g),this.logger.log("Signaling initialized successfully."),await initializeMediaStack(g,this._tsStack),await initializeSignalingAgent(g,this._tsStack),await initializeTsStack(this._tsStack),S(this._tsStack)):(this.logger.error("Base stack failed to create"),v(new CallingCommunicationError({defaultError:D.CALL_STACK.USER_STACK_NO_BASE_STACK})))}catch(g){v(g)}})),initializeMediaStack=async(g,f)=>{try{if(await f.initializeMediaAgent({httpRequestDispatcher:this.getRequestDispatcher(),tokenProvider:g,relayManager:this.getCustomRelayManager(),configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{const g=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(g)}},appStateProvider:this._getAppStateProvider(),clientInformation:this._ecsProvider.getJsCsaConfig().clientInformation}),getAcsEcsConfig().calling.platformSupportValidation&&0===f.getPlatformSupportLevel()){const g=new CallingCommunicationError({defaultError:D.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED_PLATFORM_NOT_SUPPORTED});throw this.logger.error(g.message),g}}catch(g){throw this.logger.error("Failed to  initialize media stack",g),new CallingCommunicationError({defaultError:D.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED,originalError:g})}},initializeSignalingAgent=async(g,f)=>{try{await f.initializeSignalingAgentProvider({signalingAgentConfig:this._getSignalingConfig(g),trouterService:this._trouterService})}catch(g){throw this.logger.error("Failed to  initialize signaling agent",g),new CallingCommunicationError({defaultError:D.CALL_STACK.USER_STACK_SIGNALING_INIT_FAILED,originalError:g})}},initializeTsStack=async g=>{try{await g.init()}catch(g){throw this.logger.error("Failed to initialize calling stack",g),new CallingCommunicationError({defaultError:D.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:g})}};try{this._initializeStackForUserWaitPromise=wait((()=>S),bm);const g=await this._initializeStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log("User stack init success"),g}catch(g){if(await this.dispose(),g.code===L)throw this.sendStackInitEvent(!1,"User stack init timeout",g),new CallingCommunicationError({defaultError:D.CALL_STACK.USER_STACK_INIT_TIMEOUT});if(!(g instanceof CallingCommunicationError)&&"Uninitialized"===this.getTrouterState())throw new CallingCommunicationError({defaultError:D.CALL_STACK.SIGNALING_UNINITIALIZED,originalError:g});throw this.sendStackInitEvent(!1,"User stack init failed",g),new CallingCommunicationError({defaultError:D.CALL_STACK.USER_STACK_INIT_FAILED,originalError:g})}}getRequestDispatcher(){return this._acsProxy.hasProxyUrl()?(this.logger.info("Using custom proxy for network requests (non media)"),new HttpRequestDispatcher(this.logger,this._acsProxy)):getAcsEcsConfig().telemetry.sendNetworkInfo?new HttpRequestDispatcher(this.logger):new w.HttpRequestDispatcherImplementation}async updateConfig(g,f){if(g.Headers?.CountryCode&&this.updateEmergencyCallCountry(g?.Headers?.CountryCode),this._tsStack)try{setAcsEcsConfig(g),this._ecsProvider.setConfig(f,g),setMediaConfig(this._ecsProvider.getJamaSettings());const S=await(this._tsStack?.getEcsProviderAsync?.());await(S?.setEcsConfig({ecsBlob:JSON.stringify(g),userIdentity:"",etag:this._ecsClient.getETag()}))}catch(g){throw this.logger.warn(`Unable to update ECS configuration ${g}`),new CallingCommunicationError({defaultError:D.CALL_STACK.PARSE_CONFIG,originalError:g})}}async initializeEcsBase(g){const f=Date.now(),S=generateGuid();this._ecsTelemetryLogger.sendAttemptEvent(f,uA.Default,S);let v=D.CALL_STACK.FETCH_CONFIG;try{const C=await this._ecsClient.fetchDefaultConfig(this.getEcsQueryParameters(g),g);v=D.CALL_STACK.PARSE_CONFIG,await this.updateConfig(C,g),this._ecsTelemetryLogger.sendSuccessEvent(f,uA.Default,S,this._ecsProvider.getConfigIds());try{this._ecsProvider.assertConfigs(C)}catch(g){this._ecsTelemetryLogger.sendFailureEvent(f,uA.Default,S,g)}}catch(C){this.logger.warn("Failed to fetch base settings. Stack will initialize with default settings",C),this._ecsProvider.setConfig(g,void 0);const _=new CallingCommunicationError({defaultError:v,originalError:C});this._ecsTelemetryLogger.sendFailureEvent(f,uA.Default,S,_)}}async initializeEcsForUser(g,f){const S=Date.now(),v=generateGuid();this._ecsTelemetryLogger.sendAttemptEvent(S,uA.User,v);let C=D.CALL_STACK.FETCH_CONFIG;try{const _=await this._ecsClient.fetchUserConfig(this.getEcsQueryParameters(g),g,f);C=D.CALL_STACK.PARSE_CONFIG,await this.updateConfig(_,g),this._ecsTelemetryLogger.sendSuccessEvent(S,uA.User,v,this._ecsProvider.getConfigIds());try{this._ecsProvider.assertConfigs(_)}catch(g){this._ecsTelemetryLogger.sendFailureEvent(S,uA.User,v,g)}}catch(g){this.logger.warn("Failed to fetch user settings.",g);const f=new CallingCommunicationError({defaultError:C,originalError:g});this._ecsTelemetryLogger.sendFailureEvent(S,uA.User,v,f)}}async getDeviceManager(){if(!this._createStackBaseWaitPromise)throw new CallingCommunicationError({defaultError:D.CALL_STACK.GET_DM});return(await this._createStackBaseWaitPromise).getDeviceManagerAsync()}async dispose(g){if(!this._disposed){if(this._disposed=!0,this._trouterService)try{this._trouterService.clearMessageHandlers(),this._trouterService.stop(g),this._trouterService=void 0}catch(g){this.logger.error("Failed to dispose signaling")}if(this._tsStack)try{await this._tsStack.dispose(),this._tsStack=void 0}catch(g){this.logger.error("Failed to dispose calling stack")}this._ecsClient.dispose(),this._createStackBaseWaitPromise=void 0,this._initializeStackForUserWaitPromise=void 0,this._tsStack=void 0,this.logger.info("Calling stack disposed")}}getEcsQueryParameters(g){const f={};try{f.CLRelease=w.getVersion();const S=getBrowserInfo();f.BrowserName=S.name,f.BrowserEngine=S.engine,f.BrowserVersion=S.version,f.FormFactor=S.formFactor,f.IdentityType=lm.Consumer,f.Cloud=tm.Public,f.OSVer=`${getOS()}-${getOSVersion()}`,g&&(f.Cloud=g.cloudType,f.IdentityType=g.identityType);const v="_TS_BUILC_VERSION_".replace("C","D");f.CLRelease===v?f.CLRelease="9999.99":f.CLRelease.match(/^\d+\.\d+\.\d+\.\d+$/)||delete f.CLRelease}catch(g){throw this.logger.error(g),new CallingCommunicationError({defaultError:D.CALL_STACK.SET_STACK_PARAMS,originalError:g})}return f}updateEmergencyCallCountry(g){this.caConfigBag&&!this.caConfigBag.emergencyCountryCode&&!this.caConfigBag.IsUserEmergencyCountryCode&&g&&(this.caConfigBag.emergencyCountryCode=g)}async _initTrouter(g){let f=+new Date;try{this._trouterService=new Trouter(this.logger,this._ecsProvider,(f=>g(f)),this._telemetryLogManager,this._acsProxy),f=+new Date;let S=await this._trouterService.start();const v=this._trouterService.getTrouterSettings();return void this.sendSignalingInitEvent(!0,+new Date-f,v.registrationId??"",v.sessionId,S.trouterRequestCompletionTimeDeltaMs,S.registrarRequestCompletionTimeDeltaMs)}catch(g){throw this.sendSignalingInitEvent(!1,+new Date-f,"","",void 0,void 0,g),g}}_getBaseStackConfig(){const g=this._getMediaProviderConfig(),f={clientInformation:this._ecsProvider.getClientInformation(),logger:this.logger,mediaSettings:g.mediaSettings,platformType:getPlatformName(),callSettings:{useLwjForAllCalls:!1},usePlatformSupportApi:!0,telemetryTenants:{media:"mediaAgent",signaling:"signalingAgent",tlePlayer:wf},telemetryService:this._telemetryService,webcvProvider:this._webcvProvider,wasmVqeProvider:this._wasmvqeProvider};return void 0!==this._encodedStreamsWorkerProvider&&(f.encodedStreamsWorkerProvider=this._encodedStreamsWorkerProvider),f}_getSignalingConfig(g){const f={...this._ecsProvider.getJsCsaConfig(),httpRequestDispatcher:this.getRequestDispatcher(),telemetryManager:this._telemetryService.getCallingAdapter(),logger:this.logger,skypeToken:()=>g(),trouterServiceProvider:this._trouterService,ecsEtag:this._ecsClient.getETag()};return this.caConfigBag?.emergencyCountryCode&&(f.emergencyCallCountry=this.caConfigBag?.emergencyCountryCode),f}_getMediaProviderConfig(){return{logger:this.logger,mediaSettings:this._getMediaAgentConfig()}}_getMediaAgentConfig(){return{...this._ecsProvider.getJamaSettings()}}_getAppStateProvider(){return{isOnline:()=>!0}}sendStackInitEvent(g,f,S){try{let v,C;S&&(v=S.message,C=extractCommunicationServicesErrorForTelemetry(S)),this._telemetryLogManager.sendEvent({name:uE.acs_calling_stack_init,tenant:tf,properties:{success:g,reason:f,failureReason:v||"unknown",additionalDetails:{...C}}})}catch(g){}}sendSignalingInitEvent(g,f,S,v,C,_,T){try{let I,b;T&&(I=T.message,b=extractCommunicationServicesErrorForTelemetry(T)),this._telemetryLogManager.sendEvent({name:uE.acs_calling_signaling_init,tenant:tf,properties:{success:g,failureReason:I||"unknown",timestampInfo:{deltaTimeInMs:f,deltaTimeInMsTrouterRequest:C,deltaTimeInMsRegistrarRequest:_},additionalDetails:{...b,registrationId:S,sessionId:v}}})}catch(g){}}getCustomRelayManager(){if(this._tsCustomRelayManager=this._acsCustomRelayManager.getTsRelayManager(),this._tsCustomRelayManager&&getAcsEcsConfig().calling.enableCustomTurnUsage)return this.logger.info("Using custom relays for media traffic"),this._acsCustomRelayManager.customRelayManagerInUse=!0,this._tsCustomRelayManager}}__decorate$q([loggerProperty,__metadata$q("design:type",Object)],CallStack.prototype,"logger",void 0),__decorate$q([asyncOperation(wS.CreateStackBase),__metadata$q("design:type",Function),__metadata$q("design:paramtypes",[Object]),__metadata$q("design:returntype",Promise)],CallStack.prototype,"createStackBase",null),__decorate$q([asyncOperation(wS.InitializeStackForUser),__metadata$q("design:type",Function),__metadata$q("design:paramtypes",[Function,Object]),__metadata$q("design:returntype",Promise)],CallStack.prototype,"initializeStackForUser",null),__decorate$q([asyncOperation(wS.GetDeviceManager),__metadata$q("design:type",Function),__metadata$q("design:paramtypes",[]),__metadata$q("design:returntype",Promise)],CallStack.prototype,"getDeviceManager",null),__decorate$q([asyncOperation(wS.Dispose),__metadata$q("design:type",Function),__metadata$q("design:paramtypes",[Boolean]),__metadata$q("design:returntype",Promise)],CallStack.prototype,"dispose",null);class ObservableSubjects{constructor(){this._eventEmitter=new LE.EventEmitter}notifyAll(g){this._eventEmitter.emit(g)}waitFor(g,f){return new Promise(((S,v)=>{let C=0;const listener=()=>{S(),clearTimeout(C)};this._eventEmitter.once(g,listener),C=window.setTimeout((()=>{this._eventEmitter.off(g,listener),v(new Error("timeout"))}),f)}))}}class DeviceInfoMapper{constructor(){this._deviceIdMapping=new Map,this._deviceId=1,this._keywords=getAcsEcsConfig().telemetry.deviceChangedEvents.piiSafeWords}getDeviceId(g){let f=this._deviceIdMapping.get(g);if(void 0!==f)return f;++this._deviceId;return f=`${g.split(":")[0]??""}:${this._deviceId}`,this._deviceIdMapping.set(g,f),f}scrubDeviceLabel(g){return scrubDeviceLabelPii(g,this._keywords)}}function scrubDeviceLabelPii(g,f){if(!g)return"";if(g.length<3)return g;const S=[],v=g.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);v&&S.push(v[1]);try{if(!f?.length)return"no_keywords";{const v=new RegExp(`(${f.join("|")})`,"gi");let C=v.exec(g);for(;C;)S.push(C[1]),C=v.exec(g)}}catch(g){const stringifyError=g=>M.isString(g)?g:g?.message??"";S.push(`Error: ${stringifyError(g)}`)}return 0===S.length?"unknown":S.join(" ")}var __decorate$r=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$r=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class DeviceManagerImpl{constructor(g,f,S){this._callStack=f,this._videoDevices=[],this._audioDevices=[],this._tsDeviceTypeToAudioDeviceType={2:"Microphone",3:"Speaker",4:"CompositeAudioDevice"},this.logger=g.createChild("DeviceManager"),this._telemetryLogManager=S,this._eventEmitter=new CallingEventEmitter(this.logger),this._browserInfo=getBrowserInfo(),this._safariVideoPermissionState="unknown",this._combinedDevicePermission=new Map,this._deviceInfoMapper=new DeviceInfoMapper,this._deviceSelectionNotifications=new ObservableSubjects}get telemetryLogManager(){return this._telemetryLogManager}getRawDeviceMediaStream(g){const f=generateGuid(),S=+new Date;if(this.sendRawMediaEvent({eventName:uE.acs_calling_get_raw_device_media_stream,correlationId:f,kindOfEvent:"attempt",mediaType:g,timestampInfo:"",additionalDetails:""}),!this._tsDeviceManager?.getRawDeviceMediaStream){const v=new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.GET_MEDIA_STREAM_TRACK});this.logger.error("Failed to get raw device stream track");const C=+new Date;throw this.sendRawMediaEvent({eventName:uE.acs_calling_get_raw_device_media_stream,correlationId:f,kindOfEvent:"failure",mediaType:g,timestampInfo:{deltaTimeInMs:C-S},additionalDetails:{failureReason:v.message||"",code:v.code,subCode:v.subCode,...extractCommunicationServicesErrorForTelemetry(v)}}),v}let v;try{v=this._tsDeviceManager?.getRawDeviceMediaStream(g);const C=+new Date;return this.sendRawMediaEvent({eventName:uE.acs_calling_get_raw_device_media_stream,correlationId:f,kindOfEvent:"success",mediaType:g,timestampInfo:{deltaTimeInMs:C-S},additionalDetails:""}),v}catch(v){const C=new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.GET_MEDIA_STREAM_DEVICE_UNAVAILABLE,originalError:v});this.logger.error("Failed to get raw device stream track");const _=+new Date;throw this.sendRawMediaEvent({eventName:uE.acs_calling_get_raw_device_media_stream,correlationId:f,kindOfEvent:"failure",mediaType:g,timestampInfo:{deltaTimeInMs:_-S},additionalDetails:{failureReason:C.message||"",code:C.code,subCode:C.subCode,...extractCommunicationServicesErrorForTelemetry(C)}}),C}}getClientId(){return this._callStack.getClientId()}async getDeviceManager(){if(this._tsDeviceManager)return this._tsDeviceManager;const g=+new Date;try{this.sendGetDeviceManagerEvent({eventName:uE.acs_calling_get_device_manager,kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),await this._callStack.createStackBase(),this._tsDeviceManager=await this._callStack.getDeviceManager();const f=await this.enumerateDevicesAsync();this.logger.info(`tsDevicesList:${JSON.stringify(f)}`),f.forEach((g=>{if(1===g.kind){const f=g;this._videoDevices.push(new VideoDeviceInfoImpl(f.label,f.id,"UsbCamera",this))}else if(2===g.kind||3===g.kind){const f=g,S=new AudioDeviceInfoImpl(f.label,f.id,f.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[f.kind],this);this._audioDevices.push(S)}}));const S=await(this._tsDeviceManager.getSelectedDevicesAsync?.());S&&(this._selectedMicrophone=this._audioDevices.find((g=>g.id===S.microphone)),this._selectedSpeaker=this._audioDevices.find((g=>g.id===S.speaker))),this._dmDevicesChangedSub=this._tsDeviceManager.on("devicesChanged",(async()=>{try{await this.syncDeviceList(await this.enumerateDevicesAsync()),await this.checkForSelectedDevicesChanges()}catch(f){this.logger.warn(`Unable to handle devicesChanged, error=${f?.message}, code=${f?.code}`);const S=+new Date;this.sendGetDeviceManagerEvent({eventName:uE.acs_calling_get_device_manager,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:S-g},additionalDetails:{failureReason:f?.message,code:f?.code,...extractCommunicationServicesErrorForTelemetry(f),context:"devicesChanged"}})}})),getAcsEcsConfig().calling.devicePermissions.getCurrentState&&(this._audioDevicePermission=permissionStateToBool(this._tsDeviceManager?.getPermissionState("microphone"),this.logger),this._videoDevicePermission=permissionStateToBool(this._tsDeviceManager?.getPermissionState("camera"),this.logger)),this.logger.info("Initial permission state audio:",this._audioDevicePermission,"video:",this._videoDevicePermission),this._dmDevicesPermissionChangedSub=this._tsDeviceManager.on("onPermissionStateChanged",this.permissionsChanged.bind(this));const v=+new Date;this.sendGetDeviceManagerEvent({eventName:uE.acs_calling_get_device_manager,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:v-g},additionalDetails:""})}catch(f){const S=new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.GET_DM,originalError:f});this.logger.error(S.message);const v=+new Date;this.sendGetDeviceManagerEvent({eventName:uE.acs_calling_get_device_manager,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:v-g},additionalDetails:{failureReason:S.message,code:S.code,...extractCommunicationServicesErrorForTelemetry(S)}})}return this._tsDeviceManager}on(g,f){if("videoDevicesUpdated"!==g&&"audioDevicesUpdated"!==g&&"selectedMicrophoneChanged"!==g&&"selectedSpeakerChanged"!==g)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("videoDevicesUpdated"!==g&&"audioDevicesUpdated"!==g&&"selectedMicrophoneChanged"!==g&&"selectedSpeakerChanged"!==g)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}getTsDeviceManager(){if(!this._tsDeviceManager)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager}getSafariPermissionState(){return"Safari"===this._browserInfo.engine?this._safariVideoPermissionState:"unknown"}getAcsResourceId(){return this._callStack?.caConfigBag?.acsResourceId}getAudioDevicePermission(){return this._audioDevicePermission}getVideoDevicePermission(){return this._videoDevicePermission}get callStackWebCvProvider(){return this._callStack.webcvProvider}get callStackWasmVqeProvider(){return this._callStack.wasmvqeProvider}get callStackVideoEffectsStatusManager(){return this._callStack.videoEffectsStatusManager}get callStackAudioEffectsStatusManager(){return this._callStack.audioEffectsStatusManager}get deviceInfoMapper(){return this._deviceInfoMapper}getEnvironmentInfoInternal(){return this._environmentInfo||(this._environmentInfo=getEnvironmentInfos()),this._environmentInfo}getOSNameInternal(){return getOS()}sendRawMediaEvent(g){try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this.logger.debug("Unable to send raw media telemetry")}}sendGetDeviceManagerEvent(g){try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this.logger.debug("Unable to send get_device_manager telemetry")}}permissionsChanged(g,f){const S=this._audioDevicePermission,v=this._videoDevicePermission;let C,_;getAcsEcsConfig().calling.devicePermissions.getCurrentState?(C=permissionStateToBool(this._tsDeviceManager?.getPermissionState("microphone"),this.logger),_=permissionStateToBool(this._tsDeviceManager?.getPermissionState("camera"),this.logger)):(C=S,_=v),this._audioDevicePermission=C||!!g?.audio,this._videoDevicePermission=_||!!g?.video,f&&(f.audio&&(this._audioDevicePermission=g?.audio??!1),f.video&&(this._videoDevicePermission=g?.video??!1)),S===this._audioDevicePermission&&v===this._videoDevicePermission||(this.logger.info(`permission state changed from audio: ${S}, video: ${v}\n                          to audio: ${this._audioDevicePermission}, video: ${this._videoDevicePermission}`),this._telemetryLogManager.sendEvent({name:uE.acs_calling_device_permission_changed,tenant:tf,properties:{previousAudioDevicePermission:this.nullHandler(S),previousVideoDevicePermission:this.nullHandler(v),newAudioDevicePermission:this.nullHandler(this._audioDevicePermission),newVideoDevicePermission:this.nullHandler(this._videoDevicePermission)}}))}async checkForSelectedDevicesChanges(){if(this.logger.info("checkForSelectedDevicesChanges"),this._tsDeviceManager){const g=await(this._tsDeviceManager.getSelectedDevicesAsync?.());g&&(g.microphone!==this._selectedMicrophone?.id&&(this._selectedMicrophone=this._audioDevices.find((f=>f.id===g.microphone)),this._eventEmitter.emit("selectedMicrophoneChanged"),void 0!==g.microphone&&this._deviceSelectionNotifications.notifyAll(g.microphone)),g.speaker!==this._selectedSpeaker?.id&&(this._selectedSpeaker=this._audioDevices.find((f=>f.id===g.speaker)),this._eventEmitter.emit("selectedSpeakerChanged"),void 0!==g.speaker&&this._deviceSelectionNotifications.notifyAll(g.speaker)))}else this.logger.warn("DeviceManager is undefined, Unable to check selected devices")}isACSDeviceEqualToTSDevice(g,f){return g.id===f.id}async syncDeviceList(g){if(!this._tsDeviceManager)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.ACCESS_DM});this.logger.info("syncDeviceList"),void 0===g&&(g=await this.enumerateDevicesAsync());const f=[];let S=[];const v=[];let C=[];g.map((g=>{if(1===g.kind){const S=this._videoDevices.find((f=>this.isACSDeviceEqualToTSDevice(f,g)));if(S)S.setName(g.label),S.setId(g.id),S.setDeviceType("UsbCamera");else{const S=new VideoDeviceInfoImpl(g.label,g.id,"UsbCamera",this);f.push(S),this._videoDevices.push(S)}}else if(2===g.kind||3===g.kind){const f=this._audioDevices.find((f=>this.isACSDeviceEqualToTSDevice(f,g)));if(f){const S=g;f.setName(S.label),f.setId(S.id),f.setIsSystemDefault(S.isSystemDefault),f.setDeviceType(this._tsDeviceTypeToAudioDeviceType[S.kind])}else{const f=new AudioDeviceInfoImpl(g.label,g.id,g.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[g.kind],this);v.push(f),this._audioDevices.push(f)}}}));const calculateRemovedDiffs=f=>{const S=f.filter((f=>!g.find((g=>this.isACSDeviceEqualToTSDevice(f,g)))));return S.map((g=>{f.splice(f.indexOf(g),1)})),S};S=calculateRemovedDiffs(this._videoDevices),C=calculateRemovedDiffs(this._audioDevices),(f.length>0||S.length>0)&&this._eventEmitter.emit("videoDevicesUpdated",{added:f,removed:S}),(v.length>0||C.length>0)&&this._eventEmitter.emit("audioDevicesUpdated",{added:v,removed:C})}async enumerateDevicesAsync(){if(!this._tsDeviceManager)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.ACCESS_DM});try{return await this._tsDeviceManager.enumerateDevicesAsync()}catch(g){throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL})}}get isSpeakerSelectionAvailable(){if(!this._tsDeviceManager)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager.isAudioOutputSelectionSupported}get selectedMicrophone(){return this._selectedMicrophone}get selectedSpeaker(){return this._selectedSpeaker}async getCameras(){return await this.syncDeviceList(),this._videoDevices}async getMicrophones(){return await this.syncDeviceList(),this._audioDevices.filter((g=>"Microphone"===g.deviceType))}async getSpeakers(){if(this.isSpeakerSelectionAvailable)return await this.syncDeviceList(),this._audioDevices.filter((g=>"Speaker"===g.deviceType));throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.SPEAKER_ENUMERATION_UNSUPPORTED})}async selectMicrophone(g){if(!this._tsDeviceManager)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.ACCESS_DM});if(!g||!g.id)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.INVALID_DEVICE});if("microphone:"===g.id)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(this.logger.info("selectMicrophone called"),this._selectedMicrophone?.id!==g.id){const f=getAcsEcsConfig().calling.deviceSelectionTimeoutInMs,S=this._deviceSelectionNotifications.waitFor(g.id,f),v="Microphone",C=this._deviceInfoMapper.getDeviceId(g.id),_=this._deviceInfoMapper.scrubDeviceLabel(g.name),T=generateGuid(),sendEvent=(g,f,S)=>{this.sendDeviceSelectionEvent({eventName:uE.acs_calling_client_operations,operation:aA.deviceSelection,kindOfEvent:g,correlationId:T,timestampInfo:void 0!==f?{deltaTimeInMs:f}:{},additionalDetails:void 0!==S?{failureReason:S.message,code:S.code,...extractCommunicationServicesErrorForTelemetry(S)}:"",deviceSelection:{deviceId:C,deviceName:_,deviceType:v}})};sendEvent("attempt");const I=Date.now();try{await(this._tsDeviceManager.selectDevicesAsync?.({microphone:g.id})),await S.catch((f=>{if(this._selectedMicrophone?.id!==g.id)throw f})),sendEvent("success",Date.now()-I)}catch(g){let f;throw f=new CallingCommunicationError("timeout"===g?.message?{defaultError:D.DEVICE_MANAGER.SELECT_MICROPHONE_TIMEOUT}:{defaultError:D.DEVICE_MANAGER.SELECT_MICROPHONE_FAIL,originalError:g}),sendEvent("failure",Date.now()-I,f),f}}else this.logger.warn("microphoneDevice is already active")}async selectSpeaker(g){const f=this.logger.createFnLogger(OS.SelectSpeaker);if(!this._tsDeviceManager)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.ACCESS_DM});if(!this.isSpeakerSelectionAvailable)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.SPEAKER_SELECTION_UNSUPPORTED});if(!g||!g.id)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.INVALID_DEVICE});if("speaker:"===g.id)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(f.info("selectSpeaker called"),this._selectedSpeaker?.id!==g.id){const f=getAcsEcsConfig().calling.deviceSelectionTimeoutInMs,S=this._deviceSelectionNotifications.waitFor(g.id,f),v="Speaker",C=this._deviceInfoMapper.getDeviceId(g.id),_=this._deviceInfoMapper.scrubDeviceLabel(g.name),T=generateGuid(),sendEvent=(g,f,S)=>{this.sendDeviceSelectionEvent({eventName:uE.acs_calling_client_operations,operation:aA.deviceSelection,kindOfEvent:g,correlationId:T,timestampInfo:void 0!==f?{deltaTimeInMs:f}:{},additionalDetails:void 0!==S?{failureReason:S.message,code:S.code,...extractCommunicationServicesErrorForTelemetry(S)}:"",deviceSelection:{deviceId:C,deviceName:_,deviceType:v}})};sendEvent("attempt");const I=Date.now();try{await(this._tsDeviceManager.selectDevicesAsync?.({speaker:g.id})),await S.catch((f=>{if(this._selectedSpeaker?.id!==g.id)throw f})),sendEvent("success",Date.now()-I)}catch(g){let f;throw f=new CallingCommunicationError("timeout"===g?.message?{defaultError:D.DEVICE_MANAGER.SELECT_SPEAKER_TIMEOUT}:{defaultError:D.DEVICE_MANAGER.SELECT_SPEAKER_FAIL,originalError:g}),sendEvent("failure",Date.now()-I,f),f}}else f.warn("device is already selected")}async askDevicePermission(g){const f={audio:!!g.audio,video:!!g.video};if(!g.audio&&!g.video)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.ONE_PERMISSION_ATLEAST});const S=this.getKeyForConstrains(f);let v=this._combinedDevicePermission.get(S);return v?this.logger.info(`askDevicePermission attempt: audio:${f.audio}, video:${f.video} on pending existing request ${getPrintableObject(v)}`):(v=this.askDevicePermissionInternal(f),this._combinedDevicePermission.set(S,v),v.finally((()=>{this._combinedDevicePermission.delete(S)}))),v}getKeyForConstrains(g){return Object.keys(g).filter((f=>g[f])).toString()}async askDevicePermissionInternal(g){this.logger.info(`askDevicePermission attempt: audio:${g.audio}, video:${g.video}`);const f=generateGuid(),S=+new Date;this.sendAudioVideoPermissionEvent({eventName:uE.acs_calling_adp_attempt,correlationId:f,audioPermissionRequested:g.audio,videoPermissionRequested:g.video});try{if(!this._tsDeviceManager)throw new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.ACCESS_DM});const v=[];if(getAcsEcsConfig().calling.devicePermissions.splitAskAudioVideo){this.logger.info("askDevicePermission, split permission check");const f=[];if(g.audio&&(this.logger.info("askDevicePermission, split permission audio"),f.push(this._tsDeviceManager.askDevicePermission({audio:g.audio,video:!1}))),g.video){const askDevicePermissionVideoWithDelay=async f=>new Promise(((S,v)=>{const askDevicePermissionVideo=async()=>{if(this.logger.info("askDevicePermission, split permission video"),!this._tsDeviceManager){const g="askDevicePermission, split permission video failed device manager not found";return this.logger.error(g),void v(g)}try{const f=await this._tsDeviceManager.askDevicePermission({audio:!1,video:g.video});S(f)}catch(g){v(g)}};f?window.setTimeout(askDevicePermissionVideo,f):askDevicePermissionVideo()}));f.push(askDevicePermissionVideoWithDelay(getAcsEcsConfig().calling.devicePermissions.timeoutInBetween))}const S=await Promise.allSettled(f);let C={audio:!1,video:!1};S.forEach((g=>{"fulfilled"===g.status&&g?.value&&(C={audio:C.audio||!!g?.value?.audio,video:C.video||!!g?.value?.video}),"rejected"===g.status&&g?.reason&&v.push(g.reason)})),this.permissionsChanged(C,g),this._safariVideoPermissionState=this._videoDevicePermission?"granted":"denied"}else{const f=await this._tsDeviceManager.askDevicePermission({audio:g.audio,video:g.video});this.permissionsChanged(f,g)}if(g?.audio&&!this._audioDevicePermission||g?.video&&!this._videoDevicePermission)this.sendAudioVideoPermissionEvent({eventName:uE.acs_calling_adp_failure,correlationId:f,audioPermissionRequested:g.audio,videoPermissionRequested:g.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission},new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.PERMISSION_NOT_GRANTED_OR_FAILED,defaultErrorMessageArgs:[getPrintableObject(v)]}));else{const v=+new Date;this.sendAudioVideoPermissionEvent({eventName:uE.acs_calling_adp_success,correlationId:f,audioPermissionRequested:g.audio,videoPermissionRequested:g.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:v-S})}}catch(v){const C=new CallingCommunicationError({defaultError:D.DEVICE_MANAGER.ADP_FAIL,originalError:v}),_=+new Date;this.sendAudioVideoPermissionEvent({eventName:uE.acs_calling_adp_failure,correlationId:f,audioPermissionRequested:g.audio,videoPermissionRequested:g.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:_-S},C)}return{audio:!!this._audioDevicePermission,video:!!this._videoDevicePermission}}sendAudioVideoPermissionEvent(g,f){try{let S,v,C;f&&(S="string"==typeof f?.message?f?.message:void 0,v=extractCommunicationServicesErrorForTelemetry(f)),g.deltaTimeInMs&&(C=g.deltaTimeInMs>25e3),this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:{audioPermissionGranted:this.nullHandler(g.audioPermissionGranted),videoPermissionGranted:this.nullHandler(g.videoPermissionGranted),audioPermissionRequested:g.audioPermissionRequested,videoPermissionRequested:g.videoPermissionRequested,correlationId:g.correlationId||"",failureReason:S||"",deltaTimeInMs:g.deltaTimeInMs||"",deltaTimeGreaterThanJAMATimeout:this.nullHandler(C),additionalDetails:{...v}}})}catch(g){this.logger.debug("Unable to send audio video permission failure success telemtery")}}sendDeviceSelectionEvent(g){try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this.logger.debug("Unable to send device selection telemetry")}}nullHandler(g){return void 0===g?"":g}dispose(){this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesPermissionChangedSub&&this._dmDevicesPermissionChangedSub.dispose(),this._dmDevicesPermissionChangedSub=void 0,this._dmDevicesChangedSub=void 0}}__decorate$r([loggerProperty,__metadata$r("design:type",Object)],DeviceManagerImpl.prototype,"logger",void 0),__decorate$r([asyncOperation(OS.GetDeviceManager),__metadata$r("design:type",Function),__metadata$r("design:paramtypes",[]),__metadata$r("design:returntype",Promise)],DeviceManagerImpl.prototype,"getDeviceManager",null),__decorate$r([asyncOperation(OS.GetCameras),__metadata$r("design:type",Function),__metadata$r("design:paramtypes",[]),__metadata$r("design:returntype",Promise)],DeviceManagerImpl.prototype,"getCameras",null),__decorate$r([asyncOperation(OS.GetMicrophones),__metadata$r("design:type",Function),__metadata$r("design:paramtypes",[]),__metadata$r("design:returntype",Promise)],DeviceManagerImpl.prototype,"getMicrophones",null),__decorate$r([syncOperation(OS.GetSpeakers),__metadata$r("design:type",Function),__metadata$r("design:paramtypes",[]),__metadata$r("design:returntype",Promise)],DeviceManagerImpl.prototype,"getSpeakers",null),__decorate$r([asyncOperation(OS.SelectMicrophone),__metadata$r("design:type",Function),__metadata$r("design:paramtypes",[Object]),__metadata$r("design:returntype",Promise)],DeviceManagerImpl.prototype,"selectMicrophone",null),__decorate$r([asyncOperation(OS.SelectSpeaker),__metadata$r("design:type",Function),__metadata$r("design:paramtypes",[Object]),__metadata$r("design:returntype",Promise)],DeviceManagerImpl.prototype,"selectSpeaker",null),__decorate$r([asyncOperation(OS.AskDevicePermission),__metadata$r("design:type",Function),__metadata$r("design:paramtypes",[Object]),__metadata$r("design:returntype",Promise)],DeviceManagerImpl.prototype,"askDevicePermission",null);var __decorate$s=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$s=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class TeamsIncomingCallImpl extends IncomingCallCommonImpl{get info(){return this._teamsCall.info}constructor(f){super(f,g.IncomingCallKind.TeamsIncomingCall),this._teamsCall=f}async accept(g){if(!isProxyAndCustomTurnAllowed(this._teamsCall.acsProxy,this._teamsCall.acsCustomRelayManager,!0))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._teamsCall.accept(g),this._teamsCall}}__decorate$s([asyncOperation(PS.Accept),__metadata$s("design:type",Function),__metadata$s("design:paramtypes",[Object]),__metadata$s("design:returntype",Promise)],TeamsIncomingCallImpl.prototype,"accept",null);var __decorate$t=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$t=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class TeamsCallImpl extends CallCommonImpl{get info(){return this._info}constructor(f,S,v,C){super(f,S,v,C,g.CallKind.TeamsCall),this._isEmergencyCall=!1,this._musicOnHoldEnabled=!1,this._hasFetchedPolicies=!1,this._info=this.callInfo,this._mtPolicyService=S.mtPolicyService}async startCallInternal(g,f,S,v,C,_){if(this._mtPolicyService&&this._mtPolicyService.isFetchUserPoliciesAndSettingsApplicable(!0,_)){this._mtPolicyService.userDialedNumber(Array.isArray(_)?_[0].phoneNumber:_.phoneNumber);let g="",f=!0;this._isEmergencyCall=!1;try{this.logger.info("Fetching Teams User policy from MiddleTier Service"),await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri())}catch(g){f=!1,this.logger.warn(`Fetching Teams user policy from ACS MiddleTier Service failed.\n                    Error message = ${g?.message}, code = ${g?.code}, subcode = ${g?.subCode}.\n                    Proceeding as normal pstn call`)}if(f){try{this.enforcePolicyAndLicenseRestrictions()}catch(g){return void this.handlePolicyAndLicenseRestrictionsFailure(g)}try{this.logger.info("Deriving emergency content from fetched policies and settings"),g=this._mtPolicyService.getEmergencyContent()}catch(g){this.logger.warn(`Error deriving emergency content from fetched policies and settings. \n                    Error message = ${g?.message}, code = ${g?.code}, subcode = ${g?.subCode}. Proceeding as normal pstn call`)}v&&(v.emergencyContent=g||"",v.isEmergency=g?.trim().length>0||!1,this._isEmergencyCall=v.isEmergency)}}if(_){let f=[];Array.isArray(_)?f=_:f.push(_),this._isEmergencyCall&&1==f.length&&(this.logger.info(`user dialed number (${f[0].phoneNumber}) resolved to actual emergency number (${this._mtPolicyService.getEmergencyNumber()} during startCall`),f[0]={phoneNumber:this._mtPolicyService.getEmergencyNumber()}),f.length>1&&await this.setupThreadIdWhenStartingGroupCall(f,g,v),f.forEach((g=>{this.tsCall.addParticipant(getMriFromIdentifier(g)).catch((()=>{this.logger.error("Failed to add participant during call start")}))})),this.logger.info("Paticipant added during startCall")}this._allowBreakoutRoomJoin=getAcsEcsConfig().calling.breakoutRooms.enabled&&this._mtPolicyService.isBreakoutRoomsAllowed()&&!!S,this._allowIPAudio=this._mtPolicyService.isIPAudioAllowed(),this._allowIPVideo=this._mtPolicyService.isIPVideoAllowed(),super.startCallInternal(g,f,S,v,C).catch(noop)}isEmergencyCallInProgress(){return this._isEmergencyCall}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(g,f){const v=+new Date,C=generateGuid();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.attempt,participantAddedOrRemoved:"add",correlationId:C,timestampInfo:{attemptTimestamp:v},additionalDetails:{customContext:{userToUserPresent:!!f?.customContext?.userToUser,xHeadersPresent:!!f?.customContext?.xHeaders&&f?.customContext.xHeaders.length>0}}});try{validateCallConnected(PS.AddParticipant,this.state),validateIdentifier(g)}catch(g){const f=new CallingCommunicationError({defaultError:D.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:g});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:C,timestampInfo:{deltaTimeInMs:v-+new Date},additionalDetails:{code:g.code,failureReason:g.message,...extractCommunicationServicesErrorForTelemetry(f)}}),f}if(!isProxyAndCustomTurnAllowed(this.acsProxy,this.acsCustomRelayManager,!0)){const g=new CallingCommunicationError({defaultError:D.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:C,timestampInfo:{deltaTimeInMs:v-+new Date},additionalDetails:{code:g.code,failureReason:g.message,...extractCommunicationServicesErrorForTelemetry(g)}}),g}if(this._remoteParticipants.find((f=>getMriFromIdentifier(f.identifier)===getMriFromIdentifier(g)))){const f=new CallingCommunicationError({defaultError:D.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[S.getIdentifierKind(g).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:C,timestampInfo:{deltaTimeInMs:v-+new Date},additionalDetails:{code:f.code,failureReason:f.message,...extractCommunicationServicesErrorForTelemetry(f)}}),f}if(this.tsCall.threadId&&isAcsThreadlessId(this.tsCall.threadId))try{if(this.IsTargetUserAllowed(g))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.UNSUPPORTED_TARGET_TYPE})}catch(g){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:C,timestampInfo:{deltaTimeInMs:v-+new Date},additionalDetails:{code:g.code,failureReason:g.message,...extractCommunicationServicesErrorForTelemetry(g)}}),this.logger.error(g),g}const _=this.getOrCreateRemoteParticipant(constructIdentifierKindFromMri(getMriFromIdentifier(g)));let T="";return this.GetOrCreateGroupChatThread(!!f?.threadId,g,f).then((S=>{S&&((f=f??{}).threadId=S,T=S,this._info.setThreadId(S)),this.addParticipantToTsCall(g,T,f,_,C,v)})).catch((g=>{throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:C,timestampInfo:{deltaTimeInMs:v-+new Date},additionalDetails:{code:g.code,failureReason:g.message,...extractCommunicationServicesErrorForTelemetry(g)}}),g})),_}async removeParticipant(g){const f=+new Date,v=generateGuid();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.attempt,participantAddedOrRemoved:"remove",correlationId:v,timestampInfo:{attemptTimestamp:f}});try{validateCallConnected(PS.RemoveParticipant,this.state),validateIdentifier(g)}catch(g){const S=new CallingCommunicationError({defaultError:D.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:g});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"remove",correlationId:v,timestampInfo:{deltaTimeInMs:f-+new Date},additionalDetails:{code:g.code,failureReason:g.message,...extractCommunicationServicesErrorForTelemetry(S)}}),S}const C=this._remoteParticipants.find((f=>getMriFromIdentifier(f.identifier)===getMriFromIdentifier(g)));if(!C){const C=new CallingCommunicationError({defaultError:D.CALL.PARTICIPANT_NOT_IN_CALL,originalError:[S.getIdentifierKind(g).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"remove",correlationId:v,timestampInfo:{deltaTimeInMs:+new Date-f},additionalDetails:{code:C.code,subCode:C.subCode,failureReason:C.message,...extractCommunicationServicesErrorForTelemetry(C)}}),C}try{await this.tsCall.removeParticipant(getMriFromIdentifier(g)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.success,participantAddedOrRemoved:"remove",correlationId:v,timestampInfo:{deltaTimeInMs:f-+new Date}})}catch(g){const{callEndReason:S}=getRemoteParticipantCallEndReason(this,C.tsRemoteParticipant,g);C.callEndReason||C.setCallEndReason(S);const _=extractCallEndReasonForTelemetry(S);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"remove",correlationId:v,timestampInfo:{deltaTimeInMs:f-+new Date},additionalDetails:{code:_?.callEndReason.code,subCode:_?.callEndReason.subCode,failureReason:_?.callEndReason.message,..._}}),new CallingCommunicationError({defaultError:{message:S.message,code:S.code,subCode:S.subCode||0,resultCategories:S.resultCategories},originalError:g})}}async mute(){super.mute()}async unmute(){super.unmute()}async hold(){if(4===this.tsCall.state)return void this.logger.info("Call already on hold");if(!getAcsEcsConfig().calling.musicOnHoldEnabled)return this.logger.warn("Music on Hold is not enabled"),super.hold();const g=+new Date,f=generateGuid();if(this._causeId=w.generateCauseId(),this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Hold,kindOfEvent:gE.attempt,timestampInfo:{deltaTimeInMs:g},additionalDetails:{holdType:qS.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),!this._hasFetchedPolicies)try{this.logger.info("Fetching Teams Calling Policy from Azure Communication Services"),await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri(),{policyUrlSuffix:getAcsEcsConfig().MiddleTier.policyUrlSuffixV2,userPolicies:["TeamsCallingPolicy"]}),this._hasFetchedPolicies=!0,this._musicOnHoldEnabled=this._mtPolicyService.isMoHEnabled()}catch(g){this.logger.warn(`Fetching Teams Calling Policy from Azure Communication Services failed.\n                    Error message = ${g?.message}, code = ${g?.code}, subcode = ${g?.subCode}.`)}return this._musicOnHoldEnabled?(getAcsEcsConfig().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log("Successfully turned off screen sharing before hold")})).catch((()=>{this.logger.error("Failed to turn off screensharing before hold")})),await this.tsCall.hold(void 0,this._causeId,{isLocal:!0},1).then((async()=>{this.logger.info("Successfully detached devices as part of Hold"),await this.tsCall.park(3,this._causeId).then((()=>{const S=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Hold,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:S-g},additionalDetails:{holdType:qS.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info("Successful park() as part of hold, Music on Hold completed successfully")}))})).catch((()=>{const S=+new Date,v=new CallingCommunicationError({defaultError:D.CALL.HOLD_CALL});throw this.logger.warn(`Attempting to perform Music on Hold failed.\n                    Error message = ${v.message}, code = ${v.code}, subcode = ${v.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Hold,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:S-g},additionalDetails:{failureReason:v.message,code:v.code,subCode:v.subCode,holdType:qS.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...extractCommunicationServicesErrorForTelemetry(v)}}),v}))):(this.logger.info("Fetching  of Teams Calling Policy failed or Music on Hold Disabled, proceeding with standard hold"),super.hold())}async resume(){if(this._musicOnHoldEnabled){const g=+new Date,f=generateGuid();return this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Resume,kindOfEvent:gE.attempt,timestampInfo:{deltaTimeInMs:g},additionalDetails:{holdType:qS.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unpark(3,this._causeId).then((async()=>{this.logger.info("Successful unpark() as part of resume"),await this.tsCall.unhold(void 0,this._causeId).then((()=>{const S=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Resume,kindOfEvent:gE.success,timestampInfo:{deltaTimeInMs:S-g},additionalDetails:{holdType:qS.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info("Successful unhold() as part of resume, resume completed successfully")}))})).catch((()=>{const S=+new Date,v=new CallingCommunicationError({defaultError:D.CALL.RESUME_CALL});throw this.logger.warn(`Attempting to perform resume from Music on Hold failed.\n                    Error message = ${v.message}, code = ${v.code}, subcode = ${v.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:uE.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:f,operation:PS.Resume,kindOfEvent:gE.failure,timestampInfo:{deltaTimeInMs:S-g},additionalDetails:{failureReason:v.message,code:v.code,subCode:v.subCode,holdType:qS.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...extractCommunicationServicesErrorForTelemetry(v)}}),v}))}return this.logger.info("Music on Hold Disabled, proceeding with standard resume"),super.resume()}validateAndSetThreadId(g,f){if(!f?.threadId){const g=new CallingCommunicationError({defaultError:D.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});throw this.logger.error(`Error Message = ${g.message}, code = ${g.code}, subcode = ${g.subCode}`),g}return this.validateThreadIdFormat(f?.threadId),f?.threadId}validateThreadIdFormat(g){if(!g.startsWith("19")){const g=new CallingCommunicationError({defaultError:D.CALL.TEAMS_INVALID_THREAD_ID});throw this.logger.error(`Error Message = ${g.message}, code = ${g.code}, subcode = ${g.subCode}`),g}}enforcePolicyAndLicenseRestrictions(){const g=+new Date;if(!this._mtPolicyService.isEvEnabled()){const f=+new Date,S=new CallingCommunicationError({defaultError:D.CALL.CTE_VOICE_NOT_ENABLED});this.logger.error(`Error Message = ${S.message}, code = ${S.code}, subcode = ${S.subCode}`);const v=this._callAgent.getEcsConfigIds();throw this.sendCallStageEvent({eventName:uE.acs_calling_call_failed,correlationId:generateGuid(),timestampInfo:{deltaTimeInMs:f-g},additionalPayload:{additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:v.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:v.SkypeWebMedia},additionalDetails:{...extractCommunicationServicesErrorForTelemetry(S)}}},S,{code:S.code,subCode:S.subCode,phrase:S.message}),S}}handlePolicyAndLicenseRestrictionsFailure(g){this._callEndReason={message:"Unknown",code:g?.code,subCode:g?.subCode,resultCategories:g?.resultCategories},this._state="Disconnected",this._eventEmitter.emit("stateChanged"),this._callAgent.handleCallRemoved(this.tsCall)}async setupThreadIdWhenStartingGroupCall(g,f,S){if(f&&f.threadId&&(this.validateThreadIdFormat(f.threadId),this.logger.info("ThreadId is already provided in the options parameter: "+JSON.stringify(f))),void 0===f||!f.threadId){const v=[];g.forEach((g=>{v.push({id:getMriFromIdentifier(g)})}));try{const g=await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:getAcsEcsConfig().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:v});f||(f={}),f.threadId=g,g&&this._info.setThreadId(g),S&&g&&(S.threadId=g)}catch(g){const f="Failed to create thread Id for Teams group call ";if(!getAcsEcsConfig().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(f+g)}}}async GetOrCreateGroupChatThread(g,f,S){let v="";if(g)return this.logger.info("Customer provided threadId in options: "+JSON.stringify(S)),v=this.validateAndSetThreadId(f,S),Promise.resolve(v);if(!getAcsEcsConfig().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation)throw new CallingCommunicationError({defaultError:D.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});if(null!==this._info.threadId&&void 0!==this._info.threadId){v=this._info.threadId;const g=[];return g.push({id:getMriFromIdentifier(f)}),await this._mtPolicyService.AddParticipantsToThread(this.tsCall.callId,{threadId:v,addParticipantsSuffix:getAcsEcsConfig().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,participants:g}).catch((f=>{this.logger.warn("Error when adding participants "+JSON.stringify(g)+" to thread. "+f)})),Promise.resolve(v)}{const g=[];return this._remoteParticipants.forEach((f=>{g.push({id:getMriFromIdentifier(f.identifier)})})),g.push({id:getMriFromIdentifier(f)}),await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:getAcsEcsConfig().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:g}).then((g=>{v=g,this.logger.info("Add participant into 1on1 call to convert it into Teams group call. Create thread id: "+v)})).catch((g=>{const S="Error when adding participants "+getMriFromIdentifier(f)+" to thread to create a Teams group call. ";if(!getAcsEcsConfig().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new CallingCommunicationError({defaultError:D.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(S+g)})),Promise.resolve(v)}}addParticipantToTsCall(g,f,S,v,C,_){this.tsCall.addParticipant(getMriFromIdentifier(g),{threadId:f,customHeaderContext:processCustomContext(S)}).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.success,participantAddedOrRemoved:"add",correlationId:C,timestampInfo:{deltaTimeInMs:_-+new Date}})})).catch((f=>{const{callEndReason:S}=getRemoteParticipantCallEndReason(this,v.tsRemoteParticipant,f);v.callEndReason||v.setCallEndReason(S);const T=extractCallEndReasonForTelemetry(S);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:gE.failure,participantAddedOrRemoved:"add",correlationId:C,timestampInfo:{deltaTimeInMs:_-+new Date},additionalDetails:{code:T?.callEndReason.code,subCode:T?.callEndReason.subCode,failureReason:T?.callEndReason.message,...T}}),this._remoteParticipants.find((f=>getMriFromIdentifier(f.identifier)===getMriFromIdentifier(g)))&&(this.deleteRemoteParticipant(v),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:[v]}))}))}IsTargetUserAllowed(g){return S.isUnknownIdentifier(g)||S.isPhoneNumberIdentifier(g)||S.isCommunicationUserIdentifier(g)}}__decorate$t([validateEmergencyCallOperation(PS.AddParticipant),syncOperation(PS.AddParticipant),__metadata$t("design:type",Function),__metadata$t("design:paramtypes",[Object,Object]),__metadata$t("design:returntype",Object)],TeamsCallImpl.prototype,"addParticipant",null),__decorate$t([validateEmergencyCallOperation(PS.RemoveParticipant),asyncOperation(PS.RemoveParticipant),__metadata$t("design:type",Function),__metadata$t("design:paramtypes",[Object]),__metadata$t("design:returntype",Promise)],TeamsCallImpl.prototype,"removeParticipant",null),__decorate$t([validateEmergencyCallOperation(PS.Mute),__metadata$t("design:type",Function),__metadata$t("design:paramtypes",[]),__metadata$t("design:returntype",Promise)],TeamsCallImpl.prototype,"mute",null),__decorate$t([validateEmergencyCallOperation(PS.Unmute),__metadata$t("design:type",Function),__metadata$t("design:paramtypes",[]),__metadata$t("design:returntype",Promise)],TeamsCallImpl.prototype,"unmute",null),__decorate$t([validateEmergencyCallOperation(PS.Hold),asyncOperation(PS.Hold),__metadata$t("design:type",Function),__metadata$t("design:paramtypes",[]),__metadata$t("design:returntype",Promise)],TeamsCallImpl.prototype,"hold",null),__decorate$t([validateEmergencyCallOperation(PS.Resume),asyncOperation(PS.Resume),__metadata$t("design:type",Function),__metadata$t("design:paramtypes",[]),__metadata$t("design:returntype",Promise)],TeamsCallImpl.prototype,"resume",null);var __decorate$u=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$u=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};class TeamsCallAgentImpl extends CallAgentCommonImpl{get calls(){return this._calls}constructor(f,S,v,C,_,T){super(f,S,C,_,v,g.CallAgentKind.TeamsCallAgent,T),this._calls=[],this.handleCallAdded=g=>{if(!this._calls.find((f=>f.id===g.callId))){const f=g.on("callStateChanged",(()=>{if(1===g.state){const S=g.callId;f.dispose();const v=new TeamsCallImpl({callId:S,isIncoming:!0},this,g,this._telemetryLogManager),C=new TeamsIncomingCallImpl(v);this.handleCallState(v),v.bindTsCall(),this._eventEmitter.emit("incomingCall",{incomingCall:C})}}))}},this.handleCallRemoved=g=>{this.logger.info(`removing callId=${g.callId}`);const f=this._calls.find((f=>f.id===g.callId));if(f){if(f.isBreakoutRoomCall){const g=getAcsEcsConfig().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(f)}),g)}else this.disposeCall(f);this._eventEmitter.emit("callsUpdated",{added:[],removed:[f]}),this.logger.info("call removed")}},this.handleCallState=g=>{g.on("stateChanged",(async()=>{try{if("Disconnected"===g.state){this.tsStack?(await(this._tsCallRegistry.deleteCallAsync?.(g.tsCall))||this.logger.error(`Failed to remove call from registry, call id: ${g.id}`),g.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(g.id).catch((()=>{this.logger.error("Failed to flush telemetry log manager events")}))):this.logger.info("Unable to remove call from registry")}else"Connecting"===g.state&&"Incoming"==g.direction&&(this.addToCallArray(g),this._eventEmitter.emit("callsUpdated",{added:[g],removed:[]}))}catch(g){this.logger.error("Failed to handle call state changed event")}}))},this.logger=S}createNewCall(g,f){return new TeamsCallImpl({callId:g},this,f,this._telemetryLogManager)}addToCallArray(g){this._calls.push(g),this.trackCallEndTimeToStopTelemetry(this._calls)}addToCallAgentsMap(g){TeamsCallAgentImpl.teamsCallAgents.get(g?.identityMri)&&logErrorAndThrow(D.CALL_AGENT.TEAMS_CALLAGENT_ALREADY_EXSISTS,this.logger),TeamsCallAgentImpl.teamsCallAgents.set(g?.identityMri,this)}removeFromCallAgentsMap(g){g?.identityMri&&TeamsCallAgentImpl.teamsCallAgents.get(g?.identityMri)===this&&TeamsCallAgentImpl.teamsCallAgents.delete(g?.identityMri)}disposeCall(g){const f=this._calls.indexOf(g);-1!==f&&this._calls.splice(f,1),g.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}getMiddleTierServiceInstance(){return this.mtPolicyService}async setUserPoliciesOnAgentInitialization(){super.setUserPoliciesOnAgentInitialization();try{if(this.isEnterpriseUser()){const g=generateGuid();this.logger.info(`ACS MiddleTier service called on Teams Call Agent initialization with call Id=${g}`),await this.mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(g,this.getUserMri(),{policyUrlSuffix:getAcsEcsConfig().MiddleTier.policyUrlSuffixV2,userPolicies:["EmergencyPolicies","TeamsCallingPolicy","TeamsMeetingPolicy"],userProperties:["FeatureTypes","PoliciesMetadata","phoneNumber","sipUri","hostType","accountEnabled","useTeamsCalling","evEnabled","region","routingType","preferredDataLocation","featureTypes","displayName"]}),this._userPolicies=this.mtPolicyService.getUserPolicy(),this._userProperties=this.mtPolicyService.getUserProperties(),this.logger.info(`****User policy initialized to ${JSON.stringify(this._userPolicies)}`),this.logger.info(`****User properties initialized to ${JSON.stringify(this._userProperties)}`)}}catch(g){this.logger.warn(`Fetching Teams user policy and Properties from ACS MiddleTier Service failed.\n            Error message = ${g?.message}, code = ${g?.code}, subcode = ${g?.subCode}.`)}}startCall(g,f){const S=generateGuid(),v=+new Date,C={correlationId:S,timestampInfo:{attemptTimestamp:v}};this._telemetryLogManager.sendEvent({name:uE.acs_calling_call_attempt,tenant:tf,properties:C},void 0,"attempt");try{let C;if(this.assertParticipants(g),Array.isArray(g)){if(this.isTeamsMultipersonaUser()&&!getAcsEcsConfig().calling.teamsMultipersonaSettings.enableJoinCall)throw new CallingCommunicationError({defaultError:D.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});if(C=f,g.length>1&&!getAcsEcsConfig().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation&&!C?.threadId)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.GROUPCALL_THREADID});if(1==g.length&&C?.threadId)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.ONE_TO_ONE_THREADID})}else{if(this.isTeamsMultipersonaUser()&&!getAcsEcsConfig().calling.teamsMultipersonaSettings.enableStartCall)throw new CallingCommunicationError({defaultError:D.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});C=f}if(getAcsEcsConfig().calling.enableSmePassFakeConversation&&this.isAcsToTeamsInteropCall(g)&&!this.isTeamsMultipersonaUser())throw new CallingCommunicationError({defaultError:D.CALL_AGENT.UNSUPPORTED_TARGET_TYPE});let _=C?.audioOptions?.muted;return void 0===_&&(_=!1),this.logger.info(`startCall with video=${!!C?.videoOptions},muted=${_}`),this.createCall({participants:g,startCallOptions:C},{correlationId:S,attemptTimestamp:v})}catch(g){let f,C;throw g instanceof CallingCommunicationError&&(f="string"==typeof g?.message?g?.message:void 0,C={...extractCommunicationServicesErrorForTelemetry(g)}),this._telemetryLogManager.sendEvent({name:uE.acs_calling_call_failed,tenant:tf,properties:{correlationId:S,timestampInfo:{deltaTimeInMs:+new Date-v},failureReason:f||"",additionalDetails:C||{}}},void 0,"failure"),g}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(S)}}join(g,f){this.assertCallContext(g);const S=!!f?.audioOptions?.muted;return this.logger.info(`join with video=${!!f?.videoOptions},muted=${S}`),this.createCall({teamsCallContext:g,startCallOptions:f})}async dispose(){if(this._disposed)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.CTE_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&TeamsCallAgentImpl.teamsCallAgents.delete(this._parsedTokenCredential?.identityMri);try{const g=this._tokenFetchTries>this._maxNmberOfRetries;await(this._callStack?.dispose(g))}catch(g){this.logger.error("Call Agent failed to dispose to Call Stack")}this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),delete this._callStack,this._telemetryLogManager.clearTelemetryLoggers(),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit("disposed"),this._internalEventEmitter.removeAllListeners()}on(g,f){if("incomingCall"!==g&&"callsUpdated"!==g&&"connectionStateChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.on(g,f)}off(g,f){if("incomingCall"!==g&&"callsUpdated"!==g&&"connectionStateChanged"!==g)throw new CallingCommunicationError({defaultError:D.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[g]});this._eventEmitter.off(g,f)}createCall(g,f){let v,C,_,T=g?.teamsCallContext?.threadId,I=!1;const b=g?.teamsCallContext?.meetingLink,A=g?.teamsCallContext?.meetingId,P=g?.teamsCallContext?.passcode||"",R=!!g?.participants&&(Array.isArray(g?.participants)&&g?.participants.length>1);if(this.isEnterpriseUser()&&R&&(T=(g?.startCallOptions).threadId),!isProxyAndCustomTurnAllowed(this.acsProxy,this.acsCustomRelayManager,!0))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});if(b)if(isLongMeetingUrl(b))C=parseLongMeetingLink(b);else{if(!isShortMeetingUrl(b,this.logger))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INVALID_MEETING_LINK});if(isTflMeetingLink(b.trim().toLocaleLowerCase(),getAcsEcsConfig().calling.tfl.hosts))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});I=!0}if(g?.teamsCallContext?.threadId&&g?.teamsCallContext?.organizerId&&g?.teamsCallContext?.tenantId&&(C={threadId:g?.teamsCallContext?.threadId,messageId:g?.teamsCallContext?.messageId?g?.teamsCallContext?.messageId.toString():"0",organizerId:g?.teamsCallContext?.organizerId,tenantId:g?.teamsCallContext?.tenantId}),C&&(_={meetingType:"0"===C.messageId?1:2,tenantId:C.tenantId,organizerId:C.organizerId,replyChainMessageId:C.messageId}||void 0,T=C.threadId,v=C.messageId),this.tsStack){const C=w.generateCauseId(),R=generateGuid(),M=generateGuid();let O;O=A?this._tsCallRegistry.createCallWithMeetingData({meetingCode:A,passcode:P,threadId:T},R,M,C):I?this._tsCallRegistry.createCallWithMeetingData({meetingUrl:b},R,M,C):this._tsCallRegistry.createCall(T||"",R,M,v,C);const N=new TeamsCallImpl({callId:R},this,O,this._telemetryLogManager);this.addToCallArray(N),this.handleCallState(N);const k=g?.startCallOptions?.onBehalfOfOptions,L=k?.userId;let F;if(L){if((g?.startCallOptions).customContext)throw new CallingCommunicationError({defaultError:D.FEATURES.ONE_PHONE_SYSTEM.CUSTOM_CONTEXT_NOT_SUPPORTED});if(S.isMicrosoftTeamsAppIdentifier(L))F=S.getIdentifierRawId(L);else{if(!S.isMicrosoftTeamsUserIdentifier(L))throw new CallingCommunicationError({defaultError:D.IDENTIFIER.INVALID_COMM_USER});if(!getAcsEcsConfig().calling.sharedLineAppearance.enabled)throw new CallingCommunicationError({defaultError:D.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if(!this.getUserPolicy()?.teamsCallingPolicy?.allowDelegation)throw new CallingCommunicationError({defaultError:D.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_BY_CALLING_POLICY});F=S.getIdentifierRawId(L)}}const x={threadId:T||"",messageId:v||"",meetingInfo:_,mediaPeerType:2,onBehalfOf:F};return N.startCallInternal(g?.startCallOptions,!!A,g?.teamsCallContext,x,f,g?.participants).catch(noop),N.bindTsCall(),this._eventEmitter.emit("callsUpdated",{added:[N],removed:[]}),N}throw new CallingCommunicationError({defaultError:D.CALL_AGENT.STACK_NOT_INIT})}assertParticipants(g){assertIsObject(g,D.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),assertNotNull(g,D.CALL_AGENT.USERIDS_CANNOT_BE_NULL)}assertCallContext(g){if(!g||this.checkForAtLeastOneValidCallConfig(g)||this.checkForInvalidTeamsMeetingCoordinates(g))throw new CallingCommunicationError({defaultError:D.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(g){return!g.threadId&&!g.meetingLink&&!g.meetingId}checkForInvalidTeamsMeetingCoordinates(g){return!g.threadId&&g.tenantId&&g.organizerId||g.threadId&&(g.organizerId&&!g.tenantId||!g.organizerId&&g.tenantId)}isAcsToTeamsInteropCall(g){let f=!1;return this.isEnterpriseUser()&&(Array.isArray(g)?g.length>=1&&g.find((g=>S.isCommunicationUserIdentifier(g)))&&(f=!0):S.isCommunicationUserIdentifier(g)&&(f=!0)),f}}TeamsCallAgentImpl.teamsCallAgents=new Map,__decorate$u([syncOperation(AS.StartCall),__metadata$u("design:type",Function),__metadata$u("design:paramtypes",[Object,Object]),__metadata$u("design:returntype",Object)],TeamsCallAgentImpl.prototype,"startCall",null),__decorate$u([syncOperation(AS.Join),__metadata$u("design:type",Function),__metadata$u("design:paramtypes",[Object,Object]),__metadata$u("design:returntype",Object)],TeamsCallAgentImpl.prototype,"join",null),__decorate$u([asyncOperation(AS.Dispose),__metadata$u("design:type",Function),__metadata$u("design:paramtypes",[]),__metadata$u("design:returntype",Promise)],TeamsCallAgentImpl.prototype,"dispose",null);class AcsProxy{constructor(){this._proxyInUse=!1;const g=f.createClientLogger("ACS-calling");this.logger=new DefaultLogger(g,[()=>"AcsProxy"])}get proxyInUse(){return this._proxyInUse}set proxyInUse(g){this._proxyInUse=g}get proxyUrl(){return this._proxyUrl?.toString()||""}set proxyUrl(g){if(g.length<4)throw new CallingCommunicationError({defaultError:D.CALL_CLIENT.PROXY_SHORT_URL});"/"!==g.slice(-1)&&(g=g.concat("","/"));try{const f=new URL(g);if("https:"!==f.protocol&&"http:"!==f.protocol)throw new CallingCommunicationError({defaultError:D.CALL_CLIENT.PROXY_PROTOCOL});this._proxyUrl=f}catch(f){const S=new CallingCommunicationError({defaultError:D.CALL_CLIENT.SETUP_PROXY,defaultErrorMessageArgs:[g],originalError:f});throw this.logger.error(S.message),S}}hasProxyUrl(){return!!this._proxyUrl}proxyfyUrl(g){let f=g;if(!this._proxyUrl)return this.logger.info(`Proxy url not defined, return original ${redactUrlQueryParameters(f)}`),f;try{const g=new URL(f);f=`${`${g.protocol}//${this._proxyUrl.host}${this._proxyUrl.pathname}`}${g.host}${g.pathname}${g.search}`,this.logger.info(`Proxyfing url from ${redactUrlQueryParameters(g)} to ${redactUrlQueryParameters(f)}`)}catch(g){const f=`Failed proxyfy url with error: ${JSON.stringify(g)}, returning original`;this.logger.error(f)}return this._proxyInUse=!0,f}}class AcsCustomRelayManager{constructor(){this._hasCustomRelay=!1,this._customRelayManagerInUse=!1;const g=f.createClientLogger("ACS-calling");this._logger=new DefaultLogger(g,[()=>"AcsCustomRelayManager"])}getRelayConfig(){return this._relayConfig}setRelayConfig(g){this._relayConfig={...g},this._logger.info("Custom relay config provided"),this._hasCustomRelay=!0,this._createTsRelayManager()}get hasRelayConfig(){return this._hasCustomRelay}get customRelayManagerInUse(){return this._customRelayManagerInUse}set customRelayManagerInUse(g){this._customRelayManagerInUse=g}getTsRelayManager(){return this._tsRelayManager}_createTsRelayManager(){if(!this._hasCustomRelay||!this._relayConfig||this._relayConfig.iceServers.length<1)return void this._logger.warn("No relay config provided. No op.");const g=[];this._relayConfig.iceServers.forEach((f=>{f.urls.forEach((S=>{const v=this._getIndividualRelay(S,f?.username,f?.credential);g.push(v)}))})),this._tsRelayManager={initialize(){},queryRelaysAsync:f=>Promise.resolve(g)}}_getIndividualRelay(g,f,S){const v=3478,C=[],_=[],T=[RE.turn,RE.turns,RE.stun],I=[ME.tcp,ME.tls,ME.udp];let b;try{b=new URL(g)}catch(f){throw new CallingCommunicationError({defaultError:D.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[g],originalError:f})}const A=b.protocol.replace(":","");if(!T.includes(A))throw new CallingCommunicationError({defaultError:D.CALL_CLIENT.RELAY_UNRECOGNIZED_SCHEMA});let P,R="";try{R=b.href.replace(/((turn)s?|stun):/,"https:"),P=new URL(R)}catch(g){throw new CallingCommunicationError({defaultError:D.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[R],originalError:g})}let M=P.searchParams.get("transport")??"";I.includes(M)||(this._logger.warn(`Unknown transport protocol detected for the provided turn, defaulting to ${ME.udp}`),M=ME.udp);let w=""===P.port?this._extractPortFromUrl(b):Number(P.port);w||(this._logger.warn(`Could not read port from relay url, defaulting to ${v}`),w=v);let O=P.hostname;return isIpv4Address(O)?C.push(O):_.push(O),{addresses:C,udpPort:M===ME.udp?w:void 0,tcpPort:M===ME.tcp?w:void 0,tlsPort:M===ME.tls?w:void 0,username:f??"",password:S??"",type:"turn",fqdns:_}}_extractPortFromUrl(g){const f=g.href.match(fS)?.[0];return Number(f?.replace(":",""))}}var FA,__decorate$v=function(g,f,S,v){var C,_=arguments.length,T=_<3?f:null===v?v=Object.getOwnPropertyDescriptor(f,S):v;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)T=Reflect.decorate(g,f,S,v);else for(var I=g.length-1;I>=0;I--)(C=g[I])&&(T=(_<3?C(T):_>3?C(f,S,T):C(f,S))||T);return _>3&&T&&Object.defineProperty(f,S,T),T},__metadata$v=function(g,f){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(g,f)};let xA=1;class CallClient{get callAgent(){return this._callAgent}get teamsCallAgent(){return this._teamsCallAgent}get sdkDiagnosticInformation(){return this._sdkDiagnosticInformation}get telemetryLogManager(){return this._telemetryLogManager}setCallAgent(g){this._callAgent=g}setTeamsCallAgent(g){this._teamsCallAgent=g}on(g,f){this._eventEmitter.on(g,f)}off(g,f){this._eventEmitter.off(g,f)}constructor(g){this._customProxyAndTurnInformation={proxy:null,turn:null},this.sendTelemetry=()=>{try{if(getAcsEcsConfig().telemetry.telemetryBeforeUnload&&this._callAgent&&this._callAgent._calls)for(const g of this._callAgent._calls){g.tsCall.sendLastKnownStats()}}catch(g){this.logger.debug("Error logging telemetry",g)}},this.handleVisibilityChange=()=>{"hidden"===document.visibilityState?(this.logger.debug("Visibility changed to hidden"),this.sendPageVisibilityInfoEvent("visibilityChange",!0),this.hangupCalls()):(this.logger.debug("Visibility changed to visible"),this.sendPageVisibilityInfoEvent("visibilityChange",!1))},this.handlePageShow=()=>{this.logger.debug("Page show"),this.sendPageVisibilityInfoEvent("pageShow",!0)},this.handlePageHide=()=>{this.logger.debug("Page hide"),this.sendPageVisibilityInfoEvent("pageHide",!1)},this.handleOrientationChange=()=>{this.logger.debug(`Orientation changed to ${screen.orientation.type}`),this.sendOrientationChangeEvent(screen.orientation.type)},this.getOrientationBasedOnWindowSize=()=>window.innerHeight>window.innerWidth?"portrait-primary":"landscape-primary",this.handleResize=()=>{const g=this.getOrientationBasedOnWindowSize();this._previousOrientation!==g&&(this._previousOrientation=g,this.sendOrientationChangeEvent(g))};const S=+new Date;this.clientId=generateGuid();const v=g?.logger||f.createClientLogger("ACS-calling"),C=xA++;if(this._acsProxy=new AcsProxy,this._acsCustomRelayManager=new AcsCustomRelayManager,g?.networkConfiguration){g.networkConfiguration.proxy?.url&&(this._customProxyAndTurnInformation.proxy={...g.networkConfiguration.proxy},this._acsProxy.proxyUrl=this._customProxyAndTurnInformation.proxy.url),g.networkConfiguration.turn&&(this._customProxyAndTurnInformation.turn={...g.networkConfiguration.turn},this._acsCustomRelayManager.setRelayConfig(this._customProxyAndTurnInformation.turn));const f=this.getTelemetryTag();g.diagnostics?g.diagnostics.tags?g.diagnostics.tags.push(f):g.diagnostics.tags=[f]:g.diagnostics={tags:[f]}}this.logger=new DefaultLogger(v,[()=>`CallClient${C}[${this.clientId}]`]),this._eventEmitter=new CallingEventEmitter(this.logger),this._sdkDiagnosticInformation=buildCallingUserAgent(getSdkVersion(),this.logger,g),this.diagnosticOptions=g?.diagnostics,this.firstPartyOptions=g?.firstPartyOptions,this._telemetryLogManager=new TelemetryLogManager(this.logger,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager);try{this.sendCallClientInitEvent({eventName:uE.acs_calling_call_client_init,kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),Object.defineProperty(globalThis,Lf,{value:C,writable:!0,enumerable:!1}),1===C&&Object.defineProperty(globalThis,kf,{value:this._telemetryLogManager,writable:!1,enumerable:!1}),this.logger.info("created"),this._callStack=new CallStack(this.logger,this.clientId,this._telemetryLogManager,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager,this.firstPartyOptions?.encodedStreamsJsPath),this._deviceManager=new DeviceManagerImpl(this.logger,this._callStack,this._telemetryLogManager),this._previousOrientation="",this.sendInitialOrientation(),window.addEventListener("beforeunload",this.sendTelemetry),window.addEventListener("visibilitychange",this.handleVisibilityChange,!1),window.addEventListener("pageshow",this.handlePageShow,!1),window.addEventListener("pagehide",this.handlePageHide,!1),screen.orientation?screen.orientation.addEventListener("change",this.handleOrientationChange):window.addEventListener("resize",this.handleResize,!1),this._extensibleApi=new ExtensibleFeatureImpl(this.logger,{callClient:this},{callClient:this,telemetryLogManager:this._telemetryLogManager});const g=getRegisteredFeatures(UE.CallClientFeature);for(const f of g)"OnExtendedObjectConstructor"===f.activationOptions.activationEvent&&this.feature(f);this.sendCallClientInitEvent({eventName:uE.acs_calling_call_client_init,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:+new Date-S},additionalDetails:""})}catch(g){const f=new CallingCommunicationError({defaultError:D.CALL_CLIENT.INIT_CALL_CLIENT,originalError:g});throw this.sendCallClientInitEvent({eventName:uE.acs_calling_call_client_init,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-S},additionalDetails:{failureReason:f.message,code:f.code,subCode:f.subCode,...extractCommunicationServicesErrorForTelemetry(f)}}),f}}createInstance(g){return new CallClient(g)}get acsProxy(){return this._acsProxy}get acsCustomRelayManager(){return this._acsCustomRelayManager}getSDKVersion(){return getSdkVersion()}feature(g){return this._extensibleApi.getApiObjectInstance(g.callClientApiCtor)}async createCallAgent(g,f){const{identityMri:S}=await parseTokenCredential(g);if(this._callAgent?._caConfigBag?.identityMri===S)return this._callAgent;if((this._callAgent||this._teamsCallAgent)&&logErrorAndThrow(D.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger),this._callAgent=CallAgentImpl.callAgents.get(S),this._callAgent)return this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit("callAgentCreated"),this._callAgent;this.validateEmergencyCountryCode(f);try{return this._callAgent=new CallAgentImpl(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager,f),await this._callAgent.initialize(g,f),this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit("callAgentCreated"),this._callAgent}catch(g){throw this._callAgent=void 0,new CallingCommunicationError({defaultError:D.CALL_CLIENT.CREATE_CALL_AGENT,originalError:g})}}async createTeamsCallAgent(g,f){const{identityMri:S}=await parseTokenCredential(g);if(this._teamsCallAgent?._caConfigBag?.identityMri===S)return this._teamsCallAgent;if((this._callAgent||this._teamsCallAgent)&&logErrorAndThrow(D.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger),this._teamsCallAgent=TeamsCallAgentImpl.teamsCallAgents.get(S),this._teamsCallAgent)return this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit("teamsCallAgentCreated"),this._teamsCallAgent;try{return this._teamsCallAgent=new TeamsCallAgentImpl(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager),await this._teamsCallAgent.initialize(g,f),this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit("teamsCallAgentCreated"),this._teamsCallAgent}catch(g){throw this._teamsCallAgent=void 0,new CallingCommunicationError({defaultError:D.CALL_CLIENT.CREATE_TEAMS_CALL_AGENT,originalError:g})}}async getDeviceManager(){return await this._deviceManager.getDeviceManager(),this._deviceManager}async getEnvironmentInfoInternal(){return this._environmentInfos||(await this._callStack.createStackBase(),this._environmentInfos=getEnvironmentInfos()),this._environmentInfos}validateEmergencyCountryCode(g){g?.emergencyCallOptions?.countryCode&&g.emergencyCallOptions?.countryCode.length>lf&&logErrorAndThrow(D.CALL_CLIENT.EMERGENCY_CODE_TOO_LONG,this.logger)}sendOrientationChangeEvent(g,f=!1){if(this._callAgent?._calls?.length)try{this._telemetryLogManager.sendEvent({name:uE.acs_calling_orientation_changed,tenant:tf,properties:{orientation:g,isInitial:f}})}catch(g){this.logger.debug("Unable to send orientation change telemetry")}}sendInitialOrientation(){let g=screen.orientation&&screen.orientation.type;g||(g=this.getOrientationBasedOnWindowSize()),this.sendOrientationChangeEvent(g,!0)}sendCallClientInitEvent(g){try{this._telemetryLogManager.sendEvent({name:g.eventName,tenant:tf,properties:g})}catch(g){this.logger.debug("Unable to send CallClient initialized telemetry event")}}hangupCalls(){try{"Mobile"===getBrowserInfo().formFactor&&getAcsEcsConfig().calling.hangUpCallOnPageHide&&this._callAgent?.calls.forEach((g=>g.hangUp()))}catch(g){try{this.logger.error(`Unable to hangup call on page hide due to ${JSON.stringify(g)}`)}catch(g){this.logger.error("Unable to hangup call on page hide due to unknown error")}}}sendPageVisibilityInfoEvent(g,f){if(this._callAgent?._calls?.length)try{this._telemetryLogManager.sendEvent({name:uE.acs_calling_page_hidden,tenant:tf,properties:{eventName:g,pageHidden:f}})}catch(g){this.logger.debug("Unable to send page hide telemetry")}}getTelemetryTag(){return this._customProxyAndTurnInformation.proxy&&this._customProxyAndTurnInformation.turn?hS.usedProxyAndNonMsftTurn:this._customProxyAndTurnInformation.proxy?hS.onlyUsedProxy:this._customProxyAndTurnInformation.turn?hS.onlyUsedNonMsftTurn:""}}__decorate$v([loggerProperty,__metadata$v("design:type",Object)],CallClient.prototype,"logger",void 0),__decorate$v([syncOperation(bS.GetSDKVersion),__metadata$v("design:type",Function),__metadata$v("design:paramtypes",[]),__metadata$v("design:returntype",String)],CallClient.prototype,"getSDKVersion",null),__decorate$v([syncOperation(bS.Feature),__metadata$v("design:type",Function),__metadata$v("design:paramtypes",[Object]),__metadata$v("design:returntype","function"==typeof(FA="undefined"!=typeof TFeature&&TFeature)?FA:Object)],CallClient.prototype,"feature",null),__decorate$v([asyncOperation(bS.CreateCallAgent),__metadata$v("design:type",Function),__metadata$v("design:paramtypes",[Object,Object]),__metadata$v("design:returntype",Promise)],CallClient.prototype,"createCallAgent",null),__decorate$v([asyncOperation(bS.CreateTeamsCallAgent),__metadata$v("design:type",Function),__metadata$v("design:paramtypes",[Object,Object]),__metadata$v("design:returntype",Promise)],CallClient.prototype,"createTeamsCallAgent",null),__decorate$v([asyncOperation(bS.GetDeviceManager),__metadata$v("design:type",Function),__metadata$v("design:paramtypes",[]),__metadata$v("design:returntype",Promise)],CallClient.prototype,"getDeviceManager",null),__decorate$v([asyncOperation(bS.GetEnvironmentInfo),__metadata$v("design:type",Function),__metadata$v("design:paramtypes",[]),__metadata$v("design:returntype",Promise)],CallClient.prototype,"getEnvironmentInfoInternal",null),g.CallClient=CallClient,g.Features=fb,g.LocalAudioStream=LocalAudioStream,g.LocalVideoStream=LocalVideoStream,g.VideoStreamRenderer=VideoStreamRenderer,Object.defineProperty(g,"__esModule",{value:!0})}));
